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