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