1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * kernel/lockdep.c 4 * 5 * Runtime locking correctness validator 6 * 7 * Started by Ingo Molnar: 8 * 9 * Copyright (C) 2006,2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com> 10 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra 11 * 12 * this code maps all the lock dependencies as they occur in a live kernel 13 * and will warn about the following classes of locking bugs: 14 * 15 * - lock inversion scenarios 16 * - circular lock dependencies 17 * - hardirq/softirq safe/unsafe locking bugs 18 * 19 * Bugs are reported even if the current locking scenario does not cause 20 * any deadlock at this point. 21 * 22 * I.e. if anytime in the past two locks were taken in a different order, 23 * even if it happened for another task, even if those were different 24 * locks (but of the same class as this lock), this code will detect it. 25 * 26 * Thanks to Arjan van de Ven for coming up with the initial idea of 27 * mapping lock dependencies runtime. 28 */ 29 #define DISABLE_BRANCH_PROFILING 30 #include <linux/mutex.h> 31 #include <linux/sched.h> 32 #include <linux/sched/clock.h> 33 #include <linux/sched/task.h> 34 #include <linux/sched/mm.h> 35 #include <linux/delay.h> 36 #include <linux/module.h> 37 #include <linux/proc_fs.h> 38 #include <linux/seq_file.h> 39 #include <linux/spinlock.h> 40 #include <linux/kallsyms.h> 41 #include <linux/interrupt.h> 42 #include <linux/stacktrace.h> 43 #include <linux/debug_locks.h> 44 #include <linux/irqflags.h> 45 #include <linux/utsname.h> 46 #include <linux/hash.h> 47 #include <linux/ftrace.h> 48 #include <linux/stringify.h> 49 #include <linux/bitmap.h> 50 #include <linux/bitops.h> 51 #include <linux/gfp.h> 52 #include <linux/random.h> 53 #include <linux/jhash.h> 54 #include <linux/nmi.h> 55 #include <linux/rcupdate.h> 56 #include <linux/kprobes.h> 57 #include <linux/lockdep.h> 58 #include <linux/context_tracking.h> 59 #include <linux/console.h> 60 #include <linux/kasan.h> 61 62 #include <asm/sections.h> 63 64 #include "lockdep_internals.h" 65 #include "lock_events.h" 66 67 #include <trace/events/lock.h> 68 69 #ifdef CONFIG_PROVE_LOCKING 70 static int prove_locking = 1; 71 module_param(prove_locking, int, 0644); 72 #else 73 #define prove_locking 0 74 #endif 75 76 #ifdef CONFIG_LOCK_STAT 77 static int lock_stat = 1; 78 module_param(lock_stat, int, 0644); 79 #else 80 #define lock_stat 0 81 #endif 82 83 #ifdef CONFIG_SYSCTL 84 static const struct ctl_table kern_lockdep_table[] = { 85 #ifdef CONFIG_PROVE_LOCKING 86 { 87 .procname = "prove_locking", 88 .data = &prove_locking, 89 .maxlen = sizeof(int), 90 .mode = 0644, 91 .proc_handler = proc_dointvec, 92 }, 93 #endif /* CONFIG_PROVE_LOCKING */ 94 #ifdef CONFIG_LOCK_STAT 95 { 96 .procname = "lock_stat", 97 .data = &lock_stat, 98 .maxlen = sizeof(int), 99 .mode = 0644, 100 .proc_handler = proc_dointvec, 101 }, 102 #endif /* CONFIG_LOCK_STAT */ 103 }; 104 105 static __init int kernel_lockdep_sysctls_init(void) 106 { 107 register_sysctl_init("kernel", kern_lockdep_table); 108 return 0; 109 } 110 late_initcall(kernel_lockdep_sysctls_init); 111 #endif /* CONFIG_SYSCTL */ 112 113 DEFINE_PER_CPU(unsigned int, lockdep_recursion); 114 EXPORT_PER_CPU_SYMBOL_GPL(lockdep_recursion); 115 116 static __always_inline bool lockdep_enabled(void) 117 { 118 if (!debug_locks) 119 return false; 120 121 if (this_cpu_read(lockdep_recursion)) 122 return false; 123 124 if (current->lockdep_recursion) 125 return false; 126 127 return true; 128 } 129 130 /* 131 * lockdep_lock: protects the lockdep graph, the hashes and the 132 * class/list/hash allocators. 133 * 134 * This is one of the rare exceptions where it's justified 135 * to use a raw spinlock - we really dont want the spinlock 136 * code to recurse back into the lockdep code... 137 */ 138 static arch_spinlock_t __lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED; 139 static struct task_struct *__owner; 140 141 static inline void lockdep_lock(void) 142 { 143 DEBUG_LOCKS_WARN_ON(!irqs_disabled()); 144 145 __this_cpu_inc(lockdep_recursion); 146 arch_spin_lock(&__lock); 147 __owner = current; 148 } 149 150 static inline void lockdep_unlock(void) 151 { 152 DEBUG_LOCKS_WARN_ON(!irqs_disabled()); 153 154 if (debug_locks && DEBUG_LOCKS_WARN_ON(__owner != current)) 155 return; 156 157 __owner = NULL; 158 arch_spin_unlock(&__lock); 159 __this_cpu_dec(lockdep_recursion); 160 } 161 162 #ifdef CONFIG_PROVE_LOCKING 163 static inline bool lockdep_assert_locked(void) 164 { 165 return DEBUG_LOCKS_WARN_ON(__owner != current); 166 } 167 #endif 168 169 static struct task_struct *lockdep_selftest_task_struct; 170 171 172 static int graph_lock(void) 173 { 174 lockdep_lock(); 175 lockevent_inc(lockdep_lock); 176 /* 177 * Make sure that if another CPU detected a bug while 178 * walking the graph we dont change it (while the other 179 * CPU is busy printing out stuff with the graph lock 180 * dropped already) 181 */ 182 if (!debug_locks) { 183 lockdep_unlock(); 184 return 0; 185 } 186 return 1; 187 } 188 189 static inline void graph_unlock(void) 190 { 191 lockdep_unlock(); 192 } 193 194 /* 195 * Turn lock debugging off and return with 0 if it was off already, 196 * and also release the graph lock: 197 */ 198 static inline int debug_locks_off_graph_unlock(void) 199 { 200 int ret = debug_locks_off(); 201 202 lockdep_unlock(); 203 204 return ret; 205 } 206 207 unsigned long nr_list_entries; 208 static struct lock_list list_entries[MAX_LOCKDEP_ENTRIES]; 209 static DECLARE_BITMAP(list_entries_in_use, MAX_LOCKDEP_ENTRIES); 210 211 /* 212 * All data structures here are protected by the global debug_lock. 213 * 214 * nr_lock_classes is the number of elements of lock_classes[] that is 215 * in use. 216 */ 217 #define KEYHASH_BITS (MAX_LOCKDEP_KEYS_BITS - 1) 218 #define KEYHASH_SIZE (1UL << KEYHASH_BITS) 219 static struct hlist_head lock_keys_hash[KEYHASH_SIZE]; 220 unsigned long nr_lock_classes; 221 unsigned long nr_zapped_classes; 222 unsigned long nr_dynamic_keys; 223 unsigned long max_lock_class_idx; 224 struct lock_class lock_classes[MAX_LOCKDEP_KEYS]; 225 DECLARE_BITMAP(lock_classes_in_use, MAX_LOCKDEP_KEYS); 226 227 static inline struct lock_class *hlock_class(struct held_lock *hlock) 228 { 229 unsigned int class_idx = hlock->class_idx; 230 231 /* Don't re-read hlock->class_idx, can't use READ_ONCE() on bitfield */ 232 barrier(); 233 234 if (!test_bit(class_idx, lock_classes_in_use)) { 235 /* 236 * Someone passed in garbage, we give up. 237 */ 238 DEBUG_LOCKS_WARN_ON(1); 239 return NULL; 240 } 241 242 /* 243 * At this point, if the passed hlock->class_idx is still garbage, 244 * we just have to live with it 245 */ 246 return lock_classes + class_idx; 247 } 248 249 #ifdef CONFIG_LOCK_STAT 250 static DEFINE_PER_CPU(struct lock_class_stats[MAX_LOCKDEP_KEYS], cpu_lock_stats); 251 252 static inline u64 lockstat_clock(void) 253 { 254 return local_clock(); 255 } 256 257 static int lock_point(unsigned long points[], unsigned long ip) 258 { 259 int i; 260 261 for (i = 0; i < LOCKSTAT_POINTS; i++) { 262 if (points[i] == 0) { 263 points[i] = ip; 264 break; 265 } 266 if (points[i] == ip) 267 break; 268 } 269 270 return i; 271 } 272 273 static void lock_time_inc(struct lock_time *lt, u64 time) 274 { 275 if (time > lt->max) 276 lt->max = time; 277 278 if (time < lt->min || !lt->nr) 279 lt->min = time; 280 281 lt->total += time; 282 lt->nr++; 283 } 284 285 static inline void lock_time_add(struct lock_time *src, struct lock_time *dst) 286 { 287 if (!src->nr) 288 return; 289 290 if (src->max > dst->max) 291 dst->max = src->max; 292 293 if (src->min < dst->min || !dst->nr) 294 dst->min = src->min; 295 296 dst->total += src->total; 297 dst->nr += src->nr; 298 } 299 300 struct lock_class_stats lock_stats(struct lock_class *class) 301 { 302 struct lock_class_stats stats; 303 int cpu, i; 304 305 memset(&stats, 0, sizeof(struct lock_class_stats)); 306 for_each_possible_cpu(cpu) { 307 struct lock_class_stats *pcs = 308 &per_cpu(cpu_lock_stats, cpu)[class - lock_classes]; 309 310 for (i = 0; i < ARRAY_SIZE(stats.contention_point); i++) 311 stats.contention_point[i] += pcs->contention_point[i]; 312 313 for (i = 0; i < ARRAY_SIZE(stats.contending_point); i++) 314 stats.contending_point[i] += pcs->contending_point[i]; 315 316 lock_time_add(&pcs->read_waittime, &stats.read_waittime); 317 lock_time_add(&pcs->write_waittime, &stats.write_waittime); 318 319 lock_time_add(&pcs->read_holdtime, &stats.read_holdtime); 320 lock_time_add(&pcs->write_holdtime, &stats.write_holdtime); 321 322 for (i = 0; i < ARRAY_SIZE(stats.bounces); i++) 323 stats.bounces[i] += pcs->bounces[i]; 324 } 325 326 return stats; 327 } 328 329 void clear_lock_stats(struct lock_class *class) 330 { 331 int cpu; 332 333 for_each_possible_cpu(cpu) { 334 struct lock_class_stats *cpu_stats = 335 &per_cpu(cpu_lock_stats, cpu)[class - lock_classes]; 336 337 memset(cpu_stats, 0, sizeof(struct lock_class_stats)); 338 } 339 memset(class->contention_point, 0, sizeof(class->contention_point)); 340 memset(class->contending_point, 0, sizeof(class->contending_point)); 341 } 342 343 static struct lock_class_stats *get_lock_stats(struct lock_class *class) 344 { 345 return &this_cpu_ptr(cpu_lock_stats)[class - lock_classes]; 346 } 347 348 static void lock_release_holdtime(struct held_lock *hlock) 349 { 350 struct lock_class_stats *stats; 351 u64 holdtime; 352 353 if (!lock_stat) 354 return; 355 356 holdtime = lockstat_clock() - hlock->holdtime_stamp; 357 358 stats = get_lock_stats(hlock_class(hlock)); 359 if (hlock->read) 360 lock_time_inc(&stats->read_holdtime, holdtime); 361 else 362 lock_time_inc(&stats->write_holdtime, holdtime); 363 } 364 #else 365 static inline void lock_release_holdtime(struct held_lock *hlock) 366 { 367 } 368 #endif 369 370 /* 371 * We keep a global list of all lock classes. The list is only accessed with 372 * the lockdep spinlock lock held. free_lock_classes is a list with free 373 * elements. These elements are linked together by the lock_entry member in 374 * struct lock_class. 375 */ 376 static LIST_HEAD(all_lock_classes); 377 static LIST_HEAD(free_lock_classes); 378 379 /** 380 * struct pending_free - information about data structures about to be freed 381 * @zapped: Head of a list with struct lock_class elements. 382 * @lock_chains_being_freed: Bitmap that indicates which lock_chains[] elements 383 * are about to be freed. 384 */ 385 struct pending_free { 386 struct list_head zapped; 387 DECLARE_BITMAP(lock_chains_being_freed, MAX_LOCKDEP_CHAINS); 388 }; 389 390 /** 391 * struct delayed_free - data structures used for delayed freeing 392 * 393 * A data structure for delayed freeing of data structures that may be 394 * accessed by RCU readers at the time these were freed. 395 * 396 * @rcu_head: Used to schedule an RCU callback for freeing data structures. 397 * @index: Index of @pf to which freed data structures are added. 398 * @scheduled: Whether or not an RCU callback has been scheduled. 399 * @pf: Array with information about data structures about to be freed. 400 */ 401 static struct delayed_free { 402 struct rcu_head rcu_head; 403 int index; 404 int scheduled; 405 struct pending_free pf[2]; 406 } delayed_free; 407 408 /* 409 * The lockdep classes are in a hash-table as well, for fast lookup: 410 */ 411 #define CLASSHASH_BITS (MAX_LOCKDEP_KEYS_BITS - 1) 412 #define CLASSHASH_SIZE (1UL << CLASSHASH_BITS) 413 #define __classhashfn(key) hash_long((unsigned long)key, CLASSHASH_BITS) 414 #define classhashentry(key) (classhash_table + __classhashfn((key))) 415 416 static struct hlist_head classhash_table[CLASSHASH_SIZE]; 417 418 /* 419 * We put the lock dependency chains into a hash-table as well, to cache 420 * their existence: 421 */ 422 #define CHAINHASH_BITS (MAX_LOCKDEP_CHAINS_BITS-1) 423 #define CHAINHASH_SIZE (1UL << CHAINHASH_BITS) 424 #define __chainhashfn(chain) hash_long(chain, CHAINHASH_BITS) 425 #define chainhashentry(chain) (chainhash_table + __chainhashfn((chain))) 426 427 static struct hlist_head chainhash_table[CHAINHASH_SIZE]; 428 429 /* 430 * the id of held_lock 431 */ 432 static inline u16 hlock_id(struct held_lock *hlock) 433 { 434 BUILD_BUG_ON(MAX_LOCKDEP_KEYS_BITS + 2 > 16); 435 436 return (hlock->class_idx | (hlock->read << MAX_LOCKDEP_KEYS_BITS)); 437 } 438 439 static inline __maybe_unused unsigned int chain_hlock_class_idx(u16 hlock_id) 440 { 441 return hlock_id & (MAX_LOCKDEP_KEYS - 1); 442 } 443 444 /* 445 * The hash key of the lock dependency chains is a hash itself too: 446 * it's a hash of all locks taken up to that lock, including that lock. 447 * It's a 64-bit hash, because it's important for the keys to be 448 * unique. 449 */ 450 static inline u64 iterate_chain_key(u64 key, u32 idx) 451 { 452 u32 k0 = key, k1 = key >> 32; 453 454 __jhash_mix(idx, k0, k1); /* Macro that modifies arguments! */ 455 456 return k0 | (u64)k1 << 32; 457 } 458 459 void lockdep_init_task(struct task_struct *task) 460 { 461 task->lockdep_depth = 0; /* no locks held yet */ 462 task->curr_chain_key = INITIAL_CHAIN_KEY; 463 task->lockdep_recursion = 0; 464 } 465 466 static __always_inline void lockdep_recursion_inc(void) 467 { 468 __this_cpu_inc(lockdep_recursion); 469 } 470 471 static __always_inline void lockdep_recursion_finish(void) 472 { 473 if (WARN_ON_ONCE(__this_cpu_dec_return(lockdep_recursion))) 474 __this_cpu_write(lockdep_recursion, 0); 475 } 476 477 void lockdep_set_selftest_task(struct task_struct *task) 478 { 479 lockdep_selftest_task_struct = task; 480 } 481 482 /* 483 * Debugging switches: 484 */ 485 486 #define VERBOSE 0 487 #define VERY_VERBOSE 0 488 489 #if VERBOSE 490 # define HARDIRQ_VERBOSE 1 491 # define SOFTIRQ_VERBOSE 1 492 #else 493 # define HARDIRQ_VERBOSE 0 494 # define SOFTIRQ_VERBOSE 0 495 #endif 496 497 #if VERBOSE || HARDIRQ_VERBOSE || SOFTIRQ_VERBOSE 498 /* 499 * Quick filtering for interesting events: 500 */ 501 static int class_filter(struct lock_class *class) 502 { 503 #if 0 504 /* Example */ 505 if (class->name_version == 1 && 506 !strcmp(class->name, "lockname")) 507 return 1; 508 if (class->name_version == 1 && 509 !strcmp(class->name, "&struct->lockfield")) 510 return 1; 511 #endif 512 /* Filter everything else. 1 would be to allow everything else */ 513 return 0; 514 } 515 #endif 516 517 static int verbose(struct lock_class *class) 518 { 519 #if VERBOSE 520 return class_filter(class); 521 #endif 522 return 0; 523 } 524 525 static void print_lockdep_off(const char *bug_msg) 526 { 527 printk(KERN_DEBUG "%s\n", bug_msg); 528 printk(KERN_DEBUG "turning off the locking correctness validator.\n"); 529 #ifdef CONFIG_LOCK_STAT 530 printk(KERN_DEBUG "Please attach the output of /proc/lock_stat to the bug report\n"); 531 #endif 532 } 533 534 unsigned long nr_stack_trace_entries; 535 536 #ifdef CONFIG_PROVE_LOCKING 537 /** 538 * struct lock_trace - single stack backtrace 539 * @hash_entry: Entry in a stack_trace_hash[] list. 540 * @hash: jhash() of @entries. 541 * @nr_entries: Number of entries in @entries. 542 * @entries: Actual stack backtrace. 543 */ 544 struct lock_trace { 545 struct hlist_node hash_entry; 546 u32 hash; 547 u32 nr_entries; 548 unsigned long entries[] __aligned(sizeof(unsigned long)); 549 }; 550 #define LOCK_TRACE_SIZE_IN_LONGS \ 551 (sizeof(struct lock_trace) / sizeof(unsigned long)) 552 /* 553 * Stack-trace: sequence of lock_trace structures. Protected by the graph_lock. 554 */ 555 static unsigned long stack_trace[MAX_STACK_TRACE_ENTRIES]; 556 static struct hlist_head stack_trace_hash[STACK_TRACE_HASH_SIZE]; 557 558 static bool traces_identical(struct lock_trace *t1, struct lock_trace *t2) 559 { 560 return t1->hash == t2->hash && t1->nr_entries == t2->nr_entries && 561 memcmp(t1->entries, t2->entries, 562 t1->nr_entries * sizeof(t1->entries[0])) == 0; 563 } 564 565 static struct lock_trace *save_trace(void) 566 { 567 struct lock_trace *trace, *t2; 568 struct hlist_head *hash_head; 569 u32 hash; 570 int max_entries; 571 572 BUILD_BUG_ON_NOT_POWER_OF_2(STACK_TRACE_HASH_SIZE); 573 BUILD_BUG_ON(LOCK_TRACE_SIZE_IN_LONGS >= MAX_STACK_TRACE_ENTRIES); 574 575 trace = (struct lock_trace *)(stack_trace + nr_stack_trace_entries); 576 max_entries = MAX_STACK_TRACE_ENTRIES - nr_stack_trace_entries - 577 LOCK_TRACE_SIZE_IN_LONGS; 578 579 if (max_entries <= 0) { 580 if (!debug_locks_off_graph_unlock()) 581 return NULL; 582 583 nbcon_cpu_emergency_enter(); 584 print_lockdep_off("BUG: MAX_STACK_TRACE_ENTRIES too low!"); 585 dump_stack(); 586 nbcon_cpu_emergency_exit(); 587 588 return NULL; 589 } 590 trace->nr_entries = stack_trace_save(trace->entries, max_entries, 3); 591 592 hash = jhash(trace->entries, trace->nr_entries * 593 sizeof(trace->entries[0]), 0); 594 trace->hash = hash; 595 hash_head = stack_trace_hash + (hash & (STACK_TRACE_HASH_SIZE - 1)); 596 hlist_for_each_entry(t2, hash_head, hash_entry) { 597 if (traces_identical(trace, t2)) 598 return t2; 599 } 600 nr_stack_trace_entries += LOCK_TRACE_SIZE_IN_LONGS + trace->nr_entries; 601 hlist_add_head(&trace->hash_entry, hash_head); 602 603 return trace; 604 } 605 606 /* Return the number of stack traces in the stack_trace[] array. */ 607 u64 lockdep_stack_trace_count(void) 608 { 609 struct lock_trace *trace; 610 u64 c = 0; 611 int i; 612 613 for (i = 0; i < ARRAY_SIZE(stack_trace_hash); i++) { 614 hlist_for_each_entry(trace, &stack_trace_hash[i], hash_entry) { 615 c++; 616 } 617 } 618 619 return c; 620 } 621 622 /* Return the number of stack hash chains that have at least one stack trace. */ 623 u64 lockdep_stack_hash_count(void) 624 { 625 u64 c = 0; 626 int i; 627 628 for (i = 0; i < ARRAY_SIZE(stack_trace_hash); i++) 629 if (!hlist_empty(&stack_trace_hash[i])) 630 c++; 631 632 return c; 633 } 634 #endif 635 636 unsigned int nr_hardirq_chains; 637 unsigned int nr_softirq_chains; 638 unsigned int nr_process_chains; 639 unsigned int max_lockdep_depth; 640 641 #ifdef CONFIG_DEBUG_LOCKDEP 642 /* 643 * Various lockdep statistics: 644 */ 645 DEFINE_PER_CPU(struct lockdep_stats, lockdep_stats); 646 #endif 647 648 #ifdef CONFIG_PROVE_LOCKING 649 /* 650 * Locking printouts: 651 */ 652 653 #define __USAGE(__STATE) \ 654 [LOCK_USED_IN_##__STATE] = "IN-"__stringify(__STATE)"-W", \ 655 [LOCK_ENABLED_##__STATE] = __stringify(__STATE)"-ON-W", \ 656 [LOCK_USED_IN_##__STATE##_READ] = "IN-"__stringify(__STATE)"-R",\ 657 [LOCK_ENABLED_##__STATE##_READ] = __stringify(__STATE)"-ON-R", 658 659 static const char *usage_str[] = 660 { 661 #define LOCKDEP_STATE(__STATE) __USAGE(__STATE) 662 #include "lockdep_states.h" 663 #undef LOCKDEP_STATE 664 [LOCK_USED] = "INITIAL USE", 665 [LOCK_USED_READ] = "INITIAL READ USE", 666 /* abused as string storage for verify_lock_unused() */ 667 [LOCK_USAGE_STATES] = "IN-NMI", 668 }; 669 #endif 670 671 const char *__get_key_name(const struct lockdep_subclass_key *key, char *str) 672 { 673 return kallsyms_lookup((unsigned long)key, NULL, NULL, NULL, str); 674 } 675 676 static inline unsigned long lock_flag(enum lock_usage_bit bit) 677 { 678 return 1UL << bit; 679 } 680 681 static char get_usage_char(struct lock_class *class, enum lock_usage_bit bit) 682 { 683 /* 684 * The usage character defaults to '.' (i.e., irqs disabled and not in 685 * irq context), which is the safest usage category. 686 */ 687 char c = '.'; 688 689 /* 690 * The order of the following usage checks matters, which will 691 * result in the outcome character as follows: 692 * 693 * - '+': irq is enabled and not in irq context 694 * - '-': in irq context and irq is disabled 695 * - '?': in irq context and irq is enabled 696 */ 697 if (class->usage_mask & lock_flag(bit + LOCK_USAGE_DIR_MASK)) { 698 c = '+'; 699 if (class->usage_mask & lock_flag(bit)) 700 c = '?'; 701 } else if (class->usage_mask & lock_flag(bit)) 702 c = '-'; 703 704 return c; 705 } 706 707 void get_usage_chars(struct lock_class *class, char usage[LOCK_USAGE_CHARS]) 708 { 709 int i = 0; 710 711 #define LOCKDEP_STATE(__STATE) \ 712 usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE); \ 713 usage[i++] = get_usage_char(class, LOCK_USED_IN_##__STATE##_READ); 714 #include "lockdep_states.h" 715 #undef LOCKDEP_STATE 716 717 usage[i] = '\0'; 718 } 719 720 static void __print_lock_name(struct held_lock *hlock, struct lock_class *class) 721 { 722 char str[KSYM_NAME_LEN]; 723 const char *name; 724 725 name = class->name; 726 if (!name) { 727 name = __get_key_name(class->key, str); 728 printk(KERN_CONT "%s", name); 729 } else { 730 printk(KERN_CONT "%s", name); 731 if (class->name_version > 1) 732 printk(KERN_CONT "#%d", class->name_version); 733 if (class->subclass) 734 printk(KERN_CONT "/%d", class->subclass); 735 if (hlock && class->print_fn) 736 class->print_fn(hlock->instance); 737 } 738 } 739 740 static void print_lock_name(struct held_lock *hlock, struct lock_class *class) 741 { 742 char usage[LOCK_USAGE_CHARS]; 743 744 get_usage_chars(class, usage); 745 746 printk(KERN_CONT " ("); 747 __print_lock_name(hlock, class); 748 printk(KERN_CONT "){%s}-{%d:%d}", usage, 749 class->wait_type_outer ?: class->wait_type_inner, 750 class->wait_type_inner); 751 } 752 753 static void print_lockdep_cache(struct lockdep_map *lock) 754 { 755 const char *name; 756 char str[KSYM_NAME_LEN]; 757 758 name = lock->name; 759 if (!name) 760 name = __get_key_name(lock->key->subkeys, str); 761 762 printk(KERN_CONT "%s", name); 763 } 764 765 static void print_lock(struct held_lock *hlock) 766 { 767 /* 768 * We can be called locklessly through debug_show_all_locks() so be 769 * extra careful, the hlock might have been released and cleared. 770 * 771 * If this indeed happens, lets pretend it does not hurt to continue 772 * to print the lock unless the hlock class_idx does not point to a 773 * registered class. The rationale here is: since we don't attempt 774 * to distinguish whether we are in this situation, if it just 775 * happened we can't count on class_idx to tell either. 776 */ 777 struct lock_class *lock = hlock_class(hlock); 778 779 if (!lock) { 780 printk(KERN_CONT "<RELEASED>\n"); 781 return; 782 } 783 784 printk(KERN_CONT "%px", hlock->instance); 785 print_lock_name(hlock, lock); 786 printk(KERN_CONT ", at: %pS\n", (void *)hlock->acquire_ip); 787 } 788 789 static void lockdep_print_held_locks(struct task_struct *p) 790 { 791 int i, depth = READ_ONCE(p->lockdep_depth); 792 793 if (!depth) 794 printk("no locks held by %s/%d.\n", p->comm, task_pid_nr(p)); 795 else 796 printk("%d lock%s held by %s/%d:\n", depth, 797 str_plural(depth), p->comm, task_pid_nr(p)); 798 /* 799 * It's not reliable to print a task's held locks if it's not sleeping 800 * and it's not the current task. 801 */ 802 if (p != current && task_is_running(p)) 803 return; 804 for (i = 0; i < depth; i++) { 805 printk(" #%d: ", i); 806 print_lock(p->held_locks + i); 807 } 808 } 809 810 static void print_kernel_ident(void) 811 { 812 printk("%s %.*s %s\n", init_utsname()->release, 813 (int)strcspn(init_utsname()->version, " "), 814 init_utsname()->version, 815 print_tainted()); 816 } 817 818 static int very_verbose(struct lock_class *class) 819 { 820 #if VERY_VERBOSE 821 return class_filter(class); 822 #endif 823 return 0; 824 } 825 826 /* 827 * Is this the address of a static object: 828 */ 829 #ifdef __KERNEL__ 830 static int static_obj(const void *obj) 831 { 832 unsigned long addr = (unsigned long) obj; 833 834 if (is_kernel_core_data(addr)) 835 return 1; 836 837 /* 838 * keys are allowed in the __ro_after_init section. 839 */ 840 if (is_kernel_rodata(addr)) 841 return 1; 842 843 /* 844 * in initdata section and used during bootup only? 845 * NOTE: On some platforms the initdata section is 846 * outside of the _stext ... _end range. 847 */ 848 if (system_state < SYSTEM_FREEING_INITMEM && 849 init_section_contains((void *)addr, 1)) 850 return 1; 851 852 /* 853 * in-kernel percpu var? 854 */ 855 if (is_kernel_percpu_address(addr)) 856 return 1; 857 858 /* 859 * module static or percpu var? 860 */ 861 return is_module_address(addr) || is_module_percpu_address(addr); 862 } 863 #endif 864 865 /* 866 * To make lock name printouts unique, we calculate a unique 867 * class->name_version generation counter. The caller must hold the graph 868 * lock. 869 */ 870 static int count_matching_names(struct lock_class *new_class) 871 { 872 struct lock_class *class; 873 int count = 0; 874 875 if (!new_class->name) 876 return 0; 877 878 list_for_each_entry(class, &all_lock_classes, lock_entry) { 879 if (new_class->key - new_class->subclass == class->key) 880 return class->name_version; 881 if (class->name && !strcmp(class->name, new_class->name)) 882 count = max(count, class->name_version); 883 } 884 885 return count + 1; 886 } 887 888 /* used from NMI context -- must be lockless */ 889 static noinstr struct lock_class * 890 look_up_lock_class(const struct lockdep_map *lock, unsigned int subclass) 891 { 892 struct lockdep_subclass_key *key; 893 struct hlist_head *hash_head; 894 struct lock_class *class; 895 896 if (unlikely(subclass >= MAX_LOCKDEP_SUBCLASSES)) { 897 instrumentation_begin(); 898 debug_locks_off(); 899 nbcon_cpu_emergency_enter(); 900 printk(KERN_ERR 901 "BUG: looking up invalid subclass: %u\n", subclass); 902 printk(KERN_ERR 903 "turning off the locking correctness validator.\n"); 904 dump_stack(); 905 nbcon_cpu_emergency_exit(); 906 instrumentation_end(); 907 return NULL; 908 } 909 910 /* 911 * If it is not initialised then it has never been locked, 912 * so it won't be present in the hash table. 913 */ 914 if (unlikely(!lock->key)) 915 return NULL; 916 917 /* 918 * NOTE: the class-key must be unique. For dynamic locks, a static 919 * lock_class_key variable is passed in through the mutex_init() 920 * (or spin_lock_init()) call - which acts as the key. For static 921 * locks we use the lock object itself as the key. 922 */ 923 BUILD_BUG_ON(sizeof(struct lock_class_key) > 924 sizeof(struct lockdep_map)); 925 926 key = lock->key->subkeys + subclass; 927 928 hash_head = classhashentry(key); 929 930 /* 931 * We do an RCU walk of the hash, see lockdep_free_key_range(). 932 */ 933 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled())) 934 return NULL; 935 936 hlist_for_each_entry_rcu_notrace(class, hash_head, hash_entry) { 937 if (class->key == key) { 938 /* 939 * Huh! same key, different name? Did someone trample 940 * on some memory? We're most confused. 941 */ 942 WARN_ONCE(class->name != lock->name && 943 lock->key != &__lockdep_no_validate__, 944 "Looking for class \"%s\" with key %ps, but found a different class \"%s\" with the same key\n", 945 lock->name, lock->key, class->name); 946 return class; 947 } 948 } 949 950 return NULL; 951 } 952 953 /* 954 * Static locks do not have their class-keys yet - for them the key is 955 * the lock object itself. If the lock is in the per cpu area, the 956 * canonical address of the lock (per cpu offset removed) is used. 957 */ 958 static bool assign_lock_key(struct lockdep_map *lock) 959 { 960 unsigned long can_addr, addr = (unsigned long)lock; 961 962 #ifdef __KERNEL__ 963 /* 964 * lockdep_free_key_range() assumes that struct lock_class_key 965 * objects do not overlap. Since we use the address of lock 966 * objects as class key for static objects, check whether the 967 * size of lock_class_key objects does not exceed the size of 968 * the smallest lock object. 969 */ 970 BUILD_BUG_ON(sizeof(struct lock_class_key) > sizeof(raw_spinlock_t)); 971 #endif 972 973 if (__is_kernel_percpu_address(addr, &can_addr)) 974 lock->key = (void *)can_addr; 975 else if (__is_module_percpu_address(addr, &can_addr)) 976 lock->key = (void *)can_addr; 977 else if (static_obj(lock)) 978 lock->key = (void *)lock; 979 else { 980 /* Debug-check: all keys must be persistent! */ 981 debug_locks_off(); 982 nbcon_cpu_emergency_enter(); 983 pr_err("INFO: trying to register non-static key.\n"); 984 pr_err("The code is fine but needs lockdep annotation, or maybe\n"); 985 pr_err("you didn't initialize this object before use?\n"); 986 pr_err("turning off the locking correctness validator.\n"); 987 dump_stack(); 988 nbcon_cpu_emergency_exit(); 989 return false; 990 } 991 992 return true; 993 } 994 995 #ifdef CONFIG_DEBUG_LOCKDEP 996 997 /* Check whether element @e occurs in list @h */ 998 static bool in_list(struct list_head *e, struct list_head *h) 999 { 1000 struct list_head *f; 1001 1002 list_for_each(f, h) { 1003 if (e == f) 1004 return true; 1005 } 1006 1007 return false; 1008 } 1009 1010 /* 1011 * Check whether entry @e occurs in any of the locks_after or locks_before 1012 * lists. 1013 */ 1014 static bool in_any_class_list(struct list_head *e) 1015 { 1016 struct lock_class *class; 1017 int i; 1018 1019 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) { 1020 class = &lock_classes[i]; 1021 if (in_list(e, &class->locks_after) || 1022 in_list(e, &class->locks_before)) 1023 return true; 1024 } 1025 return false; 1026 } 1027 1028 static bool class_lock_list_valid(struct lock_class *c, struct list_head *h) 1029 { 1030 struct lock_list *e; 1031 1032 list_for_each_entry(e, h, entry) { 1033 if (e->links_to != c) { 1034 printk(KERN_INFO "class %s: mismatch for lock entry %ld; class %s <> %s", 1035 c->name ? : "(?)", 1036 (unsigned long)(e - list_entries), 1037 e->links_to && e->links_to->name ? 1038 e->links_to->name : "(?)", 1039 e->class && e->class->name ? e->class->name : 1040 "(?)"); 1041 return false; 1042 } 1043 } 1044 return true; 1045 } 1046 1047 #ifdef CONFIG_PROVE_LOCKING 1048 static u16 chain_hlocks[MAX_LOCKDEP_CHAIN_HLOCKS]; 1049 #endif 1050 1051 static bool check_lock_chain_key(struct lock_chain *chain) 1052 { 1053 #ifdef CONFIG_PROVE_LOCKING 1054 u64 chain_key = INITIAL_CHAIN_KEY; 1055 int i; 1056 1057 for (i = chain->base; i < chain->base + chain->depth; i++) 1058 chain_key = iterate_chain_key(chain_key, chain_hlocks[i]); 1059 /* 1060 * The 'unsigned long long' casts avoid that a compiler warning 1061 * is reported when building tools/lib/lockdep. 1062 */ 1063 if (chain->chain_key != chain_key) { 1064 printk(KERN_INFO "chain %lld: key %#llx <> %#llx\n", 1065 (unsigned long long)(chain - lock_chains), 1066 (unsigned long long)chain->chain_key, 1067 (unsigned long long)chain_key); 1068 return false; 1069 } 1070 #endif 1071 return true; 1072 } 1073 1074 static bool in_any_zapped_class_list(struct lock_class *class) 1075 { 1076 struct pending_free *pf; 1077 int i; 1078 1079 for (i = 0, pf = delayed_free.pf; i < ARRAY_SIZE(delayed_free.pf); i++, pf++) { 1080 if (in_list(&class->lock_entry, &pf->zapped)) 1081 return true; 1082 } 1083 1084 return false; 1085 } 1086 1087 static bool __check_data_structures(void) 1088 { 1089 struct lock_class *class; 1090 struct lock_chain *chain; 1091 struct hlist_head *head; 1092 struct lock_list *e; 1093 int i; 1094 1095 /* Check whether all classes occur in a lock list. */ 1096 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) { 1097 class = &lock_classes[i]; 1098 if (!in_list(&class->lock_entry, &all_lock_classes) && 1099 !in_list(&class->lock_entry, &free_lock_classes) && 1100 !in_any_zapped_class_list(class)) { 1101 printk(KERN_INFO "class %px/%s is not in any class list\n", 1102 class, class->name ? : "(?)"); 1103 return false; 1104 } 1105 } 1106 1107 /* Check whether all classes have valid lock lists. */ 1108 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) { 1109 class = &lock_classes[i]; 1110 if (!class_lock_list_valid(class, &class->locks_before)) 1111 return false; 1112 if (!class_lock_list_valid(class, &class->locks_after)) 1113 return false; 1114 } 1115 1116 /* Check the chain_key of all lock chains. */ 1117 for (i = 0; i < ARRAY_SIZE(chainhash_table); i++) { 1118 head = chainhash_table + i; 1119 hlist_for_each_entry_rcu(chain, head, entry) { 1120 if (!check_lock_chain_key(chain)) 1121 return false; 1122 } 1123 } 1124 1125 /* 1126 * Check whether all list entries that are in use occur in a class 1127 * lock list. 1128 */ 1129 for_each_set_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) { 1130 e = list_entries + i; 1131 if (!in_any_class_list(&e->entry)) { 1132 printk(KERN_INFO "list entry %d is not in any class list; class %s <> %s\n", 1133 (unsigned int)(e - list_entries), 1134 e->class->name ? : "(?)", 1135 e->links_to->name ? : "(?)"); 1136 return false; 1137 } 1138 } 1139 1140 /* 1141 * Check whether all list entries that are not in use do not occur in 1142 * a class lock list. 1143 */ 1144 for_each_clear_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) { 1145 e = list_entries + i; 1146 if (in_any_class_list(&e->entry)) { 1147 printk(KERN_INFO "list entry %d occurs in a class list; class %s <> %s\n", 1148 (unsigned int)(e - list_entries), 1149 e->class && e->class->name ? e->class->name : 1150 "(?)", 1151 e->links_to && e->links_to->name ? 1152 e->links_to->name : "(?)"); 1153 return false; 1154 } 1155 } 1156 1157 return true; 1158 } 1159 1160 int check_consistency = 0; 1161 module_param(check_consistency, int, 0644); 1162 1163 static void check_data_structures(void) 1164 { 1165 static bool once = false; 1166 1167 if (check_consistency && !once) { 1168 if (!__check_data_structures()) { 1169 once = true; 1170 WARN_ON(once); 1171 } 1172 } 1173 } 1174 1175 #else /* CONFIG_DEBUG_LOCKDEP */ 1176 1177 static inline void check_data_structures(void) { } 1178 1179 #endif /* CONFIG_DEBUG_LOCKDEP */ 1180 1181 static void init_chain_block_buckets(void); 1182 1183 /* 1184 * Initialize the lock_classes[] array elements, the free_lock_classes list 1185 * and also the delayed_free structure. 1186 */ 1187 static void init_data_structures_once(void) 1188 { 1189 static bool __read_mostly ds_initialized, rcu_head_initialized; 1190 int i; 1191 1192 if (likely(rcu_head_initialized)) 1193 return; 1194 1195 if (system_state >= SYSTEM_SCHEDULING) { 1196 init_rcu_head(&delayed_free.rcu_head); 1197 rcu_head_initialized = true; 1198 } 1199 1200 if (ds_initialized) 1201 return; 1202 1203 ds_initialized = true; 1204 1205 INIT_LIST_HEAD(&delayed_free.pf[0].zapped); 1206 INIT_LIST_HEAD(&delayed_free.pf[1].zapped); 1207 1208 for (i = 0; i < ARRAY_SIZE(lock_classes); i++) { 1209 list_add_tail(&lock_classes[i].lock_entry, &free_lock_classes); 1210 INIT_LIST_HEAD(&lock_classes[i].locks_after); 1211 INIT_LIST_HEAD(&lock_classes[i].locks_before); 1212 } 1213 init_chain_block_buckets(); 1214 } 1215 1216 static inline struct hlist_head *keyhashentry(const struct lock_class_key *key) 1217 { 1218 unsigned long hash = hash_long((uintptr_t)key, KEYHASH_BITS); 1219 1220 return lock_keys_hash + hash; 1221 } 1222 1223 /* Register a dynamically allocated key. */ 1224 void lockdep_register_key(struct lock_class_key *key) 1225 { 1226 struct hlist_head *hash_head; 1227 struct lock_class_key *k; 1228 unsigned long flags; 1229 1230 if (WARN_ON_ONCE(static_obj(key))) 1231 return; 1232 hash_head = keyhashentry(key); 1233 1234 raw_local_irq_save(flags); 1235 if (!graph_lock()) 1236 goto restore_irqs; 1237 hlist_for_each_entry_rcu(k, hash_head, hash_entry) { 1238 if (WARN_ON_ONCE(k == key)) 1239 goto out_unlock; 1240 } 1241 hlist_add_head_rcu(&key->hash_entry, hash_head); 1242 nr_dynamic_keys++; 1243 out_unlock: 1244 graph_unlock(); 1245 restore_irqs: 1246 raw_local_irq_restore(flags); 1247 } 1248 EXPORT_SYMBOL_GPL(lockdep_register_key); 1249 1250 /* Check whether a key has been registered as a dynamic key. */ 1251 static bool is_dynamic_key(const struct lock_class_key *key) 1252 { 1253 struct hlist_head *hash_head; 1254 struct lock_class_key *k; 1255 bool found = false; 1256 1257 if (WARN_ON_ONCE(static_obj(key))) 1258 return false; 1259 1260 /* 1261 * If lock debugging is disabled lock_keys_hash[] may contain 1262 * pointers to memory that has already been freed. Avoid triggering 1263 * a use-after-free in that case by returning early. 1264 */ 1265 if (!debug_locks) 1266 return true; 1267 1268 hash_head = keyhashentry(key); 1269 1270 rcu_read_lock(); 1271 hlist_for_each_entry_rcu(k, hash_head, hash_entry) { 1272 if (k == key) { 1273 found = true; 1274 break; 1275 } 1276 } 1277 rcu_read_unlock(); 1278 1279 return found; 1280 } 1281 1282 /* 1283 * Register a lock's class in the hash-table, if the class is not present 1284 * yet. Otherwise we look it up. We cache the result in the lock object 1285 * itself, so actual lookup of the hash should be once per lock object. 1286 */ 1287 static struct lock_class * 1288 register_lock_class(struct lockdep_map *lock, unsigned int subclass, int force) 1289 { 1290 struct lockdep_subclass_key *key; 1291 struct hlist_head *hash_head; 1292 struct lock_class *class; 1293 int idx; 1294 1295 DEBUG_LOCKS_WARN_ON(!irqs_disabled()); 1296 1297 class = look_up_lock_class(lock, subclass); 1298 if (likely(class)) 1299 goto out_set_class_cache; 1300 1301 if (!lock->key) { 1302 if (!assign_lock_key(lock)) 1303 return NULL; 1304 } else if (!static_obj(lock->key) && !is_dynamic_key(lock->key)) { 1305 return NULL; 1306 } 1307 1308 key = lock->key->subkeys + subclass; 1309 hash_head = classhashentry(key); 1310 1311 if (!graph_lock()) { 1312 return NULL; 1313 } 1314 /* 1315 * We have to do the hash-walk again, to avoid races 1316 * with another CPU: 1317 */ 1318 hlist_for_each_entry_rcu(class, hash_head, hash_entry) { 1319 if (class->key == key) 1320 goto out_unlock_set; 1321 } 1322 1323 init_data_structures_once(); 1324 1325 /* Allocate a new lock class and add it to the hash. */ 1326 class = list_first_entry_or_null(&free_lock_classes, typeof(*class), 1327 lock_entry); 1328 if (!class) { 1329 if (!debug_locks_off_graph_unlock()) { 1330 return NULL; 1331 } 1332 1333 nbcon_cpu_emergency_enter(); 1334 print_lockdep_off("BUG: MAX_LOCKDEP_KEYS too low!"); 1335 dump_stack(); 1336 nbcon_cpu_emergency_exit(); 1337 return NULL; 1338 } 1339 nr_lock_classes++; 1340 __set_bit(class - lock_classes, lock_classes_in_use); 1341 debug_atomic_inc(nr_unused_locks); 1342 class->key = key; 1343 class->name = lock->name; 1344 class->subclass = subclass; 1345 WARN_ON_ONCE(!list_empty(&class->locks_before)); 1346 WARN_ON_ONCE(!list_empty(&class->locks_after)); 1347 class->name_version = count_matching_names(class); 1348 class->wait_type_inner = lock->wait_type_inner; 1349 class->wait_type_outer = lock->wait_type_outer; 1350 class->lock_type = lock->lock_type; 1351 /* 1352 * We use RCU's safe list-add method to make 1353 * parallel walking of the hash-list safe: 1354 */ 1355 hlist_add_head_rcu(&class->hash_entry, hash_head); 1356 /* 1357 * Remove the class from the free list and add it to the global list 1358 * of classes. 1359 */ 1360 list_move_tail(&class->lock_entry, &all_lock_classes); 1361 idx = class - lock_classes; 1362 if (idx > max_lock_class_idx) 1363 max_lock_class_idx = idx; 1364 1365 if (verbose(class)) { 1366 graph_unlock(); 1367 1368 nbcon_cpu_emergency_enter(); 1369 printk("\nnew class %px: %s", class->key, class->name); 1370 if (class->name_version > 1) 1371 printk(KERN_CONT "#%d", class->name_version); 1372 printk(KERN_CONT "\n"); 1373 dump_stack(); 1374 nbcon_cpu_emergency_exit(); 1375 1376 if (!graph_lock()) { 1377 return NULL; 1378 } 1379 } 1380 out_unlock_set: 1381 graph_unlock(); 1382 1383 out_set_class_cache: 1384 if (!subclass || force) 1385 lock->class_cache[0] = class; 1386 else if (subclass < NR_LOCKDEP_CACHING_CLASSES) 1387 lock->class_cache[subclass] = class; 1388 1389 /* 1390 * Hash collision, did we smoke some? We found a class with a matching 1391 * hash but the subclass -- which is hashed in -- didn't match. 1392 */ 1393 if (DEBUG_LOCKS_WARN_ON(class->subclass != subclass)) 1394 return NULL; 1395 1396 return class; 1397 } 1398 1399 #ifdef CONFIG_PROVE_LOCKING 1400 /* 1401 * Allocate a lockdep entry. (assumes the graph_lock held, returns 1402 * with NULL on failure) 1403 */ 1404 static struct lock_list *alloc_list_entry(void) 1405 { 1406 int idx = find_first_zero_bit(list_entries_in_use, 1407 ARRAY_SIZE(list_entries)); 1408 1409 if (idx >= ARRAY_SIZE(list_entries)) { 1410 if (!debug_locks_off_graph_unlock()) 1411 return NULL; 1412 1413 nbcon_cpu_emergency_enter(); 1414 print_lockdep_off("BUG: MAX_LOCKDEP_ENTRIES too low!"); 1415 dump_stack(); 1416 nbcon_cpu_emergency_exit(); 1417 return NULL; 1418 } 1419 nr_list_entries++; 1420 __set_bit(idx, list_entries_in_use); 1421 return list_entries + idx; 1422 } 1423 1424 /* 1425 * Add a new dependency to the head of the list: 1426 */ 1427 static int add_lock_to_list(struct lock_class *this, 1428 struct lock_class *links_to, struct list_head *head, 1429 u16 distance, u8 dep, 1430 const struct lock_trace *trace) 1431 { 1432 struct lock_list *entry; 1433 /* 1434 * Lock not present yet - get a new dependency struct and 1435 * add it to the list: 1436 */ 1437 entry = alloc_list_entry(); 1438 if (!entry) 1439 return 0; 1440 1441 entry->class = this; 1442 entry->links_to = links_to; 1443 entry->dep = dep; 1444 entry->distance = distance; 1445 entry->trace = trace; 1446 /* 1447 * Both allocation and removal are done under the graph lock; but 1448 * iteration is under RCU-sched; see look_up_lock_class() and 1449 * lockdep_free_key_range(). 1450 */ 1451 list_add_tail_rcu(&entry->entry, head); 1452 1453 return 1; 1454 } 1455 1456 /* 1457 * For good efficiency of modular, we use power of 2 1458 */ 1459 #define MAX_CIRCULAR_QUEUE_SIZE (1UL << CONFIG_LOCKDEP_CIRCULAR_QUEUE_BITS) 1460 #define CQ_MASK (MAX_CIRCULAR_QUEUE_SIZE-1) 1461 1462 /* 1463 * The circular_queue and helpers are used to implement graph 1464 * breadth-first search (BFS) algorithm, by which we can determine 1465 * whether there is a path from a lock to another. In deadlock checks, 1466 * a path from the next lock to be acquired to a previous held lock 1467 * indicates that adding the <prev> -> <next> lock dependency will 1468 * produce a circle in the graph. Breadth-first search instead of 1469 * depth-first search is used in order to find the shortest (circular) 1470 * path. 1471 */ 1472 struct circular_queue { 1473 struct lock_list *element[MAX_CIRCULAR_QUEUE_SIZE]; 1474 unsigned int front, rear; 1475 }; 1476 1477 static struct circular_queue lock_cq; 1478 1479 unsigned int max_bfs_queue_depth; 1480 1481 static unsigned int lockdep_dependency_gen_id; 1482 1483 static inline void __cq_init(struct circular_queue *cq) 1484 { 1485 cq->front = cq->rear = 0; 1486 lockdep_dependency_gen_id++; 1487 } 1488 1489 static inline int __cq_empty(struct circular_queue *cq) 1490 { 1491 return (cq->front == cq->rear); 1492 } 1493 1494 static inline int __cq_full(struct circular_queue *cq) 1495 { 1496 return ((cq->rear + 1) & CQ_MASK) == cq->front; 1497 } 1498 1499 static inline int __cq_enqueue(struct circular_queue *cq, struct lock_list *elem) 1500 { 1501 if (__cq_full(cq)) 1502 return -1; 1503 1504 cq->element[cq->rear] = elem; 1505 cq->rear = (cq->rear + 1) & CQ_MASK; 1506 return 0; 1507 } 1508 1509 /* 1510 * Dequeue an element from the circular_queue, return a lock_list if 1511 * the queue is not empty, or NULL if otherwise. 1512 */ 1513 static inline struct lock_list * __cq_dequeue(struct circular_queue *cq) 1514 { 1515 struct lock_list * lock; 1516 1517 if (__cq_empty(cq)) 1518 return NULL; 1519 1520 lock = cq->element[cq->front]; 1521 cq->front = (cq->front + 1) & CQ_MASK; 1522 1523 return lock; 1524 } 1525 1526 static inline unsigned int __cq_get_elem_count(struct circular_queue *cq) 1527 { 1528 return (cq->rear - cq->front) & CQ_MASK; 1529 } 1530 1531 static inline void mark_lock_accessed(struct lock_list *lock) 1532 { 1533 lock->class->dep_gen_id = lockdep_dependency_gen_id; 1534 } 1535 1536 static inline void visit_lock_entry(struct lock_list *lock, 1537 struct lock_list *parent) 1538 { 1539 lock->parent = parent; 1540 } 1541 1542 static inline unsigned long lock_accessed(struct lock_list *lock) 1543 { 1544 return lock->class->dep_gen_id == lockdep_dependency_gen_id; 1545 } 1546 1547 static inline struct lock_list *get_lock_parent(struct lock_list *child) 1548 { 1549 return child->parent; 1550 } 1551 1552 static inline int get_lock_depth(struct lock_list *child) 1553 { 1554 int depth = 0; 1555 struct lock_list *parent; 1556 1557 while ((parent = get_lock_parent(child))) { 1558 child = parent; 1559 depth++; 1560 } 1561 return depth; 1562 } 1563 1564 /* 1565 * Return the forward or backward dependency list. 1566 * 1567 * @lock: the lock_list to get its class's dependency list 1568 * @offset: the offset to struct lock_class to determine whether it is 1569 * locks_after or locks_before 1570 */ 1571 static inline struct list_head *get_dep_list(struct lock_list *lock, int offset) 1572 { 1573 void *lock_class = lock->class; 1574 1575 return lock_class + offset; 1576 } 1577 /* 1578 * Return values of a bfs search: 1579 * 1580 * BFS_E* indicates an error 1581 * BFS_R* indicates a result (match or not) 1582 * 1583 * BFS_EINVALIDNODE: Find a invalid node in the graph. 1584 * 1585 * BFS_EQUEUEFULL: The queue is full while doing the bfs. 1586 * 1587 * BFS_RMATCH: Find the matched node in the graph, and put that node into 1588 * *@target_entry. 1589 * 1590 * BFS_RNOMATCH: Haven't found the matched node and keep *@target_entry 1591 * _unchanged_. 1592 */ 1593 enum bfs_result { 1594 BFS_EINVALIDNODE = -2, 1595 BFS_EQUEUEFULL = -1, 1596 BFS_RMATCH = 0, 1597 BFS_RNOMATCH = 1, 1598 }; 1599 1600 /* 1601 * bfs_result < 0 means error 1602 */ 1603 static inline bool bfs_error(enum bfs_result res) 1604 { 1605 return res < 0; 1606 } 1607 1608 /* 1609 * DEP_*_BIT in lock_list::dep 1610 * 1611 * For dependency @prev -> @next: 1612 * 1613 * SR: @prev is shared reader (->read != 0) and @next is recursive reader 1614 * (->read == 2) 1615 * ER: @prev is exclusive locker (->read == 0) and @next is recursive reader 1616 * SN: @prev is shared reader and @next is non-recursive locker (->read != 2) 1617 * EN: @prev is exclusive locker and @next is non-recursive locker 1618 * 1619 * Note that we define the value of DEP_*_BITs so that: 1620 * bit0 is prev->read == 0 1621 * bit1 is next->read != 2 1622 */ 1623 #define DEP_SR_BIT (0 + (0 << 1)) /* 0 */ 1624 #define DEP_ER_BIT (1 + (0 << 1)) /* 1 */ 1625 #define DEP_SN_BIT (0 + (1 << 1)) /* 2 */ 1626 #define DEP_EN_BIT (1 + (1 << 1)) /* 3 */ 1627 1628 #define DEP_SR_MASK (1U << (DEP_SR_BIT)) 1629 #define DEP_ER_MASK (1U << (DEP_ER_BIT)) 1630 #define DEP_SN_MASK (1U << (DEP_SN_BIT)) 1631 #define DEP_EN_MASK (1U << (DEP_EN_BIT)) 1632 1633 static inline unsigned int 1634 __calc_dep_bit(struct held_lock *prev, struct held_lock *next) 1635 { 1636 return (prev->read == 0) + ((next->read != 2) << 1); 1637 } 1638 1639 static inline u8 calc_dep(struct held_lock *prev, struct held_lock *next) 1640 { 1641 return 1U << __calc_dep_bit(prev, next); 1642 } 1643 1644 /* 1645 * calculate the dep_bit for backwards edges. We care about whether @prev is 1646 * shared and whether @next is recursive. 1647 */ 1648 static inline unsigned int 1649 __calc_dep_bitb(struct held_lock *prev, struct held_lock *next) 1650 { 1651 return (next->read != 2) + ((prev->read == 0) << 1); 1652 } 1653 1654 static inline u8 calc_depb(struct held_lock *prev, struct held_lock *next) 1655 { 1656 return 1U << __calc_dep_bitb(prev, next); 1657 } 1658 1659 /* 1660 * Initialize a lock_list entry @lock belonging to @class as the root for a BFS 1661 * search. 1662 */ 1663 static inline void __bfs_init_root(struct lock_list *lock, 1664 struct lock_class *class) 1665 { 1666 lock->class = class; 1667 lock->parent = NULL; 1668 lock->only_xr = 0; 1669 } 1670 1671 /* 1672 * Initialize a lock_list entry @lock based on a lock acquisition @hlock as the 1673 * root for a BFS search. 1674 * 1675 * ->only_xr of the initial lock node is set to @hlock->read == 2, to make sure 1676 * that <prev> -> @hlock and @hlock -> <whatever __bfs() found> is not -(*R)-> 1677 * and -(S*)->. 1678 */ 1679 static inline void bfs_init_root(struct lock_list *lock, 1680 struct held_lock *hlock) 1681 { 1682 __bfs_init_root(lock, hlock_class(hlock)); 1683 lock->only_xr = (hlock->read == 2); 1684 } 1685 1686 /* 1687 * Similar to bfs_init_root() but initialize the root for backwards BFS. 1688 * 1689 * ->only_xr of the initial lock node is set to @hlock->read != 0, to make sure 1690 * that <next> -> @hlock and @hlock -> <whatever backwards BFS found> is not 1691 * -(*S)-> and -(R*)-> (reverse order of -(*R)-> and -(S*)->). 1692 */ 1693 static inline void bfs_init_rootb(struct lock_list *lock, 1694 struct held_lock *hlock) 1695 { 1696 __bfs_init_root(lock, hlock_class(hlock)); 1697 lock->only_xr = (hlock->read != 0); 1698 } 1699 1700 static inline struct lock_list *__bfs_next(struct lock_list *lock, int offset) 1701 { 1702 if (!lock || !lock->parent) 1703 return NULL; 1704 1705 return list_next_or_null_rcu(get_dep_list(lock->parent, offset), 1706 &lock->entry, struct lock_list, entry); 1707 } 1708 1709 /* 1710 * Breadth-First Search to find a strong path in the dependency graph. 1711 * 1712 * @source_entry: the source of the path we are searching for. 1713 * @data: data used for the second parameter of @match function 1714 * @match: match function for the search 1715 * @target_entry: pointer to the target of a matched path 1716 * @offset: the offset to struct lock_class to determine whether it is 1717 * locks_after or locks_before 1718 * 1719 * We may have multiple edges (considering different kinds of dependencies, 1720 * e.g. ER and SN) between two nodes in the dependency graph. But 1721 * only the strong dependency path in the graph is relevant to deadlocks. A 1722 * strong dependency path is a dependency path that doesn't have two adjacent 1723 * dependencies as -(*R)-> -(S*)->, please see: 1724 * 1725 * Documentation/locking/lockdep-design.rst 1726 * 1727 * for more explanation of the definition of strong dependency paths 1728 * 1729 * In __bfs(), we only traverse in the strong dependency path: 1730 * 1731 * In lock_list::only_xr, we record whether the previous dependency only 1732 * has -(*R)-> in the search, and if it does (prev only has -(*R)->), we 1733 * filter out any -(S*)-> in the current dependency and after that, the 1734 * ->only_xr is set according to whether we only have -(*R)-> left. 1735 */ 1736 static enum bfs_result __bfs(struct lock_list *source_entry, 1737 void *data, 1738 bool (*match)(struct lock_list *entry, void *data), 1739 bool (*skip)(struct lock_list *entry, void *data), 1740 struct lock_list **target_entry, 1741 int offset) 1742 { 1743 struct circular_queue *cq = &lock_cq; 1744 struct lock_list *lock = NULL; 1745 struct lock_list *entry; 1746 struct list_head *head; 1747 unsigned int cq_depth; 1748 bool first; 1749 1750 lockdep_assert_locked(); 1751 1752 __cq_init(cq); 1753 __cq_enqueue(cq, source_entry); 1754 1755 while ((lock = __bfs_next(lock, offset)) || (lock = __cq_dequeue(cq))) { 1756 if (!lock->class) 1757 return BFS_EINVALIDNODE; 1758 1759 /* 1760 * Step 1: check whether we already finish on this one. 1761 * 1762 * If we have visited all the dependencies from this @lock to 1763 * others (iow, if we have visited all lock_list entries in 1764 * @lock->class->locks_{after,before}) we skip, otherwise go 1765 * and visit all the dependencies in the list and mark this 1766 * list accessed. 1767 */ 1768 if (lock_accessed(lock)) 1769 continue; 1770 else 1771 mark_lock_accessed(lock); 1772 1773 /* 1774 * Step 2: check whether prev dependency and this form a strong 1775 * dependency path. 1776 */ 1777 if (lock->parent) { /* Parent exists, check prev dependency */ 1778 u8 dep = lock->dep; 1779 bool prev_only_xr = lock->parent->only_xr; 1780 1781 /* 1782 * Mask out all -(S*)-> if we only have *R in previous 1783 * step, because -(*R)-> -(S*)-> don't make up a strong 1784 * dependency. 1785 */ 1786 if (prev_only_xr) 1787 dep &= ~(DEP_SR_MASK | DEP_SN_MASK); 1788 1789 /* If nothing left, we skip */ 1790 if (!dep) 1791 continue; 1792 1793 /* If there are only -(*R)-> left, set that for the next step */ 1794 lock->only_xr = !(dep & (DEP_SN_MASK | DEP_EN_MASK)); 1795 } 1796 1797 /* 1798 * Step 3: we haven't visited this and there is a strong 1799 * dependency path to this, so check with @match. 1800 * If @skip is provide and returns true, we skip this 1801 * lock (and any path this lock is in). 1802 */ 1803 if (skip && skip(lock, data)) 1804 continue; 1805 1806 if (match(lock, data)) { 1807 *target_entry = lock; 1808 return BFS_RMATCH; 1809 } 1810 1811 /* 1812 * Step 4: if not match, expand the path by adding the 1813 * forward or backwards dependencies in the search 1814 * 1815 */ 1816 first = true; 1817 head = get_dep_list(lock, offset); 1818 list_for_each_entry_rcu(entry, head, entry) { 1819 visit_lock_entry(entry, lock); 1820 1821 /* 1822 * Note we only enqueue the first of the list into the 1823 * queue, because we can always find a sibling 1824 * dependency from one (see __bfs_next()), as a result 1825 * the space of queue is saved. 1826 */ 1827 if (!first) 1828 continue; 1829 1830 first = false; 1831 1832 if (__cq_enqueue(cq, entry)) 1833 return BFS_EQUEUEFULL; 1834 1835 cq_depth = __cq_get_elem_count(cq); 1836 if (max_bfs_queue_depth < cq_depth) 1837 max_bfs_queue_depth = cq_depth; 1838 } 1839 } 1840 1841 return BFS_RNOMATCH; 1842 } 1843 1844 static inline enum bfs_result 1845 __bfs_forwards(struct lock_list *src_entry, 1846 void *data, 1847 bool (*match)(struct lock_list *entry, void *data), 1848 bool (*skip)(struct lock_list *entry, void *data), 1849 struct lock_list **target_entry) 1850 { 1851 return __bfs(src_entry, data, match, skip, target_entry, 1852 offsetof(struct lock_class, locks_after)); 1853 1854 } 1855 1856 static inline enum bfs_result 1857 __bfs_backwards(struct lock_list *src_entry, 1858 void *data, 1859 bool (*match)(struct lock_list *entry, void *data), 1860 bool (*skip)(struct lock_list *entry, void *data), 1861 struct lock_list **target_entry) 1862 { 1863 return __bfs(src_entry, data, match, skip, target_entry, 1864 offsetof(struct lock_class, locks_before)); 1865 1866 } 1867 1868 static void print_lock_trace(const struct lock_trace *trace, 1869 unsigned int spaces) 1870 { 1871 stack_trace_print(trace->entries, trace->nr_entries, spaces); 1872 } 1873 1874 /* 1875 * Print a dependency chain entry (this is only done when a deadlock 1876 * has been detected): 1877 */ 1878 static noinline void 1879 print_circular_bug_entry(struct lock_list *target, int depth) 1880 { 1881 if (debug_locks_silent) 1882 return; 1883 printk("\n-> #%u", depth); 1884 print_lock_name(NULL, target->class); 1885 printk(KERN_CONT ":\n"); 1886 print_lock_trace(target->trace, 6); 1887 } 1888 1889 static void 1890 print_circular_lock_scenario(struct held_lock *src, 1891 struct held_lock *tgt, 1892 struct lock_list *prt) 1893 { 1894 struct lock_class *source = hlock_class(src); 1895 struct lock_class *target = hlock_class(tgt); 1896 struct lock_class *parent = prt->class; 1897 int src_read = src->read; 1898 int tgt_read = tgt->read; 1899 1900 /* 1901 * A direct locking problem where unsafe_class lock is taken 1902 * directly by safe_class lock, then all we need to show 1903 * is the deadlock scenario, as it is obvious that the 1904 * unsafe lock is taken under the safe lock. 1905 * 1906 * But if there is a chain instead, where the safe lock takes 1907 * an intermediate lock (middle_class) where this lock is 1908 * not the same as the safe lock, then the lock chain is 1909 * used to describe the problem. Otherwise we would need 1910 * to show a different CPU case for each link in the chain 1911 * from the safe_class lock to the unsafe_class lock. 1912 */ 1913 if (parent != source) { 1914 printk("Chain exists of:\n "); 1915 __print_lock_name(src, source); 1916 printk(KERN_CONT " --> "); 1917 __print_lock_name(NULL, parent); 1918 printk(KERN_CONT " --> "); 1919 __print_lock_name(tgt, target); 1920 printk(KERN_CONT "\n\n"); 1921 } 1922 1923 printk(" Possible unsafe locking scenario:\n\n"); 1924 printk(" CPU0 CPU1\n"); 1925 printk(" ---- ----\n"); 1926 if (tgt_read != 0) 1927 printk(" rlock("); 1928 else 1929 printk(" lock("); 1930 __print_lock_name(tgt, target); 1931 printk(KERN_CONT ");\n"); 1932 printk(" lock("); 1933 __print_lock_name(NULL, parent); 1934 printk(KERN_CONT ");\n"); 1935 printk(" lock("); 1936 __print_lock_name(tgt, target); 1937 printk(KERN_CONT ");\n"); 1938 if (src_read != 0) 1939 printk(" rlock("); 1940 else if (src->sync) 1941 printk(" sync("); 1942 else 1943 printk(" lock("); 1944 __print_lock_name(src, source); 1945 printk(KERN_CONT ");\n"); 1946 printk("\n *** DEADLOCK ***\n\n"); 1947 } 1948 1949 /* 1950 * When a circular dependency is detected, print the 1951 * header first: 1952 */ 1953 static noinline void 1954 print_circular_bug_header(struct lock_list *entry, unsigned int depth, 1955 struct held_lock *check_src, 1956 struct held_lock *check_tgt) 1957 { 1958 struct task_struct *curr = current; 1959 1960 if (debug_locks_silent) 1961 return; 1962 1963 pr_warn("\n"); 1964 pr_warn("======================================================\n"); 1965 pr_warn("WARNING: possible circular locking dependency detected\n"); 1966 print_kernel_ident(); 1967 pr_warn("------------------------------------------------------\n"); 1968 pr_warn("%s/%d is trying to acquire lock:\n", 1969 curr->comm, task_pid_nr(curr)); 1970 print_lock(check_src); 1971 1972 pr_warn("\nbut task is already holding lock:\n"); 1973 1974 print_lock(check_tgt); 1975 pr_warn("\nwhich lock already depends on the new lock.\n\n"); 1976 pr_warn("\nthe existing dependency chain (in reverse order) is:\n"); 1977 1978 print_circular_bug_entry(entry, depth); 1979 } 1980 1981 /* 1982 * We are about to add B -> A into the dependency graph, and in __bfs() a 1983 * strong dependency path A -> .. -> B is found: hlock_class equals 1984 * entry->class. 1985 * 1986 * We will have a deadlock case (conflict) if A -> .. -> B -> A is a strong 1987 * dependency cycle, that means: 1988 * 1989 * Either 1990 * 1991 * a) B -> A is -(E*)-> 1992 * 1993 * or 1994 * 1995 * b) A -> .. -> B is -(*N)-> (i.e. A -> .. -(*N)-> B) 1996 * 1997 * as then we don't have -(*R)-> -(S*)-> in the cycle. 1998 */ 1999 static inline bool hlock_conflict(struct lock_list *entry, void *data) 2000 { 2001 struct held_lock *hlock = (struct held_lock *)data; 2002 2003 return hlock_class(hlock) == entry->class && /* Found A -> .. -> B */ 2004 (hlock->read == 0 || /* B -> A is -(E*)-> */ 2005 !entry->only_xr); /* A -> .. -> B is -(*N)-> */ 2006 } 2007 2008 static noinline void print_circular_bug(struct lock_list *this, 2009 struct lock_list *target, 2010 struct held_lock *check_src, 2011 struct held_lock *check_tgt) 2012 { 2013 struct task_struct *curr = current; 2014 struct lock_list *parent; 2015 struct lock_list *first_parent; 2016 int depth; 2017 2018 if (!debug_locks_off_graph_unlock() || debug_locks_silent) 2019 return; 2020 2021 this->trace = save_trace(); 2022 if (!this->trace) 2023 return; 2024 2025 depth = get_lock_depth(target); 2026 2027 nbcon_cpu_emergency_enter(); 2028 2029 print_circular_bug_header(target, depth, check_src, check_tgt); 2030 2031 parent = get_lock_parent(target); 2032 first_parent = parent; 2033 2034 while (parent) { 2035 print_circular_bug_entry(parent, --depth); 2036 parent = get_lock_parent(parent); 2037 } 2038 2039 printk("\nother info that might help us debug this:\n\n"); 2040 print_circular_lock_scenario(check_src, check_tgt, 2041 first_parent); 2042 2043 lockdep_print_held_locks(curr); 2044 2045 printk("\nstack backtrace:\n"); 2046 dump_stack(); 2047 2048 nbcon_cpu_emergency_exit(); 2049 } 2050 2051 static noinline void print_bfs_bug(int ret) 2052 { 2053 if (!debug_locks_off_graph_unlock()) 2054 return; 2055 2056 /* 2057 * Breadth-first-search failed, graph got corrupted? 2058 */ 2059 if (ret == BFS_EQUEUEFULL) 2060 pr_warn("Increase LOCKDEP_CIRCULAR_QUEUE_BITS to avoid this warning:\n"); 2061 2062 WARN(1, "lockdep bfs error:%d\n", ret); 2063 } 2064 2065 static bool noop_count(struct lock_list *entry, void *data) 2066 { 2067 (*(unsigned long *)data)++; 2068 return false; 2069 } 2070 2071 static unsigned long __lockdep_count_forward_deps(struct lock_list *this) 2072 { 2073 unsigned long count = 0; 2074 struct lock_list *target_entry; 2075 2076 __bfs_forwards(this, (void *)&count, noop_count, NULL, &target_entry); 2077 2078 return count; 2079 } 2080 unsigned long lockdep_count_forward_deps(struct lock_class *class) 2081 { 2082 unsigned long ret, flags; 2083 struct lock_list this; 2084 2085 __bfs_init_root(&this, class); 2086 2087 raw_local_irq_save(flags); 2088 lockdep_lock(); 2089 ret = __lockdep_count_forward_deps(&this); 2090 lockdep_unlock(); 2091 raw_local_irq_restore(flags); 2092 2093 return ret; 2094 } 2095 2096 static unsigned long __lockdep_count_backward_deps(struct lock_list *this) 2097 { 2098 unsigned long count = 0; 2099 struct lock_list *target_entry; 2100 2101 __bfs_backwards(this, (void *)&count, noop_count, NULL, &target_entry); 2102 2103 return count; 2104 } 2105 2106 unsigned long lockdep_count_backward_deps(struct lock_class *class) 2107 { 2108 unsigned long ret, flags; 2109 struct lock_list this; 2110 2111 __bfs_init_root(&this, class); 2112 2113 raw_local_irq_save(flags); 2114 lockdep_lock(); 2115 ret = __lockdep_count_backward_deps(&this); 2116 lockdep_unlock(); 2117 raw_local_irq_restore(flags); 2118 2119 return ret; 2120 } 2121 2122 /* 2123 * Check that the dependency graph starting at <src> can lead to 2124 * <target> or not. 2125 */ 2126 static noinline enum bfs_result 2127 check_path(struct held_lock *target, struct lock_list *src_entry, 2128 bool (*match)(struct lock_list *entry, void *data), 2129 bool (*skip)(struct lock_list *entry, void *data), 2130 struct lock_list **target_entry) 2131 { 2132 enum bfs_result ret; 2133 2134 ret = __bfs_forwards(src_entry, target, match, skip, target_entry); 2135 2136 if (unlikely(bfs_error(ret))) 2137 print_bfs_bug(ret); 2138 2139 return ret; 2140 } 2141 2142 static void print_deadlock_bug(struct task_struct *, struct held_lock *, struct held_lock *); 2143 2144 /* 2145 * Prove that the dependency graph starting at <src> can not 2146 * lead to <target>. If it can, there is a circle when adding 2147 * <target> -> <src> dependency. 2148 * 2149 * Print an error and return BFS_RMATCH if it does. 2150 */ 2151 static noinline enum bfs_result 2152 check_noncircular(struct held_lock *src, struct held_lock *target, 2153 struct lock_trace **const trace) 2154 { 2155 enum bfs_result ret; 2156 struct lock_list *target_entry; 2157 struct lock_list src_entry; 2158 2159 bfs_init_root(&src_entry, src); 2160 2161 debug_atomic_inc(nr_cyclic_checks); 2162 2163 ret = check_path(target, &src_entry, hlock_conflict, NULL, &target_entry); 2164 2165 if (unlikely(ret == BFS_RMATCH)) { 2166 if (!*trace) { 2167 /* 2168 * If save_trace fails here, the printing might 2169 * trigger a WARN but because of the !nr_entries it 2170 * should not do bad things. 2171 */ 2172 *trace = save_trace(); 2173 } 2174 2175 if (src->class_idx == target->class_idx) 2176 print_deadlock_bug(current, src, target); 2177 else 2178 print_circular_bug(&src_entry, target_entry, src, target); 2179 } 2180 2181 return ret; 2182 } 2183 2184 #ifdef CONFIG_TRACE_IRQFLAGS 2185 2186 /* 2187 * Forwards and backwards subgraph searching, for the purposes of 2188 * proving that two subgraphs can be connected by a new dependency 2189 * without creating any illegal irq-safe -> irq-unsafe lock dependency. 2190 * 2191 * A irq safe->unsafe deadlock happens with the following conditions: 2192 * 2193 * 1) We have a strong dependency path A -> ... -> B 2194 * 2195 * 2) and we have ENABLED_IRQ usage of B and USED_IN_IRQ usage of A, therefore 2196 * irq can create a new dependency B -> A (consider the case that a holder 2197 * of B gets interrupted by an irq whose handler will try to acquire A). 2198 * 2199 * 3) the dependency circle A -> ... -> B -> A we get from 1) and 2) is a 2200 * strong circle: 2201 * 2202 * For the usage bits of B: 2203 * a) if A -> B is -(*N)->, then B -> A could be any type, so any 2204 * ENABLED_IRQ usage suffices. 2205 * b) if A -> B is -(*R)->, then B -> A must be -(E*)->, so only 2206 * ENABLED_IRQ_*_READ usage suffices. 2207 * 2208 * For the usage bits of A: 2209 * c) if A -> B is -(E*)->, then B -> A could be any type, so any 2210 * USED_IN_IRQ usage suffices. 2211 * d) if A -> B is -(S*)->, then B -> A must be -(*N)->, so only 2212 * USED_IN_IRQ_*_READ usage suffices. 2213 */ 2214 2215 /* 2216 * There is a strong dependency path in the dependency graph: A -> B, and now 2217 * we need to decide which usage bit of A should be accumulated to detect 2218 * safe->unsafe bugs. 2219 * 2220 * Note that usage_accumulate() is used in backwards search, so ->only_xr 2221 * stands for whether A -> B only has -(S*)-> (in this case ->only_xr is true). 2222 * 2223 * As above, if only_xr is false, which means A -> B has -(E*)-> dependency 2224 * path, any usage of A should be considered. Otherwise, we should only 2225 * consider _READ usage. 2226 */ 2227 static inline bool usage_accumulate(struct lock_list *entry, void *mask) 2228 { 2229 if (!entry->only_xr) 2230 *(unsigned long *)mask |= entry->class->usage_mask; 2231 else /* Mask out _READ usage bits */ 2232 *(unsigned long *)mask |= (entry->class->usage_mask & LOCKF_IRQ); 2233 2234 return false; 2235 } 2236 2237 /* 2238 * There is a strong dependency path in the dependency graph: A -> B, and now 2239 * we need to decide which usage bit of B conflicts with the usage bits of A, 2240 * i.e. which usage bit of B may introduce safe->unsafe deadlocks. 2241 * 2242 * As above, if only_xr is false, which means A -> B has -(*N)-> dependency 2243 * path, any usage of B should be considered. Otherwise, we should only 2244 * consider _READ usage. 2245 */ 2246 static inline bool usage_match(struct lock_list *entry, void *mask) 2247 { 2248 if (!entry->only_xr) 2249 return !!(entry->class->usage_mask & *(unsigned long *)mask); 2250 else /* Mask out _READ usage bits */ 2251 return !!((entry->class->usage_mask & LOCKF_IRQ) & *(unsigned long *)mask); 2252 } 2253 2254 static inline bool usage_skip(struct lock_list *entry, void *mask) 2255 { 2256 if (entry->class->lock_type == LD_LOCK_NORMAL) 2257 return false; 2258 2259 /* 2260 * Skip local_lock() for irq inversion detection. 2261 * 2262 * For !RT, local_lock() is not a real lock, so it won't carry any 2263 * dependency. 2264 * 2265 * For RT, an irq inversion happens when we have lock A and B, and on 2266 * some CPU we can have: 2267 * 2268 * lock(A); 2269 * <interrupted> 2270 * lock(B); 2271 * 2272 * where lock(B) cannot sleep, and we have a dependency B -> ... -> A. 2273 * 2274 * Now we prove local_lock() cannot exist in that dependency. First we 2275 * have the observation for any lock chain L1 -> ... -> Ln, for any 2276 * 1 <= i <= n, Li.inner_wait_type <= L1.inner_wait_type, otherwise 2277 * wait context check will complain. And since B is not a sleep lock, 2278 * therefore B.inner_wait_type >= 2, and since the inner_wait_type of 2279 * local_lock() is 3, which is greater than 2, therefore there is no 2280 * way the local_lock() exists in the dependency B -> ... -> A. 2281 * 2282 * As a result, we will skip local_lock(), when we search for irq 2283 * inversion bugs. 2284 */ 2285 if (entry->class->lock_type == LD_LOCK_PERCPU && 2286 DEBUG_LOCKS_WARN_ON(entry->class->wait_type_inner < LD_WAIT_CONFIG)) 2287 return false; 2288 2289 /* 2290 * Skip WAIT_OVERRIDE for irq inversion detection -- it's not actually 2291 * a lock and only used to override the wait_type. 2292 */ 2293 2294 return true; 2295 } 2296 2297 /* 2298 * Find a node in the forwards-direction dependency sub-graph starting 2299 * at @root->class that matches @bit. 2300 * 2301 * Return BFS_MATCH if such a node exists in the subgraph, and put that node 2302 * into *@target_entry. 2303 */ 2304 static enum bfs_result 2305 find_usage_forwards(struct lock_list *root, unsigned long usage_mask, 2306 struct lock_list **target_entry) 2307 { 2308 enum bfs_result result; 2309 2310 debug_atomic_inc(nr_find_usage_forwards_checks); 2311 2312 result = __bfs_forwards(root, &usage_mask, usage_match, usage_skip, target_entry); 2313 2314 return result; 2315 } 2316 2317 /* 2318 * Find a node in the backwards-direction dependency sub-graph starting 2319 * at @root->class that matches @bit. 2320 */ 2321 static enum bfs_result 2322 find_usage_backwards(struct lock_list *root, unsigned long usage_mask, 2323 struct lock_list **target_entry) 2324 { 2325 enum bfs_result result; 2326 2327 debug_atomic_inc(nr_find_usage_backwards_checks); 2328 2329 result = __bfs_backwards(root, &usage_mask, usage_match, usage_skip, target_entry); 2330 2331 return result; 2332 } 2333 2334 static void print_lock_class_header(struct lock_class *class, int depth) 2335 { 2336 int bit; 2337 2338 printk("%*s->", depth, ""); 2339 print_lock_name(NULL, class); 2340 #ifdef CONFIG_DEBUG_LOCKDEP 2341 printk(KERN_CONT " ops: %lu", debug_class_ops_read(class)); 2342 #endif 2343 printk(KERN_CONT " {\n"); 2344 2345 for (bit = 0; bit < LOCK_TRACE_STATES; bit++) { 2346 if (class->usage_mask & (1 << bit)) { 2347 int len = depth; 2348 2349 len += printk("%*s %s", depth, "", usage_str[bit]); 2350 len += printk(KERN_CONT " at:\n"); 2351 print_lock_trace(class->usage_traces[bit], len); 2352 } 2353 } 2354 printk("%*s }\n", depth, ""); 2355 2356 printk("%*s ... key at: [<%px>] %pS\n", 2357 depth, "", class->key, class->key); 2358 } 2359 2360 /* 2361 * Dependency path printing: 2362 * 2363 * After BFS we get a lock dependency path (linked via ->parent of lock_list), 2364 * printing out each lock in the dependency path will help on understanding how 2365 * the deadlock could happen. Here are some details about dependency path 2366 * printing: 2367 * 2368 * 1) A lock_list can be either forwards or backwards for a lock dependency, 2369 * for a lock dependency A -> B, there are two lock_lists: 2370 * 2371 * a) lock_list in the ->locks_after list of A, whose ->class is B and 2372 * ->links_to is A. In this case, we can say the lock_list is 2373 * "A -> B" (forwards case). 2374 * 2375 * b) lock_list in the ->locks_before list of B, whose ->class is A 2376 * and ->links_to is B. In this case, we can say the lock_list is 2377 * "B <- A" (bacwards case). 2378 * 2379 * The ->trace of both a) and b) point to the call trace where B was 2380 * acquired with A held. 2381 * 2382 * 2) A "helper" lock_list is introduced during BFS, this lock_list doesn't 2383 * represent a certain lock dependency, it only provides an initial entry 2384 * for BFS. For example, BFS may introduce a "helper" lock_list whose 2385 * ->class is A, as a result BFS will search all dependencies starting with 2386 * A, e.g. A -> B or A -> C. 2387 * 2388 * The notation of a forwards helper lock_list is like "-> A", which means 2389 * we should search the forwards dependencies starting with "A", e.g A -> B 2390 * or A -> C. 2391 * 2392 * The notation of a bacwards helper lock_list is like "<- B", which means 2393 * we should search the backwards dependencies ending with "B", e.g. 2394 * B <- A or B <- C. 2395 */ 2396 2397 /* 2398 * printk the shortest lock dependencies from @root to @leaf in reverse order. 2399 * 2400 * We have a lock dependency path as follow: 2401 * 2402 * @root @leaf 2403 * | | 2404 * V V 2405 * ->parent ->parent 2406 * | lock_list | <--------- | lock_list | ... | lock_list | <--------- | lock_list | 2407 * | -> L1 | | L1 -> L2 | ... |Ln-2 -> Ln-1| | Ln-1 -> Ln| 2408 * 2409 * , so it's natural that we start from @leaf and print every ->class and 2410 * ->trace until we reach the @root. 2411 */ 2412 static void __used 2413 print_shortest_lock_dependencies(struct lock_list *leaf, 2414 struct lock_list *root) 2415 { 2416 struct lock_list *entry = leaf; 2417 int depth; 2418 2419 /*compute depth from generated tree by BFS*/ 2420 depth = get_lock_depth(leaf); 2421 2422 do { 2423 print_lock_class_header(entry->class, depth); 2424 printk("%*s ... acquired at:\n", depth, ""); 2425 print_lock_trace(entry->trace, 2); 2426 printk("\n"); 2427 2428 if (depth == 0 && (entry != root)) { 2429 printk("lockdep:%s bad path found in chain graph\n", __func__); 2430 break; 2431 } 2432 2433 entry = get_lock_parent(entry); 2434 depth--; 2435 } while (entry && (depth >= 0)); 2436 } 2437 2438 /* 2439 * printk the shortest lock dependencies from @leaf to @root. 2440 * 2441 * We have a lock dependency path (from a backwards search) as follow: 2442 * 2443 * @leaf @root 2444 * | | 2445 * V V 2446 * ->parent ->parent 2447 * | lock_list | ---------> | lock_list | ... | lock_list | ---------> | lock_list | 2448 * | L2 <- L1 | | L3 <- L2 | ... | Ln <- Ln-1 | | <- Ln | 2449 * 2450 * , so when we iterate from @leaf to @root, we actually print the lock 2451 * dependency path L1 -> L2 -> .. -> Ln in the non-reverse order. 2452 * 2453 * Another thing to notice here is that ->class of L2 <- L1 is L1, while the 2454 * ->trace of L2 <- L1 is the call trace of L2, in fact we don't have the call 2455 * trace of L1 in the dependency path, which is alright, because most of the 2456 * time we can figure out where L1 is held from the call trace of L2. 2457 */ 2458 static void __used 2459 print_shortest_lock_dependencies_backwards(struct lock_list *leaf, 2460 struct lock_list *root) 2461 { 2462 struct lock_list *entry = leaf; 2463 const struct lock_trace *trace = NULL; 2464 int depth; 2465 2466 /*compute depth from generated tree by BFS*/ 2467 depth = get_lock_depth(leaf); 2468 2469 do { 2470 print_lock_class_header(entry->class, depth); 2471 if (trace) { 2472 printk("%*s ... acquired at:\n", depth, ""); 2473 print_lock_trace(trace, 2); 2474 printk("\n"); 2475 } 2476 2477 /* 2478 * Record the pointer to the trace for the next lock_list 2479 * entry, see the comments for the function. 2480 */ 2481 trace = entry->trace; 2482 2483 if (depth == 0 && (entry != root)) { 2484 printk("lockdep:%s bad path found in chain graph\n", __func__); 2485 break; 2486 } 2487 2488 entry = get_lock_parent(entry); 2489 depth--; 2490 } while (entry && (depth >= 0)); 2491 } 2492 2493 static void 2494 print_irq_lock_scenario(struct lock_list *safe_entry, 2495 struct lock_list *unsafe_entry, 2496 struct lock_class *prev_class, 2497 struct lock_class *next_class) 2498 { 2499 struct lock_class *safe_class = safe_entry->class; 2500 struct lock_class *unsafe_class = unsafe_entry->class; 2501 struct lock_class *middle_class = prev_class; 2502 2503 if (middle_class == safe_class) 2504 middle_class = next_class; 2505 2506 /* 2507 * A direct locking problem where unsafe_class lock is taken 2508 * directly by safe_class lock, then all we need to show 2509 * is the deadlock scenario, as it is obvious that the 2510 * unsafe lock is taken under the safe lock. 2511 * 2512 * But if there is a chain instead, where the safe lock takes 2513 * an intermediate lock (middle_class) where this lock is 2514 * not the same as the safe lock, then the lock chain is 2515 * used to describe the problem. Otherwise we would need 2516 * to show a different CPU case for each link in the chain 2517 * from the safe_class lock to the unsafe_class lock. 2518 */ 2519 if (middle_class != unsafe_class) { 2520 printk("Chain exists of:\n "); 2521 __print_lock_name(NULL, safe_class); 2522 printk(KERN_CONT " --> "); 2523 __print_lock_name(NULL, middle_class); 2524 printk(KERN_CONT " --> "); 2525 __print_lock_name(NULL, unsafe_class); 2526 printk(KERN_CONT "\n\n"); 2527 } 2528 2529 printk(" Possible interrupt unsafe locking scenario:\n\n"); 2530 printk(" CPU0 CPU1\n"); 2531 printk(" ---- ----\n"); 2532 printk(" lock("); 2533 __print_lock_name(NULL, unsafe_class); 2534 printk(KERN_CONT ");\n"); 2535 printk(" local_irq_disable();\n"); 2536 printk(" lock("); 2537 __print_lock_name(NULL, safe_class); 2538 printk(KERN_CONT ");\n"); 2539 printk(" lock("); 2540 __print_lock_name(NULL, middle_class); 2541 printk(KERN_CONT ");\n"); 2542 printk(" <Interrupt>\n"); 2543 printk(" lock("); 2544 __print_lock_name(NULL, safe_class); 2545 printk(KERN_CONT ");\n"); 2546 printk("\n *** DEADLOCK ***\n\n"); 2547 } 2548 2549 static void 2550 print_bad_irq_dependency(struct task_struct *curr, 2551 struct lock_list *prev_root, 2552 struct lock_list *next_root, 2553 struct lock_list *backwards_entry, 2554 struct lock_list *forwards_entry, 2555 struct held_lock *prev, 2556 struct held_lock *next, 2557 enum lock_usage_bit bit1, 2558 enum lock_usage_bit bit2, 2559 const char *irqclass) 2560 { 2561 if (!debug_locks_off_graph_unlock() || debug_locks_silent) 2562 return; 2563 2564 nbcon_cpu_emergency_enter(); 2565 2566 pr_warn("\n"); 2567 pr_warn("=====================================================\n"); 2568 pr_warn("WARNING: %s-safe -> %s-unsafe lock order detected\n", 2569 irqclass, irqclass); 2570 print_kernel_ident(); 2571 pr_warn("-----------------------------------------------------\n"); 2572 pr_warn("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] is trying to acquire:\n", 2573 curr->comm, task_pid_nr(curr), 2574 lockdep_hardirq_context(), hardirq_count() >> HARDIRQ_SHIFT, 2575 curr->softirq_context, softirq_count() >> SOFTIRQ_SHIFT, 2576 lockdep_hardirqs_enabled(), 2577 curr->softirqs_enabled); 2578 print_lock(next); 2579 2580 pr_warn("\nand this task is already holding:\n"); 2581 print_lock(prev); 2582 pr_warn("which would create a new lock dependency:\n"); 2583 print_lock_name(prev, hlock_class(prev)); 2584 pr_cont(" ->"); 2585 print_lock_name(next, hlock_class(next)); 2586 pr_cont("\n"); 2587 2588 pr_warn("\nbut this new dependency connects a %s-irq-safe lock:\n", 2589 irqclass); 2590 print_lock_name(NULL, backwards_entry->class); 2591 pr_warn("\n... which became %s-irq-safe at:\n", irqclass); 2592 2593 print_lock_trace(backwards_entry->class->usage_traces[bit1], 1); 2594 2595 pr_warn("\nto a %s-irq-unsafe lock:\n", irqclass); 2596 print_lock_name(NULL, forwards_entry->class); 2597 pr_warn("\n... which became %s-irq-unsafe at:\n", irqclass); 2598 pr_warn("..."); 2599 2600 print_lock_trace(forwards_entry->class->usage_traces[bit2], 1); 2601 2602 pr_warn("\nother info that might help us debug this:\n\n"); 2603 print_irq_lock_scenario(backwards_entry, forwards_entry, 2604 hlock_class(prev), hlock_class(next)); 2605 2606 lockdep_print_held_locks(curr); 2607 2608 pr_warn("\nthe dependencies between %s-irq-safe lock and the holding lock:\n", irqclass); 2609 print_shortest_lock_dependencies_backwards(backwards_entry, prev_root); 2610 2611 pr_warn("\nthe dependencies between the lock to be acquired"); 2612 pr_warn(" and %s-irq-unsafe lock:\n", irqclass); 2613 next_root->trace = save_trace(); 2614 if (!next_root->trace) 2615 goto out; 2616 print_shortest_lock_dependencies(forwards_entry, next_root); 2617 2618 pr_warn("\nstack backtrace:\n"); 2619 dump_stack(); 2620 out: 2621 nbcon_cpu_emergency_exit(); 2622 } 2623 2624 static const char *state_names[] = { 2625 #define LOCKDEP_STATE(__STATE) \ 2626 __stringify(__STATE), 2627 #include "lockdep_states.h" 2628 #undef LOCKDEP_STATE 2629 }; 2630 2631 static const char *state_rnames[] = { 2632 #define LOCKDEP_STATE(__STATE) \ 2633 __stringify(__STATE)"-READ", 2634 #include "lockdep_states.h" 2635 #undef LOCKDEP_STATE 2636 }; 2637 2638 static inline const char *state_name(enum lock_usage_bit bit) 2639 { 2640 if (bit & LOCK_USAGE_READ_MASK) 2641 return state_rnames[bit >> LOCK_USAGE_DIR_MASK]; 2642 else 2643 return state_names[bit >> LOCK_USAGE_DIR_MASK]; 2644 } 2645 2646 /* 2647 * The bit number is encoded like: 2648 * 2649 * bit0: 0 exclusive, 1 read lock 2650 * bit1: 0 used in irq, 1 irq enabled 2651 * bit2-n: state 2652 */ 2653 static int exclusive_bit(int new_bit) 2654 { 2655 int state = new_bit & LOCK_USAGE_STATE_MASK; 2656 int dir = new_bit & LOCK_USAGE_DIR_MASK; 2657 2658 /* 2659 * keep state, bit flip the direction and strip read. 2660 */ 2661 return state | (dir ^ LOCK_USAGE_DIR_MASK); 2662 } 2663 2664 /* 2665 * Observe that when given a bitmask where each bitnr is encoded as above, a 2666 * right shift of the mask transforms the individual bitnrs as -1 and 2667 * conversely, a left shift transforms into +1 for the individual bitnrs. 2668 * 2669 * So for all bits whose number have LOCK_ENABLED_* set (bitnr1 == 1), we can 2670 * create the mask with those bit numbers using LOCK_USED_IN_* (bitnr1 == 0) 2671 * instead by subtracting the bit number by 2, or shifting the mask right by 2. 2672 * 2673 * Similarly, bitnr1 == 0 becomes bitnr1 == 1 by adding 2, or shifting left 2. 2674 * 2675 * So split the mask (note that LOCKF_ENABLED_IRQ_ALL|LOCKF_USED_IN_IRQ_ALL is 2676 * all bits set) and recompose with bitnr1 flipped. 2677 */ 2678 static unsigned long invert_dir_mask(unsigned long mask) 2679 { 2680 unsigned long excl = 0; 2681 2682 /* Invert dir */ 2683 excl |= (mask & LOCKF_ENABLED_IRQ_ALL) >> LOCK_USAGE_DIR_MASK; 2684 excl |= (mask & LOCKF_USED_IN_IRQ_ALL) << LOCK_USAGE_DIR_MASK; 2685 2686 return excl; 2687 } 2688 2689 /* 2690 * Note that a LOCK_ENABLED_IRQ_*_READ usage and a LOCK_USED_IN_IRQ_*_READ 2691 * usage may cause deadlock too, for example: 2692 * 2693 * P1 P2 2694 * <irq disabled> 2695 * write_lock(l1); <irq enabled> 2696 * read_lock(l2); 2697 * write_lock(l2); 2698 * <in irq> 2699 * read_lock(l1); 2700 * 2701 * , in above case, l1 will be marked as LOCK_USED_IN_IRQ_HARDIRQ_READ and l2 2702 * will marked as LOCK_ENABLE_IRQ_HARDIRQ_READ, and this is a possible 2703 * deadlock. 2704 * 2705 * In fact, all of the following cases may cause deadlocks: 2706 * 2707 * LOCK_USED_IN_IRQ_* -> LOCK_ENABLED_IRQ_* 2708 * LOCK_USED_IN_IRQ_*_READ -> LOCK_ENABLED_IRQ_* 2709 * LOCK_USED_IN_IRQ_* -> LOCK_ENABLED_IRQ_*_READ 2710 * LOCK_USED_IN_IRQ_*_READ -> LOCK_ENABLED_IRQ_*_READ 2711 * 2712 * As a result, to calculate the "exclusive mask", first we invert the 2713 * direction (USED_IN/ENABLED) of the original mask, and 1) for all bits with 2714 * bitnr0 set (LOCK_*_READ), add those with bitnr0 cleared (LOCK_*). 2) for all 2715 * bits with bitnr0 cleared (LOCK_*_READ), add those with bitnr0 set (LOCK_*). 2716 */ 2717 static unsigned long exclusive_mask(unsigned long mask) 2718 { 2719 unsigned long excl = invert_dir_mask(mask); 2720 2721 excl |= (excl & LOCKF_IRQ_READ) >> LOCK_USAGE_READ_MASK; 2722 excl |= (excl & LOCKF_IRQ) << LOCK_USAGE_READ_MASK; 2723 2724 return excl; 2725 } 2726 2727 /* 2728 * Retrieve the _possible_ original mask to which @mask is 2729 * exclusive. Ie: this is the opposite of exclusive_mask(). 2730 * Note that 2 possible original bits can match an exclusive 2731 * bit: one has LOCK_USAGE_READ_MASK set, the other has it 2732 * cleared. So both are returned for each exclusive bit. 2733 */ 2734 static unsigned long original_mask(unsigned long mask) 2735 { 2736 unsigned long excl = invert_dir_mask(mask); 2737 2738 /* Include read in existing usages */ 2739 excl |= (excl & LOCKF_IRQ_READ) >> LOCK_USAGE_READ_MASK; 2740 excl |= (excl & LOCKF_IRQ) << LOCK_USAGE_READ_MASK; 2741 2742 return excl; 2743 } 2744 2745 /* 2746 * Find the first pair of bit match between an original 2747 * usage mask and an exclusive usage mask. 2748 */ 2749 static int find_exclusive_match(unsigned long mask, 2750 unsigned long excl_mask, 2751 enum lock_usage_bit *bitp, 2752 enum lock_usage_bit *excl_bitp) 2753 { 2754 int bit, excl, excl_read; 2755 2756 for_each_set_bit(bit, &mask, LOCK_USED) { 2757 /* 2758 * exclusive_bit() strips the read bit, however, 2759 * LOCK_ENABLED_IRQ_*_READ may cause deadlocks too, so we need 2760 * to search excl | LOCK_USAGE_READ_MASK as well. 2761 */ 2762 excl = exclusive_bit(bit); 2763 excl_read = excl | LOCK_USAGE_READ_MASK; 2764 if (excl_mask & lock_flag(excl)) { 2765 *bitp = bit; 2766 *excl_bitp = excl; 2767 return 0; 2768 } else if (excl_mask & lock_flag(excl_read)) { 2769 *bitp = bit; 2770 *excl_bitp = excl_read; 2771 return 0; 2772 } 2773 } 2774 return -1; 2775 } 2776 2777 /* 2778 * Prove that the new dependency does not connect a hardirq-safe(-read) 2779 * lock with a hardirq-unsafe lock - to achieve this we search 2780 * the backwards-subgraph starting at <prev>, and the 2781 * forwards-subgraph starting at <next>: 2782 */ 2783 static int check_irq_usage(struct task_struct *curr, struct held_lock *prev, 2784 struct held_lock *next) 2785 { 2786 unsigned long usage_mask = 0, forward_mask, backward_mask; 2787 enum lock_usage_bit forward_bit = 0, backward_bit = 0; 2788 struct lock_list *target_entry1; 2789 struct lock_list *target_entry; 2790 struct lock_list this, that; 2791 enum bfs_result ret; 2792 2793 /* 2794 * Step 1: gather all hard/soft IRQs usages backward in an 2795 * accumulated usage mask. 2796 */ 2797 bfs_init_rootb(&this, prev); 2798 2799 ret = __bfs_backwards(&this, &usage_mask, usage_accumulate, usage_skip, NULL); 2800 if (bfs_error(ret)) { 2801 print_bfs_bug(ret); 2802 return 0; 2803 } 2804 2805 usage_mask &= LOCKF_USED_IN_IRQ_ALL; 2806 if (!usage_mask) 2807 return 1; 2808 2809 /* 2810 * Step 2: find exclusive uses forward that match the previous 2811 * backward accumulated mask. 2812 */ 2813 forward_mask = exclusive_mask(usage_mask); 2814 2815 bfs_init_root(&that, next); 2816 2817 ret = find_usage_forwards(&that, forward_mask, &target_entry1); 2818 if (bfs_error(ret)) { 2819 print_bfs_bug(ret); 2820 return 0; 2821 } 2822 if (ret == BFS_RNOMATCH) 2823 return 1; 2824 2825 /* 2826 * Step 3: we found a bad match! Now retrieve a lock from the backward 2827 * list whose usage mask matches the exclusive usage mask from the 2828 * lock found on the forward list. 2829 * 2830 * Note, we should only keep the LOCKF_ENABLED_IRQ_ALL bits, considering 2831 * the follow case: 2832 * 2833 * When trying to add A -> B to the graph, we find that there is a 2834 * hardirq-safe L, that L -> ... -> A, and another hardirq-unsafe M, 2835 * that B -> ... -> M. However M is **softirq-safe**, if we use exact 2836 * invert bits of M's usage_mask, we will find another lock N that is 2837 * **softirq-unsafe** and N -> ... -> A, however N -> .. -> M will not 2838 * cause a inversion deadlock. 2839 */ 2840 backward_mask = original_mask(target_entry1->class->usage_mask & LOCKF_ENABLED_IRQ_ALL); 2841 2842 ret = find_usage_backwards(&this, backward_mask, &target_entry); 2843 if (bfs_error(ret)) { 2844 print_bfs_bug(ret); 2845 return 0; 2846 } 2847 if (DEBUG_LOCKS_WARN_ON(ret == BFS_RNOMATCH)) 2848 return 1; 2849 2850 /* 2851 * Step 4: narrow down to a pair of incompatible usage bits 2852 * and report it. 2853 */ 2854 ret = find_exclusive_match(target_entry->class->usage_mask, 2855 target_entry1->class->usage_mask, 2856 &backward_bit, &forward_bit); 2857 if (DEBUG_LOCKS_WARN_ON(ret == -1)) 2858 return 1; 2859 2860 print_bad_irq_dependency(curr, &this, &that, 2861 target_entry, target_entry1, 2862 prev, next, 2863 backward_bit, forward_bit, 2864 state_name(backward_bit)); 2865 2866 return 0; 2867 } 2868 2869 #else 2870 2871 static inline int check_irq_usage(struct task_struct *curr, 2872 struct held_lock *prev, struct held_lock *next) 2873 { 2874 return 1; 2875 } 2876 2877 static inline bool usage_skip(struct lock_list *entry, void *mask) 2878 { 2879 return false; 2880 } 2881 2882 #endif /* CONFIG_TRACE_IRQFLAGS */ 2883 2884 #ifdef CONFIG_LOCKDEP_SMALL 2885 /* 2886 * We are about to add A -> B into the dependency graph, and in __bfs() a 2887 * strong dependency path A -> .. -> B is found: hlock_class equals 2888 * entry->class. 2889 * 2890 * If A -> .. -> B can replace A -> B in any __bfs() search (means the former 2891 * is _stronger_ than or equal to the latter), we consider A -> B as redundant. 2892 * For example if A -> .. -> B is -(EN)-> (i.e. A -(E*)-> .. -(*N)-> B), and A 2893 * -> B is -(ER)-> or -(EN)->, then we don't need to add A -> B into the 2894 * dependency graph, as any strong path ..-> A -> B ->.. we can get with 2895 * having dependency A -> B, we could already get a equivalent path ..-> A -> 2896 * .. -> B -> .. with A -> .. -> B. Therefore A -> B is redundant. 2897 * 2898 * We need to make sure both the start and the end of A -> .. -> B is not 2899 * weaker than A -> B. For the start part, please see the comment in 2900 * check_redundant(). For the end part, we need: 2901 * 2902 * Either 2903 * 2904 * a) A -> B is -(*R)-> (everything is not weaker than that) 2905 * 2906 * or 2907 * 2908 * b) A -> .. -> B is -(*N)-> (nothing is stronger than this) 2909 * 2910 */ 2911 static inline bool hlock_equal(struct lock_list *entry, void *data) 2912 { 2913 struct held_lock *hlock = (struct held_lock *)data; 2914 2915 return hlock_class(hlock) == entry->class && /* Found A -> .. -> B */ 2916 (hlock->read == 2 || /* A -> B is -(*R)-> */ 2917 !entry->only_xr); /* A -> .. -> B is -(*N)-> */ 2918 } 2919 2920 /* 2921 * Check that the dependency graph starting at <src> can lead to 2922 * <target> or not. If it can, <src> -> <target> dependency is already 2923 * in the graph. 2924 * 2925 * Return BFS_RMATCH if it does, or BFS_RNOMATCH if it does not, return BFS_E* if 2926 * any error appears in the bfs search. 2927 */ 2928 static noinline enum bfs_result 2929 check_redundant(struct held_lock *src, struct held_lock *target) 2930 { 2931 enum bfs_result ret; 2932 struct lock_list *target_entry; 2933 struct lock_list src_entry; 2934 2935 bfs_init_root(&src_entry, src); 2936 /* 2937 * Special setup for check_redundant(). 2938 * 2939 * To report redundant, we need to find a strong dependency path that 2940 * is equal to or stronger than <src> -> <target>. So if <src> is E, 2941 * we need to let __bfs() only search for a path starting at a -(E*)->, 2942 * we achieve this by setting the initial node's ->only_xr to true in 2943 * that case. And if <prev> is S, we set initial ->only_xr to false 2944 * because both -(S*)-> (equal) and -(E*)-> (stronger) are redundant. 2945 */ 2946 src_entry.only_xr = src->read == 0; 2947 2948 debug_atomic_inc(nr_redundant_checks); 2949 2950 /* 2951 * Note: we skip local_lock() for redundant check, because as the 2952 * comment in usage_skip(), A -> local_lock() -> B and A -> B are not 2953 * the same. 2954 */ 2955 ret = check_path(target, &src_entry, hlock_equal, usage_skip, &target_entry); 2956 2957 if (ret == BFS_RMATCH) 2958 debug_atomic_inc(nr_redundant); 2959 2960 return ret; 2961 } 2962 2963 #else 2964 2965 static inline enum bfs_result 2966 check_redundant(struct held_lock *src, struct held_lock *target) 2967 { 2968 return BFS_RNOMATCH; 2969 } 2970 2971 #endif 2972 2973 static void inc_chains(int irq_context) 2974 { 2975 if (irq_context & LOCK_CHAIN_HARDIRQ_CONTEXT) 2976 nr_hardirq_chains++; 2977 else if (irq_context & LOCK_CHAIN_SOFTIRQ_CONTEXT) 2978 nr_softirq_chains++; 2979 else 2980 nr_process_chains++; 2981 } 2982 2983 static void dec_chains(int irq_context) 2984 { 2985 if (irq_context & LOCK_CHAIN_HARDIRQ_CONTEXT) 2986 nr_hardirq_chains--; 2987 else if (irq_context & LOCK_CHAIN_SOFTIRQ_CONTEXT) 2988 nr_softirq_chains--; 2989 else 2990 nr_process_chains--; 2991 } 2992 2993 static void 2994 print_deadlock_scenario(struct held_lock *nxt, struct held_lock *prv) 2995 { 2996 struct lock_class *next = hlock_class(nxt); 2997 struct lock_class *prev = hlock_class(prv); 2998 2999 printk(" Possible unsafe locking scenario:\n\n"); 3000 printk(" CPU0\n"); 3001 printk(" ----\n"); 3002 printk(" lock("); 3003 __print_lock_name(prv, prev); 3004 printk(KERN_CONT ");\n"); 3005 printk(" lock("); 3006 __print_lock_name(nxt, next); 3007 printk(KERN_CONT ");\n"); 3008 printk("\n *** DEADLOCK ***\n\n"); 3009 printk(" May be due to missing lock nesting notation\n\n"); 3010 } 3011 3012 static void 3013 print_deadlock_bug(struct task_struct *curr, struct held_lock *prev, 3014 struct held_lock *next) 3015 { 3016 struct lock_class *class = hlock_class(prev); 3017 3018 if (!debug_locks_off_graph_unlock() || debug_locks_silent) 3019 return; 3020 3021 nbcon_cpu_emergency_enter(); 3022 3023 pr_warn("\n"); 3024 pr_warn("============================================\n"); 3025 pr_warn("WARNING: possible recursive locking detected\n"); 3026 print_kernel_ident(); 3027 pr_warn("--------------------------------------------\n"); 3028 pr_warn("%s/%d is trying to acquire lock:\n", 3029 curr->comm, task_pid_nr(curr)); 3030 print_lock(next); 3031 pr_warn("\nbut task is already holding lock:\n"); 3032 print_lock(prev); 3033 3034 if (class->cmp_fn) { 3035 pr_warn("and the lock comparison function returns %i:\n", 3036 class->cmp_fn(prev->instance, next->instance)); 3037 } 3038 3039 pr_warn("\nother info that might help us debug this:\n"); 3040 print_deadlock_scenario(next, prev); 3041 lockdep_print_held_locks(curr); 3042 3043 pr_warn("\nstack backtrace:\n"); 3044 dump_stack(); 3045 3046 nbcon_cpu_emergency_exit(); 3047 } 3048 3049 /* 3050 * Check whether we are holding such a class already. 3051 * 3052 * (Note that this has to be done separately, because the graph cannot 3053 * detect such classes of deadlocks.) 3054 * 3055 * Returns: 0 on deadlock detected, 1 on OK, 2 if another lock with the same 3056 * lock class is held but nest_lock is also held, i.e. we rely on the 3057 * nest_lock to avoid the deadlock. 3058 */ 3059 static int 3060 check_deadlock(struct task_struct *curr, struct held_lock *next) 3061 { 3062 struct lock_class *class; 3063 struct held_lock *prev; 3064 struct held_lock *nest = NULL; 3065 int i; 3066 3067 for (i = 0; i < curr->lockdep_depth; i++) { 3068 prev = curr->held_locks + i; 3069 3070 if (prev->instance == next->nest_lock) 3071 nest = prev; 3072 3073 if (hlock_class(prev) != hlock_class(next)) 3074 continue; 3075 3076 /* 3077 * Allow read-after-read recursion of the same 3078 * lock class (i.e. read_lock(lock)+read_lock(lock)): 3079 */ 3080 if ((next->read == 2) && prev->read) 3081 continue; 3082 3083 class = hlock_class(prev); 3084 3085 if (class->cmp_fn && 3086 class->cmp_fn(prev->instance, next->instance) < 0) 3087 continue; 3088 3089 /* 3090 * We're holding the nest_lock, which serializes this lock's 3091 * nesting behaviour. 3092 */ 3093 if (nest) 3094 return 2; 3095 3096 print_deadlock_bug(curr, prev, next); 3097 return 0; 3098 } 3099 return 1; 3100 } 3101 3102 /* 3103 * There was a chain-cache miss, and we are about to add a new dependency 3104 * to a previous lock. We validate the following rules: 3105 * 3106 * - would the adding of the <prev> -> <next> dependency create a 3107 * circular dependency in the graph? [== circular deadlock] 3108 * 3109 * - does the new prev->next dependency connect any hardirq-safe lock 3110 * (in the full backwards-subgraph starting at <prev>) with any 3111 * hardirq-unsafe lock (in the full forwards-subgraph starting at 3112 * <next>)? [== illegal lock inversion with hardirq contexts] 3113 * 3114 * - does the new prev->next dependency connect any softirq-safe lock 3115 * (in the full backwards-subgraph starting at <prev>) with any 3116 * softirq-unsafe lock (in the full forwards-subgraph starting at 3117 * <next>)? [== illegal lock inversion with softirq contexts] 3118 * 3119 * any of these scenarios could lead to a deadlock. 3120 * 3121 * Then if all the validations pass, we add the forwards and backwards 3122 * dependency. 3123 */ 3124 static int 3125 check_prev_add(struct task_struct *curr, struct held_lock *prev, 3126 struct held_lock *next, u16 distance, 3127 struct lock_trace **const trace) 3128 { 3129 struct lock_list *entry; 3130 enum bfs_result ret; 3131 3132 if (!hlock_class(prev)->key || !hlock_class(next)->key) { 3133 /* 3134 * The warning statements below may trigger a use-after-free 3135 * of the class name. It is better to trigger a use-after free 3136 * and to have the class name most of the time instead of not 3137 * having the class name available. 3138 */ 3139 WARN_ONCE(!debug_locks_silent && !hlock_class(prev)->key, 3140 "Detected use-after-free of lock class %px/%s\n", 3141 hlock_class(prev), 3142 hlock_class(prev)->name); 3143 WARN_ONCE(!debug_locks_silent && !hlock_class(next)->key, 3144 "Detected use-after-free of lock class %px/%s\n", 3145 hlock_class(next), 3146 hlock_class(next)->name); 3147 return 2; 3148 } 3149 3150 if (prev->class_idx == next->class_idx) { 3151 struct lock_class *class = hlock_class(prev); 3152 3153 if (class->cmp_fn && 3154 class->cmp_fn(prev->instance, next->instance) < 0) 3155 return 2; 3156 } 3157 3158 /* 3159 * Prove that the new <prev> -> <next> dependency would not 3160 * create a circular dependency in the graph. (We do this by 3161 * a breadth-first search into the graph starting at <next>, 3162 * and check whether we can reach <prev>.) 3163 * 3164 * The search is limited by the size of the circular queue (i.e., 3165 * MAX_CIRCULAR_QUEUE_SIZE) which keeps track of a breadth of nodes 3166 * in the graph whose neighbours are to be checked. 3167 */ 3168 ret = check_noncircular(next, prev, trace); 3169 if (unlikely(bfs_error(ret) || ret == BFS_RMATCH)) 3170 return 0; 3171 3172 if (!check_irq_usage(curr, prev, next)) 3173 return 0; 3174 3175 /* 3176 * Is the <prev> -> <next> dependency already present? 3177 * 3178 * (this may occur even though this is a new chain: consider 3179 * e.g. the L1 -> L2 -> L3 -> L4 and the L5 -> L1 -> L2 -> L3 3180 * chains - the second one will be new, but L1 already has 3181 * L2 added to its dependency list, due to the first chain.) 3182 */ 3183 list_for_each_entry(entry, &hlock_class(prev)->locks_after, entry) { 3184 if (entry->class == hlock_class(next)) { 3185 if (distance == 1) 3186 entry->distance = 1; 3187 entry->dep |= calc_dep(prev, next); 3188 3189 /* 3190 * Also, update the reverse dependency in @next's 3191 * ->locks_before list. 3192 * 3193 * Here we reuse @entry as the cursor, which is fine 3194 * because we won't go to the next iteration of the 3195 * outer loop: 3196 * 3197 * For normal cases, we return in the inner loop. 3198 * 3199 * If we fail to return, we have inconsistency, i.e. 3200 * <prev>::locks_after contains <next> while 3201 * <next>::locks_before doesn't contain <prev>. In 3202 * that case, we return after the inner and indicate 3203 * something is wrong. 3204 */ 3205 list_for_each_entry(entry, &hlock_class(next)->locks_before, entry) { 3206 if (entry->class == hlock_class(prev)) { 3207 if (distance == 1) 3208 entry->distance = 1; 3209 entry->dep |= calc_depb(prev, next); 3210 return 1; 3211 } 3212 } 3213 3214 /* <prev> is not found in <next>::locks_before */ 3215 return 0; 3216 } 3217 } 3218 3219 /* 3220 * Is the <prev> -> <next> link redundant? 3221 */ 3222 ret = check_redundant(prev, next); 3223 if (bfs_error(ret)) 3224 return 0; 3225 else if (ret == BFS_RMATCH) 3226 return 2; 3227 3228 if (!*trace) { 3229 *trace = save_trace(); 3230 if (!*trace) 3231 return 0; 3232 } 3233 3234 /* 3235 * Ok, all validations passed, add the new lock 3236 * to the previous lock's dependency list: 3237 */ 3238 ret = add_lock_to_list(hlock_class(next), hlock_class(prev), 3239 &hlock_class(prev)->locks_after, distance, 3240 calc_dep(prev, next), *trace); 3241 3242 if (!ret) 3243 return 0; 3244 3245 ret = add_lock_to_list(hlock_class(prev), hlock_class(next), 3246 &hlock_class(next)->locks_before, distance, 3247 calc_depb(prev, next), *trace); 3248 if (!ret) 3249 return 0; 3250 3251 return 2; 3252 } 3253 3254 /* 3255 * Add the dependency to all directly-previous locks that are 'relevant'. 3256 * The ones that are relevant are (in increasing distance from curr): 3257 * all consecutive trylock entries and the final non-trylock entry - or 3258 * the end of this context's lock-chain - whichever comes first. 3259 */ 3260 static int 3261 check_prevs_add(struct task_struct *curr, struct held_lock *next) 3262 { 3263 struct lock_trace *trace = NULL; 3264 int depth = curr->lockdep_depth; 3265 struct held_lock *hlock; 3266 3267 /* 3268 * Debugging checks. 3269 * 3270 * Depth must not be zero for a non-head lock: 3271 */ 3272 if (!depth) 3273 goto out_bug; 3274 /* 3275 * At least two relevant locks must exist for this 3276 * to be a head: 3277 */ 3278 if (curr->held_locks[depth].irq_context != 3279 curr->held_locks[depth-1].irq_context) 3280 goto out_bug; 3281 3282 for (;;) { 3283 u16 distance = curr->lockdep_depth - depth + 1; 3284 hlock = curr->held_locks + depth - 1; 3285 3286 if (hlock->check) { 3287 int ret = check_prev_add(curr, hlock, next, distance, &trace); 3288 if (!ret) 3289 return 0; 3290 3291 /* 3292 * Stop after the first non-trylock entry, 3293 * as non-trylock entries have added their 3294 * own direct dependencies already, so this 3295 * lock is connected to them indirectly: 3296 */ 3297 if (!hlock->trylock) 3298 break; 3299 } 3300 3301 depth--; 3302 /* 3303 * End of lock-stack? 3304 */ 3305 if (!depth) 3306 break; 3307 /* 3308 * Stop the search if we cross into another context: 3309 */ 3310 if (curr->held_locks[depth].irq_context != 3311 curr->held_locks[depth-1].irq_context) 3312 break; 3313 } 3314 return 1; 3315 out_bug: 3316 if (!debug_locks_off_graph_unlock()) 3317 return 0; 3318 3319 /* 3320 * Clearly we all shouldn't be here, but since we made it we 3321 * can reliable say we messed up our state. See the above two 3322 * gotos for reasons why we could possibly end up here. 3323 */ 3324 WARN_ON(1); 3325 3326 return 0; 3327 } 3328 3329 struct lock_chain lock_chains[MAX_LOCKDEP_CHAINS]; 3330 static DECLARE_BITMAP(lock_chains_in_use, MAX_LOCKDEP_CHAINS); 3331 static u16 chain_hlocks[MAX_LOCKDEP_CHAIN_HLOCKS]; 3332 unsigned long nr_zapped_lock_chains; 3333 unsigned int nr_free_chain_hlocks; /* Free chain_hlocks in buckets */ 3334 unsigned int nr_lost_chain_hlocks; /* Lost chain_hlocks */ 3335 unsigned int nr_large_chain_blocks; /* size > MAX_CHAIN_BUCKETS */ 3336 3337 /* 3338 * The first 2 chain_hlocks entries in the chain block in the bucket 3339 * list contains the following meta data: 3340 * 3341 * entry[0]: 3342 * Bit 15 - always set to 1 (it is not a class index) 3343 * Bits 0-14 - upper 15 bits of the next block index 3344 * entry[1] - lower 16 bits of next block index 3345 * 3346 * A next block index of all 1 bits means it is the end of the list. 3347 * 3348 * On the unsized bucket (bucket-0), the 3rd and 4th entries contain 3349 * the chain block size: 3350 * 3351 * entry[2] - upper 16 bits of the chain block size 3352 * entry[3] - lower 16 bits of the chain block size 3353 */ 3354 #define MAX_CHAIN_BUCKETS 16 3355 #define CHAIN_BLK_FLAG (1U << 15) 3356 #define CHAIN_BLK_LIST_END 0xFFFFU 3357 3358 static int chain_block_buckets[MAX_CHAIN_BUCKETS]; 3359 3360 static inline int size_to_bucket(int size) 3361 { 3362 if (size > MAX_CHAIN_BUCKETS) 3363 return 0; 3364 3365 return size - 1; 3366 } 3367 3368 /* 3369 * Iterate all the chain blocks in a bucket. 3370 */ 3371 #define for_each_chain_block(bucket, prev, curr) \ 3372 for ((prev) = -1, (curr) = chain_block_buckets[bucket]; \ 3373 (curr) >= 0; \ 3374 (prev) = (curr), (curr) = chain_block_next(curr)) 3375 3376 /* 3377 * next block or -1 3378 */ 3379 static inline int chain_block_next(int offset) 3380 { 3381 int next = chain_hlocks[offset]; 3382 3383 WARN_ON_ONCE(!(next & CHAIN_BLK_FLAG)); 3384 3385 if (next == CHAIN_BLK_LIST_END) 3386 return -1; 3387 3388 next &= ~CHAIN_BLK_FLAG; 3389 next <<= 16; 3390 next |= chain_hlocks[offset + 1]; 3391 3392 return next; 3393 } 3394 3395 /* 3396 * bucket-0 only 3397 */ 3398 static inline int chain_block_size(int offset) 3399 { 3400 return (chain_hlocks[offset + 2] << 16) | chain_hlocks[offset + 3]; 3401 } 3402 3403 static inline void init_chain_block(int offset, int next, int bucket, int size) 3404 { 3405 chain_hlocks[offset] = (next >> 16) | CHAIN_BLK_FLAG; 3406 chain_hlocks[offset + 1] = (u16)next; 3407 3408 if (size && !bucket) { 3409 chain_hlocks[offset + 2] = size >> 16; 3410 chain_hlocks[offset + 3] = (u16)size; 3411 } 3412 } 3413 3414 static inline void add_chain_block(int offset, int size) 3415 { 3416 int bucket = size_to_bucket(size); 3417 int next = chain_block_buckets[bucket]; 3418 int prev, curr; 3419 3420 if (unlikely(size < 2)) { 3421 /* 3422 * We can't store single entries on the freelist. Leak them. 3423 * 3424 * One possible way out would be to uniquely mark them, other 3425 * than with CHAIN_BLK_FLAG, such that we can recover them when 3426 * the block before it is re-added. 3427 */ 3428 if (size) 3429 nr_lost_chain_hlocks++; 3430 return; 3431 } 3432 3433 nr_free_chain_hlocks += size; 3434 if (!bucket) { 3435 nr_large_chain_blocks++; 3436 3437 /* 3438 * Variable sized, sort large to small. 3439 */ 3440 for_each_chain_block(0, prev, curr) { 3441 if (size >= chain_block_size(curr)) 3442 break; 3443 } 3444 init_chain_block(offset, curr, 0, size); 3445 if (prev < 0) 3446 chain_block_buckets[0] = offset; 3447 else 3448 init_chain_block(prev, offset, 0, 0); 3449 return; 3450 } 3451 /* 3452 * Fixed size, add to head. 3453 */ 3454 init_chain_block(offset, next, bucket, size); 3455 chain_block_buckets[bucket] = offset; 3456 } 3457 3458 /* 3459 * Only the first block in the list can be deleted. 3460 * 3461 * For the variable size bucket[0], the first block (the largest one) is 3462 * returned, broken up and put back into the pool. So if a chain block of 3463 * length > MAX_CHAIN_BUCKETS is ever used and zapped, it will just be 3464 * queued up after the primordial chain block and never be used until the 3465 * hlock entries in the primordial chain block is almost used up. That 3466 * causes fragmentation and reduce allocation efficiency. That can be 3467 * monitored by looking at the "large chain blocks" number in lockdep_stats. 3468 */ 3469 static inline void del_chain_block(int bucket, int size, int next) 3470 { 3471 nr_free_chain_hlocks -= size; 3472 chain_block_buckets[bucket] = next; 3473 3474 if (!bucket) 3475 nr_large_chain_blocks--; 3476 } 3477 3478 static void init_chain_block_buckets(void) 3479 { 3480 int i; 3481 3482 for (i = 0; i < MAX_CHAIN_BUCKETS; i++) 3483 chain_block_buckets[i] = -1; 3484 3485 add_chain_block(0, ARRAY_SIZE(chain_hlocks)); 3486 } 3487 3488 /* 3489 * Return offset of a chain block of the right size or -1 if not found. 3490 * 3491 * Fairly simple worst-fit allocator with the addition of a number of size 3492 * specific free lists. 3493 */ 3494 static int alloc_chain_hlocks(int req) 3495 { 3496 int bucket, curr, size; 3497 3498 /* 3499 * We rely on the MSB to act as an escape bit to denote freelist 3500 * pointers. Make sure this bit isn't set in 'normal' class_idx usage. 3501 */ 3502 BUILD_BUG_ON((MAX_LOCKDEP_KEYS-1) & CHAIN_BLK_FLAG); 3503 3504 init_data_structures_once(); 3505 3506 if (nr_free_chain_hlocks < req) 3507 return -1; 3508 3509 /* 3510 * We require a minimum of 2 (u16) entries to encode a freelist 3511 * 'pointer'. 3512 */ 3513 req = max(req, 2); 3514 bucket = size_to_bucket(req); 3515 curr = chain_block_buckets[bucket]; 3516 3517 if (bucket) { 3518 if (curr >= 0) { 3519 del_chain_block(bucket, req, chain_block_next(curr)); 3520 return curr; 3521 } 3522 /* Try bucket 0 */ 3523 curr = chain_block_buckets[0]; 3524 } 3525 3526 /* 3527 * The variable sized freelist is sorted by size; the first entry is 3528 * the largest. Use it if it fits. 3529 */ 3530 if (curr >= 0) { 3531 size = chain_block_size(curr); 3532 if (likely(size >= req)) { 3533 del_chain_block(0, size, chain_block_next(curr)); 3534 if (size > req) 3535 add_chain_block(curr + req, size - req); 3536 return curr; 3537 } 3538 } 3539 3540 /* 3541 * Last resort, split a block in a larger sized bucket. 3542 */ 3543 for (size = MAX_CHAIN_BUCKETS; size > req; size--) { 3544 bucket = size_to_bucket(size); 3545 curr = chain_block_buckets[bucket]; 3546 if (curr < 0) 3547 continue; 3548 3549 del_chain_block(bucket, size, chain_block_next(curr)); 3550 add_chain_block(curr + req, size - req); 3551 return curr; 3552 } 3553 3554 return -1; 3555 } 3556 3557 static inline void free_chain_hlocks(int base, int size) 3558 { 3559 add_chain_block(base, max(size, 2)); 3560 } 3561 3562 struct lock_class *lock_chain_get_class(struct lock_chain *chain, int i) 3563 { 3564 u16 chain_hlock = chain_hlocks[chain->base + i]; 3565 unsigned int class_idx = chain_hlock_class_idx(chain_hlock); 3566 3567 return lock_classes + class_idx; 3568 } 3569 3570 /* 3571 * Returns the index of the first held_lock of the current chain 3572 */ 3573 static inline int get_first_held_lock(struct task_struct *curr, 3574 struct held_lock *hlock) 3575 { 3576 int i; 3577 struct held_lock *hlock_curr; 3578 3579 for (i = curr->lockdep_depth - 1; i >= 0; i--) { 3580 hlock_curr = curr->held_locks + i; 3581 if (hlock_curr->irq_context != hlock->irq_context) 3582 break; 3583 3584 } 3585 3586 return ++i; 3587 } 3588 3589 #ifdef CONFIG_DEBUG_LOCKDEP 3590 /* 3591 * Returns the next chain_key iteration 3592 */ 3593 static u64 print_chain_key_iteration(u16 hlock_id, u64 chain_key) 3594 { 3595 u64 new_chain_key = iterate_chain_key(chain_key, hlock_id); 3596 3597 printk(" hlock_id:%d -> chain_key:%016Lx", 3598 (unsigned int)hlock_id, 3599 (unsigned long long)new_chain_key); 3600 return new_chain_key; 3601 } 3602 3603 static void 3604 print_chain_keys_held_locks(struct task_struct *curr, struct held_lock *hlock_next) 3605 { 3606 struct held_lock *hlock; 3607 u64 chain_key = INITIAL_CHAIN_KEY; 3608 int depth = curr->lockdep_depth; 3609 int i = get_first_held_lock(curr, hlock_next); 3610 3611 printk("depth: %u (irq_context %u)\n", depth - i + 1, 3612 hlock_next->irq_context); 3613 for (; i < depth; i++) { 3614 hlock = curr->held_locks + i; 3615 chain_key = print_chain_key_iteration(hlock_id(hlock), chain_key); 3616 3617 print_lock(hlock); 3618 } 3619 3620 print_chain_key_iteration(hlock_id(hlock_next), chain_key); 3621 print_lock(hlock_next); 3622 } 3623 3624 static void print_chain_keys_chain(struct lock_chain *chain) 3625 { 3626 int i; 3627 u64 chain_key = INITIAL_CHAIN_KEY; 3628 u16 hlock_id; 3629 3630 printk("depth: %u\n", chain->depth); 3631 for (i = 0; i < chain->depth; i++) { 3632 hlock_id = chain_hlocks[chain->base + i]; 3633 chain_key = print_chain_key_iteration(hlock_id, chain_key); 3634 3635 print_lock_name(NULL, lock_classes + chain_hlock_class_idx(hlock_id)); 3636 printk("\n"); 3637 } 3638 } 3639 3640 static void print_collision(struct task_struct *curr, 3641 struct held_lock *hlock_next, 3642 struct lock_chain *chain) 3643 { 3644 nbcon_cpu_emergency_enter(); 3645 3646 pr_warn("\n"); 3647 pr_warn("============================\n"); 3648 pr_warn("WARNING: chain_key collision\n"); 3649 print_kernel_ident(); 3650 pr_warn("----------------------------\n"); 3651 pr_warn("%s/%d: ", current->comm, task_pid_nr(current)); 3652 pr_warn("Hash chain already cached but the contents don't match!\n"); 3653 3654 pr_warn("Held locks:"); 3655 print_chain_keys_held_locks(curr, hlock_next); 3656 3657 pr_warn("Locks in cached chain:"); 3658 print_chain_keys_chain(chain); 3659 3660 pr_warn("\nstack backtrace:\n"); 3661 dump_stack(); 3662 3663 nbcon_cpu_emergency_exit(); 3664 } 3665 #endif 3666 3667 /* 3668 * Checks whether the chain and the current held locks are consistent 3669 * in depth and also in content. If they are not it most likely means 3670 * that there was a collision during the calculation of the chain_key. 3671 * Returns: 0 not passed, 1 passed 3672 */ 3673 static int check_no_collision(struct task_struct *curr, 3674 struct held_lock *hlock, 3675 struct lock_chain *chain) 3676 { 3677 #ifdef CONFIG_DEBUG_LOCKDEP 3678 int i, j, id; 3679 3680 i = get_first_held_lock(curr, hlock); 3681 3682 if (DEBUG_LOCKS_WARN_ON(chain->depth != curr->lockdep_depth - (i - 1))) { 3683 print_collision(curr, hlock, chain); 3684 return 0; 3685 } 3686 3687 for (j = 0; j < chain->depth - 1; j++, i++) { 3688 id = hlock_id(&curr->held_locks[i]); 3689 3690 if (DEBUG_LOCKS_WARN_ON(chain_hlocks[chain->base + j] != id)) { 3691 print_collision(curr, hlock, chain); 3692 return 0; 3693 } 3694 } 3695 #endif 3696 return 1; 3697 } 3698 3699 /* 3700 * Given an index that is >= -1, return the index of the next lock chain. 3701 * Return -2 if there is no next lock chain. 3702 */ 3703 long lockdep_next_lockchain(long i) 3704 { 3705 i = find_next_bit(lock_chains_in_use, ARRAY_SIZE(lock_chains), i + 1); 3706 return i < ARRAY_SIZE(lock_chains) ? i : -2; 3707 } 3708 3709 unsigned long lock_chain_count(void) 3710 { 3711 return bitmap_weight(lock_chains_in_use, ARRAY_SIZE(lock_chains)); 3712 } 3713 3714 /* Must be called with the graph lock held. */ 3715 static struct lock_chain *alloc_lock_chain(void) 3716 { 3717 int idx = find_first_zero_bit(lock_chains_in_use, 3718 ARRAY_SIZE(lock_chains)); 3719 3720 if (unlikely(idx >= ARRAY_SIZE(lock_chains))) 3721 return NULL; 3722 __set_bit(idx, lock_chains_in_use); 3723 return lock_chains + idx; 3724 } 3725 3726 /* 3727 * Adds a dependency chain into chain hashtable. And must be called with 3728 * graph_lock held. 3729 * 3730 * Return 0 if fail, and graph_lock is released. 3731 * Return 1 if succeed, with graph_lock held. 3732 */ 3733 static inline int add_chain_cache(struct task_struct *curr, 3734 struct held_lock *hlock, 3735 u64 chain_key) 3736 { 3737 struct hlist_head *hash_head = chainhashentry(chain_key); 3738 struct lock_chain *chain; 3739 int i, j; 3740 3741 /* 3742 * The caller must hold the graph lock, ensure we've got IRQs 3743 * disabled to make this an IRQ-safe lock.. for recursion reasons 3744 * lockdep won't complain about its own locking errors. 3745 */ 3746 if (lockdep_assert_locked()) 3747 return 0; 3748 3749 chain = alloc_lock_chain(); 3750 if (!chain) { 3751 if (!debug_locks_off_graph_unlock()) 3752 return 0; 3753 3754 nbcon_cpu_emergency_enter(); 3755 print_lockdep_off("BUG: MAX_LOCKDEP_CHAINS too low!"); 3756 dump_stack(); 3757 nbcon_cpu_emergency_exit(); 3758 return 0; 3759 } 3760 chain->chain_key = chain_key; 3761 chain->irq_context = hlock->irq_context; 3762 i = get_first_held_lock(curr, hlock); 3763 chain->depth = curr->lockdep_depth + 1 - i; 3764 3765 BUILD_BUG_ON((1UL << 24) <= ARRAY_SIZE(chain_hlocks)); 3766 BUILD_BUG_ON((1UL << 6) <= ARRAY_SIZE(curr->held_locks)); 3767 BUILD_BUG_ON((1UL << 8*sizeof(chain_hlocks[0])) <= ARRAY_SIZE(lock_classes)); 3768 3769 j = alloc_chain_hlocks(chain->depth); 3770 if (j < 0) { 3771 if (!debug_locks_off_graph_unlock()) 3772 return 0; 3773 3774 nbcon_cpu_emergency_enter(); 3775 print_lockdep_off("BUG: MAX_LOCKDEP_CHAIN_HLOCKS too low!"); 3776 dump_stack(); 3777 nbcon_cpu_emergency_exit(); 3778 return 0; 3779 } 3780 3781 chain->base = j; 3782 for (j = 0; j < chain->depth - 1; j++, i++) { 3783 int lock_id = hlock_id(curr->held_locks + i); 3784 3785 chain_hlocks[chain->base + j] = lock_id; 3786 } 3787 chain_hlocks[chain->base + j] = hlock_id(hlock); 3788 hlist_add_head_rcu(&chain->entry, hash_head); 3789 debug_atomic_inc(chain_lookup_misses); 3790 inc_chains(chain->irq_context); 3791 3792 return 1; 3793 } 3794 3795 /* 3796 * Look up a dependency chain. Must be called with either the graph lock or 3797 * the RCU read lock held. 3798 */ 3799 static inline struct lock_chain *lookup_chain_cache(u64 chain_key) 3800 { 3801 struct hlist_head *hash_head = chainhashentry(chain_key); 3802 struct lock_chain *chain; 3803 3804 hlist_for_each_entry_rcu(chain, hash_head, entry) { 3805 if (READ_ONCE(chain->chain_key) == chain_key) { 3806 debug_atomic_inc(chain_lookup_hits); 3807 return chain; 3808 } 3809 } 3810 return NULL; 3811 } 3812 3813 /* 3814 * If the key is not present yet in dependency chain cache then 3815 * add it and return 1 - in this case the new dependency chain is 3816 * validated. If the key is already hashed, return 0. 3817 * (On return with 1 graph_lock is held.) 3818 */ 3819 static inline int lookup_chain_cache_add(struct task_struct *curr, 3820 struct held_lock *hlock, 3821 u64 chain_key) 3822 { 3823 struct lock_class *class = hlock_class(hlock); 3824 struct lock_chain *chain = lookup_chain_cache(chain_key); 3825 3826 if (chain) { 3827 cache_hit: 3828 if (!check_no_collision(curr, hlock, chain)) 3829 return 0; 3830 3831 if (very_verbose(class)) { 3832 printk("\nhash chain already cached, key: " 3833 "%016Lx tail class: [%px] %s\n", 3834 (unsigned long long)chain_key, 3835 class->key, class->name); 3836 } 3837 3838 return 0; 3839 } 3840 3841 if (very_verbose(class)) { 3842 printk("\nnew hash chain, key: %016Lx tail class: [%px] %s\n", 3843 (unsigned long long)chain_key, class->key, class->name); 3844 } 3845 3846 if (!graph_lock()) 3847 return 0; 3848 3849 /* 3850 * We have to walk the chain again locked - to avoid duplicates: 3851 */ 3852 chain = lookup_chain_cache(chain_key); 3853 if (chain) { 3854 graph_unlock(); 3855 goto cache_hit; 3856 } 3857 3858 if (!add_chain_cache(curr, hlock, chain_key)) 3859 return 0; 3860 3861 return 1; 3862 } 3863 3864 static int validate_chain(struct task_struct *curr, 3865 struct held_lock *hlock, 3866 int chain_head, u64 chain_key) 3867 { 3868 /* 3869 * Trylock needs to maintain the stack of held locks, but it 3870 * does not add new dependencies, because trylock can be done 3871 * in any order. 3872 * 3873 * We look up the chain_key and do the O(N^2) check and update of 3874 * the dependencies only if this is a new dependency chain. 3875 * (If lookup_chain_cache_add() return with 1 it acquires 3876 * graph_lock for us) 3877 */ 3878 if (!hlock->trylock && hlock->check && 3879 lookup_chain_cache_add(curr, hlock, chain_key)) { 3880 /* 3881 * Check whether last held lock: 3882 * 3883 * - is irq-safe, if this lock is irq-unsafe 3884 * - is softirq-safe, if this lock is hardirq-unsafe 3885 * 3886 * And check whether the new lock's dependency graph 3887 * could lead back to the previous lock: 3888 * 3889 * - within the current held-lock stack 3890 * - across our accumulated lock dependency records 3891 * 3892 * any of these scenarios could lead to a deadlock. 3893 */ 3894 /* 3895 * The simple case: does the current hold the same lock 3896 * already? 3897 */ 3898 int ret = check_deadlock(curr, hlock); 3899 3900 if (!ret) 3901 return 0; 3902 /* 3903 * Add dependency only if this lock is not the head 3904 * of the chain, and if the new lock introduces no more 3905 * lock dependency (because we already hold a lock with the 3906 * same lock class) nor deadlock (because the nest_lock 3907 * serializes nesting locks), see the comments for 3908 * check_deadlock(). 3909 */ 3910 if (!chain_head && ret != 2) { 3911 if (!check_prevs_add(curr, hlock)) 3912 return 0; 3913 } 3914 3915 graph_unlock(); 3916 } else { 3917 /* after lookup_chain_cache_add(): */ 3918 if (unlikely(!debug_locks)) 3919 return 0; 3920 } 3921 3922 return 1; 3923 } 3924 #else 3925 static inline int validate_chain(struct task_struct *curr, 3926 struct held_lock *hlock, 3927 int chain_head, u64 chain_key) 3928 { 3929 return 1; 3930 } 3931 3932 static void init_chain_block_buckets(void) { } 3933 #endif /* CONFIG_PROVE_LOCKING */ 3934 3935 /* 3936 * We are building curr_chain_key incrementally, so double-check 3937 * it from scratch, to make sure that it's done correctly: 3938 */ 3939 static void check_chain_key(struct task_struct *curr) 3940 { 3941 #ifdef CONFIG_DEBUG_LOCKDEP 3942 struct held_lock *hlock, *prev_hlock = NULL; 3943 unsigned int i; 3944 u64 chain_key = INITIAL_CHAIN_KEY; 3945 3946 for (i = 0; i < curr->lockdep_depth; i++) { 3947 hlock = curr->held_locks + i; 3948 if (chain_key != hlock->prev_chain_key) { 3949 debug_locks_off(); 3950 /* 3951 * We got mighty confused, our chain keys don't match 3952 * with what we expect, someone trample on our task state? 3953 */ 3954 WARN(1, "hm#1, depth: %u [%u], %016Lx != %016Lx\n", 3955 curr->lockdep_depth, i, 3956 (unsigned long long)chain_key, 3957 (unsigned long long)hlock->prev_chain_key); 3958 return; 3959 } 3960 3961 /* 3962 * hlock->class_idx can't go beyond MAX_LOCKDEP_KEYS, but is 3963 * it registered lock class index? 3964 */ 3965 if (DEBUG_LOCKS_WARN_ON(!test_bit(hlock->class_idx, lock_classes_in_use))) 3966 return; 3967 3968 if (prev_hlock && (prev_hlock->irq_context != 3969 hlock->irq_context)) 3970 chain_key = INITIAL_CHAIN_KEY; 3971 chain_key = iterate_chain_key(chain_key, hlock_id(hlock)); 3972 prev_hlock = hlock; 3973 } 3974 if (chain_key != curr->curr_chain_key) { 3975 debug_locks_off(); 3976 /* 3977 * More smoking hash instead of calculating it, damn see these 3978 * numbers float.. I bet that a pink elephant stepped on my memory. 3979 */ 3980 WARN(1, "hm#2, depth: %u [%u], %016Lx != %016Lx\n", 3981 curr->lockdep_depth, i, 3982 (unsigned long long)chain_key, 3983 (unsigned long long)curr->curr_chain_key); 3984 } 3985 #endif 3986 } 3987 3988 #ifdef CONFIG_PROVE_LOCKING 3989 static int mark_lock(struct task_struct *curr, struct held_lock *this, 3990 enum lock_usage_bit new_bit); 3991 3992 static void print_usage_bug_scenario(struct held_lock *lock) 3993 { 3994 struct lock_class *class = hlock_class(lock); 3995 3996 printk(" Possible unsafe locking scenario:\n\n"); 3997 printk(" CPU0\n"); 3998 printk(" ----\n"); 3999 printk(" lock("); 4000 __print_lock_name(lock, class); 4001 printk(KERN_CONT ");\n"); 4002 printk(" <Interrupt>\n"); 4003 printk(" lock("); 4004 __print_lock_name(lock, class); 4005 printk(KERN_CONT ");\n"); 4006 printk("\n *** DEADLOCK ***\n\n"); 4007 } 4008 4009 static void 4010 print_usage_bug(struct task_struct *curr, struct held_lock *this, 4011 enum lock_usage_bit prev_bit, enum lock_usage_bit new_bit) 4012 { 4013 if (!debug_locks_off() || debug_locks_silent) 4014 return; 4015 4016 nbcon_cpu_emergency_enter(); 4017 4018 pr_warn("\n"); 4019 pr_warn("================================\n"); 4020 pr_warn("WARNING: inconsistent lock state\n"); 4021 print_kernel_ident(); 4022 pr_warn("--------------------------------\n"); 4023 4024 pr_warn("inconsistent {%s} -> {%s} usage.\n", 4025 usage_str[prev_bit], usage_str[new_bit]); 4026 4027 pr_warn("%s/%d [HC%u[%lu]:SC%u[%lu]:HE%u:SE%u] takes:\n", 4028 curr->comm, task_pid_nr(curr), 4029 lockdep_hardirq_context(), hardirq_count() >> HARDIRQ_SHIFT, 4030 lockdep_softirq_context(curr), softirq_count() >> SOFTIRQ_SHIFT, 4031 lockdep_hardirqs_enabled(), 4032 lockdep_softirqs_enabled(curr)); 4033 print_lock(this); 4034 4035 pr_warn("{%s} state was registered at:\n", usage_str[prev_bit]); 4036 print_lock_trace(hlock_class(this)->usage_traces[prev_bit], 1); 4037 4038 print_irqtrace_events(curr); 4039 pr_warn("\nother info that might help us debug this:\n"); 4040 print_usage_bug_scenario(this); 4041 4042 lockdep_print_held_locks(curr); 4043 4044 pr_warn("\nstack backtrace:\n"); 4045 dump_stack(); 4046 4047 nbcon_cpu_emergency_exit(); 4048 } 4049 4050 /* 4051 * Print out an error if an invalid bit is set: 4052 */ 4053 static inline int 4054 valid_state(struct task_struct *curr, struct held_lock *this, 4055 enum lock_usage_bit new_bit, enum lock_usage_bit bad_bit) 4056 { 4057 if (unlikely(hlock_class(this)->usage_mask & (1 << bad_bit))) { 4058 graph_unlock(); 4059 print_usage_bug(curr, this, bad_bit, new_bit); 4060 return 0; 4061 } 4062 return 1; 4063 } 4064 4065 4066 /* 4067 * print irq inversion bug: 4068 */ 4069 static void 4070 print_irq_inversion_bug(struct task_struct *curr, 4071 struct lock_list *root, struct lock_list *other, 4072 struct held_lock *this, int forwards, 4073 const char *irqclass) 4074 { 4075 struct lock_list *entry = other; 4076 struct lock_list *middle = NULL; 4077 int depth; 4078 4079 if (!debug_locks_off_graph_unlock() || debug_locks_silent) 4080 return; 4081 4082 nbcon_cpu_emergency_enter(); 4083 4084 pr_warn("\n"); 4085 pr_warn("========================================================\n"); 4086 pr_warn("WARNING: possible irq lock inversion dependency detected\n"); 4087 print_kernel_ident(); 4088 pr_warn("--------------------------------------------------------\n"); 4089 pr_warn("%s/%d just changed the state of lock:\n", 4090 curr->comm, task_pid_nr(curr)); 4091 print_lock(this); 4092 if (forwards) 4093 pr_warn("but this lock took another, %s-unsafe lock in the past:\n", irqclass); 4094 else 4095 pr_warn("but this lock was taken by another, %s-safe lock in the past:\n", irqclass); 4096 print_lock_name(NULL, other->class); 4097 pr_warn("\n\nand interrupts could create inverse lock ordering between them.\n\n"); 4098 4099 pr_warn("\nother info that might help us debug this:\n"); 4100 4101 /* Find a middle lock (if one exists) */ 4102 depth = get_lock_depth(other); 4103 do { 4104 if (depth == 0 && (entry != root)) { 4105 pr_warn("lockdep:%s bad path found in chain graph\n", __func__); 4106 break; 4107 } 4108 middle = entry; 4109 entry = get_lock_parent(entry); 4110 depth--; 4111 } while (entry && entry != root && (depth >= 0)); 4112 if (forwards) 4113 print_irq_lock_scenario(root, other, 4114 middle ? middle->class : root->class, other->class); 4115 else 4116 print_irq_lock_scenario(other, root, 4117 middle ? middle->class : other->class, root->class); 4118 4119 lockdep_print_held_locks(curr); 4120 4121 pr_warn("\nthe shortest dependencies between 2nd lock and 1st lock:\n"); 4122 root->trace = save_trace(); 4123 if (!root->trace) 4124 goto out; 4125 print_shortest_lock_dependencies(other, root); 4126 4127 pr_warn("\nstack backtrace:\n"); 4128 dump_stack(); 4129 out: 4130 nbcon_cpu_emergency_exit(); 4131 } 4132 4133 /* 4134 * Prove that in the forwards-direction subgraph starting at <this> 4135 * there is no lock matching <mask>: 4136 */ 4137 static int 4138 check_usage_forwards(struct task_struct *curr, struct held_lock *this, 4139 enum lock_usage_bit bit) 4140 { 4141 enum bfs_result ret; 4142 struct lock_list root; 4143 struct lock_list *target_entry; 4144 enum lock_usage_bit read_bit = bit + LOCK_USAGE_READ_MASK; 4145 unsigned usage_mask = lock_flag(bit) | lock_flag(read_bit); 4146 4147 bfs_init_root(&root, this); 4148 ret = find_usage_forwards(&root, usage_mask, &target_entry); 4149 if (bfs_error(ret)) { 4150 print_bfs_bug(ret); 4151 return 0; 4152 } 4153 if (ret == BFS_RNOMATCH) 4154 return 1; 4155 4156 /* Check whether write or read usage is the match */ 4157 if (target_entry->class->usage_mask & lock_flag(bit)) { 4158 print_irq_inversion_bug(curr, &root, target_entry, 4159 this, 1, state_name(bit)); 4160 } else { 4161 print_irq_inversion_bug(curr, &root, target_entry, 4162 this, 1, state_name(read_bit)); 4163 } 4164 4165 return 0; 4166 } 4167 4168 /* 4169 * Prove that in the backwards-direction subgraph starting at <this> 4170 * there is no lock matching <mask>: 4171 */ 4172 static int 4173 check_usage_backwards(struct task_struct *curr, struct held_lock *this, 4174 enum lock_usage_bit bit) 4175 { 4176 enum bfs_result ret; 4177 struct lock_list root; 4178 struct lock_list *target_entry; 4179 enum lock_usage_bit read_bit = bit + LOCK_USAGE_READ_MASK; 4180 unsigned usage_mask = lock_flag(bit) | lock_flag(read_bit); 4181 4182 bfs_init_rootb(&root, this); 4183 ret = find_usage_backwards(&root, usage_mask, &target_entry); 4184 if (bfs_error(ret)) { 4185 print_bfs_bug(ret); 4186 return 0; 4187 } 4188 if (ret == BFS_RNOMATCH) 4189 return 1; 4190 4191 /* Check whether write or read usage is the match */ 4192 if (target_entry->class->usage_mask & lock_flag(bit)) { 4193 print_irq_inversion_bug(curr, &root, target_entry, 4194 this, 0, state_name(bit)); 4195 } else { 4196 print_irq_inversion_bug(curr, &root, target_entry, 4197 this, 0, state_name(read_bit)); 4198 } 4199 4200 return 0; 4201 } 4202 4203 void print_irqtrace_events(struct task_struct *curr) 4204 { 4205 const struct irqtrace_events *trace = &curr->irqtrace; 4206 4207 nbcon_cpu_emergency_enter(); 4208 4209 printk("irq event stamp: %u\n", trace->irq_events); 4210 printk("hardirqs last enabled at (%u): [<%px>] %pS\n", 4211 trace->hardirq_enable_event, (void *)trace->hardirq_enable_ip, 4212 (void *)trace->hardirq_enable_ip); 4213 printk("hardirqs last disabled at (%u): [<%px>] %pS\n", 4214 trace->hardirq_disable_event, (void *)trace->hardirq_disable_ip, 4215 (void *)trace->hardirq_disable_ip); 4216 printk("softirqs last enabled at (%u): [<%px>] %pS\n", 4217 trace->softirq_enable_event, (void *)trace->softirq_enable_ip, 4218 (void *)trace->softirq_enable_ip); 4219 printk("softirqs last disabled at (%u): [<%px>] %pS\n", 4220 trace->softirq_disable_event, (void *)trace->softirq_disable_ip, 4221 (void *)trace->softirq_disable_ip); 4222 4223 nbcon_cpu_emergency_exit(); 4224 } 4225 4226 static int HARDIRQ_verbose(struct lock_class *class) 4227 { 4228 #if HARDIRQ_VERBOSE 4229 return class_filter(class); 4230 #endif 4231 return 0; 4232 } 4233 4234 static int SOFTIRQ_verbose(struct lock_class *class) 4235 { 4236 #if SOFTIRQ_VERBOSE 4237 return class_filter(class); 4238 #endif 4239 return 0; 4240 } 4241 4242 static int (*state_verbose_f[])(struct lock_class *class) = { 4243 #define LOCKDEP_STATE(__STATE) \ 4244 __STATE##_verbose, 4245 #include "lockdep_states.h" 4246 #undef LOCKDEP_STATE 4247 }; 4248 4249 static inline int state_verbose(enum lock_usage_bit bit, 4250 struct lock_class *class) 4251 { 4252 return state_verbose_f[bit >> LOCK_USAGE_DIR_MASK](class); 4253 } 4254 4255 typedef int (*check_usage_f)(struct task_struct *, struct held_lock *, 4256 enum lock_usage_bit bit, const char *name); 4257 4258 static int 4259 mark_lock_irq(struct task_struct *curr, struct held_lock *this, 4260 enum lock_usage_bit new_bit) 4261 { 4262 int excl_bit = exclusive_bit(new_bit); 4263 int read = new_bit & LOCK_USAGE_READ_MASK; 4264 int dir = new_bit & LOCK_USAGE_DIR_MASK; 4265 4266 /* 4267 * Validate that this particular lock does not have conflicting 4268 * usage states. 4269 */ 4270 if (!valid_state(curr, this, new_bit, excl_bit)) 4271 return 0; 4272 4273 /* 4274 * Check for read in write conflicts 4275 */ 4276 if (!read && !valid_state(curr, this, new_bit, 4277 excl_bit + LOCK_USAGE_READ_MASK)) 4278 return 0; 4279 4280 4281 /* 4282 * Validate that the lock dependencies don't have conflicting usage 4283 * states. 4284 */ 4285 if (dir) { 4286 /* 4287 * mark ENABLED has to look backwards -- to ensure no dependee 4288 * has USED_IN state, which, again, would allow recursion deadlocks. 4289 */ 4290 if (!check_usage_backwards(curr, this, excl_bit)) 4291 return 0; 4292 } else { 4293 /* 4294 * mark USED_IN has to look forwards -- to ensure no dependency 4295 * has ENABLED state, which would allow recursion deadlocks. 4296 */ 4297 if (!check_usage_forwards(curr, this, excl_bit)) 4298 return 0; 4299 } 4300 4301 if (state_verbose(new_bit, hlock_class(this))) 4302 return 2; 4303 4304 return 1; 4305 } 4306 4307 /* 4308 * Mark all held locks with a usage bit: 4309 */ 4310 static int 4311 mark_held_locks(struct task_struct *curr, enum lock_usage_bit base_bit) 4312 { 4313 struct held_lock *hlock; 4314 int i; 4315 4316 for (i = 0; i < curr->lockdep_depth; i++) { 4317 enum lock_usage_bit hlock_bit = base_bit; 4318 hlock = curr->held_locks + i; 4319 4320 if (hlock->read) 4321 hlock_bit += LOCK_USAGE_READ_MASK; 4322 4323 BUG_ON(hlock_bit >= LOCK_USAGE_STATES); 4324 4325 if (!hlock->check) 4326 continue; 4327 4328 if (!mark_lock(curr, hlock, hlock_bit)) 4329 return 0; 4330 } 4331 4332 return 1; 4333 } 4334 4335 /* 4336 * Hardirqs will be enabled: 4337 */ 4338 static void __trace_hardirqs_on_caller(void) 4339 { 4340 struct task_struct *curr = current; 4341 4342 /* 4343 * We are going to turn hardirqs on, so set the 4344 * usage bit for all held locks: 4345 */ 4346 if (!mark_held_locks(curr, LOCK_ENABLED_HARDIRQ)) 4347 return; 4348 /* 4349 * If we have softirqs enabled, then set the usage 4350 * bit for all held locks. (disabled hardirqs prevented 4351 * this bit from being set before) 4352 */ 4353 if (curr->softirqs_enabled) 4354 mark_held_locks(curr, LOCK_ENABLED_SOFTIRQ); 4355 } 4356 4357 /** 4358 * lockdep_hardirqs_on_prepare - Prepare for enabling interrupts 4359 * 4360 * Invoked before a possible transition to RCU idle from exit to user or 4361 * guest mode. This ensures that all RCU operations are done before RCU 4362 * stops watching. After the RCU transition lockdep_hardirqs_on() has to be 4363 * invoked to set the final state. 4364 */ 4365 void lockdep_hardirqs_on_prepare(void) 4366 { 4367 if (unlikely(!debug_locks)) 4368 return; 4369 4370 /* 4371 * NMIs do not (and cannot) track lock dependencies, nothing to do. 4372 */ 4373 if (unlikely(in_nmi())) 4374 return; 4375 4376 if (unlikely(this_cpu_read(lockdep_recursion))) 4377 return; 4378 4379 if (unlikely(lockdep_hardirqs_enabled())) { 4380 /* 4381 * Neither irq nor preemption are disabled here 4382 * so this is racy by nature but losing one hit 4383 * in a stat is not a big deal. 4384 */ 4385 __debug_atomic_inc(redundant_hardirqs_on); 4386 return; 4387 } 4388 4389 /* 4390 * We're enabling irqs and according to our state above irqs weren't 4391 * already enabled, yet we find the hardware thinks they are in fact 4392 * enabled.. someone messed up their IRQ state tracing. 4393 */ 4394 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled())) 4395 return; 4396 4397 /* 4398 * See the fine text that goes along with this variable definition. 4399 */ 4400 if (DEBUG_LOCKS_WARN_ON(early_boot_irqs_disabled)) 4401 return; 4402 4403 /* 4404 * Can't allow enabling interrupts while in an interrupt handler, 4405 * that's general bad form and such. Recursion, limited stack etc.. 4406 */ 4407 if (DEBUG_LOCKS_WARN_ON(lockdep_hardirq_context())) 4408 return; 4409 4410 current->hardirq_chain_key = current->curr_chain_key; 4411 4412 lockdep_recursion_inc(); 4413 __trace_hardirqs_on_caller(); 4414 lockdep_recursion_finish(); 4415 } 4416 EXPORT_SYMBOL_GPL(lockdep_hardirqs_on_prepare); 4417 4418 void noinstr lockdep_hardirqs_on(unsigned long ip) 4419 { 4420 struct irqtrace_events *trace = ¤t->irqtrace; 4421 4422 if (unlikely(!debug_locks)) 4423 return; 4424 4425 /* 4426 * NMIs can happen in the middle of local_irq_{en,dis}able() where the 4427 * tracking state and hardware state are out of sync. 4428 * 4429 * NMIs must save lockdep_hardirqs_enabled() to restore IRQ state from, 4430 * and not rely on hardware state like normal interrupts. 4431 */ 4432 if (unlikely(in_nmi())) { 4433 if (!IS_ENABLED(CONFIG_TRACE_IRQFLAGS_NMI)) 4434 return; 4435 4436 /* 4437 * Skip: 4438 * - recursion check, because NMI can hit lockdep; 4439 * - hardware state check, because above; 4440 * - chain_key check, see lockdep_hardirqs_on_prepare(). 4441 */ 4442 goto skip_checks; 4443 } 4444 4445 if (unlikely(this_cpu_read(lockdep_recursion))) 4446 return; 4447 4448 if (lockdep_hardirqs_enabled()) { 4449 /* 4450 * Neither irq nor preemption are disabled here 4451 * so this is racy by nature but losing one hit 4452 * in a stat is not a big deal. 4453 */ 4454 __debug_atomic_inc(redundant_hardirqs_on); 4455 return; 4456 } 4457 4458 /* 4459 * We're enabling irqs and according to our state above irqs weren't 4460 * already enabled, yet we find the hardware thinks they are in fact 4461 * enabled.. someone messed up their IRQ state tracing. 4462 */ 4463 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled())) 4464 return; 4465 4466 /* 4467 * Ensure the lock stack remained unchanged between 4468 * lockdep_hardirqs_on_prepare() and lockdep_hardirqs_on(). 4469 */ 4470 DEBUG_LOCKS_WARN_ON(current->hardirq_chain_key != 4471 current->curr_chain_key); 4472 4473 skip_checks: 4474 /* we'll do an OFF -> ON transition: */ 4475 __this_cpu_write(hardirqs_enabled, 1); 4476 trace->hardirq_enable_ip = ip; 4477 trace->hardirq_enable_event = ++trace->irq_events; 4478 debug_atomic_inc(hardirqs_on_events); 4479 } 4480 EXPORT_SYMBOL_GPL(lockdep_hardirqs_on); 4481 4482 /* 4483 * Hardirqs were disabled: 4484 */ 4485 void noinstr lockdep_hardirqs_off(unsigned long ip) 4486 { 4487 if (unlikely(!debug_locks)) 4488 return; 4489 4490 /* 4491 * Matching lockdep_hardirqs_on(), allow NMIs in the middle of lockdep; 4492 * they will restore the software state. This ensures the software 4493 * state is consistent inside NMIs as well. 4494 */ 4495 if (in_nmi()) { 4496 if (!IS_ENABLED(CONFIG_TRACE_IRQFLAGS_NMI)) 4497 return; 4498 } else if (__this_cpu_read(lockdep_recursion)) 4499 return; 4500 4501 /* 4502 * So we're supposed to get called after you mask local IRQs, but for 4503 * some reason the hardware doesn't quite think you did a proper job. 4504 */ 4505 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled())) 4506 return; 4507 4508 if (lockdep_hardirqs_enabled()) { 4509 struct irqtrace_events *trace = ¤t->irqtrace; 4510 4511 /* 4512 * We have done an ON -> OFF transition: 4513 */ 4514 __this_cpu_write(hardirqs_enabled, 0); 4515 trace->hardirq_disable_ip = ip; 4516 trace->hardirq_disable_event = ++trace->irq_events; 4517 debug_atomic_inc(hardirqs_off_events); 4518 } else { 4519 debug_atomic_inc(redundant_hardirqs_off); 4520 } 4521 } 4522 EXPORT_SYMBOL_GPL(lockdep_hardirqs_off); 4523 4524 /* 4525 * Softirqs will be enabled: 4526 */ 4527 void lockdep_softirqs_on(unsigned long ip) 4528 { 4529 struct irqtrace_events *trace = ¤t->irqtrace; 4530 4531 if (unlikely(!lockdep_enabled())) 4532 return; 4533 4534 /* 4535 * We fancy IRQs being disabled here, see softirq.c, avoids 4536 * funny state and nesting things. 4537 */ 4538 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled())) 4539 return; 4540 4541 if (current->softirqs_enabled) { 4542 debug_atomic_inc(redundant_softirqs_on); 4543 return; 4544 } 4545 4546 lockdep_recursion_inc(); 4547 /* 4548 * We'll do an OFF -> ON transition: 4549 */ 4550 current->softirqs_enabled = 1; 4551 trace->softirq_enable_ip = ip; 4552 trace->softirq_enable_event = ++trace->irq_events; 4553 debug_atomic_inc(softirqs_on_events); 4554 /* 4555 * We are going to turn softirqs on, so set the 4556 * usage bit for all held locks, if hardirqs are 4557 * enabled too: 4558 */ 4559 if (lockdep_hardirqs_enabled()) 4560 mark_held_locks(current, LOCK_ENABLED_SOFTIRQ); 4561 lockdep_recursion_finish(); 4562 } 4563 4564 /* 4565 * Softirqs were disabled: 4566 */ 4567 void lockdep_softirqs_off(unsigned long ip) 4568 { 4569 if (unlikely(!lockdep_enabled())) 4570 return; 4571 4572 /* 4573 * We fancy IRQs being disabled here, see softirq.c 4574 */ 4575 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled())) 4576 return; 4577 4578 if (current->softirqs_enabled) { 4579 struct irqtrace_events *trace = ¤t->irqtrace; 4580 4581 /* 4582 * We have done an ON -> OFF transition: 4583 */ 4584 current->softirqs_enabled = 0; 4585 trace->softirq_disable_ip = ip; 4586 trace->softirq_disable_event = ++trace->irq_events; 4587 debug_atomic_inc(softirqs_off_events); 4588 /* 4589 * Whoops, we wanted softirqs off, so why aren't they? 4590 */ 4591 DEBUG_LOCKS_WARN_ON(!softirq_count()); 4592 } else 4593 debug_atomic_inc(redundant_softirqs_off); 4594 } 4595 4596 /** 4597 * lockdep_cleanup_dead_cpu - Ensure CPU lockdep state is cleanly stopped 4598 * 4599 * @cpu: index of offlined CPU 4600 * @idle: task pointer for offlined CPU's idle thread 4601 * 4602 * Invoked after the CPU is dead. Ensures that the tracing infrastructure 4603 * is left in a suitable state for the CPU to be subsequently brought 4604 * online again. 4605 */ 4606 void lockdep_cleanup_dead_cpu(unsigned int cpu, struct task_struct *idle) 4607 { 4608 if (unlikely(!debug_locks)) 4609 return; 4610 4611 if (unlikely(per_cpu(hardirqs_enabled, cpu))) { 4612 pr_warn("CPU %u left hardirqs enabled!", cpu); 4613 if (idle) 4614 print_irqtrace_events(idle); 4615 /* Clean it up for when the CPU comes online again. */ 4616 per_cpu(hardirqs_enabled, cpu) = 0; 4617 } 4618 } 4619 4620 static int 4621 mark_usage(struct task_struct *curr, struct held_lock *hlock, int check) 4622 { 4623 if (!check) 4624 goto lock_used; 4625 4626 /* 4627 * If non-trylock use in a hardirq or softirq context, then 4628 * mark the lock as used in these contexts: 4629 */ 4630 if (!hlock->trylock) { 4631 if (hlock->read) { 4632 if (lockdep_hardirq_context()) 4633 if (!mark_lock(curr, hlock, 4634 LOCK_USED_IN_HARDIRQ_READ)) 4635 return 0; 4636 if (curr->softirq_context) 4637 if (!mark_lock(curr, hlock, 4638 LOCK_USED_IN_SOFTIRQ_READ)) 4639 return 0; 4640 } else { 4641 if (lockdep_hardirq_context()) 4642 if (!mark_lock(curr, hlock, LOCK_USED_IN_HARDIRQ)) 4643 return 0; 4644 if (curr->softirq_context) 4645 if (!mark_lock(curr, hlock, LOCK_USED_IN_SOFTIRQ)) 4646 return 0; 4647 } 4648 } 4649 4650 /* 4651 * For lock_sync(), don't mark the ENABLED usage, since lock_sync() 4652 * creates no critical section and no extra dependency can be introduced 4653 * by interrupts 4654 */ 4655 if (!hlock->hardirqs_off && !hlock->sync) { 4656 if (hlock->read) { 4657 if (!mark_lock(curr, hlock, 4658 LOCK_ENABLED_HARDIRQ_READ)) 4659 return 0; 4660 if (curr->softirqs_enabled) 4661 if (!mark_lock(curr, hlock, 4662 LOCK_ENABLED_SOFTIRQ_READ)) 4663 return 0; 4664 } else { 4665 if (!mark_lock(curr, hlock, 4666 LOCK_ENABLED_HARDIRQ)) 4667 return 0; 4668 if (curr->softirqs_enabled) 4669 if (!mark_lock(curr, hlock, 4670 LOCK_ENABLED_SOFTIRQ)) 4671 return 0; 4672 } 4673 } 4674 4675 lock_used: 4676 /* mark it as used: */ 4677 if (!mark_lock(curr, hlock, LOCK_USED)) 4678 return 0; 4679 4680 return 1; 4681 } 4682 4683 static inline unsigned int task_irq_context(struct task_struct *task) 4684 { 4685 return LOCK_CHAIN_HARDIRQ_CONTEXT * !!lockdep_hardirq_context() + 4686 LOCK_CHAIN_SOFTIRQ_CONTEXT * !!task->softirq_context; 4687 } 4688 4689 static int separate_irq_context(struct task_struct *curr, 4690 struct held_lock *hlock) 4691 { 4692 unsigned int depth = curr->lockdep_depth; 4693 4694 /* 4695 * Keep track of points where we cross into an interrupt context: 4696 */ 4697 if (depth) { 4698 struct held_lock *prev_hlock; 4699 4700 prev_hlock = curr->held_locks + depth-1; 4701 /* 4702 * If we cross into another context, reset the 4703 * hash key (this also prevents the checking and the 4704 * adding of the dependency to 'prev'): 4705 */ 4706 if (prev_hlock->irq_context != hlock->irq_context) 4707 return 1; 4708 } 4709 return 0; 4710 } 4711 4712 /* 4713 * Mark a lock with a usage bit, and validate the state transition: 4714 */ 4715 static int mark_lock(struct task_struct *curr, struct held_lock *this, 4716 enum lock_usage_bit new_bit) 4717 { 4718 unsigned int new_mask, ret = 1; 4719 4720 if (new_bit >= LOCK_USAGE_STATES) { 4721 DEBUG_LOCKS_WARN_ON(1); 4722 return 0; 4723 } 4724 4725 if (new_bit == LOCK_USED && this->read) 4726 new_bit = LOCK_USED_READ; 4727 4728 new_mask = 1 << new_bit; 4729 4730 /* 4731 * If already set then do not dirty the cacheline, 4732 * nor do any checks: 4733 */ 4734 if (likely(hlock_class(this)->usage_mask & new_mask)) 4735 return 1; 4736 4737 if (!graph_lock()) 4738 return 0; 4739 /* 4740 * Make sure we didn't race: 4741 */ 4742 if (unlikely(hlock_class(this)->usage_mask & new_mask)) 4743 goto unlock; 4744 4745 if (!hlock_class(this)->usage_mask) 4746 debug_atomic_dec(nr_unused_locks); 4747 4748 hlock_class(this)->usage_mask |= new_mask; 4749 4750 if (new_bit < LOCK_TRACE_STATES) { 4751 if (!(hlock_class(this)->usage_traces[new_bit] = save_trace())) 4752 return 0; 4753 } 4754 4755 if (new_bit < LOCK_USED) { 4756 ret = mark_lock_irq(curr, this, new_bit); 4757 if (!ret) 4758 return 0; 4759 } 4760 4761 unlock: 4762 graph_unlock(); 4763 4764 /* 4765 * We must printk outside of the graph_lock: 4766 */ 4767 if (ret == 2) { 4768 nbcon_cpu_emergency_enter(); 4769 printk("\nmarked lock as {%s}:\n", usage_str[new_bit]); 4770 print_lock(this); 4771 print_irqtrace_events(curr); 4772 dump_stack(); 4773 nbcon_cpu_emergency_exit(); 4774 } 4775 4776 return ret; 4777 } 4778 4779 static inline short task_wait_context(struct task_struct *curr) 4780 { 4781 /* 4782 * Set appropriate wait type for the context; for IRQs we have to take 4783 * into account force_irqthread as that is implied by PREEMPT_RT. 4784 */ 4785 if (lockdep_hardirq_context()) { 4786 /* 4787 * Check if force_irqthreads will run us threaded. 4788 */ 4789 if (curr->hardirq_threaded || curr->irq_config) 4790 return LD_WAIT_CONFIG; 4791 4792 return LD_WAIT_SPIN; 4793 } else if (curr->softirq_context) { 4794 /* 4795 * Softirqs are always threaded. 4796 */ 4797 return LD_WAIT_CONFIG; 4798 } 4799 4800 return LD_WAIT_MAX; 4801 } 4802 4803 static int 4804 print_lock_invalid_wait_context(struct task_struct *curr, 4805 struct held_lock *hlock) 4806 { 4807 short curr_inner; 4808 4809 if (!debug_locks_off()) 4810 return 0; 4811 if (debug_locks_silent) 4812 return 0; 4813 4814 nbcon_cpu_emergency_enter(); 4815 4816 pr_warn("\n"); 4817 pr_warn("=============================\n"); 4818 pr_warn("[ BUG: Invalid wait context ]\n"); 4819 print_kernel_ident(); 4820 pr_warn("-----------------------------\n"); 4821 4822 pr_warn("%s/%d is trying to lock:\n", curr->comm, task_pid_nr(curr)); 4823 print_lock(hlock); 4824 4825 pr_warn("other info that might help us debug this:\n"); 4826 4827 curr_inner = task_wait_context(curr); 4828 pr_warn("context-{%d:%d}\n", curr_inner, curr_inner); 4829 4830 lockdep_print_held_locks(curr); 4831 4832 pr_warn("stack backtrace:\n"); 4833 dump_stack(); 4834 4835 nbcon_cpu_emergency_exit(); 4836 4837 return 0; 4838 } 4839 4840 /* 4841 * Verify the wait_type context. 4842 * 4843 * This check validates we take locks in the right wait-type order; that is it 4844 * ensures that we do not take mutexes inside spinlocks and do not attempt to 4845 * acquire spinlocks inside raw_spinlocks and the sort. 4846 * 4847 * The entire thing is slightly more complex because of RCU, RCU is a lock that 4848 * can be taken from (pretty much) any context but also has constraints. 4849 * However when taken in a stricter environment the RCU lock does not loosen 4850 * the constraints. 4851 * 4852 * Therefore we must look for the strictest environment in the lock stack and 4853 * compare that to the lock we're trying to acquire. 4854 */ 4855 static int check_wait_context(struct task_struct *curr, struct held_lock *next) 4856 { 4857 u8 next_inner = hlock_class(next)->wait_type_inner; 4858 u8 next_outer = hlock_class(next)->wait_type_outer; 4859 u8 curr_inner; 4860 int depth; 4861 4862 if (!next_inner || next->trylock) 4863 return 0; 4864 4865 if (!next_outer) 4866 next_outer = next_inner; 4867 4868 /* 4869 * Find start of current irq_context.. 4870 */ 4871 for (depth = curr->lockdep_depth - 1; depth >= 0; depth--) { 4872 struct held_lock *prev = curr->held_locks + depth; 4873 if (prev->irq_context != next->irq_context) 4874 break; 4875 } 4876 depth++; 4877 4878 curr_inner = task_wait_context(curr); 4879 4880 for (; depth < curr->lockdep_depth; depth++) { 4881 struct held_lock *prev = curr->held_locks + depth; 4882 struct lock_class *class = hlock_class(prev); 4883 u8 prev_inner = class->wait_type_inner; 4884 4885 if (prev_inner) { 4886 /* 4887 * We can have a bigger inner than a previous one 4888 * when outer is smaller than inner, as with RCU. 4889 * 4890 * Also due to trylocks. 4891 */ 4892 curr_inner = min(curr_inner, prev_inner); 4893 4894 /* 4895 * Allow override for annotations -- this is typically 4896 * only valid/needed for code that only exists when 4897 * CONFIG_PREEMPT_RT=n. 4898 */ 4899 if (unlikely(class->lock_type == LD_LOCK_WAIT_OVERRIDE)) 4900 curr_inner = prev_inner; 4901 } 4902 } 4903 4904 if (next_outer > curr_inner) 4905 return print_lock_invalid_wait_context(curr, next); 4906 4907 return 0; 4908 } 4909 4910 #else /* CONFIG_PROVE_LOCKING */ 4911 4912 static inline int 4913 mark_usage(struct task_struct *curr, struct held_lock *hlock, int check) 4914 { 4915 return 1; 4916 } 4917 4918 static inline unsigned int task_irq_context(struct task_struct *task) 4919 { 4920 return 0; 4921 } 4922 4923 static inline int separate_irq_context(struct task_struct *curr, 4924 struct held_lock *hlock) 4925 { 4926 return 0; 4927 } 4928 4929 static inline int check_wait_context(struct task_struct *curr, 4930 struct held_lock *next) 4931 { 4932 return 0; 4933 } 4934 4935 #endif /* CONFIG_PROVE_LOCKING */ 4936 4937 /* 4938 * Initialize a lock instance's lock-class mapping info: 4939 */ 4940 void lockdep_init_map_type(struct lockdep_map *lock, const char *name, 4941 struct lock_class_key *key, int subclass, 4942 u8 inner, u8 outer, u8 lock_type) 4943 { 4944 int i; 4945 4946 for (i = 0; i < NR_LOCKDEP_CACHING_CLASSES; i++) 4947 lock->class_cache[i] = NULL; 4948 4949 #ifdef CONFIG_LOCK_STAT 4950 lock->cpu = raw_smp_processor_id(); 4951 #endif 4952 4953 /* 4954 * Can't be having no nameless bastards around this place! 4955 */ 4956 if (DEBUG_LOCKS_WARN_ON(!name)) { 4957 lock->name = "NULL"; 4958 return; 4959 } 4960 4961 lock->name = name; 4962 4963 lock->wait_type_outer = outer; 4964 lock->wait_type_inner = inner; 4965 lock->lock_type = lock_type; 4966 4967 /* 4968 * No key, no joy, we need to hash something. 4969 */ 4970 if (DEBUG_LOCKS_WARN_ON(!key)) 4971 return; 4972 /* 4973 * Sanity check, the lock-class key must either have been allocated 4974 * statically or must have been registered as a dynamic key. 4975 */ 4976 if (!static_obj(key) && !is_dynamic_key(key)) { 4977 if (debug_locks) 4978 printk(KERN_ERR "BUG: key %px has not been registered!\n", key); 4979 DEBUG_LOCKS_WARN_ON(1); 4980 return; 4981 } 4982 lock->key = key; 4983 4984 if (unlikely(!debug_locks)) 4985 return; 4986 4987 if (subclass) { 4988 unsigned long flags; 4989 4990 if (DEBUG_LOCKS_WARN_ON(!lockdep_enabled())) 4991 return; 4992 4993 raw_local_irq_save(flags); 4994 lockdep_recursion_inc(); 4995 register_lock_class(lock, subclass, 1); 4996 lockdep_recursion_finish(); 4997 raw_local_irq_restore(flags); 4998 } 4999 } 5000 EXPORT_SYMBOL_GPL(lockdep_init_map_type); 5001 5002 struct lock_class_key __lockdep_no_validate__; 5003 EXPORT_SYMBOL_GPL(__lockdep_no_validate__); 5004 5005 struct lock_class_key __lockdep_no_track__; 5006 EXPORT_SYMBOL_GPL(__lockdep_no_track__); 5007 5008 #ifdef CONFIG_PROVE_LOCKING 5009 void lockdep_set_lock_cmp_fn(struct lockdep_map *lock, lock_cmp_fn cmp_fn, 5010 lock_print_fn print_fn) 5011 { 5012 struct lock_class *class = lock->class_cache[0]; 5013 unsigned long flags; 5014 5015 raw_local_irq_save(flags); 5016 lockdep_recursion_inc(); 5017 5018 if (!class) 5019 class = register_lock_class(lock, 0, 0); 5020 5021 if (class) { 5022 WARN_ON(class->cmp_fn && class->cmp_fn != cmp_fn); 5023 WARN_ON(class->print_fn && class->print_fn != print_fn); 5024 5025 class->cmp_fn = cmp_fn; 5026 class->print_fn = print_fn; 5027 } 5028 5029 lockdep_recursion_finish(); 5030 raw_local_irq_restore(flags); 5031 } 5032 EXPORT_SYMBOL_GPL(lockdep_set_lock_cmp_fn); 5033 #endif 5034 5035 static void 5036 print_lock_nested_lock_not_held(struct task_struct *curr, 5037 struct held_lock *hlock) 5038 { 5039 if (!debug_locks_off()) 5040 return; 5041 if (debug_locks_silent) 5042 return; 5043 5044 nbcon_cpu_emergency_enter(); 5045 5046 pr_warn("\n"); 5047 pr_warn("==================================\n"); 5048 pr_warn("WARNING: Nested lock was not taken\n"); 5049 print_kernel_ident(); 5050 pr_warn("----------------------------------\n"); 5051 5052 pr_warn("%s/%d is trying to lock:\n", curr->comm, task_pid_nr(curr)); 5053 print_lock(hlock); 5054 5055 pr_warn("\nbut this task is not holding:\n"); 5056 pr_warn("%s\n", hlock->nest_lock->name); 5057 5058 pr_warn("\nstack backtrace:\n"); 5059 dump_stack(); 5060 5061 pr_warn("\nother info that might help us debug this:\n"); 5062 lockdep_print_held_locks(curr); 5063 5064 pr_warn("\nstack backtrace:\n"); 5065 dump_stack(); 5066 5067 nbcon_cpu_emergency_exit(); 5068 } 5069 5070 static int __lock_is_held(const struct lockdep_map *lock, int read); 5071 5072 /* 5073 * This gets called for every mutex_lock*()/spin_lock*() operation. 5074 * We maintain the dependency maps and validate the locking attempt: 5075 * 5076 * The callers must make sure that IRQs are disabled before calling it, 5077 * otherwise we could get an interrupt which would want to take locks, 5078 * which would end up in lockdep again. 5079 */ 5080 static int __lock_acquire(struct lockdep_map *lock, unsigned int subclass, 5081 int trylock, int read, int check, int hardirqs_off, 5082 struct lockdep_map *nest_lock, unsigned long ip, 5083 int references, int pin_count, int sync) 5084 { 5085 struct task_struct *curr = current; 5086 struct lock_class *class = NULL; 5087 struct held_lock *hlock; 5088 unsigned int depth; 5089 int chain_head = 0; 5090 int class_idx; 5091 u64 chain_key; 5092 5093 if (unlikely(!debug_locks)) 5094 return 0; 5095 5096 if (unlikely(lock->key == &__lockdep_no_track__)) 5097 return 0; 5098 5099 lockevent_inc(lockdep_acquire); 5100 5101 if (!prove_locking || lock->key == &__lockdep_no_validate__) { 5102 check = 0; 5103 lockevent_inc(lockdep_nocheck); 5104 } 5105 5106 if (DEBUG_LOCKS_WARN_ON(subclass >= MAX_LOCKDEP_SUBCLASSES)) 5107 return 0; 5108 5109 if (subclass < NR_LOCKDEP_CACHING_CLASSES) 5110 class = lock->class_cache[subclass]; 5111 /* 5112 * Not cached? 5113 */ 5114 if (unlikely(!class)) { 5115 class = register_lock_class(lock, subclass, 0); 5116 if (!class) 5117 return 0; 5118 } 5119 5120 debug_class_ops_inc(class); 5121 5122 if (very_verbose(class)) { 5123 nbcon_cpu_emergency_enter(); 5124 printk("\nacquire class [%px] %s", class->key, class->name); 5125 if (class->name_version > 1) 5126 printk(KERN_CONT "#%d", class->name_version); 5127 printk(KERN_CONT "\n"); 5128 dump_stack(); 5129 nbcon_cpu_emergency_exit(); 5130 } 5131 5132 /* 5133 * Add the lock to the list of currently held locks. 5134 * (we dont increase the depth just yet, up until the 5135 * dependency checks are done) 5136 */ 5137 depth = curr->lockdep_depth; 5138 /* 5139 * Ran out of static storage for our per-task lock stack again have we? 5140 */ 5141 if (DEBUG_LOCKS_WARN_ON(depth >= MAX_LOCK_DEPTH)) 5142 return 0; 5143 5144 class_idx = class - lock_classes; 5145 5146 if (depth && !sync) { 5147 /* we're holding locks and the new held lock is not a sync */ 5148 hlock = curr->held_locks + depth - 1; 5149 if (hlock->class_idx == class_idx && nest_lock) { 5150 if (!references) 5151 references++; 5152 5153 if (!hlock->references) 5154 hlock->references++; 5155 5156 hlock->references += references; 5157 5158 /* Overflow */ 5159 if (DEBUG_LOCKS_WARN_ON(hlock->references < references)) 5160 return 0; 5161 5162 return 2; 5163 } 5164 } 5165 5166 hlock = curr->held_locks + depth; 5167 /* 5168 * Plain impossible, we just registered it and checked it weren't no 5169 * NULL like.. I bet this mushroom I ate was good! 5170 */ 5171 if (DEBUG_LOCKS_WARN_ON(!class)) 5172 return 0; 5173 hlock->class_idx = class_idx; 5174 hlock->acquire_ip = ip; 5175 hlock->instance = lock; 5176 hlock->nest_lock = nest_lock; 5177 hlock->irq_context = task_irq_context(curr); 5178 hlock->trylock = trylock; 5179 hlock->read = read; 5180 hlock->check = check; 5181 hlock->sync = !!sync; 5182 hlock->hardirqs_off = !!hardirqs_off; 5183 hlock->references = references; 5184 #ifdef CONFIG_LOCK_STAT 5185 hlock->waittime_stamp = 0; 5186 hlock->holdtime_stamp = lockstat_clock(); 5187 #endif 5188 hlock->pin_count = pin_count; 5189 5190 if (check_wait_context(curr, hlock)) 5191 return 0; 5192 5193 /* Initialize the lock usage bit */ 5194 if (!mark_usage(curr, hlock, check)) 5195 return 0; 5196 5197 /* 5198 * Calculate the chain hash: it's the combined hash of all the 5199 * lock keys along the dependency chain. We save the hash value 5200 * at every step so that we can get the current hash easily 5201 * after unlock. The chain hash is then used to cache dependency 5202 * results. 5203 * 5204 * The 'key ID' is what is the most compact key value to drive 5205 * the hash, not class->key. 5206 */ 5207 /* 5208 * Whoops, we did it again.. class_idx is invalid. 5209 */ 5210 if (DEBUG_LOCKS_WARN_ON(!test_bit(class_idx, lock_classes_in_use))) 5211 return 0; 5212 5213 chain_key = curr->curr_chain_key; 5214 if (!depth) { 5215 /* 5216 * How can we have a chain hash when we ain't got no keys?! 5217 */ 5218 if (DEBUG_LOCKS_WARN_ON(chain_key != INITIAL_CHAIN_KEY)) 5219 return 0; 5220 chain_head = 1; 5221 } 5222 5223 hlock->prev_chain_key = chain_key; 5224 if (separate_irq_context(curr, hlock)) { 5225 chain_key = INITIAL_CHAIN_KEY; 5226 chain_head = 1; 5227 } 5228 chain_key = iterate_chain_key(chain_key, hlock_id(hlock)); 5229 5230 if (nest_lock && !__lock_is_held(nest_lock, -1)) { 5231 print_lock_nested_lock_not_held(curr, hlock); 5232 return 0; 5233 } 5234 5235 if (!debug_locks_silent) { 5236 WARN_ON_ONCE(depth && !hlock_class(hlock - 1)->key); 5237 WARN_ON_ONCE(!hlock_class(hlock)->key); 5238 } 5239 5240 if (!validate_chain(curr, hlock, chain_head, chain_key)) 5241 return 0; 5242 5243 /* For lock_sync(), we are done here since no actual critical section */ 5244 if (hlock->sync) 5245 return 1; 5246 5247 curr->curr_chain_key = chain_key; 5248 curr->lockdep_depth++; 5249 check_chain_key(curr); 5250 #ifdef CONFIG_DEBUG_LOCKDEP 5251 if (unlikely(!debug_locks)) 5252 return 0; 5253 #endif 5254 if (unlikely(curr->lockdep_depth >= MAX_LOCK_DEPTH)) { 5255 debug_locks_off(); 5256 nbcon_cpu_emergency_enter(); 5257 print_lockdep_off("BUG: MAX_LOCK_DEPTH too low!"); 5258 printk(KERN_DEBUG "depth: %i max: %lu!\n", 5259 curr->lockdep_depth, MAX_LOCK_DEPTH); 5260 5261 lockdep_print_held_locks(current); 5262 debug_show_all_locks(); 5263 dump_stack(); 5264 nbcon_cpu_emergency_exit(); 5265 5266 return 0; 5267 } 5268 5269 if (unlikely(curr->lockdep_depth > max_lockdep_depth)) 5270 max_lockdep_depth = curr->lockdep_depth; 5271 5272 return 1; 5273 } 5274 5275 static void print_unlock_imbalance_bug(struct task_struct *curr, 5276 struct lockdep_map *lock, 5277 unsigned long ip) 5278 { 5279 if (!debug_locks_off()) 5280 return; 5281 if (debug_locks_silent) 5282 return; 5283 5284 nbcon_cpu_emergency_enter(); 5285 5286 pr_warn("\n"); 5287 pr_warn("=====================================\n"); 5288 pr_warn("WARNING: bad unlock balance detected!\n"); 5289 print_kernel_ident(); 5290 pr_warn("-------------------------------------\n"); 5291 pr_warn("%s/%d is trying to release lock (", 5292 curr->comm, task_pid_nr(curr)); 5293 print_lockdep_cache(lock); 5294 pr_cont(") at:\n"); 5295 print_ip_sym(KERN_WARNING, ip); 5296 pr_warn("but there are no more locks to release!\n"); 5297 pr_warn("\nother info that might help us debug this:\n"); 5298 lockdep_print_held_locks(curr); 5299 5300 pr_warn("\nstack backtrace:\n"); 5301 dump_stack(); 5302 5303 nbcon_cpu_emergency_exit(); 5304 } 5305 5306 static noinstr int match_held_lock(const struct held_lock *hlock, 5307 const struct lockdep_map *lock) 5308 { 5309 if (hlock->instance == lock) 5310 return 1; 5311 5312 if (hlock->references) { 5313 const struct lock_class *class = lock->class_cache[0]; 5314 5315 if (!class) 5316 class = look_up_lock_class(lock, 0); 5317 5318 /* 5319 * If look_up_lock_class() failed to find a class, we're trying 5320 * to test if we hold a lock that has never yet been acquired. 5321 * Clearly if the lock hasn't been acquired _ever_, we're not 5322 * holding it either, so report failure. 5323 */ 5324 if (!class) 5325 return 0; 5326 5327 /* 5328 * References, but not a lock we're actually ref-counting? 5329 * State got messed up, follow the sites that change ->references 5330 * and try to make sense of it. 5331 */ 5332 if (DEBUG_LOCKS_WARN_ON(!hlock->nest_lock)) 5333 return 0; 5334 5335 if (hlock->class_idx == class - lock_classes) 5336 return 1; 5337 } 5338 5339 return 0; 5340 } 5341 5342 /* @depth must not be zero */ 5343 static struct held_lock *find_held_lock(struct task_struct *curr, 5344 struct lockdep_map *lock, 5345 unsigned int depth, int *idx) 5346 { 5347 struct held_lock *ret, *hlock, *prev_hlock; 5348 int i; 5349 5350 i = depth - 1; 5351 hlock = curr->held_locks + i; 5352 ret = hlock; 5353 if (match_held_lock(hlock, lock)) 5354 goto out; 5355 5356 ret = NULL; 5357 for (i--, prev_hlock = hlock--; 5358 i >= 0; 5359 i--, prev_hlock = hlock--) { 5360 /* 5361 * We must not cross into another context: 5362 */ 5363 if (prev_hlock->irq_context != hlock->irq_context) { 5364 ret = NULL; 5365 break; 5366 } 5367 if (match_held_lock(hlock, lock)) { 5368 ret = hlock; 5369 break; 5370 } 5371 } 5372 5373 out: 5374 *idx = i; 5375 return ret; 5376 } 5377 5378 static int reacquire_held_locks(struct task_struct *curr, unsigned int depth, 5379 int idx, unsigned int *merged) 5380 { 5381 struct held_lock *hlock; 5382 int first_idx = idx; 5383 5384 if (DEBUG_LOCKS_WARN_ON(!irqs_disabled())) 5385 return 0; 5386 5387 for (hlock = curr->held_locks + idx; idx < depth; idx++, hlock++) { 5388 switch (__lock_acquire(hlock->instance, 5389 hlock_class(hlock)->subclass, 5390 hlock->trylock, 5391 hlock->read, hlock->check, 5392 hlock->hardirqs_off, 5393 hlock->nest_lock, hlock->acquire_ip, 5394 hlock->references, hlock->pin_count, 0)) { 5395 case 0: 5396 return 1; 5397 case 1: 5398 break; 5399 case 2: 5400 *merged += (idx == first_idx); 5401 break; 5402 default: 5403 WARN_ON(1); 5404 return 0; 5405 } 5406 } 5407 return 0; 5408 } 5409 5410 static int 5411 __lock_set_class(struct lockdep_map *lock, const char *name, 5412 struct lock_class_key *key, unsigned int subclass, 5413 unsigned long ip) 5414 { 5415 struct task_struct *curr = current; 5416 unsigned int depth, merged = 0; 5417 struct held_lock *hlock; 5418 struct lock_class *class; 5419 int i; 5420 5421 if (unlikely(!debug_locks)) 5422 return 0; 5423 5424 depth = curr->lockdep_depth; 5425 /* 5426 * This function is about (re)setting the class of a held lock, 5427 * yet we're not actually holding any locks. Naughty user! 5428 */ 5429 if (DEBUG_LOCKS_WARN_ON(!depth)) 5430 return 0; 5431 5432 hlock = find_held_lock(curr, lock, depth, &i); 5433 if (!hlock) { 5434 print_unlock_imbalance_bug(curr, lock, ip); 5435 return 0; 5436 } 5437 5438 lockdep_init_map_type(lock, name, key, 0, 5439 lock->wait_type_inner, 5440 lock->wait_type_outer, 5441 lock->lock_type); 5442 class = register_lock_class(lock, subclass, 0); 5443 hlock->class_idx = class - lock_classes; 5444 5445 curr->lockdep_depth = i; 5446 curr->curr_chain_key = hlock->prev_chain_key; 5447 5448 if (reacquire_held_locks(curr, depth, i, &merged)) 5449 return 0; 5450 5451 /* 5452 * I took it apart and put it back together again, except now I have 5453 * these 'spare' parts.. where shall I put them. 5454 */ 5455 if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - merged)) 5456 return 0; 5457 return 1; 5458 } 5459 5460 static int __lock_downgrade(struct lockdep_map *lock, unsigned long ip) 5461 { 5462 struct task_struct *curr = current; 5463 unsigned int depth, merged = 0; 5464 struct held_lock *hlock; 5465 int i; 5466 5467 if (unlikely(!debug_locks)) 5468 return 0; 5469 5470 depth = curr->lockdep_depth; 5471 /* 5472 * This function is about (re)setting the class of a held lock, 5473 * yet we're not actually holding any locks. Naughty user! 5474 */ 5475 if (DEBUG_LOCKS_WARN_ON(!depth)) 5476 return 0; 5477 5478 hlock = find_held_lock(curr, lock, depth, &i); 5479 if (!hlock) { 5480 print_unlock_imbalance_bug(curr, lock, ip); 5481 return 0; 5482 } 5483 5484 curr->lockdep_depth = i; 5485 curr->curr_chain_key = hlock->prev_chain_key; 5486 5487 WARN(hlock->read, "downgrading a read lock"); 5488 hlock->read = 1; 5489 hlock->acquire_ip = ip; 5490 5491 if (reacquire_held_locks(curr, depth, i, &merged)) 5492 return 0; 5493 5494 /* Merging can't happen with unchanged classes.. */ 5495 if (DEBUG_LOCKS_WARN_ON(merged)) 5496 return 0; 5497 5498 /* 5499 * I took it apart and put it back together again, except now I have 5500 * these 'spare' parts.. where shall I put them. 5501 */ 5502 if (DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth)) 5503 return 0; 5504 5505 return 1; 5506 } 5507 5508 /* 5509 * Remove the lock from the list of currently held locks - this gets 5510 * called on mutex_unlock()/spin_unlock*() (or on a failed 5511 * mutex_lock_interruptible()). 5512 */ 5513 static int 5514 __lock_release(struct lockdep_map *lock, unsigned long ip) 5515 { 5516 struct task_struct *curr = current; 5517 unsigned int depth, merged = 1; 5518 struct held_lock *hlock; 5519 int i; 5520 5521 if (unlikely(!debug_locks)) 5522 return 0; 5523 5524 depth = curr->lockdep_depth; 5525 /* 5526 * So we're all set to release this lock.. wait what lock? We don't 5527 * own any locks, you've been drinking again? 5528 */ 5529 if (depth <= 0) { 5530 print_unlock_imbalance_bug(curr, lock, ip); 5531 return 0; 5532 } 5533 5534 /* 5535 * Check whether the lock exists in the current stack 5536 * of held locks: 5537 */ 5538 hlock = find_held_lock(curr, lock, depth, &i); 5539 if (!hlock) { 5540 print_unlock_imbalance_bug(curr, lock, ip); 5541 return 0; 5542 } 5543 5544 if (hlock->instance == lock) 5545 lock_release_holdtime(hlock); 5546 5547 WARN(hlock->pin_count, "releasing a pinned lock\n"); 5548 5549 if (hlock->references) { 5550 hlock->references--; 5551 if (hlock->references) { 5552 /* 5553 * We had, and after removing one, still have 5554 * references, the current lock stack is still 5555 * valid. We're done! 5556 */ 5557 return 1; 5558 } 5559 } 5560 5561 /* 5562 * We have the right lock to unlock, 'hlock' points to it. 5563 * Now we remove it from the stack, and add back the other 5564 * entries (if any), recalculating the hash along the way: 5565 */ 5566 5567 curr->lockdep_depth = i; 5568 curr->curr_chain_key = hlock->prev_chain_key; 5569 5570 /* 5571 * The most likely case is when the unlock is on the innermost 5572 * lock. In this case, we are done! 5573 */ 5574 if (i == depth-1) 5575 return 1; 5576 5577 if (reacquire_held_locks(curr, depth, i + 1, &merged)) 5578 return 0; 5579 5580 /* 5581 * We had N bottles of beer on the wall, we drank one, but now 5582 * there's not N-1 bottles of beer left on the wall... 5583 * Pouring two of the bottles together is acceptable. 5584 */ 5585 DEBUG_LOCKS_WARN_ON(curr->lockdep_depth != depth - merged); 5586 5587 /* 5588 * Since reacquire_held_locks() would have called check_chain_key() 5589 * indirectly via __lock_acquire(), we don't need to do it again 5590 * on return. 5591 */ 5592 return 0; 5593 } 5594 5595 static __always_inline 5596 int __lock_is_held(const struct lockdep_map *lock, int read) 5597 { 5598 struct task_struct *curr = current; 5599 int i; 5600 5601 for (i = 0; i < curr->lockdep_depth; i++) { 5602 struct held_lock *hlock = curr->held_locks + i; 5603 5604 if (match_held_lock(hlock, lock)) { 5605 if (read == -1 || !!hlock->read == read) 5606 return LOCK_STATE_HELD; 5607 5608 return LOCK_STATE_NOT_HELD; 5609 } 5610 } 5611 5612 return LOCK_STATE_NOT_HELD; 5613 } 5614 5615 static struct pin_cookie __lock_pin_lock(struct lockdep_map *lock) 5616 { 5617 struct pin_cookie cookie = NIL_COOKIE; 5618 struct task_struct *curr = current; 5619 int i; 5620 5621 if (unlikely(!debug_locks)) 5622 return cookie; 5623 5624 for (i = 0; i < curr->lockdep_depth; i++) { 5625 struct held_lock *hlock = curr->held_locks + i; 5626 5627 if (match_held_lock(hlock, lock)) { 5628 /* 5629 * Grab 16bits of randomness; this is sufficient to not 5630 * be guessable and still allows some pin nesting in 5631 * our u32 pin_count. 5632 */ 5633 cookie.val = 1 + (sched_clock() & 0xffff); 5634 hlock->pin_count += cookie.val; 5635 return cookie; 5636 } 5637 } 5638 5639 WARN(1, "pinning an unheld lock\n"); 5640 return cookie; 5641 } 5642 5643 static void __lock_repin_lock(struct lockdep_map *lock, struct pin_cookie cookie) 5644 { 5645 struct task_struct *curr = current; 5646 int i; 5647 5648 if (unlikely(!debug_locks)) 5649 return; 5650 5651 for (i = 0; i < curr->lockdep_depth; i++) { 5652 struct held_lock *hlock = curr->held_locks + i; 5653 5654 if (match_held_lock(hlock, lock)) { 5655 hlock->pin_count += cookie.val; 5656 return; 5657 } 5658 } 5659 5660 WARN(1, "pinning an unheld lock\n"); 5661 } 5662 5663 static void __lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie cookie) 5664 { 5665 struct task_struct *curr = current; 5666 int i; 5667 5668 if (unlikely(!debug_locks)) 5669 return; 5670 5671 for (i = 0; i < curr->lockdep_depth; i++) { 5672 struct held_lock *hlock = curr->held_locks + i; 5673 5674 if (match_held_lock(hlock, lock)) { 5675 if (WARN(!hlock->pin_count, "unpinning an unpinned lock\n")) 5676 return; 5677 5678 hlock->pin_count -= cookie.val; 5679 5680 if (WARN((int)hlock->pin_count < 0, "pin count corrupted\n")) 5681 hlock->pin_count = 0; 5682 5683 return; 5684 } 5685 } 5686 5687 WARN(1, "unpinning an unheld lock\n"); 5688 } 5689 5690 /* 5691 * Check whether we follow the irq-flags state precisely: 5692 */ 5693 static noinstr void check_flags(unsigned long flags) 5694 { 5695 #if defined(CONFIG_PROVE_LOCKING) && defined(CONFIG_DEBUG_LOCKDEP) 5696 if (!debug_locks) 5697 return; 5698 5699 /* Get the warning out.. */ 5700 instrumentation_begin(); 5701 5702 if (irqs_disabled_flags(flags)) { 5703 if (DEBUG_LOCKS_WARN_ON(lockdep_hardirqs_enabled())) { 5704 printk("possible reason: unannotated irqs-off.\n"); 5705 } 5706 } else { 5707 if (DEBUG_LOCKS_WARN_ON(!lockdep_hardirqs_enabled())) { 5708 printk("possible reason: unannotated irqs-on.\n"); 5709 } 5710 } 5711 5712 #ifndef CONFIG_PREEMPT_RT 5713 /* 5714 * We dont accurately track softirq state in e.g. 5715 * hardirq contexts (such as on 4KSTACKS), so only 5716 * check if not in hardirq contexts: 5717 */ 5718 if (!hardirq_count()) { 5719 if (softirq_count()) { 5720 /* like the above, but with softirqs */ 5721 DEBUG_LOCKS_WARN_ON(current->softirqs_enabled); 5722 } else { 5723 /* lick the above, does it taste good? */ 5724 DEBUG_LOCKS_WARN_ON(!current->softirqs_enabled); 5725 } 5726 } 5727 #endif 5728 5729 if (!debug_locks) 5730 print_irqtrace_events(current); 5731 5732 instrumentation_end(); 5733 #endif 5734 } 5735 5736 void lock_set_class(struct lockdep_map *lock, const char *name, 5737 struct lock_class_key *key, unsigned int subclass, 5738 unsigned long ip) 5739 { 5740 unsigned long flags; 5741 5742 if (unlikely(!lockdep_enabled())) 5743 return; 5744 5745 raw_local_irq_save(flags); 5746 lockdep_recursion_inc(); 5747 check_flags(flags); 5748 if (__lock_set_class(lock, name, key, subclass, ip)) 5749 check_chain_key(current); 5750 lockdep_recursion_finish(); 5751 raw_local_irq_restore(flags); 5752 } 5753 EXPORT_SYMBOL_GPL(lock_set_class); 5754 5755 void lock_downgrade(struct lockdep_map *lock, unsigned long ip) 5756 { 5757 unsigned long flags; 5758 5759 if (unlikely(!lockdep_enabled())) 5760 return; 5761 5762 raw_local_irq_save(flags); 5763 lockdep_recursion_inc(); 5764 check_flags(flags); 5765 if (__lock_downgrade(lock, ip)) 5766 check_chain_key(current); 5767 lockdep_recursion_finish(); 5768 raw_local_irq_restore(flags); 5769 } 5770 EXPORT_SYMBOL_GPL(lock_downgrade); 5771 5772 /* NMI context !!! */ 5773 static void verify_lock_unused(struct lockdep_map *lock, struct held_lock *hlock, int subclass) 5774 { 5775 #ifdef CONFIG_PROVE_LOCKING 5776 struct lock_class *class = look_up_lock_class(lock, subclass); 5777 unsigned long mask = LOCKF_USED; 5778 5779 /* if it doesn't have a class (yet), it certainly hasn't been used yet */ 5780 if (!class) 5781 return; 5782 5783 /* 5784 * READ locks only conflict with USED, such that if we only ever use 5785 * READ locks, there is no deadlock possible -- RCU. 5786 */ 5787 if (!hlock->read) 5788 mask |= LOCKF_USED_READ; 5789 5790 if (!(class->usage_mask & mask)) 5791 return; 5792 5793 hlock->class_idx = class - lock_classes; 5794 5795 print_usage_bug(current, hlock, LOCK_USED, LOCK_USAGE_STATES); 5796 #endif 5797 } 5798 5799 static bool lockdep_nmi(void) 5800 { 5801 if (raw_cpu_read(lockdep_recursion)) 5802 return false; 5803 5804 if (!in_nmi()) 5805 return false; 5806 5807 return true; 5808 } 5809 5810 /* 5811 * read_lock() is recursive if: 5812 * 1. We force lockdep think this way in selftests or 5813 * 2. The implementation is not queued read/write lock or 5814 * 3. The locker is at an in_interrupt() context. 5815 */ 5816 bool read_lock_is_recursive(void) 5817 { 5818 return force_read_lock_recursive || 5819 !IS_ENABLED(CONFIG_QUEUED_RWLOCKS) || 5820 in_interrupt(); 5821 } 5822 EXPORT_SYMBOL_GPL(read_lock_is_recursive); 5823 5824 /* 5825 * We are not always called with irqs disabled - do that here, 5826 * and also avoid lockdep recursion: 5827 */ 5828 void lock_acquire(struct lockdep_map *lock, unsigned int subclass, 5829 int trylock, int read, int check, 5830 struct lockdep_map *nest_lock, unsigned long ip) 5831 { 5832 unsigned long flags; 5833 5834 trace_lock_acquire(lock, subclass, trylock, read, check, nest_lock, ip); 5835 5836 if (!debug_locks) 5837 return; 5838 5839 /* 5840 * As KASAN instrumentation is disabled and lock_acquire() is usually 5841 * the first lockdep call when a task tries to acquire a lock, add 5842 * kasan_check_byte() here to check for use-after-free and other 5843 * memory errors. 5844 */ 5845 kasan_check_byte(lock); 5846 5847 if (unlikely(!lockdep_enabled())) { 5848 /* XXX allow trylock from NMI ?!? */ 5849 if (lockdep_nmi() && !trylock) { 5850 struct held_lock hlock; 5851 5852 hlock.acquire_ip = ip; 5853 hlock.instance = lock; 5854 hlock.nest_lock = nest_lock; 5855 hlock.irq_context = 2; // XXX 5856 hlock.trylock = trylock; 5857 hlock.read = read; 5858 hlock.check = check; 5859 hlock.hardirqs_off = true; 5860 hlock.references = 0; 5861 5862 verify_lock_unused(lock, &hlock, subclass); 5863 } 5864 return; 5865 } 5866 5867 raw_local_irq_save(flags); 5868 check_flags(flags); 5869 5870 lockdep_recursion_inc(); 5871 __lock_acquire(lock, subclass, trylock, read, check, 5872 irqs_disabled_flags(flags), nest_lock, ip, 0, 0, 0); 5873 lockdep_recursion_finish(); 5874 raw_local_irq_restore(flags); 5875 } 5876 EXPORT_SYMBOL_GPL(lock_acquire); 5877 5878 void lock_release(struct lockdep_map *lock, unsigned long ip) 5879 { 5880 unsigned long flags; 5881 5882 trace_lock_release(lock, ip); 5883 5884 if (unlikely(!lockdep_enabled() || 5885 lock->key == &__lockdep_no_track__)) 5886 return; 5887 5888 raw_local_irq_save(flags); 5889 check_flags(flags); 5890 5891 lockdep_recursion_inc(); 5892 if (__lock_release(lock, ip)) 5893 check_chain_key(current); 5894 lockdep_recursion_finish(); 5895 raw_local_irq_restore(flags); 5896 } 5897 EXPORT_SYMBOL_GPL(lock_release); 5898 5899 /* 5900 * lock_sync() - A special annotation for synchronize_{s,}rcu()-like API. 5901 * 5902 * No actual critical section is created by the APIs annotated with this: these 5903 * APIs are used to wait for one or multiple critical sections (on other CPUs 5904 * or threads), and it means that calling these APIs inside these critical 5905 * sections is potential deadlock. 5906 */ 5907 void lock_sync(struct lockdep_map *lock, unsigned subclass, int read, 5908 int check, struct lockdep_map *nest_lock, unsigned long ip) 5909 { 5910 unsigned long flags; 5911 5912 if (unlikely(!lockdep_enabled())) 5913 return; 5914 5915 raw_local_irq_save(flags); 5916 check_flags(flags); 5917 5918 lockdep_recursion_inc(); 5919 __lock_acquire(lock, subclass, 0, read, check, 5920 irqs_disabled_flags(flags), nest_lock, ip, 0, 0, 1); 5921 check_chain_key(current); 5922 lockdep_recursion_finish(); 5923 raw_local_irq_restore(flags); 5924 } 5925 EXPORT_SYMBOL_GPL(lock_sync); 5926 5927 noinstr int lock_is_held_type(const struct lockdep_map *lock, int read) 5928 { 5929 unsigned long flags; 5930 int ret = LOCK_STATE_NOT_HELD; 5931 5932 /* 5933 * Avoid false negative lockdep_assert_held() and 5934 * lockdep_assert_not_held(). 5935 */ 5936 if (unlikely(!lockdep_enabled())) 5937 return LOCK_STATE_UNKNOWN; 5938 5939 raw_local_irq_save(flags); 5940 check_flags(flags); 5941 5942 lockdep_recursion_inc(); 5943 ret = __lock_is_held(lock, read); 5944 lockdep_recursion_finish(); 5945 raw_local_irq_restore(flags); 5946 5947 return ret; 5948 } 5949 EXPORT_SYMBOL_GPL(lock_is_held_type); 5950 NOKPROBE_SYMBOL(lock_is_held_type); 5951 5952 struct pin_cookie lock_pin_lock(struct lockdep_map *lock) 5953 { 5954 struct pin_cookie cookie = NIL_COOKIE; 5955 unsigned long flags; 5956 5957 if (unlikely(!lockdep_enabled())) 5958 return cookie; 5959 5960 raw_local_irq_save(flags); 5961 check_flags(flags); 5962 5963 lockdep_recursion_inc(); 5964 cookie = __lock_pin_lock(lock); 5965 lockdep_recursion_finish(); 5966 raw_local_irq_restore(flags); 5967 5968 return cookie; 5969 } 5970 EXPORT_SYMBOL_GPL(lock_pin_lock); 5971 5972 void lock_repin_lock(struct lockdep_map *lock, struct pin_cookie cookie) 5973 { 5974 unsigned long flags; 5975 5976 if (unlikely(!lockdep_enabled())) 5977 return; 5978 5979 raw_local_irq_save(flags); 5980 check_flags(flags); 5981 5982 lockdep_recursion_inc(); 5983 __lock_repin_lock(lock, cookie); 5984 lockdep_recursion_finish(); 5985 raw_local_irq_restore(flags); 5986 } 5987 EXPORT_SYMBOL_GPL(lock_repin_lock); 5988 5989 void lock_unpin_lock(struct lockdep_map *lock, struct pin_cookie cookie) 5990 { 5991 unsigned long flags; 5992 5993 if (unlikely(!lockdep_enabled())) 5994 return; 5995 5996 raw_local_irq_save(flags); 5997 check_flags(flags); 5998 5999 lockdep_recursion_inc(); 6000 __lock_unpin_lock(lock, cookie); 6001 lockdep_recursion_finish(); 6002 raw_local_irq_restore(flags); 6003 } 6004 EXPORT_SYMBOL_GPL(lock_unpin_lock); 6005 6006 #ifdef CONFIG_LOCK_STAT 6007 static void print_lock_contention_bug(struct task_struct *curr, 6008 struct lockdep_map *lock, 6009 unsigned long ip) 6010 { 6011 if (!debug_locks_off()) 6012 return; 6013 if (debug_locks_silent) 6014 return; 6015 6016 nbcon_cpu_emergency_enter(); 6017 6018 pr_warn("\n"); 6019 pr_warn("=================================\n"); 6020 pr_warn("WARNING: bad contention detected!\n"); 6021 print_kernel_ident(); 6022 pr_warn("---------------------------------\n"); 6023 pr_warn("%s/%d is trying to contend lock (", 6024 curr->comm, task_pid_nr(curr)); 6025 print_lockdep_cache(lock); 6026 pr_cont(") at:\n"); 6027 print_ip_sym(KERN_WARNING, ip); 6028 pr_warn("but there are no locks held!\n"); 6029 pr_warn("\nother info that might help us debug this:\n"); 6030 lockdep_print_held_locks(curr); 6031 6032 pr_warn("\nstack backtrace:\n"); 6033 dump_stack(); 6034 6035 nbcon_cpu_emergency_exit(); 6036 } 6037 6038 static void 6039 __lock_contended(struct lockdep_map *lock, unsigned long ip) 6040 { 6041 struct task_struct *curr = current; 6042 struct held_lock *hlock; 6043 struct lock_class_stats *stats; 6044 unsigned int depth; 6045 int i, contention_point, contending_point; 6046 6047 depth = curr->lockdep_depth; 6048 /* 6049 * Whee, we contended on this lock, except it seems we're not 6050 * actually trying to acquire anything much at all.. 6051 */ 6052 if (DEBUG_LOCKS_WARN_ON(!depth)) 6053 return; 6054 6055 if (unlikely(lock->key == &__lockdep_no_track__)) 6056 return; 6057 6058 hlock = find_held_lock(curr, lock, depth, &i); 6059 if (!hlock) { 6060 print_lock_contention_bug(curr, lock, ip); 6061 return; 6062 } 6063 6064 if (hlock->instance != lock) 6065 return; 6066 6067 hlock->waittime_stamp = lockstat_clock(); 6068 6069 contention_point = lock_point(hlock_class(hlock)->contention_point, ip); 6070 contending_point = lock_point(hlock_class(hlock)->contending_point, 6071 lock->ip); 6072 6073 stats = get_lock_stats(hlock_class(hlock)); 6074 if (contention_point < LOCKSTAT_POINTS) 6075 stats->contention_point[contention_point]++; 6076 if (contending_point < LOCKSTAT_POINTS) 6077 stats->contending_point[contending_point]++; 6078 if (lock->cpu != smp_processor_id()) 6079 stats->bounces[bounce_contended + !!hlock->read]++; 6080 } 6081 6082 static void 6083 __lock_acquired(struct lockdep_map *lock, unsigned long ip) 6084 { 6085 struct task_struct *curr = current; 6086 struct held_lock *hlock; 6087 struct lock_class_stats *stats; 6088 unsigned int depth; 6089 u64 now, waittime = 0; 6090 int i, cpu; 6091 6092 depth = curr->lockdep_depth; 6093 /* 6094 * Yay, we acquired ownership of this lock we didn't try to 6095 * acquire, how the heck did that happen? 6096 */ 6097 if (DEBUG_LOCKS_WARN_ON(!depth)) 6098 return; 6099 6100 if (unlikely(lock->key == &__lockdep_no_track__)) 6101 return; 6102 6103 hlock = find_held_lock(curr, lock, depth, &i); 6104 if (!hlock) { 6105 print_lock_contention_bug(curr, lock, _RET_IP_); 6106 return; 6107 } 6108 6109 if (hlock->instance != lock) 6110 return; 6111 6112 cpu = smp_processor_id(); 6113 if (hlock->waittime_stamp) { 6114 now = lockstat_clock(); 6115 waittime = now - hlock->waittime_stamp; 6116 hlock->holdtime_stamp = now; 6117 } 6118 6119 stats = get_lock_stats(hlock_class(hlock)); 6120 if (waittime) { 6121 if (hlock->read) 6122 lock_time_inc(&stats->read_waittime, waittime); 6123 else 6124 lock_time_inc(&stats->write_waittime, waittime); 6125 } 6126 if (lock->cpu != cpu) 6127 stats->bounces[bounce_acquired + !!hlock->read]++; 6128 6129 lock->cpu = cpu; 6130 lock->ip = ip; 6131 } 6132 6133 void lock_contended(struct lockdep_map *lock, unsigned long ip) 6134 { 6135 unsigned long flags; 6136 6137 trace_lock_contended(lock, ip); 6138 6139 if (unlikely(!lock_stat || !lockdep_enabled())) 6140 return; 6141 6142 raw_local_irq_save(flags); 6143 check_flags(flags); 6144 lockdep_recursion_inc(); 6145 __lock_contended(lock, ip); 6146 lockdep_recursion_finish(); 6147 raw_local_irq_restore(flags); 6148 } 6149 EXPORT_SYMBOL_GPL(lock_contended); 6150 6151 void lock_acquired(struct lockdep_map *lock, unsigned long ip) 6152 { 6153 unsigned long flags; 6154 6155 trace_lock_acquired(lock, ip); 6156 6157 if (unlikely(!lock_stat || !lockdep_enabled())) 6158 return; 6159 6160 raw_local_irq_save(flags); 6161 check_flags(flags); 6162 lockdep_recursion_inc(); 6163 __lock_acquired(lock, ip); 6164 lockdep_recursion_finish(); 6165 raw_local_irq_restore(flags); 6166 } 6167 EXPORT_SYMBOL_GPL(lock_acquired); 6168 #endif 6169 6170 /* 6171 * Used by the testsuite, sanitize the validator state 6172 * after a simulated failure: 6173 */ 6174 6175 void lockdep_reset(void) 6176 { 6177 unsigned long flags; 6178 int i; 6179 6180 raw_local_irq_save(flags); 6181 lockdep_init_task(current); 6182 memset(current->held_locks, 0, MAX_LOCK_DEPTH*sizeof(struct held_lock)); 6183 nr_hardirq_chains = 0; 6184 nr_softirq_chains = 0; 6185 nr_process_chains = 0; 6186 debug_locks = 1; 6187 for (i = 0; i < CHAINHASH_SIZE; i++) 6188 INIT_HLIST_HEAD(chainhash_table + i); 6189 raw_local_irq_restore(flags); 6190 } 6191 6192 /* Remove a class from a lock chain. Must be called with the graph lock held. */ 6193 static void remove_class_from_lock_chain(struct pending_free *pf, 6194 struct lock_chain *chain, 6195 struct lock_class *class) 6196 { 6197 #ifdef CONFIG_PROVE_LOCKING 6198 int i; 6199 6200 for (i = chain->base; i < chain->base + chain->depth; i++) { 6201 if (chain_hlock_class_idx(chain_hlocks[i]) != class - lock_classes) 6202 continue; 6203 /* 6204 * Each lock class occurs at most once in a lock chain so once 6205 * we found a match we can break out of this loop. 6206 */ 6207 goto free_lock_chain; 6208 } 6209 /* Since the chain has not been modified, return. */ 6210 return; 6211 6212 free_lock_chain: 6213 free_chain_hlocks(chain->base, chain->depth); 6214 /* Overwrite the chain key for concurrent RCU readers. */ 6215 WRITE_ONCE(chain->chain_key, INITIAL_CHAIN_KEY); 6216 dec_chains(chain->irq_context); 6217 6218 /* 6219 * Note: calling hlist_del_rcu() from inside a 6220 * hlist_for_each_entry_rcu() loop is safe. 6221 */ 6222 hlist_del_rcu(&chain->entry); 6223 __set_bit(chain - lock_chains, pf->lock_chains_being_freed); 6224 nr_zapped_lock_chains++; 6225 #endif 6226 } 6227 6228 /* Must be called with the graph lock held. */ 6229 static void remove_class_from_lock_chains(struct pending_free *pf, 6230 struct lock_class *class) 6231 { 6232 struct lock_chain *chain; 6233 struct hlist_head *head; 6234 int i; 6235 6236 for (i = 0; i < ARRAY_SIZE(chainhash_table); i++) { 6237 head = chainhash_table + i; 6238 hlist_for_each_entry_rcu(chain, head, entry) { 6239 remove_class_from_lock_chain(pf, chain, class); 6240 } 6241 } 6242 } 6243 6244 /* 6245 * Remove all references to a lock class. The caller must hold the graph lock. 6246 */ 6247 static void zap_class(struct pending_free *pf, struct lock_class *class) 6248 { 6249 struct lock_list *entry; 6250 int i; 6251 6252 WARN_ON_ONCE(!class->key); 6253 6254 /* 6255 * Remove all dependencies this lock is 6256 * involved in: 6257 */ 6258 for_each_set_bit(i, list_entries_in_use, ARRAY_SIZE(list_entries)) { 6259 entry = list_entries + i; 6260 if (entry->class != class && entry->links_to != class) 6261 continue; 6262 __clear_bit(i, list_entries_in_use); 6263 nr_list_entries--; 6264 list_del_rcu(&entry->entry); 6265 } 6266 if (list_empty(&class->locks_after) && 6267 list_empty(&class->locks_before)) { 6268 list_move_tail(&class->lock_entry, &pf->zapped); 6269 hlist_del_rcu(&class->hash_entry); 6270 WRITE_ONCE(class->key, NULL); 6271 WRITE_ONCE(class->name, NULL); 6272 /* Class allocated but not used, -1 in nr_unused_locks */ 6273 if (class->usage_mask == 0) 6274 debug_atomic_dec(nr_unused_locks); 6275 nr_lock_classes--; 6276 __clear_bit(class - lock_classes, lock_classes_in_use); 6277 if (class - lock_classes == max_lock_class_idx) 6278 max_lock_class_idx--; 6279 } else { 6280 WARN_ONCE(true, "%s() failed for class %s\n", __func__, 6281 class->name); 6282 } 6283 6284 remove_class_from_lock_chains(pf, class); 6285 nr_zapped_classes++; 6286 } 6287 6288 static void reinit_class(struct lock_class *class) 6289 { 6290 WARN_ON_ONCE(!class->lock_entry.next); 6291 WARN_ON_ONCE(!list_empty(&class->locks_after)); 6292 WARN_ON_ONCE(!list_empty(&class->locks_before)); 6293 memset_startat(class, 0, key); 6294 WARN_ON_ONCE(!class->lock_entry.next); 6295 WARN_ON_ONCE(!list_empty(&class->locks_after)); 6296 WARN_ON_ONCE(!list_empty(&class->locks_before)); 6297 } 6298 6299 static inline int within(const void *addr, void *start, unsigned long size) 6300 { 6301 return addr >= start && addr < start + size; 6302 } 6303 6304 static bool inside_selftest(void) 6305 { 6306 return current == lockdep_selftest_task_struct; 6307 } 6308 6309 /* The caller must hold the graph lock. */ 6310 static struct pending_free *get_pending_free(void) 6311 { 6312 return delayed_free.pf + delayed_free.index; 6313 } 6314 6315 static void free_zapped_rcu(struct rcu_head *cb); 6316 6317 /* 6318 * See if we need to queue an RCU callback, must called with 6319 * the lockdep lock held, returns false if either we don't have 6320 * any pending free or the callback is already scheduled. 6321 * Otherwise, a call_rcu() must follow this function call. 6322 */ 6323 static bool prepare_call_rcu_zapped(struct pending_free *pf) 6324 { 6325 WARN_ON_ONCE(inside_selftest()); 6326 6327 if (list_empty(&pf->zapped)) 6328 return false; 6329 6330 if (delayed_free.scheduled) 6331 return false; 6332 6333 delayed_free.scheduled = true; 6334 6335 WARN_ON_ONCE(delayed_free.pf + delayed_free.index != pf); 6336 delayed_free.index ^= 1; 6337 6338 return true; 6339 } 6340 6341 /* The caller must hold the graph lock. May be called from RCU context. */ 6342 static void __free_zapped_classes(struct pending_free *pf) 6343 { 6344 struct lock_class *class; 6345 6346 check_data_structures(); 6347 6348 list_for_each_entry(class, &pf->zapped, lock_entry) 6349 reinit_class(class); 6350 6351 list_splice_init(&pf->zapped, &free_lock_classes); 6352 6353 #ifdef CONFIG_PROVE_LOCKING 6354 bitmap_andnot(lock_chains_in_use, lock_chains_in_use, 6355 pf->lock_chains_being_freed, ARRAY_SIZE(lock_chains)); 6356 bitmap_clear(pf->lock_chains_being_freed, 0, ARRAY_SIZE(lock_chains)); 6357 #endif 6358 } 6359 6360 static void free_zapped_rcu(struct rcu_head *ch) 6361 { 6362 struct pending_free *pf; 6363 unsigned long flags; 6364 bool need_callback; 6365 6366 if (WARN_ON_ONCE(ch != &delayed_free.rcu_head)) 6367 return; 6368 6369 raw_local_irq_save(flags); 6370 lockdep_lock(); 6371 6372 /* closed head */ 6373 pf = delayed_free.pf + (delayed_free.index ^ 1); 6374 __free_zapped_classes(pf); 6375 delayed_free.scheduled = false; 6376 need_callback = 6377 prepare_call_rcu_zapped(delayed_free.pf + delayed_free.index); 6378 lockdep_unlock(); 6379 raw_local_irq_restore(flags); 6380 6381 /* 6382 * If there's pending free and its callback has not been scheduled, 6383 * queue an RCU callback. 6384 */ 6385 if (need_callback) 6386 call_rcu(&delayed_free.rcu_head, free_zapped_rcu); 6387 6388 } 6389 6390 /* 6391 * Remove all lock classes from the class hash table and from the 6392 * all_lock_classes list whose key or name is in the address range [start, 6393 * start + size). Move these lock classes to the zapped_classes list. Must 6394 * be called with the graph lock held. 6395 */ 6396 static void __lockdep_free_key_range(struct pending_free *pf, void *start, 6397 unsigned long size) 6398 { 6399 struct lock_class *class; 6400 struct hlist_head *head; 6401 int i; 6402 6403 /* Unhash all classes that were created by a module. */ 6404 for (i = 0; i < CLASSHASH_SIZE; i++) { 6405 head = classhash_table + i; 6406 hlist_for_each_entry_rcu(class, head, hash_entry) { 6407 if (!within(class->key, start, size) && 6408 !within(class->name, start, size)) 6409 continue; 6410 zap_class(pf, class); 6411 } 6412 } 6413 } 6414 6415 /* 6416 * Used in module.c to remove lock classes from memory that is going to be 6417 * freed; and possibly re-used by other modules. 6418 * 6419 * We will have had one synchronize_rcu() before getting here, so we're 6420 * guaranteed nobody will look up these exact classes -- they're properly dead 6421 * but still allocated. 6422 */ 6423 static void lockdep_free_key_range_reg(void *start, unsigned long size) 6424 { 6425 struct pending_free *pf; 6426 unsigned long flags; 6427 bool need_callback; 6428 6429 init_data_structures_once(); 6430 6431 raw_local_irq_save(flags); 6432 lockdep_lock(); 6433 pf = get_pending_free(); 6434 __lockdep_free_key_range(pf, start, size); 6435 need_callback = prepare_call_rcu_zapped(pf); 6436 lockdep_unlock(); 6437 raw_local_irq_restore(flags); 6438 if (need_callback) 6439 call_rcu(&delayed_free.rcu_head, free_zapped_rcu); 6440 /* 6441 * Wait for any possible iterators from look_up_lock_class() to pass 6442 * before continuing to free the memory they refer to. 6443 */ 6444 synchronize_rcu(); 6445 } 6446 6447 /* 6448 * Free all lockdep keys in the range [start, start+size). Does not sleep. 6449 * Ignores debug_locks. Must only be used by the lockdep selftests. 6450 */ 6451 static void lockdep_free_key_range_imm(void *start, unsigned long size) 6452 { 6453 struct pending_free *pf = delayed_free.pf; 6454 unsigned long flags; 6455 6456 init_data_structures_once(); 6457 6458 raw_local_irq_save(flags); 6459 lockdep_lock(); 6460 __lockdep_free_key_range(pf, start, size); 6461 __free_zapped_classes(pf); 6462 lockdep_unlock(); 6463 raw_local_irq_restore(flags); 6464 } 6465 6466 void lockdep_free_key_range(void *start, unsigned long size) 6467 { 6468 init_data_structures_once(); 6469 6470 if (inside_selftest()) 6471 lockdep_free_key_range_imm(start, size); 6472 else 6473 lockdep_free_key_range_reg(start, size); 6474 } 6475 6476 /* 6477 * Check whether any element of the @lock->class_cache[] array refers to a 6478 * registered lock class. The caller must hold either the graph lock or the 6479 * RCU read lock. 6480 */ 6481 static bool lock_class_cache_is_registered(struct lockdep_map *lock) 6482 { 6483 struct lock_class *class; 6484 struct hlist_head *head; 6485 int i, j; 6486 6487 for (i = 0; i < CLASSHASH_SIZE; i++) { 6488 head = classhash_table + i; 6489 hlist_for_each_entry_rcu(class, head, hash_entry) { 6490 for (j = 0; j < NR_LOCKDEP_CACHING_CLASSES; j++) 6491 if (lock->class_cache[j] == class) 6492 return true; 6493 } 6494 } 6495 return false; 6496 } 6497 6498 /* The caller must hold the graph lock. Does not sleep. */ 6499 static void __lockdep_reset_lock(struct pending_free *pf, 6500 struct lockdep_map *lock) 6501 { 6502 struct lock_class *class; 6503 int j; 6504 6505 /* 6506 * Remove all classes this lock might have: 6507 */ 6508 for (j = 0; j < MAX_LOCKDEP_SUBCLASSES; j++) { 6509 /* 6510 * If the class exists we look it up and zap it: 6511 */ 6512 class = look_up_lock_class(lock, j); 6513 if (class) 6514 zap_class(pf, class); 6515 } 6516 /* 6517 * Debug check: in the end all mapped classes should 6518 * be gone. 6519 */ 6520 if (WARN_ON_ONCE(lock_class_cache_is_registered(lock))) 6521 debug_locks_off(); 6522 } 6523 6524 /* 6525 * Remove all information lockdep has about a lock if debug_locks == 1. Free 6526 * released data structures from RCU context. 6527 */ 6528 static void lockdep_reset_lock_reg(struct lockdep_map *lock) 6529 { 6530 struct pending_free *pf; 6531 unsigned long flags; 6532 int locked; 6533 bool need_callback = false; 6534 6535 raw_local_irq_save(flags); 6536 locked = graph_lock(); 6537 if (!locked) 6538 goto out_irq; 6539 6540 pf = get_pending_free(); 6541 __lockdep_reset_lock(pf, lock); 6542 need_callback = prepare_call_rcu_zapped(pf); 6543 6544 graph_unlock(); 6545 out_irq: 6546 raw_local_irq_restore(flags); 6547 if (need_callback) 6548 call_rcu(&delayed_free.rcu_head, free_zapped_rcu); 6549 } 6550 6551 /* 6552 * Reset a lock. Does not sleep. Ignores debug_locks. Must only be used by the 6553 * lockdep selftests. 6554 */ 6555 static void lockdep_reset_lock_imm(struct lockdep_map *lock) 6556 { 6557 struct pending_free *pf = delayed_free.pf; 6558 unsigned long flags; 6559 6560 raw_local_irq_save(flags); 6561 lockdep_lock(); 6562 __lockdep_reset_lock(pf, lock); 6563 __free_zapped_classes(pf); 6564 lockdep_unlock(); 6565 raw_local_irq_restore(flags); 6566 } 6567 6568 void lockdep_reset_lock(struct lockdep_map *lock) 6569 { 6570 init_data_structures_once(); 6571 6572 if (inside_selftest()) 6573 lockdep_reset_lock_imm(lock); 6574 else 6575 lockdep_reset_lock_reg(lock); 6576 } 6577 6578 /* 6579 * Unregister a dynamically allocated key. 6580 * 6581 * Unlike lockdep_register_key(), a search is always done to find a matching 6582 * key irrespective of debug_locks to avoid potential invalid access to freed 6583 * memory in lock_class entry. 6584 */ 6585 void lockdep_unregister_key(struct lock_class_key *key) 6586 { 6587 struct hlist_head *hash_head = keyhashentry(key); 6588 struct lock_class_key *k; 6589 struct pending_free *pf; 6590 unsigned long flags; 6591 bool found = false; 6592 bool need_callback = false; 6593 6594 might_sleep(); 6595 6596 if (WARN_ON_ONCE(static_obj(key))) 6597 return; 6598 6599 raw_local_irq_save(flags); 6600 lockdep_lock(); 6601 6602 hlist_for_each_entry_rcu(k, hash_head, hash_entry) { 6603 if (k == key) { 6604 hlist_del_rcu(&k->hash_entry); 6605 found = true; 6606 break; 6607 } 6608 } 6609 WARN_ON_ONCE(!found && debug_locks); 6610 if (found) { 6611 pf = get_pending_free(); 6612 __lockdep_free_key_range(pf, key, 1); 6613 need_callback = prepare_call_rcu_zapped(pf); 6614 nr_dynamic_keys--; 6615 } 6616 lockdep_unlock(); 6617 raw_local_irq_restore(flags); 6618 6619 if (need_callback) 6620 call_rcu(&delayed_free.rcu_head, free_zapped_rcu); 6621 6622 /* Wait until is_dynamic_key() has finished accessing k->hash_entry. */ 6623 synchronize_rcu(); 6624 } 6625 EXPORT_SYMBOL_GPL(lockdep_unregister_key); 6626 6627 void __init lockdep_init(void) 6628 { 6629 pr_info("Lock dependency validator: Copyright (c) 2006 Red Hat, Inc., Ingo Molnar\n"); 6630 6631 pr_info("... MAX_LOCKDEP_SUBCLASSES: %lu\n", MAX_LOCKDEP_SUBCLASSES); 6632 pr_info("... MAX_LOCK_DEPTH: %lu\n", MAX_LOCK_DEPTH); 6633 pr_info("... MAX_LOCKDEP_KEYS: %lu\n", MAX_LOCKDEP_KEYS); 6634 pr_info("... CLASSHASH_SIZE: %lu\n", CLASSHASH_SIZE); 6635 pr_info("... MAX_LOCKDEP_ENTRIES: %lu\n", MAX_LOCKDEP_ENTRIES); 6636 pr_info("... MAX_LOCKDEP_CHAINS: %lu\n", MAX_LOCKDEP_CHAINS); 6637 pr_info("... CHAINHASH_SIZE: %lu\n", CHAINHASH_SIZE); 6638 6639 pr_info(" memory used by lock dependency info: %zu kB\n", 6640 (sizeof(lock_classes) + 6641 sizeof(lock_classes_in_use) + 6642 sizeof(classhash_table) + 6643 sizeof(list_entries) + 6644 sizeof(list_entries_in_use) + 6645 sizeof(chainhash_table) + 6646 sizeof(delayed_free) 6647 #ifdef CONFIG_PROVE_LOCKING 6648 + sizeof(lock_cq) 6649 + sizeof(lock_chains) 6650 + sizeof(lock_chains_in_use) 6651 + sizeof(chain_hlocks) 6652 #endif 6653 ) / 1024 6654 ); 6655 6656 #if defined(CONFIG_TRACE_IRQFLAGS) && defined(CONFIG_PROVE_LOCKING) 6657 pr_info(" memory used for stack traces: %zu kB\n", 6658 (sizeof(stack_trace) + sizeof(stack_trace_hash)) / 1024 6659 ); 6660 #endif 6661 6662 pr_info(" per task-struct memory footprint: %zu bytes\n", 6663 sizeof(((struct task_struct *)NULL)->held_locks)); 6664 } 6665 6666 static void 6667 print_freed_lock_bug(struct task_struct *curr, const void *mem_from, 6668 const void *mem_to, struct held_lock *hlock) 6669 { 6670 if (!debug_locks_off()) 6671 return; 6672 if (debug_locks_silent) 6673 return; 6674 6675 nbcon_cpu_emergency_enter(); 6676 6677 pr_warn("\n"); 6678 pr_warn("=========================\n"); 6679 pr_warn("WARNING: held lock freed!\n"); 6680 print_kernel_ident(); 6681 pr_warn("-------------------------\n"); 6682 pr_warn("%s/%d is freeing memory %px-%px, with a lock still held there!\n", 6683 curr->comm, task_pid_nr(curr), mem_from, mem_to-1); 6684 print_lock(hlock); 6685 lockdep_print_held_locks(curr); 6686 6687 pr_warn("\nstack backtrace:\n"); 6688 dump_stack(); 6689 6690 nbcon_cpu_emergency_exit(); 6691 } 6692 6693 static inline int not_in_range(const void* mem_from, unsigned long mem_len, 6694 const void* lock_from, unsigned long lock_len) 6695 { 6696 return lock_from + lock_len <= mem_from || 6697 mem_from + mem_len <= lock_from; 6698 } 6699 6700 /* 6701 * Called when kernel memory is freed (or unmapped), or if a lock 6702 * is destroyed or reinitialized - this code checks whether there is 6703 * any held lock in the memory range of <from> to <to>: 6704 */ 6705 void debug_check_no_locks_freed(const void *mem_from, unsigned long mem_len) 6706 { 6707 struct task_struct *curr = current; 6708 struct held_lock *hlock; 6709 unsigned long flags; 6710 int i; 6711 6712 if (unlikely(!debug_locks)) 6713 return; 6714 6715 raw_local_irq_save(flags); 6716 for (i = 0; i < curr->lockdep_depth; i++) { 6717 hlock = curr->held_locks + i; 6718 6719 if (not_in_range(mem_from, mem_len, hlock->instance, 6720 sizeof(*hlock->instance))) 6721 continue; 6722 6723 print_freed_lock_bug(curr, mem_from, mem_from + mem_len, hlock); 6724 break; 6725 } 6726 raw_local_irq_restore(flags); 6727 } 6728 EXPORT_SYMBOL_GPL(debug_check_no_locks_freed); 6729 6730 static void print_held_locks_bug(void) 6731 { 6732 if (!debug_locks_off()) 6733 return; 6734 if (debug_locks_silent) 6735 return; 6736 6737 nbcon_cpu_emergency_enter(); 6738 6739 pr_warn("\n"); 6740 pr_warn("====================================\n"); 6741 pr_warn("WARNING: %s/%d still has locks held!\n", 6742 current->comm, task_pid_nr(current)); 6743 print_kernel_ident(); 6744 pr_warn("------------------------------------\n"); 6745 lockdep_print_held_locks(current); 6746 pr_warn("\nstack backtrace:\n"); 6747 dump_stack(); 6748 6749 nbcon_cpu_emergency_exit(); 6750 } 6751 6752 void debug_check_no_locks_held(void) 6753 { 6754 if (unlikely(current->lockdep_depth > 0)) 6755 print_held_locks_bug(); 6756 } 6757 EXPORT_SYMBOL_GPL(debug_check_no_locks_held); 6758 6759 #ifdef __KERNEL__ 6760 void debug_show_all_locks(void) 6761 { 6762 struct task_struct *g, *p; 6763 6764 if (unlikely(!debug_locks)) { 6765 pr_warn("INFO: lockdep is turned off.\n"); 6766 return; 6767 } 6768 pr_warn("\nShowing all locks held in the system:\n"); 6769 6770 rcu_read_lock(); 6771 for_each_process_thread(g, p) { 6772 if (!p->lockdep_depth) 6773 continue; 6774 lockdep_print_held_locks(p); 6775 touch_nmi_watchdog(); 6776 touch_all_softlockup_watchdogs(); 6777 } 6778 rcu_read_unlock(); 6779 6780 pr_warn("\n"); 6781 pr_warn("=============================================\n\n"); 6782 } 6783 EXPORT_SYMBOL_GPL(debug_show_all_locks); 6784 #endif 6785 6786 /* 6787 * Careful: only use this function if you are sure that 6788 * the task cannot run in parallel! 6789 */ 6790 void debug_show_held_locks(struct task_struct *task) 6791 { 6792 if (unlikely(!debug_locks)) { 6793 printk("INFO: lockdep is turned off.\n"); 6794 return; 6795 } 6796 lockdep_print_held_locks(task); 6797 } 6798 EXPORT_SYMBOL_GPL(debug_show_held_locks); 6799 6800 asmlinkage __visible void lockdep_sys_exit(void) 6801 { 6802 struct task_struct *curr = current; 6803 6804 if (unlikely(curr->lockdep_depth)) { 6805 if (!debug_locks_off()) 6806 return; 6807 nbcon_cpu_emergency_enter(); 6808 pr_warn("\n"); 6809 pr_warn("================================================\n"); 6810 pr_warn("WARNING: lock held when returning to user space!\n"); 6811 print_kernel_ident(); 6812 pr_warn("------------------------------------------------\n"); 6813 pr_warn("%s/%d is leaving the kernel with locks still held!\n", 6814 curr->comm, curr->pid); 6815 lockdep_print_held_locks(curr); 6816 nbcon_cpu_emergency_exit(); 6817 } 6818 6819 /* 6820 * The lock history for each syscall should be independent. So wipe the 6821 * slate clean on return to userspace. 6822 */ 6823 lockdep_invariant_state(false); 6824 } 6825 6826 void lockdep_rcu_suspicious(const char *file, const int line, const char *s) 6827 { 6828 struct task_struct *curr = current; 6829 int dl = READ_ONCE(debug_locks); 6830 bool rcu = warn_rcu_enter(); 6831 6832 /* Note: the following can be executed concurrently, so be careful. */ 6833 nbcon_cpu_emergency_enter(); 6834 pr_warn("\n"); 6835 pr_warn("=============================\n"); 6836 pr_warn("WARNING: suspicious RCU usage\n"); 6837 print_kernel_ident(); 6838 pr_warn("-----------------------------\n"); 6839 pr_warn("%s:%d %s!\n", file, line, s); 6840 pr_warn("\nother info that might help us debug this:\n\n"); 6841 pr_warn("\n%srcu_scheduler_active = %d, debug_locks = %d\n%s", 6842 !rcu_lockdep_current_cpu_online() 6843 ? "RCU used illegally from offline CPU!\n" 6844 : "", 6845 rcu_scheduler_active, dl, 6846 dl ? "" : "Possible false positive due to lockdep disabling via debug_locks = 0\n"); 6847 6848 /* 6849 * If a CPU is in the RCU-free window in idle (ie: in the section 6850 * between ct_idle_enter() and ct_idle_exit(), then RCU 6851 * considers that CPU to be in an "extended quiescent state", 6852 * which means that RCU will be completely ignoring that CPU. 6853 * Therefore, rcu_read_lock() and friends have absolutely no 6854 * effect on a CPU running in that state. In other words, even if 6855 * such an RCU-idle CPU has called rcu_read_lock(), RCU might well 6856 * delete data structures out from under it. RCU really has no 6857 * choice here: we need to keep an RCU-free window in idle where 6858 * the CPU may possibly enter into low power mode. This way we can 6859 * notice an extended quiescent state to other CPUs that started a grace 6860 * period. Otherwise we would delay any grace period as long as we run 6861 * in the idle task. 6862 * 6863 * So complain bitterly if someone does call rcu_read_lock(), 6864 * rcu_read_lock_bh() and so on from extended quiescent states. 6865 */ 6866 if (!rcu_is_watching()) 6867 pr_warn("RCU used illegally from extended quiescent state!\n"); 6868 6869 lockdep_print_held_locks(curr); 6870 pr_warn("\nstack backtrace:\n"); 6871 dump_stack(); 6872 nbcon_cpu_emergency_exit(); 6873 warn_rcu_exit(rcu); 6874 } 6875 EXPORT_SYMBOL_GPL(lockdep_rcu_suspicious); 6876