Merge branch 'work.fdpic' of git://git.kernel.org/pub/scm/linux/kernel/git/viro/vfs
[linux-2.6-microblaze.git] / kernel / dma / debug.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2008 Advanced Micro Devices, Inc.
4  *
5  * Author: Joerg Roedel <joerg.roedel@amd.com>
6  */
7
8 #define pr_fmt(fmt)     "DMA-API: " fmt
9
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>
27
28 #include <asm/sections.h>
29
30 #define HASH_SIZE       16384ULL
31 #define HASH_FN_SHIFT   13
32 #define HASH_FN_MASK    (HASH_SIZE - 1)
33
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))
37
38 enum {
39         dma_debug_single,
40         dma_debug_sg,
41         dma_debug_coherent,
42         dma_debug_resource,
43 };
44
45 enum map_err_types {
46         MAP_ERR_CHECK_NOT_APPLICABLE,
47         MAP_ERR_NOT_CHECKED,
48         MAP_ERR_CHECKED,
49 };
50
51 #define DMA_DEBUG_STACKTRACE_ENTRIES 5
52
53 /**
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  * @size: length of the mapping
58  * @type: single, page, sg, coherent
59  * @direction: enum dma_data_direction
60  * @sg_call_ents: 'nents' from dma_map_sg
61  * @sg_mapped_ents: 'mapped_ents' from dma_map_sg
62  * @pfn: page frame of the start address
63  * @offset: offset of mapping relative to pfn
64  * @map_err_type: track whether dma_mapping_error() was checked
65  * @stacktrace: support backtraces when a violation is detected
66  */
67 struct dma_debug_entry {
68         struct list_head list;
69         struct device    *dev;
70         u64              dev_addr;
71         u64              size;
72         int              type;
73         int              direction;
74         int              sg_call_ents;
75         int              sg_mapped_ents;
76         unsigned long    pfn;
77         size_t           offset;
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];
82 #endif
83 } ____cacheline_aligned_in_smp;
84
85 typedef bool (*match_fn)(struct dma_debug_entry *, struct dma_debug_entry *);
86
87 struct hash_bucket {
88         struct list_head list;
89         spinlock_t lock;
90 };
91
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);
98
99 /* Global disable flag - will be set in case of an error */
100 static bool global_disable __read_mostly;
101
102 /* Early initialization disable flag, set at the end of dma_debug_init */
103 static bool dma_debug_initialized __read_mostly;
104
105 static inline bool dma_debug_disabled(void)
106 {
107         return global_disable || !dma_debug_initialized;
108 }
109
110 /* Global error count */
111 static u32 error_count;
112
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;
117
118 static u32 num_free_entries;
119 static u32 min_free_entries;
120 static u32 nr_total_entries;
121
122 /* number of preallocated entries requested by kernel cmdline */
123 static u32 nr_prealloc_entries = PREALLOC_DMA_DEBUG_ENTRIES;
124
125 /* per-driver filter related state */
126
127 #define NAME_MAX_LEN    64
128
129 static char                  current_driver_name[NAME_MAX_LEN] __read_mostly;
130 static struct device_driver *current_driver                    __read_mostly;
131
132 static DEFINE_RWLOCK(driver_name_lock);
133
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",
138 };
139
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",
145 };
146
147 static const char *dir2name[] = {
148         [DMA_BIDIRECTIONAL]     = "DMA_BIDIRECTIONAL",
149         [DMA_TO_DEVICE]         = "DMA_TO_DEVICE",
150         [DMA_FROM_DEVICE]       = "DMA_FROM_DEVICE",
151         [DMA_NONE]              = "DMA_NONE",
152 };
153
154 /*
155  * The access to some variables in this macro is racy. We can't use atomic_t
156  * here because all these variables are exported to debugfs. Some of them even
157  * writeable. This is also the reason why a lock won't help much. But anyway,
158  * the races are no big deal. Here is why:
159  *
160  *   error_count: the addition is racy, but the worst thing that can happen is
161  *                that we don't count some errors
162  *   show_num_errors: the subtraction is racy. Also no big deal because in
163  *                    worst case this will result in one warning more in the
164  *                    system log than the user configured. This variable is
165  *                    writeable via debugfs.
166  */
167 static inline void dump_entry_trace(struct dma_debug_entry *entry)
168 {
169 #ifdef CONFIG_STACKTRACE
170         if (entry) {
171                 pr_warn("Mapped at:\n");
172                 stack_trace_print(entry->stack_entries, entry->stack_len, 0);
173         }
174 #endif
175 }
176
177 static bool driver_filter(struct device *dev)
178 {
179         struct device_driver *drv;
180         unsigned long flags;
181         bool ret;
182
183         /* driver filter off */
184         if (likely(!current_driver_name[0]))
185                 return true;
186
187         /* driver filter on and initialized */
188         if (current_driver && dev && dev->driver == current_driver)
189                 return true;
190
191         /* driver filter on, but we can't filter on a NULL device... */
192         if (!dev)
193                 return false;
194
195         if (current_driver || !current_driver_name[0])
196                 return false;
197
198         /* driver filter on but not yet initialized */
199         drv = dev->driver;
200         if (!drv)
201                 return false;
202
203         /* lock to protect against change of current_driver_name */
204         read_lock_irqsave(&driver_name_lock, flags);
205
206         ret = false;
207         if (drv->name &&
208             strncmp(current_driver_name, drv->name, NAME_MAX_LEN - 1) == 0) {
209                 current_driver = drv;
210                 ret = true;
211         }
212
213         read_unlock_irqrestore(&driver_name_lock, flags);
214
215         return ret;
216 }
217
218 #define err_printk(dev, entry, format, arg...) do {                     \
219                 error_count += 1;                                       \
220                 if (driver_filter(dev) &&                               \
221                     (show_all_errors || show_num_errors > 0)) {         \
222                         WARN(1, pr_fmt("%s %s: ") format,               \
223                              dev ? dev_driver_string(dev) : "NULL",     \
224                              dev ? dev_name(dev) : "NULL", ## arg);     \
225                         dump_entry_trace(entry);                        \
226                 }                                                       \
227                 if (!show_all_errors && show_num_errors > 0)            \
228                         show_num_errors -= 1;                           \
229         } while (0);
230
231 /*
232  * Hash related functions
233  *
234  * Every DMA-API request is saved into a struct dma_debug_entry. To
235  * have quick access to these structs they are stored into a hash.
236  */
237 static int hash_fn(struct dma_debug_entry *entry)
238 {
239         /*
240          * Hash function is based on the dma address.
241          * We use bits 20-27 here as the index into the hash
242          */
243         return (entry->dev_addr >> HASH_FN_SHIFT) & HASH_FN_MASK;
244 }
245
246 /*
247  * Request exclusive access to a hash bucket for a given dma_debug_entry.
248  */
249 static struct hash_bucket *get_hash_bucket(struct dma_debug_entry *entry,
250                                            unsigned long *flags)
251         __acquires(&dma_entry_hash[idx].lock)
252 {
253         int idx = hash_fn(entry);
254         unsigned long __flags;
255
256         spin_lock_irqsave(&dma_entry_hash[idx].lock, __flags);
257         *flags = __flags;
258         return &dma_entry_hash[idx];
259 }
260
261 /*
262  * Give up exclusive access to the hash bucket
263  */
264 static void put_hash_bucket(struct hash_bucket *bucket,
265                             unsigned long flags)
266         __releases(&bucket->lock)
267 {
268         spin_unlock_irqrestore(&bucket->lock, flags);
269 }
270
271 static bool exact_match(struct dma_debug_entry *a, struct dma_debug_entry *b)
272 {
273         return ((a->dev_addr == b->dev_addr) &&
274                 (a->dev == b->dev)) ? true : false;
275 }
276
277 static bool containing_match(struct dma_debug_entry *a,
278                              struct dma_debug_entry *b)
279 {
280         if (a->dev != b->dev)
281                 return false;
282
283         if ((b->dev_addr <= a->dev_addr) &&
284             ((b->dev_addr + b->size) >= (a->dev_addr + a->size)))
285                 return true;
286
287         return false;
288 }
289
290 /*
291  * Search a given entry in the hash bucket list
292  */
293 static struct dma_debug_entry *__hash_bucket_find(struct hash_bucket *bucket,
294                                                   struct dma_debug_entry *ref,
295                                                   match_fn match)
296 {
297         struct dma_debug_entry *entry, *ret = NULL;
298         int matches = 0, match_lvl, last_lvl = -1;
299
300         list_for_each_entry(entry, &bucket->list, list) {
301                 if (!match(ref, entry))
302                         continue;
303
304                 /*
305                  * Some drivers map the same physical address multiple
306                  * times. Without a hardware IOMMU this results in the
307                  * same device addresses being put into the dma-debug
308                  * hash multiple times too. This can result in false
309                  * positives being reported. Therefore we implement a
310                  * best-fit algorithm here which returns the entry from
311                  * the hash which fits best to the reference value
312                  * instead of the first-fit.
313                  */
314                 matches += 1;
315                 match_lvl = 0;
316                 entry->size         == ref->size         ? ++match_lvl : 0;
317                 entry->type         == ref->type         ? ++match_lvl : 0;
318                 entry->direction    == ref->direction    ? ++match_lvl : 0;
319                 entry->sg_call_ents == ref->sg_call_ents ? ++match_lvl : 0;
320
321                 if (match_lvl == 4) {
322                         /* perfect-fit - return the result */
323                         return entry;
324                 } else if (match_lvl > last_lvl) {
325                         /*
326                          * We found an entry that fits better then the
327                          * previous one or it is the 1st match.
328                          */
329                         last_lvl = match_lvl;
330                         ret      = entry;
331                 }
332         }
333
334         /*
335          * If we have multiple matches but no perfect-fit, just return
336          * NULL.
337          */
338         ret = (matches == 1) ? ret : NULL;
339
340         return ret;
341 }
342
343 static struct dma_debug_entry *bucket_find_exact(struct hash_bucket *bucket,
344                                                  struct dma_debug_entry *ref)
345 {
346         return __hash_bucket_find(bucket, ref, exact_match);
347 }
348
349 static struct dma_debug_entry *bucket_find_contain(struct hash_bucket **bucket,
350                                                    struct dma_debug_entry *ref,
351                                                    unsigned long *flags)
352 {
353
354         unsigned int max_range = dma_get_max_seg_size(ref->dev);
355         struct dma_debug_entry *entry, index = *ref;
356         unsigned int range = 0;
357
358         while (range <= max_range) {
359                 entry = __hash_bucket_find(*bucket, ref, containing_match);
360
361                 if (entry)
362                         return entry;
363
364                 /*
365                  * Nothing found, go back a hash bucket
366                  */
367                 put_hash_bucket(*bucket, *flags);
368                 range          += (1 << HASH_FN_SHIFT);
369                 index.dev_addr -= (1 << HASH_FN_SHIFT);
370                 *bucket = get_hash_bucket(&index, flags);
371         }
372
373         return NULL;
374 }
375
376 /*
377  * Add an entry to a hash bucket
378  */
379 static void hash_bucket_add(struct hash_bucket *bucket,
380                             struct dma_debug_entry *entry)
381 {
382         list_add_tail(&entry->list, &bucket->list);
383 }
384
385 /*
386  * Remove entry from a hash bucket list
387  */
388 static void hash_bucket_del(struct dma_debug_entry *entry)
389 {
390         list_del(&entry->list);
391 }
392
393 static unsigned long long phys_addr(struct dma_debug_entry *entry)
394 {
395         if (entry->type == dma_debug_resource)
396                 return __pfn_to_phys(entry->pfn) + entry->offset;
397
398         return page_to_phys(pfn_to_page(entry->pfn)) + entry->offset;
399 }
400
401 /*
402  * Dump mapping entries for debugging purposes
403  */
404 void debug_dma_dump_mappings(struct device *dev)
405 {
406         int idx;
407
408         for (idx = 0; idx < HASH_SIZE; idx++) {
409                 struct hash_bucket *bucket = &dma_entry_hash[idx];
410                 struct dma_debug_entry *entry;
411                 unsigned long flags;
412
413                 spin_lock_irqsave(&bucket->lock, flags);
414
415                 list_for_each_entry(entry, &bucket->list, list) {
416                         if (!dev || dev == entry->dev) {
417                                 dev_info(entry->dev,
418                                          "%s idx %d P=%Lx N=%lx D=%Lx L=%Lx %s %s\n",
419                                          type2name[entry->type], idx,
420                                          phys_addr(entry), entry->pfn,
421                                          entry->dev_addr, entry->size,
422                                          dir2name[entry->direction],
423                                          maperr2str[entry->map_err_type]);
424                         }
425                 }
426
427                 spin_unlock_irqrestore(&bucket->lock, flags);
428                 cond_resched();
429         }
430 }
431
432 /*
433  * For each mapping (initial cacheline in the case of
434  * dma_alloc_coherent/dma_map_page, initial cacheline in each page of a
435  * scatterlist, or the cacheline specified in dma_map_single) insert
436  * into this tree using the cacheline as the key. At
437  * dma_unmap_{single|sg|page} or dma_free_coherent delete the entry.  If
438  * the entry already exists at insertion time add a tag as a reference
439  * count for the overlapping mappings.  For now, the overlap tracking
440  * just ensures that 'unmaps' balance 'maps' before marking the
441  * cacheline idle, but we should also be flagging overlaps as an API
442  * violation.
443  *
444  * Memory usage is mostly constrained by the maximum number of available
445  * dma-debug entries in that we need a free dma_debug_entry before
446  * inserting into the tree.  In the case of dma_map_page and
447  * dma_alloc_coherent there is only one dma_debug_entry and one
448  * dma_active_cacheline entry to track per event.  dma_map_sg(), on the
449  * other hand, consumes a single dma_debug_entry, but inserts 'nents'
450  * entries into the tree.
451  *
452  * At any time debug_dma_assert_idle() can be called to trigger a
453  * warning if any cachelines in the given page are in the active set.
454  */
455 static RADIX_TREE(dma_active_cacheline, GFP_NOWAIT);
456 static DEFINE_SPINLOCK(radix_lock);
457 #define ACTIVE_CACHELINE_MAX_OVERLAP ((1 << RADIX_TREE_MAX_TAGS) - 1)
458 #define CACHELINE_PER_PAGE_SHIFT (PAGE_SHIFT - L1_CACHE_SHIFT)
459 #define CACHELINES_PER_PAGE (1 << CACHELINE_PER_PAGE_SHIFT)
460
461 static phys_addr_t to_cacheline_number(struct dma_debug_entry *entry)
462 {
463         return (entry->pfn << CACHELINE_PER_PAGE_SHIFT) +
464                 (entry->offset >> L1_CACHE_SHIFT);
465 }
466
467 static int active_cacheline_read_overlap(phys_addr_t cln)
468 {
469         int overlap = 0, i;
470
471         for (i = RADIX_TREE_MAX_TAGS - 1; i >= 0; i--)
472                 if (radix_tree_tag_get(&dma_active_cacheline, cln, i))
473                         overlap |= 1 << i;
474         return overlap;
475 }
476
477 static int active_cacheline_set_overlap(phys_addr_t cln, int overlap)
478 {
479         int i;
480
481         if (overlap > ACTIVE_CACHELINE_MAX_OVERLAP || overlap < 0)
482                 return overlap;
483
484         for (i = RADIX_TREE_MAX_TAGS - 1; i >= 0; i--)
485                 if (overlap & 1 << i)
486                         radix_tree_tag_set(&dma_active_cacheline, cln, i);
487                 else
488                         radix_tree_tag_clear(&dma_active_cacheline, cln, i);
489
490         return overlap;
491 }
492
493 static void active_cacheline_inc_overlap(phys_addr_t cln)
494 {
495         int overlap = active_cacheline_read_overlap(cln);
496
497         overlap = active_cacheline_set_overlap(cln, ++overlap);
498
499         /* If we overflowed the overlap counter then we're potentially
500          * leaking dma-mappings.  Otherwise, if maps and unmaps are
501          * balanced then this overflow may cause false negatives in
502          * debug_dma_assert_idle() as the cacheline may be marked idle
503          * prematurely.
504          */
505         WARN_ONCE(overlap > ACTIVE_CACHELINE_MAX_OVERLAP,
506                   pr_fmt("exceeded %d overlapping mappings of cacheline %pa\n"),
507                   ACTIVE_CACHELINE_MAX_OVERLAP, &cln);
508 }
509
510 static int active_cacheline_dec_overlap(phys_addr_t cln)
511 {
512         int overlap = active_cacheline_read_overlap(cln);
513
514         return active_cacheline_set_overlap(cln, --overlap);
515 }
516
517 static int active_cacheline_insert(struct dma_debug_entry *entry)
518 {
519         phys_addr_t cln = to_cacheline_number(entry);
520         unsigned long flags;
521         int rc;
522
523         /* If the device is not writing memory then we don't have any
524          * concerns about the cpu consuming stale data.  This mitigates
525          * legitimate usages of overlapping mappings.
526          */
527         if (entry->direction == DMA_TO_DEVICE)
528                 return 0;
529
530         spin_lock_irqsave(&radix_lock, flags);
531         rc = radix_tree_insert(&dma_active_cacheline, cln, entry);
532         if (rc == -EEXIST)
533                 active_cacheline_inc_overlap(cln);
534         spin_unlock_irqrestore(&radix_lock, flags);
535
536         return rc;
537 }
538
539 static void active_cacheline_remove(struct dma_debug_entry *entry)
540 {
541         phys_addr_t cln = to_cacheline_number(entry);
542         unsigned long flags;
543
544         /* ...mirror the insert case */
545         if (entry->direction == DMA_TO_DEVICE)
546                 return;
547
548         spin_lock_irqsave(&radix_lock, flags);
549         /* since we are counting overlaps the final put of the
550          * cacheline will occur when the overlap count is 0.
551          * active_cacheline_dec_overlap() returns -1 in that case
552          */
553         if (active_cacheline_dec_overlap(cln) < 0)
554                 radix_tree_delete(&dma_active_cacheline, cln);
555         spin_unlock_irqrestore(&radix_lock, flags);
556 }
557
558 /**
559  * debug_dma_assert_idle() - assert that a page is not undergoing dma
560  * @page: page to lookup in the dma_active_cacheline tree
561  *
562  * Place a call to this routine in cases where the cpu touching the page
563  * before the dma completes (page is dma_unmapped) will lead to data
564  * corruption.
565  */
566 void debug_dma_assert_idle(struct page *page)
567 {
568         static struct dma_debug_entry *ents[CACHELINES_PER_PAGE];
569         struct dma_debug_entry *entry = NULL;
570         void **results = (void **) &ents;
571         unsigned int nents, i;
572         unsigned long flags;
573         phys_addr_t cln;
574
575         if (dma_debug_disabled())
576                 return;
577
578         if (!page)
579                 return;
580
581         cln = (phys_addr_t) page_to_pfn(page) << CACHELINE_PER_PAGE_SHIFT;
582         spin_lock_irqsave(&radix_lock, flags);
583         nents = radix_tree_gang_lookup(&dma_active_cacheline, results, cln,
584                                        CACHELINES_PER_PAGE);
585         for (i = 0; i < nents; i++) {
586                 phys_addr_t ent_cln = to_cacheline_number(ents[i]);
587
588                 if (ent_cln == cln) {
589                         entry = ents[i];
590                         break;
591                 } else if (ent_cln >= cln + CACHELINES_PER_PAGE)
592                         break;
593         }
594         spin_unlock_irqrestore(&radix_lock, flags);
595
596         if (!entry)
597                 return;
598
599         cln = to_cacheline_number(entry);
600         err_printk(entry->dev, entry,
601                    "cpu touching an active dma mapped cacheline [cln=%pa]\n",
602                    &cln);
603 }
604
605 /*
606  * Wrapper function for adding an entry to the hash.
607  * This function takes care of locking itself.
608  */
609 static void add_dma_entry(struct dma_debug_entry *entry)
610 {
611         struct hash_bucket *bucket;
612         unsigned long flags;
613         int rc;
614
615         bucket = get_hash_bucket(entry, &flags);
616         hash_bucket_add(bucket, entry);
617         put_hash_bucket(bucket, flags);
618
619         rc = active_cacheline_insert(entry);
620         if (rc == -ENOMEM) {
621                 pr_err("cacheline tracking ENOMEM, dma-debug disabled\n");
622                 global_disable = true;
623         }
624
625         /* TODO: report -EEXIST errors here as overlapping mappings are
626          * not supported by the DMA API
627          */
628 }
629
630 static int dma_debug_create_entries(gfp_t gfp)
631 {
632         struct dma_debug_entry *entry;
633         int i;
634
635         entry = (void *)get_zeroed_page(gfp);
636         if (!entry)
637                 return -ENOMEM;
638
639         for (i = 0; i < DMA_DEBUG_DYNAMIC_ENTRIES; i++)
640                 list_add_tail(&entry[i].list, &free_entries);
641
642         num_free_entries += DMA_DEBUG_DYNAMIC_ENTRIES;
643         nr_total_entries += DMA_DEBUG_DYNAMIC_ENTRIES;
644
645         return 0;
646 }
647
648 static struct dma_debug_entry *__dma_entry_alloc(void)
649 {
650         struct dma_debug_entry *entry;
651
652         entry = list_entry(free_entries.next, struct dma_debug_entry, list);
653         list_del(&entry->list);
654         memset(entry, 0, sizeof(*entry));
655
656         num_free_entries -= 1;
657         if (num_free_entries < min_free_entries)
658                 min_free_entries = num_free_entries;
659
660         return entry;
661 }
662
663 static void __dma_entry_alloc_check_leak(void)
664 {
665         u32 tmp = nr_total_entries % nr_prealloc_entries;
666
667         /* Shout each time we tick over some multiple of the initial pool */
668         if (tmp < DMA_DEBUG_DYNAMIC_ENTRIES) {
669                 pr_info("dma_debug_entry pool grown to %u (%u00%%)\n",
670                         nr_total_entries,
671                         (nr_total_entries / nr_prealloc_entries));
672         }
673 }
674
675 /* struct dma_entry allocator
676  *
677  * The next two functions implement the allocator for
678  * struct dma_debug_entries.
679  */
680 static struct dma_debug_entry *dma_entry_alloc(void)
681 {
682         struct dma_debug_entry *entry;
683         unsigned long flags;
684
685         spin_lock_irqsave(&free_entries_lock, flags);
686         if (num_free_entries == 0) {
687                 if (dma_debug_create_entries(GFP_ATOMIC)) {
688                         global_disable = true;
689                         spin_unlock_irqrestore(&free_entries_lock, flags);
690                         pr_err("debugging out of memory - disabling\n");
691                         return NULL;
692                 }
693                 __dma_entry_alloc_check_leak();
694         }
695
696         entry = __dma_entry_alloc();
697
698         spin_unlock_irqrestore(&free_entries_lock, flags);
699
700 #ifdef CONFIG_STACKTRACE
701         entry->stack_len = stack_trace_save(entry->stack_entries,
702                                             ARRAY_SIZE(entry->stack_entries),
703                                             1);
704 #endif
705         return entry;
706 }
707
708 static void dma_entry_free(struct dma_debug_entry *entry)
709 {
710         unsigned long flags;
711
712         active_cacheline_remove(entry);
713
714         /*
715          * add to beginning of the list - this way the entries are
716          * more likely cache hot when they are reallocated.
717          */
718         spin_lock_irqsave(&free_entries_lock, flags);
719         list_add(&entry->list, &free_entries);
720         num_free_entries += 1;
721         spin_unlock_irqrestore(&free_entries_lock, flags);
722 }
723
724 /*
725  * DMA-API debugging init code
726  *
727  * The init code does two things:
728  *   1. Initialize core data structures
729  *   2. Preallocate a given number of dma_debug_entry structs
730  */
731
732 static ssize_t filter_read(struct file *file, char __user *user_buf,
733                            size_t count, loff_t *ppos)
734 {
735         char buf[NAME_MAX_LEN + 1];
736         unsigned long flags;
737         int len;
738
739         if (!current_driver_name[0])
740                 return 0;
741
742         /*
743          * We can't copy to userspace directly because current_driver_name can
744          * only be read under the driver_name_lock with irqs disabled. So
745          * create a temporary copy first.
746          */
747         read_lock_irqsave(&driver_name_lock, flags);
748         len = scnprintf(buf, NAME_MAX_LEN + 1, "%s\n", current_driver_name);
749         read_unlock_irqrestore(&driver_name_lock, flags);
750
751         return simple_read_from_buffer(user_buf, count, ppos, buf, len);
752 }
753
754 static ssize_t filter_write(struct file *file, const char __user *userbuf,
755                             size_t count, loff_t *ppos)
756 {
757         char buf[NAME_MAX_LEN];
758         unsigned long flags;
759         size_t len;
760         int i;
761
762         /*
763          * We can't copy from userspace directly. Access to
764          * current_driver_name is protected with a write_lock with irqs
765          * disabled. Since copy_from_user can fault and may sleep we
766          * need to copy to temporary buffer first
767          */
768         len = min(count, (size_t)(NAME_MAX_LEN - 1));
769         if (copy_from_user(buf, userbuf, len))
770                 return -EFAULT;
771
772         buf[len] = 0;
773
774         write_lock_irqsave(&driver_name_lock, flags);
775
776         /*
777          * Now handle the string we got from userspace very carefully.
778          * The rules are:
779          *         - only use the first token we got
780          *         - token delimiter is everything looking like a space
781          *           character (' ', '\n', '\t' ...)
782          *
783          */
784         if (!isalnum(buf[0])) {
785                 /*
786                  * If the first character userspace gave us is not
787                  * alphanumerical then assume the filter should be
788                  * switched off.
789                  */
790                 if (current_driver_name[0])
791                         pr_info("switching off dma-debug driver filter\n");
792                 current_driver_name[0] = 0;
793                 current_driver = NULL;
794                 goto out_unlock;
795         }
796
797         /*
798          * Now parse out the first token and use it as the name for the
799          * driver to filter for.
800          */
801         for (i = 0; i < NAME_MAX_LEN - 1; ++i) {
802                 current_driver_name[i] = buf[i];
803                 if (isspace(buf[i]) || buf[i] == ' ' || buf[i] == 0)
804                         break;
805         }
806         current_driver_name[i] = 0;
807         current_driver = NULL;
808
809         pr_info("enable driver filter for driver [%s]\n",
810                 current_driver_name);
811
812 out_unlock:
813         write_unlock_irqrestore(&driver_name_lock, flags);
814
815         return count;
816 }
817
818 static const struct file_operations filter_fops = {
819         .read  = filter_read,
820         .write = filter_write,
821         .llseek = default_llseek,
822 };
823
824 static int dump_show(struct seq_file *seq, void *v)
825 {
826         int idx;
827
828         for (idx = 0; idx < HASH_SIZE; idx++) {
829                 struct hash_bucket *bucket = &dma_entry_hash[idx];
830                 struct dma_debug_entry *entry;
831                 unsigned long flags;
832
833                 spin_lock_irqsave(&bucket->lock, flags);
834                 list_for_each_entry(entry, &bucket->list, list) {
835                         seq_printf(seq,
836                                    "%s %s %s idx %d P=%llx N=%lx D=%llx L=%llx %s %s\n",
837                                    dev_name(entry->dev),
838                                    dev_driver_string(entry->dev),
839                                    type2name[entry->type], idx,
840                                    phys_addr(entry), entry->pfn,
841                                    entry->dev_addr, entry->size,
842                                    dir2name[entry->direction],
843                                    maperr2str[entry->map_err_type]);
844                 }
845                 spin_unlock_irqrestore(&bucket->lock, flags);
846         }
847         return 0;
848 }
849 DEFINE_SHOW_ATTRIBUTE(dump);
850
851 static void dma_debug_fs_init(void)
852 {
853         struct dentry *dentry = debugfs_create_dir("dma-api", NULL);
854
855         debugfs_create_bool("disabled", 0444, dentry, &global_disable);
856         debugfs_create_u32("error_count", 0444, dentry, &error_count);
857         debugfs_create_u32("all_errors", 0644, dentry, &show_all_errors);
858         debugfs_create_u32("num_errors", 0644, dentry, &show_num_errors);
859         debugfs_create_u32("num_free_entries", 0444, dentry, &num_free_entries);
860         debugfs_create_u32("min_free_entries", 0444, dentry, &min_free_entries);
861         debugfs_create_u32("nr_total_entries", 0444, dentry, &nr_total_entries);
862         debugfs_create_file("driver_filter", 0644, dentry, NULL, &filter_fops);
863         debugfs_create_file("dump", 0444, dentry, NULL, &dump_fops);
864 }
865
866 static int device_dma_allocations(struct device *dev, struct dma_debug_entry **out_entry)
867 {
868         struct dma_debug_entry *entry;
869         unsigned long flags;
870         int count = 0, i;
871
872         for (i = 0; i < HASH_SIZE; ++i) {
873                 spin_lock_irqsave(&dma_entry_hash[i].lock, flags);
874                 list_for_each_entry(entry, &dma_entry_hash[i].list, list) {
875                         if (entry->dev == dev) {
876                                 count += 1;
877                                 *out_entry = entry;
878                         }
879                 }
880                 spin_unlock_irqrestore(&dma_entry_hash[i].lock, flags);
881         }
882
883         return count;
884 }
885
886 static int dma_debug_device_change(struct notifier_block *nb, unsigned long action, void *data)
887 {
888         struct device *dev = data;
889         struct dma_debug_entry *entry;
890         int count;
891
892         if (dma_debug_disabled())
893                 return 0;
894
895         switch (action) {
896         case BUS_NOTIFY_UNBOUND_DRIVER:
897                 count = device_dma_allocations(dev, &entry);
898                 if (count == 0)
899                         break;
900                 err_printk(dev, entry, "device driver has pending "
901                                 "DMA allocations while released from device "
902                                 "[count=%d]\n"
903                                 "One of leaked entries details: "
904                                 "[device address=0x%016llx] [size=%llu bytes] "
905                                 "[mapped with %s] [mapped as %s]\n",
906                         count, entry->dev_addr, entry->size,
907                         dir2name[entry->direction], type2name[entry->type]);
908                 break;
909         default:
910                 break;
911         }
912
913         return 0;
914 }
915
916 void dma_debug_add_bus(struct bus_type *bus)
917 {
918         struct notifier_block *nb;
919
920         if (dma_debug_disabled())
921                 return;
922
923         nb = kzalloc(sizeof(struct notifier_block), GFP_KERNEL);
924         if (nb == NULL) {
925                 pr_err("dma_debug_add_bus: out of memory\n");
926                 return;
927         }
928
929         nb->notifier_call = dma_debug_device_change;
930
931         bus_register_notifier(bus, nb);
932 }
933
934 static int dma_debug_init(void)
935 {
936         int i, nr_pages;
937
938         /* Do not use dma_debug_initialized here, since we really want to be
939          * called to set dma_debug_initialized
940          */
941         if (global_disable)
942                 return 0;
943
944         for (i = 0; i < HASH_SIZE; ++i) {
945                 INIT_LIST_HEAD(&dma_entry_hash[i].list);
946                 spin_lock_init(&dma_entry_hash[i].lock);
947         }
948
949         dma_debug_fs_init();
950
951         nr_pages = DIV_ROUND_UP(nr_prealloc_entries, DMA_DEBUG_DYNAMIC_ENTRIES);
952         for (i = 0; i < nr_pages; ++i)
953                 dma_debug_create_entries(GFP_KERNEL);
954         if (num_free_entries >= nr_prealloc_entries) {
955                 pr_info("preallocated %d debug entries\n", nr_total_entries);
956         } else if (num_free_entries > 0) {
957                 pr_warn("%d debug entries requested but only %d allocated\n",
958                         nr_prealloc_entries, nr_total_entries);
959         } else {
960                 pr_err("debugging out of memory error - disabled\n");
961                 global_disable = true;
962
963                 return 0;
964         }
965         min_free_entries = num_free_entries;
966
967         dma_debug_initialized = true;
968
969         pr_info("debugging enabled by kernel config\n");
970         return 0;
971 }
972 core_initcall(dma_debug_init);
973
974 static __init int dma_debug_cmdline(char *str)
975 {
976         if (!str)
977                 return -EINVAL;
978
979         if (strncmp(str, "off", 3) == 0) {
980                 pr_info("debugging disabled on kernel command line\n");
981                 global_disable = true;
982         }
983
984         return 0;
985 }
986
987 static __init int dma_debug_entries_cmdline(char *str)
988 {
989         if (!str)
990                 return -EINVAL;
991         if (!get_option(&str, &nr_prealloc_entries))
992                 nr_prealloc_entries = PREALLOC_DMA_DEBUG_ENTRIES;
993         return 0;
994 }
995
996 __setup("dma_debug=", dma_debug_cmdline);
997 __setup("dma_debug_entries=", dma_debug_entries_cmdline);
998
999 static void check_unmap(struct dma_debug_entry *ref)
1000 {
1001         struct dma_debug_entry *entry;
1002         struct hash_bucket *bucket;
1003         unsigned long flags;
1004
1005         bucket = get_hash_bucket(ref, &flags);
1006         entry = bucket_find_exact(bucket, ref);
1007
1008         if (!entry) {
1009                 /* must drop lock before calling dma_mapping_error */
1010                 put_hash_bucket(bucket, flags);
1011
1012                 if (dma_mapping_error(ref->dev, ref->dev_addr)) {
1013                         err_printk(ref->dev, NULL,
1014                                    "device driver tries to free an "
1015                                    "invalid DMA memory address\n");
1016                 } else {
1017                         err_printk(ref->dev, NULL,
1018                                    "device driver tries to free DMA "
1019                                    "memory it has not allocated [device "
1020                                    "address=0x%016llx] [size=%llu bytes]\n",
1021                                    ref->dev_addr, ref->size);
1022                 }
1023                 return;
1024         }
1025
1026         if (ref->size != entry->size) {
1027                 err_printk(ref->dev, entry, "device driver frees "
1028                            "DMA memory with different size "
1029                            "[device address=0x%016llx] [map size=%llu bytes] "
1030                            "[unmap size=%llu bytes]\n",
1031                            ref->dev_addr, entry->size, ref->size);
1032         }
1033
1034         if (ref->type != entry->type) {
1035                 err_printk(ref->dev, entry, "device driver frees "
1036                            "DMA memory with wrong function "
1037                            "[device address=0x%016llx] [size=%llu bytes] "
1038                            "[mapped as %s] [unmapped as %s]\n",
1039                            ref->dev_addr, ref->size,
1040                            type2name[entry->type], type2name[ref->type]);
1041         } else if ((entry->type == dma_debug_coherent) &&
1042                    (phys_addr(ref) != phys_addr(entry))) {
1043                 err_printk(ref->dev, entry, "device driver frees "
1044                            "DMA memory with different CPU address "
1045                            "[device address=0x%016llx] [size=%llu bytes] "
1046                            "[cpu alloc address=0x%016llx] "
1047                            "[cpu free address=0x%016llx]",
1048                            ref->dev_addr, ref->size,
1049                            phys_addr(entry),
1050                            phys_addr(ref));
1051         }
1052
1053         if (ref->sg_call_ents && ref->type == dma_debug_sg &&
1054             ref->sg_call_ents != entry->sg_call_ents) {
1055                 err_printk(ref->dev, entry, "device driver frees "
1056                            "DMA sg list with different entry count "
1057                            "[map count=%d] [unmap count=%d]\n",
1058                            entry->sg_call_ents, ref->sg_call_ents);
1059         }
1060
1061         /*
1062          * This may be no bug in reality - but most implementations of the
1063          * DMA API don't handle this properly, so check for it here
1064          */
1065         if (ref->direction != entry->direction) {
1066                 err_printk(ref->dev, entry, "device driver frees "
1067                            "DMA memory with different direction "
1068                            "[device address=0x%016llx] [size=%llu bytes] "
1069                            "[mapped with %s] [unmapped with %s]\n",
1070                            ref->dev_addr, ref->size,
1071                            dir2name[entry->direction],
1072                            dir2name[ref->direction]);
1073         }
1074
1075         /*
1076          * Drivers should use dma_mapping_error() to check the returned
1077          * addresses of dma_map_single() and dma_map_page().
1078          * If not, print this warning message. See Documentation/core-api/dma-api.rst.
1079          */
1080         if (entry->map_err_type == MAP_ERR_NOT_CHECKED) {
1081                 err_printk(ref->dev, entry,
1082                            "device driver failed to check map error"
1083                            "[device address=0x%016llx] [size=%llu bytes] "
1084                            "[mapped as %s]",
1085                            ref->dev_addr, ref->size,
1086                            type2name[entry->type]);
1087         }
1088
1089         hash_bucket_del(entry);
1090         dma_entry_free(entry);
1091
1092         put_hash_bucket(bucket, flags);
1093 }
1094
1095 static void check_for_stack(struct device *dev,
1096                             struct page *page, size_t offset)
1097 {
1098         void *addr;
1099         struct vm_struct *stack_vm_area = task_stack_vm_area(current);
1100
1101         if (!stack_vm_area) {
1102                 /* Stack is direct-mapped. */
1103                 if (PageHighMem(page))
1104                         return;
1105                 addr = page_address(page) + offset;
1106                 if (object_is_on_stack(addr))
1107                         err_printk(dev, NULL, "device driver maps memory from stack [addr=%p]\n", addr);
1108         } else {
1109                 /* Stack is vmalloced. */
1110                 int i;
1111
1112                 for (i = 0; i < stack_vm_area->nr_pages; i++) {
1113                         if (page != stack_vm_area->pages[i])
1114                                 continue;
1115
1116                         addr = (u8 *)current->stack + i * PAGE_SIZE + offset;
1117                         err_printk(dev, NULL, "device driver maps memory from stack [probable addr=%p]\n", addr);
1118                         break;
1119                 }
1120         }
1121 }
1122
1123 static inline bool overlap(void *addr, unsigned long len, void *start, void *end)
1124 {
1125         unsigned long a1 = (unsigned long)addr;
1126         unsigned long b1 = a1 + len;
1127         unsigned long a2 = (unsigned long)start;
1128         unsigned long b2 = (unsigned long)end;
1129
1130         return !(b1 <= a2 || a1 >= b2);
1131 }
1132
1133 static void check_for_illegal_area(struct device *dev, void *addr, unsigned long len)
1134 {
1135         if (overlap(addr, len, _stext, _etext) ||
1136             overlap(addr, len, __start_rodata, __end_rodata))
1137                 err_printk(dev, NULL, "device driver maps memory from kernel text or rodata [addr=%p] [len=%lu]\n", addr, len);
1138 }
1139
1140 static void check_sync(struct device *dev,
1141                        struct dma_debug_entry *ref,
1142                        bool to_cpu)
1143 {
1144         struct dma_debug_entry *entry;
1145         struct hash_bucket *bucket;
1146         unsigned long flags;
1147
1148         bucket = get_hash_bucket(ref, &flags);
1149
1150         entry = bucket_find_contain(&bucket, ref, &flags);
1151
1152         if (!entry) {
1153                 err_printk(dev, NULL, "device driver tries "
1154                                 "to sync DMA memory it has not allocated "
1155                                 "[device address=0x%016llx] [size=%llu bytes]\n",
1156                                 (unsigned long long)ref->dev_addr, ref->size);
1157                 goto out;
1158         }
1159
1160         if (ref->size > entry->size) {
1161                 err_printk(dev, entry, "device driver syncs"
1162                                 " DMA memory outside allocated range "
1163                                 "[device address=0x%016llx] "
1164                                 "[allocation size=%llu bytes] "
1165                                 "[sync offset+size=%llu]\n",
1166                                 entry->dev_addr, entry->size,
1167                                 ref->size);
1168         }
1169
1170         if (entry->direction == DMA_BIDIRECTIONAL)
1171                 goto out;
1172
1173         if (ref->direction != entry->direction) {
1174                 err_printk(dev, entry, "device driver syncs "
1175                                 "DMA memory with different direction "
1176                                 "[device address=0x%016llx] [size=%llu bytes] "
1177                                 "[mapped with %s] [synced with %s]\n",
1178                                 (unsigned long long)ref->dev_addr, entry->size,
1179                                 dir2name[entry->direction],
1180                                 dir2name[ref->direction]);
1181         }
1182
1183         if (to_cpu && !(entry->direction == DMA_FROM_DEVICE) &&
1184                       !(ref->direction == DMA_TO_DEVICE))
1185                 err_printk(dev, entry, "device driver syncs "
1186                                 "device read-only DMA memory for cpu "
1187                                 "[device address=0x%016llx] [size=%llu bytes] "
1188                                 "[mapped with %s] [synced with %s]\n",
1189                                 (unsigned long long)ref->dev_addr, entry->size,
1190                                 dir2name[entry->direction],
1191                                 dir2name[ref->direction]);
1192
1193         if (!to_cpu && !(entry->direction == DMA_TO_DEVICE) &&
1194                        !(ref->direction == DMA_FROM_DEVICE))
1195                 err_printk(dev, entry, "device driver syncs "
1196                                 "device write-only DMA memory to device "
1197                                 "[device address=0x%016llx] [size=%llu bytes] "
1198                                 "[mapped with %s] [synced with %s]\n",
1199                                 (unsigned long long)ref->dev_addr, entry->size,
1200                                 dir2name[entry->direction],
1201                                 dir2name[ref->direction]);
1202
1203         if (ref->sg_call_ents && ref->type == dma_debug_sg &&
1204             ref->sg_call_ents != entry->sg_call_ents) {
1205                 err_printk(ref->dev, entry, "device driver syncs "
1206                            "DMA sg list with different entry count "
1207                            "[map count=%d] [sync count=%d]\n",
1208                            entry->sg_call_ents, ref->sg_call_ents);
1209         }
1210
1211 out:
1212         put_hash_bucket(bucket, flags);
1213 }
1214
1215 static void check_sg_segment(struct device *dev, struct scatterlist *sg)
1216 {
1217 #ifdef CONFIG_DMA_API_DEBUG_SG
1218         unsigned int max_seg = dma_get_max_seg_size(dev);
1219         u64 start, end, boundary = dma_get_seg_boundary(dev);
1220
1221         /*
1222          * Either the driver forgot to set dma_parms appropriately, or
1223          * whoever generated the list forgot to check them.
1224          */
1225         if (sg->length > max_seg)
1226                 err_printk(dev, NULL, "mapping sg segment longer than device claims to support [len=%u] [max=%u]\n",
1227                            sg->length, max_seg);
1228         /*
1229          * In some cases this could potentially be the DMA API
1230          * implementation's fault, but it would usually imply that
1231          * the scatterlist was built inappropriately to begin with.
1232          */
1233         start = sg_dma_address(sg);
1234         end = start + sg_dma_len(sg) - 1;
1235         if ((start ^ end) & ~boundary)
1236                 err_printk(dev, NULL, "mapping sg segment across boundary [start=0x%016llx] [end=0x%016llx] [boundary=0x%016llx]\n",
1237                            start, end, boundary);
1238 #endif
1239 }
1240
1241 void debug_dma_map_single(struct device *dev, const void *addr,
1242                             unsigned long len)
1243 {
1244         if (unlikely(dma_debug_disabled()))
1245                 return;
1246
1247         if (!virt_addr_valid(addr))
1248                 err_printk(dev, NULL, "device driver maps memory from invalid area [addr=%p] [len=%lu]\n",
1249                            addr, len);
1250
1251         if (is_vmalloc_addr(addr))
1252                 err_printk(dev, NULL, "device driver maps memory from vmalloc area [addr=%p] [len=%lu]\n",
1253                            addr, len);
1254 }
1255 EXPORT_SYMBOL(debug_dma_map_single);
1256
1257 void debug_dma_map_page(struct device *dev, struct page *page, size_t offset,
1258                         size_t size, int direction, dma_addr_t dma_addr)
1259 {
1260         struct dma_debug_entry *entry;
1261
1262         if (unlikely(dma_debug_disabled()))
1263                 return;
1264
1265         if (dma_mapping_error(dev, dma_addr))
1266                 return;
1267
1268         entry = dma_entry_alloc();
1269         if (!entry)
1270                 return;
1271
1272         entry->dev       = dev;
1273         entry->type      = dma_debug_single;
1274         entry->pfn       = page_to_pfn(page);
1275         entry->offset    = offset,
1276         entry->dev_addr  = dma_addr;
1277         entry->size      = size;
1278         entry->direction = direction;
1279         entry->map_err_type = MAP_ERR_NOT_CHECKED;
1280
1281         check_for_stack(dev, page, offset);
1282
1283         if (!PageHighMem(page)) {
1284                 void *addr = page_address(page) + offset;
1285
1286                 check_for_illegal_area(dev, addr, size);
1287         }
1288
1289         add_dma_entry(entry);
1290 }
1291 EXPORT_SYMBOL(debug_dma_map_page);
1292
1293 void debug_dma_mapping_error(struct device *dev, dma_addr_t dma_addr)
1294 {
1295         struct dma_debug_entry ref;
1296         struct dma_debug_entry *entry;
1297         struct hash_bucket *bucket;
1298         unsigned long flags;
1299
1300         if (unlikely(dma_debug_disabled()))
1301                 return;
1302
1303         ref.dev = dev;
1304         ref.dev_addr = dma_addr;
1305         bucket = get_hash_bucket(&ref, &flags);
1306
1307         list_for_each_entry(entry, &bucket->list, list) {
1308                 if (!exact_match(&ref, entry))
1309                         continue;
1310
1311                 /*
1312                  * The same physical address can be mapped multiple
1313                  * times. Without a hardware IOMMU this results in the
1314                  * same device addresses being put into the dma-debug
1315                  * hash multiple times too. This can result in false
1316                  * positives being reported. Therefore we implement a
1317                  * best-fit algorithm here which updates the first entry
1318                  * from the hash which fits the reference value and is
1319                  * not currently listed as being checked.
1320                  */
1321                 if (entry->map_err_type == MAP_ERR_NOT_CHECKED) {
1322                         entry->map_err_type = MAP_ERR_CHECKED;
1323                         break;
1324                 }
1325         }
1326
1327         put_hash_bucket(bucket, flags);
1328 }
1329 EXPORT_SYMBOL(debug_dma_mapping_error);
1330
1331 void debug_dma_unmap_page(struct device *dev, dma_addr_t addr,
1332                           size_t size, int direction)
1333 {
1334         struct dma_debug_entry ref = {
1335                 .type           = dma_debug_single,
1336                 .dev            = dev,
1337                 .dev_addr       = addr,
1338                 .size           = size,
1339                 .direction      = direction,
1340         };
1341
1342         if (unlikely(dma_debug_disabled()))
1343                 return;
1344         check_unmap(&ref);
1345 }
1346 EXPORT_SYMBOL(debug_dma_unmap_page);
1347
1348 void debug_dma_map_sg(struct device *dev, struct scatterlist *sg,
1349                       int nents, int mapped_ents, int direction)
1350 {
1351         struct dma_debug_entry *entry;
1352         struct scatterlist *s;
1353         int i;
1354
1355         if (unlikely(dma_debug_disabled()))
1356                 return;
1357
1358         for_each_sg(sg, s, mapped_ents, i) {
1359                 entry = dma_entry_alloc();
1360                 if (!entry)
1361                         return;
1362
1363                 entry->type           = dma_debug_sg;
1364                 entry->dev            = dev;
1365                 entry->pfn            = page_to_pfn(sg_page(s));
1366                 entry->offset         = s->offset,
1367                 entry->size           = sg_dma_len(s);
1368                 entry->dev_addr       = sg_dma_address(s);
1369                 entry->direction      = direction;
1370                 entry->sg_call_ents   = nents;
1371                 entry->sg_mapped_ents = mapped_ents;
1372
1373                 check_for_stack(dev, sg_page(s), s->offset);
1374
1375                 if (!PageHighMem(sg_page(s))) {
1376                         check_for_illegal_area(dev, sg_virt(s), sg_dma_len(s));
1377                 }
1378
1379                 check_sg_segment(dev, s);
1380
1381                 add_dma_entry(entry);
1382         }
1383 }
1384 EXPORT_SYMBOL(debug_dma_map_sg);
1385
1386 static int get_nr_mapped_entries(struct device *dev,
1387                                  struct dma_debug_entry *ref)
1388 {
1389         struct dma_debug_entry *entry;
1390         struct hash_bucket *bucket;
1391         unsigned long flags;
1392         int mapped_ents;
1393
1394         bucket       = get_hash_bucket(ref, &flags);
1395         entry        = bucket_find_exact(bucket, ref);
1396         mapped_ents  = 0;
1397
1398         if (entry)
1399                 mapped_ents = entry->sg_mapped_ents;
1400         put_hash_bucket(bucket, flags);
1401
1402         return mapped_ents;
1403 }
1404
1405 void debug_dma_unmap_sg(struct device *dev, struct scatterlist *sglist,
1406                         int nelems, int dir)
1407 {
1408         struct scatterlist *s;
1409         int mapped_ents = 0, i;
1410
1411         if (unlikely(dma_debug_disabled()))
1412                 return;
1413
1414         for_each_sg(sglist, s, nelems, i) {
1415
1416                 struct dma_debug_entry ref = {
1417                         .type           = dma_debug_sg,
1418                         .dev            = dev,
1419                         .pfn            = page_to_pfn(sg_page(s)),
1420                         .offset         = s->offset,
1421                         .dev_addr       = sg_dma_address(s),
1422                         .size           = sg_dma_len(s),
1423                         .direction      = dir,
1424                         .sg_call_ents   = nelems,
1425                 };
1426
1427                 if (mapped_ents && i >= mapped_ents)
1428                         break;
1429
1430                 if (!i)
1431                         mapped_ents = get_nr_mapped_entries(dev, &ref);
1432
1433                 check_unmap(&ref);
1434         }
1435 }
1436 EXPORT_SYMBOL(debug_dma_unmap_sg);
1437
1438 void debug_dma_alloc_coherent(struct device *dev, size_t size,
1439                               dma_addr_t dma_addr, void *virt)
1440 {
1441         struct dma_debug_entry *entry;
1442
1443         if (unlikely(dma_debug_disabled()))
1444                 return;
1445
1446         if (unlikely(virt == NULL))
1447                 return;
1448
1449         /* handle vmalloc and linear addresses */
1450         if (!is_vmalloc_addr(virt) && !virt_addr_valid(virt))
1451                 return;
1452
1453         entry = dma_entry_alloc();
1454         if (!entry)
1455                 return;
1456
1457         entry->type      = dma_debug_coherent;
1458         entry->dev       = dev;
1459         entry->offset    = offset_in_page(virt);
1460         entry->size      = size;
1461         entry->dev_addr  = dma_addr;
1462         entry->direction = DMA_BIDIRECTIONAL;
1463
1464         if (is_vmalloc_addr(virt))
1465                 entry->pfn = vmalloc_to_pfn(virt);
1466         else
1467                 entry->pfn = page_to_pfn(virt_to_page(virt));
1468
1469         add_dma_entry(entry);
1470 }
1471
1472 void debug_dma_free_coherent(struct device *dev, size_t size,
1473                          void *virt, dma_addr_t addr)
1474 {
1475         struct dma_debug_entry ref = {
1476                 .type           = dma_debug_coherent,
1477                 .dev            = dev,
1478                 .offset         = offset_in_page(virt),
1479                 .dev_addr       = addr,
1480                 .size           = size,
1481                 .direction      = DMA_BIDIRECTIONAL,
1482         };
1483
1484         /* handle vmalloc and linear addresses */
1485         if (!is_vmalloc_addr(virt) && !virt_addr_valid(virt))
1486                 return;
1487
1488         if (is_vmalloc_addr(virt))
1489                 ref.pfn = vmalloc_to_pfn(virt);
1490         else
1491                 ref.pfn = page_to_pfn(virt_to_page(virt));
1492
1493         if (unlikely(dma_debug_disabled()))
1494                 return;
1495
1496         check_unmap(&ref);
1497 }
1498
1499 void debug_dma_map_resource(struct device *dev, phys_addr_t addr, size_t size,
1500                             int direction, dma_addr_t dma_addr)
1501 {
1502         struct dma_debug_entry *entry;
1503
1504         if (unlikely(dma_debug_disabled()))
1505                 return;
1506
1507         entry = dma_entry_alloc();
1508         if (!entry)
1509                 return;
1510
1511         entry->type             = dma_debug_resource;
1512         entry->dev              = dev;
1513         entry->pfn              = PHYS_PFN(addr);
1514         entry->offset           = offset_in_page(addr);
1515         entry->size             = size;
1516         entry->dev_addr         = dma_addr;
1517         entry->direction        = direction;
1518         entry->map_err_type     = MAP_ERR_NOT_CHECKED;
1519
1520         add_dma_entry(entry);
1521 }
1522 EXPORT_SYMBOL(debug_dma_map_resource);
1523
1524 void debug_dma_unmap_resource(struct device *dev, dma_addr_t dma_addr,
1525                               size_t size, int direction)
1526 {
1527         struct dma_debug_entry ref = {
1528                 .type           = dma_debug_resource,
1529                 .dev            = dev,
1530                 .dev_addr       = dma_addr,
1531                 .size           = size,
1532                 .direction      = direction,
1533         };
1534
1535         if (unlikely(dma_debug_disabled()))
1536                 return;
1537
1538         check_unmap(&ref);
1539 }
1540 EXPORT_SYMBOL(debug_dma_unmap_resource);
1541
1542 void debug_dma_sync_single_for_cpu(struct device *dev, dma_addr_t dma_handle,
1543                                    size_t size, int direction)
1544 {
1545         struct dma_debug_entry ref;
1546
1547         if (unlikely(dma_debug_disabled()))
1548                 return;
1549
1550         ref.type         = dma_debug_single;
1551         ref.dev          = dev;
1552         ref.dev_addr     = dma_handle;
1553         ref.size         = size;
1554         ref.direction    = direction;
1555         ref.sg_call_ents = 0;
1556
1557         check_sync(dev, &ref, true);
1558 }
1559 EXPORT_SYMBOL(debug_dma_sync_single_for_cpu);
1560
1561 void debug_dma_sync_single_for_device(struct device *dev,
1562                                       dma_addr_t dma_handle, size_t size,
1563                                       int direction)
1564 {
1565         struct dma_debug_entry ref;
1566
1567         if (unlikely(dma_debug_disabled()))
1568                 return;
1569
1570         ref.type         = dma_debug_single;
1571         ref.dev          = dev;
1572         ref.dev_addr     = dma_handle;
1573         ref.size         = size;
1574         ref.direction    = direction;
1575         ref.sg_call_ents = 0;
1576
1577         check_sync(dev, &ref, false);
1578 }
1579 EXPORT_SYMBOL(debug_dma_sync_single_for_device);
1580
1581 void debug_dma_sync_sg_for_cpu(struct device *dev, struct scatterlist *sg,
1582                                int nelems, int direction)
1583 {
1584         struct scatterlist *s;
1585         int mapped_ents = 0, i;
1586
1587         if (unlikely(dma_debug_disabled()))
1588                 return;
1589
1590         for_each_sg(sg, s, nelems, i) {
1591
1592                 struct dma_debug_entry ref = {
1593                         .type           = dma_debug_sg,
1594                         .dev            = dev,
1595                         .pfn            = page_to_pfn(sg_page(s)),
1596                         .offset         = s->offset,
1597                         .dev_addr       = sg_dma_address(s),
1598                         .size           = sg_dma_len(s),
1599                         .direction      = direction,
1600                         .sg_call_ents   = nelems,
1601                 };
1602
1603                 if (!i)
1604                         mapped_ents = get_nr_mapped_entries(dev, &ref);
1605
1606                 if (i >= mapped_ents)
1607                         break;
1608
1609                 check_sync(dev, &ref, true);
1610         }
1611 }
1612 EXPORT_SYMBOL(debug_dma_sync_sg_for_cpu);
1613
1614 void debug_dma_sync_sg_for_device(struct device *dev, struct scatterlist *sg,
1615                                   int nelems, int direction)
1616 {
1617         struct scatterlist *s;
1618         int mapped_ents = 0, i;
1619
1620         if (unlikely(dma_debug_disabled()))
1621                 return;
1622
1623         for_each_sg(sg, s, nelems, i) {
1624
1625                 struct dma_debug_entry ref = {
1626                         .type           = dma_debug_sg,
1627                         .dev            = dev,
1628                         .pfn            = page_to_pfn(sg_page(s)),
1629                         .offset         = s->offset,
1630                         .dev_addr       = sg_dma_address(s),
1631                         .size           = sg_dma_len(s),
1632                         .direction      = direction,
1633                         .sg_call_ents   = nelems,
1634                 };
1635                 if (!i)
1636                         mapped_ents = get_nr_mapped_entries(dev, &ref);
1637
1638                 if (i >= mapped_ents)
1639                         break;
1640
1641                 check_sync(dev, &ref, false);
1642         }
1643 }
1644 EXPORT_SYMBOL(debug_dma_sync_sg_for_device);
1645
1646 static int __init dma_debug_driver_setup(char *str)
1647 {
1648         int i;
1649
1650         for (i = 0; i < NAME_MAX_LEN - 1; ++i, ++str) {
1651                 current_driver_name[i] = *str;
1652                 if (*str == 0)
1653                         break;
1654         }
1655
1656         if (current_driver_name[0])
1657                 pr_info("enable driver filter for driver [%s]\n",
1658                         current_driver_name);
1659
1660
1661         return 1;
1662 }
1663 __setup("dma_debug_driver=", dma_debug_driver_setup);