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