]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_lock.c
Merge ^/vendor/compiler-rt/dist up to its last change, and resolve conflicts.
[FreeBSD/FreeBSD.git] / sys / kern / kern_lock.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2008 Attilio Rao <attilio@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice(s), this list of conditions and the following disclaimer as
12  *    the first lines of this file unmodified other than the possible
13  *    addition of one or more copyright notices.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice(s), this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
28  * DAMAGE.
29  */
30
31 #include "opt_ddb.h"
32 #include "opt_hwpmc_hooks.h"
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 #include <sys/param.h>
38 #include <sys/kdb.h>
39 #include <sys/ktr.h>
40 #include <sys/lock.h>
41 #include <sys/lock_profile.h>
42 #include <sys/lockmgr.h>
43 #include <sys/lockstat.h>
44 #include <sys/mutex.h>
45 #include <sys/proc.h>
46 #include <sys/sleepqueue.h>
47 #ifdef DEBUG_LOCKS
48 #include <sys/stack.h>
49 #endif
50 #include <sys/sysctl.h>
51 #include <sys/systm.h>
52
53 #include <machine/cpu.h>
54
55 #ifdef DDB
56 #include <ddb/ddb.h>
57 #endif
58
59 #ifdef HWPMC_HOOKS
60 #include <sys/pmckern.h>
61 PMC_SOFT_DECLARE( , , lock, failed);
62 #endif
63
64 CTASSERT(LK_UNLOCKED == (LK_UNLOCKED &
65     ~(LK_ALL_WAITERS | LK_EXCLUSIVE_SPINNERS)));
66
67 #define SQ_EXCLUSIVE_QUEUE      0
68 #define SQ_SHARED_QUEUE         1
69
70 #ifndef INVARIANTS
71 #define _lockmgr_assert(lk, what, file, line)
72 #endif
73
74 #define TD_SLOCKS_INC(td)       ((td)->td_lk_slocks++)
75 #define TD_SLOCKS_DEC(td)       ((td)->td_lk_slocks--)
76
77 #ifndef DEBUG_LOCKS
78 #define STACK_PRINT(lk)
79 #define STACK_SAVE(lk)
80 #define STACK_ZERO(lk)
81 #else
82 #define STACK_PRINT(lk) stack_print_ddb(&(lk)->lk_stack)
83 #define STACK_SAVE(lk)  stack_save(&(lk)->lk_stack)
84 #define STACK_ZERO(lk)  stack_zero(&(lk)->lk_stack)
85 #endif
86
87 #define LOCK_LOG2(lk, string, arg1, arg2)                               \
88         if (LOCK_LOG_TEST(&(lk)->lock_object, 0))                       \
89                 CTR2(KTR_LOCK, (string), (arg1), (arg2))
90 #define LOCK_LOG3(lk, string, arg1, arg2, arg3)                         \
91         if (LOCK_LOG_TEST(&(lk)->lock_object, 0))                       \
92                 CTR3(KTR_LOCK, (string), (arg1), (arg2), (arg3))
93
94 #define GIANT_DECLARE                                                   \
95         int _i = 0;                                                     \
96         WITNESS_SAVE_DECL(Giant)
97 #define GIANT_RESTORE() do {                                            \
98         if (__predict_false(_i > 0)) {                                  \
99                 while (_i--)                                            \
100                         mtx_lock(&Giant);                               \
101                 WITNESS_RESTORE(&Giant.lock_object, Giant);             \
102         }                                                               \
103 } while (0)
104 #define GIANT_SAVE() do {                                               \
105         if (__predict_false(mtx_owned(&Giant))) {                       \
106                 WITNESS_SAVE(&Giant.lock_object, Giant);                \
107                 while (mtx_owned(&Giant)) {                             \
108                         _i++;                                           \
109                         mtx_unlock(&Giant);                             \
110                 }                                                       \
111         }                                                               \
112 } while (0)
113
114 static bool __always_inline
115 LK_CAN_SHARE(uintptr_t x, int flags, bool fp)
116 {
117
118         if ((x & (LK_SHARE | LK_EXCLUSIVE_WAITERS | LK_EXCLUSIVE_SPINNERS)) ==
119             LK_SHARE)
120                 return (true);
121         if (fp || (!(x & LK_SHARE)))
122                 return (false);
123         if ((curthread->td_lk_slocks != 0 && !(flags & LK_NODDLKTREAT)) ||
124             (curthread->td_pflags & TDP_DEADLKTREAT))
125                 return (true);
126         return (false);
127 }
128
129 #define LK_TRYOP(x)                                                     \
130         ((x) & LK_NOWAIT)
131
132 #define LK_CAN_WITNESS(x)                                               \
133         (((x) & LK_NOWITNESS) == 0 && !LK_TRYOP(x))
134 #define LK_TRYWIT(x)                                                    \
135         (LK_TRYOP(x) ? LOP_TRYLOCK : 0)
136
137 #define lockmgr_disowned(lk)                                            \
138         (((lk)->lk_lock & ~(LK_FLAGMASK & ~LK_SHARE)) == LK_KERNPROC)
139
140 #define lockmgr_xlocked_v(v)                                            \
141         (((v) & ~(LK_FLAGMASK & ~LK_SHARE)) == (uintptr_t)curthread)
142
143 #define lockmgr_xlocked(lk) lockmgr_xlocked_v((lk)->lk_lock)
144
145 static void     assert_lockmgr(const struct lock_object *lock, int how);
146 #ifdef DDB
147 static void     db_show_lockmgr(const struct lock_object *lock);
148 #endif
149 static void     lock_lockmgr(struct lock_object *lock, uintptr_t how);
150 #ifdef KDTRACE_HOOKS
151 static int      owner_lockmgr(const struct lock_object *lock,
152                     struct thread **owner);
153 #endif
154 static uintptr_t unlock_lockmgr(struct lock_object *lock);
155
156 struct lock_class lock_class_lockmgr = {
157         .lc_name = "lockmgr",
158         .lc_flags = LC_RECURSABLE | LC_SLEEPABLE | LC_SLEEPLOCK | LC_UPGRADABLE,
159         .lc_assert = assert_lockmgr,
160 #ifdef DDB
161         .lc_ddb_show = db_show_lockmgr,
162 #endif
163         .lc_lock = lock_lockmgr,
164         .lc_unlock = unlock_lockmgr,
165 #ifdef KDTRACE_HOOKS
166         .lc_owner = owner_lockmgr,
167 #endif
168 };
169
170 struct lockmgr_wait {
171         const char *iwmesg;
172         int ipri;
173         int itimo;
174 };
175
176 static bool __always_inline lockmgr_slock_try(struct lock *lk, uintptr_t *xp,
177     int flags, bool fp);
178 static bool __always_inline lockmgr_sunlock_try(struct lock *lk, uintptr_t *xp);
179
180 static void
181 lockmgr_exit(u_int flags, struct lock_object *ilk, int wakeup_swapper)
182 {
183         struct lock_class *class;
184
185         if (flags & LK_INTERLOCK) {
186                 class = LOCK_CLASS(ilk);
187                 class->lc_unlock(ilk);
188         }
189
190         if (__predict_false(wakeup_swapper))
191                 kick_proc0();
192 }
193
194 static void
195 lockmgr_note_shared_acquire(struct lock *lk, int contested,
196     uint64_t waittime, const char *file, int line, int flags)
197 {
198
199         LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(lockmgr__acquire, lk, contested,
200             waittime, file, line, LOCKSTAT_READER);
201         LOCK_LOG_LOCK("SLOCK", &lk->lock_object, 0, 0, file, line);
202         WITNESS_LOCK(&lk->lock_object, LK_TRYWIT(flags), file, line);
203         TD_LOCKS_INC(curthread);
204         TD_SLOCKS_INC(curthread);
205         STACK_SAVE(lk);
206 }
207
208 static void
209 lockmgr_note_shared_release(struct lock *lk, const char *file, int line)
210 {
211
212         LOCKSTAT_PROFILE_RELEASE_RWLOCK(lockmgr__release, lk, LOCKSTAT_READER);
213         WITNESS_UNLOCK(&lk->lock_object, 0, file, line);
214         LOCK_LOG_LOCK("SUNLOCK", &lk->lock_object, 0, 0, file, line);
215         TD_LOCKS_DEC(curthread);
216         TD_SLOCKS_DEC(curthread);
217 }
218
219 static void
220 lockmgr_note_exclusive_acquire(struct lock *lk, int contested,
221     uint64_t waittime, const char *file, int line, int flags)
222 {
223
224         LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(lockmgr__acquire, lk, contested,
225             waittime, file, line, LOCKSTAT_WRITER);
226         LOCK_LOG_LOCK("XLOCK", &lk->lock_object, 0, lk->lk_recurse, file, line);
227         WITNESS_LOCK(&lk->lock_object, LOP_EXCLUSIVE | LK_TRYWIT(flags), file,
228             line);
229         TD_LOCKS_INC(curthread);
230         STACK_SAVE(lk);
231 }
232
233 static void
234 lockmgr_note_exclusive_release(struct lock *lk, const char *file, int line)
235 {
236
237         LOCKSTAT_PROFILE_RELEASE_RWLOCK(lockmgr__release, lk, LOCKSTAT_WRITER);
238         LOCK_LOG_LOCK("XUNLOCK", &lk->lock_object, 0, lk->lk_recurse, file,
239             line);
240         WITNESS_UNLOCK(&lk->lock_object, LOP_EXCLUSIVE, file, line);
241         TD_LOCKS_DEC(curthread);
242 }
243
244 static __inline struct thread *
245 lockmgr_xholder(const struct lock *lk)
246 {
247         uintptr_t x;
248
249         x = lk->lk_lock;
250         return ((x & LK_SHARE) ? NULL : (struct thread *)LK_HOLDER(x));
251 }
252
253 /*
254  * It assumes sleepq_lock held and returns with this one unheld.
255  * It also assumes the generic interlock is sane and previously checked.
256  * If LK_INTERLOCK is specified the interlock is not reacquired after the
257  * sleep.
258  */
259 static __inline int
260 sleeplk(struct lock *lk, u_int flags, struct lock_object *ilk,
261     const char *wmesg, int pri, int timo, int queue)
262 {
263         GIANT_DECLARE;
264         struct lock_class *class;
265         int catch, error;
266
267         class = (flags & LK_INTERLOCK) ? LOCK_CLASS(ilk) : NULL;
268         catch = pri & PCATCH;
269         pri &= PRIMASK;
270         error = 0;
271
272         LOCK_LOG3(lk, "%s: %p blocking on the %s sleepqueue", __func__, lk,
273             (queue == SQ_EXCLUSIVE_QUEUE) ? "exclusive" : "shared");
274
275         if (flags & LK_INTERLOCK)
276                 class->lc_unlock(ilk);
277         if (queue == SQ_EXCLUSIVE_QUEUE && (flags & LK_SLEEPFAIL) != 0)
278                 lk->lk_exslpfail++;
279         GIANT_SAVE();
280         sleepq_add(&lk->lock_object, NULL, wmesg, SLEEPQ_LK | (catch ?
281             SLEEPQ_INTERRUPTIBLE : 0), queue);
282         if ((flags & LK_TIMELOCK) && timo)
283                 sleepq_set_timeout(&lk->lock_object, timo);
284
285         /*
286          * Decisional switch for real sleeping.
287          */
288         if ((flags & LK_TIMELOCK) && timo && catch)
289                 error = sleepq_timedwait_sig(&lk->lock_object, pri);
290         else if ((flags & LK_TIMELOCK) && timo)
291                 error = sleepq_timedwait(&lk->lock_object, pri);
292         else if (catch)
293                 error = sleepq_wait_sig(&lk->lock_object, pri);
294         else
295                 sleepq_wait(&lk->lock_object, pri);
296         GIANT_RESTORE();
297         if ((flags & LK_SLEEPFAIL) && error == 0)
298                 error = ENOLCK;
299
300         return (error);
301 }
302
303 static __inline int
304 wakeupshlk(struct lock *lk, const char *file, int line)
305 {
306         uintptr_t v, x, orig_x;
307         u_int realexslp;
308         int queue, wakeup_swapper;
309
310         wakeup_swapper = 0;
311         for (;;) {
312                 x = lk->lk_lock;
313                 if (lockmgr_sunlock_try(lk, &x))
314                         break;
315
316                 /*
317                  * We should have a sharer with waiters, so enter the hard
318                  * path in order to handle wakeups correctly.
319                  */
320                 sleepq_lock(&lk->lock_object);
321                 orig_x = lk->lk_lock;
322 retry_sleepq:
323                 x = orig_x & (LK_ALL_WAITERS | LK_EXCLUSIVE_SPINNERS);
324                 v = LK_UNLOCKED;
325
326                 /*
327                  * If the lock has exclusive waiters, give them preference in
328                  * order to avoid deadlock with shared runners up.
329                  * If interruptible sleeps left the exclusive queue empty
330                  * avoid a starvation for the threads sleeping on the shared
331                  * queue by giving them precedence and cleaning up the
332                  * exclusive waiters bit anyway.
333                  * Please note that lk_exslpfail count may be lying about
334                  * the real number of waiters with the LK_SLEEPFAIL flag on
335                  * because they may be used in conjunction with interruptible
336                  * sleeps so lk_exslpfail might be considered an 'upper limit'
337                  * bound, including the edge cases.
338                  */
339                 realexslp = sleepq_sleepcnt(&lk->lock_object,
340                     SQ_EXCLUSIVE_QUEUE);
341                 if ((x & LK_EXCLUSIVE_WAITERS) != 0 && realexslp != 0) {
342                         if (lk->lk_exslpfail < realexslp) {
343                                 lk->lk_exslpfail = 0;
344                                 queue = SQ_EXCLUSIVE_QUEUE;
345                                 v |= (x & LK_SHARED_WAITERS);
346                         } else {
347                                 lk->lk_exslpfail = 0;
348                                 LOCK_LOG2(lk,
349                                     "%s: %p has only LK_SLEEPFAIL sleepers",
350                                     __func__, lk);
351                                 LOCK_LOG2(lk,
352                             "%s: %p waking up threads on the exclusive queue",
353                                     __func__, lk);
354                                 wakeup_swapper =
355                                     sleepq_broadcast(&lk->lock_object,
356                                     SLEEPQ_LK, 0, SQ_EXCLUSIVE_QUEUE);
357                                 queue = SQ_SHARED_QUEUE;
358                         }
359                                 
360                 } else {
361
362                         /*
363                          * Exclusive waiters sleeping with LK_SLEEPFAIL on
364                          * and using interruptible sleeps/timeout may have
365                          * left spourious lk_exslpfail counts on, so clean
366                          * it up anyway.
367                          */
368                         lk->lk_exslpfail = 0;
369                         queue = SQ_SHARED_QUEUE;
370                 }
371
372                 if (lockmgr_sunlock_try(lk, &orig_x)) {
373                         sleepq_release(&lk->lock_object);
374                         break;
375                 }
376
377                 x |= LK_SHARERS_LOCK(1);
378                 if (!atomic_fcmpset_rel_ptr(&lk->lk_lock, &x, v)) {
379                         orig_x = x;
380                         goto retry_sleepq;
381                 }
382                 LOCK_LOG3(lk, "%s: %p waking up threads on the %s queue",
383                     __func__, lk, queue == SQ_SHARED_QUEUE ? "shared" :
384                     "exclusive");
385                 wakeup_swapper |= sleepq_broadcast(&lk->lock_object, SLEEPQ_LK,
386                     0, queue);
387                 sleepq_release(&lk->lock_object);
388                 break;
389         }
390
391         lockmgr_note_shared_release(lk, file, line);
392         return (wakeup_swapper);
393 }
394
395 static void
396 assert_lockmgr(const struct lock_object *lock, int what)
397 {
398
399         panic("lockmgr locks do not support assertions");
400 }
401
402 static void
403 lock_lockmgr(struct lock_object *lock, uintptr_t how)
404 {
405
406         panic("lockmgr locks do not support sleep interlocking");
407 }
408
409 static uintptr_t
410 unlock_lockmgr(struct lock_object *lock)
411 {
412
413         panic("lockmgr locks do not support sleep interlocking");
414 }
415
416 #ifdef KDTRACE_HOOKS
417 static int
418 owner_lockmgr(const struct lock_object *lock, struct thread **owner)
419 {
420
421         panic("lockmgr locks do not support owner inquiring");
422 }
423 #endif
424
425 void
426 lockinit(struct lock *lk, int pri, const char *wmesg, int timo, int flags)
427 {
428         int iflags;
429
430         MPASS((flags & ~LK_INIT_MASK) == 0);
431         ASSERT_ATOMIC_LOAD_PTR(lk->lk_lock,
432             ("%s: lockmgr not aligned for %s: %p", __func__, wmesg,
433             &lk->lk_lock));
434
435         iflags = LO_SLEEPABLE | LO_UPGRADABLE;
436         if (flags & LK_CANRECURSE)
437                 iflags |= LO_RECURSABLE;
438         if ((flags & LK_NODUP) == 0)
439                 iflags |= LO_DUPOK;
440         if (flags & LK_NOPROFILE)
441                 iflags |= LO_NOPROFILE;
442         if ((flags & LK_NOWITNESS) == 0)
443                 iflags |= LO_WITNESS;
444         if (flags & LK_QUIET)
445                 iflags |= LO_QUIET;
446         if (flags & LK_IS_VNODE)
447                 iflags |= LO_IS_VNODE;
448         if (flags & LK_NEW)
449                 iflags |= LO_NEW;
450         iflags |= flags & LK_NOSHARE;
451
452         lock_init(&lk->lock_object, &lock_class_lockmgr, wmesg, NULL, iflags);
453         lk->lk_lock = LK_UNLOCKED;
454         lk->lk_recurse = 0;
455         lk->lk_exslpfail = 0;
456         lk->lk_timo = timo;
457         lk->lk_pri = pri;
458         STACK_ZERO(lk);
459 }
460
461 /*
462  * XXX: Gross hacks to manipulate external lock flags after
463  * initialization.  Used for certain vnode and buf locks.
464  */
465 void
466 lockallowshare(struct lock *lk)
467 {
468
469         lockmgr_assert(lk, KA_XLOCKED);
470         lk->lock_object.lo_flags &= ~LK_NOSHARE;
471 }
472
473 void
474 lockdisableshare(struct lock *lk)
475 {
476
477         lockmgr_assert(lk, KA_XLOCKED);
478         lk->lock_object.lo_flags |= LK_NOSHARE;
479 }
480
481 void
482 lockallowrecurse(struct lock *lk)
483 {
484
485         lockmgr_assert(lk, KA_XLOCKED);
486         lk->lock_object.lo_flags |= LO_RECURSABLE;
487 }
488
489 void
490 lockdisablerecurse(struct lock *lk)
491 {
492
493         lockmgr_assert(lk, KA_XLOCKED);
494         lk->lock_object.lo_flags &= ~LO_RECURSABLE;
495 }
496
497 void
498 lockdestroy(struct lock *lk)
499 {
500
501         KASSERT(lk->lk_lock == LK_UNLOCKED, ("lockmgr still held"));
502         KASSERT(lk->lk_recurse == 0, ("lockmgr still recursed"));
503         KASSERT(lk->lk_exslpfail == 0, ("lockmgr still exclusive waiters"));
504         lock_destroy(&lk->lock_object);
505 }
506
507 static bool __always_inline
508 lockmgr_slock_try(struct lock *lk, uintptr_t *xp, int flags, bool fp)
509 {
510
511         /*
512          * If no other thread has an exclusive lock, or
513          * no exclusive waiter is present, bump the count of
514          * sharers.  Since we have to preserve the state of
515          * waiters, if we fail to acquire the shared lock
516          * loop back and retry.
517          */
518         *xp = lk->lk_lock;
519         while (LK_CAN_SHARE(*xp, flags, fp)) {
520                 if (atomic_fcmpset_acq_ptr(&lk->lk_lock, xp,
521                     *xp + LK_ONE_SHARER)) {
522                         return (true);
523                 }
524         }
525         return (false);
526 }
527
528 static bool __always_inline
529 lockmgr_sunlock_try(struct lock *lk, uintptr_t *xp)
530 {
531
532         for (;;) {
533                 if (LK_SHARERS(*xp) > 1 || !(*xp & LK_ALL_WAITERS)) {
534                         if (atomic_fcmpset_rel_ptr(&lk->lk_lock, xp,
535                             *xp - LK_ONE_SHARER))
536                                 return (true);
537                         continue;
538                 }
539                 break;
540         }
541         return (false);
542 }
543
544 static __noinline int
545 lockmgr_slock_hard(struct lock *lk, u_int flags, struct lock_object *ilk,
546     const char *file, int line, struct lockmgr_wait *lwa)
547 {
548         uintptr_t tid, x;
549         int error = 0;
550         const char *iwmesg;
551         int ipri, itimo;
552
553 #ifdef KDTRACE_HOOKS
554         uint64_t sleep_time = 0;
555 #endif
556 #ifdef LOCK_PROFILING
557         uint64_t waittime = 0;
558         int contested = 0;
559 #endif
560
561         if (KERNEL_PANICKED())
562                 goto out;
563
564         tid = (uintptr_t)curthread;
565
566         if (LK_CAN_WITNESS(flags))
567                 WITNESS_CHECKORDER(&lk->lock_object, LOP_NEWORDER,
568                     file, line, flags & LK_INTERLOCK ? ilk : NULL);
569         for (;;) {
570                 if (lockmgr_slock_try(lk, &x, flags, false))
571                         break;
572 #ifdef HWPMC_HOOKS
573                 PMC_SOFT_CALL( , , lock, failed);
574 #endif
575                 lock_profile_obtain_lock_failed(&lk->lock_object,
576                     &contested, &waittime);
577
578                 /*
579                  * If the lock is already held by curthread in
580                  * exclusive way avoid a deadlock.
581                  */
582                 if (LK_HOLDER(x) == tid) {
583                         LOCK_LOG2(lk,
584                             "%s: %p already held in exclusive mode",
585                             __func__, lk);
586                         error = EDEADLK;
587                         break;
588                 }
589
590                 /*
591                  * If the lock is expected to not sleep just give up
592                  * and return.
593                  */
594                 if (LK_TRYOP(flags)) {
595                         LOCK_LOG2(lk, "%s: %p fails the try operation",
596                             __func__, lk);
597                         error = EBUSY;
598                         break;
599                 }
600
601                 /*
602                  * Acquire the sleepqueue chain lock because we
603                  * probabilly will need to manipulate waiters flags.
604                  */
605                 sleepq_lock(&lk->lock_object);
606                 x = lk->lk_lock;
607 retry_sleepq:
608
609                 /*
610                  * if the lock can be acquired in shared mode, try
611                  * again.
612                  */
613                 if (LK_CAN_SHARE(x, flags, false)) {
614                         sleepq_release(&lk->lock_object);
615                         continue;
616                 }
617
618                 /*
619                  * Try to set the LK_SHARED_WAITERS flag.  If we fail,
620                  * loop back and retry.
621                  */
622                 if ((x & LK_SHARED_WAITERS) == 0) {
623                         if (!atomic_fcmpset_acq_ptr(&lk->lk_lock, &x,
624                             x | LK_SHARED_WAITERS)) {
625                                 goto retry_sleepq;
626                         }
627                         LOCK_LOG2(lk, "%s: %p set shared waiters flag",
628                             __func__, lk);
629                 }
630
631                 if (lwa == NULL) {
632                         iwmesg = lk->lock_object.lo_name;
633                         ipri = lk->lk_pri;
634                         itimo = lk->lk_timo;
635                 } else {
636                         iwmesg = lwa->iwmesg;
637                         ipri = lwa->ipri;
638                         itimo = lwa->itimo;
639                 }
640
641                 /*
642                  * As far as we have been unable to acquire the
643                  * shared lock and the shared waiters flag is set,
644                  * we will sleep.
645                  */
646 #ifdef KDTRACE_HOOKS
647                 sleep_time -= lockstat_nsecs(&lk->lock_object);
648 #endif
649                 error = sleeplk(lk, flags, ilk, iwmesg, ipri, itimo,
650                     SQ_SHARED_QUEUE);
651 #ifdef KDTRACE_HOOKS
652                 sleep_time += lockstat_nsecs(&lk->lock_object);
653 #endif
654                 flags &= ~LK_INTERLOCK;
655                 if (error) {
656                         LOCK_LOG3(lk,
657                             "%s: interrupted sleep for %p with %d",
658                             __func__, lk, error);
659                         break;
660                 }
661                 LOCK_LOG2(lk, "%s: %p resuming from the sleep queue",
662                     __func__, lk);
663         }
664         if (error == 0) {
665 #ifdef KDTRACE_HOOKS
666                 if (sleep_time != 0)
667                         LOCKSTAT_RECORD4(lockmgr__block, lk, sleep_time,
668                             LOCKSTAT_READER, (x & LK_SHARE) == 0,
669                             (x & LK_SHARE) == 0 ? 0 : LK_SHARERS(x));
670 #endif
671 #ifdef LOCK_PROFILING
672                 lockmgr_note_shared_acquire(lk, contested, waittime,
673                     file, line, flags);
674 #else
675                 lockmgr_note_shared_acquire(lk, 0, 0, file, line,
676                     flags);
677 #endif
678         }
679
680 out:
681         lockmgr_exit(flags, ilk, 0);
682         return (error);
683 }
684
685 static __noinline int
686 lockmgr_xlock_hard(struct lock *lk, u_int flags, struct lock_object *ilk,
687     const char *file, int line, struct lockmgr_wait *lwa)
688 {
689         struct lock_class *class;
690         uintptr_t tid, x, v;
691         int error = 0;
692         const char *iwmesg;
693         int ipri, itimo;
694
695 #ifdef KDTRACE_HOOKS
696         uint64_t sleep_time = 0;
697 #endif
698 #ifdef LOCK_PROFILING
699         uint64_t waittime = 0;
700         int contested = 0;
701 #endif
702
703         if (KERNEL_PANICKED())
704                 goto out;
705
706         tid = (uintptr_t)curthread;
707
708         if (LK_CAN_WITNESS(flags))
709                 WITNESS_CHECKORDER(&lk->lock_object, LOP_NEWORDER |
710                     LOP_EXCLUSIVE, file, line, flags & LK_INTERLOCK ?
711                     ilk : NULL);
712
713         /*
714          * If curthread already holds the lock and this one is
715          * allowed to recurse, simply recurse on it.
716          */
717         if (lockmgr_xlocked(lk)) {
718                 if ((flags & LK_CANRECURSE) == 0 &&
719                     (lk->lock_object.lo_flags & LO_RECURSABLE) == 0) {
720                         /*
721                          * If the lock is expected to not panic just
722                          * give up and return.
723                          */
724                         if (LK_TRYOP(flags)) {
725                                 LOCK_LOG2(lk,
726                                     "%s: %p fails the try operation",
727                                     __func__, lk);
728                                 error = EBUSY;
729                                 goto out;
730                         }
731                         if (flags & LK_INTERLOCK) {
732                                 class = LOCK_CLASS(ilk);
733                                 class->lc_unlock(ilk);
734                         }
735                         panic("%s: recursing on non recursive lockmgr %p "
736                             "@ %s:%d\n", __func__, lk, file, line);
737                 }
738                 lk->lk_recurse++;
739                 LOCK_LOG2(lk, "%s: %p recursing", __func__, lk);
740                 LOCK_LOG_LOCK("XLOCK", &lk->lock_object, 0,
741                     lk->lk_recurse, file, line);
742                 WITNESS_LOCK(&lk->lock_object, LOP_EXCLUSIVE |
743                     LK_TRYWIT(flags), file, line);
744                 TD_LOCKS_INC(curthread);
745                 goto out;
746         }
747
748         for (;;) {
749                 if (lk->lk_lock == LK_UNLOCKED &&
750                     atomic_cmpset_acq_ptr(&lk->lk_lock, LK_UNLOCKED, tid))
751                         break;
752 #ifdef HWPMC_HOOKS
753                 PMC_SOFT_CALL( , , lock, failed);
754 #endif
755                 lock_profile_obtain_lock_failed(&lk->lock_object,
756                     &contested, &waittime);
757
758                 /*
759                  * If the lock is expected to not sleep just give up
760                  * and return.
761                  */
762                 if (LK_TRYOP(flags)) {
763                         LOCK_LOG2(lk, "%s: %p fails the try operation",
764                             __func__, lk);
765                         error = EBUSY;
766                         break;
767                 }
768
769                 /*
770                  * Acquire the sleepqueue chain lock because we
771                  * probabilly will need to manipulate waiters flags.
772                  */
773                 sleepq_lock(&lk->lock_object);
774                 x = lk->lk_lock;
775 retry_sleepq:
776
777                 /*
778                  * if the lock has been released while we spun on
779                  * the sleepqueue chain lock just try again.
780                  */
781                 if (x == LK_UNLOCKED) {
782                         sleepq_release(&lk->lock_object);
783                         continue;
784                 }
785
786                 /*
787                  * The lock can be in the state where there is a
788                  * pending queue of waiters, but still no owner.
789                  * This happens when the lock is contested and an
790                  * owner is going to claim the lock.
791                  * If curthread is the one successfully acquiring it
792                  * claim lock ownership and return, preserving waiters
793                  * flags.
794                  */
795                 v = x & (LK_ALL_WAITERS | LK_EXCLUSIVE_SPINNERS);
796                 if ((x & ~v) == LK_UNLOCKED) {
797                         v &= ~LK_EXCLUSIVE_SPINNERS;
798                         if (atomic_fcmpset_acq_ptr(&lk->lk_lock, &x,
799                             tid | v)) {
800                                 sleepq_release(&lk->lock_object);
801                                 LOCK_LOG2(lk,
802                                     "%s: %p claimed by a new writer",
803                                     __func__, lk);
804                                 break;
805                         }
806                         goto retry_sleepq;
807                 }
808
809                 /*
810                  * Try to set the LK_EXCLUSIVE_WAITERS flag.  If we
811                  * fail, loop back and retry.
812                  */
813                 if ((x & LK_EXCLUSIVE_WAITERS) == 0) {
814                         if (!atomic_fcmpset_ptr(&lk->lk_lock, &x,
815                             x | LK_EXCLUSIVE_WAITERS)) {
816                                 goto retry_sleepq;
817                         }
818                         LOCK_LOG2(lk, "%s: %p set excl waiters flag",
819                             __func__, lk);
820                 }
821
822                 if (lwa == NULL) {
823                         iwmesg = lk->lock_object.lo_name;
824                         ipri = lk->lk_pri;
825                         itimo = lk->lk_timo;
826                 } else {
827                         iwmesg = lwa->iwmesg;
828                         ipri = lwa->ipri;
829                         itimo = lwa->itimo;
830                 }
831
832                 /*
833                  * As far as we have been unable to acquire the
834                  * exclusive lock and the exclusive waiters flag
835                  * is set, we will sleep.
836                  */
837 #ifdef KDTRACE_HOOKS
838                 sleep_time -= lockstat_nsecs(&lk->lock_object);
839 #endif
840                 error = sleeplk(lk, flags, ilk, iwmesg, ipri, itimo,
841                     SQ_EXCLUSIVE_QUEUE);
842 #ifdef KDTRACE_HOOKS
843                 sleep_time += lockstat_nsecs(&lk->lock_object);
844 #endif
845                 flags &= ~LK_INTERLOCK;
846                 if (error) {
847                         LOCK_LOG3(lk,
848                             "%s: interrupted sleep for %p with %d",
849                             __func__, lk, error);
850                         break;
851                 }
852                 LOCK_LOG2(lk, "%s: %p resuming from the sleep queue",
853                     __func__, lk);
854         }
855         if (error == 0) {
856 #ifdef KDTRACE_HOOKS
857                 if (sleep_time != 0)
858                         LOCKSTAT_RECORD4(lockmgr__block, lk, sleep_time,
859                             LOCKSTAT_WRITER, (x & LK_SHARE) == 0,
860                             (x & LK_SHARE) == 0 ? 0 : LK_SHARERS(x));
861 #endif
862 #ifdef LOCK_PROFILING
863                 lockmgr_note_exclusive_acquire(lk, contested, waittime,
864                     file, line, flags);
865 #else
866                 lockmgr_note_exclusive_acquire(lk, 0, 0, file, line,
867                     flags);
868 #endif
869         }
870
871 out:
872         lockmgr_exit(flags, ilk, 0);
873         return (error);
874 }
875
876 static __noinline int
877 lockmgr_upgrade(struct lock *lk, u_int flags, struct lock_object *ilk,
878     const char *file, int line, struct lockmgr_wait *lwa)
879 {
880         uintptr_t tid, x, v;
881         int error = 0;
882         int wakeup_swapper = 0;
883         int op;
884
885         if (KERNEL_PANICKED())
886                 goto out;
887
888         tid = (uintptr_t)curthread;
889
890         _lockmgr_assert(lk, KA_SLOCKED, file, line);
891         v = lk->lk_lock;
892         x = v & LK_ALL_WAITERS;
893         v &= LK_EXCLUSIVE_SPINNERS;
894
895         /*
896          * Try to switch from one shared lock to an exclusive one.
897          * We need to preserve waiters flags during the operation.
898          */
899         if (atomic_cmpset_ptr(&lk->lk_lock, LK_SHARERS_LOCK(1) | x | v,
900             tid | x)) {
901                 LOCK_LOG_LOCK("XUPGRADE", &lk->lock_object, 0, 0, file,
902                     line);
903                 WITNESS_UPGRADE(&lk->lock_object, LOP_EXCLUSIVE |
904                     LK_TRYWIT(flags), file, line);
905                 LOCKSTAT_RECORD0(lockmgr__upgrade, lk);
906                 TD_SLOCKS_DEC(curthread);
907                 goto out;
908         }
909
910         op = flags & LK_TYPE_MASK;
911
912         /*
913          * In LK_TRYUPGRADE mode, do not drop the lock,
914          * returning EBUSY instead.
915          */
916         if (op == LK_TRYUPGRADE) {
917                 LOCK_LOG2(lk, "%s: %p failed the nowait upgrade",
918                     __func__, lk);
919                 error = EBUSY;
920                 goto out;
921         }
922
923         /*
924          * We have been unable to succeed in upgrading, so just
925          * give up the shared lock.
926          */
927         wakeup_swapper |= wakeupshlk(lk, file, line);
928         error = lockmgr_xlock_hard(lk, flags, ilk, file, line, lwa);
929         flags &= ~LK_INTERLOCK;
930 out:
931         lockmgr_exit(flags, ilk, wakeup_swapper);
932         return (error);
933 }
934
935 int
936 lockmgr_lock_fast_path(struct lock *lk, u_int flags, struct lock_object *ilk,
937     const char *file, int line)
938 {
939         struct lock_class *class;
940         uintptr_t x, tid;
941         u_int op;
942         bool locked;
943
944         if (KERNEL_PANICKED())
945                 return (0);
946
947         op = flags & LK_TYPE_MASK;
948         locked = false;
949         switch (op) {
950         case LK_SHARED:
951                 if (LK_CAN_WITNESS(flags))
952                         WITNESS_CHECKORDER(&lk->lock_object, LOP_NEWORDER,
953                             file, line, flags & LK_INTERLOCK ? ilk : NULL);
954                 if (__predict_false(lk->lock_object.lo_flags & LK_NOSHARE))
955                         break;
956                 if (lockmgr_slock_try(lk, &x, flags, true)) {
957                         lockmgr_note_shared_acquire(lk, 0, 0,
958                             file, line, flags);
959                         locked = true;
960                 } else {
961                         return (lockmgr_slock_hard(lk, flags, ilk, file, line,
962                             NULL));
963                 }
964                 break;
965         case LK_EXCLUSIVE:
966                 if (LK_CAN_WITNESS(flags))
967                         WITNESS_CHECKORDER(&lk->lock_object, LOP_NEWORDER |
968                             LOP_EXCLUSIVE, file, line, flags & LK_INTERLOCK ?
969                             ilk : NULL);
970                 tid = (uintptr_t)curthread;
971                 if (lk->lk_lock == LK_UNLOCKED &&
972                     atomic_cmpset_acq_ptr(&lk->lk_lock, LK_UNLOCKED, tid)) {
973                         lockmgr_note_exclusive_acquire(lk, 0, 0, file, line,
974                             flags);
975                         locked = true;
976                 } else {
977                         return (lockmgr_xlock_hard(lk, flags, ilk, file, line,
978                             NULL));
979                 }
980                 break;
981         case LK_UPGRADE:
982         case LK_TRYUPGRADE:
983                 return (lockmgr_upgrade(lk, flags, ilk, file, line, NULL));
984         default:
985                 break;
986         }
987         if (__predict_true(locked)) {
988                 if (__predict_false(flags & LK_INTERLOCK)) {
989                         class = LOCK_CLASS(ilk);
990                         class->lc_unlock(ilk);
991                 }
992                 return (0);
993         } else {
994                 return (__lockmgr_args(lk, flags, ilk, LK_WMESG_DEFAULT,
995                     LK_PRIO_DEFAULT, LK_TIMO_DEFAULT, file, line));
996         }
997 }
998
999 static __noinline int
1000 lockmgr_sunlock_hard(struct lock *lk, uintptr_t x, u_int flags, struct lock_object *ilk,
1001     const char *file, int line)
1002
1003 {
1004         int wakeup_swapper = 0;
1005
1006         if (KERNEL_PANICKED())
1007                 goto out;
1008
1009         wakeup_swapper = wakeupshlk(lk, file, line);
1010
1011 out:
1012         lockmgr_exit(flags, ilk, wakeup_swapper);
1013         return (0);
1014 }
1015
1016 static __noinline int
1017 lockmgr_xunlock_hard(struct lock *lk, uintptr_t x, u_int flags, struct lock_object *ilk,
1018     const char *file, int line)
1019 {
1020         uintptr_t tid, v;
1021         int wakeup_swapper = 0;
1022         u_int realexslp;
1023         int queue;
1024
1025         if (KERNEL_PANICKED())
1026                 goto out;
1027
1028         tid = (uintptr_t)curthread;
1029
1030         /*
1031          * As first option, treact the lock as if it has not
1032          * any waiter.
1033          * Fix-up the tid var if the lock has been disowned.
1034          */
1035         if (LK_HOLDER(x) == LK_KERNPROC)
1036                 tid = LK_KERNPROC;
1037         else {
1038                 WITNESS_UNLOCK(&lk->lock_object, LOP_EXCLUSIVE, file, line);
1039                 TD_LOCKS_DEC(curthread);
1040         }
1041         LOCK_LOG_LOCK("XUNLOCK", &lk->lock_object, 0, lk->lk_recurse, file, line);
1042
1043         /*
1044          * The lock is held in exclusive mode.
1045          * If the lock is recursed also, then unrecurse it.
1046          */
1047         if (lockmgr_xlocked_v(x) && lockmgr_recursed(lk)) {
1048                 LOCK_LOG2(lk, "%s: %p unrecursing", __func__, lk);
1049                 lk->lk_recurse--;
1050                 goto out;
1051         }
1052         if (tid != LK_KERNPROC)
1053                 LOCKSTAT_PROFILE_RELEASE_RWLOCK(lockmgr__release, lk,
1054                     LOCKSTAT_WRITER);
1055
1056         if (x == tid && atomic_cmpset_rel_ptr(&lk->lk_lock, tid, LK_UNLOCKED))
1057                 goto out;
1058
1059         sleepq_lock(&lk->lock_object);
1060         x = lk->lk_lock;
1061         v = LK_UNLOCKED;
1062
1063         /*
1064          * If the lock has exclusive waiters, give them
1065          * preference in order to avoid deadlock with
1066          * shared runners up.
1067          * If interruptible sleeps left the exclusive queue
1068          * empty avoid a starvation for the threads sleeping
1069          * on the shared queue by giving them precedence
1070          * and cleaning up the exclusive waiters bit anyway.
1071          * Please note that lk_exslpfail count may be lying
1072          * about the real number of waiters with the
1073          * LK_SLEEPFAIL flag on because they may be used in
1074          * conjunction with interruptible sleeps so
1075          * lk_exslpfail might be considered an 'upper limit'
1076          * bound, including the edge cases.
1077          */
1078         MPASS((x & LK_EXCLUSIVE_SPINNERS) == 0);
1079         realexslp = sleepq_sleepcnt(&lk->lock_object, SQ_EXCLUSIVE_QUEUE);
1080         if ((x & LK_EXCLUSIVE_WAITERS) != 0 && realexslp != 0) {
1081                 if (lk->lk_exslpfail < realexslp) {
1082                         lk->lk_exslpfail = 0;
1083                         queue = SQ_EXCLUSIVE_QUEUE;
1084                         v |= (x & LK_SHARED_WAITERS);
1085                 } else {
1086                         lk->lk_exslpfail = 0;
1087                         LOCK_LOG2(lk,
1088                             "%s: %p has only LK_SLEEPFAIL sleepers",
1089                             __func__, lk);
1090                         LOCK_LOG2(lk,
1091                             "%s: %p waking up threads on the exclusive queue",
1092                             __func__, lk);
1093                         wakeup_swapper = sleepq_broadcast(&lk->lock_object,
1094                             SLEEPQ_LK, 0, SQ_EXCLUSIVE_QUEUE);
1095                         queue = SQ_SHARED_QUEUE;
1096                 }
1097         } else {
1098
1099                 /*
1100                  * Exclusive waiters sleeping with LK_SLEEPFAIL
1101                  * on and using interruptible sleeps/timeout
1102                  * may have left spourious lk_exslpfail counts
1103                  * on, so clean it up anyway.
1104                  */
1105                 lk->lk_exslpfail = 0;
1106                 queue = SQ_SHARED_QUEUE;
1107         }
1108
1109         LOCK_LOG3(lk, "%s: %p waking up threads on the %s queue",
1110             __func__, lk, queue == SQ_SHARED_QUEUE ? "shared" :
1111             "exclusive");
1112         atomic_store_rel_ptr(&lk->lk_lock, v);
1113         wakeup_swapper |= sleepq_broadcast(&lk->lock_object, SLEEPQ_LK, 0, queue);
1114         sleepq_release(&lk->lock_object);
1115
1116 out:
1117         lockmgr_exit(flags, ilk, wakeup_swapper);
1118         return (0);
1119 }
1120
1121 int
1122 lockmgr_unlock_fast_path(struct lock *lk, u_int flags, struct lock_object *ilk)
1123 {
1124         struct lock_class *class;
1125         uintptr_t x, tid;
1126         const char *file;
1127         int line;
1128
1129         if (KERNEL_PANICKED())
1130                 return (0);
1131
1132         file = __FILE__;
1133         line = __LINE__;
1134
1135         _lockmgr_assert(lk, KA_LOCKED, file, line);
1136         x = lk->lk_lock;
1137         if (__predict_true(x & LK_SHARE) != 0) {
1138                 if (lockmgr_sunlock_try(lk, &x)) {
1139                         lockmgr_note_shared_release(lk, file, line);
1140                 } else {
1141                         return (lockmgr_sunlock_hard(lk, x, flags, ilk, file, line));
1142                 }
1143         } else {
1144                 tid = (uintptr_t)curthread;
1145                 if (!lockmgr_recursed(lk) &&
1146                     atomic_cmpset_rel_ptr(&lk->lk_lock, tid, LK_UNLOCKED)) {
1147                         lockmgr_note_exclusive_release(lk, file, line);
1148                 } else {
1149                         return (lockmgr_xunlock_hard(lk, x, flags, ilk, file, line));
1150                 }
1151         }
1152         if (__predict_false(flags & LK_INTERLOCK)) {
1153                 class = LOCK_CLASS(ilk);
1154                 class->lc_unlock(ilk);
1155         }
1156         return (0);
1157 }
1158
1159 /*
1160  * Lightweight entry points for common operations.
1161  *
1162  * Functionality is similar to sx locks, in that none of the additional lockmgr
1163  * features are supported. To be clear, these are NOT supported:
1164  * 1. shared locking disablement
1165  * 2. returning with an error after sleep
1166  * 3. unlocking the interlock
1167  *
1168  * If in doubt, use lockmgr_*_fast_path.
1169  */
1170 int
1171 lockmgr_slock(struct lock *lk, u_int flags, const char *file, int line)
1172 {
1173         uintptr_t x;
1174
1175         MPASS((flags & LK_TYPE_MASK) == LK_SHARED);
1176         MPASS((flags & LK_INTERLOCK) == 0);
1177         MPASS((lk->lock_object.lo_flags & LK_NOSHARE) == 0);
1178
1179         if (LK_CAN_WITNESS(flags))
1180                 WITNESS_CHECKORDER(&lk->lock_object, LOP_NEWORDER,
1181                     file, line, NULL);
1182         if (__predict_true(lockmgr_slock_try(lk, &x, flags, true))) {
1183                 lockmgr_note_shared_acquire(lk, 0, 0, file, line, flags);
1184                 return (0);
1185         }
1186
1187         return (lockmgr_slock_hard(lk, flags, NULL, file, line, NULL));
1188 }
1189
1190 int
1191 lockmgr_xlock(struct lock *lk, u_int flags, const char *file, int line)
1192 {
1193         uintptr_t tid;
1194
1195         MPASS((flags & LK_TYPE_MASK) == LK_EXCLUSIVE);
1196         MPASS((flags & LK_INTERLOCK) == 0);
1197
1198         if (LK_CAN_WITNESS(flags))
1199                 WITNESS_CHECKORDER(&lk->lock_object, LOP_NEWORDER |
1200                     LOP_EXCLUSIVE, file, line, NULL);
1201         tid = (uintptr_t)curthread;
1202         if (atomic_cmpset_acq_ptr(&lk->lk_lock, LK_UNLOCKED, tid)) {
1203                 lockmgr_note_exclusive_acquire(lk, 0, 0, file, line,
1204                     flags);
1205                 return (0);
1206         }
1207
1208         return (lockmgr_xlock_hard(lk, flags, NULL, file, line, NULL));
1209 }
1210
1211 int
1212 lockmgr_unlock(struct lock *lk)
1213 {
1214         uintptr_t x, tid;
1215         const char *file;
1216         int line;
1217
1218         file = __FILE__;
1219         line = __LINE__;
1220
1221         _lockmgr_assert(lk, KA_LOCKED, file, line);
1222         x = lk->lk_lock;
1223         if (__predict_true(x & LK_SHARE) != 0) {
1224                 if (lockmgr_sunlock_try(lk, &x)) {
1225                         lockmgr_note_shared_release(lk, file, line);
1226                 } else {
1227                         return (lockmgr_sunlock_hard(lk, x, LK_RELEASE, NULL, file, line));
1228                 }
1229         } else {
1230                 tid = (uintptr_t)curthread;
1231                 if (!lockmgr_recursed(lk) &&
1232                     atomic_cmpset_rel_ptr(&lk->lk_lock, tid, LK_UNLOCKED)) {
1233                         lockmgr_note_exclusive_release(lk, file, line);
1234                 } else {
1235                         return (lockmgr_xunlock_hard(lk, x, LK_RELEASE, NULL, file, line));
1236                 }
1237         }
1238         return (0);
1239 }
1240
1241 int
1242 __lockmgr_args(struct lock *lk, u_int flags, struct lock_object *ilk,
1243     const char *wmesg, int pri, int timo, const char *file, int line)
1244 {
1245         GIANT_DECLARE;
1246         struct lockmgr_wait lwa;
1247         struct lock_class *class;
1248         const char *iwmesg;
1249         uintptr_t tid, v, x;
1250         u_int op, realexslp;
1251         int error, ipri, itimo, queue, wakeup_swapper;
1252 #ifdef LOCK_PROFILING
1253         uint64_t waittime = 0;
1254         int contested = 0;
1255 #endif
1256
1257         if (KERNEL_PANICKED())
1258                 return (0);
1259
1260         error = 0;
1261         tid = (uintptr_t)curthread;
1262         op = (flags & LK_TYPE_MASK);
1263         iwmesg = (wmesg == LK_WMESG_DEFAULT) ? lk->lock_object.lo_name : wmesg;
1264         ipri = (pri == LK_PRIO_DEFAULT) ? lk->lk_pri : pri;
1265         itimo = (timo == LK_TIMO_DEFAULT) ? lk->lk_timo : timo;
1266
1267         lwa.iwmesg = iwmesg;
1268         lwa.ipri = ipri;
1269         lwa.itimo = itimo;
1270
1271         MPASS((flags & ~LK_TOTAL_MASK) == 0);
1272         KASSERT((op & (op - 1)) == 0,
1273             ("%s: Invalid requested operation @ %s:%d", __func__, file, line));
1274         KASSERT((flags & (LK_NOWAIT | LK_SLEEPFAIL)) == 0 ||
1275             (op != LK_DOWNGRADE && op != LK_RELEASE),
1276             ("%s: Invalid flags in regard of the operation desired @ %s:%d",
1277             __func__, file, line));
1278         KASSERT((flags & LK_INTERLOCK) == 0 || ilk != NULL,
1279             ("%s: LK_INTERLOCK passed without valid interlock @ %s:%d",
1280             __func__, file, line));
1281         KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
1282             ("%s: idle thread %p on lockmgr %s @ %s:%d", __func__, curthread,
1283             lk->lock_object.lo_name, file, line));
1284
1285         class = (flags & LK_INTERLOCK) ? LOCK_CLASS(ilk) : NULL;
1286
1287         if (lk->lock_object.lo_flags & LK_NOSHARE) {
1288                 switch (op) {
1289                 case LK_SHARED:
1290                         op = LK_EXCLUSIVE;
1291                         break;
1292                 case LK_UPGRADE:
1293                 case LK_TRYUPGRADE:
1294                 case LK_DOWNGRADE:
1295                         _lockmgr_assert(lk, KA_XLOCKED | KA_NOTRECURSED,
1296                             file, line);
1297                         if (flags & LK_INTERLOCK)
1298                                 class->lc_unlock(ilk);
1299                         return (0);
1300                 }
1301         }
1302
1303         wakeup_swapper = 0;
1304         switch (op) {
1305         case LK_SHARED:
1306                 return (lockmgr_slock_hard(lk, flags, ilk, file, line, &lwa));
1307                 break;
1308         case LK_UPGRADE:
1309         case LK_TRYUPGRADE:
1310                 return (lockmgr_upgrade(lk, flags, ilk, file, line, &lwa));
1311                 break;
1312         case LK_EXCLUSIVE:
1313                 return (lockmgr_xlock_hard(lk, flags, ilk, file, line, &lwa));
1314                 break;
1315         case LK_DOWNGRADE:
1316                 _lockmgr_assert(lk, KA_XLOCKED, file, line);
1317                 WITNESS_DOWNGRADE(&lk->lock_object, 0, file, line);
1318
1319                 /*
1320                  * Panic if the lock is recursed.
1321                  */
1322                 if (lockmgr_xlocked(lk) && lockmgr_recursed(lk)) {
1323                         if (flags & LK_INTERLOCK)
1324                                 class->lc_unlock(ilk);
1325                         panic("%s: downgrade a recursed lockmgr %s @ %s:%d\n",
1326                             __func__, iwmesg, file, line);
1327                 }
1328                 TD_SLOCKS_INC(curthread);
1329
1330                 /*
1331                  * In order to preserve waiters flags, just spin.
1332                  */
1333                 for (;;) {
1334                         x = lk->lk_lock;
1335                         MPASS((x & LK_EXCLUSIVE_SPINNERS) == 0);
1336                         x &= LK_ALL_WAITERS;
1337                         if (atomic_cmpset_rel_ptr(&lk->lk_lock, tid | x,
1338                             LK_SHARERS_LOCK(1) | x))
1339                                 break;
1340                         cpu_spinwait();
1341                 }
1342                 LOCK_LOG_LOCK("XDOWNGRADE", &lk->lock_object, 0, 0, file, line);
1343                 LOCKSTAT_RECORD0(lockmgr__downgrade, lk);
1344                 break;
1345         case LK_RELEASE:
1346                 _lockmgr_assert(lk, KA_LOCKED, file, line);
1347                 x = lk->lk_lock;
1348
1349                 if (__predict_true(x & LK_SHARE) != 0) {
1350                         return (lockmgr_sunlock_hard(lk, x, flags, ilk, file, line));
1351                 } else {
1352                         return (lockmgr_xunlock_hard(lk, x, flags, ilk, file, line));
1353                 }
1354                 break;
1355         case LK_DRAIN:
1356                 if (LK_CAN_WITNESS(flags))
1357                         WITNESS_CHECKORDER(&lk->lock_object, LOP_NEWORDER |
1358                             LOP_EXCLUSIVE, file, line, flags & LK_INTERLOCK ?
1359                             ilk : NULL);
1360
1361                 /*
1362                  * Trying to drain a lock we already own will result in a
1363                  * deadlock.
1364                  */
1365                 if (lockmgr_xlocked(lk)) {
1366                         if (flags & LK_INTERLOCK)
1367                                 class->lc_unlock(ilk);
1368                         panic("%s: draining %s with the lock held @ %s:%d\n",
1369                             __func__, iwmesg, file, line);
1370                 }
1371
1372                 for (;;) {
1373                         if (lk->lk_lock == LK_UNLOCKED &&
1374                             atomic_cmpset_acq_ptr(&lk->lk_lock, LK_UNLOCKED, tid))
1375                                 break;
1376
1377 #ifdef HWPMC_HOOKS
1378                         PMC_SOFT_CALL( , , lock, failed);
1379 #endif
1380                         lock_profile_obtain_lock_failed(&lk->lock_object,
1381                             &contested, &waittime);
1382
1383                         /*
1384                          * If the lock is expected to not sleep just give up
1385                          * and return.
1386                          */
1387                         if (LK_TRYOP(flags)) {
1388                                 LOCK_LOG2(lk, "%s: %p fails the try operation",
1389                                     __func__, lk);
1390                                 error = EBUSY;
1391                                 break;
1392                         }
1393
1394                         /*
1395                          * Acquire the sleepqueue chain lock because we
1396                          * probabilly will need to manipulate waiters flags.
1397                          */
1398                         sleepq_lock(&lk->lock_object);
1399                         x = lk->lk_lock;
1400
1401                         /*
1402                          * if the lock has been released while we spun on
1403                          * the sleepqueue chain lock just try again.
1404                          */
1405                         if (x == LK_UNLOCKED) {
1406                                 sleepq_release(&lk->lock_object);
1407                                 continue;
1408                         }
1409
1410                         v = x & (LK_ALL_WAITERS | LK_EXCLUSIVE_SPINNERS);
1411                         if ((x & ~v) == LK_UNLOCKED) {
1412                                 v = (x & ~LK_EXCLUSIVE_SPINNERS);
1413
1414                                 /*
1415                                  * If interruptible sleeps left the exclusive
1416                                  * queue empty avoid a starvation for the
1417                                  * threads sleeping on the shared queue by
1418                                  * giving them precedence and cleaning up the
1419                                  * exclusive waiters bit anyway.
1420                                  * Please note that lk_exslpfail count may be
1421                                  * lying about the real number of waiters with
1422                                  * the LK_SLEEPFAIL flag on because they may
1423                                  * be used in conjunction with interruptible
1424                                  * sleeps so lk_exslpfail might be considered
1425                                  * an 'upper limit' bound, including the edge
1426                                  * cases.
1427                                  */
1428                                 if (v & LK_EXCLUSIVE_WAITERS) {
1429                                         queue = SQ_EXCLUSIVE_QUEUE;
1430                                         v &= ~LK_EXCLUSIVE_WAITERS;
1431                                 } else {
1432
1433                                         /*
1434                                          * Exclusive waiters sleeping with
1435                                          * LK_SLEEPFAIL on and using
1436                                          * interruptible sleeps/timeout may
1437                                          * have left spourious lk_exslpfail
1438                                          * counts on, so clean it up anyway.
1439                                          */
1440                                         MPASS(v & LK_SHARED_WAITERS);
1441                                         lk->lk_exslpfail = 0;
1442                                         queue = SQ_SHARED_QUEUE;
1443                                         v &= ~LK_SHARED_WAITERS;
1444                                 }
1445                                 if (queue == SQ_EXCLUSIVE_QUEUE) {
1446                                         realexslp =
1447                                             sleepq_sleepcnt(&lk->lock_object,
1448                                             SQ_EXCLUSIVE_QUEUE);
1449                                         if (lk->lk_exslpfail >= realexslp) {
1450                                                 lk->lk_exslpfail = 0;
1451                                                 queue = SQ_SHARED_QUEUE;
1452                                                 v &= ~LK_SHARED_WAITERS;
1453                                                 if (realexslp != 0) {
1454                                                         LOCK_LOG2(lk,
1455                                         "%s: %p has only LK_SLEEPFAIL sleepers",
1456                                                             __func__, lk);
1457                                                         LOCK_LOG2(lk,
1458                         "%s: %p waking up threads on the exclusive queue",
1459                                                             __func__, lk);
1460                                                         wakeup_swapper =
1461                                                             sleepq_broadcast(
1462                                                             &lk->lock_object,
1463                                                             SLEEPQ_LK, 0,
1464                                                             SQ_EXCLUSIVE_QUEUE);
1465                                                 }
1466                                         } else
1467                                                 lk->lk_exslpfail = 0;
1468                                 }
1469                                 if (!atomic_cmpset_ptr(&lk->lk_lock, x, v)) {
1470                                         sleepq_release(&lk->lock_object);
1471                                         continue;
1472                                 }
1473                                 LOCK_LOG3(lk,
1474                                 "%s: %p waking up all threads on the %s queue",
1475                                     __func__, lk, queue == SQ_SHARED_QUEUE ?
1476                                     "shared" : "exclusive");
1477                                 wakeup_swapper |= sleepq_broadcast(
1478                                     &lk->lock_object, SLEEPQ_LK, 0, queue);
1479
1480                                 /*
1481                                  * If shared waiters have been woken up we need
1482                                  * to wait for one of them to acquire the lock
1483                                  * before to set the exclusive waiters in
1484                                  * order to avoid a deadlock.
1485                                  */
1486                                 if (queue == SQ_SHARED_QUEUE) {
1487                                         for (v = lk->lk_lock;
1488                                             (v & LK_SHARE) && !LK_SHARERS(v);
1489                                             v = lk->lk_lock)
1490                                                 cpu_spinwait();
1491                                 }
1492                         }
1493
1494                         /*
1495                          * Try to set the LK_EXCLUSIVE_WAITERS flag.  If we
1496                          * fail, loop back and retry.
1497                          */
1498                         if ((x & LK_EXCLUSIVE_WAITERS) == 0) {
1499                                 if (!atomic_cmpset_ptr(&lk->lk_lock, x,
1500                                     x | LK_EXCLUSIVE_WAITERS)) {
1501                                         sleepq_release(&lk->lock_object);
1502                                         continue;
1503                                 }
1504                                 LOCK_LOG2(lk, "%s: %p set drain waiters flag",
1505                                     __func__, lk);
1506                         }
1507
1508                         /*
1509                          * As far as we have been unable to acquire the
1510                          * exclusive lock and the exclusive waiters flag
1511                          * is set, we will sleep.
1512                          */
1513                         if (flags & LK_INTERLOCK) {
1514                                 class->lc_unlock(ilk);
1515                                 flags &= ~LK_INTERLOCK;
1516                         }
1517                         GIANT_SAVE();
1518                         sleepq_add(&lk->lock_object, NULL, iwmesg, SLEEPQ_LK,
1519                             SQ_EXCLUSIVE_QUEUE);
1520                         sleepq_wait(&lk->lock_object, ipri & PRIMASK);
1521                         GIANT_RESTORE();
1522                         LOCK_LOG2(lk, "%s: %p resuming from the sleep queue",
1523                             __func__, lk);
1524                 }
1525
1526                 if (error == 0) {
1527                         lock_profile_obtain_lock_success(&lk->lock_object,
1528                             contested, waittime, file, line);
1529                         LOCK_LOG_LOCK("DRAIN", &lk->lock_object, 0,
1530                             lk->lk_recurse, file, line);
1531                         WITNESS_LOCK(&lk->lock_object, LOP_EXCLUSIVE |
1532                             LK_TRYWIT(flags), file, line);
1533                         TD_LOCKS_INC(curthread);
1534                         STACK_SAVE(lk);
1535                 }
1536                 break;
1537         default:
1538                 if (flags & LK_INTERLOCK)
1539                         class->lc_unlock(ilk);
1540                 panic("%s: unknown lockmgr request 0x%x\n", __func__, op);
1541         }
1542
1543         if (flags & LK_INTERLOCK)
1544                 class->lc_unlock(ilk);
1545         if (wakeup_swapper)
1546                 kick_proc0();
1547
1548         return (error);
1549 }
1550
1551 void
1552 _lockmgr_disown(struct lock *lk, const char *file, int line)
1553 {
1554         uintptr_t tid, x;
1555
1556         if (SCHEDULER_STOPPED())
1557                 return;
1558
1559         tid = (uintptr_t)curthread;
1560         _lockmgr_assert(lk, KA_XLOCKED, file, line);
1561
1562         /*
1563          * Panic if the lock is recursed.
1564          */
1565         if (lockmgr_xlocked(lk) && lockmgr_recursed(lk))
1566                 panic("%s: disown a recursed lockmgr @ %s:%d\n",
1567                     __func__,  file, line);
1568
1569         /*
1570          * If the owner is already LK_KERNPROC just skip the whole operation.
1571          */
1572         if (LK_HOLDER(lk->lk_lock) != tid)
1573                 return;
1574         lock_profile_release_lock(&lk->lock_object);
1575         LOCKSTAT_RECORD1(lockmgr__disown, lk, LOCKSTAT_WRITER);
1576         LOCK_LOG_LOCK("XDISOWN", &lk->lock_object, 0, 0, file, line);
1577         WITNESS_UNLOCK(&lk->lock_object, LOP_EXCLUSIVE, file, line);
1578         TD_LOCKS_DEC(curthread);
1579         STACK_SAVE(lk);
1580
1581         /*
1582          * In order to preserve waiters flags, just spin.
1583          */
1584         for (;;) {
1585                 x = lk->lk_lock;
1586                 MPASS((x & LK_EXCLUSIVE_SPINNERS) == 0);
1587                 x &= LK_ALL_WAITERS;
1588                 if (atomic_cmpset_rel_ptr(&lk->lk_lock, tid | x,
1589                     LK_KERNPROC | x))
1590                         return;
1591                 cpu_spinwait();
1592         }
1593 }
1594
1595 void
1596 lockmgr_printinfo(const struct lock *lk)
1597 {
1598         struct thread *td;
1599         uintptr_t x;
1600
1601         if (lk->lk_lock == LK_UNLOCKED)
1602                 printf("lock type %s: UNLOCKED\n", lk->lock_object.lo_name);
1603         else if (lk->lk_lock & LK_SHARE)
1604                 printf("lock type %s: SHARED (count %ju)\n",
1605                     lk->lock_object.lo_name,
1606                     (uintmax_t)LK_SHARERS(lk->lk_lock));
1607         else {
1608                 td = lockmgr_xholder(lk);
1609                 if (td == (struct thread *)LK_KERNPROC)
1610                         printf("lock type %s: EXCL by KERNPROC\n",
1611                             lk->lock_object.lo_name);
1612                 else
1613                         printf("lock type %s: EXCL by thread %p "
1614                             "(pid %d, %s, tid %d)\n", lk->lock_object.lo_name,
1615                             td, td->td_proc->p_pid, td->td_proc->p_comm,
1616                             td->td_tid);
1617         }
1618
1619         x = lk->lk_lock;
1620         if (x & LK_EXCLUSIVE_WAITERS)
1621                 printf(" with exclusive waiters pending\n");
1622         if (x & LK_SHARED_WAITERS)
1623                 printf(" with shared waiters pending\n");
1624         if (x & LK_EXCLUSIVE_SPINNERS)
1625                 printf(" with exclusive spinners pending\n");
1626
1627         STACK_PRINT(lk);
1628 }
1629
1630 int
1631 lockstatus(const struct lock *lk)
1632 {
1633         uintptr_t v, x;
1634         int ret;
1635
1636         ret = LK_SHARED;
1637         x = lk->lk_lock;
1638         v = LK_HOLDER(x);
1639
1640         if ((x & LK_SHARE) == 0) {
1641                 if (v == (uintptr_t)curthread || v == LK_KERNPROC)
1642                         ret = LK_EXCLUSIVE;
1643                 else
1644                         ret = LK_EXCLOTHER;
1645         } else if (x == LK_UNLOCKED)
1646                 ret = 0;
1647
1648         return (ret);
1649 }
1650
1651 #ifdef INVARIANT_SUPPORT
1652
1653 FEATURE(invariant_support,
1654     "Support for modules compiled with INVARIANTS option");
1655
1656 #ifndef INVARIANTS
1657 #undef  _lockmgr_assert
1658 #endif
1659
1660 void
1661 _lockmgr_assert(const struct lock *lk, int what, const char *file, int line)
1662 {
1663         int slocked = 0;
1664
1665         if (KERNEL_PANICKED())
1666                 return;
1667         switch (what) {
1668         case KA_SLOCKED:
1669         case KA_SLOCKED | KA_NOTRECURSED:
1670         case KA_SLOCKED | KA_RECURSED:
1671                 slocked = 1;
1672         case KA_LOCKED:
1673         case KA_LOCKED | KA_NOTRECURSED:
1674         case KA_LOCKED | KA_RECURSED:
1675 #ifdef WITNESS
1676
1677                 /*
1678                  * We cannot trust WITNESS if the lock is held in exclusive
1679                  * mode and a call to lockmgr_disown() happened.
1680                  * Workaround this skipping the check if the lock is held in
1681                  * exclusive mode even for the KA_LOCKED case.
1682                  */
1683                 if (slocked || (lk->lk_lock & LK_SHARE)) {
1684                         witness_assert(&lk->lock_object, what, file, line);
1685                         break;
1686                 }
1687 #endif
1688                 if (lk->lk_lock == LK_UNLOCKED ||
1689                     ((lk->lk_lock & LK_SHARE) == 0 && (slocked ||
1690                     (!lockmgr_xlocked(lk) && !lockmgr_disowned(lk)))))
1691                         panic("Lock %s not %slocked @ %s:%d\n",
1692                             lk->lock_object.lo_name, slocked ? "share" : "",
1693                             file, line);
1694
1695                 if ((lk->lk_lock & LK_SHARE) == 0) {
1696                         if (lockmgr_recursed(lk)) {
1697                                 if (what & KA_NOTRECURSED)
1698                                         panic("Lock %s recursed @ %s:%d\n",
1699                                             lk->lock_object.lo_name, file,
1700                                             line);
1701                         } else if (what & KA_RECURSED)
1702                                 panic("Lock %s not recursed @ %s:%d\n",
1703                                     lk->lock_object.lo_name, file, line);
1704                 }
1705                 break;
1706         case KA_XLOCKED:
1707         case KA_XLOCKED | KA_NOTRECURSED:
1708         case KA_XLOCKED | KA_RECURSED:
1709                 if (!lockmgr_xlocked(lk) && !lockmgr_disowned(lk))
1710                         panic("Lock %s not exclusively locked @ %s:%d\n",
1711                             lk->lock_object.lo_name, file, line);
1712                 if (lockmgr_recursed(lk)) {
1713                         if (what & KA_NOTRECURSED)
1714                                 panic("Lock %s recursed @ %s:%d\n",
1715                                     lk->lock_object.lo_name, file, line);
1716                 } else if (what & KA_RECURSED)
1717                         panic("Lock %s not recursed @ %s:%d\n",
1718                             lk->lock_object.lo_name, file, line);
1719                 break;
1720         case KA_UNLOCKED:
1721                 if (lockmgr_xlocked(lk) || lockmgr_disowned(lk))
1722                         panic("Lock %s exclusively locked @ %s:%d\n",
1723                             lk->lock_object.lo_name, file, line);
1724                 break;
1725         default:
1726                 panic("Unknown lockmgr assertion: %d @ %s:%d\n", what, file,
1727                     line);
1728         }
1729 }
1730 #endif
1731
1732 #ifdef DDB
1733 int
1734 lockmgr_chain(struct thread *td, struct thread **ownerp)
1735 {
1736         const struct lock *lk;
1737
1738         lk = td->td_wchan;
1739
1740         if (LOCK_CLASS(&lk->lock_object) != &lock_class_lockmgr)
1741                 return (0);
1742         db_printf("blocked on lockmgr %s", lk->lock_object.lo_name);
1743         if (lk->lk_lock & LK_SHARE)
1744                 db_printf("SHARED (count %ju)\n",
1745                     (uintmax_t)LK_SHARERS(lk->lk_lock));
1746         else
1747                 db_printf("EXCL\n");
1748         *ownerp = lockmgr_xholder(lk);
1749
1750         return (1);
1751 }
1752
1753 static void
1754 db_show_lockmgr(const struct lock_object *lock)
1755 {
1756         struct thread *td;
1757         const struct lock *lk;
1758
1759         lk = (const struct lock *)lock;
1760
1761         db_printf(" state: ");
1762         if (lk->lk_lock == LK_UNLOCKED)
1763                 db_printf("UNLOCKED\n");
1764         else if (lk->lk_lock & LK_SHARE)
1765                 db_printf("SLOCK: %ju\n", (uintmax_t)LK_SHARERS(lk->lk_lock));
1766         else {
1767                 td = lockmgr_xholder(lk);
1768                 if (td == (struct thread *)LK_KERNPROC)
1769                         db_printf("XLOCK: LK_KERNPROC\n");
1770                 else
1771                         db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1772                             td->td_tid, td->td_proc->p_pid,
1773                             td->td_proc->p_comm);
1774                 if (lockmgr_recursed(lk))
1775                         db_printf(" recursed: %d\n", lk->lk_recurse);
1776         }
1777         db_printf(" waiters: ");
1778         switch (lk->lk_lock & LK_ALL_WAITERS) {
1779         case LK_SHARED_WAITERS:
1780                 db_printf("shared\n");
1781                 break;
1782         case LK_EXCLUSIVE_WAITERS:
1783                 db_printf("exclusive\n");
1784                 break;
1785         case LK_ALL_WAITERS:
1786                 db_printf("shared and exclusive\n");
1787                 break;
1788         default:
1789                 db_printf("none\n");
1790         }
1791         db_printf(" spinners: ");
1792         if (lk->lk_lock & LK_EXCLUSIVE_SPINNERS)
1793                 db_printf("exclusive\n");
1794         else
1795                 db_printf("none\n");
1796 }
1797 #endif