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