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