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 struct dma_debug_entry *entry, index = *ref;
354 int limit = min(HASH_SIZE, (index.dev_addr >> HASH_FN_SHIFT) + 1);
355
356 for (int i = 0; i < limit; i++) {
357 entry = __hash_bucket_find(*bucket, ref, containing_match);
358
359 if (entry)
360 return entry;
361
362 /*
363 * Nothing found, go back a hash bucket
364 */
365 put_hash_bucket(*bucket, *flags);
366 index.dev_addr -= (1 << HASH_FN_SHIFT);
367 *bucket = get_hash_bucket(&index, flags);
368 }
369
370 return NULL;
371 }
372
373 /*
374 * Add an entry to a hash bucket
375 */
hash_bucket_add(struct hash_bucket * bucket,struct dma_debug_entry * entry)376 static void hash_bucket_add(struct hash_bucket *bucket,
377 struct dma_debug_entry *entry)
378 {
379 list_add_tail(&entry->list, &bucket->list);
380 }
381
382 /*
383 * Remove entry from a hash bucket list
384 */
hash_bucket_del(struct dma_debug_entry * entry)385 static void hash_bucket_del(struct dma_debug_entry *entry)
386 {
387 list_del(&entry->list);
388 }
389
phys_addr(struct dma_debug_entry * entry)390 static unsigned long long phys_addr(struct dma_debug_entry *entry)
391 {
392 if (entry->type == dma_debug_resource)
393 return __pfn_to_phys(entry->pfn) + entry->offset;
394
395 return page_to_phys(pfn_to_page(entry->pfn)) + entry->offset;
396 }
397
398 /*
399 * Dump mapping entries for debugging purposes
400 */
debug_dma_dump_mappings(struct device * dev)401 void debug_dma_dump_mappings(struct device *dev)
402 {
403 int idx;
404
405 for (idx = 0; idx < HASH_SIZE; idx++) {
406 struct hash_bucket *bucket = &dma_entry_hash[idx];
407 struct dma_debug_entry *entry;
408 unsigned long flags;
409
410 spin_lock_irqsave(&bucket->lock, flags);
411
412 list_for_each_entry(entry, &bucket->list, list) {
413 if (!dev || dev == entry->dev) {
414 dev_info(entry->dev,
415 "%s idx %d P=%Lx N=%lx D=%Lx L=%Lx %s %s\n",
416 type2name[entry->type], idx,
417 phys_addr(entry), entry->pfn,
418 entry->dev_addr, entry->size,
419 dir2name[entry->direction],
420 maperr2str[entry->map_err_type]);
421 }
422 }
423
424 spin_unlock_irqrestore(&bucket->lock, flags);
425 cond_resched();
426 }
427 }
428
429 /*
430 * For each mapping (initial cacheline in the case of
431 * dma_alloc_coherent/dma_map_page, initial cacheline in each page of a
432 * scatterlist, or the cacheline specified in dma_map_single) insert
433 * into this tree using the cacheline as the key. At
434 * dma_unmap_{single|sg|page} or dma_free_coherent delete the entry. If
435 * the entry already exists at insertion time add a tag as a reference
436 * count for the overlapping mappings. For now, the overlap tracking
437 * just ensures that 'unmaps' balance 'maps' before marking the
438 * cacheline idle, but we should also be flagging overlaps as an API
439 * violation.
440 *
441 * Memory usage is mostly constrained by the maximum number of available
442 * dma-debug entries in that we need a free dma_debug_entry before
443 * inserting into the tree. In the case of dma_map_page and
444 * dma_alloc_coherent there is only one dma_debug_entry and one
445 * dma_active_cacheline entry to track per event. dma_map_sg(), on the
446 * other hand, consumes a single dma_debug_entry, but inserts 'nents'
447 * entries into the tree.
448 */
449 static RADIX_TREE(dma_active_cacheline, GFP_ATOMIC);
450 static DEFINE_SPINLOCK(radix_lock);
451 #define ACTIVE_CACHELINE_MAX_OVERLAP ((1 << RADIX_TREE_MAX_TAGS) - 1)
452 #define CACHELINE_PER_PAGE_SHIFT (PAGE_SHIFT - L1_CACHE_SHIFT)
453 #define CACHELINES_PER_PAGE (1 << CACHELINE_PER_PAGE_SHIFT)
454
to_cacheline_number(struct dma_debug_entry * entry)455 static phys_addr_t to_cacheline_number(struct dma_debug_entry *entry)
456 {
457 return (entry->pfn << CACHELINE_PER_PAGE_SHIFT) +
458 (entry->offset >> L1_CACHE_SHIFT);
459 }
460
active_cacheline_read_overlap(phys_addr_t cln)461 static int active_cacheline_read_overlap(phys_addr_t cln)
462 {
463 int overlap = 0, i;
464
465 for (i = RADIX_TREE_MAX_TAGS - 1; i >= 0; i--)
466 if (radix_tree_tag_get(&dma_active_cacheline, cln, i))
467 overlap |= 1 << i;
468 return overlap;
469 }
470
active_cacheline_set_overlap(phys_addr_t cln,int overlap)471 static int active_cacheline_set_overlap(phys_addr_t cln, int overlap)
472 {
473 int i;
474
475 if (overlap > ACTIVE_CACHELINE_MAX_OVERLAP || overlap < 0)
476 return overlap;
477
478 for (i = RADIX_TREE_MAX_TAGS - 1; i >= 0; i--)
479 if (overlap & 1 << i)
480 radix_tree_tag_set(&dma_active_cacheline, cln, i);
481 else
482 radix_tree_tag_clear(&dma_active_cacheline, cln, i);
483
484 return overlap;
485 }
486
active_cacheline_inc_overlap(phys_addr_t cln)487 static void active_cacheline_inc_overlap(phys_addr_t cln)
488 {
489 int overlap = active_cacheline_read_overlap(cln);
490
491 overlap = active_cacheline_set_overlap(cln, ++overlap);
492
493 /* If we overflowed the overlap counter then we're potentially
494 * leaking dma-mappings.
495 */
496 WARN_ONCE(overlap > ACTIVE_CACHELINE_MAX_OVERLAP,
497 pr_fmt("exceeded %d overlapping mappings of cacheline %pa\n"),
498 ACTIVE_CACHELINE_MAX_OVERLAP, &cln);
499 }
500
active_cacheline_dec_overlap(phys_addr_t cln)501 static int active_cacheline_dec_overlap(phys_addr_t cln)
502 {
503 int overlap = active_cacheline_read_overlap(cln);
504
505 return active_cacheline_set_overlap(cln, --overlap);
506 }
507
active_cacheline_insert(struct dma_debug_entry * entry)508 static int active_cacheline_insert(struct dma_debug_entry *entry)
509 {
510 phys_addr_t cln = to_cacheline_number(entry);
511 unsigned long flags;
512 int rc;
513
514 /* If the device is not writing memory then we don't have any
515 * concerns about the cpu consuming stale data. This mitigates
516 * legitimate usages of overlapping mappings.
517 */
518 if (entry->direction == DMA_TO_DEVICE)
519 return 0;
520
521 spin_lock_irqsave(&radix_lock, flags);
522 rc = radix_tree_insert(&dma_active_cacheline, cln, entry);
523 if (rc == -EEXIST)
524 active_cacheline_inc_overlap(cln);
525 spin_unlock_irqrestore(&radix_lock, flags);
526
527 return rc;
528 }
529
active_cacheline_remove(struct dma_debug_entry * entry)530 static void active_cacheline_remove(struct dma_debug_entry *entry)
531 {
532 phys_addr_t cln = to_cacheline_number(entry);
533 unsigned long flags;
534
535 /* ...mirror the insert case */
536 if (entry->direction == DMA_TO_DEVICE)
537 return;
538
539 spin_lock_irqsave(&radix_lock, flags);
540 /* since we are counting overlaps the final put of the
541 * cacheline will occur when the overlap count is 0.
542 * active_cacheline_dec_overlap() returns -1 in that case
543 */
544 if (active_cacheline_dec_overlap(cln) < 0)
545 radix_tree_delete(&dma_active_cacheline, cln);
546 spin_unlock_irqrestore(&radix_lock, flags);
547 }
548
549 /*
550 * Wrapper function for adding an entry to the hash.
551 * This function takes care of locking itself.
552 */
add_dma_entry(struct dma_debug_entry * entry,unsigned long attrs)553 static void add_dma_entry(struct dma_debug_entry *entry, unsigned long attrs)
554 {
555 struct hash_bucket *bucket;
556 unsigned long flags;
557 int rc;
558
559 bucket = get_hash_bucket(entry, &flags);
560 hash_bucket_add(bucket, entry);
561 put_hash_bucket(bucket, flags);
562
563 rc = active_cacheline_insert(entry);
564 if (rc == -ENOMEM) {
565 pr_err_once("cacheline tracking ENOMEM, dma-debug disabled\n");
566 global_disable = true;
567 } else if (rc == -EEXIST && !(attrs & DMA_ATTR_SKIP_CPU_SYNC)) {
568 err_printk(entry->dev, entry,
569 "cacheline tracking EEXIST, overlapping mappings aren't supported\n");
570 }
571 }
572
dma_debug_create_entries(gfp_t gfp)573 static int dma_debug_create_entries(gfp_t gfp)
574 {
575 struct dma_debug_entry *entry;
576 int i;
577
578 entry = (void *)get_zeroed_page(gfp);
579 if (!entry)
580 return -ENOMEM;
581
582 for (i = 0; i < DMA_DEBUG_DYNAMIC_ENTRIES; i++)
583 list_add_tail(&entry[i].list, &free_entries);
584
585 num_free_entries += DMA_DEBUG_DYNAMIC_ENTRIES;
586 nr_total_entries += DMA_DEBUG_DYNAMIC_ENTRIES;
587
588 return 0;
589 }
590
__dma_entry_alloc(void)591 static struct dma_debug_entry *__dma_entry_alloc(void)
592 {
593 struct dma_debug_entry *entry;
594
595 entry = list_entry(free_entries.next, struct dma_debug_entry, list);
596 list_del(&entry->list);
597 memset(entry, 0, sizeof(*entry));
598
599 num_free_entries -= 1;
600 if (num_free_entries < min_free_entries)
601 min_free_entries = num_free_entries;
602
603 return entry;
604 }
605
606 /*
607 * This should be called outside of free_entries_lock scope to avoid potential
608 * deadlocks with serial consoles that use DMA.
609 */
__dma_entry_alloc_check_leak(u32 nr_entries)610 static void __dma_entry_alloc_check_leak(u32 nr_entries)
611 {
612 u32 tmp = nr_entries % nr_prealloc_entries;
613
614 /* Shout each time we tick over some multiple of the initial pool */
615 if (tmp < DMA_DEBUG_DYNAMIC_ENTRIES) {
616 pr_info("dma_debug_entry pool grown to %u (%u00%%)\n",
617 nr_entries,
618 (nr_entries / nr_prealloc_entries));
619 }
620 }
621
622 /* struct dma_entry allocator
623 *
624 * The next two functions implement the allocator for
625 * struct dma_debug_entries.
626 */
dma_entry_alloc(void)627 static struct dma_debug_entry *dma_entry_alloc(void)
628 {
629 bool alloc_check_leak = false;
630 struct dma_debug_entry *entry;
631 unsigned long flags;
632 u32 nr_entries;
633
634 spin_lock_irqsave(&free_entries_lock, flags);
635 if (num_free_entries == 0) {
636 if (dma_debug_create_entries(GFP_ATOMIC)) {
637 global_disable = true;
638 spin_unlock_irqrestore(&free_entries_lock, flags);
639 pr_err("debugging out of memory - disabling\n");
640 return NULL;
641 }
642 alloc_check_leak = true;
643 nr_entries = nr_total_entries;
644 }
645
646 entry = __dma_entry_alloc();
647
648 spin_unlock_irqrestore(&free_entries_lock, flags);
649
650 if (alloc_check_leak)
651 __dma_entry_alloc_check_leak(nr_entries);
652
653 #ifdef CONFIG_STACKTRACE
654 entry->stack_len = stack_trace_save(entry->stack_entries,
655 ARRAY_SIZE(entry->stack_entries),
656 1);
657 #endif
658 return entry;
659 }
660
dma_entry_free(struct dma_debug_entry * entry)661 static void dma_entry_free(struct dma_debug_entry *entry)
662 {
663 unsigned long flags;
664
665 active_cacheline_remove(entry);
666
667 /*
668 * add to beginning of the list - this way the entries are
669 * more likely cache hot when they are reallocated.
670 */
671 spin_lock_irqsave(&free_entries_lock, flags);
672 list_add(&entry->list, &free_entries);
673 num_free_entries += 1;
674 spin_unlock_irqrestore(&free_entries_lock, flags);
675 }
676
677 /*
678 * DMA-API debugging init code
679 *
680 * The init code does two things:
681 * 1. Initialize core data structures
682 * 2. Preallocate a given number of dma_debug_entry structs
683 */
684
filter_read(struct file * file,char __user * user_buf,size_t count,loff_t * ppos)685 static ssize_t filter_read(struct file *file, char __user *user_buf,
686 size_t count, loff_t *ppos)
687 {
688 char buf[NAME_MAX_LEN + 1];
689 unsigned long flags;
690 int len;
691
692 if (!current_driver_name[0])
693 return 0;
694
695 /*
696 * We can't copy to userspace directly because current_driver_name can
697 * only be read under the driver_name_lock with irqs disabled. So
698 * create a temporary copy first.
699 */
700 read_lock_irqsave(&driver_name_lock, flags);
701 len = scnprintf(buf, NAME_MAX_LEN + 1, "%s\n", current_driver_name);
702 read_unlock_irqrestore(&driver_name_lock, flags);
703
704 return simple_read_from_buffer(user_buf, count, ppos, buf, len);
705 }
706
filter_write(struct file * file,const char __user * userbuf,size_t count,loff_t * ppos)707 static ssize_t filter_write(struct file *file, const char __user *userbuf,
708 size_t count, loff_t *ppos)
709 {
710 char buf[NAME_MAX_LEN];
711 unsigned long flags;
712 size_t len;
713 int i;
714
715 /*
716 * We can't copy from userspace directly. Access to
717 * current_driver_name is protected with a write_lock with irqs
718 * disabled. Since copy_from_user can fault and may sleep we
719 * need to copy to temporary buffer first
720 */
721 len = min(count, (size_t)(NAME_MAX_LEN - 1));
722 if (copy_from_user(buf, userbuf, len))
723 return -EFAULT;
724
725 buf[len] = 0;
726
727 write_lock_irqsave(&driver_name_lock, flags);
728
729 /*
730 * Now handle the string we got from userspace very carefully.
731 * The rules are:
732 * - only use the first token we got
733 * - token delimiter is everything looking like a space
734 * character (' ', '\n', '\t' ...)
735 *
736 */
737 if (!isalnum(buf[0])) {
738 /*
739 * If the first character userspace gave us is not
740 * alphanumerical then assume the filter should be
741 * switched off.
742 */
743 if (current_driver_name[0])
744 pr_info("switching off dma-debug driver filter\n");
745 current_driver_name[0] = 0;
746 current_driver = NULL;
747 goto out_unlock;
748 }
749
750 /*
751 * Now parse out the first token and use it as the name for the
752 * driver to filter for.
753 */
754 for (i = 0; i < NAME_MAX_LEN - 1; ++i) {
755 current_driver_name[i] = buf[i];
756 if (isspace(buf[i]) || buf[i] == ' ' || buf[i] == 0)
757 break;
758 }
759 current_driver_name[i] = 0;
760 current_driver = NULL;
761
762 pr_info("enable driver filter for driver [%s]\n",
763 current_driver_name);
764
765 out_unlock:
766 write_unlock_irqrestore(&driver_name_lock, flags);
767
768 return count;
769 }
770
771 static const struct file_operations filter_fops = {
772 .read = filter_read,
773 .write = filter_write,
774 .llseek = default_llseek,
775 };
776
dump_show(struct seq_file * seq,void * v)777 static int dump_show(struct seq_file *seq, void *v)
778 {
779 int idx;
780
781 for (idx = 0; idx < HASH_SIZE; idx++) {
782 struct hash_bucket *bucket = &dma_entry_hash[idx];
783 struct dma_debug_entry *entry;
784 unsigned long flags;
785
786 spin_lock_irqsave(&bucket->lock, flags);
787 list_for_each_entry(entry, &bucket->list, list) {
788 seq_printf(seq,
789 "%s %s %s idx %d P=%llx N=%lx D=%llx L=%llx %s %s\n",
790 dev_name(entry->dev),
791 dev_driver_string(entry->dev),
792 type2name[entry->type], idx,
793 phys_addr(entry), entry->pfn,
794 entry->dev_addr, entry->size,
795 dir2name[entry->direction],
796 maperr2str[entry->map_err_type]);
797 }
798 spin_unlock_irqrestore(&bucket->lock, flags);
799 }
800 return 0;
801 }
802 DEFINE_SHOW_ATTRIBUTE(dump);
803
dma_debug_fs_init(void)804 static int __init dma_debug_fs_init(void)
805 {
806 struct dentry *dentry = debugfs_create_dir("dma-api", NULL);
807
808 debugfs_create_bool("disabled", 0444, dentry, &global_disable);
809 debugfs_create_u32("error_count", 0444, dentry, &error_count);
810 debugfs_create_u32("all_errors", 0644, dentry, &show_all_errors);
811 debugfs_create_u32("num_errors", 0644, dentry, &show_num_errors);
812 debugfs_create_u32("num_free_entries", 0444, dentry, &num_free_entries);
813 debugfs_create_u32("min_free_entries", 0444, dentry, &min_free_entries);
814 debugfs_create_u32("nr_total_entries", 0444, dentry, &nr_total_entries);
815 debugfs_create_file("driver_filter", 0644, dentry, NULL, &filter_fops);
816 debugfs_create_file("dump", 0444, dentry, NULL, &dump_fops);
817
818 return 0;
819 }
820 core_initcall_sync(dma_debug_fs_init);
821
device_dma_allocations(struct device * dev,struct dma_debug_entry ** out_entry)822 static int device_dma_allocations(struct device *dev, struct dma_debug_entry **out_entry)
823 {
824 struct dma_debug_entry *entry;
825 unsigned long flags;
826 int count = 0, i;
827
828 for (i = 0; i < HASH_SIZE; ++i) {
829 spin_lock_irqsave(&dma_entry_hash[i].lock, flags);
830 list_for_each_entry(entry, &dma_entry_hash[i].list, list) {
831 if (entry->dev == dev) {
832 count += 1;
833 *out_entry = entry;
834 }
835 }
836 spin_unlock_irqrestore(&dma_entry_hash[i].lock, flags);
837 }
838
839 return count;
840 }
841
dma_debug_device_change(struct notifier_block * nb,unsigned long action,void * data)842 static int dma_debug_device_change(struct notifier_block *nb, unsigned long action, void *data)
843 {
844 struct device *dev = data;
845 struct dma_debug_entry *entry;
846 int count;
847
848 if (dma_debug_disabled())
849 return 0;
850
851 switch (action) {
852 case BUS_NOTIFY_UNBOUND_DRIVER:
853 count = device_dma_allocations(dev, &entry);
854 if (count == 0)
855 break;
856 err_printk(dev, entry, "device driver has pending "
857 "DMA allocations while released from device "
858 "[count=%d]\n"
859 "One of leaked entries details: "
860 "[device address=0x%016llx] [size=%llu bytes] "
861 "[mapped with %s] [mapped as %s]\n",
862 count, entry->dev_addr, entry->size,
863 dir2name[entry->direction], type2name[entry->type]);
864 break;
865 default:
866 break;
867 }
868
869 return 0;
870 }
871
dma_debug_add_bus(struct bus_type * bus)872 void dma_debug_add_bus(struct bus_type *bus)
873 {
874 struct notifier_block *nb;
875
876 if (dma_debug_disabled())
877 return;
878
879 nb = kzalloc(sizeof(struct notifier_block), GFP_KERNEL);
880 if (nb == NULL) {
881 pr_err("dma_debug_add_bus: out of memory\n");
882 return;
883 }
884
885 nb->notifier_call = dma_debug_device_change;
886
887 bus_register_notifier(bus, nb);
888 }
889
dma_debug_init(void)890 static int dma_debug_init(void)
891 {
892 int i, nr_pages;
893
894 /* Do not use dma_debug_initialized here, since we really want to be
895 * called to set dma_debug_initialized
896 */
897 if (global_disable)
898 return 0;
899
900 for (i = 0; i < HASH_SIZE; ++i) {
901 INIT_LIST_HEAD(&dma_entry_hash[i].list);
902 spin_lock_init(&dma_entry_hash[i].lock);
903 }
904
905 nr_pages = DIV_ROUND_UP(nr_prealloc_entries, DMA_DEBUG_DYNAMIC_ENTRIES);
906 for (i = 0; i < nr_pages; ++i)
907 dma_debug_create_entries(GFP_KERNEL);
908 if (num_free_entries >= nr_prealloc_entries) {
909 pr_info("preallocated %d debug entries\n", nr_total_entries);
910 } else if (num_free_entries > 0) {
911 pr_warn("%d debug entries requested but only %d allocated\n",
912 nr_prealloc_entries, nr_total_entries);
913 } else {
914 pr_err("debugging out of memory error - disabled\n");
915 global_disable = true;
916
917 return 0;
918 }
919 min_free_entries = num_free_entries;
920
921 dma_debug_initialized = true;
922
923 pr_info("debugging enabled by kernel config\n");
924 return 0;
925 }
926 core_initcall(dma_debug_init);
927
dma_debug_cmdline(char * str)928 static __init int dma_debug_cmdline(char *str)
929 {
930 if (!str)
931 return -EINVAL;
932
933 if (strncmp(str, "off", 3) == 0) {
934 pr_info("debugging disabled on kernel command line\n");
935 global_disable = true;
936 }
937
938 return 1;
939 }
940
dma_debug_entries_cmdline(char * str)941 static __init int dma_debug_entries_cmdline(char *str)
942 {
943 if (!str)
944 return -EINVAL;
945 if (!get_option(&str, &nr_prealloc_entries))
946 nr_prealloc_entries = PREALLOC_DMA_DEBUG_ENTRIES;
947 return 1;
948 }
949
950 __setup("dma_debug=", dma_debug_cmdline);
951 __setup("dma_debug_entries=", dma_debug_entries_cmdline);
952
check_unmap(struct dma_debug_entry * ref)953 static void check_unmap(struct dma_debug_entry *ref)
954 {
955 struct dma_debug_entry *entry;
956 struct hash_bucket *bucket;
957 unsigned long flags;
958
959 bucket = get_hash_bucket(ref, &flags);
960 entry = bucket_find_exact(bucket, ref);
961
962 if (!entry) {
963 /* must drop lock before calling dma_mapping_error */
964 put_hash_bucket(bucket, flags);
965
966 if (dma_mapping_error(ref->dev, ref->dev_addr)) {
967 err_printk(ref->dev, NULL,
968 "device driver tries to free an "
969 "invalid DMA memory address\n");
970 } else {
971 err_printk(ref->dev, NULL,
972 "device driver tries to free DMA "
973 "memory it has not allocated [device "
974 "address=0x%016llx] [size=%llu bytes]\n",
975 ref->dev_addr, ref->size);
976 }
977 return;
978 }
979
980 if (ref->size != entry->size) {
981 err_printk(ref->dev, entry, "device driver frees "
982 "DMA memory with different size "
983 "[device address=0x%016llx] [map size=%llu bytes] "
984 "[unmap size=%llu bytes]\n",
985 ref->dev_addr, entry->size, ref->size);
986 }
987
988 if (ref->type != entry->type) {
989 err_printk(ref->dev, entry, "device driver frees "
990 "DMA memory with wrong function "
991 "[device address=0x%016llx] [size=%llu bytes] "
992 "[mapped as %s] [unmapped as %s]\n",
993 ref->dev_addr, ref->size,
994 type2name[entry->type], type2name[ref->type]);
995 } else if ((entry->type == dma_debug_coherent) &&
996 (phys_addr(ref) != phys_addr(entry))) {
997 err_printk(ref->dev, entry, "device driver frees "
998 "DMA memory with different CPU address "
999 "[device address=0x%016llx] [size=%llu bytes] "
1000 "[cpu alloc address=0x%016llx] "
1001 "[cpu free address=0x%016llx]",
1002 ref->dev_addr, ref->size,
1003 phys_addr(entry),
1004 phys_addr(ref));
1005 }
1006
1007 if (ref->sg_call_ents && ref->type == dma_debug_sg &&
1008 ref->sg_call_ents != entry->sg_call_ents) {
1009 err_printk(ref->dev, entry, "device driver frees "
1010 "DMA sg list with different entry count "
1011 "[map count=%d] [unmap count=%d]\n",
1012 entry->sg_call_ents, ref->sg_call_ents);
1013 }
1014
1015 /*
1016 * This may be no bug in reality - but most implementations of the
1017 * DMA API don't handle this properly, so check for it here
1018 */
1019 if (ref->direction != entry->direction) {
1020 err_printk(ref->dev, entry, "device driver frees "
1021 "DMA memory with different direction "
1022 "[device address=0x%016llx] [size=%llu bytes] "
1023 "[mapped with %s] [unmapped with %s]\n",
1024 ref->dev_addr, ref->size,
1025 dir2name[entry->direction],
1026 dir2name[ref->direction]);
1027 }
1028
1029 /*
1030 * Drivers should use dma_mapping_error() to check the returned
1031 * addresses of dma_map_single() and dma_map_page().
1032 * If not, print this warning message. See Documentation/core-api/dma-api.rst.
1033 */
1034 if (entry->map_err_type == MAP_ERR_NOT_CHECKED) {
1035 err_printk(ref->dev, entry,
1036 "device driver failed to check map error"
1037 "[device address=0x%016llx] [size=%llu bytes] "
1038 "[mapped as %s]",
1039 ref->dev_addr, ref->size,
1040 type2name[entry->type]);
1041 }
1042
1043 hash_bucket_del(entry);
1044 dma_entry_free(entry);
1045
1046 put_hash_bucket(bucket, flags);
1047 }
1048
check_for_stack(struct device * dev,struct page * page,size_t offset)1049 static void check_for_stack(struct device *dev,
1050 struct page *page, size_t offset)
1051 {
1052 void *addr;
1053 struct vm_struct *stack_vm_area = task_stack_vm_area(current);
1054
1055 if (!stack_vm_area) {
1056 /* Stack is direct-mapped. */
1057 if (PageHighMem(page))
1058 return;
1059 addr = page_address(page) + offset;
1060 if (object_is_on_stack(addr))
1061 err_printk(dev, NULL, "device driver maps memory from stack [addr=%p]\n", addr);
1062 } else {
1063 /* Stack is vmalloced. */
1064 int i;
1065
1066 for (i = 0; i < stack_vm_area->nr_pages; i++) {
1067 if (page != stack_vm_area->pages[i])
1068 continue;
1069
1070 addr = (u8 *)current->stack + i * PAGE_SIZE + offset;
1071 err_printk(dev, NULL, "device driver maps memory from stack [probable addr=%p]\n", addr);
1072 break;
1073 }
1074 }
1075 }
1076
check_for_illegal_area(struct device * dev,void * addr,unsigned long len)1077 static void check_for_illegal_area(struct device *dev, void *addr, unsigned long len)
1078 {
1079 if (memory_intersects(_stext, _etext, addr, len) ||
1080 memory_intersects(__start_rodata, __end_rodata, addr, len))
1081 err_printk(dev, NULL, "device driver maps memory from kernel text or rodata [addr=%p] [len=%lu]\n", addr, len);
1082 }
1083
check_sync(struct device * dev,struct dma_debug_entry * ref,bool to_cpu)1084 static void check_sync(struct device *dev,
1085 struct dma_debug_entry *ref,
1086 bool to_cpu)
1087 {
1088 struct dma_debug_entry *entry;
1089 struct hash_bucket *bucket;
1090 unsigned long flags;
1091
1092 bucket = get_hash_bucket(ref, &flags);
1093
1094 entry = bucket_find_contain(&bucket, ref, &flags);
1095
1096 if (!entry) {
1097 err_printk(dev, NULL, "device driver tries "
1098 "to sync DMA memory it has not allocated "
1099 "[device address=0x%016llx] [size=%llu bytes]\n",
1100 (unsigned long long)ref->dev_addr, ref->size);
1101 goto out;
1102 }
1103
1104 if (ref->size > entry->size) {
1105 err_printk(dev, entry, "device driver syncs"
1106 " DMA memory outside allocated range "
1107 "[device address=0x%016llx] "
1108 "[allocation size=%llu bytes] "
1109 "[sync offset+size=%llu]\n",
1110 entry->dev_addr, entry->size,
1111 ref->size);
1112 }
1113
1114 if (entry->direction == DMA_BIDIRECTIONAL)
1115 goto out;
1116
1117 if (ref->direction != entry->direction) {
1118 err_printk(dev, entry, "device driver syncs "
1119 "DMA memory with different direction "
1120 "[device address=0x%016llx] [size=%llu bytes] "
1121 "[mapped with %s] [synced with %s]\n",
1122 (unsigned long long)ref->dev_addr, entry->size,
1123 dir2name[entry->direction],
1124 dir2name[ref->direction]);
1125 }
1126
1127 if (to_cpu && !(entry->direction == DMA_FROM_DEVICE) &&
1128 !(ref->direction == DMA_TO_DEVICE))
1129 err_printk(dev, entry, "device driver syncs "
1130 "device read-only DMA memory for cpu "
1131 "[device address=0x%016llx] [size=%llu bytes] "
1132 "[mapped with %s] [synced with %s]\n",
1133 (unsigned long long)ref->dev_addr, entry->size,
1134 dir2name[entry->direction],
1135 dir2name[ref->direction]);
1136
1137 if (!to_cpu && !(entry->direction == DMA_TO_DEVICE) &&
1138 !(ref->direction == DMA_FROM_DEVICE))
1139 err_printk(dev, entry, "device driver syncs "
1140 "device write-only DMA memory to device "
1141 "[device address=0x%016llx] [size=%llu bytes] "
1142 "[mapped with %s] [synced with %s]\n",
1143 (unsigned long long)ref->dev_addr, entry->size,
1144 dir2name[entry->direction],
1145 dir2name[ref->direction]);
1146
1147 /* sg list count can be less than map count when partial cache sync */
1148 if (ref->sg_call_ents && ref->type == dma_debug_sg &&
1149 ref->sg_call_ents > entry->sg_call_ents) {
1150 err_printk(ref->dev, entry, "device driver syncs "
1151 "DMA sg list count larger than map count "
1152 "[map count=%d] [sync count=%d]\n",
1153 entry->sg_call_ents, ref->sg_call_ents);
1154 }
1155
1156 out:
1157 put_hash_bucket(bucket, flags);
1158 }
1159
check_sg_segment(struct device * dev,struct scatterlist * sg)1160 static void check_sg_segment(struct device *dev, struct scatterlist *sg)
1161 {
1162 #ifdef CONFIG_DMA_API_DEBUG_SG
1163 unsigned int max_seg = dma_get_max_seg_size(dev);
1164 u64 start, end, boundary = dma_get_seg_boundary(dev);
1165
1166 /*
1167 * Either the driver forgot to set dma_parms appropriately, or
1168 * whoever generated the list forgot to check them.
1169 */
1170 if (sg->length > max_seg)
1171 err_printk(dev, NULL, "mapping sg segment longer than device claims to support [len=%u] [max=%u]\n",
1172 sg->length, max_seg);
1173 /*
1174 * In some cases this could potentially be the DMA API
1175 * implementation's fault, but it would usually imply that
1176 * the scatterlist was built inappropriately to begin with.
1177 */
1178 start = sg_dma_address(sg);
1179 end = start + sg_dma_len(sg) - 1;
1180 if ((start ^ end) & ~boundary)
1181 err_printk(dev, NULL, "mapping sg segment across boundary [start=0x%016llx] [end=0x%016llx] [boundary=0x%016llx]\n",
1182 start, end, boundary);
1183 #endif
1184 }
1185
debug_dma_map_single(struct device * dev,const void * addr,unsigned long len)1186 void debug_dma_map_single(struct device *dev, const void *addr,
1187 unsigned long len)
1188 {
1189 if (unlikely(dma_debug_disabled()))
1190 return;
1191
1192 if (!virt_addr_valid(addr))
1193 err_printk(dev, NULL, "device driver maps memory from invalid area [addr=%p] [len=%lu]\n",
1194 addr, len);
1195
1196 if (is_vmalloc_addr(addr))
1197 err_printk(dev, NULL, "device driver maps memory from vmalloc area [addr=%p] [len=%lu]\n",
1198 addr, len);
1199 }
1200 EXPORT_SYMBOL(debug_dma_map_single);
1201
debug_dma_map_page(struct device * dev,struct page * page,size_t offset,size_t size,int direction,dma_addr_t dma_addr,unsigned long attrs)1202 void debug_dma_map_page(struct device *dev, struct page *page, size_t offset,
1203 size_t size, int direction, dma_addr_t dma_addr,
1204 unsigned long attrs)
1205 {
1206 struct dma_debug_entry *entry;
1207
1208 if (unlikely(dma_debug_disabled()))
1209 return;
1210
1211 if (dma_mapping_error(dev, dma_addr))
1212 return;
1213
1214 entry = dma_entry_alloc();
1215 if (!entry)
1216 return;
1217
1218 entry->dev = dev;
1219 entry->type = dma_debug_single;
1220 entry->pfn = page_to_pfn(page);
1221 entry->offset = offset;
1222 entry->dev_addr = dma_addr;
1223 entry->size = size;
1224 entry->direction = direction;
1225 entry->map_err_type = MAP_ERR_NOT_CHECKED;
1226
1227 check_for_stack(dev, page, offset);
1228
1229 if (!PageHighMem(page)) {
1230 void *addr = page_address(page) + offset;
1231
1232 check_for_illegal_area(dev, addr, size);
1233 }
1234
1235 add_dma_entry(entry, attrs);
1236 }
1237
debug_dma_mapping_error(struct device * dev,dma_addr_t dma_addr)1238 void debug_dma_mapping_error(struct device *dev, dma_addr_t dma_addr)
1239 {
1240 struct dma_debug_entry ref;
1241 struct dma_debug_entry *entry;
1242 struct hash_bucket *bucket;
1243 unsigned long flags;
1244
1245 if (unlikely(dma_debug_disabled()))
1246 return;
1247
1248 ref.dev = dev;
1249 ref.dev_addr = dma_addr;
1250 bucket = get_hash_bucket(&ref, &flags);
1251
1252 list_for_each_entry(entry, &bucket->list, list) {
1253 if (!exact_match(&ref, entry))
1254 continue;
1255
1256 /*
1257 * The same physical address can be mapped multiple
1258 * times. Without a hardware IOMMU this results in the
1259 * same device addresses being put into the dma-debug
1260 * hash multiple times too. This can result in false
1261 * positives being reported. Therefore we implement a
1262 * best-fit algorithm here which updates the first entry
1263 * from the hash which fits the reference value and is
1264 * not currently listed as being checked.
1265 */
1266 if (entry->map_err_type == MAP_ERR_NOT_CHECKED) {
1267 entry->map_err_type = MAP_ERR_CHECKED;
1268 break;
1269 }
1270 }
1271
1272 put_hash_bucket(bucket, flags);
1273 }
1274 EXPORT_SYMBOL(debug_dma_mapping_error);
1275
debug_dma_unmap_page(struct device * dev,dma_addr_t addr,size_t size,int direction)1276 void debug_dma_unmap_page(struct device *dev, dma_addr_t addr,
1277 size_t size, int direction)
1278 {
1279 struct dma_debug_entry ref = {
1280 .type = dma_debug_single,
1281 .dev = dev,
1282 .dev_addr = addr,
1283 .size = size,
1284 .direction = direction,
1285 };
1286
1287 if (unlikely(dma_debug_disabled()))
1288 return;
1289 check_unmap(&ref);
1290 }
1291
debug_dma_map_sg(struct device * dev,struct scatterlist * sg,int nents,int mapped_ents,int direction,unsigned long attrs)1292 void debug_dma_map_sg(struct device *dev, struct scatterlist *sg,
1293 int nents, int mapped_ents, int direction,
1294 unsigned long attrs)
1295 {
1296 struct dma_debug_entry *entry;
1297 struct scatterlist *s;
1298 int i;
1299
1300 if (unlikely(dma_debug_disabled()))
1301 return;
1302
1303 for_each_sg(sg, s, nents, i) {
1304 check_for_stack(dev, sg_page(s), s->offset);
1305 if (!PageHighMem(sg_page(s)))
1306 check_for_illegal_area(dev, sg_virt(s), s->length);
1307 }
1308
1309 for_each_sg(sg, s, mapped_ents, i) {
1310 entry = dma_entry_alloc();
1311 if (!entry)
1312 return;
1313
1314 entry->type = dma_debug_sg;
1315 entry->dev = dev;
1316 entry->pfn = page_to_pfn(sg_page(s));
1317 entry->offset = s->offset;
1318 entry->size = sg_dma_len(s);
1319 entry->dev_addr = sg_dma_address(s);
1320 entry->direction = direction;
1321 entry->sg_call_ents = nents;
1322 entry->sg_mapped_ents = mapped_ents;
1323
1324 check_sg_segment(dev, s);
1325
1326 add_dma_entry(entry, attrs);
1327 }
1328 }
1329
get_nr_mapped_entries(struct device * dev,struct dma_debug_entry * ref)1330 static int get_nr_mapped_entries(struct device *dev,
1331 struct dma_debug_entry *ref)
1332 {
1333 struct dma_debug_entry *entry;
1334 struct hash_bucket *bucket;
1335 unsigned long flags;
1336 int mapped_ents;
1337
1338 bucket = get_hash_bucket(ref, &flags);
1339 entry = bucket_find_exact(bucket, ref);
1340 mapped_ents = 0;
1341
1342 if (entry)
1343 mapped_ents = entry->sg_mapped_ents;
1344 put_hash_bucket(bucket, flags);
1345
1346 return mapped_ents;
1347 }
1348
debug_dma_unmap_sg(struct device * dev,struct scatterlist * sglist,int nelems,int dir)1349 void debug_dma_unmap_sg(struct device *dev, struct scatterlist *sglist,
1350 int nelems, int dir)
1351 {
1352 struct scatterlist *s;
1353 int mapped_ents = 0, i;
1354
1355 if (unlikely(dma_debug_disabled()))
1356 return;
1357
1358 for_each_sg(sglist, s, nelems, i) {
1359
1360 struct dma_debug_entry ref = {
1361 .type = dma_debug_sg,
1362 .dev = dev,
1363 .pfn = page_to_pfn(sg_page(s)),
1364 .offset = s->offset,
1365 .dev_addr = sg_dma_address(s),
1366 .size = sg_dma_len(s),
1367 .direction = dir,
1368 .sg_call_ents = nelems,
1369 };
1370
1371 if (mapped_ents && i >= mapped_ents)
1372 break;
1373
1374 if (!i)
1375 mapped_ents = get_nr_mapped_entries(dev, &ref);
1376
1377 check_unmap(&ref);
1378 }
1379 }
1380
debug_dma_alloc_coherent(struct device * dev,size_t size,dma_addr_t dma_addr,void * virt,unsigned long attrs)1381 void debug_dma_alloc_coherent(struct device *dev, size_t size,
1382 dma_addr_t dma_addr, void *virt,
1383 unsigned long attrs)
1384 {
1385 struct dma_debug_entry *entry;
1386
1387 if (unlikely(dma_debug_disabled()))
1388 return;
1389
1390 if (unlikely(virt == NULL))
1391 return;
1392
1393 /* handle vmalloc and linear addresses */
1394 if (!is_vmalloc_addr(virt) && !virt_addr_valid(virt))
1395 return;
1396
1397 entry = dma_entry_alloc();
1398 if (!entry)
1399 return;
1400
1401 entry->type = dma_debug_coherent;
1402 entry->dev = dev;
1403 entry->offset = offset_in_page(virt);
1404 entry->size = size;
1405 entry->dev_addr = dma_addr;
1406 entry->direction = DMA_BIDIRECTIONAL;
1407
1408 if (is_vmalloc_addr(virt))
1409 entry->pfn = vmalloc_to_pfn(virt);
1410 else
1411 entry->pfn = page_to_pfn(virt_to_page(virt));
1412
1413 add_dma_entry(entry, attrs);
1414 }
1415
debug_dma_free_coherent(struct device * dev,size_t size,void * virt,dma_addr_t addr)1416 void debug_dma_free_coherent(struct device *dev, size_t size,
1417 void *virt, dma_addr_t addr)
1418 {
1419 struct dma_debug_entry ref = {
1420 .type = dma_debug_coherent,
1421 .dev = dev,
1422 .offset = offset_in_page(virt),
1423 .dev_addr = addr,
1424 .size = size,
1425 .direction = DMA_BIDIRECTIONAL,
1426 };
1427
1428 /* handle vmalloc and linear addresses */
1429 if (!is_vmalloc_addr(virt) && !virt_addr_valid(virt))
1430 return;
1431
1432 if (is_vmalloc_addr(virt))
1433 ref.pfn = vmalloc_to_pfn(virt);
1434 else
1435 ref.pfn = page_to_pfn(virt_to_page(virt));
1436
1437 if (unlikely(dma_debug_disabled()))
1438 return;
1439
1440 check_unmap(&ref);
1441 }
1442
debug_dma_map_resource(struct device * dev,phys_addr_t addr,size_t size,int direction,dma_addr_t dma_addr,unsigned long attrs)1443 void debug_dma_map_resource(struct device *dev, phys_addr_t addr, size_t size,
1444 int direction, dma_addr_t dma_addr,
1445 unsigned long attrs)
1446 {
1447 struct dma_debug_entry *entry;
1448
1449 if (unlikely(dma_debug_disabled()))
1450 return;
1451
1452 entry = dma_entry_alloc();
1453 if (!entry)
1454 return;
1455
1456 entry->type = dma_debug_resource;
1457 entry->dev = dev;
1458 entry->pfn = PHYS_PFN(addr);
1459 entry->offset = offset_in_page(addr);
1460 entry->size = size;
1461 entry->dev_addr = dma_addr;
1462 entry->direction = direction;
1463 entry->map_err_type = MAP_ERR_NOT_CHECKED;
1464
1465 add_dma_entry(entry, attrs);
1466 }
1467
debug_dma_unmap_resource(struct device * dev,dma_addr_t dma_addr,size_t size,int direction)1468 void debug_dma_unmap_resource(struct device *dev, dma_addr_t dma_addr,
1469 size_t size, int direction)
1470 {
1471 struct dma_debug_entry ref = {
1472 .type = dma_debug_resource,
1473 .dev = dev,
1474 .dev_addr = dma_addr,
1475 .size = size,
1476 .direction = direction,
1477 };
1478
1479 if (unlikely(dma_debug_disabled()))
1480 return;
1481
1482 check_unmap(&ref);
1483 }
1484
debug_dma_sync_single_for_cpu(struct device * dev,dma_addr_t dma_handle,size_t size,int direction)1485 void debug_dma_sync_single_for_cpu(struct device *dev, dma_addr_t dma_handle,
1486 size_t size, int direction)
1487 {
1488 struct dma_debug_entry ref;
1489
1490 if (unlikely(dma_debug_disabled()))
1491 return;
1492
1493 ref.type = dma_debug_single;
1494 ref.dev = dev;
1495 ref.dev_addr = dma_handle;
1496 ref.size = size;
1497 ref.direction = direction;
1498 ref.sg_call_ents = 0;
1499
1500 check_sync(dev, &ref, true);
1501 }
1502
debug_dma_sync_single_for_device(struct device * dev,dma_addr_t dma_handle,size_t size,int direction)1503 void debug_dma_sync_single_for_device(struct device *dev,
1504 dma_addr_t dma_handle, size_t size,
1505 int direction)
1506 {
1507 struct dma_debug_entry ref;
1508
1509 if (unlikely(dma_debug_disabled()))
1510 return;
1511
1512 ref.type = dma_debug_single;
1513 ref.dev = dev;
1514 ref.dev_addr = dma_handle;
1515 ref.size = size;
1516 ref.direction = direction;
1517 ref.sg_call_ents = 0;
1518
1519 check_sync(dev, &ref, false);
1520 }
1521
debug_dma_sync_sg_for_cpu(struct device * dev,struct scatterlist * sg,int nelems,int direction)1522 void debug_dma_sync_sg_for_cpu(struct device *dev, struct scatterlist *sg,
1523 int nelems, int direction)
1524 {
1525 struct scatterlist *s;
1526 int mapped_ents = 0, i;
1527
1528 if (unlikely(dma_debug_disabled()))
1529 return;
1530
1531 for_each_sg(sg, s, nelems, i) {
1532
1533 struct dma_debug_entry ref = {
1534 .type = dma_debug_sg,
1535 .dev = dev,
1536 .pfn = page_to_pfn(sg_page(s)),
1537 .offset = s->offset,
1538 .dev_addr = sg_dma_address(s),
1539 .size = sg_dma_len(s),
1540 .direction = direction,
1541 .sg_call_ents = nelems,
1542 };
1543
1544 if (!i)
1545 mapped_ents = get_nr_mapped_entries(dev, &ref);
1546
1547 if (i >= mapped_ents)
1548 break;
1549
1550 check_sync(dev, &ref, true);
1551 }
1552 }
1553
debug_dma_sync_sg_for_device(struct device * dev,struct scatterlist * sg,int nelems,int direction)1554 void debug_dma_sync_sg_for_device(struct device *dev, struct scatterlist *sg,
1555 int nelems, int direction)
1556 {
1557 struct scatterlist *s;
1558 int mapped_ents = 0, i;
1559
1560 if (unlikely(dma_debug_disabled()))
1561 return;
1562
1563 for_each_sg(sg, s, nelems, i) {
1564
1565 struct dma_debug_entry ref = {
1566 .type = dma_debug_sg,
1567 .dev = dev,
1568 .pfn = page_to_pfn(sg_page(s)),
1569 .offset = s->offset,
1570 .dev_addr = sg_dma_address(s),
1571 .size = sg_dma_len(s),
1572 .direction = direction,
1573 .sg_call_ents = nelems,
1574 };
1575 if (!i)
1576 mapped_ents = get_nr_mapped_entries(dev, &ref);
1577
1578 if (i >= mapped_ents)
1579 break;
1580
1581 check_sync(dev, &ref, false);
1582 }
1583 }
1584
dma_debug_driver_setup(char * str)1585 static int __init dma_debug_driver_setup(char *str)
1586 {
1587 int i;
1588
1589 for (i = 0; i < NAME_MAX_LEN - 1; ++i, ++str) {
1590 current_driver_name[i] = *str;
1591 if (*str == 0)
1592 break;
1593 }
1594
1595 if (current_driver_name[0])
1596 pr_info("enable driver filter for driver [%s]\n",
1597 current_driver_name);
1598
1599
1600 return 1;
1601 }
1602 __setup("dma_debug_driver=", dma_debug_driver_setup);
1603