Merge branch 'master' of ssh://crater.dragonflybsd.org/repository/git/dragonfly
[dragonfly.git] / sys / kern / lwkt_token.c
1 /*
2  * Copyright (c) 2003,2004,2009 The DragonFly Project.  All rights reserved.
3  * 
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
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  * 
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  * 
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 /*
36  * lwkt_token - Implement soft token locks.
37  *
38  * Tokens are locks which serialize a thread only while the thread is
39  * running.  If the thread blocks all tokens are released, then reacquired
40  * when the thread resumes.
41  *
42  * This implementation requires no critical sections or spin locks, but
43  * does use atomic_cmpset_ptr().
44  *
45  * Tokens may be recursively acquired by the same thread.  However the
46  * caller must be sure to release such tokens in reverse order.
47  */
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/kernel.h>
51 #include <sys/proc.h>
52 #include <sys/rtprio.h>
53 #include <sys/queue.h>
54 #include <sys/sysctl.h>
55 #include <sys/ktr.h>
56 #include <sys/kthread.h>
57 #include <machine/cpu.h>
58 #include <sys/lock.h>
59 #include <sys/caps.h>
60 #include <sys/spinlock.h>
61
62 #include <sys/thread2.h>
63 #include <sys/spinlock2.h>
64 #include <sys/mplock2.h>
65
66 #include <vm/vm.h>
67 #include <vm/vm_param.h>
68 #include <vm/vm_kern.h>
69 #include <vm/vm_object.h>
70 #include <vm/vm_page.h>
71 #include <vm/vm_map.h>
72 #include <vm/vm_pager.h>
73 #include <vm/vm_extern.h>
74 #include <vm/vm_zone.h>
75
76 #include <machine/stdarg.h>
77 #include <machine/smp.h>
78
79 #ifndef LWKT_NUM_POOL_TOKENS
80 #define LWKT_NUM_POOL_TOKENS    1024    /* power of 2 */
81 #endif
82 #define LWKT_MASK_POOL_TOKENS   (LWKT_NUM_POOL_TOKENS - 1)
83
84 static lwkt_token       pool_tokens[LWKT_NUM_POOL_TOKENS];
85
86 #define TOKEN_STRING    "REF=%p TOK=%p TD=%p"
87 #define CONTENDED_STRING        "REF=%p TOK=%p TD=%p (contention started)"
88 #define UNCONTENDED_STRING      "REF=%p TOK=%p TD=%p (contention stopped)"
89 #if !defined(KTR_TOKENS)
90 #define KTR_TOKENS      KTR_ALL
91 #endif
92
93 KTR_INFO_MASTER(tokens);
94 KTR_INFO(KTR_TOKENS, tokens, fail, 0, TOKEN_STRING, sizeof(void *) * 3);
95 KTR_INFO(KTR_TOKENS, tokens, succ, 1, TOKEN_STRING, sizeof(void *) * 3);
96 #if 0
97 KTR_INFO(KTR_TOKENS, tokens, release, 2, TOKEN_STRING, sizeof(void *) * 3);
98 KTR_INFO(KTR_TOKENS, tokens, remote, 3, TOKEN_STRING, sizeof(void *) * 3);
99 KTR_INFO(KTR_TOKENS, tokens, reqremote, 4, TOKEN_STRING, sizeof(void *) * 3);
100 KTR_INFO(KTR_TOKENS, tokens, reqfail, 5, TOKEN_STRING, sizeof(void *) * 3);
101 KTR_INFO(KTR_TOKENS, tokens, drain, 6, TOKEN_STRING, sizeof(void *) * 3);
102 KTR_INFO(KTR_TOKENS, tokens, contention_start, 7, CONTENDED_STRING, sizeof(void *) * 3);
103 KTR_INFO(KTR_TOKENS, tokens, contention_stop, 7, UNCONTENDED_STRING, sizeof(void *) * 3);
104 #endif
105
106 #define logtoken(name, ref)                                             \
107         KTR_LOG(tokens_ ## name, ref, ref->tr_tok, curthread)
108
109 /*
110  * Global tokens.  These replace the MP lock for major subsystem locking.
111  * These tokens are initially used to lockup both global and individual
112  * operations.
113  *
114  * Once individual structures get their own locks these tokens are used
115  * only to protect global lists & other variables and to interlock
116  * allocations and teardowns and such.
117  *
118  * The UP initializer causes token acquisition to also acquire the MP lock
119  * for maximum compatibility.  The feature may be enabled and disabled at
120  * any time, the MP state is copied to the tokref when the token is acquired
121  * and will not race against sysctl changes.
122  */
123 struct lwkt_token mp_token = LWKT_TOKEN_MP_INITIALIZER(mp_token);
124 struct lwkt_token pmap_token = LWKT_TOKEN_UP_INITIALIZER(pmap_token);
125 struct lwkt_token dev_token = LWKT_TOKEN_UP_INITIALIZER(dev_token);
126 struct lwkt_token vm_token = LWKT_TOKEN_UP_INITIALIZER(vm_token);
127 struct lwkt_token vmspace_token = LWKT_TOKEN_UP_INITIALIZER(vmspace_token);
128 struct lwkt_token kvm_token = LWKT_TOKEN_UP_INITIALIZER(kvm_token);
129 struct lwkt_token proc_token = LWKT_TOKEN_UP_INITIALIZER(proc_token);
130 struct lwkt_token tty_token = LWKT_TOKEN_UP_INITIALIZER(tty_token);
131 struct lwkt_token vnode_token = LWKT_TOKEN_UP_INITIALIZER(vnode_token);
132 struct lwkt_token vmobj_token = LWKT_TOKEN_UP_INITIALIZER(vmobj_token);
133
134 SYSCTL_INT(_lwkt, OID_AUTO, pmap_mpsafe, CTLFLAG_RW,
135     &pmap_token.t_flags, 0, "Require MP lock for pmap_token");
136 SYSCTL_INT(_lwkt, OID_AUTO, dev_mpsafe, CTLFLAG_RW,
137     &dev_token.t_flags, 0, "Require MP lock for dev_token");
138 SYSCTL_INT(_lwkt, OID_AUTO, vm_mpsafe, CTLFLAG_RW,
139     &vm_token.t_flags, 0, "Require MP lock for vm_token");
140 SYSCTL_INT(_lwkt, OID_AUTO, vmspace_mpsafe, CTLFLAG_RW,
141     &vmspace_token.t_flags, 0, "Require MP lock for vmspace_token");
142 SYSCTL_INT(_lwkt, OID_AUTO, kvm_mpsafe, CTLFLAG_RW,
143     &kvm_token.t_flags, 0, "Require MP lock for kvm_token");
144 SYSCTL_INT(_lwkt, OID_AUTO, proc_mpsafe, CTLFLAG_RW,
145     &proc_token.t_flags, 0, "Require MP lock for proc_token");
146 SYSCTL_INT(_lwkt, OID_AUTO, tty_mpsafe, CTLFLAG_RW,
147     &tty_token.t_flags, 0, "Require MP lock for tty_token");
148 SYSCTL_INT(_lwkt, OID_AUTO, vnode_mpsafe, CTLFLAG_RW,
149     &vnode_token.t_flags, 0, "Require MP lock for vnode_token");
150 SYSCTL_INT(_lwkt, OID_AUTO, vmobj_mpsafe, CTLFLAG_RW,
151     &vmobj_token.t_flags, 0, "Require MP lock for vmobj_token");
152
153 /*
154  * The collision count is bumped every time the LWKT scheduler fails
155  * to acquire needed tokens in addition to a normal lwkt_gettoken()
156  * stall.
157  */
158 SYSCTL_LONG(_lwkt, OID_AUTO, mp_collisions, CTLFLAG_RW,
159     &mp_token.t_collisions, 0, "Collision counter of mp_token");
160 SYSCTL_LONG(_lwkt, OID_AUTO, pmap_collisions, CTLFLAG_RW,
161     &pmap_token.t_collisions, 0, "Collision counter of pmap_token");
162 SYSCTL_LONG(_lwkt, OID_AUTO, dev_collisions, CTLFLAG_RW,
163     &dev_token.t_collisions, 0, "Collision counter of dev_token");
164 SYSCTL_LONG(_lwkt, OID_AUTO, vm_collisions, CTLFLAG_RW,
165     &vm_token.t_collisions, 0, "Collision counter of vm_token");
166 SYSCTL_LONG(_lwkt, OID_AUTO, vmspace_collisions, CTLFLAG_RW,
167     &vmspace_token.t_collisions, 0, "Collision counter of vmspace_token");
168 SYSCTL_LONG(_lwkt, OID_AUTO, kvm_collisions, CTLFLAG_RW,
169     &kvm_token.t_collisions, 0, "Collision counter of kvm_token");
170 SYSCTL_LONG(_lwkt, OID_AUTO, proc_collisions, CTLFLAG_RW,
171     &proc_token.t_collisions, 0, "Collision counter of proc_token");
172 SYSCTL_LONG(_lwkt, OID_AUTO, tty_collisions, CTLFLAG_RW,
173     &tty_token.t_collisions, 0, "Collision counter of tty_token");
174 SYSCTL_LONG(_lwkt, OID_AUTO, vnode_collisions, CTLFLAG_RW,
175     &vnode_token.t_collisions, 0, "Collision counter of vnode_token");
176
177 #ifdef SMP
178 /*
179  * Acquire the initial mplock
180  *
181  * (low level boot only)
182  */
183 void
184 cpu_get_initial_mplock(void)
185 {
186         KKASSERT(mp_token.t_ref == NULL);
187         if (lwkt_trytoken(&mp_token) == FALSE)
188                 panic("cpu_get_initial_mplock");
189 }
190 #endif
191
192 /*
193  * Return a pool token given an address
194  */
195 static __inline
196 lwkt_token_t
197 _lwkt_token_pool_lookup(void *ptr)
198 {
199         int i;
200
201         i = ((int)(intptr_t)ptr >> 2) ^ ((int)(intptr_t)ptr >> 12);
202         return(&pool_tokens[i & LWKT_MASK_POOL_TOKENS]);
203 }
204
205 /*
206  * Initialize a tokref_t prior to making it visible in the thread's
207  * token array.
208  *
209  * As an optimization we set the MPSAFE flag if the thread is already
210  * holding the mp_token.  This bypasses unncessary calls to get_mplock() and
211  * rel_mplock() on tokens which are not normally MPSAFE when the thread
212  * is already holding the MP lock.
213  */
214 static __inline
215 intptr_t
216 _lwkt_tok_flags(lwkt_token_t tok, thread_t td)
217 {
218         intptr_t flags;
219
220         /*
221          * tok->t_flags can change out from under us, make sure we have
222          * a local copy.
223          */
224         flags = tok->t_flags;
225         cpu_ccfence();
226 #ifdef SMP
227         if ((flags & LWKT_TOKEN_MPSAFE) == 0 &&
228             _lwkt_token_held(&mp_token, td)) {
229                 return (flags | LWKT_TOKEN_MPSAFE);
230         } else {
231                 return (flags);
232         }
233 #else
234         return (flags | LWKT_TOKEN_MPSAFE);
235 #endif
236 }
237
238 static __inline
239 void
240 _lwkt_tokref_init(lwkt_tokref_t ref, lwkt_token_t tok, thread_t td,
241                   intptr_t flags)
242 {
243         ref->tr_tok = tok;
244         ref->tr_owner = td;
245         ref->tr_flags = flags;
246 }
247
248 #ifdef SMP
249 /*
250  * Force a LWKT reschedule on the target cpu when a requested token
251  * becomes available.
252  */
253 static
254 void
255 lwkt_reltoken_mask_remote(void *arg, int arg2, struct intrframe *frame)
256 {
257         need_lwkt_resched();
258 }
259 #endif
260
261 static __inline
262 void
263 _lwkt_reltoken_mask(lwkt_token_t tok)
264 {
265 #ifdef SMP
266         cpumask_t mask;
267
268         while ((mask = tok->t_collmask) != 0) {
269                 if (atomic_cmpset_cpumask(&tok->t_collmask, mask, 0)) {
270                         lwkt_send_ipiq3_mask(mask, lwkt_reltoken_mask_remote,
271                                              NULL, 0);
272                         break;
273                 }
274         }
275 #endif
276 }
277
278 /*
279  * Obtain all the tokens required by the specified thread on the current
280  * cpu, return 0 on failure and non-zero on success.  If a failure occurs
281  * any partially acquired tokens will be released prior to return.
282  *
283  * lwkt_getalltokens is called by the LWKT scheduler to acquire all
284  * tokens that the thread had acquired prior to going to sleep.
285  *
286  * The scheduler is responsible for maintaining the MP lock count, so
287  * we don't need to deal with tr_flags here.  We also do not do any
288  * logging here.  The logging done by lwkt_gettoken() is plenty good
289  * enough to get a feel for it.
290  *
291  * Called from a critical section.
292  */
293 int
294 lwkt_getalltokens(thread_t td)
295 {
296         lwkt_tokref_t scan;
297         lwkt_tokref_t ref;
298         lwkt_token_t tok;
299
300         /*
301          * Acquire tokens in forward order, assign or validate tok->t_ref.
302          */
303         for (scan = &td->td_toks_base; scan < td->td_toks_stop; ++scan) {
304                 tok = scan->tr_tok;
305                 for (;;) {
306                         /*
307                          * Try to acquire the token if we do not already have
308                          * it.
309                          *
310                          * NOTE: If atomic_cmpset_ptr() fails we have to
311                          *       loop and try again.  It just means we
312                          *       lost a cpu race.
313                          */
314                         ref = tok->t_ref;
315                         if (ref == NULL) {
316                                 if (atomic_cmpset_ptr(&tok->t_ref, NULL, scan))
317                                         break;
318                                 continue;
319                         }
320
321                         /*
322                          * Test if ref is already recursively held by this
323                          * thread.  We cannot safely dereference tok->t_ref
324                          * (it might belong to another thread and is thus
325                          * unstable), but we don't have to. We can simply
326                          * range-check it.
327                          */
328                         if (ref >= &td->td_toks_base && ref < td->td_toks_stop)
329                                 break;
330
331 #ifdef SMP
332                         /*
333                          * Otherwise we failed to acquire all the tokens.
334                          * Undo and return.  We have to try once more after
335                          * setting cpumask to cover possible races.
336                          */
337                         atomic_set_cpumask(&tok->t_collmask,
338                                            td->td_gd->gd_cpumask);
339                         if (atomic_cmpset_ptr(&tok->t_ref, NULL, scan)) {
340                                 atomic_clear_cpumask(&tok->t_collmask,
341                                                      td->td_gd->gd_cpumask);
342                                 break;
343                         }
344 #endif
345                         td->td_wmesg = tok->t_desc;
346                         atomic_add_long(&tok->t_collisions, 1);
347                         lwkt_relalltokens(td);
348                         return(FALSE);
349                 }
350         }
351         return (TRUE);
352 }
353
354 /*
355  * Release all tokens owned by the specified thread on the current cpu.
356  *
357  * This code is really simple.  Even in cases where we own all the tokens
358  * note that t_ref may not match the scan for recursively held tokens,
359  * or for the case where a lwkt_getalltokens() failed.
360  *
361  * The scheduler is responsible for maintaining the MP lock count, so
362  * we don't need to deal with tr_flags here.
363  * 
364  * Called from a critical section.
365  */
366 void
367 lwkt_relalltokens(thread_t td)
368 {
369         lwkt_tokref_t scan;
370         lwkt_token_t tok;
371
372         for (scan = &td->td_toks_base; scan < td->td_toks_stop; ++scan) {
373                 tok = scan->tr_tok;
374                 if (tok->t_ref == scan) {
375                         tok->t_ref = NULL;
376                         _lwkt_reltoken_mask(tok);
377                 }
378         }
379 }
380
381 /*
382  * Token acquisition helper function.  The caller must have already
383  * made nref visible by adjusting td_toks_stop and will be responsible
384  * for the disposition of nref on either success or failure.
385  *
386  * When acquiring tokens recursively we want tok->t_ref to point to
387  * the outer (first) acquisition so it gets cleared only on the last
388  * release.
389  */
390 static __inline
391 int
392 _lwkt_trytokref2(lwkt_tokref_t nref, thread_t td, int blocking)
393 {
394         lwkt_token_t tok;
395         lwkt_tokref_t ref;
396
397         /*
398          * Make sure the compiler does not reorder prior instructions
399          * beyond this demark.
400          */
401         cpu_ccfence();
402
403         /*
404          * Attempt to gain ownership
405          */
406         tok = nref->tr_tok;
407         for (;;) {
408                 /*
409                  * Try to acquire the token if we do not already have
410                  * it.  This is not allowed if we are in a hard code
411                  * section (because it 'might' have blocked).
412                  */
413                 ref = tok->t_ref;
414                 if (ref == NULL) {
415                         KASSERT((blocking == 0 ||
416                                 td->td_gd->gd_intr_nesting_level == 0 ||
417                                 panic_cpu_gd == mycpu),
418                                 ("Attempt to acquire token %p not already "
419                                  "held in hard code section", tok));
420
421                         /*
422                          * NOTE: If atomic_cmpset_ptr() fails we have to
423                          *       loop and try again.  It just means we
424                          *       lost a cpu race.
425                          */
426                         if (atomic_cmpset_ptr(&tok->t_ref, NULL, nref))
427                                 return (TRUE);
428                         continue;
429                 }
430
431                 /*
432                  * Test if ref is already recursively held by this
433                  * thread.  We cannot safely dereference tok->t_ref
434                  * (it might belong to another thread and is thus
435                  * unstable), but we don't have to. We can simply
436                  * range-check it.
437                  *
438                  * It is ok to acquire a token that is already held
439                  * by the current thread when in a hard code section.
440                  */
441                 if (ref >= &td->td_toks_base && ref < td->td_toks_stop)
442                         return(TRUE);
443
444                 /*
445                  * Otherwise we failed, and it is not ok to attempt to
446                  * acquire a token in a hard code section.
447                  */
448                 KASSERT((blocking == 0 ||
449                         td->td_gd->gd_intr_nesting_level == 0),
450                         ("Attempt to acquire token %p not already "
451                          "held in hard code section", tok));
452
453                 return(FALSE);
454         }
455 }
456
457 /*
458  * Get a serializing token.  This routine can block.
459  */
460 void
461 lwkt_gettoken(lwkt_token_t tok)
462 {
463         thread_t td = curthread;
464         lwkt_tokref_t ref;
465         intptr_t flags;
466
467         flags = _lwkt_tok_flags(tok, td);
468         if ((flags & LWKT_TOKEN_MPSAFE) == 0)
469                 get_mplock();
470
471         ref = td->td_toks_stop;
472         KKASSERT(ref < &td->td_toks_end);
473         ++td->td_toks_stop;
474         cpu_ccfence();
475         _lwkt_tokref_init(ref, tok, td, flags);
476
477         if (_lwkt_trytokref2(ref, td, 1) == FALSE) {
478                 /*
479                  * Give up running if we can't acquire the token right now.
480                  *
481                  * Since the tokref is already active the scheduler now
482                  * takes care of acquisition, so we need only call
483                  * lwkt_switch().
484                  *
485                  * Since we failed this was not a recursive token so upon
486                  * return tr_tok->t_ref should be assigned to this specific
487                  * ref.
488                  */
489 #ifdef SMP
490                 atomic_set_cpumask(&tok->t_collmask, td->td_gd->gd_cpumask);
491                 if (atomic_cmpset_ptr(&tok->t_ref, NULL, ref)) {
492                         atomic_clear_cpumask(&tok->t_collmask,
493                                              td->td_gd->gd_cpumask);
494                         return;
495                 }
496 #endif
497                 td->td_wmesg = tok->t_desc;
498                 atomic_add_long(&tok->t_collisions, 1);
499                 logtoken(fail, ref);
500                 lwkt_switch();
501                 logtoken(succ, ref);
502                 KKASSERT(tok->t_ref == ref);
503         }
504 }
505
506 void
507 lwkt_gettoken_hard(lwkt_token_t tok)
508 {
509         thread_t td = curthread;
510         lwkt_tokref_t ref;
511         intptr_t flags;
512
513         flags = _lwkt_tok_flags(tok, td);
514         if ((flags & LWKT_TOKEN_MPSAFE) == 0)
515                 get_mplock();
516
517         ref = td->td_toks_stop;
518         KKASSERT(ref < &td->td_toks_end);
519         ++td->td_toks_stop;
520         cpu_ccfence();
521         _lwkt_tokref_init(ref, tok, td, flags);
522
523         if (_lwkt_trytokref2(ref, td, 1) == FALSE) {
524                 /*
525                  * Give up running if we can't acquire the token right now.
526                  *
527                  * Since the tokref is already active the scheduler now
528                  * takes care of acquisition, so we need only call
529                  * lwkt_switch().
530                  *
531                  * Since we failed this was not a recursive token so upon
532                  * return tr_tok->t_ref should be assigned to this specific
533                  * ref.
534                  */
535 #ifdef SMP
536                 atomic_set_cpumask(&tok->t_collmask, td->td_gd->gd_cpumask);
537                 if (atomic_cmpset_ptr(&tok->t_ref, NULL, ref)) {
538                         atomic_clear_cpumask(&tok->t_collmask,
539                                              td->td_gd->gd_cpumask);
540                         goto success;
541                 }
542 #endif
543                 td->td_wmesg = tok->t_desc;
544                 atomic_add_long(&tok->t_collisions, 1);
545                 logtoken(fail, ref);
546                 lwkt_switch();
547                 logtoken(succ, ref);
548                 KKASSERT(tok->t_ref == ref);
549         }
550 #ifdef SMP
551 success:
552 #endif
553         crit_enter_hard_gd(td->td_gd);
554 }
555
556 lwkt_token_t
557 lwkt_getpooltoken(void *ptr)
558 {
559         thread_t td = curthread;
560         lwkt_token_t tok;
561         lwkt_tokref_t ref;
562         intptr_t flags;
563
564         tok = _lwkt_token_pool_lookup(ptr);
565         flags = _lwkt_tok_flags(tok, td);
566         if ((flags & LWKT_TOKEN_MPSAFE) == 0)
567                 get_mplock();
568
569         ref = td->td_toks_stop;
570         KKASSERT(ref < &td->td_toks_end);
571         ++td->td_toks_stop;
572         cpu_ccfence();
573         _lwkt_tokref_init(ref, tok, td, flags);
574
575         if (_lwkt_trytokref2(ref, td, 1) == FALSE) {
576                 /*
577                  * Give up running if we can't acquire the token right now.
578                  *
579                  * Since the tokref is already active the scheduler now
580                  * takes care of acquisition, so we need only call
581                  * lwkt_switch().
582                  *
583                  * Since we failed this was not a recursive token so upon
584                  * return tr_tok->t_ref should be assigned to this specific
585                  * ref.
586                  */
587 #ifdef SMP
588                 atomic_set_cpumask(&tok->t_collmask, td->td_gd->gd_cpumask);
589                 if (atomic_cmpset_ptr(&tok->t_ref, NULL, ref)) {
590                         atomic_clear_cpumask(&tok->t_collmask,
591                                              td->td_gd->gd_cpumask);
592                         goto success;
593                 }
594 #endif
595                 td->td_wmesg = tok->t_desc;
596                 atomic_add_long(&tok->t_collisions, 1);
597                 logtoken(fail, ref);
598                 lwkt_switch();
599                 logtoken(succ, ref);
600                 KKASSERT(tok->t_ref == ref);
601         }
602 #ifdef SMP
603 success:
604 #endif
605         return(tok);
606 }
607
608 /*
609  * Attempt to acquire a token, return TRUE on success, FALSE on failure.
610  */
611 int
612 lwkt_trytoken(lwkt_token_t tok)
613 {
614         thread_t td = curthread;
615         lwkt_tokref_t ref;
616         intptr_t flags;
617
618         flags = _lwkt_tok_flags(tok, td);
619         if ((flags & LWKT_TOKEN_MPSAFE) == 0) {
620                 if (try_mplock() == 0)
621                         return (FALSE);
622         }
623
624         ref = td->td_toks_stop;
625         KKASSERT(ref < &td->td_toks_end);
626         ++td->td_toks_stop;
627         cpu_ccfence();
628         _lwkt_tokref_init(ref, tok, td, flags);
629
630         if (_lwkt_trytokref2(ref, td, 0) == FALSE) {
631                 /*
632                  * Cleanup, deactivate the failed token.
633                  */
634                 if ((ref->tr_flags & LWKT_TOKEN_MPSAFE) == 0) {
635                         cpu_ccfence();
636                         --td->td_toks_stop;
637                         cpu_ccfence();
638                         rel_mplock();
639                 } else {
640                         cpu_ccfence();
641                         --td->td_toks_stop;
642                 }
643                 return (FALSE);
644         }
645         return (TRUE);
646 }
647
648 /*
649  * Release a serializing token.
650  *
651  * WARNING!  All tokens must be released in reverse order.  This will be
652  *           asserted.
653  */
654 void
655 lwkt_reltoken(lwkt_token_t tok)
656 {
657         thread_t td = curthread;
658         lwkt_tokref_t ref;
659
660         /*
661          * Remove ref from thread token list and assert that it matches
662          * the token passed in.  Tokens must be released in reverse order.
663          */
664         ref = td->td_toks_stop - 1;
665         KKASSERT(ref >= &td->td_toks_base && ref->tr_tok == tok);
666
667         /*
668          * Only clear the token if it matches ref.  If ref was a recursively
669          * acquired token it may not match.  Then adjust td_toks_stop.
670          *
671          * Some comparisons must be run prior to adjusting td_toks_stop
672          * to avoid racing against a fast interrupt/ ipi which tries to
673          * acquire a token.
674          *
675          * We must also be absolutely sure that the compiler does not
676          * reorder the clearing of t_ref and the adjustment of td_toks_stop,
677          * or reorder the adjustment of td_toks_stop against the conditional.
678          *
679          * NOTE: The mplock is a token also so sequencing is a bit complex.
680          */
681         if (tok->t_ref == ref) {
682                 tok->t_ref = NULL;
683                 _lwkt_reltoken_mask(tok);
684         }
685         cpu_sfence();
686         if ((ref->tr_flags & LWKT_TOKEN_MPSAFE) == 0) {
687                 cpu_ccfence();
688                 td->td_toks_stop = ref;
689                 cpu_ccfence();
690                 rel_mplock();
691         } else {
692                 cpu_ccfence();
693                 td->td_toks_stop = ref;
694                 cpu_ccfence();
695         }
696         KKASSERT(tok->t_ref != ref);
697 }
698
699 void
700 lwkt_reltoken_hard(lwkt_token_t tok)
701 {
702         lwkt_reltoken(tok);
703         crit_exit_hard();
704 }
705
706 /*
707  * It is faster for users of lwkt_getpooltoken() to use the returned
708  * token and just call lwkt_reltoken(), but for convenience we provide
709  * this function which looks the token up based on the ident.
710  */
711 void
712 lwkt_relpooltoken(void *ptr)
713 {
714         lwkt_token_t tok = _lwkt_token_pool_lookup(ptr);
715         lwkt_reltoken(tok);
716 }
717
718 /*
719  * Return a count of the number of token refs the thread has to the
720  * specified token, whether it currently owns the token or not.
721  */
722 int
723 lwkt_cnttoken(lwkt_token_t tok, thread_t td)
724 {
725         lwkt_tokref_t scan;
726         int count = 0;
727
728         for (scan = &td->td_toks_base; scan < td->td_toks_stop; ++scan) {
729                 if (scan->tr_tok == tok)
730                         ++count;
731         }
732         return(count);
733 }
734
735
736 /*
737  * Pool tokens are used to provide a type-stable serializing token
738  * pointer that does not race against disappearing data structures.
739  *
740  * This routine is called in early boot just after we setup the BSP's
741  * globaldata structure.
742  */
743 void
744 lwkt_token_pool_init(void)
745 {
746         int i;
747
748         for (i = 0; i < LWKT_NUM_POOL_TOKENS; ++i)
749                 lwkt_token_init(&pool_tokens[i], 1, "pool");
750 }
751
752 lwkt_token_t
753 lwkt_token_pool_lookup(void *ptr)
754 {
755         return (_lwkt_token_pool_lookup(ptr));
756 }
757
758 /*
759  * Initialize a token.  If mpsafe is 0, the MP lock is acquired before
760  * acquiring the token and released after releasing the token.
761  */
762 void
763 lwkt_token_init(lwkt_token_t tok, int mpsafe, const char *desc)
764 {
765         tok->t_ref = NULL;
766         tok->t_flags = mpsafe ? LWKT_TOKEN_MPSAFE : 0;
767         tok->t_collisions = 0;
768         tok->t_collmask = 0;
769         tok->t_desc = desc;
770 }
771
772 void
773 lwkt_token_uninit(lwkt_token_t tok)
774 {
775         /* empty */
776 }
777
778 #if 0
779 int
780 lwkt_token_is_stale(lwkt_tokref_t ref)
781 {
782         lwkt_token_t tok = ref->tr_tok;
783
784         KKASSERT(tok->t_owner == curthread && ref->tr_state == 1 &&
785                  tok->t_count > 0);
786
787         /* Token is not stale */
788         if (tok->t_lastowner == tok->t_owner)
789                 return (FALSE);
790
791         /*
792          * The token is stale. Reset to not stale so that the next call to
793          * lwkt_token_is_stale will return "not stale" unless the token
794          * was acquired in-between by another thread.
795          */
796         tok->t_lastowner = tok->t_owner;
797         return (TRUE);
798 }
799 #endif