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