xref: /f-stack/freebsd/kern/subr_epoch.c (revision 22ce4aff)
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/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
stackentry_compare(struct stackentry * a,struct stackentry * b)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
epoch_trace_report(const char * fmt,...)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
epoch_trace_enter(struct thread * td,epoch_t epoch,epoch_tracker_t et,const char * file,int line)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
epoch_trace_exit(struct thread * td,epoch_t epoch,epoch_tracker_t et,const char * file,int line)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
epoch_trace_list(struct thread * td)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
epoch_init(void * arg __unused)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 #ifndef FSTACK
284 		taskqgroup_attach_cpu(qgroup_softirq,
285 		    DPCPU_ID_PTR(cpu, epoch_cb_task), NULL, cpu, NULL, NULL,
286 		    "epoch call task");
287 #endif
288 	}
289 #ifdef EPOCH_TRACE
290 	SLIST_INIT(&thread0.td_epochs);
291 #endif
292 	sx_init(&epoch_sx, "epoch-sx");
293 	inited = 1;
294 	global_epoch = epoch_alloc("Global", 0);
295 	global_epoch_preempt = epoch_alloc("Global preemptible", EPOCH_PREEMPT);
296 }
297 SYSINIT(epoch, SI_SUB_EPOCH, SI_ORDER_FIRST, epoch_init, NULL);
298 
299 #if !defined(EARLY_AP_STARTUP)
300 static void
epoch_init_smp(void * dummy __unused)301 epoch_init_smp(void *dummy __unused)
302 {
303 	inited = 2;
304 }
305 SYSINIT(epoch_smp, SI_SUB_SMP + 1, SI_ORDER_FIRST, epoch_init_smp, NULL);
306 #endif
307 
308 static void
epoch_ctor(epoch_t epoch)309 epoch_ctor(epoch_t epoch)
310 {
311 	epoch_record_t er;
312 	int cpu;
313 
314 	epoch->e_pcpu_record = uma_zalloc_pcpu(pcpu_zone_record, M_WAITOK);
315 	CPU_FOREACH(cpu) {
316 		er = zpcpu_get_cpu(epoch->e_pcpu_record, cpu);
317 		bzero(er, sizeof(*er));
318 		ck_epoch_register(&epoch->e_epoch, &er->er_record, NULL);
319 		TAILQ_INIT((struct threadlist *)(uintptr_t)&er->er_tdlist);
320 		er->er_cpuid = cpu;
321 		er->er_parent = epoch;
322 	}
323 }
324 
325 static void
epoch_adjust_prio(struct thread * td,u_char prio)326 epoch_adjust_prio(struct thread *td, u_char prio)
327 {
328 
329 	thread_lock(td);
330 	sched_prio(td, prio);
331 	thread_unlock(td);
332 }
333 
334 epoch_t
epoch_alloc(const char * name,int flags)335 epoch_alloc(const char *name, int flags)
336 {
337 	epoch_t epoch;
338 	int i;
339 
340 	MPASS(name != NULL);
341 
342 	if (__predict_false(!inited))
343 		panic("%s called too early in boot", __func__);
344 
345 	EPOCH_LOCK();
346 
347 	/*
348 	 * Find a free index in the epoch array. If no free index is
349 	 * found, try to use the index after the last one.
350 	 */
351 	for (i = 0;; i++) {
352 		/*
353 		 * If too many epochs are currently allocated,
354 		 * return NULL.
355 		 */
356 		if (i == MAX_EPOCHS) {
357 			epoch = NULL;
358 			goto done;
359 		}
360 		if (epoch_array[i].e_in_use == 0)
361 			break;
362 	}
363 
364 	epoch = epoch_array + i;
365 	ck_epoch_init(&epoch->e_epoch);
366 	epoch_ctor(epoch);
367 	epoch->e_flags = flags;
368 	epoch->e_name = name;
369 	sx_init(&epoch->e_drain_sx, "epoch-drain-sx");
370 	mtx_init(&epoch->e_drain_mtx, "epoch-drain-mtx", NULL, MTX_DEF);
371 
372 	/*
373 	 * Set e_in_use last, because when this field is set the
374 	 * epoch_call_task() function will start scanning this epoch
375 	 * structure.
376 	 */
377 	atomic_store_rel_int(&epoch->e_in_use, 1);
378 done:
379 	EPOCH_UNLOCK();
380 	return (epoch);
381 }
382 
383 void
epoch_free(epoch_t epoch)384 epoch_free(epoch_t epoch)
385 {
386 #ifdef INVARIANTS
387 	int cpu;
388 #endif
389 
390 	EPOCH_LOCK();
391 
392 	MPASS(epoch->e_in_use != 0);
393 
394 	epoch_drain_callbacks(epoch);
395 
396 	atomic_store_rel_int(&epoch->e_in_use, 0);
397 	/*
398 	 * Make sure the epoch_call_task() function see e_in_use equal
399 	 * to zero, by calling epoch_wait() on the global_epoch:
400 	 */
401 	epoch_wait(global_epoch);
402 #ifdef INVARIANTS
403 	CPU_FOREACH(cpu) {
404 		epoch_record_t er;
405 
406 		er = zpcpu_get_cpu(epoch->e_pcpu_record, cpu);
407 
408 		/*
409 		 * Sanity check: none of the records should be in use anymore.
410 		 * We drained callbacks above and freeing the pcpu records is
411 		 * imminent.
412 		 */
413 		MPASS(er->er_td == NULL);
414 		MPASS(TAILQ_EMPTY(&er->er_tdlist));
415 	}
416 #endif
417 	uma_zfree_pcpu(pcpu_zone_record, epoch->e_pcpu_record);
418 	mtx_destroy(&epoch->e_drain_mtx);
419 	sx_destroy(&epoch->e_drain_sx);
420 	memset(epoch, 0, sizeof(*epoch));
421 
422 	EPOCH_UNLOCK();
423 }
424 
425 static epoch_record_t
epoch_currecord(epoch_t epoch)426 epoch_currecord(epoch_t epoch)
427 {
428 
429 	return (zpcpu_get(epoch->e_pcpu_record));
430 }
431 
432 #define INIT_CHECK(epoch)					\
433 	do {							\
434 		if (__predict_false((epoch) == NULL))		\
435 			return;					\
436 	} while (0)
437 
438 void
_epoch_enter_preempt(epoch_t epoch,epoch_tracker_t et EPOCH_FILE_LINE)439 _epoch_enter_preempt(epoch_t epoch, epoch_tracker_t et EPOCH_FILE_LINE)
440 {
441 	struct epoch_record *er;
442 	struct thread *td;
443 
444 	MPASS(cold || epoch != NULL);
445 	MPASS(epoch->e_flags & EPOCH_PREEMPT);
446 	td = curthread;
447 	MPASS((vm_offset_t)et >= td->td_kstack &&
448 	    (vm_offset_t)et + sizeof(struct epoch_tracker) <=
449 	    td->td_kstack + td->td_kstack_pages * PAGE_SIZE);
450 
451 	INIT_CHECK(epoch);
452 #ifdef EPOCH_TRACE
453 	epoch_trace_enter(td, epoch, et, file, line);
454 #endif
455 	et->et_td = td;
456 	THREAD_NO_SLEEPING();
457 	critical_enter();
458 	sched_pin();
459 	td->td_pre_epoch_prio = td->td_priority;
460 	er = epoch_currecord(epoch);
461 	/* Record-level tracking is reserved for non-preemptible epochs. */
462 	MPASS(er->er_td == NULL);
463 	TAILQ_INSERT_TAIL(&er->er_tdlist, et, et_link);
464 	ck_epoch_begin(&er->er_record, &et->et_section);
465 	critical_exit();
466 }
467 
468 void
epoch_enter(epoch_t epoch)469 epoch_enter(epoch_t epoch)
470 {
471 	epoch_record_t er;
472 
473 	MPASS(cold || epoch != NULL);
474 	INIT_CHECK(epoch);
475 	critical_enter();
476 	er = epoch_currecord(epoch);
477 #ifdef INVARIANTS
478 	if (er->er_record.active == 0) {
479 		MPASS(er->er_td == NULL);
480 		er->er_td = curthread;
481 	} else {
482 		/* We've recursed, just make sure our accounting isn't wrong. */
483 		MPASS(er->er_td == curthread);
484 	}
485 #endif
486 	ck_epoch_begin(&er->er_record, NULL);
487 }
488 
489 void
_epoch_exit_preempt(epoch_t epoch,epoch_tracker_t et EPOCH_FILE_LINE)490 _epoch_exit_preempt(epoch_t epoch, epoch_tracker_t et EPOCH_FILE_LINE)
491 {
492 	struct epoch_record *er;
493 	struct thread *td;
494 
495 	INIT_CHECK(epoch);
496 	td = curthread;
497 	critical_enter();
498 	sched_unpin();
499 	THREAD_SLEEPING_OK();
500 	er = epoch_currecord(epoch);
501 	MPASS(epoch->e_flags & EPOCH_PREEMPT);
502 	MPASS(et != NULL);
503 	MPASS(et->et_td == td);
504 #ifdef INVARIANTS
505 	et->et_td = (void*)0xDEADBEEF;
506 	/* Record-level tracking is reserved for non-preemptible epochs. */
507 	MPASS(er->er_td == NULL);
508 #endif
509 	ck_epoch_end(&er->er_record, &et->et_section);
510 	TAILQ_REMOVE(&er->er_tdlist, et, et_link);
511 	er->er_gen++;
512 	if (__predict_false(td->td_pre_epoch_prio != td->td_priority))
513 		epoch_adjust_prio(td, td->td_pre_epoch_prio);
514 	critical_exit();
515 #ifdef EPOCH_TRACE
516 	epoch_trace_exit(td, epoch, et, file, line);
517 #endif
518 }
519 
520 void
epoch_exit(epoch_t epoch)521 epoch_exit(epoch_t epoch)
522 {
523 	epoch_record_t er;
524 
525 	INIT_CHECK(epoch);
526 	er = epoch_currecord(epoch);
527 	ck_epoch_end(&er->er_record, NULL);
528 #ifdef INVARIANTS
529 	MPASS(er->er_td == curthread);
530 	if (er->er_record.active == 0)
531 		er->er_td = NULL;
532 #endif
533 	critical_exit();
534 }
535 
536 /*
537  * epoch_block_handler_preempt() is a callback from the CK code when another
538  * thread is currently in an epoch section.
539  */
540 static void
epoch_block_handler_preempt(struct ck_epoch * global __unused,ck_epoch_record_t * cr,void * arg __unused)541 epoch_block_handler_preempt(struct ck_epoch *global __unused,
542     ck_epoch_record_t *cr, void *arg __unused)
543 {
544 	epoch_record_t record;
545 	struct thread *td, *owner, *curwaittd;
546 	struct epoch_tracker *tdwait;
547 	struct turnstile *ts;
548 	struct lock_object *lock;
549 	int spincount, gen;
550 	int locksheld __unused;
551 
552 	record = __containerof(cr, struct epoch_record, er_record);
553 	td = curthread;
554 	locksheld = td->td_locks;
555 	spincount = 0;
556 	counter_u64_add(block_count, 1);
557 	/*
558 	 * We lost a race and there's no longer any threads
559 	 * on the CPU in an epoch section.
560 	 */
561 	if (TAILQ_EMPTY(&record->er_tdlist))
562 		return;
563 
564 	if (record->er_cpuid != curcpu) {
565 		/*
566 		 * If the head of the list is running, we can wait for it
567 		 * to remove itself from the list and thus save us the
568 		 * overhead of a migration
569 		 */
570 		gen = record->er_gen;
571 		thread_unlock(td);
572 		/*
573 		 * We can't actually check if the waiting thread is running
574 		 * so we simply poll for it to exit before giving up and
575 		 * migrating.
576 		 */
577 		do {
578 			cpu_spinwait();
579 		} while (!TAILQ_EMPTY(&record->er_tdlist) &&
580 				 gen == record->er_gen &&
581 				 spincount++ < MAX_ADAPTIVE_SPIN);
582 		thread_lock(td);
583 		/*
584 		 * If the generation has changed we can poll again
585 		 * otherwise we need to migrate.
586 		 */
587 		if (gen != record->er_gen)
588 			return;
589 		/*
590 		 * Being on the same CPU as that of the record on which
591 		 * we need to wait allows us access to the thread
592 		 * list associated with that CPU. We can then examine the
593 		 * oldest thread in the queue and wait on its turnstile
594 		 * until it resumes and so on until a grace period
595 		 * elapses.
596 		 *
597 		 */
598 		counter_u64_add(migrate_count, 1);
599 		sched_bind(td, record->er_cpuid);
600 		/*
601 		 * At this point we need to return to the ck code
602 		 * to scan to see if a grace period has elapsed.
603 		 * We can't move on to check the thread list, because
604 		 * in the meantime new threads may have arrived that
605 		 * in fact belong to a different epoch.
606 		 */
607 		return;
608 	}
609 	/*
610 	 * Try to find a thread in an epoch section on this CPU
611 	 * waiting on a turnstile. Otherwise find the lowest
612 	 * priority thread (highest prio value) and drop our priority
613 	 * to match to allow it to run.
614 	 */
615 	TAILQ_FOREACH(tdwait, &record->er_tdlist, et_link) {
616 		/*
617 		 * Propagate our priority to any other waiters to prevent us
618 		 * from starving them. They will have their original priority
619 		 * restore on exit from epoch_wait().
620 		 */
621 		curwaittd = tdwait->et_td;
622 		if (!TD_IS_INHIBITED(curwaittd) && curwaittd->td_priority > td->td_priority) {
623 			critical_enter();
624 			thread_unlock(td);
625 			thread_lock(curwaittd);
626 			sched_prio(curwaittd, td->td_priority);
627 			thread_unlock(curwaittd);
628 			thread_lock(td);
629 			critical_exit();
630 		}
631 		if (TD_IS_INHIBITED(curwaittd) && TD_ON_LOCK(curwaittd) &&
632 		    ((ts = curwaittd->td_blocked) != NULL)) {
633 			/*
634 			 * We unlock td to allow turnstile_wait to reacquire
635 			 * the thread lock. Before unlocking it we enter a
636 			 * critical section to prevent preemption after we
637 			 * reenable interrupts by dropping the thread lock in
638 			 * order to prevent curwaittd from getting to run.
639 			 */
640 			critical_enter();
641 			thread_unlock(td);
642 
643 			if (turnstile_lock(ts, &lock, &owner)) {
644 				if (ts == curwaittd->td_blocked) {
645 					MPASS(TD_IS_INHIBITED(curwaittd) &&
646 					    TD_ON_LOCK(curwaittd));
647 					critical_exit();
648 					turnstile_wait(ts, owner,
649 					    curwaittd->td_tsqueue);
650 					counter_u64_add(turnstile_count, 1);
651 					thread_lock(td);
652 					return;
653 				}
654 				turnstile_unlock(ts, lock);
655 			}
656 			thread_lock(td);
657 			critical_exit();
658 			KASSERT(td->td_locks == locksheld,
659 			    ("%d extra locks held", td->td_locks - locksheld));
660 		}
661 	}
662 	/*
663 	 * We didn't find any threads actually blocked on a lock
664 	 * so we have nothing to do except context switch away.
665 	 */
666 	counter_u64_add(switch_count, 1);
667 	mi_switch(SW_VOL | SWT_RELINQUISH);
668 	/*
669 	 * It is important the thread lock is dropped while yielding
670 	 * to allow other threads to acquire the lock pointed to by
671 	 * TDQ_LOCKPTR(td). Currently mi_switch() will unlock the
672 	 * thread lock before returning. Else a deadlock like
673 	 * situation might happen.
674 	 */
675 	thread_lock(td);
676 }
677 
678 void
epoch_wait_preempt(epoch_t epoch)679 epoch_wait_preempt(epoch_t epoch)
680 {
681 	struct thread *td;
682 	int was_bound;
683 	int old_cpu;
684 	int old_pinned;
685 	u_char old_prio;
686 	int locks __unused;
687 
688 	MPASS(cold || epoch != NULL);
689 	INIT_CHECK(epoch);
690 	td = curthread;
691 #ifdef INVARIANTS
692 	locks = curthread->td_locks;
693 	MPASS(epoch->e_flags & EPOCH_PREEMPT);
694 	if ((epoch->e_flags & EPOCH_LOCKED) == 0)
695 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
696 		    "epoch_wait() can be long running");
697 	KASSERT(!in_epoch(epoch), ("epoch_wait_preempt() called in the middle "
698 	    "of an epoch section of the same epoch"));
699 #endif
700 	DROP_GIANT();
701 	thread_lock(td);
702 
703 	old_cpu = PCPU_GET(cpuid);
704 	old_pinned = td->td_pinned;
705 	old_prio = td->td_priority;
706 	was_bound = sched_is_bound(td);
707 	sched_unbind(td);
708 	td->td_pinned = 0;
709 	sched_bind(td, old_cpu);
710 
711 	ck_epoch_synchronize_wait(&epoch->e_epoch, epoch_block_handler_preempt,
712 	    NULL);
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 	/* restore thread priority */
727 	sched_prio(td, old_prio);
728 	thread_unlock(td);
729 	PICKUP_GIANT();
730 	KASSERT(td->td_locks == locks,
731 	    ("%d residual locks held", td->td_locks - locks));
732 }
733 
734 static void
epoch_block_handler(struct ck_epoch * g __unused,ck_epoch_record_t * c __unused,void * arg __unused)735 epoch_block_handler(struct ck_epoch *g __unused, ck_epoch_record_t *c __unused,
736     void *arg __unused)
737 {
738 	cpu_spinwait();
739 }
740 
741 void
epoch_wait(epoch_t epoch)742 epoch_wait(epoch_t epoch)
743 {
744 
745 	MPASS(cold || epoch != NULL);
746 	INIT_CHECK(epoch);
747 	MPASS(epoch->e_flags == 0);
748 	critical_enter();
749 	ck_epoch_synchronize_wait(&epoch->e_epoch, epoch_block_handler, NULL);
750 	critical_exit();
751 }
752 
753 void
epoch_call(epoch_t epoch,epoch_callback_t callback,epoch_context_t ctx)754 epoch_call(epoch_t epoch, epoch_callback_t callback, epoch_context_t ctx)
755 {
756 	epoch_record_t er;
757 	ck_epoch_entry_t *cb;
758 
759 	cb = (void *)ctx;
760 
761 	MPASS(callback);
762 	/* too early in boot to have epoch set up */
763 	if (__predict_false(epoch == NULL))
764 		goto boottime;
765 #if !defined(EARLY_AP_STARTUP)
766 	if (__predict_false(inited < 2))
767 		goto boottime;
768 #endif
769 
770 	critical_enter();
771 	*DPCPU_PTR(epoch_cb_count) += 1;
772 	er = epoch_currecord(epoch);
773 	ck_epoch_call(&er->er_record, cb, (ck_epoch_cb_t *)callback);
774 	critical_exit();
775 	return;
776 boottime:
777 	callback(ctx);
778 }
779 
780 static void
epoch_call_task(void * arg __unused)781 epoch_call_task(void *arg __unused)
782 {
783 	ck_stack_entry_t *cursor, *head, *next;
784 	ck_epoch_record_t *record;
785 	epoch_record_t er;
786 	epoch_t epoch;
787 	ck_stack_t cb_stack;
788 	int i, npending, total;
789 
790 	ck_stack_init(&cb_stack);
791 	critical_enter();
792 	epoch_enter(global_epoch);
793 	for (total = i = 0; i != MAX_EPOCHS; i++) {
794 		epoch = epoch_array + i;
795 		if (__predict_false(
796 		    atomic_load_acq_int(&epoch->e_in_use) == 0))
797 			continue;
798 		er = epoch_currecord(epoch);
799 		record = &er->er_record;
800 		if ((npending = record->n_pending) == 0)
801 			continue;
802 		ck_epoch_poll_deferred(record, &cb_stack);
803 		total += npending - record->n_pending;
804 	}
805 	epoch_exit(global_epoch);
806 	*DPCPU_PTR(epoch_cb_count) -= total;
807 	critical_exit();
808 
809 	counter_u64_add(epoch_call_count, total);
810 	counter_u64_add(epoch_call_task_count, 1);
811 
812 	head = ck_stack_batch_pop_npsc(&cb_stack);
813 	for (cursor = head; cursor != NULL; cursor = next) {
814 		struct ck_epoch_entry *entry =
815 		    ck_epoch_entry_container(cursor);
816 
817 		next = CK_STACK_NEXT(cursor);
818 		entry->function(entry);
819 	}
820 }
821 
822 static int
in_epoch_verbose_preempt(epoch_t epoch,int dump_onfail)823 in_epoch_verbose_preempt(epoch_t epoch, int dump_onfail)
824 {
825 	epoch_record_t er;
826 	struct epoch_tracker *tdwait;
827 	struct thread *td;
828 
829 	MPASS(epoch != NULL);
830 	MPASS((epoch->e_flags & EPOCH_PREEMPT) != 0);
831 	td = curthread;
832 	if (THREAD_CAN_SLEEP())
833 		return (0);
834 	critical_enter();
835 	er = epoch_currecord(epoch);
836 	TAILQ_FOREACH(tdwait, &er->er_tdlist, et_link)
837 		if (tdwait->et_td == td) {
838 			critical_exit();
839 			return (1);
840 		}
841 #ifdef INVARIANTS
842 	if (dump_onfail) {
843 		MPASS(td->td_pinned);
844 		printf("cpu: %d id: %d\n", curcpu, td->td_tid);
845 		TAILQ_FOREACH(tdwait, &er->er_tdlist, et_link)
846 			printf("td_tid: %d ", tdwait->et_td->td_tid);
847 		printf("\n");
848 	}
849 #endif
850 	critical_exit();
851 	return (0);
852 }
853 
854 #ifdef INVARIANTS
855 static void
epoch_assert_nocpu(epoch_t epoch,struct thread * td)856 epoch_assert_nocpu(epoch_t epoch, struct thread *td)
857 {
858 	epoch_record_t er;
859 	int cpu;
860 	bool crit;
861 
862 	crit = td->td_critnest > 0;
863 
864 	/* Check for a critical section mishap. */
865 	CPU_FOREACH(cpu) {
866 		er = zpcpu_get_cpu(epoch->e_pcpu_record, cpu);
867 		KASSERT(er->er_td != td,
868 		    ("%s critical section in epoch '%s', from cpu %d",
869 		    (crit ? "exited" : "re-entered"), epoch->e_name, cpu));
870 	}
871 }
872 #else
873 #define	epoch_assert_nocpu(e, td)
874 #endif
875 
876 int
in_epoch_verbose(epoch_t epoch,int dump_onfail)877 in_epoch_verbose(epoch_t epoch, int dump_onfail)
878 {
879 	epoch_record_t er;
880 	struct thread *td;
881 
882 	if (__predict_false((epoch) == NULL))
883 		return (0);
884 	if ((epoch->e_flags & EPOCH_PREEMPT) != 0)
885 		return (in_epoch_verbose_preempt(epoch, dump_onfail));
886 
887 	/*
888 	 * The thread being in a critical section is a necessary
889 	 * condition to be correctly inside a non-preemptible epoch,
890 	 * so it's definitely not in this epoch.
891 	 */
892 	td = curthread;
893 	if (td->td_critnest == 0) {
894 		epoch_assert_nocpu(epoch, td);
895 		return (0);
896 	}
897 
898 	/*
899 	 * The current cpu is in a critical section, so the epoch record will be
900 	 * stable for the rest of this function.  Knowing that the record is not
901 	 * active is sufficient for knowing whether we're in this epoch or not,
902 	 * since it's a pcpu record.
903 	 */
904 	er = epoch_currecord(epoch);
905 	if (er->er_record.active == 0) {
906 		epoch_assert_nocpu(epoch, td);
907 		return (0);
908 	}
909 
910 	MPASS(er->er_td == td);
911 	return (1);
912 }
913 
914 int
in_epoch(epoch_t epoch)915 in_epoch(epoch_t epoch)
916 {
917 	return (in_epoch_verbose(epoch, 0));
918 }
919 
920 static void
epoch_drain_cb(struct epoch_context * ctx)921 epoch_drain_cb(struct epoch_context *ctx)
922 {
923 	struct epoch *epoch =
924 	    __containerof(ctx, struct epoch_record, er_drain_ctx)->er_parent;
925 
926 	if (atomic_fetchadd_int(&epoch->e_drain_count, -1) == 1) {
927 		mtx_lock(&epoch->e_drain_mtx);
928 		wakeup(epoch);
929 		mtx_unlock(&epoch->e_drain_mtx);
930 	}
931 }
932 
933 void
epoch_drain_callbacks(epoch_t epoch)934 epoch_drain_callbacks(epoch_t epoch)
935 {
936 	epoch_record_t er;
937 	struct thread *td;
938 	int was_bound;
939 	int old_pinned;
940 	int old_cpu;
941 	int cpu;
942 
943 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
944 	    "epoch_drain_callbacks() may sleep!");
945 
946 	/* too early in boot to have epoch set up */
947 	if (__predict_false(epoch == NULL))
948 		return;
949 #if !defined(EARLY_AP_STARTUP)
950 	if (__predict_false(inited < 2))
951 		return;
952 #endif
953 	DROP_GIANT();
954 
955 	sx_xlock(&epoch->e_drain_sx);
956 	mtx_lock(&epoch->e_drain_mtx);
957 
958 	td = curthread;
959 	thread_lock(td);
960 	old_cpu = PCPU_GET(cpuid);
961 	old_pinned = td->td_pinned;
962 	was_bound = sched_is_bound(td);
963 	sched_unbind(td);
964 	td->td_pinned = 0;
965 
966 	CPU_FOREACH(cpu)
967 		epoch->e_drain_count++;
968 	CPU_FOREACH(cpu) {
969 		er = zpcpu_get_cpu(epoch->e_pcpu_record, cpu);
970 		sched_bind(td, cpu);
971 		epoch_call(epoch, &epoch_drain_cb, &er->er_drain_ctx);
972 	}
973 
974 	/* restore CPU binding, if any */
975 	if (was_bound != 0) {
976 		sched_bind(td, old_cpu);
977 	} else {
978 		/* get thread back to initial CPU, if any */
979 		if (old_pinned != 0)
980 			sched_bind(td, old_cpu);
981 		sched_unbind(td);
982 	}
983 	/* restore pinned after bind */
984 	td->td_pinned = old_pinned;
985 
986 	thread_unlock(td);
987 
988 	while (epoch->e_drain_count != 0)
989 		msleep(epoch, &epoch->e_drain_mtx, PZERO, "EDRAIN", 0);
990 
991 	mtx_unlock(&epoch->e_drain_mtx);
992 	sx_xunlock(&epoch->e_drain_sx);
993 
994 	PICKUP_GIANT();
995 }
996