kernel - MPSAFE work - Add global tokens
[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 #ifdef INVARIANTS
85 static int token_debug = 0;
86 #endif
87
88 static lwkt_token       pool_tokens[LWKT_NUM_POOL_TOKENS];
89
90 #define TOKEN_STRING    "REF=%p TOK=%p TD=%p"
91 #define CONTENDED_STRING        "REF=%p TOK=%p TD=%p (contention started)"
92 #define UNCONTENDED_STRING      "REF=%p TOK=%p TD=%p (contention stopped)"
93 #if !defined(KTR_TOKENS)
94 #define KTR_TOKENS      KTR_ALL
95 #endif
96
97 KTR_INFO_MASTER(tokens);
98 KTR_INFO(KTR_TOKENS, tokens, fail, 0, TOKEN_STRING, sizeof(void *) * 3);
99 KTR_INFO(KTR_TOKENS, tokens, succ, 1, TOKEN_STRING, sizeof(void *) * 3);
100 #if 0
101 KTR_INFO(KTR_TOKENS, tokens, release, 2, TOKEN_STRING, sizeof(void *) * 3);
102 KTR_INFO(KTR_TOKENS, tokens, remote, 3, TOKEN_STRING, sizeof(void *) * 3);
103 KTR_INFO(KTR_TOKENS, tokens, reqremote, 4, TOKEN_STRING, sizeof(void *) * 3);
104 KTR_INFO(KTR_TOKENS, tokens, reqfail, 5, TOKEN_STRING, sizeof(void *) * 3);
105 KTR_INFO(KTR_TOKENS, tokens, drain, 6, TOKEN_STRING, sizeof(void *) * 3);
106 KTR_INFO(KTR_TOKENS, tokens, contention_start, 7, CONTENDED_STRING, sizeof(void *) * 3);
107 KTR_INFO(KTR_TOKENS, tokens, contention_stop, 7, UNCONTENDED_STRING, sizeof(void *) * 3);
108 #endif
109
110 #define logtoken(name, ref)                                             \
111         KTR_LOG(tokens_ ## name, ref, ref->tr_tok, curthread)
112
113 #ifdef INVARIANTS
114 SYSCTL_INT(_lwkt, OID_AUTO, token_debug, CTLFLAG_RW, &token_debug, 0, "");
115 #endif
116
117 /*
118  * Global tokens.  These replace the MP lock for major subsystem locking.
119  * These tokens are initially used to lockup both global and individual
120  * operations.
121  *
122  * Once individual structures get their own locks these tokens are used
123  * only to protect global lists & other variables and to interlock
124  * allocations and teardowns and such.
125  *
126  * The UP initializer causes token acquisition to also acquire the MP lock
127  * for maximum compatibility.  The feature may be enabled and disabled at
128  * any time, the MP state is copied to the tokref when the token is acquired
129  * and will not race against sysctl changes.
130  */
131 struct lwkt_token pmap_token = LWKT_TOKEN_UP_INITIALIZER;
132 struct lwkt_token dev_token = LWKT_TOKEN_UP_INITIALIZER;
133 struct lwkt_token vm_page_token = LWKT_TOKEN_UP_INITIALIZER;
134 struct lwkt_token vm_object_token = LWKT_TOKEN_UP_INITIALIZER;
135 struct lwkt_token vm_map_token = LWKT_TOKEN_UP_INITIALIZER;
136 struct lwkt_token proc_token = LWKT_TOKEN_UP_INITIALIZER;
137 struct lwkt_token tty_token = LWKT_TOKEN_UP_INITIALIZER;
138 struct lwkt_token vnode_token = LWKT_TOKEN_UP_INITIALIZER;
139
140 SYSCTL_INT(_lwkt, OID_AUTO, pmap_mpsafe,
141            CTLFLAG_RW, &pmap_token.t_flags, 0, "");
142 SYSCTL_INT(_lwkt, OID_AUTO, dev_mpsafe,
143            CTLFLAG_RW, &dev_token.t_flags, 0, "");
144 SYSCTL_INT(_lwkt, OID_AUTO, vm_page_mpsafe,
145            CTLFLAG_RW, &vm_page_token.t_flags, 0, "");
146 SYSCTL_INT(_lwkt, OID_AUTO, vm_object_mpsafe,
147            CTLFLAG_RW, &vm_object_token.t_flags, 0, "");
148 SYSCTL_INT(_lwkt, OID_AUTO, vm_map_mpsafe,
149            CTLFLAG_RW, &vm_map_token.t_flags, 0, "");
150 SYSCTL_INT(_lwkt, OID_AUTO, proc_mpsafe,
151            CTLFLAG_RW, &proc_token.t_flags, 0, "");
152 SYSCTL_INT(_lwkt, OID_AUTO, tty_mpsafe,
153            CTLFLAG_RW, &tty_token.t_flags, 0, "");
154 SYSCTL_INT(_lwkt, OID_AUTO, vnode_mpsafe,
155            CTLFLAG_RW, &vnode_token.t_flags, 0, "");
156
157 /*
158  * The collision count is bumped every time the LWKT scheduler fails
159  * to acquire needed tokens in addition to a normal lwkt_gettoken()
160  * stall.
161  */
162 SYSCTL_LONG(_lwkt, OID_AUTO, pmap_collisions,
163             CTLFLAG_RW, &pmap_token.t_collisions, 0, "");
164 SYSCTL_LONG(_lwkt, OID_AUTO, dev_collisions,
165             CTLFLAG_RW, &dev_token.t_collisions, 0, "");
166 SYSCTL_LONG(_lwkt, OID_AUTO, vm_page_collisions,
167             CTLFLAG_RW, &vm_page_token.t_collisions, 0, "");
168 SYSCTL_LONG(_lwkt, OID_AUTO, vm_object_collisions,
169             CTLFLAG_RW, &vm_object_token.t_collisions, 0, "");
170 SYSCTL_LONG(_lwkt, OID_AUTO, vm_map_collisions,
171             CTLFLAG_RW, &vm_map_token.t_collisions, 0, "");
172 SYSCTL_LONG(_lwkt, OID_AUTO, proc_collisions,
173             CTLFLAG_RW, &proc_token.t_collisions, 0, "");
174 SYSCTL_LONG(_lwkt, OID_AUTO, tty_collisions,
175             CTLFLAG_RW, &tty_token.t_collisions, 0, "");
176 SYSCTL_LONG(_lwkt, OID_AUTO, vnode_collisions,
177             CTLFLAG_RW, &vnode_token.t_collisions, 0, "");
178
179 /*
180  * Return a pool token given an address
181  */
182 static __inline
183 lwkt_token_t
184 _lwkt_token_pool_lookup(void *ptr)
185 {
186         int i;
187
188         i = ((int)(intptr_t)ptr >> 2) ^ ((int)(intptr_t)ptr >> 12);
189         return(&pool_tokens[i & LWKT_MASK_POOL_TOKENS]);
190 }
191
192 /*
193  * Initialize a tokref_t prior to making it visible in the thread's
194  * token array.
195  */
196 static __inline
197 void
198 _lwkt_tokref_init(lwkt_tokref_t ref, lwkt_token_t tok, thread_t td)
199 {
200         ref->tr_tok = tok;
201         ref->tr_owner = td;
202         ref->tr_flags = tok->t_flags;
203 }
204
205 /*
206  * Obtain all the tokens required by the specified thread on the current
207  * cpu, return 0 on failure and non-zero on success.  If a failure occurs
208  * any partially acquired tokens will be released prior to return.
209  *
210  * lwkt_getalltokens is called by the LWKT scheduler to acquire all
211  * tokens that the thread had acquired prior to going to sleep.
212  *
213  * The scheduler is responsible for maintaining the MP lock count, so
214  * we don't need to deal with tr_flags here.  We also do not do any
215  * logging here.  The logging done by lwkt_gettoken() is plenty good
216  * enough to get a feel for it.
217  *
218  * Called from a critical section.
219  */
220 int
221 lwkt_getalltokens(thread_t td)
222 {
223         lwkt_tokref_t scan;
224         lwkt_tokref_t ref;
225         lwkt_token_t tok;
226
227         /*
228          * Acquire tokens in forward order, assign or validate tok->t_ref.
229          */
230         for (scan = &td->td_toks_base; scan < td->td_toks_stop; ++scan) {
231                 tok = scan->tr_tok;
232                 for (;;) {
233                         /*
234                          * Try to acquire the token if we do not already have
235                          * it.
236                          *
237                          * NOTE: If atomic_cmpset_ptr() fails we have to
238                          *       loop and try again.  It just means we
239                          *       lost a cpu race.
240                          */
241                         ref = tok->t_ref;
242                         if (ref == NULL) {
243                                 if (atomic_cmpset_ptr(&tok->t_ref, NULL, scan))
244                                         break;
245                                 continue;
246                         }
247
248                         /*
249                          * Test if ref is already recursively held by this
250                          * thread.  We cannot safely dereference tok->t_ref
251                          * (it might belong to another thread and is thus
252                          * unstable), but we don't have to. We can simply
253                          * range-check it.
254                          */
255                         if (ref >= &td->td_toks_base && ref < td->td_toks_stop)
256                                 break;
257
258                         /*
259                          * Otherwise we failed to acquire all the tokens.
260                          * Undo and return.
261                          */
262                         atomic_add_long(&tok->t_collisions, 1);
263                         lwkt_relalltokens(td);
264                         return(FALSE);
265                 }
266         }
267         return (TRUE);
268 }
269
270 /*
271  * Release all tokens owned by the specified thread on the current cpu.
272  *
273  * This code is really simple.  Even in cases where we own all the tokens
274  * note that t_ref may not match the scan for recursively held tokens,
275  * or for the case where a lwkt_getalltokens() failed.
276  *
277  * The scheduler is responsible for maintaining the MP lock count, so
278  * we don't need to deal with tr_flags here.
279  * 
280  * Called from a critical section.
281  */
282 void
283 lwkt_relalltokens(thread_t td)
284 {
285         lwkt_tokref_t scan;
286         lwkt_token_t tok;
287
288         for (scan = &td->td_toks_base; scan < td->td_toks_stop; ++scan) {
289                 tok = scan->tr_tok;
290                 if (tok->t_ref == scan)
291                         tok->t_ref = NULL;
292         }
293 }
294
295 /*
296  * Token acquisition helper function.  The caller must have already
297  * made nref visible by adjusting td_toks_stop and will be responsible
298  * for the disposition of nref on either success or failure.
299  *
300  * When acquiring tokens recursively we want tok->t_ref to point to
301  * the outer (first) acquisition so it gets cleared only on the last
302  * release.
303  */
304 static __inline
305 int
306 _lwkt_trytokref2(lwkt_tokref_t nref, thread_t td)
307 {
308         lwkt_token_t tok;
309         lwkt_tokref_t ref;
310
311         KKASSERT(td->td_gd->gd_intr_nesting_level == 0);
312
313         /*
314          * Make sure the compiler does not reorder prior instructions
315          * beyond this demark.
316          */
317         cpu_ccfence();
318
319         /*
320          * Attempt to gain ownership
321          */
322         tok = nref->tr_tok;
323         for (;;) {
324                 /*
325                  * Try to acquire the token if we do not already have
326                  * it.
327                  */
328                 ref = tok->t_ref;
329                 if (ref == NULL) {
330                         /*
331                          * NOTE: If atomic_cmpset_ptr() fails we have to
332                          *       loop and try again.  It just means we
333                          *       lost a cpu race.
334                          */
335                         if (atomic_cmpset_ptr(&tok->t_ref, NULL, nref))
336                                 return (TRUE);
337                         continue;
338                 }
339
340                 /*
341                  * Test if ref is already recursively held by this
342                  * thread.  We cannot safely dereference tok->t_ref
343                  * (it might belong to another thread and is thus
344                  * unstable), but we don't have to. We can simply
345                  * range-check it.
346                  */
347                 if (ref >= &td->td_toks_base && ref < td->td_toks_stop)
348                         return(TRUE);
349
350                 /*
351                  * Otherwise we failed.
352                  */
353                 return(FALSE);
354         }
355 }
356
357 /*
358  * Acquire a serializing token.  This routine does not block.
359  */
360 static __inline
361 int
362 _lwkt_trytokref(lwkt_tokref_t ref, thread_t td)
363 {
364         if ((ref->tr_flags & LWKT_TOKEN_MPSAFE) == 0) {
365                 if (try_mplock() == 0)
366                         return (FALSE);
367         }
368         if (_lwkt_trytokref2(ref, td) == FALSE) {
369                 /*
370                  * Cleanup, deactivate the failed token.
371                  */
372                 --td->td_toks_stop;
373                 if ((ref->tr_flags & LWKT_TOKEN_MPSAFE) == 0)
374                         rel_mplock();
375                 return (FALSE);
376         }
377         return (TRUE);
378 }
379
380 /*
381  * Acquire a serializing token.  This routine can block.
382  */
383 static __inline
384 void
385 _lwkt_gettokref(lwkt_tokref_t ref, thread_t td)
386 {
387         if ((ref->tr_flags & LWKT_TOKEN_MPSAFE) == 0)
388                 get_mplock();
389         if (_lwkt_trytokref2(ref, td) == FALSE) {
390                 /*
391                  * Give up running if we can't acquire the token right now.
392                  *
393                  * Since the tokref is already active the scheduler now
394                  * takes care of acquisition, so we need only call
395                  * lwkt_yield().
396                  *
397                  * Since we failed this was not a recursive token so upon
398                  * return tr_tok->t_ref should be assigned to this specific
399                  * ref.
400                  */
401                 atomic_add_long(&ref->tr_tok->t_collisions, 1);
402                 logtoken(fail, ref);
403                 lwkt_yield();
404                 logtoken(succ, ref);
405                 KKASSERT(ref->tr_tok->t_ref == ref);
406         }
407 }
408
409 void
410 lwkt_gettoken(lwkt_token_t tok)
411 {
412         thread_t td = curthread;
413         lwkt_tokref_t ref;
414
415         ref = td->td_toks_stop;
416         KKASSERT(ref < &td->td_toks_end);
417         _lwkt_tokref_init(ref, tok, td);
418         ++td->td_toks_stop;
419         _lwkt_gettokref(ref, td);
420 }
421
422 lwkt_token_t
423 lwkt_getpooltoken(void *ptr)
424 {
425         thread_t td = curthread;
426         lwkt_token_t tok;
427         lwkt_tokref_t ref;
428
429         ref = td->td_toks_stop;
430         KKASSERT(ref < &td->td_toks_end);
431         tok = _lwkt_token_pool_lookup(ptr);
432         _lwkt_tokref_init(ref, tok, td);
433         ++td->td_toks_stop;
434         _lwkt_gettokref(ref, td);
435         return(tok);
436 }
437
438 int
439 lwkt_trytoken(lwkt_token_t tok)
440 {
441         thread_t td = curthread;
442         lwkt_tokref_t ref;
443
444         ref = td->td_toks_stop;
445         KKASSERT(ref < &td->td_toks_end);
446         _lwkt_tokref_init(ref, tok, td);
447         ++td->td_toks_stop;
448         return(_lwkt_trytokref(ref, td));
449 }
450
451 /*
452  * Release a serializing token.
453  *
454  * WARNING!  All tokens must be released in reverse order.  This will be
455  *           asserted.
456  */
457 void
458 lwkt_reltoken(lwkt_token_t tok)
459 {
460         thread_t td = curthread;
461         lwkt_tokref_t ref;
462
463         /*
464          * Remove ref from thread token list and assert that it matches
465          * the token passed in.  Tokens must be released in reverse order.
466          */
467         ref = td->td_toks_stop - 1;
468         KKASSERT(ref >= &td->td_toks_base && ref->tr_tok == tok);
469         td->td_toks_stop = ref;
470
471         /*
472          * If the token was not MPSAFE release the MP lock.
473          */
474         if ((ref->tr_flags & LWKT_TOKEN_MPSAFE) == 0)
475                 rel_mplock();
476
477         /*
478          * Make sure the compiler does not reorder the clearing of
479          * tok->t_ref.
480          */
481         cpu_ccfence();
482
483         /*
484          * Only clear the token if it matches ref.  If ref was a recursively
485          * acquired token it may not match.
486          */
487         if (tok->t_ref == ref)
488                 tok->t_ref = NULL;
489 }
490
491 /*
492  * Pool tokens are used to provide a type-stable serializing token
493  * pointer that does not race against disappearing data structures.
494  *
495  * This routine is called in early boot just after we setup the BSP's
496  * globaldata structure.
497  */
498 void
499 lwkt_token_pool_init(void)
500 {
501         int i;
502
503         for (i = 0; i < LWKT_NUM_POOL_TOKENS; ++i)
504                 lwkt_token_init(&pool_tokens[i], 1);
505 }
506
507 lwkt_token_t
508 lwkt_token_pool_lookup(void *ptr)
509 {
510         return (_lwkt_token_pool_lookup(ptr));
511 }
512
513 /*
514  * Initialize the owner and release-to cpu to the current cpu
515  * and reset the generation count.
516  */
517 void
518 lwkt_token_init(lwkt_token_t tok, int mpsafe)
519 {
520         tok->t_ref = NULL;
521         tok->t_flags = mpsafe ? LWKT_TOKEN_MPSAFE : 0;
522 }
523
524 void
525 lwkt_token_uninit(lwkt_token_t tok)
526 {
527         /* empty */
528 }
529
530 #if 0
531 int
532 lwkt_token_is_stale(lwkt_tokref_t ref)
533 {
534         lwkt_token_t tok = ref->tr_tok;
535
536         KKASSERT(tok->t_owner == curthread && ref->tr_state == 1 &&
537                  tok->t_count > 0);
538
539         /* Token is not stale */
540         if (tok->t_lastowner == tok->t_owner)
541                 return (FALSE);
542
543         /*
544          * The token is stale. Reset to not stale so that the next call to
545          * lwkt_token_is_stale will return "not stale" unless the token
546          * was acquired in-between by another thread.
547          */
548         tok->t_lastowner = tok->t_owner;
549         return (TRUE);
550 }
551 #endif