root/kernel/dma/debug.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. dma_debug_disabled
  2. dump_entry_trace
  3. driver_filter
  4. hash_fn
  5. get_hash_bucket
  6. put_hash_bucket
  7. exact_match
  8. containing_match
  9. __hash_bucket_find
  10. bucket_find_exact
  11. bucket_find_contain
  12. hash_bucket_add
  13. hash_bucket_del
  14. phys_addr
  15. debug_dma_dump_mappings
  16. to_cacheline_number
  17. active_cacheline_read_overlap
  18. active_cacheline_set_overlap
  19. active_cacheline_inc_overlap
  20. active_cacheline_dec_overlap
  21. active_cacheline_insert
  22. active_cacheline_remove
  23. debug_dma_assert_idle
  24. add_dma_entry
  25. dma_debug_create_entries
  26. __dma_entry_alloc
  27. __dma_entry_alloc_check_leak
  28. dma_entry_alloc
  29. dma_entry_free
  30. filter_read
  31. filter_write
  32. dump_show
  33. dma_debug_fs_init
  34. device_dma_allocations
  35. dma_debug_device_change
  36. dma_debug_add_bus
  37. dma_debug_init
  38. dma_debug_cmdline
  39. dma_debug_entries_cmdline
  40. check_unmap
  41. check_for_stack
  42. overlap
  43. check_for_illegal_area
  44. check_sync
  45. check_sg_segment
  46. debug_dma_map_single
  47. debug_dma_map_page
  48. debug_dma_mapping_error
  49. debug_dma_unmap_page
  50. debug_dma_map_sg
  51. get_nr_mapped_entries
  52. debug_dma_unmap_sg
  53. debug_dma_alloc_coherent
  54. debug_dma_free_coherent
  55. debug_dma_map_resource
  56. debug_dma_unmap_resource
  57. debug_dma_sync_single_for_cpu
  58. debug_dma_sync_single_for_device
  59. debug_dma_sync_sg_for_cpu
  60. debug_dma_sync_sg_for_device
  61. dma_debug_driver_setup

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

/* [<][>][^][v][top][bottom][index][help] */