]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_lock.c
lockmgr: rewrite upgrade to stop always dropping the lock
[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(lockmgr_read_value(lk))
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         WITNESS_UNLOCK(&lk->lock_object, 0, file, line);
213         LOCK_LOG_LOCK("SUNLOCK", &lk->lock_object, 0, 0, file, line);
214         TD_LOCKS_DEC(curthread);
215         TD_SLOCKS_DEC(curthread);
216 }
217
218 static void
219 lockmgr_note_exclusive_acquire(struct lock *lk, int contested,
220     uint64_t waittime, const char *file, int line, int flags)
221 {
222
223         LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(lockmgr__acquire, lk, contested,
224             waittime, file, line, LOCKSTAT_WRITER);
225         LOCK_LOG_LOCK("XLOCK", &lk->lock_object, 0, lk->lk_recurse, file, line);
226         WITNESS_LOCK(&lk->lock_object, LOP_EXCLUSIVE | LK_TRYWIT(flags), file,
227             line);
228         TD_LOCKS_INC(curthread);
229         STACK_SAVE(lk);
230 }
231
232 static void
233 lockmgr_note_exclusive_release(struct lock *lk, const char *file, int line)
234 {
235
236         if (LK_HOLDER(lockmgr_read_value(lk)) != LK_KERNPROC) {
237                 WITNESS_UNLOCK(&lk->lock_object, LOP_EXCLUSIVE, file, line);
238                 TD_LOCKS_DEC(curthread);
239         }
240         LOCK_LOG_LOCK("XUNLOCK", &lk->lock_object, 0, lk->lk_recurse, file,
241             line);
242 }
243
244 static __inline struct thread *
245 lockmgr_xholder(const struct lock *lk)
246 {
247         uintptr_t x;
248
249         x = lockmgr_read_value(lk);
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 = lockmgr_read_value(lk);
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 = lockmgr_read_value(lk);
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         LOCKSTAT_PROFILE_RELEASE_RWLOCK(lockmgr__release, lk, LOCKSTAT_READER);
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 = lockmgr_read_value(lk);
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 = lockmgr_read_value(lk);
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                         STACK_PRINT(lk);
736                         panic("%s: recursing on non recursive lockmgr %p "
737                             "@ %s:%d\n", __func__, lk, file, line);
738                 }
739                 lk->lk_recurse++;
740                 LOCK_LOG2(lk, "%s: %p recursing", __func__, lk);
741                 LOCK_LOG_LOCK("XLOCK", &lk->lock_object, 0,
742                     lk->lk_recurse, file, line);
743                 WITNESS_LOCK(&lk->lock_object, LOP_EXCLUSIVE |
744                     LK_TRYWIT(flags), file, line);
745                 TD_LOCKS_INC(curthread);
746                 goto out;
747         }
748
749         for (;;) {
750                 if (lk->lk_lock == LK_UNLOCKED &&
751                     atomic_cmpset_acq_ptr(&lk->lk_lock, LK_UNLOCKED, tid))
752                         break;
753 #ifdef HWPMC_HOOKS
754                 PMC_SOFT_CALL( , , lock, failed);
755 #endif
756                 lock_profile_obtain_lock_failed(&lk->lock_object,
757                     &contested, &waittime);
758
759                 /*
760                  * If the lock is expected to not sleep just give up
761                  * and return.
762                  */
763                 if (LK_TRYOP(flags)) {
764                         LOCK_LOG2(lk, "%s: %p fails the try operation",
765                             __func__, lk);
766                         error = EBUSY;
767                         break;
768                 }
769
770                 /*
771                  * Acquire the sleepqueue chain lock because we
772                  * probabilly will need to manipulate waiters flags.
773                  */
774                 sleepq_lock(&lk->lock_object);
775                 x = lockmgr_read_value(lk);
776 retry_sleepq:
777
778                 /*
779                  * if the lock has been released while we spun on
780                  * the sleepqueue chain lock just try again.
781                  */
782                 if (x == LK_UNLOCKED) {
783                         sleepq_release(&lk->lock_object);
784                         continue;
785                 }
786
787                 /*
788                  * The lock can be in the state where there is a
789                  * pending queue of waiters, but still no owner.
790                  * This happens when the lock is contested and an
791                  * owner is going to claim the lock.
792                  * If curthread is the one successfully acquiring it
793                  * claim lock ownership and return, preserving waiters
794                  * flags.
795                  */
796                 v = x & (LK_ALL_WAITERS | LK_EXCLUSIVE_SPINNERS);
797                 if ((x & ~v) == LK_UNLOCKED) {
798                         v &= ~LK_EXCLUSIVE_SPINNERS;
799                         if (atomic_fcmpset_acq_ptr(&lk->lk_lock, &x,
800                             tid | v)) {
801                                 sleepq_release(&lk->lock_object);
802                                 LOCK_LOG2(lk,
803                                     "%s: %p claimed by a new writer",
804                                     __func__, lk);
805                                 break;
806                         }
807                         goto retry_sleepq;
808                 }
809
810                 /*
811                  * Try to set the LK_EXCLUSIVE_WAITERS flag.  If we
812                  * fail, loop back and retry.
813                  */
814                 if ((x & LK_EXCLUSIVE_WAITERS) == 0) {
815                         if (!atomic_fcmpset_ptr(&lk->lk_lock, &x,
816                             x | LK_EXCLUSIVE_WAITERS)) {
817                                 goto retry_sleepq;
818                         }
819                         LOCK_LOG2(lk, "%s: %p set excl waiters flag",
820                             __func__, lk);
821                 }
822
823                 if (lwa == NULL) {
824                         iwmesg = lk->lock_object.lo_name;
825                         ipri = lk->lk_pri;
826                         itimo = lk->lk_timo;
827                 } else {
828                         iwmesg = lwa->iwmesg;
829                         ipri = lwa->ipri;
830                         itimo = lwa->itimo;
831                 }
832
833                 /*
834                  * As far as we have been unable to acquire the
835                  * exclusive lock and the exclusive waiters flag
836                  * is set, we will sleep.
837                  */
838 #ifdef KDTRACE_HOOKS
839                 sleep_time -= lockstat_nsecs(&lk->lock_object);
840 #endif
841                 error = sleeplk(lk, flags, ilk, iwmesg, ipri, itimo,
842                     SQ_EXCLUSIVE_QUEUE);
843 #ifdef KDTRACE_HOOKS
844                 sleep_time += lockstat_nsecs(&lk->lock_object);
845 #endif
846                 flags &= ~LK_INTERLOCK;
847                 if (error) {
848                         LOCK_LOG3(lk,
849                             "%s: interrupted sleep for %p with %d",
850                             __func__, lk, error);
851                         break;
852                 }
853                 LOCK_LOG2(lk, "%s: %p resuming from the sleep queue",
854                     __func__, lk);
855         }
856         if (error == 0) {
857 #ifdef KDTRACE_HOOKS
858                 if (sleep_time != 0)
859                         LOCKSTAT_RECORD4(lockmgr__block, lk, sleep_time,
860                             LOCKSTAT_WRITER, (x & LK_SHARE) == 0,
861                             (x & LK_SHARE) == 0 ? 0 : LK_SHARERS(x));
862 #endif
863 #ifdef LOCK_PROFILING
864                 lockmgr_note_exclusive_acquire(lk, contested, waittime,
865                     file, line, flags);
866 #else
867                 lockmgr_note_exclusive_acquire(lk, 0, 0, file, line,
868                     flags);
869 #endif
870         }
871
872 out:
873         lockmgr_exit(flags, ilk, 0);
874         return (error);
875 }
876
877 static __noinline int
878 lockmgr_upgrade(struct lock *lk, u_int flags, struct lock_object *ilk,
879     const char *file, int line, struct lockmgr_wait *lwa)
880 {
881         uintptr_t tid, v, setv;
882         int error = 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
892         op = flags & LK_TYPE_MASK;
893         v = lockmgr_read_value(lk);
894         for (;;) {
895                 if (LK_SHARERS_LOCK(v) > 1) {
896                         if (op == LK_TRYUPGRADE) {
897                                 LOCK_LOG2(lk, "%s: %p failed the nowait upgrade",
898                                     __func__, lk);
899                                 error = EBUSY;
900                                 goto out;
901                         }
902                         if (lockmgr_sunlock_try(lk, &v)) {
903                                 lockmgr_note_shared_release(lk, file, line);
904                                 goto out_xlock;
905                         }
906                 }
907                 MPASS((v & ~LK_ALL_WAITERS) == LK_SHARERS_LOCK(1));
908
909                 setv = tid;
910                 setv |= (v & LK_ALL_WAITERS);
911
912                 /*
913                  * Try to switch from one shared lock to an exclusive one.
914                  * We need to preserve waiters flags during the operation.
915                  */
916                 if (atomic_fcmpset_ptr(&lk->lk_lock, &v, setv)) {
917                         LOCK_LOG_LOCK("XUPGRADE", &lk->lock_object, 0, 0, file,
918                             line);
919                         WITNESS_UPGRADE(&lk->lock_object, LOP_EXCLUSIVE |
920                             LK_TRYWIT(flags), file, line);
921                         LOCKSTAT_RECORD0(lockmgr__upgrade, lk);
922                         TD_SLOCKS_DEC(curthread);
923                         goto out;
924                 }
925         }
926
927 out_xlock:
928         error = lockmgr_xlock_hard(lk, flags, ilk, file, line, lwa);
929         flags &= ~LK_INTERLOCK;
930 out:
931         lockmgr_exit(flags, ilk, 0);
932         return (error);
933 }
934
935 int
936 lockmgr_lock_flags(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 (lockmgr_read_value(lk) == 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
1038         /*
1039          * The lock is held in exclusive mode.
1040          * If the lock is recursed also, then unrecurse it.
1041          */
1042         if (lockmgr_xlocked_v(x) && lockmgr_recursed(lk)) {
1043                 LOCK_LOG2(lk, "%s: %p unrecursing", __func__, lk);
1044                 lk->lk_recurse--;
1045                 goto out;
1046         }
1047         if (tid != LK_KERNPROC)
1048                 LOCKSTAT_PROFILE_RELEASE_RWLOCK(lockmgr__release, lk,
1049                     LOCKSTAT_WRITER);
1050
1051         if (x == tid && atomic_cmpset_rel_ptr(&lk->lk_lock, tid, LK_UNLOCKED))
1052                 goto out;
1053
1054         sleepq_lock(&lk->lock_object);
1055         x = lockmgr_read_value(lk);
1056         v = LK_UNLOCKED;
1057
1058         /*
1059          * If the lock has exclusive waiters, give them
1060          * preference in order to avoid deadlock with
1061          * shared runners up.
1062          * If interruptible sleeps left the exclusive queue
1063          * empty avoid a starvation for the threads sleeping
1064          * on the shared queue by giving them precedence
1065          * and cleaning up the exclusive waiters bit anyway.
1066          * Please note that lk_exslpfail count may be lying
1067          * about the real number of waiters with the
1068          * LK_SLEEPFAIL flag on because they may be used in
1069          * conjunction with interruptible sleeps so
1070          * lk_exslpfail might be considered an 'upper limit'
1071          * bound, including the edge cases.
1072          */
1073         MPASS((x & LK_EXCLUSIVE_SPINNERS) == 0);
1074         realexslp = sleepq_sleepcnt(&lk->lock_object, SQ_EXCLUSIVE_QUEUE);
1075         if ((x & LK_EXCLUSIVE_WAITERS) != 0 && realexslp != 0) {
1076                 if (lk->lk_exslpfail < realexslp) {
1077                         lk->lk_exslpfail = 0;
1078                         queue = SQ_EXCLUSIVE_QUEUE;
1079                         v |= (x & LK_SHARED_WAITERS);
1080                 } else {
1081                         lk->lk_exslpfail = 0;
1082                         LOCK_LOG2(lk,
1083                             "%s: %p has only LK_SLEEPFAIL sleepers",
1084                             __func__, lk);
1085                         LOCK_LOG2(lk,
1086                             "%s: %p waking up threads on the exclusive queue",
1087                             __func__, lk);
1088                         wakeup_swapper = sleepq_broadcast(&lk->lock_object,
1089                             SLEEPQ_LK, 0, SQ_EXCLUSIVE_QUEUE);
1090                         queue = SQ_SHARED_QUEUE;
1091                 }
1092         } else {
1093
1094                 /*
1095                  * Exclusive waiters sleeping with LK_SLEEPFAIL
1096                  * on and using interruptible sleeps/timeout
1097                  * may have left spourious lk_exslpfail counts
1098                  * on, so clean it up anyway.
1099                  */
1100                 lk->lk_exslpfail = 0;
1101                 queue = SQ_SHARED_QUEUE;
1102         }
1103
1104         LOCK_LOG3(lk, "%s: %p waking up threads on the %s queue",
1105             __func__, lk, queue == SQ_SHARED_QUEUE ? "shared" :
1106             "exclusive");
1107         atomic_store_rel_ptr(&lk->lk_lock, v);
1108         wakeup_swapper |= sleepq_broadcast(&lk->lock_object, SLEEPQ_LK, 0, queue);
1109         sleepq_release(&lk->lock_object);
1110
1111 out:
1112         lockmgr_exit(flags, ilk, wakeup_swapper);
1113         return (0);
1114 }
1115
1116 /*
1117  * Lightweight entry points for common operations.
1118  *
1119  * Functionality is similar to sx locks, in that none of the additional lockmgr
1120  * features are supported. To be clear, these are NOT supported:
1121  * 1. shared locking disablement
1122  * 2. returning with an error after sleep
1123  * 3. unlocking the interlock
1124  *
1125  * If in doubt, use lockmgr_lock_flags.
1126  */
1127 int
1128 lockmgr_slock(struct lock *lk, u_int flags, const char *file, int line)
1129 {
1130         uintptr_t x;
1131
1132         MPASS((flags & LK_TYPE_MASK) == LK_SHARED);
1133         MPASS((flags & LK_INTERLOCK) == 0);
1134         MPASS((lk->lock_object.lo_flags & LK_NOSHARE) == 0);
1135
1136         if (LK_CAN_WITNESS(flags))
1137                 WITNESS_CHECKORDER(&lk->lock_object, LOP_NEWORDER,
1138                     file, line, NULL);
1139         if (__predict_true(lockmgr_slock_try(lk, &x, flags, true))) {
1140                 lockmgr_note_shared_acquire(lk, 0, 0, file, line, flags);
1141                 return (0);
1142         }
1143
1144         return (lockmgr_slock_hard(lk, flags, NULL, file, line, NULL));
1145 }
1146
1147 int
1148 lockmgr_xlock(struct lock *lk, u_int flags, const char *file, int line)
1149 {
1150         uintptr_t tid;
1151
1152         MPASS((flags & LK_TYPE_MASK) == LK_EXCLUSIVE);
1153         MPASS((flags & LK_INTERLOCK) == 0);
1154
1155         if (LK_CAN_WITNESS(flags))
1156                 WITNESS_CHECKORDER(&lk->lock_object, LOP_NEWORDER |
1157                     LOP_EXCLUSIVE, file, line, NULL);
1158         tid = (uintptr_t)curthread;
1159         if (atomic_cmpset_acq_ptr(&lk->lk_lock, LK_UNLOCKED, tid)) {
1160                 lockmgr_note_exclusive_acquire(lk, 0, 0, file, line,
1161                     flags);
1162                 return (0);
1163         }
1164
1165         return (lockmgr_xlock_hard(lk, flags, NULL, file, line, NULL));
1166 }
1167
1168 int
1169 lockmgr_unlock(struct lock *lk)
1170 {
1171         uintptr_t x, tid;
1172         const char *file;
1173         int line;
1174
1175         file = __FILE__;
1176         line = __LINE__;
1177
1178         _lockmgr_assert(lk, KA_LOCKED, file, line);
1179         x = lockmgr_read_value(lk);
1180         if (__predict_true(x & LK_SHARE) != 0) {
1181                 lockmgr_note_shared_release(lk, file, line);
1182                 if (lockmgr_sunlock_try(lk, &x)) {
1183                         LOCKSTAT_PROFILE_RELEASE_RWLOCK(lockmgr__release, lk, LOCKSTAT_READER);
1184                 } else {
1185                         return (lockmgr_sunlock_hard(lk, x, LK_RELEASE, NULL, file, line));
1186                 }
1187         } else {
1188                 tid = (uintptr_t)curthread;
1189                 lockmgr_note_exclusive_release(lk, file, line);
1190                 if (!lockmgr_recursed(lk) &&
1191                     atomic_cmpset_rel_ptr(&lk->lk_lock, tid, LK_UNLOCKED)) {
1192                         LOCKSTAT_PROFILE_RELEASE_RWLOCK(lockmgr__release, lk, LOCKSTAT_WRITER);
1193                 } else {
1194                         return (lockmgr_xunlock_hard(lk, x, LK_RELEASE, NULL, file, line));
1195                 }
1196         }
1197         return (0);
1198 }
1199
1200 int
1201 __lockmgr_args(struct lock *lk, u_int flags, struct lock_object *ilk,
1202     const char *wmesg, int pri, int timo, const char *file, int line)
1203 {
1204         GIANT_DECLARE;
1205         struct lockmgr_wait lwa;
1206         struct lock_class *class;
1207         const char *iwmesg;
1208         uintptr_t tid, v, x;
1209         u_int op, realexslp;
1210         int error, ipri, itimo, queue, wakeup_swapper;
1211 #ifdef LOCK_PROFILING
1212         uint64_t waittime = 0;
1213         int contested = 0;
1214 #endif
1215
1216         if (KERNEL_PANICKED())
1217                 return (0);
1218
1219         error = 0;
1220         tid = (uintptr_t)curthread;
1221         op = (flags & LK_TYPE_MASK);
1222         iwmesg = (wmesg == LK_WMESG_DEFAULT) ? lk->lock_object.lo_name : wmesg;
1223         ipri = (pri == LK_PRIO_DEFAULT) ? lk->lk_pri : pri;
1224         itimo = (timo == LK_TIMO_DEFAULT) ? lk->lk_timo : timo;
1225
1226         lwa.iwmesg = iwmesg;
1227         lwa.ipri = ipri;
1228         lwa.itimo = itimo;
1229
1230         MPASS((flags & ~LK_TOTAL_MASK) == 0);
1231         KASSERT((op & (op - 1)) == 0,
1232             ("%s: Invalid requested operation @ %s:%d", __func__, file, line));
1233         KASSERT((flags & (LK_NOWAIT | LK_SLEEPFAIL)) == 0 ||
1234             (op != LK_DOWNGRADE && op != LK_RELEASE),
1235             ("%s: Invalid flags in regard of the operation desired @ %s:%d",
1236             __func__, file, line));
1237         KASSERT((flags & LK_INTERLOCK) == 0 || ilk != NULL,
1238             ("%s: LK_INTERLOCK passed without valid interlock @ %s:%d",
1239             __func__, file, line));
1240         KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread),
1241             ("%s: idle thread %p on lockmgr %s @ %s:%d", __func__, curthread,
1242             lk->lock_object.lo_name, file, line));
1243
1244         class = (flags & LK_INTERLOCK) ? LOCK_CLASS(ilk) : NULL;
1245
1246         if (lk->lock_object.lo_flags & LK_NOSHARE) {
1247                 switch (op) {
1248                 case LK_SHARED:
1249                         op = LK_EXCLUSIVE;
1250                         break;
1251                 case LK_UPGRADE:
1252                 case LK_TRYUPGRADE:
1253                 case LK_DOWNGRADE:
1254                         _lockmgr_assert(lk, KA_XLOCKED | KA_NOTRECURSED,
1255                             file, line);
1256                         if (flags & LK_INTERLOCK)
1257                                 class->lc_unlock(ilk);
1258                         return (0);
1259                 }
1260         }
1261
1262         wakeup_swapper = 0;
1263         switch (op) {
1264         case LK_SHARED:
1265                 return (lockmgr_slock_hard(lk, flags, ilk, file, line, &lwa));
1266                 break;
1267         case LK_UPGRADE:
1268         case LK_TRYUPGRADE:
1269                 return (lockmgr_upgrade(lk, flags, ilk, file, line, &lwa));
1270                 break;
1271         case LK_EXCLUSIVE:
1272                 return (lockmgr_xlock_hard(lk, flags, ilk, file, line, &lwa));
1273                 break;
1274         case LK_DOWNGRADE:
1275                 _lockmgr_assert(lk, KA_XLOCKED, file, line);
1276                 WITNESS_DOWNGRADE(&lk->lock_object, 0, file, line);
1277
1278                 /*
1279                  * Panic if the lock is recursed.
1280                  */
1281                 if (lockmgr_xlocked(lk) && lockmgr_recursed(lk)) {
1282                         if (flags & LK_INTERLOCK)
1283                                 class->lc_unlock(ilk);
1284                         panic("%s: downgrade a recursed lockmgr %s @ %s:%d\n",
1285                             __func__, iwmesg, file, line);
1286                 }
1287                 TD_SLOCKS_INC(curthread);
1288
1289                 /*
1290                  * In order to preserve waiters flags, just spin.
1291                  */
1292                 for (;;) {
1293                         x = lockmgr_read_value(lk);
1294                         MPASS((x & LK_EXCLUSIVE_SPINNERS) == 0);
1295                         x &= LK_ALL_WAITERS;
1296                         if (atomic_cmpset_rel_ptr(&lk->lk_lock, tid | x,
1297                             LK_SHARERS_LOCK(1) | x))
1298                                 break;
1299                         cpu_spinwait();
1300                 }
1301                 LOCK_LOG_LOCK("XDOWNGRADE", &lk->lock_object, 0, 0, file, line);
1302                 LOCKSTAT_RECORD0(lockmgr__downgrade, lk);
1303                 break;
1304         case LK_RELEASE:
1305                 _lockmgr_assert(lk, KA_LOCKED, file, line);
1306                 x = lockmgr_read_value(lk);
1307
1308                 if (__predict_true(x & LK_SHARE) != 0) {
1309                         lockmgr_note_shared_release(lk, file, line);
1310                         return (lockmgr_sunlock_hard(lk, x, flags, ilk, file, line));
1311                 } else {
1312                         lockmgr_note_exclusive_release(lk, file, line);
1313                         return (lockmgr_xunlock_hard(lk, x, flags, ilk, file, line));
1314                 }
1315                 break;
1316         case LK_DRAIN:
1317                 if (LK_CAN_WITNESS(flags))
1318                         WITNESS_CHECKORDER(&lk->lock_object, LOP_NEWORDER |
1319                             LOP_EXCLUSIVE, file, line, flags & LK_INTERLOCK ?
1320                             ilk : NULL);
1321
1322                 /*
1323                  * Trying to drain a lock we already own will result in a
1324                  * deadlock.
1325                  */
1326                 if (lockmgr_xlocked(lk)) {
1327                         if (flags & LK_INTERLOCK)
1328                                 class->lc_unlock(ilk);
1329                         panic("%s: draining %s with the lock held @ %s:%d\n",
1330                             __func__, iwmesg, file, line);
1331                 }
1332
1333                 for (;;) {
1334                         if (lk->lk_lock == LK_UNLOCKED &&
1335                             atomic_cmpset_acq_ptr(&lk->lk_lock, LK_UNLOCKED, tid))
1336                                 break;
1337
1338 #ifdef HWPMC_HOOKS
1339                         PMC_SOFT_CALL( , , lock, failed);
1340 #endif
1341                         lock_profile_obtain_lock_failed(&lk->lock_object,
1342                             &contested, &waittime);
1343
1344                         /*
1345                          * If the lock is expected to not sleep just give up
1346                          * and return.
1347                          */
1348                         if (LK_TRYOP(flags)) {
1349                                 LOCK_LOG2(lk, "%s: %p fails the try operation",
1350                                     __func__, lk);
1351                                 error = EBUSY;
1352                                 break;
1353                         }
1354
1355                         /*
1356                          * Acquire the sleepqueue chain lock because we
1357                          * probabilly will need to manipulate waiters flags.
1358                          */
1359                         sleepq_lock(&lk->lock_object);
1360                         x = lockmgr_read_value(lk);
1361
1362                         /*
1363                          * if the lock has been released while we spun on
1364                          * the sleepqueue chain lock just try again.
1365                          */
1366                         if (x == LK_UNLOCKED) {
1367                                 sleepq_release(&lk->lock_object);
1368                                 continue;
1369                         }
1370
1371                         v = x & (LK_ALL_WAITERS | LK_EXCLUSIVE_SPINNERS);
1372                         if ((x & ~v) == LK_UNLOCKED) {
1373                                 v = (x & ~LK_EXCLUSIVE_SPINNERS);
1374
1375                                 /*
1376                                  * If interruptible sleeps left the exclusive
1377                                  * queue empty avoid a starvation for the
1378                                  * threads sleeping on the shared queue by
1379                                  * giving them precedence and cleaning up the
1380                                  * exclusive waiters bit anyway.
1381                                  * Please note that lk_exslpfail count may be
1382                                  * lying about the real number of waiters with
1383                                  * the LK_SLEEPFAIL flag on because they may
1384                                  * be used in conjunction with interruptible
1385                                  * sleeps so lk_exslpfail might be considered
1386                                  * an 'upper limit' bound, including the edge
1387                                  * cases.
1388                                  */
1389                                 if (v & LK_EXCLUSIVE_WAITERS) {
1390                                         queue = SQ_EXCLUSIVE_QUEUE;
1391                                         v &= ~LK_EXCLUSIVE_WAITERS;
1392                                 } else {
1393
1394                                         /*
1395                                          * Exclusive waiters sleeping with
1396                                          * LK_SLEEPFAIL on and using
1397                                          * interruptible sleeps/timeout may
1398                                          * have left spourious lk_exslpfail
1399                                          * counts on, so clean it up anyway.
1400                                          */
1401                                         MPASS(v & LK_SHARED_WAITERS);
1402                                         lk->lk_exslpfail = 0;
1403                                         queue = SQ_SHARED_QUEUE;
1404                                         v &= ~LK_SHARED_WAITERS;
1405                                 }
1406                                 if (queue == SQ_EXCLUSIVE_QUEUE) {
1407                                         realexslp =
1408                                             sleepq_sleepcnt(&lk->lock_object,
1409                                             SQ_EXCLUSIVE_QUEUE);
1410                                         if (lk->lk_exslpfail >= realexslp) {
1411                                                 lk->lk_exslpfail = 0;
1412                                                 queue = SQ_SHARED_QUEUE;
1413                                                 v &= ~LK_SHARED_WAITERS;
1414                                                 if (realexslp != 0) {
1415                                                         LOCK_LOG2(lk,
1416                                         "%s: %p has only LK_SLEEPFAIL sleepers",
1417                                                             __func__, lk);
1418                                                         LOCK_LOG2(lk,
1419                         "%s: %p waking up threads on the exclusive queue",
1420                                                             __func__, lk);
1421                                                         wakeup_swapper =
1422                                                             sleepq_broadcast(
1423                                                             &lk->lock_object,
1424                                                             SLEEPQ_LK, 0,
1425                                                             SQ_EXCLUSIVE_QUEUE);
1426                                                 }
1427                                         } else
1428                                                 lk->lk_exslpfail = 0;
1429                                 }
1430                                 if (!atomic_cmpset_ptr(&lk->lk_lock, x, v)) {
1431                                         sleepq_release(&lk->lock_object);
1432                                         continue;
1433                                 }
1434                                 LOCK_LOG3(lk,
1435                                 "%s: %p waking up all threads on the %s queue",
1436                                     __func__, lk, queue == SQ_SHARED_QUEUE ?
1437                                     "shared" : "exclusive");
1438                                 wakeup_swapper |= sleepq_broadcast(
1439                                     &lk->lock_object, SLEEPQ_LK, 0, queue);
1440
1441                                 /*
1442                                  * If shared waiters have been woken up we need
1443                                  * to wait for one of them to acquire the lock
1444                                  * before to set the exclusive waiters in
1445                                  * order to avoid a deadlock.
1446                                  */
1447                                 if (queue == SQ_SHARED_QUEUE) {
1448                                         for (v = lk->lk_lock;
1449                                             (v & LK_SHARE) && !LK_SHARERS(v);
1450                                             v = lk->lk_lock)
1451                                                 cpu_spinwait();
1452                                 }
1453                         }
1454
1455                         /*
1456                          * Try to set the LK_EXCLUSIVE_WAITERS flag.  If we
1457                          * fail, loop back and retry.
1458                          */
1459                         if ((x & LK_EXCLUSIVE_WAITERS) == 0) {
1460                                 if (!atomic_cmpset_ptr(&lk->lk_lock, x,
1461                                     x | LK_EXCLUSIVE_WAITERS)) {
1462                                         sleepq_release(&lk->lock_object);
1463                                         continue;
1464                                 }
1465                                 LOCK_LOG2(lk, "%s: %p set drain waiters flag",
1466                                     __func__, lk);
1467                         }
1468
1469                         /*
1470                          * As far as we have been unable to acquire the
1471                          * exclusive lock and the exclusive waiters flag
1472                          * is set, we will sleep.
1473                          */
1474                         if (flags & LK_INTERLOCK) {
1475                                 class->lc_unlock(ilk);
1476                                 flags &= ~LK_INTERLOCK;
1477                         }
1478                         GIANT_SAVE();
1479                         sleepq_add(&lk->lock_object, NULL, iwmesg, SLEEPQ_LK,
1480                             SQ_EXCLUSIVE_QUEUE);
1481                         sleepq_wait(&lk->lock_object, ipri & PRIMASK);
1482                         GIANT_RESTORE();
1483                         LOCK_LOG2(lk, "%s: %p resuming from the sleep queue",
1484                             __func__, lk);
1485                 }
1486
1487                 if (error == 0) {
1488                         lock_profile_obtain_lock_success(&lk->lock_object,
1489                             contested, waittime, file, line);
1490                         LOCK_LOG_LOCK("DRAIN", &lk->lock_object, 0,
1491                             lk->lk_recurse, file, line);
1492                         WITNESS_LOCK(&lk->lock_object, LOP_EXCLUSIVE |
1493                             LK_TRYWIT(flags), file, line);
1494                         TD_LOCKS_INC(curthread);
1495                         STACK_SAVE(lk);
1496                 }
1497                 break;
1498         default:
1499                 if (flags & LK_INTERLOCK)
1500                         class->lc_unlock(ilk);
1501                 panic("%s: unknown lockmgr request 0x%x\n", __func__, op);
1502         }
1503
1504         if (flags & LK_INTERLOCK)
1505                 class->lc_unlock(ilk);
1506         if (wakeup_swapper)
1507                 kick_proc0();
1508
1509         return (error);
1510 }
1511
1512 void
1513 _lockmgr_disown(struct lock *lk, const char *file, int line)
1514 {
1515         uintptr_t tid, x;
1516
1517         if (SCHEDULER_STOPPED())
1518                 return;
1519
1520         tid = (uintptr_t)curthread;
1521         _lockmgr_assert(lk, KA_XLOCKED, file, line);
1522
1523         /*
1524          * Panic if the lock is recursed.
1525          */
1526         if (lockmgr_xlocked(lk) && lockmgr_recursed(lk))
1527                 panic("%s: disown a recursed lockmgr @ %s:%d\n",
1528                     __func__,  file, line);
1529
1530         /*
1531          * If the owner is already LK_KERNPROC just skip the whole operation.
1532          */
1533         if (LK_HOLDER(lk->lk_lock) != tid)
1534                 return;
1535         lock_profile_release_lock(&lk->lock_object);
1536         LOCKSTAT_RECORD1(lockmgr__disown, lk, LOCKSTAT_WRITER);
1537         LOCK_LOG_LOCK("XDISOWN", &lk->lock_object, 0, 0, file, line);
1538         WITNESS_UNLOCK(&lk->lock_object, LOP_EXCLUSIVE, file, line);
1539         TD_LOCKS_DEC(curthread);
1540         STACK_SAVE(lk);
1541
1542         /*
1543          * In order to preserve waiters flags, just spin.
1544          */
1545         for (;;) {
1546                 x = lockmgr_read_value(lk);
1547                 MPASS((x & LK_EXCLUSIVE_SPINNERS) == 0);
1548                 x &= LK_ALL_WAITERS;
1549                 if (atomic_cmpset_rel_ptr(&lk->lk_lock, tid | x,
1550                     LK_KERNPROC | x))
1551                         return;
1552                 cpu_spinwait();
1553         }
1554 }
1555
1556 void
1557 lockmgr_printinfo(const struct lock *lk)
1558 {
1559         struct thread *td;
1560         uintptr_t x;
1561
1562         if (lk->lk_lock == LK_UNLOCKED)
1563                 printf("lock type %s: UNLOCKED\n", lk->lock_object.lo_name);
1564         else if (lk->lk_lock & LK_SHARE)
1565                 printf("lock type %s: SHARED (count %ju)\n",
1566                     lk->lock_object.lo_name,
1567                     (uintmax_t)LK_SHARERS(lk->lk_lock));
1568         else {
1569                 td = lockmgr_xholder(lk);
1570                 if (td == (struct thread *)LK_KERNPROC)
1571                         printf("lock type %s: EXCL by KERNPROC\n",
1572                             lk->lock_object.lo_name);
1573                 else
1574                         printf("lock type %s: EXCL by thread %p "
1575                             "(pid %d, %s, tid %d)\n", lk->lock_object.lo_name,
1576                             td, td->td_proc->p_pid, td->td_proc->p_comm,
1577                             td->td_tid);
1578         }
1579
1580         x = lk->lk_lock;
1581         if (x & LK_EXCLUSIVE_WAITERS)
1582                 printf(" with exclusive waiters pending\n");
1583         if (x & LK_SHARED_WAITERS)
1584                 printf(" with shared waiters pending\n");
1585         if (x & LK_EXCLUSIVE_SPINNERS)
1586                 printf(" with exclusive spinners pending\n");
1587
1588         STACK_PRINT(lk);
1589 }
1590
1591 int
1592 lockstatus(const struct lock *lk)
1593 {
1594         uintptr_t v, x;
1595         int ret;
1596
1597         ret = LK_SHARED;
1598         x = lockmgr_read_value(lk);
1599         v = LK_HOLDER(x);
1600
1601         if ((x & LK_SHARE) == 0) {
1602                 if (v == (uintptr_t)curthread || v == LK_KERNPROC)
1603                         ret = LK_EXCLUSIVE;
1604                 else
1605                         ret = LK_EXCLOTHER;
1606         } else if (x == LK_UNLOCKED)
1607                 ret = 0;
1608
1609         return (ret);
1610 }
1611
1612 #ifdef INVARIANT_SUPPORT
1613
1614 FEATURE(invariant_support,
1615     "Support for modules compiled with INVARIANTS option");
1616
1617 #ifndef INVARIANTS
1618 #undef  _lockmgr_assert
1619 #endif
1620
1621 void
1622 _lockmgr_assert(const struct lock *lk, int what, const char *file, int line)
1623 {
1624         int slocked = 0;
1625
1626         if (KERNEL_PANICKED())
1627                 return;
1628         switch (what) {
1629         case KA_SLOCKED:
1630         case KA_SLOCKED | KA_NOTRECURSED:
1631         case KA_SLOCKED | KA_RECURSED:
1632                 slocked = 1;
1633         case KA_LOCKED:
1634         case KA_LOCKED | KA_NOTRECURSED:
1635         case KA_LOCKED | KA_RECURSED:
1636 #ifdef WITNESS
1637
1638                 /*
1639                  * We cannot trust WITNESS if the lock is held in exclusive
1640                  * mode and a call to lockmgr_disown() happened.
1641                  * Workaround this skipping the check if the lock is held in
1642                  * exclusive mode even for the KA_LOCKED case.
1643                  */
1644                 if (slocked || (lk->lk_lock & LK_SHARE)) {
1645                         witness_assert(&lk->lock_object, what, file, line);
1646                         break;
1647                 }
1648 #endif
1649                 if (lk->lk_lock == LK_UNLOCKED ||
1650                     ((lk->lk_lock & LK_SHARE) == 0 && (slocked ||
1651                     (!lockmgr_xlocked(lk) && !lockmgr_disowned(lk)))))
1652                         panic("Lock %s not %slocked @ %s:%d\n",
1653                             lk->lock_object.lo_name, slocked ? "share" : "",
1654                             file, line);
1655
1656                 if ((lk->lk_lock & LK_SHARE) == 0) {
1657                         if (lockmgr_recursed(lk)) {
1658                                 if (what & KA_NOTRECURSED)
1659                                         panic("Lock %s recursed @ %s:%d\n",
1660                                             lk->lock_object.lo_name, file,
1661                                             line);
1662                         } else if (what & KA_RECURSED)
1663                                 panic("Lock %s not recursed @ %s:%d\n",
1664                                     lk->lock_object.lo_name, file, line);
1665                 }
1666                 break;
1667         case KA_XLOCKED:
1668         case KA_XLOCKED | KA_NOTRECURSED:
1669         case KA_XLOCKED | KA_RECURSED:
1670                 if (!lockmgr_xlocked(lk) && !lockmgr_disowned(lk))
1671                         panic("Lock %s not exclusively locked @ %s:%d\n",
1672                             lk->lock_object.lo_name, file, line);
1673                 if (lockmgr_recursed(lk)) {
1674                         if (what & KA_NOTRECURSED)
1675                                 panic("Lock %s recursed @ %s:%d\n",
1676                                     lk->lock_object.lo_name, file, line);
1677                 } else if (what & KA_RECURSED)
1678                         panic("Lock %s not recursed @ %s:%d\n",
1679                             lk->lock_object.lo_name, file, line);
1680                 break;
1681         case KA_UNLOCKED:
1682                 if (lockmgr_xlocked(lk) || lockmgr_disowned(lk))
1683                         panic("Lock %s exclusively locked @ %s:%d\n",
1684                             lk->lock_object.lo_name, file, line);
1685                 break;
1686         default:
1687                 panic("Unknown lockmgr assertion: %d @ %s:%d\n", what, file,
1688                     line);
1689         }
1690 }
1691 #endif
1692
1693 #ifdef DDB
1694 int
1695 lockmgr_chain(struct thread *td, struct thread **ownerp)
1696 {
1697         const struct lock *lk;
1698
1699         lk = td->td_wchan;
1700
1701         if (LOCK_CLASS(&lk->lock_object) != &lock_class_lockmgr)
1702                 return (0);
1703         db_printf("blocked on lockmgr %s", lk->lock_object.lo_name);
1704         if (lk->lk_lock & LK_SHARE)
1705                 db_printf("SHARED (count %ju)\n",
1706                     (uintmax_t)LK_SHARERS(lk->lk_lock));
1707         else
1708                 db_printf("EXCL\n");
1709         *ownerp = lockmgr_xholder(lk);
1710
1711         return (1);
1712 }
1713
1714 static void
1715 db_show_lockmgr(const struct lock_object *lock)
1716 {
1717         struct thread *td;
1718         const struct lock *lk;
1719
1720         lk = (const struct lock *)lock;
1721
1722         db_printf(" state: ");
1723         if (lk->lk_lock == LK_UNLOCKED)
1724                 db_printf("UNLOCKED\n");
1725         else if (lk->lk_lock & LK_SHARE)
1726                 db_printf("SLOCK: %ju\n", (uintmax_t)LK_SHARERS(lk->lk_lock));
1727         else {
1728                 td = lockmgr_xholder(lk);
1729                 if (td == (struct thread *)LK_KERNPROC)
1730                         db_printf("XLOCK: LK_KERNPROC\n");
1731                 else
1732                         db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1733                             td->td_tid, td->td_proc->p_pid,
1734                             td->td_proc->p_comm);
1735                 if (lockmgr_recursed(lk))
1736                         db_printf(" recursed: %d\n", lk->lk_recurse);
1737         }
1738         db_printf(" waiters: ");
1739         switch (lk->lk_lock & LK_ALL_WAITERS) {
1740         case LK_SHARED_WAITERS:
1741                 db_printf("shared\n");
1742                 break;
1743         case LK_EXCLUSIVE_WAITERS:
1744                 db_printf("exclusive\n");
1745                 break;
1746         case LK_ALL_WAITERS:
1747                 db_printf("shared and exclusive\n");
1748                 break;
1749         default:
1750                 db_printf("none\n");
1751         }
1752         db_printf(" spinners: ");
1753         if (lk->lk_lock & LK_EXCLUSIVE_SPINNERS)
1754                 db_printf("exclusive\n");
1755         else
1756                 db_printf("none\n");
1757 }
1758 #endif