xref: /freebsd-12.1/sys/kern/subr_epoch.c (revision b2898feb)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2018, Matthew Macy <[email protected]>
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/types.h>
34 #include <sys/systm.h>
35 #include <sys/counter.h>
36 #include <sys/epoch.h>
37 #include <sys/gtaskqueue.h>
38 #include <sys/kernel.h>
39 #include <sys/limits.h>
40 #include <sys/lock.h>
41 #include <sys/malloc.h>
42 #include <sys/mutex.h>
43 #include <sys/pcpu.h>
44 #include <sys/proc.h>
45 #include <sys/sched.h>
46 #include <sys/sx.h>
47 #include <sys/smp.h>
48 #include <sys/sysctl.h>
49 #include <sys/turnstile.h>
50 #include <vm/vm.h>
51 #include <vm/vm_extern.h>
52 #include <vm/vm_kern.h>
53 #include <vm/uma.h>
54 
55 #include <ck_epoch.h>
56 
57 static MALLOC_DEFINE(M_EPOCH, "epoch", "epoch based reclamation");
58 
59 #ifdef __amd64__
60 #define EPOCH_ALIGN CACHE_LINE_SIZE*2
61 #else
62 #define EPOCH_ALIGN CACHE_LINE_SIZE
63 #endif
64 
65 TAILQ_HEAD (epoch_tdlist, epoch_tracker);
66 typedef struct epoch_record {
67 	ck_epoch_record_t er_record;
68 	volatile struct epoch_tdlist er_tdlist;
69 	volatile uint32_t er_gen;
70 	uint32_t er_cpuid;
71 	/* fields above are part of KBI and cannot be modified */
72 	struct epoch_context er_drain_ctx;
73 	struct epoch *er_parent;
74 } __aligned(EPOCH_ALIGN)     *epoch_record_t;
75 
76 struct epoch {
77 	struct ck_epoch e_epoch __aligned(EPOCH_ALIGN);
78 	epoch_record_t e_pcpu_record;
79 	int	e_idx;
80 	int	e_flags;
81 	/* fields above are part of KBI and cannot be modified */
82 	struct sx e_drain_sx;
83 	struct mtx e_drain_mtx;
84 	volatile int e_drain_count;
85 };
86 
87 /* arbitrary --- needs benchmarking */
88 #define MAX_ADAPTIVE_SPIN 100
89 #define MAX_EPOCHS 64
90 
91 CTASSERT(sizeof(ck_epoch_entry_t) == sizeof(struct epoch_context));
92 SYSCTL_NODE(_kern, OID_AUTO, epoch, CTLFLAG_RW, 0, "epoch information");
93 SYSCTL_NODE(_kern_epoch, OID_AUTO, stats, CTLFLAG_RW, 0, "epoch stats");
94 
95 /* Stats. */
96 static counter_u64_t block_count;
97 
98 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, nblocked, CTLFLAG_RW,
99     &block_count, "# of times a thread was in an epoch when epoch_wait was called");
100 static counter_u64_t migrate_count;
101 
102 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, migrations, CTLFLAG_RW,
103     &migrate_count, "# of times thread was migrated to another CPU in epoch_wait");
104 static counter_u64_t turnstile_count;
105 
106 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, ncontended, CTLFLAG_RW,
107     &turnstile_count, "# of times a thread was blocked on a lock in an epoch during an epoch_wait");
108 static counter_u64_t switch_count;
109 
110 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, switches, CTLFLAG_RW,
111     &switch_count, "# of times a thread voluntarily context switched in epoch_wait");
112 static counter_u64_t epoch_call_count;
113 
114 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, epoch_calls, CTLFLAG_RW,
115     &epoch_call_count, "# of times a callback was deferred");
116 static counter_u64_t epoch_call_task_count;
117 
118 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, epoch_call_tasks, CTLFLAG_RW,
119     &epoch_call_task_count, "# of times a callback task was run");
120 
121 TAILQ_HEAD (threadlist, thread);
122 
123 CK_STACK_CONTAINER(struct ck_epoch_entry, stack_entry,
124     ck_epoch_entry_container)
125 
126 epoch_t	allepochs[MAX_EPOCHS];
127 
128 DPCPU_DEFINE(struct grouptask, epoch_cb_task);
129 DPCPU_DEFINE(int, epoch_cb_count);
130 
131 static __read_mostly int inited;
132 static __read_mostly int epoch_count;
133 __read_mostly epoch_t global_epoch;
134 __read_mostly epoch_t global_epoch_preempt;
135 
136 static void epoch_call_task(void *context __unused);
137 static 	uma_zone_t pcpu_zone_record;
138 
139 static void
epoch_init(void * arg __unused)140 epoch_init(void *arg __unused)
141 {
142 	int cpu;
143 
144 	block_count = counter_u64_alloc(M_WAITOK);
145 	migrate_count = counter_u64_alloc(M_WAITOK);
146 	turnstile_count = counter_u64_alloc(M_WAITOK);
147 	switch_count = counter_u64_alloc(M_WAITOK);
148 	epoch_call_count = counter_u64_alloc(M_WAITOK);
149 	epoch_call_task_count = counter_u64_alloc(M_WAITOK);
150 
151 	pcpu_zone_record = uma_zcreate("epoch_record pcpu",
152 	    sizeof(struct epoch_record), NULL, NULL, NULL, NULL,
153 	    UMA_ALIGN_PTR, UMA_ZONE_PCPU);
154 	CPU_FOREACH(cpu) {
155 		GROUPTASK_INIT(DPCPU_ID_PTR(cpu, epoch_cb_task), 0,
156 		    epoch_call_task, NULL);
157 		taskqgroup_attach_cpu(qgroup_softirq,
158 		    DPCPU_ID_PTR(cpu, epoch_cb_task), NULL, cpu, -1,
159 		    "epoch call task");
160 	}
161 	inited = 1;
162 	global_epoch = epoch_alloc(0);
163 	global_epoch_preempt = epoch_alloc(EPOCH_PREEMPT);
164 }
165 SYSINIT(epoch, SI_SUB_TASKQ + 1, SI_ORDER_FIRST, epoch_init, NULL);
166 
167 #if !defined(EARLY_AP_STARTUP)
168 static void
epoch_init_smp(void * dummy __unused)169 epoch_init_smp(void *dummy __unused)
170 {
171 	inited = 2;
172 }
173 SYSINIT(epoch_smp, SI_SUB_SMP + 1, SI_ORDER_FIRST, epoch_init_smp, NULL);
174 #endif
175 
176 static void
epoch_ctor(epoch_t epoch)177 epoch_ctor(epoch_t epoch)
178 {
179 	epoch_record_t er;
180 	int cpu;
181 
182 	epoch->e_pcpu_record = uma_zalloc_pcpu(pcpu_zone_record, M_WAITOK);
183 	CPU_FOREACH(cpu) {
184 		er = zpcpu_get_cpu(epoch->e_pcpu_record, cpu);
185 		bzero(er, sizeof(*er));
186 		ck_epoch_register(&epoch->e_epoch, &er->er_record, NULL);
187 		TAILQ_INIT((struct threadlist *)(uintptr_t)&er->er_tdlist);
188 		er->er_cpuid = cpu;
189 		er->er_parent = epoch;
190 	}
191 }
192 
193 static void
epoch_adjust_prio(struct thread * td,u_char prio)194 epoch_adjust_prio(struct thread *td, u_char prio)
195 {
196 
197 	thread_lock(td);
198 	sched_prio(td, prio);
199 	thread_unlock(td);
200 }
201 
202 epoch_t
epoch_alloc(int flags)203 epoch_alloc(int flags)
204 {
205 	epoch_t epoch;
206 
207 	if (__predict_false(!inited))
208 		panic("%s called too early in boot", __func__);
209 	epoch = malloc(sizeof(struct epoch), M_EPOCH, M_ZERO | M_WAITOK);
210 	ck_epoch_init(&epoch->e_epoch);
211 	epoch_ctor(epoch);
212 	MPASS(epoch_count < MAX_EPOCHS - 2);
213 	epoch->e_flags = flags;
214 	epoch->e_idx = epoch_count;
215 	sx_init(&epoch->e_drain_sx, "epoch-drain-sx");
216 	mtx_init(&epoch->e_drain_mtx, "epoch-drain-mtx", NULL, MTX_DEF);
217 	allepochs[epoch_count++] = epoch;
218 	return (epoch);
219 }
220 
221 void
epoch_free(epoch_t epoch)222 epoch_free(epoch_t epoch)
223 {
224 
225 	epoch_drain_callbacks(epoch);
226 	allepochs[epoch->e_idx] = NULL;
227 	epoch_wait(global_epoch);
228 	uma_zfree_pcpu(pcpu_zone_record, epoch->e_pcpu_record);
229 	mtx_destroy(&epoch->e_drain_mtx);
230 	sx_destroy(&epoch->e_drain_sx);
231 	free(epoch, M_EPOCH);
232 }
233 
234 static epoch_record_t
epoch_currecord(epoch_t epoch)235 epoch_currecord(epoch_t epoch)
236 {
237 
238 	return (zpcpu_get_cpu(epoch->e_pcpu_record, curcpu));
239 }
240 
241 #define INIT_CHECK(epoch)					\
242 	do {							\
243 		if (__predict_false((epoch) == NULL))		\
244 			return;					\
245 	} while (0)
246 
247 void
epoch_enter_preempt(epoch_t epoch,epoch_tracker_t et)248 epoch_enter_preempt(epoch_t epoch, epoch_tracker_t et)
249 {
250 	struct epoch_record *er;
251 	struct thread *td;
252 
253 	MPASS(cold || epoch != NULL);
254 	INIT_CHECK(epoch);
255 	MPASS(epoch->e_flags & EPOCH_PREEMPT);
256 #ifdef EPOCH_TRACKER_DEBUG
257 	et->et_magic_pre = EPOCH_MAGIC0;
258 	et->et_magic_post = EPOCH_MAGIC1;
259 #endif
260 	td = curthread;
261 	et->et_td = td;
262 	td->td_epochnest++;
263 	critical_enter();
264 	sched_pin();
265 
266 	td->td_pre_epoch_prio = td->td_priority;
267 	er = epoch_currecord(epoch);
268 	TAILQ_INSERT_TAIL(&er->er_tdlist, et, et_link);
269 	ck_epoch_begin(&er->er_record, &et->et_section);
270 	critical_exit();
271 }
272 
273 void
epoch_enter(epoch_t epoch)274 epoch_enter(epoch_t epoch)
275 {
276 	struct thread *td;
277 	epoch_record_t er;
278 
279 	MPASS(cold || epoch != NULL);
280 	INIT_CHECK(epoch);
281 	td = curthread;
282 
283 	td->td_epochnest++;
284 	critical_enter();
285 	er = epoch_currecord(epoch);
286 	ck_epoch_begin(&er->er_record, NULL);
287 }
288 
289 void
epoch_exit_preempt(epoch_t epoch,epoch_tracker_t et)290 epoch_exit_preempt(epoch_t epoch, epoch_tracker_t et)
291 {
292 	struct epoch_record *er;
293 	struct thread *td;
294 
295 	INIT_CHECK(epoch);
296 	td = curthread;
297 	critical_enter();
298 	sched_unpin();
299 	MPASS(td->td_epochnest);
300 	td->td_epochnest--;
301 	er = epoch_currecord(epoch);
302 	MPASS(epoch->e_flags & EPOCH_PREEMPT);
303 	MPASS(et != NULL);
304 	MPASS(et->et_td == td);
305 #ifdef EPOCH_TRACKER_DEBUG
306 	MPASS(et->et_magic_pre == EPOCH_MAGIC0);
307 	MPASS(et->et_magic_post == EPOCH_MAGIC1);
308 	et->et_magic_pre = 0;
309 	et->et_magic_post = 0;
310 #endif
311 #ifdef INVARIANTS
312 	et->et_td = (void*)0xDEADBEEF;
313 #endif
314 	ck_epoch_end(&er->er_record, &et->et_section);
315 	TAILQ_REMOVE(&er->er_tdlist, et, et_link);
316 	er->er_gen++;
317 	if (__predict_false(td->td_pre_epoch_prio != td->td_priority))
318 		epoch_adjust_prio(td, td->td_pre_epoch_prio);
319 	critical_exit();
320 }
321 
322 void
epoch_exit(epoch_t epoch)323 epoch_exit(epoch_t epoch)
324 {
325 	struct thread *td;
326 	epoch_record_t er;
327 
328 	INIT_CHECK(epoch);
329 	td = curthread;
330 	MPASS(td->td_epochnest);
331 	td->td_epochnest--;
332 	er = epoch_currecord(epoch);
333 	ck_epoch_end(&er->er_record, NULL);
334 	critical_exit();
335 }
336 
337 /*
338  * epoch_block_handler_preempt() is a callback from the CK code when another
339  * thread is currently in an epoch section.
340  */
341 static void
epoch_block_handler_preempt(struct ck_epoch * global __unused,ck_epoch_record_t * cr,void * arg __unused)342 epoch_block_handler_preempt(struct ck_epoch *global __unused,
343     ck_epoch_record_t *cr, void *arg __unused)
344 {
345 	epoch_record_t record;
346 	struct thread *td, *owner, *curwaittd;
347 	struct epoch_tracker *tdwait;
348 	struct turnstile *ts;
349 	struct lock_object *lock;
350 	int spincount, gen;
351 	int locksheld __unused;
352 
353 	record = __containerof(cr, struct epoch_record, er_record);
354 	td = curthread;
355 	locksheld = td->td_locks;
356 	spincount = 0;
357 	counter_u64_add(block_count, 1);
358 	/*
359 	 * We lost a race and there's no longer any threads
360 	 * on the CPU in an epoch section.
361 	 */
362 	if (TAILQ_EMPTY(&record->er_tdlist))
363 		return;
364 
365 	if (record->er_cpuid != curcpu) {
366 		/*
367 		 * If the head of the list is running, we can wait for it
368 		 * to remove itself from the list and thus save us the
369 		 * overhead of a migration
370 		 */
371 		gen = record->er_gen;
372 		thread_unlock(td);
373 		/*
374 		 * We can't actually check if the waiting thread is running
375 		 * so we simply poll for it to exit before giving up and
376 		 * migrating.
377 		 */
378 		do {
379 			cpu_spinwait();
380 		} while (!TAILQ_EMPTY(&record->er_tdlist) &&
381 				 gen == record->er_gen &&
382 				 spincount++ < MAX_ADAPTIVE_SPIN);
383 		thread_lock(td);
384 		/*
385 		 * If the generation has changed we can poll again
386 		 * otherwise we need to migrate.
387 		 */
388 		if (gen != record->er_gen)
389 			return;
390 		/*
391 		 * Being on the same CPU as that of the record on which
392 		 * we need to wait allows us access to the thread
393 		 * list associated with that CPU. We can then examine the
394 		 * oldest thread in the queue and wait on its turnstile
395 		 * until it resumes and so on until a grace period
396 		 * elapses.
397 		 *
398 		 */
399 		counter_u64_add(migrate_count, 1);
400 		sched_bind(td, record->er_cpuid);
401 		/*
402 		 * At this point we need to return to the ck code
403 		 * to scan to see if a grace period has elapsed.
404 		 * We can't move on to check the thread list, because
405 		 * in the meantime new threads may have arrived that
406 		 * in fact belong to a different epoch.
407 		 */
408 		return;
409 	}
410 	/*
411 	 * Try to find a thread in an epoch section on this CPU
412 	 * waiting on a turnstile. Otherwise find the lowest
413 	 * priority thread (highest prio value) and drop our priority
414 	 * to match to allow it to run.
415 	 */
416 	TAILQ_FOREACH(tdwait, &record->er_tdlist, et_link) {
417 		/*
418 		 * Propagate our priority to any other waiters to prevent us
419 		 * from starving them. They will have their original priority
420 		 * restore on exit from epoch_wait().
421 		 */
422 		curwaittd = tdwait->et_td;
423 		if (!TD_IS_INHIBITED(curwaittd) && curwaittd->td_priority > td->td_priority) {
424 			critical_enter();
425 			thread_unlock(td);
426 			thread_lock(curwaittd);
427 			sched_prio(curwaittd, td->td_priority);
428 			thread_unlock(curwaittd);
429 			thread_lock(td);
430 			critical_exit();
431 		}
432 		if (TD_IS_INHIBITED(curwaittd) && TD_ON_LOCK(curwaittd) &&
433 		    ((ts = curwaittd->td_blocked) != NULL)) {
434 			/*
435 			 * We unlock td to allow turnstile_wait to reacquire
436 			 * the thread lock. Before unlocking it we enter a
437 			 * critical section to prevent preemption after we
438 			 * reenable interrupts by dropping the thread lock in
439 			 * order to prevent curwaittd from getting to run.
440 			 */
441 			critical_enter();
442 			thread_unlock(td);
443 
444 			if (turnstile_lock(ts, &lock, &owner)) {
445 				if (ts == curwaittd->td_blocked) {
446 					MPASS(TD_IS_INHIBITED(curwaittd) &&
447 					    TD_ON_LOCK(curwaittd));
448 					critical_exit();
449 					turnstile_wait(ts, owner,
450 					    curwaittd->td_tsqueue);
451 					counter_u64_add(turnstile_count, 1);
452 					thread_lock(td);
453 					return;
454 				}
455 				turnstile_unlock(ts, lock);
456 			}
457 			thread_lock(td);
458 			critical_exit();
459 			KASSERT(td->td_locks == locksheld,
460 			    ("%d extra locks held", td->td_locks - locksheld));
461 		}
462 	}
463 	/*
464 	 * We didn't find any threads actually blocked on a lock
465 	 * so we have nothing to do except context switch away.
466 	 */
467 	counter_u64_add(switch_count, 1);
468 	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
469 
470 	/*
471 	 * Release the thread lock while yielding to
472 	 * allow other threads to acquire the lock
473 	 * pointed to by TDQ_LOCKPTR(td). Else a
474 	 * deadlock like situation might happen. (HPS)
475 	 */
476 	thread_unlock(td);
477 	thread_lock(td);
478 }
479 
480 void
epoch_wait_preempt(epoch_t epoch)481 epoch_wait_preempt(epoch_t epoch)
482 {
483 	struct thread *td;
484 	int was_bound;
485 	int old_cpu;
486 	int old_pinned;
487 	u_char old_prio;
488 	int locks __unused;
489 
490 	MPASS(cold || epoch != NULL);
491 	INIT_CHECK(epoch);
492 	td = curthread;
493 #ifdef INVARIANTS
494 	locks = curthread->td_locks;
495 	MPASS(epoch->e_flags & EPOCH_PREEMPT);
496 	if ((epoch->e_flags & EPOCH_LOCKED) == 0)
497 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
498 		    "epoch_wait() can be long running");
499 	KASSERT(!in_epoch(epoch), ("epoch_wait_preempt() called in the middle "
500 	    "of an epoch section of the same epoch"));
501 #endif
502 	thread_lock(td);
503 	DROP_GIANT();
504 
505 	old_cpu = PCPU_GET(cpuid);
506 	old_pinned = td->td_pinned;
507 	old_prio = td->td_priority;
508 	was_bound = sched_is_bound(td);
509 	sched_unbind(td);
510 	td->td_pinned = 0;
511 	sched_bind(td, old_cpu);
512 
513 	ck_epoch_synchronize_wait(&epoch->e_epoch, epoch_block_handler_preempt,
514 	    NULL);
515 
516 	/* restore CPU binding, if any */
517 	if (was_bound != 0) {
518 		sched_bind(td, old_cpu);
519 	} else {
520 		/* get thread back to initial CPU, if any */
521 		if (old_pinned != 0)
522 			sched_bind(td, old_cpu);
523 		sched_unbind(td);
524 	}
525 	/* restore pinned after bind */
526 	td->td_pinned = old_pinned;
527 
528 	/* restore thread priority */
529 	sched_prio(td, old_prio);
530 	thread_unlock(td);
531 	PICKUP_GIANT();
532 	KASSERT(td->td_locks == locks,
533 	    ("%d residual locks held", td->td_locks - locks));
534 }
535 
536 static void
epoch_block_handler(struct ck_epoch * g __unused,ck_epoch_record_t * c __unused,void * arg __unused)537 epoch_block_handler(struct ck_epoch *g __unused, ck_epoch_record_t *c __unused,
538     void *arg __unused)
539 {
540 	cpu_spinwait();
541 }
542 
543 void
epoch_wait(epoch_t epoch)544 epoch_wait(epoch_t epoch)
545 {
546 
547 	MPASS(cold || epoch != NULL);
548 	INIT_CHECK(epoch);
549 	MPASS(epoch->e_flags == 0);
550 	critical_enter();
551 	ck_epoch_synchronize_wait(&epoch->e_epoch, epoch_block_handler, NULL);
552 	critical_exit();
553 }
554 
555 void
epoch_call(epoch_t epoch,epoch_context_t ctx,void (* callback)(epoch_context_t))556 epoch_call(epoch_t epoch, epoch_context_t ctx, void (*callback) (epoch_context_t))
557 {
558 	epoch_record_t er;
559 	ck_epoch_entry_t *cb;
560 
561 	cb = (void *)ctx;
562 
563 	MPASS(callback);
564 	/* too early in boot to have epoch set up */
565 	if (__predict_false(epoch == NULL))
566 		goto boottime;
567 #if !defined(EARLY_AP_STARTUP)
568 	if (__predict_false(inited < 2))
569 		goto boottime;
570 #endif
571 
572 	critical_enter();
573 	*DPCPU_PTR(epoch_cb_count) += 1;
574 	er = epoch_currecord(epoch);
575 	ck_epoch_call(&er->er_record, cb, (ck_epoch_cb_t *)callback);
576 	critical_exit();
577 	return;
578 boottime:
579 	callback(ctx);
580 }
581 
582 static void
epoch_call_task(void * arg __unused)583 epoch_call_task(void *arg __unused)
584 {
585 	ck_stack_entry_t *cursor, *head, *next;
586 	ck_epoch_record_t *record;
587 	epoch_record_t er;
588 	epoch_t epoch;
589 	ck_stack_t cb_stack;
590 	int i, npending, total;
591 
592 	ck_stack_init(&cb_stack);
593 	critical_enter();
594 	epoch_enter(global_epoch);
595 	for (total = i = 0; i < epoch_count; i++) {
596 		if (__predict_false((epoch = allepochs[i]) == NULL))
597 			continue;
598 		er = epoch_currecord(epoch);
599 		record = &er->er_record;
600 		if ((npending = record->n_pending) == 0)
601 			continue;
602 		ck_epoch_poll_deferred(record, &cb_stack);
603 		total += npending - record->n_pending;
604 	}
605 	epoch_exit(global_epoch);
606 	*DPCPU_PTR(epoch_cb_count) -= total;
607 	critical_exit();
608 
609 	counter_u64_add(epoch_call_count, total);
610 	counter_u64_add(epoch_call_task_count, 1);
611 
612 	head = ck_stack_batch_pop_npsc(&cb_stack);
613 	for (cursor = head; cursor != NULL; cursor = next) {
614 		struct ck_epoch_entry *entry =
615 		    ck_epoch_entry_container(cursor);
616 
617 		next = CK_STACK_NEXT(cursor);
618 		entry->function(entry);
619 	}
620 }
621 
622 int
in_epoch_verbose(epoch_t epoch,int dump_onfail)623 in_epoch_verbose(epoch_t epoch, int dump_onfail)
624 {
625 	struct epoch_tracker *tdwait;
626 	struct thread *td;
627 	epoch_record_t er;
628 
629 	td = curthread;
630 	if (td->td_epochnest == 0)
631 		return (0);
632 	if (__predict_false((epoch) == NULL))
633 		return (0);
634 	critical_enter();
635 	er = epoch_currecord(epoch);
636 	TAILQ_FOREACH(tdwait, &er->er_tdlist, et_link)
637 		if (tdwait->et_td == td) {
638 			critical_exit();
639 			return (1);
640 		}
641 #ifdef INVARIANTS
642 	if (dump_onfail) {
643 		MPASS(td->td_pinned);
644 		printf("cpu: %d id: %d\n", curcpu, td->td_tid);
645 		TAILQ_FOREACH(tdwait, &er->er_tdlist, et_link)
646 			printf("td_tid: %d ", tdwait->et_td->td_tid);
647 		printf("\n");
648 	}
649 #endif
650 	critical_exit();
651 	return (0);
652 }
653 
654 int
in_epoch(epoch_t epoch)655 in_epoch(epoch_t epoch)
656 {
657 	return (in_epoch_verbose(epoch, 0));
658 }
659 
660 static void
epoch_drain_cb(struct epoch_context * ctx)661 epoch_drain_cb(struct epoch_context *ctx)
662 {
663 	struct epoch *epoch =
664 	    __containerof(ctx, struct epoch_record, er_drain_ctx)->er_parent;
665 
666 	if (atomic_fetchadd_int(&epoch->e_drain_count, -1) == 1) {
667 		mtx_lock(&epoch->e_drain_mtx);
668 		wakeup(epoch);
669 		mtx_unlock(&epoch->e_drain_mtx);
670 	}
671 }
672 
673 void
epoch_drain_callbacks(epoch_t epoch)674 epoch_drain_callbacks(epoch_t epoch)
675 {
676 	epoch_record_t er;
677 	struct thread *td;
678 	int was_bound;
679 	int old_pinned;
680 	int old_cpu;
681 	int cpu;
682 
683 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
684 	    "epoch_drain_callbacks() may sleep!");
685 
686 	/* too early in boot to have epoch set up */
687 	if (__predict_false(epoch == NULL))
688 		return;
689 #if !defined(EARLY_AP_STARTUP)
690 	if (__predict_false(inited < 2))
691 		return;
692 #endif
693 	DROP_GIANT();
694 
695 	sx_xlock(&epoch->e_drain_sx);
696 	mtx_lock(&epoch->e_drain_mtx);
697 
698 	td = curthread;
699 	thread_lock(td);
700 	old_cpu = PCPU_GET(cpuid);
701 	old_pinned = td->td_pinned;
702 	was_bound = sched_is_bound(td);
703 	sched_unbind(td);
704 	td->td_pinned = 0;
705 
706 	CPU_FOREACH(cpu)
707 		epoch->e_drain_count++;
708 	CPU_FOREACH(cpu) {
709 		er = zpcpu_get_cpu(epoch->e_pcpu_record, cpu);
710 		sched_bind(td, cpu);
711 		epoch_call(epoch, &er->er_drain_ctx, &epoch_drain_cb);
712 	}
713 
714 	/* restore CPU binding, if any */
715 	if (was_bound != 0) {
716 		sched_bind(td, old_cpu);
717 	} else {
718 		/* get thread back to initial CPU, if any */
719 		if (old_pinned != 0)
720 			sched_bind(td, old_cpu);
721 		sched_unbind(td);
722 	}
723 	/* restore pinned after bind */
724 	td->td_pinned = old_pinned;
725 
726 	thread_unlock(td);
727 
728 	while (epoch->e_drain_count != 0)
729 		msleep(epoch, &epoch->e_drain_mtx, PZERO, "EDRAIN", 0);
730 
731 	mtx_unlock(&epoch->e_drain_mtx);
732 	sx_xunlock(&epoch->e_drain_sx);
733 
734 	PICKUP_GIANT();
735 }
736 
737 /* for binary compatibility */
738 
739 struct epoch_tracker_KBI {
740 	void *datap[3];
741 #ifdef EPOCH_TRACKER_DEBUG
742 	int datai[5];
743 #else
744 	int datai[1];
745 #endif
746 } __aligned(sizeof(void *));
747 
748 CTASSERT(sizeof(struct epoch_tracker_KBI) >= sizeof(struct epoch_tracker));
749 
750 void
epoch_enter_preempt_KBI(epoch_t epoch,epoch_tracker_t et)751 epoch_enter_preempt_KBI(epoch_t epoch, epoch_tracker_t et)
752 {
753 	epoch_enter_preempt(epoch, et);
754 }
755 
756 void
epoch_exit_preempt_KBI(epoch_t epoch,epoch_tracker_t et)757 epoch_exit_preempt_KBI(epoch_t epoch, epoch_tracker_t et)
758 {
759 	epoch_exit_preempt(epoch, et);
760 }
761 
762 void
epoch_enter_KBI(epoch_t epoch)763 epoch_enter_KBI(epoch_t epoch)
764 {
765 	epoch_enter(epoch);
766 }
767 
768 void
epoch_exit_KBI(epoch_t epoch)769 epoch_exit_KBI(epoch_t epoch)
770 {
771 	epoch_exit(epoch);
772 }
773