kernel - Major vm_page, lwkt thread, and other changes
[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 extern int lwkt_sched_debug;
80
81 #ifndef LWKT_NUM_POOL_TOKENS
82 #define LWKT_NUM_POOL_TOKENS    4001    /* prime number */
83 #endif
84
85 static lwkt_token       pool_tokens[LWKT_NUM_POOL_TOKENS];
86
87 #define TOKEN_STRING    "REF=%p TOK=%p TD=%p"
88 #define CONTENDED_STRING        "REF=%p TOK=%p TD=%p (contention started)"
89 #define UNCONTENDED_STRING      "REF=%p TOK=%p TD=%p (contention stopped)"
90 #if !defined(KTR_TOKENS)
91 #define KTR_TOKENS      KTR_ALL
92 #endif
93
94 KTR_INFO_MASTER(tokens);
95 KTR_INFO(KTR_TOKENS, tokens, fail, 0, TOKEN_STRING, sizeof(void *) * 3);
96 KTR_INFO(KTR_TOKENS, tokens, succ, 1, TOKEN_STRING, sizeof(void *) * 3);
97 #if 0
98 KTR_INFO(KTR_TOKENS, tokens, release, 2, TOKEN_STRING, sizeof(void *) * 3);
99 KTR_INFO(KTR_TOKENS, tokens, remote, 3, TOKEN_STRING, sizeof(void *) * 3);
100 KTR_INFO(KTR_TOKENS, tokens, reqremote, 4, TOKEN_STRING, sizeof(void *) * 3);
101 KTR_INFO(KTR_TOKENS, tokens, reqfail, 5, TOKEN_STRING, sizeof(void *) * 3);
102 KTR_INFO(KTR_TOKENS, tokens, drain, 6, TOKEN_STRING, sizeof(void *) * 3);
103 KTR_INFO(KTR_TOKENS, tokens, contention_start, 7, CONTENDED_STRING, sizeof(void *) * 3);
104 KTR_INFO(KTR_TOKENS, tokens, contention_stop, 7, UNCONTENDED_STRING, sizeof(void *) * 3);
105 #endif
106
107 #define logtoken(name, ref)                                             \
108         KTR_LOG(tokens_ ## name, ref, ref->tr_tok, curthread)
109
110 /*
111  * Global tokens.  These replace the MP lock for major subsystem locking.
112  * These tokens are initially used to lockup both global and individual
113  * operations.
114  *
115  * Once individual structures get their own locks these tokens are used
116  * only to protect global lists & other variables and to interlock
117  * allocations and teardowns and such.
118  *
119  * The UP initializer causes token acquisition to also acquire the MP lock
120  * for maximum compatibility.  The feature may be enabled and disabled at
121  * any time, the MP state is copied to the tokref when the token is acquired
122  * and will not race against sysctl changes.
123  */
124 struct lwkt_token mp_token = LWKT_TOKEN_INITIALIZER(mp_token);
125 struct lwkt_token pmap_token = LWKT_TOKEN_INITIALIZER(pmap_token);
126 struct lwkt_token dev_token = LWKT_TOKEN_INITIALIZER(dev_token);
127 struct lwkt_token vm_token = LWKT_TOKEN_INITIALIZER(vm_token);
128 struct lwkt_token vmspace_token = LWKT_TOKEN_INITIALIZER(vmspace_token);
129 struct lwkt_token kvm_token = LWKT_TOKEN_INITIALIZER(kvm_token);
130 struct lwkt_token proc_token = LWKT_TOKEN_INITIALIZER(proc_token);
131 struct lwkt_token tty_token = LWKT_TOKEN_INITIALIZER(tty_token);
132 struct lwkt_token vnode_token = LWKT_TOKEN_INITIALIZER(vnode_token);
133 struct lwkt_token vmobj_token = LWKT_TOKEN_INITIALIZER(vmobj_token);
134
135 static int lwkt_token_spin = 5;
136 SYSCTL_INT(_lwkt, OID_AUTO, token_spin, CTLFLAG_RW,
137     &lwkt_token_spin, 0, "Decontention spin loops");
138 static int lwkt_token_delay = 0;
139 SYSCTL_INT(_lwkt, OID_AUTO, token_delay, CTLFLAG_RW,
140     &lwkt_token_delay, 0, "Decontention spin delay in ns");
141
142 /*
143  * The collision count is bumped every time the LWKT scheduler fails
144  * to acquire needed tokens in addition to a normal lwkt_gettoken()
145  * stall.
146  */
147 SYSCTL_LONG(_lwkt, OID_AUTO, mp_collisions, CTLFLAG_RW,
148     &mp_token.t_collisions, 0, "Collision counter of mp_token");
149 SYSCTL_LONG(_lwkt, OID_AUTO, pmap_collisions, CTLFLAG_RW,
150     &pmap_token.t_collisions, 0, "Collision counter of pmap_token");
151 SYSCTL_LONG(_lwkt, OID_AUTO, dev_collisions, CTLFLAG_RW,
152     &dev_token.t_collisions, 0, "Collision counter of dev_token");
153 SYSCTL_LONG(_lwkt, OID_AUTO, vm_collisions, CTLFLAG_RW,
154     &vm_token.t_collisions, 0, "Collision counter of vm_token");
155 SYSCTL_LONG(_lwkt, OID_AUTO, vmspace_collisions, CTLFLAG_RW,
156     &vmspace_token.t_collisions, 0, "Collision counter of vmspace_token");
157 SYSCTL_LONG(_lwkt, OID_AUTO, kvm_collisions, CTLFLAG_RW,
158     &kvm_token.t_collisions, 0, "Collision counter of kvm_token");
159 SYSCTL_LONG(_lwkt, OID_AUTO, proc_collisions, CTLFLAG_RW,
160     &proc_token.t_collisions, 0, "Collision counter of proc_token");
161 SYSCTL_LONG(_lwkt, OID_AUTO, tty_collisions, CTLFLAG_RW,
162     &tty_token.t_collisions, 0, "Collision counter of tty_token");
163 SYSCTL_LONG(_lwkt, OID_AUTO, vnode_collisions, CTLFLAG_RW,
164     &vnode_token.t_collisions, 0, "Collision counter of vnode_token");
165
166 static int _lwkt_getalltokens_sorted(thread_t td);
167
168 #ifdef SMP
169 /*
170  * Acquire the initial mplock
171  *
172  * (low level boot only)
173  */
174 void
175 cpu_get_initial_mplock(void)
176 {
177         KKASSERT(mp_token.t_ref == NULL);
178         if (lwkt_trytoken(&mp_token) == FALSE)
179                 panic("cpu_get_initial_mplock");
180 }
181 #endif
182
183 /*
184  * Return a pool token given an address.  Use a prime number to reduce
185  * overlaps.
186  */
187 static __inline
188 lwkt_token_t
189 _lwkt_token_pool_lookup(void *ptr)
190 {
191         u_int i;
192
193         i = (u_int)(uintptr_t)ptr % LWKT_NUM_POOL_TOKENS;
194         return(&pool_tokens[i]);
195 }
196
197 /*
198  * Initialize a tokref_t prior to making it visible in the thread's
199  * token array.
200  */
201 static __inline
202 void
203 _lwkt_tokref_init(lwkt_tokref_t ref, lwkt_token_t tok, thread_t td)
204 {
205         ref->tr_tok = tok;
206         ref->tr_owner = td;
207 }
208
209 /*
210  * See kern/kern_spinlock.c for the discussion on cache-friendly contention
211  * resolution.  We currently do not use cpu_lfence() (expensive!!) and, more
212  * importantly, we do a read-test of t_ref before attempting an atomic op,
213  * which greatly reduces hw cache bus contention.
214  */
215 static
216 int
217 _lwkt_trytoken_spin(lwkt_token_t tok, lwkt_tokref_t ref)
218 {
219         int n;
220
221         for (n = 0; n < lwkt_token_spin; ++n) {
222                 if (tok->t_ref == NULL &&
223                     atomic_cmpset_ptr(&tok->t_ref, NULL, ref)) {
224                         return TRUE;
225                 }
226                 if (lwkt_token_delay) {
227                         tsc_delay(lwkt_token_delay);
228                 } else {
229                         cpu_pause();
230                 }
231         }
232         return FALSE;
233 }
234
235 static __inline
236 void
237 _lwkt_reltoken_spin(lwkt_token_t tok)
238 {
239         tok->t_ref = NULL;
240 }
241
242 #if 0
243 /*
244  * Helper function used by lwkt_getalltokens[_sorted]().
245  *
246  * Our attempt to acquire the token has failed.  To reduce cache coherency
247  * bandwidth we set our cpu bit in t_collmask then wait for a reasonable
248  * period of time for a hand-off from the current token owner.
249  */
250 static
251 int
252 _lwkt_trytoken_spin(lwkt_token_t tok, lwkt_tokref_t ref)
253 {
254         globaldata_t gd = mycpu;
255         cpumask_t mask;
256         int n;
257
258         /*
259          * Add our cpu to the collision mask and wait for the token to be
260          * handed off to us.
261          */
262         crit_enter();
263         atomic_set_cpumask(&tok->t_collmask, gd->gd_cpumask);
264         for (n = 0; n < lwkt_token_spin; ++n) {
265                 /*
266                  * Token was released before we set our collision bit.
267                  */
268                 if (tok->t_ref == NULL &&
269                     atomic_cmpset_ptr(&tok->t_ref, NULL, ref)) {
270                         KKASSERT((tok->t_collmask & gd->gd_cpumask) != 0);
271                         atomic_clear_cpumask(&tok->t_collmask, gd->gd_cpumask);
272                         crit_exit();
273                         return TRUE;
274                 }
275
276                 /*
277                  * Token was handed-off to us.
278                  */
279                 if (tok->t_ref == &gd->gd_handoff) {
280                         KKASSERT((tok->t_collmask & gd->gd_cpumask) == 0);
281                         tok->t_ref = ref;
282                         crit_exit();
283                         return TRUE;
284                 }
285                 if (lwkt_token_delay)
286                         tsc_delay(lwkt_token_delay);
287                 else
288                         cpu_pause();
289         }
290
291         /*
292          * We failed, attempt to clear our bit in the cpumask.  We may race
293          * someone handing-off to us.  If someone other than us cleared our
294          * cpu bit a handoff is incoming and we must wait for it.
295          */
296         for (;;) {
297                 mask = tok->t_collmask;
298                 cpu_ccfence();
299                 if (mask & gd->gd_cpumask) {
300                         if (atomic_cmpset_cpumask(&tok->t_collmask,
301                                                   mask,
302                                                   mask & ~gd->gd_cpumask)) {
303                                 crit_exit();
304                                 return FALSE;
305                         }
306                         continue;
307                 }
308                 if (tok->t_ref != &gd->gd_handoff) {
309                         cpu_pause();
310                         continue;
311                 }
312                 tok->t_ref = ref;
313                 crit_exit();
314                 return TRUE;
315         }
316 }
317
318 /*
319  * Release token with hand-off
320  */
321 static __inline
322 void
323 _lwkt_reltoken_spin(lwkt_token_t tok)
324 {
325         globaldata_t xgd;
326         cpumask_t sidemask;
327         cpumask_t mask;
328         int cpuid;
329
330         if (tok->t_collmask == 0) {
331                 tok->t_ref = NULL;
332                 return;
333         }
334
335         crit_enter();
336         sidemask = ~(mycpu->gd_cpumask - 1);    /* high bits >= xcpu */
337         for (;;) {
338                 mask = tok->t_collmask;
339                 cpu_ccfence();
340                 if (mask == 0) {
341                         tok->t_ref = NULL;
342                         break;
343                 }
344                 if (mask & sidemask)
345                         cpuid = BSFCPUMASK(mask & sidemask);
346                 else
347                         cpuid = BSFCPUMASK(mask);
348                 xgd = globaldata_find(cpuid);
349                 if (atomic_cmpset_cpumask(&tok->t_collmask, mask,
350                                           mask & ~CPUMASK(cpuid))) {
351                         tok->t_ref = &xgd->gd_handoff;
352                         break;
353                 }
354         }
355         crit_exit();
356 }
357
358 #endif
359
360
361 /*
362  * Obtain all the tokens required by the specified thread on the current
363  * cpu, return 0 on failure and non-zero on success.  If a failure occurs
364  * any partially acquired tokens will be released prior to return.
365  *
366  * lwkt_getalltokens is called by the LWKT scheduler to acquire all
367  * tokens that the thread had acquired prior to going to sleep.
368  *
369  * If spinning is non-zero this function acquires the tokens in a particular
370  * order to deal with potential deadlocks.  We simply use address order for
371  * the case.
372  *
373  * Called from a critical section.
374  */
375 int
376 lwkt_getalltokens(thread_t td, int spinning)
377 {
378         lwkt_tokref_t scan;
379         lwkt_tokref_t ref;
380         lwkt_token_t tok;
381
382         if (spinning)
383                 return(_lwkt_getalltokens_sorted(td));
384
385         /*
386          * Acquire tokens in forward order, assign or validate tok->t_ref.
387          */
388         for (scan = &td->td_toks_base; scan < td->td_toks_stop; ++scan) {
389                 tok = scan->tr_tok;
390                 for (;;) {
391                         /*
392                          * Try to acquire the token if we do not already have
393                          * it.
394                          *
395                          * NOTE: If atomic_cmpset_ptr() fails we have to
396                          *       loop and try again.  It just means we
397                          *       lost a cpu race.
398                          */
399                         ref = tok->t_ref;
400                         if (ref == NULL) {
401                                 if (atomic_cmpset_ptr(&tok->t_ref, NULL,scan))
402                                         break;
403                                 continue;
404                         }
405
406                         /*
407                          * Someone holds the token.
408                          *
409                          * Test if ref is already recursively held by this
410                          * thread.  We cannot safely dereference tok->t_ref
411                          * (it might belong to another thread and is thus
412                          * unstable), but we don't have to. We can simply
413                          * range-check it.
414                          */
415                         if (ref >= &td->td_toks_base && ref < td->td_toks_stop)
416                                 break;
417
418                         /*
419                          * Try hard to acquire this token before giving up
420                          * and releasing the whole lot.
421                          */
422                         if (_lwkt_trytoken_spin(tok, scan))
423                                 break;
424                         if (lwkt_sched_debug > 0) {
425                                 --lwkt_sched_debug;
426                                 kprintf("toka %p %s %s\n",
427                                         tok, tok->t_desc, td->td_comm);
428                         }
429
430                         /*
431                          * Otherwise we failed to acquire all the tokens.
432                          * Release whatever we did get.
433                          */
434                         td->td_wmesg = tok->t_desc;
435                         atomic_add_long(&tok->t_collisions, 1);
436                         lwkt_relalltokens(td);
437
438                         return(FALSE);
439                 }
440
441         }
442         return (TRUE);
443 }
444
445 /*
446  * Release all tokens owned by the specified thread on the current cpu.
447  *
448  * This code is really simple.  Even in cases where we own all the tokens
449  * note that t_ref may not match the scan for recursively held tokens which
450  * are held deeper in the stack, or for the case where a lwkt_getalltokens()
451  * failed.
452  *
453  * Tokens are released in reverse order to reduce chasing race failures.
454  * 
455  * Called from a critical section.
456  */
457 void
458 lwkt_relalltokens(thread_t td)
459 {
460         lwkt_tokref_t scan;
461         lwkt_token_t tok;
462
463         for (scan = td->td_toks_stop - 1; scan >= &td->td_toks_base; --scan) {
464         /*for (scan = &td->td_toks_base; scan < td->td_toks_stop; ++scan) {*/
465                 tok = scan->tr_tok;
466                 if (tok->t_ref == scan)
467                         _lwkt_reltoken_spin(tok);
468         }
469 }
470
471 /*
472  * This is the decontention version of lwkt_getalltokens().  The tokens are
473  * acquired in address-sorted order to deal with any deadlocks.  Ultimately
474  * token failures will spin into the scheduler and get here.
475  *
476  * In addition, to reduce hardware cache coherency contention monitor/mwait
477  * is interlocked with gd->gd_reqflags and RQF_SPINNING.  Other cores which
478  * release a contended token will clear RQF_SPINNING and cause the mwait
479  * to resume.  Any interrupt will also generally set RQF_* flags and cause
480  * mwait to resume (or be a NOP in the first place).
481  *
482  * This code is required to set up RQF_SPINNING in case of failure.  The
483  * caller may call monitor/mwait on gd->gd_reqflags on failure.  We do NOT
484  * want to call mwait here, and doubly so while we are holding tokens.
485  *
486  * Called from critical section
487  */
488 static
489 int
490 _lwkt_getalltokens_sorted(thread_t td)
491 {
492         /*globaldata_t gd = td->td_gd;*/
493         lwkt_tokref_t sort_array[LWKT_MAXTOKENS];
494         lwkt_tokref_t scan;
495         lwkt_tokref_t ref;
496         lwkt_token_t tok;
497         int i;
498         int j;
499         int n;
500
501         /*
502          * Sort the token array.  Yah yah, I know this isn't fun.
503          *
504          * NOTE: Recursively acquired tokens are ordered the same as in the
505          *       td_toks_array so we can always get the earliest one first.
506          */
507         i = 0;
508         scan = &td->td_toks_base;
509         while (scan < td->td_toks_stop) {
510                 for (j = 0; j < i; ++j) {
511                         if (scan->tr_tok < sort_array[j]->tr_tok)
512                                 break;
513                 }
514                 if (j != i) {
515                         bcopy(sort_array + j, sort_array + j + 1,
516                               (i - j) * sizeof(lwkt_tokref_t));
517                 }
518                 sort_array[j] = scan;
519                 ++scan;
520                 ++i;
521         }
522         n = i;
523
524         /*
525          * Acquire tokens in forward order, assign or validate tok->t_ref.
526          */
527         for (i = 0; i < n; ++i) {
528                 scan = sort_array[i];
529                 tok = scan->tr_tok;
530                 for (;;) {
531                         /*
532                          * Try to acquire the token if we do not already have
533                          * it.
534                          *
535                          * NOTE: If atomic_cmpset_ptr() fails we have to
536                          *       loop and try again.  It just means we
537                          *       lost a cpu race.
538                          */
539                         ref = tok->t_ref;
540                         if (ref == NULL) {
541                                 if (atomic_cmpset_ptr(&tok->t_ref, NULL, scan))
542                                         break;
543                                 continue;
544                         }
545
546                         /*
547                          * Someone holds the token.
548                          *
549                          * Test if ref is already recursively held by this
550                          * thread.  We cannot safely dereference tok->t_ref
551                          * (it might belong to another thread and is thus
552                          * unstable), but we don't have to. We can simply
553                          * range-check it.
554                          */
555                         if (ref >= &td->td_toks_base && ref < td->td_toks_stop)
556                                 break;
557
558                         /*
559                          * Try hard to acquire this token before giving up
560                          * and releasing the whole lot.
561                          */
562                         if (_lwkt_trytoken_spin(tok, scan))
563                                 break;
564                         if (lwkt_sched_debug > 0) {
565                                 --lwkt_sched_debug;
566                                 kprintf("tokb %p %s %s\n",
567                                         tok, tok->t_desc, td->td_comm);
568                         }
569
570                         /*
571                          * Tokens are released in reverse order to reduce
572                          * chasing race failures.
573                          */
574                         td->td_wmesg = tok->t_desc;
575                         atomic_add_long(&tok->t_collisions, 1);
576
577                         for (j = i - 1; j >= 0; --j) {
578                         /*for (j = 0; j < i; ++j) {*/
579                                 scan = sort_array[j];
580                                 tok = scan->tr_tok;
581                                 if (tok->t_ref == scan)
582                                         _lwkt_reltoken_spin(tok);
583                         }
584                         return (FALSE);
585                 }
586         }
587
588         /*
589          * We were successful, there is no need for another core to signal
590          * us.
591          */
592 #if 0
593         atomic_clear_int(&gd->gd_reqflags, RQF_SPINNING);
594 #endif
595         return (TRUE);
596 }
597
598 /*
599  * Token acquisition helper function.  The caller must have already
600  * made nref visible by adjusting td_toks_stop and will be responsible
601  * for the disposition of nref on either success or failure.
602  *
603  * When acquiring tokens recursively we want tok->t_ref to point to
604  * the outer (first) acquisition so it gets cleared only on the last
605  * release.
606  */
607 static __inline
608 int
609 _lwkt_trytokref2(lwkt_tokref_t nref, thread_t td, int blocking)
610 {
611         lwkt_token_t tok;
612         lwkt_tokref_t ref;
613
614         /*
615          * Make sure the compiler does not reorder prior instructions
616          * beyond this demark.
617          */
618         cpu_ccfence();
619
620         /*
621          * Attempt to gain ownership
622          */
623         tok = nref->tr_tok;
624         for (;;) {
625                 /*
626                  * Try to acquire the token if we do not already have
627                  * it.  This is not allowed if we are in a hard code
628                  * section (because it 'might' have blocked).
629                  */
630                 ref = tok->t_ref;
631                 if (ref == NULL) {
632                         KASSERT((blocking == 0 ||
633                                 td->td_gd->gd_intr_nesting_level == 0 ||
634                                 panic_cpu_gd == mycpu),
635                                 ("Attempt to acquire token %p not already "
636                                  "held in hard code section", tok));
637
638                         /*
639                          * NOTE: If atomic_cmpset_ptr() fails we have to
640                          *       loop and try again.  It just means we
641                          *       lost a cpu race.
642                          */
643                         if (atomic_cmpset_ptr(&tok->t_ref, NULL, nref))
644                                 return (TRUE);
645                         continue;
646                 }
647
648                 /*
649                  * Test if ref is already recursively held by this
650                  * thread.  We cannot safely dereference tok->t_ref
651                  * (it might belong to another thread and is thus
652                  * unstable), but we don't have to. We can simply
653                  * range-check it.
654                  *
655                  * It is ok to acquire a token that is already held
656                  * by the current thread when in a hard code section.
657                  */
658                 if (ref >= &td->td_toks_base && ref < td->td_toks_stop)
659                         return(TRUE);
660
661                 /*
662                  * Spin generously.  This is preferable to just switching
663                  * away unconditionally.
664                  */
665                 if (_lwkt_trytoken_spin(tok, nref))
666                         return(TRUE);
667
668                 /*
669                  * Otherwise we failed, and it is not ok to attempt to
670                  * acquire a token in a hard code section.
671                  */
672                 KASSERT((blocking == 0 ||
673                         td->td_gd->gd_intr_nesting_level == 0),
674                         ("Attempt to acquire token %p not already "
675                          "held in hard code section", tok));
676
677                 return(FALSE);
678         }
679 }
680
681 /*
682  * Get a serializing token.  This routine can block.
683  */
684 void
685 lwkt_gettoken(lwkt_token_t tok)
686 {
687         thread_t td = curthread;
688         lwkt_tokref_t ref;
689
690         ref = td->td_toks_stop;
691         KKASSERT(ref < &td->td_toks_end);
692         ++td->td_toks_stop;
693         cpu_ccfence();
694         _lwkt_tokref_init(ref, tok, td);
695
696         if (_lwkt_trytokref2(ref, td, 1) == FALSE) {
697                 /*
698                  * Give up running if we can't acquire the token right now.
699                  *
700                  * Since the tokref is already active the scheduler now
701                  * takes care of acquisition, so we need only call
702                  * lwkt_switch().
703                  *
704                  * Since we failed this was not a recursive token so upon
705                  * return tr_tok->t_ref should be assigned to this specific
706                  * ref.
707                  */
708                 td->td_wmesg = tok->t_desc;
709                 atomic_add_long(&tok->t_collisions, 1);
710                 logtoken(fail, ref);
711                 lwkt_switch();
712                 logtoken(succ, ref);
713                 KKASSERT(tok->t_ref == ref);
714         }
715 }
716
717 void
718 lwkt_gettoken_hard(lwkt_token_t tok)
719 {
720         thread_t td = curthread;
721         lwkt_tokref_t ref;
722
723         ref = td->td_toks_stop;
724         KKASSERT(ref < &td->td_toks_end);
725         ++td->td_toks_stop;
726         cpu_ccfence();
727         _lwkt_tokref_init(ref, tok, td);
728
729         if (_lwkt_trytokref2(ref, td, 1) == FALSE) {
730                 /*
731                  * Give up running if we can't acquire the token right now.
732                  *
733                  * Since the tokref is already active the scheduler now
734                  * takes care of acquisition, so we need only call
735                  * lwkt_switch().
736                  *
737                  * Since we failed this was not a recursive token so upon
738                  * return tr_tok->t_ref should be assigned to this specific
739                  * ref.
740                  */
741                 td->td_wmesg = tok->t_desc;
742                 atomic_add_long(&tok->t_collisions, 1);
743                 logtoken(fail, ref);
744                 lwkt_switch();
745                 logtoken(succ, ref);
746                 KKASSERT(tok->t_ref == ref);
747         }
748         crit_enter_hard_gd(td->td_gd);
749 }
750
751 lwkt_token_t
752 lwkt_getpooltoken(void *ptr)
753 {
754         thread_t td = curthread;
755         lwkt_token_t tok;
756         lwkt_tokref_t ref;
757
758         tok = _lwkt_token_pool_lookup(ptr);
759         ref = td->td_toks_stop;
760         KKASSERT(ref < &td->td_toks_end);
761         ++td->td_toks_stop;
762         cpu_ccfence();
763         _lwkt_tokref_init(ref, tok, td);
764
765         if (_lwkt_trytokref2(ref, td, 1) == FALSE) {
766                 /*
767                  * Give up running if we can't acquire the token right now.
768                  *
769                  * Since the tokref is already active the scheduler now
770                  * takes care of acquisition, so we need only call
771                  * lwkt_switch().
772                  *
773                  * Since we failed this was not a recursive token so upon
774                  * return tr_tok->t_ref should be assigned to this specific
775                  * ref.
776                  */
777                 td->td_wmesg = tok->t_desc;
778                 atomic_add_long(&tok->t_collisions, 1);
779                 logtoken(fail, ref);
780                 lwkt_switch();
781                 logtoken(succ, ref);
782                 KKASSERT(tok->t_ref == ref);
783         }
784         return(tok);
785 }
786
787 /*
788  * Attempt to acquire a token, return TRUE on success, FALSE on failure.
789  */
790 int
791 lwkt_trytoken(lwkt_token_t tok)
792 {
793         thread_t td = curthread;
794         lwkt_tokref_t ref;
795
796         ref = td->td_toks_stop;
797         KKASSERT(ref < &td->td_toks_end);
798         ++td->td_toks_stop;
799         cpu_ccfence();
800         _lwkt_tokref_init(ref, tok, td);
801
802         if (_lwkt_trytokref2(ref, td, 0) == FALSE) {
803                 /*
804                  * Cleanup, deactivate the failed token.
805                  */
806                 cpu_ccfence();
807                 --td->td_toks_stop;
808                 return (FALSE);
809         }
810         return (TRUE);
811 }
812
813 /*
814  * Release a serializing token.
815  *
816  * WARNING!  All tokens must be released in reverse order.  This will be
817  *           asserted.
818  */
819 void
820 lwkt_reltoken(lwkt_token_t tok)
821 {
822         thread_t td = curthread;
823         lwkt_tokref_t ref;
824
825         /*
826          * Remove ref from thread token list and assert that it matches
827          * the token passed in.  Tokens must be released in reverse order.
828          */
829         ref = td->td_toks_stop - 1;
830         KKASSERT(ref >= &td->td_toks_base && ref->tr_tok == tok);
831
832         /*
833          * Only clear the token if it matches ref.  If ref was a recursively
834          * acquired token it may not match.  Then adjust td_toks_stop.
835          *
836          * Some comparisons must be run prior to adjusting td_toks_stop
837          * to avoid racing against a fast interrupt/ ipi which tries to
838          * acquire a token.
839          *
840          * We must also be absolutely sure that the compiler does not
841          * reorder the clearing of t_ref and the adjustment of td_toks_stop,
842          * or reorder the adjustment of td_toks_stop against the conditional.
843          *
844          * NOTE: The mplock is a token also so sequencing is a bit complex.
845          */
846         if (tok->t_ref == ref)
847                 _lwkt_reltoken_spin(tok);
848         cpu_sfence();
849         cpu_ccfence();
850         td->td_toks_stop = ref;
851         cpu_ccfence();
852         KKASSERT(tok->t_ref != ref);
853 }
854
855 void
856 lwkt_reltoken_hard(lwkt_token_t tok)
857 {
858         lwkt_reltoken(tok);
859         crit_exit_hard();
860 }
861
862 /*
863  * It is faster for users of lwkt_getpooltoken() to use the returned
864  * token and just call lwkt_reltoken(), but for convenience we provide
865  * this function which looks the token up based on the ident.
866  */
867 void
868 lwkt_relpooltoken(void *ptr)
869 {
870         lwkt_token_t tok = _lwkt_token_pool_lookup(ptr);
871         lwkt_reltoken(tok);
872 }
873
874 /*
875  * Return a count of the number of token refs the thread has to the
876  * specified token, whether it currently owns the token or not.
877  */
878 int
879 lwkt_cnttoken(lwkt_token_t tok, thread_t td)
880 {
881         lwkt_tokref_t scan;
882         int count = 0;
883
884         for (scan = &td->td_toks_base; scan < td->td_toks_stop; ++scan) {
885                 if (scan->tr_tok == tok)
886                         ++count;
887         }
888         return(count);
889 }
890
891
892 /*
893  * Pool tokens are used to provide a type-stable serializing token
894  * pointer that does not race against disappearing data structures.
895  *
896  * This routine is called in early boot just after we setup the BSP's
897  * globaldata structure.
898  */
899 void
900 lwkt_token_pool_init(void)
901 {
902         int i;
903
904         for (i = 0; i < LWKT_NUM_POOL_TOKENS; ++i)
905                 lwkt_token_init(&pool_tokens[i], "pool");
906 }
907
908 lwkt_token_t
909 lwkt_token_pool_lookup(void *ptr)
910 {
911         return (_lwkt_token_pool_lookup(ptr));
912 }
913
914 /*
915  * Initialize a token.  
916  */
917 void
918 lwkt_token_init(lwkt_token_t tok, const char *desc)
919 {
920         tok->t_ref = NULL;
921         tok->t_collisions = 0;
922         tok->t_collmask = 0;
923         tok->t_desc = desc;
924 }
925
926 void
927 lwkt_token_uninit(lwkt_token_t tok)
928 {
929         /* empty */
930 }
931
932 /*
933  * Exchange the two most recent tokens on the tokref stack.  This allows
934  * you to release a token out of order.
935  *
936  * We have to be careful about the case where the top two tokens are
937  * the same token.  In this case tok->t_ref will point to the deeper
938  * ref and must remain pointing to the deeper ref.  If we were to swap
939  * it the first release would clear the token even though a second
940  * ref is still present.
941  */
942 void
943 lwkt_token_swap(void)
944 {
945         lwkt_tokref_t ref1, ref2;
946         lwkt_token_t tok1, tok2;
947         thread_t td = curthread;
948
949         crit_enter();
950
951         ref1 = td->td_toks_stop - 1;
952         ref2 = td->td_toks_stop - 2;
953         KKASSERT(ref1 > &td->td_toks_base);
954         KKASSERT(ref2 > &td->td_toks_base);
955
956         tok1 = ref1->tr_tok;
957         tok2 = ref2->tr_tok;
958         if (tok1 != tok2) {
959                 ref1->tr_tok = tok2;
960                 ref2->tr_tok = tok1;
961                 if (tok1->t_ref == ref1)
962                         tok1->t_ref = ref2;
963                 if (tok2->t_ref == ref2)
964                         tok2->t_ref = ref1;
965         }
966
967         crit_exit();
968 }
969
970 #if 0
971 int
972 lwkt_token_is_stale(lwkt_tokref_t ref)
973 {
974         lwkt_token_t tok = ref->tr_tok;
975
976         KKASSERT(tok->t_owner == curthread && ref->tr_state == 1 &&
977                  tok->t_count > 0);
978
979         /* Token is not stale */
980         if (tok->t_lastowner == tok->t_owner)
981                 return (FALSE);
982
983         /*
984          * The token is stale. Reset to not stale so that the next call to
985          * lwkt_token_is_stale will return "not stale" unless the token
986          * was acquired in-between by another thread.
987          */
988         tok->t_lastowner = tok->t_owner;
989         return (TRUE);
990 }
991 #endif