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