Merge branches 'dma-debug/fixes' and 'dma-debug/driver-filter' into dma-debug/2.6.31
[pandora-kernel.git] / lib / dma-debug.c
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
20 #include <linux/scatterlist.h>
21 #include <linux/dma-mapping.h>
22 #include <linux/stacktrace.h>
23 #include <linux/dma-debug.h>
24 #include <linux/spinlock.h>
25 #include <linux/debugfs.h>
26 #include <linux/uaccess.h>
27 #include <linux/device.h>
28 #include <linux/types.h>
29 #include <linux/sched.h>
30 #include <linux/ctype.h>
31 #include <linux/list.h>
32 #include <linux/slab.h>
33
34 #include <asm/sections.h>
35
36 #define HASH_SIZE       1024ULL
37 #define HASH_FN_SHIFT   13
38 #define HASH_FN_MASK    (HASH_SIZE - 1)
39
40 enum {
41         dma_debug_single,
42         dma_debug_page,
43         dma_debug_sg,
44         dma_debug_coherent,
45 };
46
47 #define DMA_DEBUG_STACKTRACE_ENTRIES 5
48
49 struct dma_debug_entry {
50         struct list_head list;
51         struct device    *dev;
52         int              type;
53         phys_addr_t      paddr;
54         u64              dev_addr;
55         u64              size;
56         int              direction;
57         int              sg_call_ents;
58         int              sg_mapped_ents;
59 #ifdef CONFIG_STACKTRACE
60         struct           stack_trace stacktrace;
61         unsigned long    st_entries[DMA_DEBUG_STACKTRACE_ENTRIES];
62 #endif
63 };
64
65 struct hash_bucket {
66         struct list_head list;
67         spinlock_t lock;
68 } ____cacheline_aligned_in_smp;
69
70 /* Hash list to save the allocated dma addresses */
71 static struct hash_bucket dma_entry_hash[HASH_SIZE];
72 /* List of pre-allocated dma_debug_entry's */
73 static LIST_HEAD(free_entries);
74 /* Lock for the list above */
75 static DEFINE_SPINLOCK(free_entries_lock);
76
77 /* Global disable flag - will be set in case of an error */
78 static bool global_disable __read_mostly;
79
80 /* Global error count */
81 static u32 error_count;
82
83 /* Global error show enable*/
84 static u32 show_all_errors __read_mostly;
85 /* Number of errors to show */
86 static u32 show_num_errors = 1;
87
88 static u32 num_free_entries;
89 static u32 min_free_entries;
90 static u32 nr_total_entries;
91
92 /* number of preallocated entries requested by kernel cmdline */
93 static u32 req_entries;
94
95 /* debugfs dentry's for the stuff above */
96 static struct dentry *dma_debug_dent        __read_mostly;
97 static struct dentry *global_disable_dent   __read_mostly;
98 static struct dentry *error_count_dent      __read_mostly;
99 static struct dentry *show_all_errors_dent  __read_mostly;
100 static struct dentry *show_num_errors_dent  __read_mostly;
101 static struct dentry *num_free_entries_dent __read_mostly;
102 static struct dentry *min_free_entries_dent __read_mostly;
103 static struct dentry *filter_dent           __read_mostly;
104
105 /* per-driver filter related state */
106
107 #define NAME_MAX_LEN    64
108
109 static char                  current_driver_name[NAME_MAX_LEN] __read_mostly;
110 static struct device_driver *current_driver                    __read_mostly;
111
112 static DEFINE_RWLOCK(driver_name_lock);
113
114 static const char *type2name[4] = { "single", "page",
115                                     "scather-gather", "coherent" };
116
117 static const char *dir2name[4] = { "DMA_BIDIRECTIONAL", "DMA_TO_DEVICE",
118                                    "DMA_FROM_DEVICE", "DMA_NONE" };
119
120 /* little merge helper - remove it after the merge window */
121 #ifndef BUS_NOTIFY_UNBOUND_DRIVER
122 #define BUS_NOTIFY_UNBOUND_DRIVER 0x0005
123 #endif
124
125 /*
126  * The access to some variables in this macro is racy. We can't use atomic_t
127  * here because all these variables are exported to debugfs. Some of them even
128  * writeable. This is also the reason why a lock won't help much. But anyway,
129  * the races are no big deal. Here is why:
130  *
131  *   error_count: the addition is racy, but the worst thing that can happen is
132  *                that we don't count some errors
133  *   show_num_errors: the subtraction is racy. Also no big deal because in
134  *                    worst case this will result in one warning more in the
135  *                    system log than the user configured. This variable is
136  *                    writeable via debugfs.
137  */
138 static inline void dump_entry_trace(struct dma_debug_entry *entry)
139 {
140 #ifdef CONFIG_STACKTRACE
141         if (entry) {
142                 printk(KERN_WARNING "Mapped at:\n");
143                 print_stack_trace(&entry->stacktrace, 0);
144         }
145 #endif
146 }
147
148 static bool driver_filter(struct device *dev)
149 {
150         /* driver filter off */
151         if (likely(!current_driver_name[0]))
152                 return true;
153
154         /* driver filter on and initialized */
155         if (current_driver && dev->driver == current_driver)
156                 return true;
157
158         /* driver filter on but not yet initialized */
159         if (!current_driver && current_driver_name[0]) {
160                 struct device_driver *drv = get_driver(dev->driver);
161                 unsigned long flags;
162                 bool ret = false;
163
164                 if (!drv)
165                         return false;
166
167                 /* lock to protect against change of current_driver_name */
168                 read_lock_irqsave(&driver_name_lock, flags);
169
170                 if (drv->name &&
171                     strncmp(current_driver_name, drv->name,
172                             NAME_MAX_LEN-1) == 0) {
173                         current_driver = drv;
174                         ret = true;
175                 }
176
177                 read_unlock_irqrestore(&driver_name_lock, flags);
178                 put_driver(drv);
179
180                 return ret;
181         }
182
183         return false;
184 }
185
186 #define err_printk(dev, entry, format, arg...) do {             \
187                 error_count += 1;                               \
188                 if (driver_filter(dev) &&                       \
189                     (show_all_errors || show_num_errors > 0)) { \
190                         WARN(1, "%s %s: " format,               \
191                              dev_driver_string(dev),            \
192                              dev_name(dev) , ## arg);           \
193                         dump_entry_trace(entry);                \
194                 }                                               \
195                 if (!show_all_errors && show_num_errors > 0)    \
196                         show_num_errors -= 1;                   \
197         } while (0);
198
199 /*
200  * Hash related functions
201  *
202  * Every DMA-API request is saved into a struct dma_debug_entry. To
203  * have quick access to these structs they are stored into a hash.
204  */
205 static int hash_fn(struct dma_debug_entry *entry)
206 {
207         /*
208          * Hash function is based on the dma address.
209          * We use bits 20-27 here as the index into the hash
210          */
211         return (entry->dev_addr >> HASH_FN_SHIFT) & HASH_FN_MASK;
212 }
213
214 /*
215  * Request exclusive access to a hash bucket for a given dma_debug_entry.
216  */
217 static struct hash_bucket *get_hash_bucket(struct dma_debug_entry *entry,
218                                            unsigned long *flags)
219 {
220         int idx = hash_fn(entry);
221         unsigned long __flags;
222
223         spin_lock_irqsave(&dma_entry_hash[idx].lock, __flags);
224         *flags = __flags;
225         return &dma_entry_hash[idx];
226 }
227
228 /*
229  * Give up exclusive access to the hash bucket
230  */
231 static void put_hash_bucket(struct hash_bucket *bucket,
232                             unsigned long *flags)
233 {
234         unsigned long __flags = *flags;
235
236         spin_unlock_irqrestore(&bucket->lock, __flags);
237 }
238
239 /*
240  * Search a given entry in the hash bucket list
241  */
242 static struct dma_debug_entry *hash_bucket_find(struct hash_bucket *bucket,
243                                                 struct dma_debug_entry *ref)
244 {
245         struct dma_debug_entry *entry;
246
247         list_for_each_entry(entry, &bucket->list, list) {
248                 if ((entry->dev_addr == ref->dev_addr) &&
249                     (entry->dev == ref->dev))
250                         return entry;
251         }
252
253         return NULL;
254 }
255
256 /*
257  * Add an entry to a hash bucket
258  */
259 static void hash_bucket_add(struct hash_bucket *bucket,
260                             struct dma_debug_entry *entry)
261 {
262         list_add_tail(&entry->list, &bucket->list);
263 }
264
265 /*
266  * Remove entry from a hash bucket list
267  */
268 static void hash_bucket_del(struct dma_debug_entry *entry)
269 {
270         list_del(&entry->list);
271 }
272
273 /*
274  * Dump mapping entries for debugging purposes
275  */
276 void debug_dma_dump_mappings(struct device *dev)
277 {
278         int idx;
279
280         for (idx = 0; idx < HASH_SIZE; idx++) {
281                 struct hash_bucket *bucket = &dma_entry_hash[idx];
282                 struct dma_debug_entry *entry;
283                 unsigned long flags;
284
285                 spin_lock_irqsave(&bucket->lock, flags);
286
287                 list_for_each_entry(entry, &bucket->list, list) {
288                         if (!dev || dev == entry->dev) {
289                                 dev_info(entry->dev,
290                                          "%s idx %d P=%Lx D=%Lx L=%Lx %s\n",
291                                          type2name[entry->type], idx,
292                                          (unsigned long long)entry->paddr,
293                                          entry->dev_addr, entry->size,
294                                          dir2name[entry->direction]);
295                         }
296                 }
297
298                 spin_unlock_irqrestore(&bucket->lock, flags);
299         }
300 }
301 EXPORT_SYMBOL(debug_dma_dump_mappings);
302
303 /*
304  * Wrapper function for adding an entry to the hash.
305  * This function takes care of locking itself.
306  */
307 static void add_dma_entry(struct dma_debug_entry *entry)
308 {
309         struct hash_bucket *bucket;
310         unsigned long flags;
311
312         bucket = get_hash_bucket(entry, &flags);
313         hash_bucket_add(bucket, entry);
314         put_hash_bucket(bucket, &flags);
315 }
316
317 static struct dma_debug_entry *__dma_entry_alloc(void)
318 {
319         struct dma_debug_entry *entry;
320
321         entry = list_entry(free_entries.next, struct dma_debug_entry, list);
322         list_del(&entry->list);
323         memset(entry, 0, sizeof(*entry));
324
325         num_free_entries -= 1;
326         if (num_free_entries < min_free_entries)
327                 min_free_entries = num_free_entries;
328
329         return entry;
330 }
331
332 /* struct dma_entry allocator
333  *
334  * The next two functions implement the allocator for
335  * struct dma_debug_entries.
336  */
337 static struct dma_debug_entry *dma_entry_alloc(void)
338 {
339         struct dma_debug_entry *entry = NULL;
340         unsigned long flags;
341
342         spin_lock_irqsave(&free_entries_lock, flags);
343
344         if (list_empty(&free_entries)) {
345                 printk(KERN_ERR "DMA-API: debugging out of memory "
346                                 "- disabling\n");
347                 global_disable = true;
348                 goto out;
349         }
350
351         entry = __dma_entry_alloc();
352
353 #ifdef CONFIG_STACKTRACE
354         entry->stacktrace.max_entries = DMA_DEBUG_STACKTRACE_ENTRIES;
355         entry->stacktrace.entries = entry->st_entries;
356         entry->stacktrace.skip = 2;
357         save_stack_trace(&entry->stacktrace);
358 #endif
359
360 out:
361         spin_unlock_irqrestore(&free_entries_lock, flags);
362
363         return entry;
364 }
365
366 static void dma_entry_free(struct dma_debug_entry *entry)
367 {
368         unsigned long flags;
369
370         /*
371          * add to beginning of the list - this way the entries are
372          * more likely cache hot when they are reallocated.
373          */
374         spin_lock_irqsave(&free_entries_lock, flags);
375         list_add(&entry->list, &free_entries);
376         num_free_entries += 1;
377         spin_unlock_irqrestore(&free_entries_lock, flags);
378 }
379
380 int dma_debug_resize_entries(u32 num_entries)
381 {
382         int i, delta, ret = 0;
383         unsigned long flags;
384         struct dma_debug_entry *entry;
385         LIST_HEAD(tmp);
386
387         spin_lock_irqsave(&free_entries_lock, flags);
388
389         if (nr_total_entries < num_entries) {
390                 delta = num_entries - nr_total_entries;
391
392                 spin_unlock_irqrestore(&free_entries_lock, flags);
393
394                 for (i = 0; i < delta; i++) {
395                         entry = kzalloc(sizeof(*entry), GFP_KERNEL);
396                         if (!entry)
397                                 break;
398
399                         list_add_tail(&entry->list, &tmp);
400                 }
401
402                 spin_lock_irqsave(&free_entries_lock, flags);
403
404                 list_splice(&tmp, &free_entries);
405                 nr_total_entries += i;
406                 num_free_entries += i;
407         } else {
408                 delta = nr_total_entries - num_entries;
409
410                 for (i = 0; i < delta && !list_empty(&free_entries); i++) {
411                         entry = __dma_entry_alloc();
412                         kfree(entry);
413                 }
414
415                 nr_total_entries -= i;
416         }
417
418         if (nr_total_entries != num_entries)
419                 ret = 1;
420
421         spin_unlock_irqrestore(&free_entries_lock, flags);
422
423         return ret;
424 }
425 EXPORT_SYMBOL(dma_debug_resize_entries);
426
427 /*
428  * DMA-API debugging init code
429  *
430  * The init code does two things:
431  *   1. Initialize core data structures
432  *   2. Preallocate a given number of dma_debug_entry structs
433  */
434
435 static int prealloc_memory(u32 num_entries)
436 {
437         struct dma_debug_entry *entry, *next_entry;
438         int i;
439
440         for (i = 0; i < num_entries; ++i) {
441                 entry = kzalloc(sizeof(*entry), GFP_KERNEL);
442                 if (!entry)
443                         goto out_err;
444
445                 list_add_tail(&entry->list, &free_entries);
446         }
447
448         num_free_entries = num_entries;
449         min_free_entries = num_entries;
450
451         printk(KERN_INFO "DMA-API: preallocated %d debug entries\n",
452                         num_entries);
453
454         return 0;
455
456 out_err:
457
458         list_for_each_entry_safe(entry, next_entry, &free_entries, list) {
459                 list_del(&entry->list);
460                 kfree(entry);
461         }
462
463         return -ENOMEM;
464 }
465
466 static ssize_t filter_read(struct file *file, char __user *user_buf,
467                            size_t count, loff_t *ppos)
468 {
469         unsigned long flags;
470         char buf[NAME_MAX_LEN + 1];
471         int len;
472
473         if (!current_driver_name[0])
474                 return 0;
475
476         /*
477          * We can't copy to userspace directly because current_driver_name can
478          * only be read under the driver_name_lock with irqs disabled. So
479          * create a temporary copy first.
480          */
481         read_lock_irqsave(&driver_name_lock, flags);
482         len = scnprintf(buf, NAME_MAX_LEN + 1, "%s\n", current_driver_name);
483         read_unlock_irqrestore(&driver_name_lock, flags);
484
485         return simple_read_from_buffer(user_buf, count, ppos, buf, len);
486 }
487
488 static ssize_t filter_write(struct file *file, const char __user *userbuf,
489                             size_t count, loff_t *ppos)
490 {
491         unsigned long flags;
492         char buf[NAME_MAX_LEN];
493         size_t len = NAME_MAX_LEN - 1;
494         int i;
495
496         /*
497          * We can't copy from userspace directly. Access to
498          * current_driver_name is protected with a write_lock with irqs
499          * disabled. Since copy_from_user can fault and may sleep we
500          * need to copy to temporary buffer first
501          */
502         len = min(count, len);
503         if (copy_from_user(buf, userbuf, len))
504                 return -EFAULT;
505
506         buf[len] = 0;
507
508         write_lock_irqsave(&driver_name_lock, flags);
509
510         /* Now handle the string we got from userspace very carefully.
511          * The rules are:
512          *         - only use the first token we got
513          *         - token delimiter is everything looking like a space
514          *           character (' ', '\n', '\t' ...)
515          *
516          */
517         if (!isalnum(buf[0])) {
518                 /*
519                    If the first character userspace gave us is not
520                  * alphanumerical then assume the filter should be
521                  * switched off.
522                  */
523                 if (current_driver_name[0])
524                         printk(KERN_INFO "DMA-API: switching off dma-debug "
525                                          "driver filter\n");
526                 current_driver_name[0] = 0;
527                 current_driver = NULL;
528                 goto out_unlock;
529         }
530
531         /*
532          * Now parse out the first token and use it as the name for the
533          * driver to filter for.
534          */
535         for (i = 0; i < NAME_MAX_LEN; ++i) {
536                 current_driver_name[i] = buf[i];
537                 if (isspace(buf[i]) || buf[i] == ' ' || buf[i] == 0)
538                         break;
539         }
540         current_driver_name[i] = 0;
541         current_driver = NULL;
542
543         printk(KERN_INFO "DMA-API: enable driver filter for driver [%s]\n",
544                current_driver_name);
545
546 out_unlock:
547         write_unlock_irqrestore(&driver_name_lock, flags);
548
549         return count;
550 }
551
552 const struct file_operations filter_fops = {
553         .read  = filter_read,
554         .write = filter_write,
555 };
556
557 static int dma_debug_fs_init(void)
558 {
559         dma_debug_dent = debugfs_create_dir("dma-api", NULL);
560         if (!dma_debug_dent) {
561                 printk(KERN_ERR "DMA-API: can not create debugfs directory\n");
562                 return -ENOMEM;
563         }
564
565         global_disable_dent = debugfs_create_bool("disabled", 0444,
566                         dma_debug_dent,
567                         (u32 *)&global_disable);
568         if (!global_disable_dent)
569                 goto out_err;
570
571         error_count_dent = debugfs_create_u32("error_count", 0444,
572                         dma_debug_dent, &error_count);
573         if (!error_count_dent)
574                 goto out_err;
575
576         show_all_errors_dent = debugfs_create_u32("all_errors", 0644,
577                         dma_debug_dent,
578                         &show_all_errors);
579         if (!show_all_errors_dent)
580                 goto out_err;
581
582         show_num_errors_dent = debugfs_create_u32("num_errors", 0644,
583                         dma_debug_dent,
584                         &show_num_errors);
585         if (!show_num_errors_dent)
586                 goto out_err;
587
588         num_free_entries_dent = debugfs_create_u32("num_free_entries", 0444,
589                         dma_debug_dent,
590                         &num_free_entries);
591         if (!num_free_entries_dent)
592                 goto out_err;
593
594         min_free_entries_dent = debugfs_create_u32("min_free_entries", 0444,
595                         dma_debug_dent,
596                         &min_free_entries);
597         if (!min_free_entries_dent)
598                 goto out_err;
599
600         filter_dent = debugfs_create_file("driver_filter", 0644,
601                                           dma_debug_dent, NULL, &filter_fops);
602         if (!filter_dent)
603                 goto out_err;
604
605         return 0;
606
607 out_err:
608         debugfs_remove_recursive(dma_debug_dent);
609
610         return -ENOMEM;
611 }
612
613 static int device_dma_allocations(struct device *dev)
614 {
615         struct dma_debug_entry *entry;
616         unsigned long flags;
617         int count = 0, i;
618
619         for (i = 0; i < HASH_SIZE; ++i) {
620                 spin_lock_irqsave(&dma_entry_hash[i].lock, flags);
621                 list_for_each_entry(entry, &dma_entry_hash[i].list, list) {
622                         if (entry->dev == dev)
623                                 count += 1;
624                 }
625                 spin_unlock_irqrestore(&dma_entry_hash[i].lock, flags);
626         }
627
628         return count;
629 }
630
631 static int dma_debug_device_change(struct notifier_block *nb,
632                                     unsigned long action, void *data)
633 {
634         struct device *dev = data;
635         int count;
636
637
638         switch (action) {
639         case BUS_NOTIFY_UNBOUND_DRIVER:
640                 count = device_dma_allocations(dev);
641                 if (count == 0)
642                         break;
643                 err_printk(dev, NULL, "DMA-API: device driver has pending "
644                                 "DMA allocations while released from device "
645                                 "[count=%d]\n", count);
646                 break;
647         default:
648                 break;
649         }
650
651         return 0;
652 }
653
654 void dma_debug_add_bus(struct bus_type *bus)
655 {
656         struct notifier_block *nb;
657
658         nb = kzalloc(sizeof(struct notifier_block), GFP_KERNEL);
659         if (nb == NULL) {
660                 printk(KERN_ERR "dma_debug_add_bus: out of memory\n");
661                 return;
662         }
663
664         nb->notifier_call = dma_debug_device_change;
665
666         bus_register_notifier(bus, nb);
667 }
668
669 /*
670  * Let the architectures decide how many entries should be preallocated.
671  */
672 void dma_debug_init(u32 num_entries)
673 {
674         int i;
675
676         if (global_disable)
677                 return;
678
679         for (i = 0; i < HASH_SIZE; ++i) {
680                 INIT_LIST_HEAD(&dma_entry_hash[i].list);
681                 dma_entry_hash[i].lock = SPIN_LOCK_UNLOCKED;
682         }
683
684         if (dma_debug_fs_init() != 0) {
685                 printk(KERN_ERR "DMA-API: error creating debugfs entries "
686                                 "- disabling\n");
687                 global_disable = true;
688
689                 return;
690         }
691
692         if (req_entries)
693                 num_entries = req_entries;
694
695         if (prealloc_memory(num_entries) != 0) {
696                 printk(KERN_ERR "DMA-API: debugging out of memory error "
697                                 "- disabled\n");
698                 global_disable = true;
699
700                 return;
701         }
702
703         nr_total_entries = num_free_entries;
704
705         printk(KERN_INFO "DMA-API: debugging enabled by kernel config\n");
706 }
707
708 static __init int dma_debug_cmdline(char *str)
709 {
710         if (!str)
711                 return -EINVAL;
712
713         if (strncmp(str, "off", 3) == 0) {
714                 printk(KERN_INFO "DMA-API: debugging disabled on kernel "
715                                  "command line\n");
716                 global_disable = true;
717         }
718
719         return 0;
720 }
721
722 static __init int dma_debug_entries_cmdline(char *str)
723 {
724         int res;
725
726         if (!str)
727                 return -EINVAL;
728
729         res = get_option(&str, &req_entries);
730
731         if (!res)
732                 req_entries = 0;
733
734         return 0;
735 }
736
737 __setup("dma_debug=", dma_debug_cmdline);
738 __setup("dma_debug_entries=", dma_debug_entries_cmdline);
739
740 static void check_unmap(struct dma_debug_entry *ref)
741 {
742         struct dma_debug_entry *entry;
743         struct hash_bucket *bucket;
744         unsigned long flags;
745
746         if (dma_mapping_error(ref->dev, ref->dev_addr)) {
747                 err_printk(ref->dev, NULL, "DMA-API: device driver tries "
748                            "to free an invalid DMA memory address\n");
749                 return;
750         }
751
752         bucket = get_hash_bucket(ref, &flags);
753         entry = hash_bucket_find(bucket, ref);
754
755         if (!entry) {
756                 err_printk(ref->dev, NULL, "DMA-API: device driver tries "
757                            "to free DMA memory it has not allocated "
758                            "[device address=0x%016llx] [size=%llu bytes]\n",
759                            ref->dev_addr, ref->size);
760                 goto out;
761         }
762
763         if (ref->size != entry->size) {
764                 err_printk(ref->dev, entry, "DMA-API: device driver frees "
765                            "DMA memory with different size "
766                            "[device address=0x%016llx] [map size=%llu bytes] "
767                            "[unmap size=%llu bytes]\n",
768                            ref->dev_addr, entry->size, ref->size);
769         }
770
771         if (ref->type != entry->type) {
772                 err_printk(ref->dev, entry, "DMA-API: device driver frees "
773                            "DMA memory with wrong function "
774                            "[device address=0x%016llx] [size=%llu bytes] "
775                            "[mapped as %s] [unmapped as %s]\n",
776                            ref->dev_addr, ref->size,
777                            type2name[entry->type], type2name[ref->type]);
778         } else if ((entry->type == dma_debug_coherent) &&
779                    (ref->paddr != entry->paddr)) {
780                 err_printk(ref->dev, entry, "DMA-API: device driver frees "
781                            "DMA memory with different CPU address "
782                            "[device address=0x%016llx] [size=%llu bytes] "
783                            "[cpu alloc address=%p] [cpu free address=%p]",
784                            ref->dev_addr, ref->size,
785                            (void *)entry->paddr, (void *)ref->paddr);
786         }
787
788         if (ref->sg_call_ents && ref->type == dma_debug_sg &&
789             ref->sg_call_ents != entry->sg_call_ents) {
790                 err_printk(ref->dev, entry, "DMA-API: device driver frees "
791                            "DMA sg list with different entry count "
792                            "[map count=%d] [unmap count=%d]\n",
793                            entry->sg_call_ents, ref->sg_call_ents);
794         }
795
796         /*
797          * This may be no bug in reality - but most implementations of the
798          * DMA API don't handle this properly, so check for it here
799          */
800         if (ref->direction != entry->direction) {
801                 err_printk(ref->dev, entry, "DMA-API: device driver frees "
802                            "DMA memory with different direction "
803                            "[device address=0x%016llx] [size=%llu bytes] "
804                            "[mapped with %s] [unmapped with %s]\n",
805                            ref->dev_addr, ref->size,
806                            dir2name[entry->direction],
807                            dir2name[ref->direction]);
808         }
809
810         hash_bucket_del(entry);
811         dma_entry_free(entry);
812
813 out:
814         put_hash_bucket(bucket, &flags);
815 }
816
817 static void check_for_stack(struct device *dev, void *addr)
818 {
819         if (object_is_on_stack(addr))
820                 err_printk(dev, NULL, "DMA-API: device driver maps memory from"
821                                 "stack [addr=%p]\n", addr);
822 }
823
824 static inline bool overlap(void *addr, u64 size, void *start, void *end)
825 {
826         void *addr2 = (char *)addr + size;
827
828         return ((addr >= start && addr < end) ||
829                 (addr2 >= start && addr2 < end) ||
830                 ((addr < start) && (addr2 >= end)));
831 }
832
833 static void check_for_illegal_area(struct device *dev, void *addr, u64 size)
834 {
835         if (overlap(addr, size, _text, _etext) ||
836             overlap(addr, size, __start_rodata, __end_rodata))
837                 err_printk(dev, NULL, "DMA-API: device driver maps "
838                                 "memory from kernel text or rodata "
839                                 "[addr=%p] [size=%llu]\n", addr, size);
840 }
841
842 static void check_sync(struct device *dev, dma_addr_t addr,
843                        u64 size, u64 offset, int direction, bool to_cpu)
844 {
845         struct dma_debug_entry ref = {
846                 .dev            = dev,
847                 .dev_addr       = addr,
848                 .size           = size,
849                 .direction      = direction,
850         };
851         struct dma_debug_entry *entry;
852         struct hash_bucket *bucket;
853         unsigned long flags;
854
855         bucket = get_hash_bucket(&ref, &flags);
856
857         entry = hash_bucket_find(bucket, &ref);
858
859         if (!entry) {
860                 err_printk(dev, NULL, "DMA-API: device driver tries "
861                                 "to sync DMA memory it has not allocated "
862                                 "[device address=0x%016llx] [size=%llu bytes]\n",
863                                 (unsigned long long)addr, size);
864                 goto out;
865         }
866
867         if ((offset + size) > entry->size) {
868                 err_printk(dev, entry, "DMA-API: device driver syncs"
869                                 " DMA memory outside allocated range "
870                                 "[device address=0x%016llx] "
871                                 "[allocation size=%llu bytes] [sync offset=%llu] "
872                                 "[sync size=%llu]\n", entry->dev_addr, entry->size,
873                                 offset, size);
874         }
875
876         if (direction != entry->direction) {
877                 err_printk(dev, entry, "DMA-API: device driver syncs "
878                                 "DMA memory with different direction "
879                                 "[device address=0x%016llx] [size=%llu bytes] "
880                                 "[mapped with %s] [synced with %s]\n",
881                                 (unsigned long long)addr, entry->size,
882                                 dir2name[entry->direction],
883                                 dir2name[direction]);
884         }
885
886         if (entry->direction == DMA_BIDIRECTIONAL)
887                 goto out;
888
889         if (to_cpu && !(entry->direction == DMA_FROM_DEVICE) &&
890                       !(direction == DMA_TO_DEVICE))
891                 err_printk(dev, entry, "DMA-API: device driver syncs "
892                                 "device read-only DMA memory for cpu "
893                                 "[device address=0x%016llx] [size=%llu bytes] "
894                                 "[mapped with %s] [synced with %s]\n",
895                                 (unsigned long long)addr, entry->size,
896                                 dir2name[entry->direction],
897                                 dir2name[direction]);
898
899         if (!to_cpu && !(entry->direction == DMA_TO_DEVICE) &&
900                        !(direction == DMA_FROM_DEVICE))
901                 err_printk(dev, entry, "DMA-API: device driver syncs "
902                                 "device write-only DMA memory to device "
903                                 "[device address=0x%016llx] [size=%llu bytes] "
904                                 "[mapped with %s] [synced with %s]\n",
905                                 (unsigned long long)addr, entry->size,
906                                 dir2name[entry->direction],
907                                 dir2name[direction]);
908
909 out:
910         put_hash_bucket(bucket, &flags);
911
912 }
913
914 void debug_dma_map_page(struct device *dev, struct page *page, size_t offset,
915                         size_t size, int direction, dma_addr_t dma_addr,
916                         bool map_single)
917 {
918         struct dma_debug_entry *entry;
919
920         if (unlikely(global_disable))
921                 return;
922
923         if (unlikely(dma_mapping_error(dev, dma_addr)))
924                 return;
925
926         entry = dma_entry_alloc();
927         if (!entry)
928                 return;
929
930         entry->dev       = dev;
931         entry->type      = dma_debug_page;
932         entry->paddr     = page_to_phys(page) + offset;
933         entry->dev_addr  = dma_addr;
934         entry->size      = size;
935         entry->direction = direction;
936
937         if (map_single)
938                 entry->type = dma_debug_single;
939
940         if (!PageHighMem(page)) {
941                 void *addr = ((char *)page_address(page)) + offset;
942                 check_for_stack(dev, addr);
943                 check_for_illegal_area(dev, addr, size);
944         }
945
946         add_dma_entry(entry);
947 }
948 EXPORT_SYMBOL(debug_dma_map_page);
949
950 void debug_dma_unmap_page(struct device *dev, dma_addr_t addr,
951                           size_t size, int direction, bool map_single)
952 {
953         struct dma_debug_entry ref = {
954                 .type           = dma_debug_page,
955                 .dev            = dev,
956                 .dev_addr       = addr,
957                 .size           = size,
958                 .direction      = direction,
959         };
960
961         if (unlikely(global_disable))
962                 return;
963
964         if (map_single)
965                 ref.type = dma_debug_single;
966
967         check_unmap(&ref);
968 }
969 EXPORT_SYMBOL(debug_dma_unmap_page);
970
971 void debug_dma_map_sg(struct device *dev, struct scatterlist *sg,
972                       int nents, int mapped_ents, int direction)
973 {
974         struct dma_debug_entry *entry;
975         struct scatterlist *s;
976         int i;
977
978         if (unlikely(global_disable))
979                 return;
980
981         for_each_sg(sg, s, mapped_ents, i) {
982                 entry = dma_entry_alloc();
983                 if (!entry)
984                         return;
985
986                 entry->type           = dma_debug_sg;
987                 entry->dev            = dev;
988                 entry->paddr          = sg_phys(s);
989                 entry->size           = sg_dma_len(s);
990                 entry->dev_addr       = sg_dma_address(s);
991                 entry->direction      = direction;
992                 entry->sg_call_ents   = nents;
993                 entry->sg_mapped_ents = mapped_ents;
994
995                 if (!PageHighMem(sg_page(s))) {
996                         check_for_stack(dev, sg_virt(s));
997                         check_for_illegal_area(dev, sg_virt(s), sg_dma_len(s));
998                 }
999
1000                 add_dma_entry(entry);
1001         }
1002 }
1003 EXPORT_SYMBOL(debug_dma_map_sg);
1004
1005 static int get_nr_mapped_entries(struct device *dev, struct scatterlist *s)
1006 {
1007         struct dma_debug_entry *entry;
1008         struct hash_bucket *bucket;
1009         unsigned long flags;
1010         int mapped_ents = 0;
1011         struct dma_debug_entry ref;
1012
1013         ref.dev = dev;
1014         ref.dev_addr = sg_dma_address(s);
1015         ref.size = sg_dma_len(s),
1016
1017         bucket = get_hash_bucket(&ref, &flags);
1018         entry = hash_bucket_find(bucket, &ref);
1019         if (entry)
1020                 mapped_ents = entry->sg_mapped_ents;
1021         put_hash_bucket(bucket, &flags);
1022
1023         return mapped_ents;
1024 }
1025
1026 void debug_dma_unmap_sg(struct device *dev, struct scatterlist *sglist,
1027                         int nelems, int dir)
1028 {
1029         struct scatterlist *s;
1030         int mapped_ents = 0, i;
1031
1032         if (unlikely(global_disable))
1033                 return;
1034
1035         for_each_sg(sglist, s, nelems, i) {
1036
1037                 struct dma_debug_entry ref = {
1038                         .type           = dma_debug_sg,
1039                         .dev            = dev,
1040                         .paddr          = sg_phys(s),
1041                         .dev_addr       = sg_dma_address(s),
1042                         .size           = sg_dma_len(s),
1043                         .direction      = dir,
1044                         .sg_call_ents   = 0,
1045                 };
1046
1047                 if (mapped_ents && i >= mapped_ents)
1048                         break;
1049
1050                 if (!i) {
1051                         ref.sg_call_ents = nelems;
1052                         mapped_ents = get_nr_mapped_entries(dev, s);
1053                 }
1054
1055                 check_unmap(&ref);
1056         }
1057 }
1058 EXPORT_SYMBOL(debug_dma_unmap_sg);
1059
1060 void debug_dma_alloc_coherent(struct device *dev, size_t size,
1061                               dma_addr_t dma_addr, void *virt)
1062 {
1063         struct dma_debug_entry *entry;
1064
1065         if (unlikely(global_disable))
1066                 return;
1067
1068         if (unlikely(virt == NULL))
1069                 return;
1070
1071         entry = dma_entry_alloc();
1072         if (!entry)
1073                 return;
1074
1075         entry->type      = dma_debug_coherent;
1076         entry->dev       = dev;
1077         entry->paddr     = virt_to_phys(virt);
1078         entry->size      = size;
1079         entry->dev_addr  = dma_addr;
1080         entry->direction = DMA_BIDIRECTIONAL;
1081
1082         add_dma_entry(entry);
1083 }
1084 EXPORT_SYMBOL(debug_dma_alloc_coherent);
1085
1086 void debug_dma_free_coherent(struct device *dev, size_t size,
1087                          void *virt, dma_addr_t addr)
1088 {
1089         struct dma_debug_entry ref = {
1090                 .type           = dma_debug_coherent,
1091                 .dev            = dev,
1092                 .paddr          = virt_to_phys(virt),
1093                 .dev_addr       = addr,
1094                 .size           = size,
1095                 .direction      = DMA_BIDIRECTIONAL,
1096         };
1097
1098         if (unlikely(global_disable))
1099                 return;
1100
1101         check_unmap(&ref);
1102 }
1103 EXPORT_SYMBOL(debug_dma_free_coherent);
1104
1105 void debug_dma_sync_single_for_cpu(struct device *dev, dma_addr_t dma_handle,
1106                                    size_t size, int direction)
1107 {
1108         if (unlikely(global_disable))
1109                 return;
1110
1111         check_sync(dev, dma_handle, size, 0, direction, true);
1112 }
1113 EXPORT_SYMBOL(debug_dma_sync_single_for_cpu);
1114
1115 void debug_dma_sync_single_for_device(struct device *dev,
1116                                       dma_addr_t dma_handle, size_t size,
1117                                       int direction)
1118 {
1119         if (unlikely(global_disable))
1120                 return;
1121
1122         check_sync(dev, dma_handle, size, 0, direction, false);
1123 }
1124 EXPORT_SYMBOL(debug_dma_sync_single_for_device);
1125
1126 void debug_dma_sync_single_range_for_cpu(struct device *dev,
1127                                          dma_addr_t dma_handle,
1128                                          unsigned long offset, size_t size,
1129                                          int direction)
1130 {
1131         if (unlikely(global_disable))
1132                 return;
1133
1134         check_sync(dev, dma_handle, size, offset, direction, true);
1135 }
1136 EXPORT_SYMBOL(debug_dma_sync_single_range_for_cpu);
1137
1138 void debug_dma_sync_single_range_for_device(struct device *dev,
1139                                             dma_addr_t dma_handle,
1140                                             unsigned long offset,
1141                                             size_t size, int direction)
1142 {
1143         if (unlikely(global_disable))
1144                 return;
1145
1146         check_sync(dev, dma_handle, size, offset, direction, false);
1147 }
1148 EXPORT_SYMBOL(debug_dma_sync_single_range_for_device);
1149
1150 void debug_dma_sync_sg_for_cpu(struct device *dev, struct scatterlist *sg,
1151                                int nelems, int direction)
1152 {
1153         struct scatterlist *s;
1154         int mapped_ents = 0, i;
1155
1156         if (unlikely(global_disable))
1157                 return;
1158
1159         for_each_sg(sg, s, nelems, i) {
1160                 if (!i)
1161                         mapped_ents = get_nr_mapped_entries(dev, s);
1162
1163                 if (i >= mapped_ents)
1164                         break;
1165
1166                 check_sync(dev, sg_dma_address(s), sg_dma_len(s), 0,
1167                            direction, true);
1168         }
1169 }
1170 EXPORT_SYMBOL(debug_dma_sync_sg_for_cpu);
1171
1172 void debug_dma_sync_sg_for_device(struct device *dev, struct scatterlist *sg,
1173                                   int nelems, int direction)
1174 {
1175         struct scatterlist *s;
1176         int mapped_ents = 0, i;
1177
1178         if (unlikely(global_disable))
1179                 return;
1180
1181         for_each_sg(sg, s, nelems, i) {
1182                 if (!i)
1183                         mapped_ents = get_nr_mapped_entries(dev, s);
1184
1185                 if (i >= mapped_ents)
1186                         break;
1187
1188                 check_sync(dev, sg_dma_address(s), sg_dma_len(s), 0,
1189                            direction, false);
1190         }
1191 }
1192 EXPORT_SYMBOL(debug_dma_sync_sg_for_device);
1193
1194 static int __init dma_debug_driver_setup(char *str)
1195 {
1196         int i;
1197
1198         for (i = 0; i < NAME_MAX_LEN - 1; ++i, ++str) {
1199                 current_driver_name[i] = *str;
1200                 if (*str == 0)
1201                         break;
1202         }
1203
1204         if (current_driver_name[0])
1205                 printk(KERN_INFO "DMA-API: enable driver filter for "
1206                                  "driver [%s]\n", current_driver_name);
1207
1208
1209         return 1;
1210 }
1211 __setup("dma_debug_driver=", dma_debug_driver_setup);