1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * kernel/locking/mutex.c 4 * 5 * Mutexes: blocking mutual exclusion locks 6 * 7 * Started by Ingo Molnar: 8 * 9 * Copyright (C) 2004, 2005, 2006 Red Hat, Inc., Ingo Molnar <mingo@redhat.com> 10 * 11 * Many thanks to Arjan van de Ven, Thomas Gleixner, Steven Rostedt and 12 * David Howells for suggestions and improvements. 13 * 14 * - Adaptive spinning for mutexes by Peter Zijlstra. (Ported to mainline 15 * from the -rt tree, where it was originally implemented for rtmutexes 16 * by Steven Rostedt, based on work by Gregory Haskins, Peter Morreale 17 * and Sven Dietrich. 18 * 19 * Also see Documentation/locking/mutex-design.rst. 20 */ 21 #include <linux/mutex.h> 22 #include <linux/ww_mutex.h> 23 #include <linux/sched/signal.h> 24 #include <linux/sched/rt.h> 25 #include <linux/sched/wake_q.h> 26 #include <linux/sched/debug.h> 27 #include <linux/export.h> 28 #include <linux/spinlock.h> 29 #include <linux/interrupt.h> 30 #include <linux/debug_locks.h> 31 #include <linux/osq_lock.h> 32 #include <linux/hung_task.h> 33 34 #define CREATE_TRACE_POINTS 35 #include <trace/events/lock.h> 36 37 #ifndef CONFIG_PREEMPT_RT 38 #include "mutex.h" 39 40 #ifdef CONFIG_DEBUG_MUTEXES 41 # define MUTEX_WARN_ON(cond) DEBUG_LOCKS_WARN_ON(cond) 42 #else 43 # define MUTEX_WARN_ON(cond) 44 #endif 45 46 static void __mutex_init_generic(struct mutex *lock) 47 { 48 atomic_long_set(&lock->owner, 0); 49 scoped_guard (raw_spinlock_init, &lock->wait_lock) { 50 lock->first_waiter = NULL; 51 } 52 #ifdef CONFIG_MUTEX_SPIN_ON_OWNER 53 osq_lock_init(&lock->osq); 54 #endif 55 debug_mutex_init(lock); 56 } 57 58 static inline struct task_struct *__owner_task(unsigned long owner) 59 { 60 return (struct task_struct *)(owner & ~MUTEX_FLAGS); 61 } 62 63 bool mutex_is_locked(struct mutex *lock) 64 { 65 return __mutex_owner(lock) != NULL; 66 } 67 EXPORT_SYMBOL(mutex_is_locked); 68 69 static inline unsigned long __owner_flags(unsigned long owner) 70 { 71 return owner & MUTEX_FLAGS; 72 } 73 74 /* Do not use the return value as a pointer directly. */ 75 unsigned long mutex_get_owner(struct mutex *lock) 76 { 77 unsigned long owner = atomic_long_read(&lock->owner); 78 79 return (unsigned long)__owner_task(owner); 80 } 81 82 /* 83 * Returns: __mutex_owner(lock) on failure or NULL on success. 84 */ 85 static inline struct task_struct *__mutex_trylock_common(struct mutex *lock, bool handoff) 86 { 87 unsigned long owner, curr = (unsigned long)current; 88 89 owner = atomic_long_read(&lock->owner); 90 for (;;) { /* must loop, can race against a flag */ 91 unsigned long flags = __owner_flags(owner); 92 unsigned long task = owner & ~MUTEX_FLAGS; 93 94 if (task) { 95 if (flags & MUTEX_FLAG_PICKUP) { 96 if (task != curr) 97 break; 98 flags &= ~MUTEX_FLAG_PICKUP; 99 } else if (handoff) { 100 if (flags & MUTEX_FLAG_HANDOFF) 101 break; 102 flags |= MUTEX_FLAG_HANDOFF; 103 } else { 104 break; 105 } 106 } else { 107 MUTEX_WARN_ON(flags & (MUTEX_FLAG_HANDOFF | MUTEX_FLAG_PICKUP)); 108 task = curr; 109 } 110 111 if (atomic_long_try_cmpxchg_acquire(&lock->owner, &owner, task | flags)) { 112 if (task == curr) 113 return NULL; 114 break; 115 } 116 } 117 118 return __owner_task(owner); 119 } 120 121 /* 122 * Trylock or set HANDOFF 123 */ 124 static inline bool __mutex_trylock_or_handoff(struct mutex *lock, bool handoff) 125 { 126 return !__mutex_trylock_common(lock, handoff); 127 } 128 129 /* 130 * Actual trylock that will work on any unlocked state. 131 */ 132 static inline bool __mutex_trylock(struct mutex *lock) 133 { 134 return !__mutex_trylock_common(lock, false); 135 } 136 137 #ifndef CONFIG_DEBUG_LOCK_ALLOC 138 /* 139 * Lockdep annotations are contained to the slow paths for simplicity. 140 * There is nothing that would stop spreading the lockdep annotations outwards 141 * except more code. 142 */ 143 void mutex_init_generic(struct mutex *lock) 144 { 145 __mutex_init_generic(lock); 146 } 147 EXPORT_SYMBOL(mutex_init_generic); 148 149 /* 150 * Optimistic trylock that only works in the uncontended case. Make sure to 151 * follow with a __mutex_trylock() before failing. 152 */ 153 static __always_inline bool __mutex_trylock_fast(struct mutex *lock) 154 __cond_acquires(true, lock) 155 { 156 unsigned long curr = (unsigned long)current; 157 unsigned long zero = 0UL; 158 159 MUTEX_WARN_ON(lock->magic != lock); 160 161 if (atomic_long_try_cmpxchg_acquire(&lock->owner, &zero, curr)) 162 return true; 163 164 return false; 165 } 166 167 static __always_inline bool __mutex_unlock_fast(struct mutex *lock) 168 __cond_releases(true, lock) 169 { 170 unsigned long curr = (unsigned long)current; 171 172 return atomic_long_try_cmpxchg_release(&lock->owner, &curr, 0UL); 173 } 174 175 #else /* !CONFIG_DEBUG_LOCK_ALLOC */ 176 177 void mutex_init_lockdep(struct mutex *lock, const char *name, struct lock_class_key *key) 178 { 179 __mutex_init_generic(lock); 180 181 /* 182 * Make sure we are not reinitializing a held lock: 183 */ 184 debug_check_no_locks_freed((void *)lock, sizeof(*lock)); 185 lockdep_init_map_wait(&lock->dep_map, name, key, 0, LD_WAIT_SLEEP); 186 } 187 EXPORT_SYMBOL(mutex_init_lockdep); 188 #endif /* !CONFIG_DEBUG_LOCK_ALLOC */ 189 190 static inline void __mutex_set_flag(struct mutex *lock, unsigned long flag) 191 { 192 atomic_long_or(flag, &lock->owner); 193 } 194 195 static inline void __mutex_clear_flag(struct mutex *lock, unsigned long flag) 196 { 197 atomic_long_andnot(flag, &lock->owner); 198 } 199 200 /* 201 * Add @waiter to a given location in the lock wait_list and set the 202 * FLAG_WAITERS flag if it's the first waiter. 203 */ 204 static void 205 __mutex_add_waiter(struct mutex *lock, struct mutex_waiter *waiter, 206 struct mutex_waiter *first) 207 __must_hold(&lock->wait_lock) 208 { 209 hung_task_set_blocker(lock, BLOCKER_TYPE_MUTEX); 210 debug_mutex_add_waiter(lock, waiter, current); 211 212 if (!first) 213 first = lock->first_waiter; 214 215 if (first) { 216 list_add_tail(&waiter->list, &first->list); 217 } else { 218 INIT_LIST_HEAD(&waiter->list); 219 lock->first_waiter = waiter; 220 __mutex_set_flag(lock, MUTEX_FLAG_WAITERS); 221 } 222 } 223 224 static void 225 __mutex_remove_waiter(struct mutex *lock, struct mutex_waiter *waiter) 226 __must_hold(&lock->wait_lock) 227 { 228 if (list_empty(&waiter->list)) { 229 __mutex_clear_flag(lock, MUTEX_FLAGS); 230 lock->first_waiter = NULL; 231 } else { 232 if (lock->first_waiter == waiter) { 233 lock->first_waiter = list_first_entry(&waiter->list, 234 struct mutex_waiter, list); 235 } 236 list_del(&waiter->list); 237 } 238 239 debug_mutex_remove_waiter(lock, waiter, current); 240 hung_task_clear_blocker(); 241 } 242 243 /* 244 * Give up ownership to a specific task, when @task = NULL, this is equivalent 245 * to a regular unlock. Sets PICKUP on a handoff, clears HANDOFF, preserves 246 * WAITERS. Provides RELEASE semantics like a regular unlock, the 247 * __mutex_trylock() provides a matching ACQUIRE semantics for the handoff. 248 */ 249 static void __mutex_handoff(struct mutex *lock, struct task_struct *task) 250 { 251 unsigned long owner = atomic_long_read(&lock->owner); 252 253 for (;;) { 254 unsigned long new; 255 256 MUTEX_WARN_ON(__owner_task(owner) != current); 257 MUTEX_WARN_ON(owner & MUTEX_FLAG_PICKUP); 258 259 new = (owner & MUTEX_FLAG_WAITERS); 260 new |= (unsigned long)task; 261 if (task) 262 new |= MUTEX_FLAG_PICKUP; 263 264 if (atomic_long_try_cmpxchg_release(&lock->owner, &owner, new)) 265 break; 266 } 267 } 268 269 #ifndef CONFIG_DEBUG_LOCK_ALLOC 270 /* 271 * We split the mutex lock/unlock logic into separate fastpath and 272 * slowpath functions, to reduce the register pressure on the fastpath. 273 * We also put the fastpath first in the kernel image, to make sure the 274 * branch is predicted by the CPU as default-untaken. 275 */ 276 static void __sched __mutex_lock_slowpath(struct mutex *lock) 277 __acquires(lock); 278 279 /** 280 * mutex_lock - acquire the mutex 281 * @lock: the mutex to be acquired 282 * 283 * Lock the mutex exclusively for this task. If the mutex is not 284 * available right now, it will sleep until it can get it. 285 * 286 * The mutex must later on be released by the same task that 287 * acquired it. Recursive locking is not allowed. The task 288 * may not exit without first unlocking the mutex. Also, kernel 289 * memory where the mutex resides must not be freed with 290 * the mutex still locked. The mutex must first be initialized 291 * (or statically defined) before it can be locked. memset()-ing 292 * the mutex to 0 is not allowed. 293 * 294 * (The CONFIG_DEBUG_MUTEXES .config option turns on debugging 295 * checks that will enforce the restrictions and will also do 296 * deadlock debugging) 297 * 298 * This function is similar to (but not equivalent to) down(). 299 */ 300 void __sched mutex_lock(struct mutex *lock) 301 { 302 might_sleep(); 303 304 if (!__mutex_trylock_fast(lock)) 305 __mutex_lock_slowpath(lock); 306 } 307 EXPORT_SYMBOL(mutex_lock); 308 #endif 309 310 #include "ww_mutex.h" 311 312 #ifdef CONFIG_MUTEX_SPIN_ON_OWNER 313 314 /* 315 * Trylock variant that returns the owning task on failure. 316 */ 317 static inline struct task_struct *__mutex_trylock_or_owner(struct mutex *lock) 318 { 319 return __mutex_trylock_common(lock, false); 320 } 321 322 static inline 323 bool ww_mutex_spin_on_owner(struct mutex *lock, struct ww_acquire_ctx *ww_ctx, 324 struct mutex_waiter *waiter) 325 { 326 struct ww_mutex *ww; 327 328 ww = container_of(lock, struct ww_mutex, base); 329 330 /* 331 * If ww->ctx is set the contents are undefined, only 332 * by acquiring wait_lock there is a guarantee that 333 * they are not invalid when reading. 334 * 335 * As such, when deadlock detection needs to be 336 * performed the optimistic spinning cannot be done. 337 * 338 * Check this in every inner iteration because we may 339 * be racing against another thread's ww_mutex_lock. 340 */ 341 if (ww_ctx->acquired > 0 && READ_ONCE(ww->ctx)) 342 return false; 343 344 /* 345 * If we aren't on the wait list yet, cancel the spin 346 * if there are waiters. We want to avoid stealing the 347 * lock from a waiter with an earlier stamp, since the 348 * other thread may already own a lock that we also 349 * need. 350 */ 351 if (!waiter && (atomic_long_read(&lock->owner) & MUTEX_FLAG_WAITERS)) 352 return false; 353 354 /* 355 * Similarly, stop spinning if we are no longer the 356 * first waiter. 357 */ 358 if (waiter && data_race(lock->first_waiter != waiter)) 359 return false; 360 361 return true; 362 } 363 364 /* 365 * Look out! "owner" is an entirely speculative pointer access and not 366 * reliable. 367 * 368 * "noinline" so that this function shows up on perf profiles. 369 */ 370 static noinline 371 bool mutex_spin_on_owner(struct mutex *lock, struct task_struct *owner, 372 struct ww_acquire_ctx *ww_ctx, struct mutex_waiter *waiter) 373 { 374 bool ret = true; 375 376 lockdep_assert_preemption_disabled(); 377 378 while (__mutex_owner(lock) == owner) { 379 /* 380 * Ensure we emit the owner->on_cpu, dereference _after_ 381 * checking lock->owner still matches owner. And we already 382 * disabled preemption which is equal to the RCU read-side 383 * crital section in optimistic spinning code. Thus the 384 * task_strcut structure won't go away during the spinning 385 * period 386 */ 387 barrier(); 388 389 /* 390 * Use vcpu_is_preempted to detect lock holder preemption issue. 391 */ 392 if (!owner_on_cpu(owner) || need_resched()) { 393 ret = false; 394 break; 395 } 396 397 if (ww_ctx && !ww_mutex_spin_on_owner(lock, ww_ctx, waiter)) { 398 ret = false; 399 break; 400 } 401 402 cpu_relax(); 403 } 404 405 return ret; 406 } 407 408 /* 409 * Initial check for entering the mutex spinning loop 410 */ 411 static inline int mutex_can_spin_on_owner(struct mutex *lock) 412 { 413 struct task_struct *owner; 414 int retval = 1; 415 416 lockdep_assert_preemption_disabled(); 417 418 if (need_resched()) 419 return 0; 420 421 /* 422 * We already disabled preemption which is equal to the RCU read-side 423 * crital section in optimistic spinning code. Thus the task_strcut 424 * structure won't go away during the spinning period. 425 */ 426 owner = __mutex_owner(lock); 427 if (owner) 428 retval = owner_on_cpu(owner); 429 430 /* 431 * If lock->owner is not set, the mutex has been released. Return true 432 * such that we'll trylock in the spin path, which is a faster option 433 * than the blocking slow path. 434 */ 435 return retval; 436 } 437 438 /* 439 * Optimistic spinning. 440 * 441 * We try to spin for acquisition when we find that the lock owner 442 * is currently running on a (different) CPU and while we don't 443 * need to reschedule. The rationale is that if the lock owner is 444 * running, it is likely to release the lock soon. 445 * 446 * The mutex spinners are queued up using MCS lock so that only one 447 * spinner can compete for the mutex. However, if mutex spinning isn't 448 * going to happen, there is no point in going through the lock/unlock 449 * overhead. 450 * 451 * Returns true when the lock was taken, otherwise false, indicating 452 * that we need to jump to the slowpath and sleep. 453 * 454 * The waiter flag is set to true if the spinner is a waiter in the wait 455 * queue. The waiter-spinner will spin on the lock directly and concurrently 456 * with the spinner at the head of the OSQ, if present, until the owner is 457 * changed to itself. 458 */ 459 static __always_inline bool 460 mutex_optimistic_spin(struct mutex *lock, struct ww_acquire_ctx *ww_ctx, 461 struct mutex_waiter *waiter) 462 { 463 if (!waiter) { 464 /* 465 * The purpose of the mutex_can_spin_on_owner() function is 466 * to eliminate the overhead of osq_lock() and osq_unlock() 467 * in case spinning isn't possible. As a waiter-spinner 468 * is not going to take OSQ lock anyway, there is no need 469 * to call mutex_can_spin_on_owner(). 470 */ 471 if (!mutex_can_spin_on_owner(lock)) 472 goto fail; 473 474 /* 475 * In order to avoid a stampede of mutex spinners trying to 476 * acquire the mutex all at once, the spinners need to take a 477 * MCS (queued) lock first before spinning on the owner field. 478 */ 479 if (!osq_lock(&lock->osq)) 480 goto fail; 481 } 482 483 for (;;) { 484 struct task_struct *owner; 485 486 /* Try to acquire the mutex... */ 487 owner = __mutex_trylock_or_owner(lock); 488 if (!owner) 489 break; 490 491 /* 492 * There's an owner, wait for it to either 493 * release the lock or go to sleep. 494 */ 495 if (!mutex_spin_on_owner(lock, owner, ww_ctx, waiter)) 496 goto fail_unlock; 497 498 /* 499 * The cpu_relax() call is a compiler barrier which forces 500 * everything in this loop to be re-loaded. We don't need 501 * memory barriers as we'll eventually observe the right 502 * values at the cost of a few extra spins. 503 */ 504 cpu_relax(); 505 } 506 507 if (!waiter) 508 osq_unlock(&lock->osq); 509 510 return true; 511 512 513 fail_unlock: 514 if (!waiter) 515 osq_unlock(&lock->osq); 516 517 fail: 518 /* 519 * If we fell out of the spin path because of need_resched(), 520 * reschedule now, before we try-lock the mutex. This avoids getting 521 * scheduled out right after we obtained the mutex. 522 */ 523 if (need_resched()) { 524 /* 525 * We _should_ have TASK_RUNNING here, but just in case 526 * we do not, make it so, otherwise we might get stuck. 527 */ 528 __set_current_state(TASK_RUNNING); 529 schedule_preempt_disabled(); 530 } 531 532 return false; 533 } 534 #else 535 static __always_inline bool 536 mutex_optimistic_spin(struct mutex *lock, struct ww_acquire_ctx *ww_ctx, 537 struct mutex_waiter *waiter) 538 { 539 return false; 540 } 541 #endif 542 543 static noinline void __sched __mutex_unlock_slowpath(struct mutex *lock, unsigned long ip) 544 __releases(lock); 545 546 /** 547 * mutex_unlock - release the mutex 548 * @lock: the mutex to be released 549 * 550 * Unlock a mutex that has been locked by this task previously. 551 * 552 * This function must not be used in interrupt context. Unlocking 553 * of a not locked mutex is not allowed. 554 * 555 * The caller must ensure that the mutex stays alive until this function has 556 * returned - mutex_unlock() can NOT directly be used to release an object such 557 * that another concurrent task can free it. 558 * Mutexes are different from spinlocks & refcounts in this aspect. 559 * 560 * This function is similar to (but not equivalent to) up(). 561 */ 562 void __sched mutex_unlock(struct mutex *lock) 563 { 564 #ifndef CONFIG_DEBUG_LOCK_ALLOC 565 if (__mutex_unlock_fast(lock)) 566 return; 567 #endif 568 __mutex_unlock_slowpath(lock, _RET_IP_); 569 } 570 EXPORT_SYMBOL(mutex_unlock); 571 572 /** 573 * ww_mutex_unlock - release the w/w mutex 574 * @lock: the mutex to be released 575 * 576 * Unlock a mutex that has been locked by this task previously with any of the 577 * ww_mutex_lock* functions (with or without an acquire context). It is 578 * forbidden to release the locks after releasing the acquire context. 579 * 580 * This function must not be used in interrupt context. Unlocking 581 * of a unlocked mutex is not allowed. 582 */ 583 void __sched ww_mutex_unlock(struct ww_mutex *lock) 584 __no_context_analysis 585 { 586 __ww_mutex_unlock(lock); 587 mutex_unlock(&lock->base); 588 } 589 EXPORT_SYMBOL(ww_mutex_unlock); 590 591 /* 592 * Lock a mutex (possibly interruptible), slowpath: 593 */ 594 static __always_inline int __sched 595 __mutex_lock_common(struct mutex *lock, unsigned int state, unsigned int subclass, 596 struct lockdep_map *nest_lock, unsigned long ip, 597 struct ww_acquire_ctx *ww_ctx, const bool use_ww_ctx) 598 __cond_acquires(0, lock) 599 { 600 DEFINE_WAKE_Q(wake_q); 601 struct mutex_waiter waiter; 602 struct ww_mutex *ww; 603 unsigned long flags; 604 int ret; 605 606 if (!use_ww_ctx) 607 ww_ctx = NULL; 608 609 might_sleep(); 610 611 MUTEX_WARN_ON(lock->magic != lock); 612 613 ww = container_of(lock, struct ww_mutex, base); 614 if (ww_ctx) { 615 if (unlikely(ww_ctx == READ_ONCE(ww->ctx))) 616 return -EALREADY; 617 618 /* 619 * Reset the wounded flag after a kill. No other process can 620 * race and wound us here since they can't have a valid owner 621 * pointer if we don't have any locks held. 622 */ 623 if (ww_ctx->acquired == 0) 624 ww_ctx->wounded = 0; 625 626 #ifdef CONFIG_DEBUG_LOCK_ALLOC 627 nest_lock = &ww_ctx->dep_map; 628 #endif 629 } 630 631 preempt_disable(); 632 mutex_acquire_nest(&lock->dep_map, subclass, 0, nest_lock, ip); 633 634 trace_contention_begin(lock, LCB_F_MUTEX | LCB_F_SPIN); 635 if (__mutex_trylock(lock) || 636 mutex_optimistic_spin(lock, ww_ctx, NULL)) { 637 /* got the lock, yay! */ 638 lock_acquired(&lock->dep_map, ip); 639 if (ww_ctx) 640 ww_mutex_set_context_fastpath(ww, ww_ctx); 641 trace_contention_end(lock, 0); 642 preempt_enable(); 643 return 0; 644 } 645 646 raw_spin_lock_irqsave(&lock->wait_lock, flags); 647 /* 648 * After waiting to acquire the wait_lock, try again. 649 */ 650 if (__mutex_trylock(lock)) { 651 if (ww_ctx) 652 __ww_mutex_check_waiters(lock, ww_ctx, &wake_q); 653 654 goto skip_wait; 655 } 656 657 debug_mutex_lock_common(lock, &waiter); 658 waiter.task = current; 659 if (use_ww_ctx) 660 waiter.ww_ctx = ww_ctx; 661 662 lock_contended(&lock->dep_map, ip); 663 664 if (!use_ww_ctx) { 665 /* add waiting tasks to the end of the waitqueue (FIFO): */ 666 __mutex_add_waiter(lock, &waiter, NULL); 667 } else { 668 /* 669 * Add in stamp order, waking up waiters that must kill 670 * themselves. 671 */ 672 ret = __ww_mutex_add_waiter(&waiter, lock, ww_ctx, &wake_q); 673 if (ret) 674 goto err_early_kill; 675 } 676 677 raw_spin_lock(¤t->blocked_lock); 678 __set_task_blocked_on(current, lock); 679 set_current_state(state); 680 trace_contention_begin(lock, LCB_F_MUTEX); 681 for (;;) { 682 bool first; 683 684 /* 685 * Once we hold wait_lock, we're serialized against 686 * mutex_unlock() handing the lock off to us, do a trylock 687 * before testing the error conditions to make sure we pick up 688 * the handoff. 689 */ 690 if (__mutex_trylock(lock)) 691 break; 692 693 raw_spin_unlock(¤t->blocked_lock); 694 /* 695 * Check for signals and kill conditions while holding 696 * wait_lock. This ensures the lock cancellation is ordered 697 * against mutex_unlock() and wake-ups do not go missing. 698 */ 699 if (signal_pending_state(state, current)) { 700 ret = -EINTR; 701 goto err; 702 } 703 704 if (ww_ctx) { 705 ret = __ww_mutex_check_kill(lock, &waiter, ww_ctx); 706 if (ret) 707 goto err; 708 } 709 710 raw_spin_unlock_irqrestore_wake(&lock->wait_lock, flags, &wake_q); 711 712 schedule_preempt_disabled(); 713 714 first = lock->first_waiter == &waiter; 715 716 raw_spin_lock_irqsave(&lock->wait_lock, flags); 717 raw_spin_lock(¤t->blocked_lock); 718 /* 719 * As we likely have been woken up by task 720 * that has cleared our blocked_on state, re-set 721 * it to the lock we are trying to acquire. 722 */ 723 __set_task_blocked_on(current, lock); 724 set_current_state(state); 725 /* 726 * Here we order against unlock; we must either see it change 727 * state back to RUNNING and fall through the next schedule(), 728 * or we must see its unlock and acquire. 729 */ 730 if (__mutex_trylock_or_handoff(lock, first)) 731 break; 732 733 if (first) { 734 bool opt_acquired; 735 736 /* 737 * mutex_optimistic_spin() can call schedule(), so 738 * we need to release these locks before calling it, 739 * and clear blocked on so we don't become unselectable 740 * to run. 741 */ 742 __clear_task_blocked_on(current, lock); 743 raw_spin_unlock(¤t->blocked_lock); 744 raw_spin_unlock_irqrestore(&lock->wait_lock, flags); 745 746 trace_contention_begin(lock, LCB_F_MUTEX | LCB_F_SPIN); 747 opt_acquired = mutex_optimistic_spin(lock, ww_ctx, &waiter); 748 749 raw_spin_lock_irqsave(&lock->wait_lock, flags); 750 raw_spin_lock(¤t->blocked_lock); 751 __set_task_blocked_on(current, lock); 752 753 if (opt_acquired) 754 break; 755 trace_contention_begin(lock, LCB_F_MUTEX); 756 } 757 } 758 __clear_task_blocked_on(current, lock); 759 __set_current_state(TASK_RUNNING); 760 raw_spin_unlock(¤t->blocked_lock); 761 762 if (ww_ctx) { 763 /* 764 * Wound-Wait; we stole the lock (!first_waiter), check the 765 * waiters as anyone might want to wound us. 766 */ 767 if (!ww_ctx->is_wait_die && lock->first_waiter != &waiter) 768 __ww_mutex_check_waiters(lock, ww_ctx, &wake_q); 769 } 770 771 __mutex_remove_waiter(lock, &waiter); 772 773 debug_mutex_free_waiter(&waiter); 774 775 skip_wait: 776 /* got the lock - cleanup and rejoice! */ 777 lock_acquired(&lock->dep_map, ip); 778 trace_contention_end(lock, 0); 779 780 if (ww_ctx) 781 ww_mutex_lock_acquired(ww, ww_ctx); 782 783 raw_spin_unlock_irqrestore_wake(&lock->wait_lock, flags, &wake_q); 784 preempt_enable(); 785 return 0; 786 787 err: 788 clear_task_blocked_on(current, lock); 789 __set_current_state(TASK_RUNNING); 790 __mutex_remove_waiter(lock, &waiter); 791 err_early_kill: 792 WARN_ON(get_task_blocked_on(current)); 793 trace_contention_end(lock, ret); 794 raw_spin_unlock_irqrestore_wake(&lock->wait_lock, flags, &wake_q); 795 debug_mutex_free_waiter(&waiter); 796 mutex_release(&lock->dep_map, ip); 797 preempt_enable(); 798 return ret; 799 } 800 801 static int __sched 802 __mutex_lock(struct mutex *lock, unsigned int state, unsigned int subclass, 803 struct lockdep_map *nest_lock, unsigned long ip) 804 __cond_acquires(0, lock) 805 { 806 return __mutex_lock_common(lock, state, subclass, nest_lock, ip, NULL, false); 807 } 808 809 static int __sched 810 __ww_mutex_lock(struct mutex *lock, unsigned int state, unsigned int subclass, 811 unsigned long ip, struct ww_acquire_ctx *ww_ctx) 812 __cond_acquires(0, lock) 813 { 814 return __mutex_lock_common(lock, state, subclass, NULL, ip, ww_ctx, true); 815 } 816 817 /** 818 * ww_mutex_trylock - tries to acquire the w/w mutex with optional acquire context 819 * @ww: mutex to lock 820 * @ww_ctx: optional w/w acquire context 821 * 822 * Trylocks a mutex with the optional acquire context; no deadlock detection is 823 * possible. Returns 1 if the mutex has been acquired successfully, 0 otherwise. 824 * 825 * Unlike ww_mutex_lock, no deadlock handling is performed. However, if a @ctx is 826 * specified, -EALREADY handling may happen in calls to ww_mutex_trylock. 827 * 828 * A mutex acquired with this function must be released with ww_mutex_unlock. 829 */ 830 int ww_mutex_trylock(struct ww_mutex *ww, struct ww_acquire_ctx *ww_ctx) 831 { 832 if (!ww_ctx) 833 return mutex_trylock(&ww->base); 834 835 MUTEX_WARN_ON(ww->base.magic != &ww->base); 836 837 /* 838 * Reset the wounded flag after a kill. No other process can 839 * race and wound us here, since they can't have a valid owner 840 * pointer if we don't have any locks held. 841 */ 842 if (ww_ctx->acquired == 0) 843 ww_ctx->wounded = 0; 844 845 if (__mutex_trylock(&ww->base)) { 846 ww_mutex_set_context_fastpath(ww, ww_ctx); 847 mutex_acquire_nest(&ww->base.dep_map, 0, 1, &ww_ctx->dep_map, _RET_IP_); 848 return 1; 849 } 850 851 return 0; 852 } 853 EXPORT_SYMBOL(ww_mutex_trylock); 854 855 #ifdef CONFIG_DEBUG_LOCK_ALLOC 856 void __sched 857 mutex_lock_nested(struct mutex *lock, unsigned int subclass) 858 { 859 __mutex_lock(lock, TASK_UNINTERRUPTIBLE, subclass, NULL, _RET_IP_); 860 __acquire(lock); 861 } 862 863 EXPORT_SYMBOL_GPL(mutex_lock_nested); 864 865 void __sched 866 _mutex_lock_nest_lock(struct mutex *lock, struct lockdep_map *nest) 867 { 868 __mutex_lock(lock, TASK_UNINTERRUPTIBLE, 0, nest, _RET_IP_); 869 __acquire(lock); 870 } 871 EXPORT_SYMBOL_GPL(_mutex_lock_nest_lock); 872 873 int __sched 874 _mutex_lock_killable(struct mutex *lock, unsigned int subclass, 875 struct lockdep_map *nest) 876 { 877 return __mutex_lock(lock, TASK_KILLABLE, subclass, nest, _RET_IP_); 878 } 879 EXPORT_SYMBOL_GPL(_mutex_lock_killable); 880 881 int __sched 882 mutex_lock_interruptible_nested(struct mutex *lock, unsigned int subclass) 883 { 884 return __mutex_lock(lock, TASK_INTERRUPTIBLE, subclass, NULL, _RET_IP_); 885 } 886 EXPORT_SYMBOL_GPL(mutex_lock_interruptible_nested); 887 888 void __sched 889 mutex_lock_io_nested(struct mutex *lock, unsigned int subclass) 890 { 891 int token; 892 893 might_sleep(); 894 895 token = io_schedule_prepare(); 896 __mutex_lock_common(lock, TASK_UNINTERRUPTIBLE, 897 subclass, NULL, _RET_IP_, NULL, 0); 898 __acquire(lock); 899 io_schedule_finish(token); 900 } 901 EXPORT_SYMBOL_GPL(mutex_lock_io_nested); 902 903 static inline int 904 ww_mutex_deadlock_injection(struct ww_mutex *lock, struct ww_acquire_ctx *ctx) 905 __cond_releases(nonzero, lock) 906 { 907 #ifdef CONFIG_DEBUG_WW_MUTEX_SLOWPATH 908 unsigned tmp; 909 910 if (ctx->deadlock_inject_countdown-- == 0) { 911 tmp = ctx->deadlock_inject_interval; 912 if (tmp > UINT_MAX/4) 913 tmp = UINT_MAX; 914 else 915 tmp = tmp*2 + tmp + tmp/2; 916 917 ctx->deadlock_inject_interval = tmp; 918 ctx->deadlock_inject_countdown = tmp; 919 ctx->contending_lock = lock; 920 921 ww_mutex_unlock(lock); 922 923 return -EDEADLK; 924 } 925 #endif 926 927 return 0; 928 } 929 930 int __sched 931 ww_mutex_lock(struct ww_mutex *lock, struct ww_acquire_ctx *ctx) 932 { 933 int ret; 934 935 might_sleep(); 936 ret = __ww_mutex_lock(&lock->base, TASK_UNINTERRUPTIBLE, 937 0, _RET_IP_, ctx); 938 if (!ret && ctx && ctx->acquired > 1) 939 return ww_mutex_deadlock_injection(lock, ctx); 940 941 return ret; 942 } 943 EXPORT_SYMBOL_GPL(ww_mutex_lock); 944 945 int __sched 946 ww_mutex_lock_interruptible(struct ww_mutex *lock, struct ww_acquire_ctx *ctx) 947 { 948 int ret; 949 950 might_sleep(); 951 ret = __ww_mutex_lock(&lock->base, TASK_INTERRUPTIBLE, 952 0, _RET_IP_, ctx); 953 954 if (!ret && ctx && ctx->acquired > 1) 955 return ww_mutex_deadlock_injection(lock, ctx); 956 957 return ret; 958 } 959 EXPORT_SYMBOL_GPL(ww_mutex_lock_interruptible); 960 961 #endif 962 963 /* 964 * Release the lock, slowpath: 965 */ 966 static noinline void __sched __mutex_unlock_slowpath(struct mutex *lock, unsigned long ip) 967 __releases(lock) 968 { 969 struct task_struct *next = NULL; 970 struct mutex_waiter *waiter; 971 DEFINE_WAKE_Q(wake_q); 972 unsigned long owner; 973 unsigned long flags; 974 975 mutex_release(&lock->dep_map, ip); 976 __release(lock); 977 978 /* 979 * Release the lock before (potentially) taking the spinlock such that 980 * other contenders can get on with things ASAP. 981 * 982 * Except when HANDOFF, in that case we must not clear the owner field, 983 * but instead set it to the top waiter. 984 */ 985 owner = atomic_long_read(&lock->owner); 986 for (;;) { 987 MUTEX_WARN_ON(__owner_task(owner) != current); 988 MUTEX_WARN_ON(owner & MUTEX_FLAG_PICKUP); 989 990 if (owner & MUTEX_FLAG_HANDOFF) 991 break; 992 993 if (atomic_long_try_cmpxchg_release(&lock->owner, &owner, __owner_flags(owner))) { 994 if (owner & MUTEX_FLAG_WAITERS) 995 break; 996 997 return; 998 } 999 } 1000 1001 raw_spin_lock_irqsave(&lock->wait_lock, flags); 1002 debug_mutex_unlock(lock); 1003 waiter = lock->first_waiter; 1004 if (waiter) { 1005 next = waiter->task; 1006 1007 debug_mutex_wake_waiter(lock, waiter); 1008 set_task_blocked_on_waking(next, lock); 1009 wake_q_add(&wake_q, next); 1010 } 1011 1012 if (owner & MUTEX_FLAG_HANDOFF) 1013 __mutex_handoff(lock, next); 1014 1015 raw_spin_unlock_irqrestore_wake(&lock->wait_lock, flags, &wake_q); 1016 } 1017 1018 #ifndef CONFIG_DEBUG_LOCK_ALLOC 1019 /* 1020 * Here come the less common (and hence less performance-critical) APIs: 1021 * mutex_lock_interruptible() and mutex_trylock(). 1022 */ 1023 static noinline int __sched 1024 __mutex_lock_killable_slowpath(struct mutex *lock); 1025 1026 static noinline int __sched 1027 __mutex_lock_interruptible_slowpath(struct mutex *lock); 1028 1029 /** 1030 * mutex_lock_interruptible() - Acquire the mutex, interruptible by signals. 1031 * @lock: The mutex to be acquired. 1032 * 1033 * Lock the mutex like mutex_lock(). If a signal is delivered while the 1034 * process is sleeping, this function will return without acquiring the 1035 * mutex. 1036 * 1037 * Context: Process context. 1038 * Return: 0 if the lock was successfully acquired or %-EINTR if a 1039 * signal arrived. 1040 */ 1041 int __sched mutex_lock_interruptible(struct mutex *lock) 1042 { 1043 might_sleep(); 1044 1045 if (__mutex_trylock_fast(lock)) 1046 return 0; 1047 1048 return __mutex_lock_interruptible_slowpath(lock); 1049 } 1050 1051 EXPORT_SYMBOL(mutex_lock_interruptible); 1052 1053 /** 1054 * mutex_lock_killable() - Acquire the mutex, interruptible by fatal signals. 1055 * @lock: The mutex to be acquired. 1056 * 1057 * Lock the mutex like mutex_lock(). If a signal which will be fatal to 1058 * the current process is delivered while the process is sleeping, this 1059 * function will return without acquiring the mutex. 1060 * 1061 * Context: Process context. 1062 * Return: 0 if the lock was successfully acquired or %-EINTR if a 1063 * fatal signal arrived. 1064 */ 1065 int __sched mutex_lock_killable(struct mutex *lock) 1066 { 1067 might_sleep(); 1068 1069 if (__mutex_trylock_fast(lock)) 1070 return 0; 1071 1072 return __mutex_lock_killable_slowpath(lock); 1073 } 1074 EXPORT_SYMBOL(mutex_lock_killable); 1075 1076 /** 1077 * mutex_lock_io() - Acquire the mutex and mark the process as waiting for I/O 1078 * @lock: The mutex to be acquired. 1079 * 1080 * Lock the mutex like mutex_lock(). While the task is waiting for this 1081 * mutex, it will be accounted as being in the IO wait state by the 1082 * scheduler. 1083 * 1084 * Context: Process context. 1085 */ 1086 void __sched mutex_lock_io(struct mutex *lock) 1087 { 1088 int token; 1089 1090 token = io_schedule_prepare(); 1091 mutex_lock(lock); 1092 io_schedule_finish(token); 1093 } 1094 EXPORT_SYMBOL_GPL(mutex_lock_io); 1095 1096 static noinline void __sched 1097 __mutex_lock_slowpath(struct mutex *lock) 1098 __acquires(lock) 1099 { 1100 __mutex_lock(lock, TASK_UNINTERRUPTIBLE, 0, NULL, _RET_IP_); 1101 __acquire(lock); 1102 } 1103 1104 static noinline int __sched 1105 __mutex_lock_killable_slowpath(struct mutex *lock) 1106 __cond_acquires(0, lock) 1107 { 1108 return __mutex_lock(lock, TASK_KILLABLE, 0, NULL, _RET_IP_); 1109 } 1110 1111 static noinline int __sched 1112 __mutex_lock_interruptible_slowpath(struct mutex *lock) 1113 __cond_acquires(0, lock) 1114 { 1115 return __mutex_lock(lock, TASK_INTERRUPTIBLE, 0, NULL, _RET_IP_); 1116 } 1117 1118 static noinline int __sched 1119 __ww_mutex_lock_slowpath(struct ww_mutex *lock, struct ww_acquire_ctx *ctx) 1120 __cond_acquires(0, lock) 1121 { 1122 return __ww_mutex_lock(&lock->base, TASK_UNINTERRUPTIBLE, 0, 1123 _RET_IP_, ctx); 1124 } 1125 1126 static noinline int __sched 1127 __ww_mutex_lock_interruptible_slowpath(struct ww_mutex *lock, 1128 struct ww_acquire_ctx *ctx) 1129 __cond_acquires(0, lock) 1130 { 1131 return __ww_mutex_lock(&lock->base, TASK_INTERRUPTIBLE, 0, 1132 _RET_IP_, ctx); 1133 } 1134 1135 #endif 1136 1137 #ifndef CONFIG_DEBUG_LOCK_ALLOC 1138 /** 1139 * mutex_trylock - try to acquire the mutex, without waiting 1140 * @lock: the mutex to be acquired 1141 * 1142 * Try to acquire the mutex atomically. Returns 1 if the mutex 1143 * has been acquired successfully, and 0 on contention. 1144 * 1145 * NOTE: this function follows the spin_trylock() convention, so 1146 * it is negated from the down_trylock() return values! Be careful 1147 * about this when converting semaphore users to mutexes. 1148 * 1149 * This function must not be used in interrupt context. The 1150 * mutex must be released by the same task that acquired it. 1151 */ 1152 int __sched mutex_trylock(struct mutex *lock) 1153 { 1154 MUTEX_WARN_ON(lock->magic != lock); 1155 return __mutex_trylock(lock); 1156 } 1157 EXPORT_SYMBOL(mutex_trylock); 1158 #else 1159 int __sched _mutex_trylock_nest_lock(struct mutex *lock, struct lockdep_map *nest_lock) 1160 { 1161 bool locked; 1162 1163 MUTEX_WARN_ON(lock->magic != lock); 1164 locked = __mutex_trylock(lock); 1165 if (locked) 1166 mutex_acquire_nest(&lock->dep_map, 0, 1, nest_lock, _RET_IP_); 1167 1168 return locked; 1169 } 1170 EXPORT_SYMBOL(_mutex_trylock_nest_lock); 1171 #endif 1172 1173 #ifndef CONFIG_DEBUG_LOCK_ALLOC 1174 int __sched 1175 ww_mutex_lock(struct ww_mutex *lock, struct ww_acquire_ctx *ctx) 1176 { 1177 might_sleep(); 1178 1179 if (__mutex_trylock_fast(&lock->base)) { 1180 if (ctx) 1181 ww_mutex_set_context_fastpath(lock, ctx); 1182 return 0; 1183 } 1184 1185 return __ww_mutex_lock_slowpath(lock, ctx); 1186 } 1187 EXPORT_SYMBOL(ww_mutex_lock); 1188 1189 int __sched 1190 ww_mutex_lock_interruptible(struct ww_mutex *lock, struct ww_acquire_ctx *ctx) 1191 { 1192 might_sleep(); 1193 1194 if (__mutex_trylock_fast(&lock->base)) { 1195 if (ctx) 1196 ww_mutex_set_context_fastpath(lock, ctx); 1197 return 0; 1198 } 1199 1200 return __ww_mutex_lock_interruptible_slowpath(lock, ctx); 1201 } 1202 EXPORT_SYMBOL(ww_mutex_lock_interruptible); 1203 1204 #endif /* !CONFIG_DEBUG_LOCK_ALLOC */ 1205 #endif /* !CONFIG_PREEMPT_RT */ 1206 1207 EXPORT_TRACEPOINT_SYMBOL_GPL(contention_begin); 1208 EXPORT_TRACEPOINT_SYMBOL_GPL(contention_end); 1209 1210 /** 1211 * atomic_dec_and_mutex_lock - return holding mutex if we dec to 0 1212 * @cnt: the atomic which we are to dec 1213 * @lock: the mutex to return holding if we dec to 0 1214 * 1215 * return true and hold lock if we dec to 0, return false otherwise 1216 */ 1217 int atomic_dec_and_mutex_lock(atomic_t *cnt, struct mutex *lock) 1218 { 1219 /* dec if we can't possibly hit 0 */ 1220 if (atomic_add_unless(cnt, -1, 1)) 1221 return 0; 1222 /* we might hit 0, so take the lock */ 1223 mutex_lock(lock); 1224 if (!atomic_dec_and_test(cnt)) { 1225 /* when we actually did the dec, we didn't hit 0 */ 1226 mutex_unlock(lock); 1227 return 0; 1228 } 1229 /* we hit 0, and we hold the lock */ 1230 return 1; 1231 } 1232 EXPORT_SYMBOL(atomic_dec_and_mutex_lock); 1233