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