1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2008 Advanced Micro Devices, Inc.
5 * Author: Joerg Roedel <joerg.roedel@amd.com>
8 #define pr_fmt(fmt) "DMA-API: " fmt
10 #include <linux/sched/task_stack.h>
11 #include <linux/scatterlist.h>
12 #include <linux/dma-mapping.h>
13 #include <linux/sched/task.h>
14 #include <linux/stacktrace.h>
15 #include <linux/dma-debug.h>
16 #include <linux/spinlock.h>
17 #include <linux/vmalloc.h>
18 #include <linux/debugfs.h>
19 #include <linux/uaccess.h>
20 #include <linux/export.h>
21 #include <linux/device.h>
22 #include <linux/types.h>
23 #include <linux/sched.h>
24 #include <linux/ctype.h>
25 #include <linux/list.h>
26 #include <linux/slab.h>
28 #include <asm/sections.h>
30 #define HASH_SIZE 1024ULL
31 #define HASH_FN_SHIFT 13
32 #define HASH_FN_MASK (HASH_SIZE - 1)
34 #define PREALLOC_DMA_DEBUG_ENTRIES (1 << 16)
35 /* If the pool runs out, add this many new entries at once */
36 #define DMA_DEBUG_DYNAMIC_ENTRIES (PAGE_SIZE / sizeof(struct dma_debug_entry))
46 MAP_ERR_CHECK_NOT_APPLICABLE,
51 #define DMA_DEBUG_STACKTRACE_ENTRIES 5
54 * struct dma_debug_entry - track a dma_map* or dma_alloc_coherent mapping
55 * @list: node on pre-allocated free_entries list
56 * @dev: 'dev' argument to dma_map_{page|single|sg} or dma_alloc_coherent
57 * @type: single, page, sg, coherent
58 * @pfn: page frame of the start address
59 * @offset: offset of mapping relative to pfn
60 * @size: length of the mapping
61 * @direction: enum dma_data_direction
62 * @sg_call_ents: 'nents' from dma_map_sg
63 * @sg_mapped_ents: 'mapped_ents' from dma_map_sg
64 * @map_err_type: track whether dma_mapping_error() was checked
65 * @stacktrace: support backtraces when a violation is detected
67 struct dma_debug_entry {
68 struct list_head list;
78 enum map_err_types map_err_type;
79 #ifdef CONFIG_STACKTRACE
80 unsigned int stack_len;
81 unsigned long stack_entries[DMA_DEBUG_STACKTRACE_ENTRIES];
85 typedef bool (*match_fn)(struct dma_debug_entry *, struct dma_debug_entry *);
88 struct list_head list;
90 } ____cacheline_aligned_in_smp;
92 /* Hash list to save the allocated dma addresses */
93 static struct hash_bucket dma_entry_hash[HASH_SIZE];
94 /* List of pre-allocated dma_debug_entry's */
95 static LIST_HEAD(free_entries);
96 /* Lock for the list above */
97 static DEFINE_SPINLOCK(free_entries_lock);
99 /* Global disable flag - will be set in case of an error */
100 static bool global_disable __read_mostly;
102 /* Early initialization disable flag, set at the end of dma_debug_init */
103 static bool dma_debug_initialized __read_mostly;
105 static inline bool dma_debug_disabled(void)
107 return global_disable || !dma_debug_initialized;
110 /* Global error count */
111 static u32 error_count;
113 /* Global error show enable*/
114 static u32 show_all_errors __read_mostly;
115 /* Number of errors to show */
116 static u32 show_num_errors = 1;
118 static u32 num_free_entries;
119 static u32 min_free_entries;
120 static u32 nr_total_entries;
122 /* number of preallocated entries requested by kernel cmdline */
123 static u32 nr_prealloc_entries = PREALLOC_DMA_DEBUG_ENTRIES;
125 /* per-driver filter related state */
127 #define NAME_MAX_LEN 64
129 static char current_driver_name[NAME_MAX_LEN] __read_mostly;
130 static struct device_driver *current_driver __read_mostly;
132 static DEFINE_RWLOCK(driver_name_lock);
134 static const char *const maperr2str[] = {
135 [MAP_ERR_CHECK_NOT_APPLICABLE] = "dma map error check not applicable",
136 [MAP_ERR_NOT_CHECKED] = "dma map error not checked",
137 [MAP_ERR_CHECKED] = "dma map error checked",
140 static const char *type2name[] = {
141 [dma_debug_single] = "single",
142 [dma_debug_sg] = "scather-gather",
143 [dma_debug_coherent] = "coherent",
144 [dma_debug_resource] = "resource",
147 static const char *dir2name[4] = { "DMA_BIDIRECTIONAL", "DMA_TO_DEVICE",
148 "DMA_FROM_DEVICE", "DMA_NONE" };
151 * The access to some variables in this macro is racy. We can't use atomic_t
152 * here because all these variables are exported to debugfs. Some of them even
153 * writeable. This is also the reason why a lock won't help much. But anyway,
154 * the races are no big deal. Here is why:
156 * error_count: the addition is racy, but the worst thing that can happen is
157 * that we don't count some errors
158 * show_num_errors: the subtraction is racy. Also no big deal because in
159 * worst case this will result in one warning more in the
160 * system log than the user configured. This variable is
161 * writeable via debugfs.
163 static inline void dump_entry_trace(struct dma_debug_entry *entry)
165 #ifdef CONFIG_STACKTRACE
167 pr_warning("Mapped at:\n");
168 stack_trace_print(entry->stack_entries, entry->stack_len, 0);
173 static bool driver_filter(struct device *dev)
175 struct device_driver *drv;
179 /* driver filter off */
180 if (likely(!current_driver_name[0]))
183 /* driver filter on and initialized */
184 if (current_driver && dev && dev->driver == current_driver)
187 /* driver filter on, but we can't filter on a NULL device... */
191 if (current_driver || !current_driver_name[0])
194 /* driver filter on but not yet initialized */
199 /* lock to protect against change of current_driver_name */
200 read_lock_irqsave(&driver_name_lock, flags);
204 strncmp(current_driver_name, drv->name, NAME_MAX_LEN - 1) == 0) {
205 current_driver = drv;
209 read_unlock_irqrestore(&driver_name_lock, flags);
214 #define err_printk(dev, entry, format, arg...) do { \
216 if (driver_filter(dev) && \
217 (show_all_errors || show_num_errors > 0)) { \
218 WARN(1, pr_fmt("%s %s: ") format, \
219 dev ? dev_driver_string(dev) : "NULL", \
220 dev ? dev_name(dev) : "NULL", ## arg); \
221 dump_entry_trace(entry); \
223 if (!show_all_errors && show_num_errors > 0) \
224 show_num_errors -= 1; \
228 * Hash related functions
230 * Every DMA-API request is saved into a struct dma_debug_entry. To
231 * have quick access to these structs they are stored into a hash.
233 static int hash_fn(struct dma_debug_entry *entry)
236 * Hash function is based on the dma address.
237 * We use bits 20-27 here as the index into the hash
239 return (entry->dev_addr >> HASH_FN_SHIFT) & HASH_FN_MASK;
243 * Request exclusive access to a hash bucket for a given dma_debug_entry.
245 static struct hash_bucket *get_hash_bucket(struct dma_debug_entry *entry,
246 unsigned long *flags)
247 __acquires(&dma_entry_hash[idx].lock)
249 int idx = hash_fn(entry);
250 unsigned long __flags;
252 spin_lock_irqsave(&dma_entry_hash[idx].lock, __flags);
254 return &dma_entry_hash[idx];
258 * Give up exclusive access to the hash bucket
260 static void put_hash_bucket(struct hash_bucket *bucket,
261 unsigned long *flags)
262 __releases(&bucket->lock)
264 unsigned long __flags = *flags;
266 spin_unlock_irqrestore(&bucket->lock, __flags);
269 static bool exact_match(struct dma_debug_entry *a, struct dma_debug_entry *b)
271 return ((a->dev_addr == b->dev_addr) &&
272 (a->dev == b->dev)) ? true : false;
275 static bool containing_match(struct dma_debug_entry *a,
276 struct dma_debug_entry *b)
278 if (a->dev != b->dev)
281 if ((b->dev_addr <= a->dev_addr) &&
282 ((b->dev_addr + b->size) >= (a->dev_addr + a->size)))
289 * Search a given entry in the hash bucket list
291 static struct dma_debug_entry *__hash_bucket_find(struct hash_bucket *bucket,
292 struct dma_debug_entry *ref,
295 struct dma_debug_entry *entry, *ret = NULL;
296 int matches = 0, match_lvl, last_lvl = -1;
298 list_for_each_entry(entry, &bucket->list, list) {
299 if (!match(ref, entry))
303 * Some drivers map the same physical address multiple
304 * times. Without a hardware IOMMU this results in the
305 * same device addresses being put into the dma-debug
306 * hash multiple times too. This can result in false
307 * positives being reported. Therefore we implement a
308 * best-fit algorithm here which returns the entry from
309 * the hash which fits best to the reference value
310 * instead of the first-fit.
314 entry->size == ref->size ? ++match_lvl : 0;
315 entry->type == ref->type ? ++match_lvl : 0;
316 entry->direction == ref->direction ? ++match_lvl : 0;
317 entry->sg_call_ents == ref->sg_call_ents ? ++match_lvl : 0;
319 if (match_lvl == 4) {
320 /* perfect-fit - return the result */
322 } else if (match_lvl > last_lvl) {
324 * We found an entry that fits better then the
325 * previous one or it is the 1st match.
327 last_lvl = match_lvl;
333 * If we have multiple matches but no perfect-fit, just return
336 ret = (matches == 1) ? ret : NULL;
341 static struct dma_debug_entry *bucket_find_exact(struct hash_bucket *bucket,
342 struct dma_debug_entry *ref)
344 return __hash_bucket_find(bucket, ref, exact_match);
347 static struct dma_debug_entry *bucket_find_contain(struct hash_bucket **bucket,
348 struct dma_debug_entry *ref,
349 unsigned long *flags)
352 unsigned int max_range = dma_get_max_seg_size(ref->dev);
353 struct dma_debug_entry *entry, index = *ref;
354 unsigned int range = 0;
356 while (range <= max_range) {
357 entry = __hash_bucket_find(*bucket, ref, containing_match);
363 * Nothing found, go back a hash bucket
365 put_hash_bucket(*bucket, flags);
366 range += (1 << HASH_FN_SHIFT);
367 index.dev_addr -= (1 << HASH_FN_SHIFT);
368 *bucket = get_hash_bucket(&index, flags);
375 * Add an entry to a hash bucket
377 static void hash_bucket_add(struct hash_bucket *bucket,
378 struct dma_debug_entry *entry)
380 list_add_tail(&entry->list, &bucket->list);
384 * Remove entry from a hash bucket list
386 static void hash_bucket_del(struct dma_debug_entry *entry)
388 list_del(&entry->list);
391 static unsigned long long phys_addr(struct dma_debug_entry *entry)
393 if (entry->type == dma_debug_resource)
394 return __pfn_to_phys(entry->pfn) + entry->offset;
396 return page_to_phys(pfn_to_page(entry->pfn)) + entry->offset;
400 * Dump mapping entries for debugging purposes
402 void debug_dma_dump_mappings(struct device *dev)
406 for (idx = 0; idx < HASH_SIZE; idx++) {
407 struct hash_bucket *bucket = &dma_entry_hash[idx];
408 struct dma_debug_entry *entry;
411 spin_lock_irqsave(&bucket->lock, flags);
413 list_for_each_entry(entry, &bucket->list, list) {
414 if (!dev || dev == entry->dev) {
416 "%s idx %d P=%Lx N=%lx D=%Lx L=%Lx %s %s\n",
417 type2name[entry->type], idx,
418 phys_addr(entry), entry->pfn,
419 entry->dev_addr, entry->size,
420 dir2name[entry->direction],
421 maperr2str[entry->map_err_type]);
425 spin_unlock_irqrestore(&bucket->lock, flags);
431 * For each mapping (initial cacheline in the case of
432 * dma_alloc_coherent/dma_map_page, initial cacheline in each page of a
433 * scatterlist, or the cacheline specified in dma_map_single) insert
434 * into this tree using the cacheline as the key. At
435 * dma_unmap_{single|sg|page} or dma_free_coherent delete the entry. If
436 * the entry already exists at insertion time add a tag as a reference
437 * count for the overlapping mappings. For now, the overlap tracking
438 * just ensures that 'unmaps' balance 'maps' before marking the
439 * cacheline idle, but we should also be flagging overlaps as an API
442 * Memory usage is mostly constrained by the maximum number of available
443 * dma-debug entries in that we need a free dma_debug_entry before
444 * inserting into the tree. In the case of dma_map_page and
445 * dma_alloc_coherent there is only one dma_debug_entry and one
446 * dma_active_cacheline entry to track per event. dma_map_sg(), on the
447 * other hand, consumes a single dma_debug_entry, but inserts 'nents'
448 * entries into the tree.
450 * At any time debug_dma_assert_idle() can be called to trigger a
451 * warning if any cachelines in the given page are in the active set.
453 static RADIX_TREE(dma_active_cacheline, GFP_ATOMIC);
454 static DEFINE_SPINLOCK(radix_lock);
455 #define ACTIVE_CACHELINE_MAX_OVERLAP ((1 << RADIX_TREE_MAX_TAGS) - 1)
456 #define CACHELINE_PER_PAGE_SHIFT (PAGE_SHIFT - L1_CACHE_SHIFT)
457 #define CACHELINES_PER_PAGE (1 << CACHELINE_PER_PAGE_SHIFT)
459 static phys_addr_t to_cacheline_number(struct dma_debug_entry *entry)
461 return (entry->pfn << CACHELINE_PER_PAGE_SHIFT) +
462 (entry->offset >> L1_CACHE_SHIFT);
465 static int active_cacheline_read_overlap(phys_addr_t cln)
469 for (i = RADIX_TREE_MAX_TAGS - 1; i >= 0; i--)
470 if (radix_tree_tag_get(&dma_active_cacheline, cln, i))
475 static int active_cacheline_set_overlap(phys_addr_t cln, int overlap)
479 if (overlap > ACTIVE_CACHELINE_MAX_OVERLAP || overlap < 0)
482 for (i = RADIX_TREE_MAX_TAGS - 1; i >= 0; i--)
483 if (overlap & 1 << i)
484 radix_tree_tag_set(&dma_active_cacheline, cln, i);
486 radix_tree_tag_clear(&dma_active_cacheline, cln, i);
491 static void active_cacheline_inc_overlap(phys_addr_t cln)
493 int overlap = active_cacheline_read_overlap(cln);
495 overlap = active_cacheline_set_overlap(cln, ++overlap);
497 /* If we overflowed the overlap counter then we're potentially
498 * leaking dma-mappings. Otherwise, if maps and unmaps are
499 * balanced then this overflow may cause false negatives in
500 * debug_dma_assert_idle() as the cacheline may be marked idle
503 WARN_ONCE(overlap > ACTIVE_CACHELINE_MAX_OVERLAP,
504 pr_fmt("exceeded %d overlapping mappings of cacheline %pa\n"),
505 ACTIVE_CACHELINE_MAX_OVERLAP, &cln);
508 static int active_cacheline_dec_overlap(phys_addr_t cln)
510 int overlap = active_cacheline_read_overlap(cln);
512 return active_cacheline_set_overlap(cln, --overlap);
515 static int active_cacheline_insert(struct dma_debug_entry *entry)
517 phys_addr_t cln = to_cacheline_number(entry);
521 /* If the device is not writing memory then we don't have any
522 * concerns about the cpu consuming stale data. This mitigates
523 * legitimate usages of overlapping mappings.
525 if (entry->direction == DMA_TO_DEVICE)
528 spin_lock_irqsave(&radix_lock, flags);
529 rc = radix_tree_insert(&dma_active_cacheline, cln, entry);
531 active_cacheline_inc_overlap(cln);
532 spin_unlock_irqrestore(&radix_lock, flags);
537 static void active_cacheline_remove(struct dma_debug_entry *entry)
539 phys_addr_t cln = to_cacheline_number(entry);
542 /* ...mirror the insert case */
543 if (entry->direction == DMA_TO_DEVICE)
546 spin_lock_irqsave(&radix_lock, flags);
547 /* since we are counting overlaps the final put of the
548 * cacheline will occur when the overlap count is 0.
549 * active_cacheline_dec_overlap() returns -1 in that case
551 if (active_cacheline_dec_overlap(cln) < 0)
552 radix_tree_delete(&dma_active_cacheline, cln);
553 spin_unlock_irqrestore(&radix_lock, flags);
557 * debug_dma_assert_idle() - assert that a page is not undergoing dma
558 * @page: page to lookup in the dma_active_cacheline tree
560 * Place a call to this routine in cases where the cpu touching the page
561 * before the dma completes (page is dma_unmapped) will lead to data
564 void debug_dma_assert_idle(struct page *page)
566 static struct dma_debug_entry *ents[CACHELINES_PER_PAGE];
567 struct dma_debug_entry *entry = NULL;
568 void **results = (void **) &ents;
569 unsigned int nents, i;
573 if (dma_debug_disabled())
579 cln = (phys_addr_t) page_to_pfn(page) << CACHELINE_PER_PAGE_SHIFT;
580 spin_lock_irqsave(&radix_lock, flags);
581 nents = radix_tree_gang_lookup(&dma_active_cacheline, results, cln,
582 CACHELINES_PER_PAGE);
583 for (i = 0; i < nents; i++) {
584 phys_addr_t ent_cln = to_cacheline_number(ents[i]);
586 if (ent_cln == cln) {
589 } else if (ent_cln >= cln + CACHELINES_PER_PAGE)
592 spin_unlock_irqrestore(&radix_lock, flags);
597 cln = to_cacheline_number(entry);
598 err_printk(entry->dev, entry,
599 "cpu touching an active dma mapped cacheline [cln=%pa]\n",
604 * Wrapper function for adding an entry to the hash.
605 * This function takes care of locking itself.
607 static void add_dma_entry(struct dma_debug_entry *entry)
609 struct hash_bucket *bucket;
613 bucket = get_hash_bucket(entry, &flags);
614 hash_bucket_add(bucket, entry);
615 put_hash_bucket(bucket, &flags);
617 rc = active_cacheline_insert(entry);
619 pr_err_once("cacheline tracking ENOMEM, dma-debug disabled\n");
620 global_disable = true;
623 /* TODO: report -EEXIST errors here as overlapping mappings are
624 * not supported by the DMA API
628 static int dma_debug_create_entries(gfp_t gfp)
630 struct dma_debug_entry *entry;
633 entry = (void *)get_zeroed_page(gfp);
637 for (i = 0; i < DMA_DEBUG_DYNAMIC_ENTRIES; i++)
638 list_add_tail(&entry[i].list, &free_entries);
640 num_free_entries += DMA_DEBUG_DYNAMIC_ENTRIES;
641 nr_total_entries += DMA_DEBUG_DYNAMIC_ENTRIES;
646 static struct dma_debug_entry *__dma_entry_alloc(void)
648 struct dma_debug_entry *entry;
650 entry = list_entry(free_entries.next, struct dma_debug_entry, list);
651 list_del(&entry->list);
652 memset(entry, 0, sizeof(*entry));
654 num_free_entries -= 1;
655 if (num_free_entries < min_free_entries)
656 min_free_entries = num_free_entries;
661 void __dma_entry_alloc_check_leak(void)
663 u32 tmp = nr_total_entries % nr_prealloc_entries;
665 /* Shout each time we tick over some multiple of the initial pool */
666 if (tmp < DMA_DEBUG_DYNAMIC_ENTRIES) {
667 pr_info("dma_debug_entry pool grown to %u (%u00%%)\n",
669 (nr_total_entries / nr_prealloc_entries));
673 /* struct dma_entry allocator
675 * The next two functions implement the allocator for
676 * struct dma_debug_entries.
678 static struct dma_debug_entry *dma_entry_alloc(void)
680 struct dma_debug_entry *entry;
683 spin_lock_irqsave(&free_entries_lock, flags);
684 if (num_free_entries == 0) {
685 if (dma_debug_create_entries(GFP_ATOMIC)) {
686 global_disable = true;
687 spin_unlock_irqrestore(&free_entries_lock, flags);
688 pr_err("debugging out of memory - disabling\n");
691 __dma_entry_alloc_check_leak();
694 entry = __dma_entry_alloc();
696 spin_unlock_irqrestore(&free_entries_lock, flags);
698 #ifdef CONFIG_STACKTRACE
699 entry->stack_len = stack_trace_save(entry->stack_entries,
700 ARRAY_SIZE(entry->stack_entries),
706 static void dma_entry_free(struct dma_debug_entry *entry)
710 active_cacheline_remove(entry);
713 * add to beginning of the list - this way the entries are
714 * more likely cache hot when they are reallocated.
716 spin_lock_irqsave(&free_entries_lock, flags);
717 list_add(&entry->list, &free_entries);
718 num_free_entries += 1;
719 spin_unlock_irqrestore(&free_entries_lock, flags);
723 * DMA-API debugging init code
725 * The init code does two things:
726 * 1. Initialize core data structures
727 * 2. Preallocate a given number of dma_debug_entry structs
730 static ssize_t filter_read(struct file *file, char __user *user_buf,
731 size_t count, loff_t *ppos)
733 char buf[NAME_MAX_LEN + 1];
737 if (!current_driver_name[0])
741 * We can't copy to userspace directly because current_driver_name can
742 * only be read under the driver_name_lock with irqs disabled. So
743 * create a temporary copy first.
745 read_lock_irqsave(&driver_name_lock, flags);
746 len = scnprintf(buf, NAME_MAX_LEN + 1, "%s\n", current_driver_name);
747 read_unlock_irqrestore(&driver_name_lock, flags);
749 return simple_read_from_buffer(user_buf, count, ppos, buf, len);
752 static ssize_t filter_write(struct file *file, const char __user *userbuf,
753 size_t count, loff_t *ppos)
755 char buf[NAME_MAX_LEN];
761 * We can't copy from userspace directly. Access to
762 * current_driver_name is protected with a write_lock with irqs
763 * disabled. Since copy_from_user can fault and may sleep we
764 * need to copy to temporary buffer first
766 len = min(count, (size_t)(NAME_MAX_LEN - 1));
767 if (copy_from_user(buf, userbuf, len))
772 write_lock_irqsave(&driver_name_lock, flags);
775 * Now handle the string we got from userspace very carefully.
777 * - only use the first token we got
778 * - token delimiter is everything looking like a space
779 * character (' ', '\n', '\t' ...)
782 if (!isalnum(buf[0])) {
784 * If the first character userspace gave us is not
785 * alphanumerical then assume the filter should be
788 if (current_driver_name[0])
789 pr_info("switching off dma-debug driver filter\n");
790 current_driver_name[0] = 0;
791 current_driver = NULL;
796 * Now parse out the first token and use it as the name for the
797 * driver to filter for.
799 for (i = 0; i < NAME_MAX_LEN - 1; ++i) {
800 current_driver_name[i] = buf[i];
801 if (isspace(buf[i]) || buf[i] == ' ' || buf[i] == 0)
804 current_driver_name[i] = 0;
805 current_driver = NULL;
807 pr_info("enable driver filter for driver [%s]\n",
808 current_driver_name);
811 write_unlock_irqrestore(&driver_name_lock, flags);
816 static const struct file_operations filter_fops = {
818 .write = filter_write,
819 .llseek = default_llseek,
822 static int dump_show(struct seq_file *seq, void *v)
826 for (idx = 0; idx < HASH_SIZE; idx++) {
827 struct hash_bucket *bucket = &dma_entry_hash[idx];
828 struct dma_debug_entry *entry;
831 spin_lock_irqsave(&bucket->lock, flags);
832 list_for_each_entry(entry, &bucket->list, list) {
834 "%s %s %s idx %d P=%llx N=%lx D=%llx L=%llx %s %s\n",
835 dev_name(entry->dev),
836 dev_driver_string(entry->dev),
837 type2name[entry->type], idx,
838 phys_addr(entry), entry->pfn,
839 entry->dev_addr, entry->size,
840 dir2name[entry->direction],
841 maperr2str[entry->map_err_type]);
843 spin_unlock_irqrestore(&bucket->lock, flags);
847 DEFINE_SHOW_ATTRIBUTE(dump);
849 static int __init dma_debug_fs_init(void)
851 struct dentry *dentry = debugfs_create_dir("dma-api", NULL);
853 debugfs_create_bool("disabled", 0444, dentry, &global_disable);
854 debugfs_create_u32("error_count", 0444, dentry, &error_count);
855 debugfs_create_u32("all_errors", 0644, dentry, &show_all_errors);
856 debugfs_create_u32("num_errors", 0644, dentry, &show_num_errors);
857 debugfs_create_u32("num_free_entries", 0444, dentry, &num_free_entries);
858 debugfs_create_u32("min_free_entries", 0444, dentry, &min_free_entries);
859 debugfs_create_u32("nr_total_entries", 0444, dentry, &nr_total_entries);
860 debugfs_create_file("driver_filter", 0644, dentry, NULL, &filter_fops);
861 debugfs_create_file("dump", 0444, dentry, NULL, &dump_fops);
865 core_initcall_sync(dma_debug_fs_init);
867 static int device_dma_allocations(struct device *dev, struct dma_debug_entry **out_entry)
869 struct dma_debug_entry *entry;
873 for (i = 0; i < HASH_SIZE; ++i) {
874 spin_lock_irqsave(&dma_entry_hash[i].lock, flags);
875 list_for_each_entry(entry, &dma_entry_hash[i].list, list) {
876 if (entry->dev == dev) {
881 spin_unlock_irqrestore(&dma_entry_hash[i].lock, flags);
887 static int dma_debug_device_change(struct notifier_block *nb, unsigned long action, void *data)
889 struct device *dev = data;
890 struct dma_debug_entry *entry;
893 if (dma_debug_disabled())
897 case BUS_NOTIFY_UNBOUND_DRIVER:
898 count = device_dma_allocations(dev, &entry);
901 err_printk(dev, entry, "device driver has pending "
902 "DMA allocations while released from device "
904 "One of leaked entries details: "
905 "[device address=0x%016llx] [size=%llu bytes] "
906 "[mapped with %s] [mapped as %s]\n",
907 count, entry->dev_addr, entry->size,
908 dir2name[entry->direction], type2name[entry->type]);
917 void dma_debug_add_bus(struct bus_type *bus)
919 struct notifier_block *nb;
921 if (dma_debug_disabled())
924 nb = kzalloc(sizeof(struct notifier_block), GFP_KERNEL);
926 pr_err("dma_debug_add_bus: out of memory\n");
930 nb->notifier_call = dma_debug_device_change;
932 bus_register_notifier(bus, nb);
935 static int dma_debug_init(void)
939 /* Do not use dma_debug_initialized here, since we really want to be
940 * called to set dma_debug_initialized
945 for (i = 0; i < HASH_SIZE; ++i) {
946 INIT_LIST_HEAD(&dma_entry_hash[i].list);
947 spin_lock_init(&dma_entry_hash[i].lock);
950 nr_pages = DIV_ROUND_UP(nr_prealloc_entries, DMA_DEBUG_DYNAMIC_ENTRIES);
951 for (i = 0; i < nr_pages; ++i)
952 dma_debug_create_entries(GFP_KERNEL);
953 if (num_free_entries >= nr_prealloc_entries) {
954 pr_info("preallocated %d debug entries\n", nr_total_entries);
955 } else if (num_free_entries > 0) {
956 pr_warn("%d debug entries requested but only %d allocated\n",
957 nr_prealloc_entries, nr_total_entries);
959 pr_err("debugging out of memory error - disabled\n");
960 global_disable = true;
964 min_free_entries = num_free_entries;
966 dma_debug_initialized = true;
968 pr_info("debugging enabled by kernel config\n");
971 core_initcall(dma_debug_init);
973 static __init int dma_debug_cmdline(char *str)
978 if (strncmp(str, "off", 3) == 0) {
979 pr_info("debugging disabled on kernel command line\n");
980 global_disable = true;
986 static __init int dma_debug_entries_cmdline(char *str)
990 if (!get_option(&str, &nr_prealloc_entries))
991 nr_prealloc_entries = PREALLOC_DMA_DEBUG_ENTRIES;
995 __setup("dma_debug=", dma_debug_cmdline);
996 __setup("dma_debug_entries=", dma_debug_entries_cmdline);
998 static void check_unmap(struct dma_debug_entry *ref)
1000 struct dma_debug_entry *entry;
1001 struct hash_bucket *bucket;
1002 unsigned long flags;
1004 bucket = get_hash_bucket(ref, &flags);
1005 entry = bucket_find_exact(bucket, ref);
1008 /* must drop lock before calling dma_mapping_error */
1009 put_hash_bucket(bucket, &flags);
1011 if (dma_mapping_error(ref->dev, ref->dev_addr)) {
1012 err_printk(ref->dev, NULL,
1013 "device driver tries to free an "
1014 "invalid DMA memory address\n");
1016 err_printk(ref->dev, NULL,
1017 "device driver tries to free DMA "
1018 "memory it has not allocated [device "
1019 "address=0x%016llx] [size=%llu bytes]\n",
1020 ref->dev_addr, ref->size);
1025 if (ref->size != entry->size) {
1026 err_printk(ref->dev, entry, "device driver frees "
1027 "DMA memory with different size "
1028 "[device address=0x%016llx] [map size=%llu bytes] "
1029 "[unmap size=%llu bytes]\n",
1030 ref->dev_addr, entry->size, ref->size);
1033 if (ref->type != entry->type) {
1034 err_printk(ref->dev, entry, "device driver frees "
1035 "DMA memory with wrong function "
1036 "[device address=0x%016llx] [size=%llu bytes] "
1037 "[mapped as %s] [unmapped as %s]\n",
1038 ref->dev_addr, ref->size,
1039 type2name[entry->type], type2name[ref->type]);
1040 } else if ((entry->type == dma_debug_coherent) &&
1041 (phys_addr(ref) != phys_addr(entry))) {
1042 err_printk(ref->dev, entry, "device driver frees "
1043 "DMA memory with different CPU address "
1044 "[device address=0x%016llx] [size=%llu bytes] "
1045 "[cpu alloc address=0x%016llx] "
1046 "[cpu free address=0x%016llx]",
1047 ref->dev_addr, ref->size,
1052 if (ref->sg_call_ents && ref->type == dma_debug_sg &&
1053 ref->sg_call_ents != entry->sg_call_ents) {
1054 err_printk(ref->dev, entry, "device driver frees "
1055 "DMA sg list with different entry count "
1056 "[map count=%d] [unmap count=%d]\n",
1057 entry->sg_call_ents, ref->sg_call_ents);
1061 * This may be no bug in reality - but most implementations of the
1062 * DMA API don't handle this properly, so check for it here
1064 if (ref->direction != entry->direction) {
1065 err_printk(ref->dev, entry, "device driver frees "
1066 "DMA memory with different direction "
1067 "[device address=0x%016llx] [size=%llu bytes] "
1068 "[mapped with %s] [unmapped with %s]\n",
1069 ref->dev_addr, ref->size,
1070 dir2name[entry->direction],
1071 dir2name[ref->direction]);
1075 * Drivers should use dma_mapping_error() to check the returned
1076 * addresses of dma_map_single() and dma_map_page().
1077 * If not, print this warning message. See Documentation/DMA-API.txt.
1079 if (entry->map_err_type == MAP_ERR_NOT_CHECKED) {
1080 err_printk(ref->dev, entry,
1081 "device driver failed to check map error"
1082 "[device address=0x%016llx] [size=%llu bytes] "
1084 ref->dev_addr, ref->size,
1085 type2name[entry->type]);
1088 hash_bucket_del(entry);
1089 dma_entry_free(entry);
1091 put_hash_bucket(bucket, &flags);
1094 static void check_for_stack(struct device *dev,
1095 struct page *page, size_t offset)
1098 struct vm_struct *stack_vm_area = task_stack_vm_area(current);
1100 if (!stack_vm_area) {
1101 /* Stack is direct-mapped. */
1102 if (PageHighMem(page))
1104 addr = page_address(page) + offset;
1105 if (object_is_on_stack(addr))
1106 err_printk(dev, NULL, "device driver maps memory from stack [addr=%p]\n", addr);
1108 /* Stack is vmalloced. */
1111 for (i = 0; i < stack_vm_area->nr_pages; i++) {
1112 if (page != stack_vm_area->pages[i])
1115 addr = (u8 *)current->stack + i * PAGE_SIZE + offset;
1116 err_printk(dev, NULL, "device driver maps memory from stack [probable addr=%p]\n", addr);
1122 static inline bool overlap(void *addr, unsigned long len, void *start, void *end)
1124 unsigned long a1 = (unsigned long)addr;
1125 unsigned long b1 = a1 + len;
1126 unsigned long a2 = (unsigned long)start;
1127 unsigned long b2 = (unsigned long)end;
1129 return !(b1 <= a2 || a1 >= b2);
1132 static void check_for_illegal_area(struct device *dev, void *addr, unsigned long len)
1134 if (overlap(addr, len, _stext, _etext) ||
1135 overlap(addr, len, __start_rodata, __end_rodata))
1136 err_printk(dev, NULL, "device driver maps memory from kernel text or rodata [addr=%p] [len=%lu]\n", addr, len);
1139 static void check_sync(struct device *dev,
1140 struct dma_debug_entry *ref,
1143 struct dma_debug_entry *entry;
1144 struct hash_bucket *bucket;
1145 unsigned long flags;
1147 bucket = get_hash_bucket(ref, &flags);
1149 entry = bucket_find_contain(&bucket, ref, &flags);
1152 err_printk(dev, NULL, "device driver tries "
1153 "to sync DMA memory it has not allocated "
1154 "[device address=0x%016llx] [size=%llu bytes]\n",
1155 (unsigned long long)ref->dev_addr, ref->size);
1159 if (ref->size > entry->size) {
1160 err_printk(dev, entry, "device driver syncs"
1161 " DMA memory outside allocated range "
1162 "[device address=0x%016llx] "
1163 "[allocation size=%llu bytes] "
1164 "[sync offset+size=%llu]\n",
1165 entry->dev_addr, entry->size,
1169 if (entry->direction == DMA_BIDIRECTIONAL)
1172 if (ref->direction != entry->direction) {
1173 err_printk(dev, entry, "device driver syncs "
1174 "DMA memory with different direction "
1175 "[device address=0x%016llx] [size=%llu bytes] "
1176 "[mapped with %s] [synced with %s]\n",
1177 (unsigned long long)ref->dev_addr, entry->size,
1178 dir2name[entry->direction],
1179 dir2name[ref->direction]);
1182 if (to_cpu && !(entry->direction == DMA_FROM_DEVICE) &&
1183 !(ref->direction == DMA_TO_DEVICE))
1184 err_printk(dev, entry, "device driver syncs "
1185 "device read-only DMA memory for cpu "
1186 "[device address=0x%016llx] [size=%llu bytes] "
1187 "[mapped with %s] [synced with %s]\n",
1188 (unsigned long long)ref->dev_addr, entry->size,
1189 dir2name[entry->direction],
1190 dir2name[ref->direction]);
1192 if (!to_cpu && !(entry->direction == DMA_TO_DEVICE) &&
1193 !(ref->direction == DMA_FROM_DEVICE))
1194 err_printk(dev, entry, "device driver syncs "
1195 "device write-only DMA memory to device "
1196 "[device address=0x%016llx] [size=%llu bytes] "
1197 "[mapped with %s] [synced with %s]\n",
1198 (unsigned long long)ref->dev_addr, entry->size,
1199 dir2name[entry->direction],
1200 dir2name[ref->direction]);
1202 if (ref->sg_call_ents && ref->type == dma_debug_sg &&
1203 ref->sg_call_ents != entry->sg_call_ents) {
1204 err_printk(ref->dev, entry, "device driver syncs "
1205 "DMA sg list with different entry count "
1206 "[map count=%d] [sync count=%d]\n",
1207 entry->sg_call_ents, ref->sg_call_ents);
1211 put_hash_bucket(bucket, &flags);
1214 static void check_sg_segment(struct device *dev, struct scatterlist *sg)
1216 #ifdef CONFIG_DMA_API_DEBUG_SG
1217 unsigned int max_seg = dma_get_max_seg_size(dev);
1218 u64 start, end, boundary = dma_get_seg_boundary(dev);
1221 * Either the driver forgot to set dma_parms appropriately, or
1222 * whoever generated the list forgot to check them.
1224 if (sg->length > max_seg)
1225 err_printk(dev, NULL, "mapping sg segment longer than device claims to support [len=%u] [max=%u]\n",
1226 sg->length, max_seg);
1228 * In some cases this could potentially be the DMA API
1229 * implementation's fault, but it would usually imply that
1230 * the scatterlist was built inappropriately to begin with.
1232 start = sg_dma_address(sg);
1233 end = start + sg_dma_len(sg) - 1;
1234 if ((start ^ end) & ~boundary)
1235 err_printk(dev, NULL, "mapping sg segment across boundary [start=0x%016llx] [end=0x%016llx] [boundary=0x%016llx]\n",
1236 start, end, boundary);
1240 void debug_dma_map_single(struct device *dev, const void *addr,
1243 if (unlikely(dma_debug_disabled()))
1246 if (!virt_addr_valid(addr))
1247 err_printk(dev, NULL, "device driver maps memory from invalid area [addr=%p] [len=%lu]\n",
1250 if (is_vmalloc_addr(addr))
1251 err_printk(dev, NULL, "device driver maps memory from vmalloc area [addr=%p] [len=%lu]\n",
1254 EXPORT_SYMBOL(debug_dma_map_single);
1256 void debug_dma_map_page(struct device *dev, struct page *page, size_t offset,
1257 size_t size, int direction, dma_addr_t dma_addr)
1259 struct dma_debug_entry *entry;
1261 if (unlikely(dma_debug_disabled()))
1264 if (dma_mapping_error(dev, dma_addr))
1267 entry = dma_entry_alloc();
1272 entry->type = dma_debug_single;
1273 entry->pfn = page_to_pfn(page);
1274 entry->offset = offset,
1275 entry->dev_addr = dma_addr;
1277 entry->direction = direction;
1278 entry->map_err_type = MAP_ERR_NOT_CHECKED;
1280 check_for_stack(dev, page, offset);
1282 if (!PageHighMem(page)) {
1283 void *addr = page_address(page) + offset;
1285 check_for_illegal_area(dev, addr, size);
1288 add_dma_entry(entry);
1290 EXPORT_SYMBOL(debug_dma_map_page);
1292 void debug_dma_mapping_error(struct device *dev, dma_addr_t dma_addr)
1294 struct dma_debug_entry ref;
1295 struct dma_debug_entry *entry;
1296 struct hash_bucket *bucket;
1297 unsigned long flags;
1299 if (unlikely(dma_debug_disabled()))
1303 ref.dev_addr = dma_addr;
1304 bucket = get_hash_bucket(&ref, &flags);
1306 list_for_each_entry(entry, &bucket->list, list) {
1307 if (!exact_match(&ref, entry))
1311 * The same physical address can be mapped multiple
1312 * times. Without a hardware IOMMU this results in the
1313 * same device addresses being put into the dma-debug
1314 * hash multiple times too. This can result in false
1315 * positives being reported. Therefore we implement a
1316 * best-fit algorithm here which updates the first entry
1317 * from the hash which fits the reference value and is
1318 * not currently listed as being checked.
1320 if (entry->map_err_type == MAP_ERR_NOT_CHECKED) {
1321 entry->map_err_type = MAP_ERR_CHECKED;
1326 put_hash_bucket(bucket, &flags);
1328 EXPORT_SYMBOL(debug_dma_mapping_error);
1330 void debug_dma_unmap_page(struct device *dev, dma_addr_t addr,
1331 size_t size, int direction)
1333 struct dma_debug_entry ref = {
1334 .type = dma_debug_single,
1338 .direction = direction,
1341 if (unlikely(dma_debug_disabled()))
1345 EXPORT_SYMBOL(debug_dma_unmap_page);
1347 void debug_dma_map_sg(struct device *dev, struct scatterlist *sg,
1348 int nents, int mapped_ents, int direction)
1350 struct dma_debug_entry *entry;
1351 struct scatterlist *s;
1354 if (unlikely(dma_debug_disabled()))
1357 for_each_sg(sg, s, nents, i) {
1358 check_for_stack(dev, sg_page(s), s->offset);
1359 if (!PageHighMem(sg_page(s)))
1360 check_for_illegal_area(dev, sg_virt(s), s->length);
1363 for_each_sg(sg, s, mapped_ents, i) {
1364 entry = dma_entry_alloc();
1368 entry->type = dma_debug_sg;
1370 entry->pfn = page_to_pfn(sg_page(s));
1371 entry->offset = s->offset,
1372 entry->size = sg_dma_len(s);
1373 entry->dev_addr = sg_dma_address(s);
1374 entry->direction = direction;
1375 entry->sg_call_ents = nents;
1376 entry->sg_mapped_ents = mapped_ents;
1378 check_sg_segment(dev, s);
1380 add_dma_entry(entry);
1383 EXPORT_SYMBOL(debug_dma_map_sg);
1385 static int get_nr_mapped_entries(struct device *dev,
1386 struct dma_debug_entry *ref)
1388 struct dma_debug_entry *entry;
1389 struct hash_bucket *bucket;
1390 unsigned long flags;
1393 bucket = get_hash_bucket(ref, &flags);
1394 entry = bucket_find_exact(bucket, ref);
1398 mapped_ents = entry->sg_mapped_ents;
1399 put_hash_bucket(bucket, &flags);
1404 void debug_dma_unmap_sg(struct device *dev, struct scatterlist *sglist,
1405 int nelems, int dir)
1407 struct scatterlist *s;
1408 int mapped_ents = 0, i;
1410 if (unlikely(dma_debug_disabled()))
1413 for_each_sg(sglist, s, nelems, i) {
1415 struct dma_debug_entry ref = {
1416 .type = dma_debug_sg,
1418 .pfn = page_to_pfn(sg_page(s)),
1419 .offset = s->offset,
1420 .dev_addr = sg_dma_address(s),
1421 .size = sg_dma_len(s),
1423 .sg_call_ents = nelems,
1426 if (mapped_ents && i >= mapped_ents)
1430 mapped_ents = get_nr_mapped_entries(dev, &ref);
1435 EXPORT_SYMBOL(debug_dma_unmap_sg);
1437 void debug_dma_alloc_coherent(struct device *dev, size_t size,
1438 dma_addr_t dma_addr, void *virt)
1440 struct dma_debug_entry *entry;
1442 if (unlikely(dma_debug_disabled()))
1445 if (unlikely(virt == NULL))
1448 /* handle vmalloc and linear addresses */
1449 if (!is_vmalloc_addr(virt) && !virt_addr_valid(virt))
1452 entry = dma_entry_alloc();
1456 entry->type = dma_debug_coherent;
1458 entry->offset = offset_in_page(virt);
1460 entry->dev_addr = dma_addr;
1461 entry->direction = DMA_BIDIRECTIONAL;
1463 if (is_vmalloc_addr(virt))
1464 entry->pfn = vmalloc_to_pfn(virt);
1466 entry->pfn = page_to_pfn(virt_to_page(virt));
1468 add_dma_entry(entry);
1471 void debug_dma_free_coherent(struct device *dev, size_t size,
1472 void *virt, dma_addr_t addr)
1474 struct dma_debug_entry ref = {
1475 .type = dma_debug_coherent,
1477 .offset = offset_in_page(virt),
1480 .direction = DMA_BIDIRECTIONAL,
1483 /* handle vmalloc and linear addresses */
1484 if (!is_vmalloc_addr(virt) && !virt_addr_valid(virt))
1487 if (is_vmalloc_addr(virt))
1488 ref.pfn = vmalloc_to_pfn(virt);
1490 ref.pfn = page_to_pfn(virt_to_page(virt));
1492 if (unlikely(dma_debug_disabled()))
1498 void debug_dma_map_resource(struct device *dev, phys_addr_t addr, size_t size,
1499 int direction, dma_addr_t dma_addr)
1501 struct dma_debug_entry *entry;
1503 if (unlikely(dma_debug_disabled()))
1506 entry = dma_entry_alloc();
1510 entry->type = dma_debug_resource;
1512 entry->pfn = PHYS_PFN(addr);
1513 entry->offset = offset_in_page(addr);
1515 entry->dev_addr = dma_addr;
1516 entry->direction = direction;
1517 entry->map_err_type = MAP_ERR_NOT_CHECKED;
1519 add_dma_entry(entry);
1521 EXPORT_SYMBOL(debug_dma_map_resource);
1523 void debug_dma_unmap_resource(struct device *dev, dma_addr_t dma_addr,
1524 size_t size, int direction)
1526 struct dma_debug_entry ref = {
1527 .type = dma_debug_resource,
1529 .dev_addr = dma_addr,
1531 .direction = direction,
1534 if (unlikely(dma_debug_disabled()))
1539 EXPORT_SYMBOL(debug_dma_unmap_resource);
1541 void debug_dma_sync_single_for_cpu(struct device *dev, dma_addr_t dma_handle,
1542 size_t size, int direction)
1544 struct dma_debug_entry ref;
1546 if (unlikely(dma_debug_disabled()))
1549 ref.type = dma_debug_single;
1551 ref.dev_addr = dma_handle;
1553 ref.direction = direction;
1554 ref.sg_call_ents = 0;
1556 check_sync(dev, &ref, true);
1558 EXPORT_SYMBOL(debug_dma_sync_single_for_cpu);
1560 void debug_dma_sync_single_for_device(struct device *dev,
1561 dma_addr_t dma_handle, size_t size,
1564 struct dma_debug_entry ref;
1566 if (unlikely(dma_debug_disabled()))
1569 ref.type = dma_debug_single;
1571 ref.dev_addr = dma_handle;
1573 ref.direction = direction;
1574 ref.sg_call_ents = 0;
1576 check_sync(dev, &ref, false);
1578 EXPORT_SYMBOL(debug_dma_sync_single_for_device);
1580 void debug_dma_sync_sg_for_cpu(struct device *dev, struct scatterlist *sg,
1581 int nelems, int direction)
1583 struct scatterlist *s;
1584 int mapped_ents = 0, i;
1586 if (unlikely(dma_debug_disabled()))
1589 for_each_sg(sg, s, nelems, i) {
1591 struct dma_debug_entry ref = {
1592 .type = dma_debug_sg,
1594 .pfn = page_to_pfn(sg_page(s)),
1595 .offset = s->offset,
1596 .dev_addr = sg_dma_address(s),
1597 .size = sg_dma_len(s),
1598 .direction = direction,
1599 .sg_call_ents = nelems,
1603 mapped_ents = get_nr_mapped_entries(dev, &ref);
1605 if (i >= mapped_ents)
1608 check_sync(dev, &ref, true);
1611 EXPORT_SYMBOL(debug_dma_sync_sg_for_cpu);
1613 void debug_dma_sync_sg_for_device(struct device *dev, struct scatterlist *sg,
1614 int nelems, int direction)
1616 struct scatterlist *s;
1617 int mapped_ents = 0, i;
1619 if (unlikely(dma_debug_disabled()))
1622 for_each_sg(sg, s, nelems, i) {
1624 struct dma_debug_entry ref = {
1625 .type = dma_debug_sg,
1627 .pfn = page_to_pfn(sg_page(s)),
1628 .offset = s->offset,
1629 .dev_addr = sg_dma_address(s),
1630 .size = sg_dma_len(s),
1631 .direction = direction,
1632 .sg_call_ents = nelems,
1635 mapped_ents = get_nr_mapped_entries(dev, &ref);
1637 if (i >= mapped_ents)
1640 check_sync(dev, &ref, false);
1643 EXPORT_SYMBOL(debug_dma_sync_sg_for_device);
1645 static int __init dma_debug_driver_setup(char *str)
1649 for (i = 0; i < NAME_MAX_LEN - 1; ++i, ++str) {
1650 current_driver_name[i] = *str;
1655 if (current_driver_name[0])
1656 pr_info("enable driver filter for driver [%s]\n",
1657 current_driver_name);
1662 __setup("dma_debug_driver=", dma_debug_driver_setup);