xref: /freebsd/sys/kern/subr_epoch.c (revision cfd6422a5217410fbd66f7a7a8a64d9d85e61229)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2018, Matthew Macy <mmacy@freebsd.org>
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/counter.h>
35 #include <sys/epoch.h>
36 #include <sys/gtaskqueue.h>
37 #include <sys/kernel.h>
38 #include <sys/limits.h>
39 #include <sys/lock.h>
40 #include <sys/malloc.h>
41 #include <sys/mutex.h>
42 #include <sys/pcpu.h>
43 #include <sys/proc.h>
44 #include <sys/sched.h>
45 #include <sys/sx.h>
46 #include <sys/smp.h>
47 #include <sys/sysctl.h>
48 #include <sys/turnstile.h>
49 #ifdef EPOCH_TRACE
50 #include <machine/stdarg.h>
51 #include <sys/stack.h>
52 #include <sys/tree.h>
53 #endif
54 #include <vm/vm.h>
55 #include <vm/vm_extern.h>
56 #include <vm/vm_kern.h>
57 #include <vm/uma.h>
58 
59 #include <ck_epoch.h>
60 
61 #ifdef __amd64__
62 #define EPOCH_ALIGN CACHE_LINE_SIZE*2
63 #else
64 #define EPOCH_ALIGN CACHE_LINE_SIZE
65 #endif
66 
67 TAILQ_HEAD (epoch_tdlist, epoch_tracker);
68 typedef struct epoch_record {
69 	ck_epoch_record_t er_record;
70 	struct epoch_context er_drain_ctx;
71 	struct epoch *er_parent;
72 	volatile struct epoch_tdlist er_tdlist;
73 	volatile uint32_t er_gen;
74 	uint32_t er_cpuid;
75 #ifdef INVARIANTS
76 	/* Used to verify record ownership for non-preemptible epochs. */
77 	struct thread *er_td;
78 #endif
79 } __aligned(EPOCH_ALIGN)     *epoch_record_t;
80 
81 struct epoch {
82 	struct ck_epoch e_epoch __aligned(EPOCH_ALIGN);
83 	epoch_record_t e_pcpu_record;
84 	int	e_in_use;
85 	int	e_flags;
86 	struct sx e_drain_sx;
87 	struct mtx e_drain_mtx;
88 	volatile int e_drain_count;
89 	const char *e_name;
90 };
91 
92 /* arbitrary --- needs benchmarking */
93 #define MAX_ADAPTIVE_SPIN 100
94 #define MAX_EPOCHS 64
95 
96 CTASSERT(sizeof(ck_epoch_entry_t) == sizeof(struct epoch_context));
97 SYSCTL_NODE(_kern, OID_AUTO, epoch, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
98     "epoch information");
99 SYSCTL_NODE(_kern_epoch, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
100     "epoch stats");
101 
102 /* Stats. */
103 static counter_u64_t block_count;
104 
105 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, nblocked, CTLFLAG_RW,
106     &block_count, "# of times a thread was in an epoch when epoch_wait was called");
107 static counter_u64_t migrate_count;
108 
109 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, migrations, CTLFLAG_RW,
110     &migrate_count, "# of times thread was migrated to another CPU in epoch_wait");
111 static counter_u64_t turnstile_count;
112 
113 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, ncontended, CTLFLAG_RW,
114     &turnstile_count, "# of times a thread was blocked on a lock in an epoch during an epoch_wait");
115 static counter_u64_t switch_count;
116 
117 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, switches, CTLFLAG_RW,
118     &switch_count, "# of times a thread voluntarily context switched in epoch_wait");
119 static counter_u64_t epoch_call_count;
120 
121 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, epoch_calls, CTLFLAG_RW,
122     &epoch_call_count, "# of times a callback was deferred");
123 static counter_u64_t epoch_call_task_count;
124 
125 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, epoch_call_tasks, CTLFLAG_RW,
126     &epoch_call_task_count, "# of times a callback task was run");
127 
128 TAILQ_HEAD (threadlist, thread);
129 
130 CK_STACK_CONTAINER(struct ck_epoch_entry, stack_entry,
131     ck_epoch_entry_container)
132 
133 static struct epoch epoch_array[MAX_EPOCHS];
134 
135 DPCPU_DEFINE(struct grouptask, epoch_cb_task);
136 DPCPU_DEFINE(int, epoch_cb_count);
137 
138 static __read_mostly int inited;
139 __read_mostly epoch_t global_epoch;
140 __read_mostly epoch_t global_epoch_preempt;
141 
142 static void epoch_call_task(void *context __unused);
143 static 	uma_zone_t pcpu_zone_record;
144 
145 static struct sx epoch_sx;
146 
147 #define	EPOCH_LOCK() sx_xlock(&epoch_sx)
148 #define	EPOCH_UNLOCK() sx_xunlock(&epoch_sx)
149 
150 #ifdef EPOCH_TRACE
151 struct stackentry {
152 	RB_ENTRY(stackentry) se_node;
153 	struct stack se_stack;
154 };
155 
156 static int
157 stackentry_compare(struct stackentry *a, struct stackentry *b)
158 {
159 
160 	if (a->se_stack.depth > b->se_stack.depth)
161 		return (1);
162 	if (a->se_stack.depth < b->se_stack.depth)
163 		return (-1);
164 	for (int i = 0; i < a->se_stack.depth; i++) {
165 		if (a->se_stack.pcs[i] > b->se_stack.pcs[i])
166 			return (1);
167 		if (a->se_stack.pcs[i] < b->se_stack.pcs[i])
168 			return (-1);
169 	}
170 
171 	return (0);
172 }
173 
174 RB_HEAD(stacktree, stackentry) epoch_stacks = RB_INITIALIZER(&epoch_stacks);
175 RB_GENERATE_STATIC(stacktree, stackentry, se_node, stackentry_compare);
176 
177 static struct mtx epoch_stacks_lock;
178 MTX_SYSINIT(epochstacks, &epoch_stacks_lock, "epoch_stacks", MTX_DEF);
179 
180 static bool epoch_trace_stack_print = true;
181 SYSCTL_BOOL(_kern_epoch, OID_AUTO, trace_stack_print, CTLFLAG_RWTUN,
182     &epoch_trace_stack_print, 0, "Print stack traces on epoch reports");
183 
184 static void epoch_trace_report(const char *fmt, ...) __printflike(1, 2);
185 static inline void
186 epoch_trace_report(const char *fmt, ...)
187 {
188 	va_list ap;
189 	struct stackentry se, *new;
190 
191 	stack_zero(&se.se_stack);	/* XXX: is it really needed? */
192 	stack_save(&se.se_stack);
193 
194 	/* Tree is never reduced - go lockless. */
195 	if (RB_FIND(stacktree, &epoch_stacks, &se) != NULL)
196 		return;
197 
198 	new = malloc(sizeof(*new), M_STACK, M_NOWAIT);
199 	if (new != NULL) {
200 		bcopy(&se.se_stack, &new->se_stack, sizeof(struct stack));
201 
202 		mtx_lock(&epoch_stacks_lock);
203 		new = RB_INSERT(stacktree, &epoch_stacks, new);
204 		mtx_unlock(&epoch_stacks_lock);
205 		if (new != NULL)
206 			free(new, M_STACK);
207 	}
208 
209 	va_start(ap, fmt);
210 	(void)vprintf(fmt, ap);
211 	va_end(ap);
212 	if (epoch_trace_stack_print)
213 		stack_print_ddb(&se.se_stack);
214 }
215 
216 static inline void
217 epoch_trace_enter(struct thread *td, epoch_t epoch, epoch_tracker_t et,
218     const char *file, int line)
219 {
220 	epoch_tracker_t iet;
221 
222 	SLIST_FOREACH(iet, &td->td_epochs, et_tlink)
223 		if (iet->et_epoch == epoch)
224 			epoch_trace_report("Recursively entering epoch %s "
225 			    "at %s:%d, previously entered at %s:%d\n",
226 			    epoch->e_name, file, line,
227 			    iet->et_file, iet->et_line);
228 	et->et_epoch = epoch;
229 	et->et_file = file;
230 	et->et_line = line;
231 	SLIST_INSERT_HEAD(&td->td_epochs, et, et_tlink);
232 }
233 
234 static inline void
235 epoch_trace_exit(struct thread *td, epoch_t epoch, epoch_tracker_t et,
236     const char *file, int line)
237 {
238 
239 	if (SLIST_FIRST(&td->td_epochs) != et) {
240 		epoch_trace_report("Exiting epoch %s in a not nested order "
241 		    "at %s:%d. Most recently entered %s at %s:%d\n",
242 		    epoch->e_name,
243 		    file, line,
244 		    SLIST_FIRST(&td->td_epochs)->et_epoch->e_name,
245 		    SLIST_FIRST(&td->td_epochs)->et_file,
246 		    SLIST_FIRST(&td->td_epochs)->et_line);
247 		/* This will panic if et is not anywhere on td_epochs. */
248 		SLIST_REMOVE(&td->td_epochs, et, epoch_tracker, et_tlink);
249 	} else
250 		SLIST_REMOVE_HEAD(&td->td_epochs, et_tlink);
251 }
252 
253 /* Used by assertions that check thread state before going to sleep. */
254 void
255 epoch_trace_list(struct thread *td)
256 {
257 	epoch_tracker_t iet;
258 
259 	SLIST_FOREACH(iet, &td->td_epochs, et_tlink)
260 		printf("Epoch %s entered at %s:%d\n", iet->et_epoch->e_name,
261 		    iet->et_file, iet->et_line);
262 }
263 #endif /* EPOCH_TRACE */
264 
265 static void
266 epoch_init(void *arg __unused)
267 {
268 	int cpu;
269 
270 	block_count = counter_u64_alloc(M_WAITOK);
271 	migrate_count = counter_u64_alloc(M_WAITOK);
272 	turnstile_count = counter_u64_alloc(M_WAITOK);
273 	switch_count = counter_u64_alloc(M_WAITOK);
274 	epoch_call_count = counter_u64_alloc(M_WAITOK);
275 	epoch_call_task_count = counter_u64_alloc(M_WAITOK);
276 
277 	pcpu_zone_record = uma_zcreate("epoch_record pcpu",
278 	    sizeof(struct epoch_record), NULL, NULL, NULL, NULL,
279 	    UMA_ALIGN_PTR, UMA_ZONE_PCPU);
280 	CPU_FOREACH(cpu) {
281 		GROUPTASK_INIT(DPCPU_ID_PTR(cpu, epoch_cb_task), 0,
282 		    epoch_call_task, NULL);
283 		taskqgroup_attach_cpu(qgroup_softirq,
284 		    DPCPU_ID_PTR(cpu, epoch_cb_task), NULL, cpu, NULL, NULL,
285 		    "epoch call task");
286 	}
287 #ifdef EPOCH_TRACE
288 	SLIST_INIT(&thread0.td_epochs);
289 #endif
290 	sx_init(&epoch_sx, "epoch-sx");
291 	inited = 1;
292 	global_epoch = epoch_alloc("Global", 0);
293 	global_epoch_preempt = epoch_alloc("Global preemptible", EPOCH_PREEMPT);
294 }
295 SYSINIT(epoch, SI_SUB_EPOCH, SI_ORDER_FIRST, epoch_init, NULL);
296 
297 #if !defined(EARLY_AP_STARTUP)
298 static void
299 epoch_init_smp(void *dummy __unused)
300 {
301 	inited = 2;
302 }
303 SYSINIT(epoch_smp, SI_SUB_SMP + 1, SI_ORDER_FIRST, epoch_init_smp, NULL);
304 #endif
305 
306 static void
307 epoch_ctor(epoch_t epoch)
308 {
309 	epoch_record_t er;
310 	int cpu;
311 
312 	epoch->e_pcpu_record = uma_zalloc_pcpu(pcpu_zone_record, M_WAITOK);
313 	CPU_FOREACH(cpu) {
314 		er = zpcpu_get_cpu(epoch->e_pcpu_record, cpu);
315 		bzero(er, sizeof(*er));
316 		ck_epoch_register(&epoch->e_epoch, &er->er_record, NULL);
317 		TAILQ_INIT((struct threadlist *)(uintptr_t)&er->er_tdlist);
318 		er->er_cpuid = cpu;
319 		er->er_parent = epoch;
320 	}
321 }
322 
323 static void
324 epoch_adjust_prio(struct thread *td, u_char prio)
325 {
326 
327 	thread_lock(td);
328 	sched_prio(td, prio);
329 	thread_unlock(td);
330 }
331 
332 epoch_t
333 epoch_alloc(const char *name, int flags)
334 {
335 	epoch_t epoch;
336 	int i;
337 
338 	MPASS(name != NULL);
339 
340 	if (__predict_false(!inited))
341 		panic("%s called too early in boot", __func__);
342 
343 	EPOCH_LOCK();
344 
345 	/*
346 	 * Find a free index in the epoch array. If no free index is
347 	 * found, try to use the index after the last one.
348 	 */
349 	for (i = 0;; i++) {
350 		/*
351 		 * If too many epochs are currently allocated,
352 		 * return NULL.
353 		 */
354 		if (i == MAX_EPOCHS) {
355 			epoch = NULL;
356 			goto done;
357 		}
358 		if (epoch_array[i].e_in_use == 0)
359 			break;
360 	}
361 
362 	epoch = epoch_array + i;
363 	ck_epoch_init(&epoch->e_epoch);
364 	epoch_ctor(epoch);
365 	epoch->e_flags = flags;
366 	epoch->e_name = name;
367 	sx_init(&epoch->e_drain_sx, "epoch-drain-sx");
368 	mtx_init(&epoch->e_drain_mtx, "epoch-drain-mtx", NULL, MTX_DEF);
369 
370 	/*
371 	 * Set e_in_use last, because when this field is set the
372 	 * epoch_call_task() function will start scanning this epoch
373 	 * structure.
374 	 */
375 	atomic_store_rel_int(&epoch->e_in_use, 1);
376 done:
377 	EPOCH_UNLOCK();
378 	return (epoch);
379 }
380 
381 void
382 epoch_free(epoch_t epoch)
383 {
384 #ifdef INVARIANTS
385 	int cpu;
386 #endif
387 
388 	EPOCH_LOCK();
389 
390 	MPASS(epoch->e_in_use != 0);
391 
392 	epoch_drain_callbacks(epoch);
393 
394 	atomic_store_rel_int(&epoch->e_in_use, 0);
395 	/*
396 	 * Make sure the epoch_call_task() function see e_in_use equal
397 	 * to zero, by calling epoch_wait() on the global_epoch:
398 	 */
399 	epoch_wait(global_epoch);
400 #ifdef INVARIANTS
401 	CPU_FOREACH(cpu) {
402 		epoch_record_t er;
403 
404 		er = zpcpu_get_cpu(epoch->e_pcpu_record, cpu);
405 
406 		/*
407 		 * Sanity check: none of the records should be in use anymore.
408 		 * We drained callbacks above and freeing the pcpu records is
409 		 * imminent.
410 		 */
411 		MPASS(er->er_td == NULL);
412 		MPASS(TAILQ_EMPTY(&er->er_tdlist));
413 	}
414 #endif
415 	uma_zfree_pcpu(pcpu_zone_record, epoch->e_pcpu_record);
416 	mtx_destroy(&epoch->e_drain_mtx);
417 	sx_destroy(&epoch->e_drain_sx);
418 	memset(epoch, 0, sizeof(*epoch));
419 
420 	EPOCH_UNLOCK();
421 }
422 
423 static epoch_record_t
424 epoch_currecord(epoch_t epoch)
425 {
426 
427 	return (zpcpu_get(epoch->e_pcpu_record));
428 }
429 
430 #define INIT_CHECK(epoch)					\
431 	do {							\
432 		if (__predict_false((epoch) == NULL))		\
433 			return;					\
434 	} while (0)
435 
436 void
437 _epoch_enter_preempt(epoch_t epoch, epoch_tracker_t et EPOCH_FILE_LINE)
438 {
439 	struct epoch_record *er;
440 	struct thread *td;
441 
442 	MPASS(cold || epoch != NULL);
443 	MPASS(epoch->e_flags & EPOCH_PREEMPT);
444 	td = curthread;
445 	MPASS((vm_offset_t)et >= td->td_kstack &&
446 	    (vm_offset_t)et + sizeof(struct epoch_tracker) <=
447 	    td->td_kstack + td->td_kstack_pages * PAGE_SIZE);
448 
449 	INIT_CHECK(epoch);
450 #ifdef EPOCH_TRACE
451 	epoch_trace_enter(td, epoch, et, file, line);
452 #endif
453 	et->et_td = td;
454 	THREAD_NO_SLEEPING();
455 	critical_enter();
456 	sched_pin();
457 	td->td_pre_epoch_prio = td->td_priority;
458 	er = epoch_currecord(epoch);
459 	/* Record-level tracking is reserved for non-preemptible epochs. */
460 	MPASS(er->er_td == NULL);
461 	TAILQ_INSERT_TAIL(&er->er_tdlist, et, et_link);
462 	ck_epoch_begin(&er->er_record, &et->et_section);
463 	critical_exit();
464 }
465 
466 void
467 epoch_enter(epoch_t epoch)
468 {
469 	epoch_record_t er;
470 
471 	MPASS(cold || epoch != NULL);
472 	INIT_CHECK(epoch);
473 	critical_enter();
474 	er = epoch_currecord(epoch);
475 #ifdef INVARIANTS
476 	if (er->er_record.active == 0) {
477 		MPASS(er->er_td == NULL);
478 		er->er_td = curthread;
479 	} else {
480 		/* We've recursed, just make sure our accounting isn't wrong. */
481 		MPASS(er->er_td == curthread);
482 	}
483 #endif
484 	ck_epoch_begin(&er->er_record, NULL);
485 }
486 
487 void
488 _epoch_exit_preempt(epoch_t epoch, epoch_tracker_t et EPOCH_FILE_LINE)
489 {
490 	struct epoch_record *er;
491 	struct thread *td;
492 
493 	INIT_CHECK(epoch);
494 	td = curthread;
495 	critical_enter();
496 	sched_unpin();
497 	THREAD_SLEEPING_OK();
498 	er = epoch_currecord(epoch);
499 	MPASS(epoch->e_flags & EPOCH_PREEMPT);
500 	MPASS(et != NULL);
501 	MPASS(et->et_td == td);
502 #ifdef INVARIANTS
503 	et->et_td = (void*)0xDEADBEEF;
504 	/* Record-level tracking is reserved for non-preemptible epochs. */
505 	MPASS(er->er_td == NULL);
506 #endif
507 	ck_epoch_end(&er->er_record, &et->et_section);
508 	TAILQ_REMOVE(&er->er_tdlist, et, et_link);
509 	er->er_gen++;
510 	if (__predict_false(td->td_pre_epoch_prio != td->td_priority))
511 		epoch_adjust_prio(td, td->td_pre_epoch_prio);
512 	critical_exit();
513 #ifdef EPOCH_TRACE
514 	epoch_trace_exit(td, epoch, et, file, line);
515 #endif
516 }
517 
518 void
519 epoch_exit(epoch_t epoch)
520 {
521 	epoch_record_t er;
522 
523 	INIT_CHECK(epoch);
524 	er = epoch_currecord(epoch);
525 	ck_epoch_end(&er->er_record, NULL);
526 #ifdef INVARIANTS
527 	MPASS(er->er_td == curthread);
528 	if (er->er_record.active == 0)
529 		er->er_td = NULL;
530 #endif
531 	critical_exit();
532 }
533 
534 /*
535  * epoch_block_handler_preempt() is a callback from the CK code when another
536  * thread is currently in an epoch section.
537  */
538 static void
539 epoch_block_handler_preempt(struct ck_epoch *global __unused,
540     ck_epoch_record_t *cr, void *arg __unused)
541 {
542 	epoch_record_t record;
543 	struct thread *td, *owner, *curwaittd;
544 	struct epoch_tracker *tdwait;
545 	struct turnstile *ts;
546 	struct lock_object *lock;
547 	int spincount, gen;
548 	int locksheld __unused;
549 
550 	record = __containerof(cr, struct epoch_record, er_record);
551 	td = curthread;
552 	locksheld = td->td_locks;
553 	spincount = 0;
554 	counter_u64_add(block_count, 1);
555 	/*
556 	 * We lost a race and there's no longer any threads
557 	 * on the CPU in an epoch section.
558 	 */
559 	if (TAILQ_EMPTY(&record->er_tdlist))
560 		return;
561 
562 	if (record->er_cpuid != curcpu) {
563 		/*
564 		 * If the head of the list is running, we can wait for it
565 		 * to remove itself from the list and thus save us the
566 		 * overhead of a migration
567 		 */
568 		gen = record->er_gen;
569 		thread_unlock(td);
570 		/*
571 		 * We can't actually check if the waiting thread is running
572 		 * so we simply poll for it to exit before giving up and
573 		 * migrating.
574 		 */
575 		do {
576 			cpu_spinwait();
577 		} while (!TAILQ_EMPTY(&record->er_tdlist) &&
578 				 gen == record->er_gen &&
579 				 spincount++ < MAX_ADAPTIVE_SPIN);
580 		thread_lock(td);
581 		/*
582 		 * If the generation has changed we can poll again
583 		 * otherwise we need to migrate.
584 		 */
585 		if (gen != record->er_gen)
586 			return;
587 		/*
588 		 * Being on the same CPU as that of the record on which
589 		 * we need to wait allows us access to the thread
590 		 * list associated with that CPU. We can then examine the
591 		 * oldest thread in the queue and wait on its turnstile
592 		 * until it resumes and so on until a grace period
593 		 * elapses.
594 		 *
595 		 */
596 		counter_u64_add(migrate_count, 1);
597 		sched_bind(td, record->er_cpuid);
598 		/*
599 		 * At this point we need to return to the ck code
600 		 * to scan to see if a grace period has elapsed.
601 		 * We can't move on to check the thread list, because
602 		 * in the meantime new threads may have arrived that
603 		 * in fact belong to a different epoch.
604 		 */
605 		return;
606 	}
607 	/*
608 	 * Try to find a thread in an epoch section on this CPU
609 	 * waiting on a turnstile. Otherwise find the lowest
610 	 * priority thread (highest prio value) and drop our priority
611 	 * to match to allow it to run.
612 	 */
613 	TAILQ_FOREACH(tdwait, &record->er_tdlist, et_link) {
614 		/*
615 		 * Propagate our priority to any other waiters to prevent us
616 		 * from starving them. They will have their original priority
617 		 * restore on exit from epoch_wait().
618 		 */
619 		curwaittd = tdwait->et_td;
620 		if (!TD_IS_INHIBITED(curwaittd) && curwaittd->td_priority > td->td_priority) {
621 			critical_enter();
622 			thread_unlock(td);
623 			thread_lock(curwaittd);
624 			sched_prio(curwaittd, td->td_priority);
625 			thread_unlock(curwaittd);
626 			thread_lock(td);
627 			critical_exit();
628 		}
629 		if (TD_IS_INHIBITED(curwaittd) && TD_ON_LOCK(curwaittd) &&
630 		    ((ts = curwaittd->td_blocked) != NULL)) {
631 			/*
632 			 * We unlock td to allow turnstile_wait to reacquire
633 			 * the thread lock. Before unlocking it we enter a
634 			 * critical section to prevent preemption after we
635 			 * reenable interrupts by dropping the thread lock in
636 			 * order to prevent curwaittd from getting to run.
637 			 */
638 			critical_enter();
639 			thread_unlock(td);
640 
641 			if (turnstile_lock(ts, &lock, &owner)) {
642 				if (ts == curwaittd->td_blocked) {
643 					MPASS(TD_IS_INHIBITED(curwaittd) &&
644 					    TD_ON_LOCK(curwaittd));
645 					critical_exit();
646 					turnstile_wait(ts, owner,
647 					    curwaittd->td_tsqueue);
648 					counter_u64_add(turnstile_count, 1);
649 					thread_lock(td);
650 					return;
651 				}
652 				turnstile_unlock(ts, lock);
653 			}
654 			thread_lock(td);
655 			critical_exit();
656 			KASSERT(td->td_locks == locksheld,
657 			    ("%d extra locks held", td->td_locks - locksheld));
658 		}
659 	}
660 	/*
661 	 * We didn't find any threads actually blocked on a lock
662 	 * so we have nothing to do except context switch away.
663 	 */
664 	counter_u64_add(switch_count, 1);
665 	mi_switch(SW_VOL | SWT_RELINQUISH);
666 	/*
667 	 * It is important the thread lock is dropped while yielding
668 	 * to allow other threads to acquire the lock pointed to by
669 	 * TDQ_LOCKPTR(td). Currently mi_switch() will unlock the
670 	 * thread lock before returning. Else a deadlock like
671 	 * situation might happen.
672 	 */
673 	thread_lock(td);
674 }
675 
676 void
677 epoch_wait_preempt(epoch_t epoch)
678 {
679 	struct thread *td;
680 	int was_bound;
681 	int old_cpu;
682 	int old_pinned;
683 	u_char old_prio;
684 	int locks __unused;
685 
686 	MPASS(cold || epoch != NULL);
687 	INIT_CHECK(epoch);
688 	td = curthread;
689 #ifdef INVARIANTS
690 	locks = curthread->td_locks;
691 	MPASS(epoch->e_flags & EPOCH_PREEMPT);
692 	if ((epoch->e_flags & EPOCH_LOCKED) == 0)
693 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
694 		    "epoch_wait() can be long running");
695 	KASSERT(!in_epoch(epoch), ("epoch_wait_preempt() called in the middle "
696 	    "of an epoch section of the same epoch"));
697 #endif
698 	DROP_GIANT();
699 	thread_lock(td);
700 
701 	old_cpu = PCPU_GET(cpuid);
702 	old_pinned = td->td_pinned;
703 	old_prio = td->td_priority;
704 	was_bound = sched_is_bound(td);
705 	sched_unbind(td);
706 	td->td_pinned = 0;
707 	sched_bind(td, old_cpu);
708 
709 	ck_epoch_synchronize_wait(&epoch->e_epoch, epoch_block_handler_preempt,
710 	    NULL);
711 
712 	/* restore CPU binding, if any */
713 	if (was_bound != 0) {
714 		sched_bind(td, old_cpu);
715 	} else {
716 		/* get thread back to initial CPU, if any */
717 		if (old_pinned != 0)
718 			sched_bind(td, old_cpu);
719 		sched_unbind(td);
720 	}
721 	/* restore pinned after bind */
722 	td->td_pinned = old_pinned;
723 
724 	/* restore thread priority */
725 	sched_prio(td, old_prio);
726 	thread_unlock(td);
727 	PICKUP_GIANT();
728 	KASSERT(td->td_locks == locks,
729 	    ("%d residual locks held", td->td_locks - locks));
730 }
731 
732 static void
733 epoch_block_handler(struct ck_epoch *g __unused, ck_epoch_record_t *c __unused,
734     void *arg __unused)
735 {
736 	cpu_spinwait();
737 }
738 
739 void
740 epoch_wait(epoch_t epoch)
741 {
742 
743 	MPASS(cold || epoch != NULL);
744 	INIT_CHECK(epoch);
745 	MPASS(epoch->e_flags == 0);
746 	critical_enter();
747 	ck_epoch_synchronize_wait(&epoch->e_epoch, epoch_block_handler, NULL);
748 	critical_exit();
749 }
750 
751 void
752 epoch_call(epoch_t epoch, epoch_callback_t callback, epoch_context_t ctx)
753 {
754 	epoch_record_t er;
755 	ck_epoch_entry_t *cb;
756 
757 	cb = (void *)ctx;
758 
759 	MPASS(callback);
760 	/* too early in boot to have epoch set up */
761 	if (__predict_false(epoch == NULL))
762 		goto boottime;
763 #if !defined(EARLY_AP_STARTUP)
764 	if (__predict_false(inited < 2))
765 		goto boottime;
766 #endif
767 
768 	critical_enter();
769 	*DPCPU_PTR(epoch_cb_count) += 1;
770 	er = epoch_currecord(epoch);
771 	ck_epoch_call(&er->er_record, cb, (ck_epoch_cb_t *)callback);
772 	critical_exit();
773 	return;
774 boottime:
775 	callback(ctx);
776 }
777 
778 static void
779 epoch_call_task(void *arg __unused)
780 {
781 	ck_stack_entry_t *cursor, *head, *next;
782 	ck_epoch_record_t *record;
783 	epoch_record_t er;
784 	epoch_t epoch;
785 	ck_stack_t cb_stack;
786 	int i, npending, total;
787 
788 	ck_stack_init(&cb_stack);
789 	critical_enter();
790 	epoch_enter(global_epoch);
791 	for (total = i = 0; i != MAX_EPOCHS; i++) {
792 		epoch = epoch_array + i;
793 		if (__predict_false(
794 		    atomic_load_acq_int(&epoch->e_in_use) == 0))
795 			continue;
796 		er = epoch_currecord(epoch);
797 		record = &er->er_record;
798 		if ((npending = record->n_pending) == 0)
799 			continue;
800 		ck_epoch_poll_deferred(record, &cb_stack);
801 		total += npending - record->n_pending;
802 	}
803 	epoch_exit(global_epoch);
804 	*DPCPU_PTR(epoch_cb_count) -= total;
805 	critical_exit();
806 
807 	counter_u64_add(epoch_call_count, total);
808 	counter_u64_add(epoch_call_task_count, 1);
809 
810 	head = ck_stack_batch_pop_npsc(&cb_stack);
811 	for (cursor = head; cursor != NULL; cursor = next) {
812 		struct ck_epoch_entry *entry =
813 		    ck_epoch_entry_container(cursor);
814 
815 		next = CK_STACK_NEXT(cursor);
816 		entry->function(entry);
817 	}
818 }
819 
820 static int
821 in_epoch_verbose_preempt(epoch_t epoch, int dump_onfail)
822 {
823 	epoch_record_t er;
824 	struct epoch_tracker *tdwait;
825 	struct thread *td;
826 
827 	MPASS(epoch != NULL);
828 	MPASS((epoch->e_flags & EPOCH_PREEMPT) != 0);
829 	td = curthread;
830 	if (THREAD_CAN_SLEEP())
831 		return (0);
832 	critical_enter();
833 	er = epoch_currecord(epoch);
834 	TAILQ_FOREACH(tdwait, &er->er_tdlist, et_link)
835 		if (tdwait->et_td == td) {
836 			critical_exit();
837 			return (1);
838 		}
839 #ifdef INVARIANTS
840 	if (dump_onfail) {
841 		MPASS(td->td_pinned);
842 		printf("cpu: %d id: %d\n", curcpu, td->td_tid);
843 		TAILQ_FOREACH(tdwait, &er->er_tdlist, et_link)
844 			printf("td_tid: %d ", tdwait->et_td->td_tid);
845 		printf("\n");
846 	}
847 #endif
848 	critical_exit();
849 	return (0);
850 }
851 
852 #ifdef INVARIANTS
853 static void
854 epoch_assert_nocpu(epoch_t epoch, struct thread *td)
855 {
856 	epoch_record_t er;
857 	int cpu;
858 	bool crit;
859 
860 	crit = td->td_critnest > 0;
861 
862 	/* Check for a critical section mishap. */
863 	CPU_FOREACH(cpu) {
864 		er = zpcpu_get_cpu(epoch->e_pcpu_record, cpu);
865 		KASSERT(er->er_td != td,
866 		    ("%s critical section in epoch '%s', from cpu %d",
867 		    (crit ? "exited" : "re-entered"), epoch->e_name, cpu));
868 	}
869 }
870 #else
871 #define	epoch_assert_nocpu(e, td)
872 #endif
873 
874 int
875 in_epoch_verbose(epoch_t epoch, int dump_onfail)
876 {
877 	epoch_record_t er;
878 	struct thread *td;
879 
880 	if (__predict_false((epoch) == NULL))
881 		return (0);
882 	if ((epoch->e_flags & EPOCH_PREEMPT) != 0)
883 		return (in_epoch_verbose_preempt(epoch, dump_onfail));
884 
885 	/*
886 	 * The thread being in a critical section is a necessary
887 	 * condition to be correctly inside a non-preemptible epoch,
888 	 * so it's definitely not in this epoch.
889 	 */
890 	td = curthread;
891 	if (td->td_critnest == 0) {
892 		epoch_assert_nocpu(epoch, td);
893 		return (0);
894 	}
895 
896 	/*
897 	 * The current cpu is in a critical section, so the epoch record will be
898 	 * stable for the rest of this function.  Knowing that the record is not
899 	 * active is sufficient for knowing whether we're in this epoch or not,
900 	 * since it's a pcpu record.
901 	 */
902 	er = epoch_currecord(epoch);
903 	if (er->er_record.active == 0) {
904 		epoch_assert_nocpu(epoch, td);
905 		return (0);
906 	}
907 
908 	MPASS(er->er_td == td);
909 	return (1);
910 }
911 
912 int
913 in_epoch(epoch_t epoch)
914 {
915 	return (in_epoch_verbose(epoch, 0));
916 }
917 
918 static void
919 epoch_drain_cb(struct epoch_context *ctx)
920 {
921 	struct epoch *epoch =
922 	    __containerof(ctx, struct epoch_record, er_drain_ctx)->er_parent;
923 
924 	if (atomic_fetchadd_int(&epoch->e_drain_count, -1) == 1) {
925 		mtx_lock(&epoch->e_drain_mtx);
926 		wakeup(epoch);
927 		mtx_unlock(&epoch->e_drain_mtx);
928 	}
929 }
930 
931 void
932 epoch_drain_callbacks(epoch_t epoch)
933 {
934 	epoch_record_t er;
935 	struct thread *td;
936 	int was_bound;
937 	int old_pinned;
938 	int old_cpu;
939 	int cpu;
940 
941 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
942 	    "epoch_drain_callbacks() may sleep!");
943 
944 	/* too early in boot to have epoch set up */
945 	if (__predict_false(epoch == NULL))
946 		return;
947 #if !defined(EARLY_AP_STARTUP)
948 	if (__predict_false(inited < 2))
949 		return;
950 #endif
951 	DROP_GIANT();
952 
953 	sx_xlock(&epoch->e_drain_sx);
954 	mtx_lock(&epoch->e_drain_mtx);
955 
956 	td = curthread;
957 	thread_lock(td);
958 	old_cpu = PCPU_GET(cpuid);
959 	old_pinned = td->td_pinned;
960 	was_bound = sched_is_bound(td);
961 	sched_unbind(td);
962 	td->td_pinned = 0;
963 
964 	CPU_FOREACH(cpu)
965 		epoch->e_drain_count++;
966 	CPU_FOREACH(cpu) {
967 		er = zpcpu_get_cpu(epoch->e_pcpu_record, cpu);
968 		sched_bind(td, cpu);
969 		epoch_call(epoch, &epoch_drain_cb, &er->er_drain_ctx);
970 	}
971 
972 	/* restore CPU binding, if any */
973 	if (was_bound != 0) {
974 		sched_bind(td, old_cpu);
975 	} else {
976 		/* get thread back to initial CPU, if any */
977 		if (old_pinned != 0)
978 			sched_bind(td, old_cpu);
979 		sched_unbind(td);
980 	}
981 	/* restore pinned after bind */
982 	td->td_pinned = old_pinned;
983 
984 	thread_unlock(td);
985 
986 	while (epoch->e_drain_count != 0)
987 		msleep(epoch, &epoch->e_drain_mtx, PZERO, "EDRAIN", 0);
988 
989 	mtx_unlock(&epoch->e_drain_mtx);
990 	sx_xunlock(&epoch->e_drain_sx);
991 
992 	PICKUP_GIANT();
993 }
994