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