2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2018, Matthew Macy <mmacy@freebsd.org>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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.
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
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
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>
41 #include <sys/malloc.h>
42 #include <sys/mutex.h>
45 #include <sys/sched.h>
48 #include <sys/sysctl.h>
49 #include <sys/turnstile.h>
51 #include <vm/vm_extern.h>
52 #include <vm/vm_kern.h>
57 static MALLOC_DEFINE(M_EPOCH, "epoch", "epoch based reclamation");
60 #define EPOCH_ALIGN CACHE_LINE_SIZE*2
62 #define EPOCH_ALIGN CACHE_LINE_SIZE
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;
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;
77 struct ck_epoch e_epoch __aligned(EPOCH_ALIGN);
78 epoch_record_t e_pcpu_record;
81 /* fields above are part of KBI and cannot be modified */
83 struct mtx e_drain_mtx;
84 volatile int e_drain_count;
87 /* arbitrary --- needs benchmarking */
88 #define MAX_ADAPTIVE_SPIN 100
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");
96 static counter_u64_t block_count;
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;
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;
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;
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;
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;
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");
121 TAILQ_HEAD (threadlist, thread);
123 CK_STACK_CONTAINER(struct ck_epoch_entry, stack_entry,
124 ck_epoch_entry_container)
126 epoch_t allepochs[MAX_EPOCHS];
128 DPCPU_DEFINE(struct grouptask, epoch_cb_task);
129 DPCPU_DEFINE(int, epoch_cb_count);
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;
136 static void epoch_call_task(void *context __unused);
137 static uma_zone_t pcpu_zone_record;
140 epoch_init(void *arg __unused)
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);
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);
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,
162 global_epoch = epoch_alloc(0);
163 global_epoch_preempt = epoch_alloc(EPOCH_PREEMPT);
165 SYSINIT(epoch, SI_SUB_TASKQ + 1, SI_ORDER_FIRST, epoch_init, NULL);
167 #if !defined(EARLY_AP_STARTUP)
169 epoch_init_smp(void *dummy __unused)
173 SYSINIT(epoch_smp, SI_SUB_SMP + 1, SI_ORDER_FIRST, epoch_init_smp, NULL);
177 epoch_ctor(epoch_t epoch)
182 epoch->e_pcpu_record = uma_zalloc_pcpu(pcpu_zone_record, M_WAITOK);
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);
189 er->er_parent = epoch;
194 epoch_adjust_prio(struct thread *td, u_char prio)
198 sched_prio(td, prio);
203 epoch_alloc(int flags)
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);
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;
222 epoch_free(epoch_t epoch)
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);
234 static epoch_record_t
235 epoch_currecord(epoch_t epoch)
238 return (zpcpu_get_cpu(epoch->e_pcpu_record, curcpu));
241 #define INIT_CHECK(epoch) \
243 if (__predict_false((epoch) == NULL)) \
248 epoch_enter_preempt(epoch_t epoch, epoch_tracker_t et)
250 struct epoch_record *er;
253 MPASS(cold || epoch != NULL);
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;
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);
274 epoch_enter(epoch_t epoch)
279 MPASS(cold || epoch != NULL);
285 er = epoch_currecord(epoch);
286 ck_epoch_begin(&er->er_record, NULL);
290 epoch_exit_preempt(epoch_t epoch, epoch_tracker_t et)
292 struct epoch_record *er;
299 MPASS(td->td_epochnest);
301 er = epoch_currecord(epoch);
302 MPASS(epoch->e_flags & EPOCH_PREEMPT);
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;
312 et->et_td = (void*)0xDEADBEEF;
314 ck_epoch_end(&er->er_record, &et->et_section);
315 TAILQ_REMOVE(&er->er_tdlist, et, et_link);
317 if (__predict_false(td->td_pre_epoch_prio != td->td_priority))
318 epoch_adjust_prio(td, td->td_pre_epoch_prio);
323 epoch_exit(epoch_t epoch)
330 MPASS(td->td_epochnest);
332 er = epoch_currecord(epoch);
333 ck_epoch_end(&er->er_record, NULL);
338 * epoch_block_handler_preempt() is a callback from the CK code when another
339 * thread is currently in an epoch section.
342 epoch_block_handler_preempt(struct ck_epoch *global __unused,
343 ck_epoch_record_t *cr, void *arg __unused)
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;
351 int locksheld __unused;
353 record = __containerof(cr, struct epoch_record, er_record);
355 locksheld = td->td_locks;
357 counter_u64_add(block_count, 1);
359 * We lost a race and there's no longer any threads
360 * on the CPU in an epoch section.
362 if (TAILQ_EMPTY(&record->er_tdlist))
365 if (record->er_cpuid != curcpu) {
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
371 gen = record->er_gen;
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
380 } while (!TAILQ_EMPTY(&record->er_tdlist) &&
381 gen == record->er_gen &&
382 spincount++ < MAX_ADAPTIVE_SPIN);
385 * If the generation has changed we can poll again
386 * otherwise we need to migrate.
388 if (gen != record->er_gen)
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
399 counter_u64_add(migrate_count, 1);
400 sched_bind(td, record->er_cpuid);
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.
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.
416 TAILQ_FOREACH(tdwait, &record->er_tdlist, et_link) {
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().
422 curwaittd = tdwait->et_td;
423 if (!TD_IS_INHIBITED(curwaittd) && curwaittd->td_priority > td->td_priority) {
426 thread_lock(curwaittd);
427 sched_prio(curwaittd, td->td_priority);
428 thread_unlock(curwaittd);
432 if (TD_IS_INHIBITED(curwaittd) && TD_ON_LOCK(curwaittd) &&
433 ((ts = curwaittd->td_blocked) != NULL)) {
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.
444 if (turnstile_lock(ts, &lock, &owner)) {
445 if (ts == curwaittd->td_blocked) {
446 MPASS(TD_IS_INHIBITED(curwaittd) &&
447 TD_ON_LOCK(curwaittd));
449 turnstile_wait(ts, owner,
450 curwaittd->td_tsqueue);
451 counter_u64_add(turnstile_count, 1);
455 turnstile_unlock(ts, lock);
459 KASSERT(td->td_locks == locksheld,
460 ("%d extra locks held", td->td_locks - locksheld));
464 * We didn't find any threads actually blocked on a lock
465 * so we have nothing to do except context switch away.
467 counter_u64_add(switch_count, 1);
468 mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
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)
481 epoch_wait_preempt(epoch_t epoch)
490 MPASS(cold || epoch != NULL);
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"));
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);
511 sched_bind(td, old_cpu);
513 ck_epoch_synchronize_wait(&epoch->e_epoch, epoch_block_handler_preempt,
516 /* restore CPU binding, if any */
517 if (was_bound != 0) {
518 sched_bind(td, old_cpu);
520 /* get thread back to initial CPU, if any */
522 sched_bind(td, old_cpu);
525 /* restore pinned after bind */
526 td->td_pinned = old_pinned;
528 /* restore thread priority */
529 sched_prio(td, old_prio);
532 KASSERT(td->td_locks == locks,
533 ("%d residual locks held", td->td_locks - locks));
537 epoch_block_handler(struct ck_epoch *g __unused, ck_epoch_record_t *c __unused,
544 epoch_wait(epoch_t epoch)
547 MPASS(cold || epoch != NULL);
549 MPASS(epoch->e_flags == 0);
551 ck_epoch_synchronize_wait(&epoch->e_epoch, epoch_block_handler, NULL);
556 epoch_call(epoch_t epoch, epoch_context_t ctx, void (*callback) (epoch_context_t))
559 ck_epoch_entry_t *cb;
564 /* too early in boot to have epoch set up */
565 if (__predict_false(epoch == NULL))
567 #if !defined(EARLY_AP_STARTUP)
568 if (__predict_false(inited < 2))
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);
583 epoch_call_task(void *arg __unused)
585 ck_stack_entry_t *cursor, *head, *next;
586 ck_epoch_record_t *record;
590 int i, npending, total;
592 ck_stack_init(&cb_stack);
594 epoch_enter(global_epoch);
595 for (total = i = 0; i < epoch_count; i++) {
596 if (__predict_false((epoch = allepochs[i]) == NULL))
598 er = epoch_currecord(epoch);
599 record = &er->er_record;
600 if ((npending = record->n_pending) == 0)
602 ck_epoch_poll_deferred(record, &cb_stack);
603 total += npending - record->n_pending;
605 epoch_exit(global_epoch);
606 *DPCPU_PTR(epoch_cb_count) -= total;
609 counter_u64_add(epoch_call_count, total);
610 counter_u64_add(epoch_call_task_count, 1);
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);
617 next = CK_STACK_NEXT(cursor);
618 entry->function(entry);
623 in_epoch_verbose(epoch_t epoch, int dump_onfail)
625 struct epoch_tracker *tdwait;
630 if (td->td_epochnest == 0)
632 if (__predict_false((epoch) == NULL))
635 er = epoch_currecord(epoch);
636 TAILQ_FOREACH(tdwait, &er->er_tdlist, et_link)
637 if (tdwait->et_td == td) {
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);
655 in_epoch(epoch_t epoch)
657 return (in_epoch_verbose(epoch, 0));
661 epoch_drain_cb(struct epoch_context *ctx)
663 struct epoch *epoch =
664 __containerof(ctx, struct epoch_record, er_drain_ctx)->er_parent;
666 if (atomic_fetchadd_int(&epoch->e_drain_count, -1) == 1) {
667 mtx_lock(&epoch->e_drain_mtx);
669 mtx_unlock(&epoch->e_drain_mtx);
674 epoch_drain_callbacks(epoch_t epoch)
683 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
684 "epoch_drain_callbacks() may sleep!");
686 /* too early in boot to have epoch set up */
687 if (__predict_false(epoch == NULL))
689 #if !defined(EARLY_AP_STARTUP)
690 if (__predict_false(inited < 2))
695 sx_xlock(&epoch->e_drain_sx);
696 mtx_lock(&epoch->e_drain_mtx);
700 old_cpu = PCPU_GET(cpuid);
701 old_pinned = td->td_pinned;
702 was_bound = sched_is_bound(td);
707 epoch->e_drain_count++;
709 er = zpcpu_get_cpu(epoch->e_pcpu_record, cpu);
711 epoch_call(epoch, &er->er_drain_ctx, &epoch_drain_cb);
714 /* restore CPU binding, if any */
715 if (was_bound != 0) {
716 sched_bind(td, old_cpu);
718 /* get thread back to initial CPU, if any */
720 sched_bind(td, old_cpu);
723 /* restore pinned after bind */
724 td->td_pinned = old_pinned;
728 while (epoch->e_drain_count != 0)
729 msleep(epoch, &epoch->e_drain_mtx, PZERO, "EDRAIN", 0);
731 mtx_unlock(&epoch->e_drain_mtx);
732 sx_xunlock(&epoch->e_drain_sx);
737 /* for binary compatibility */
739 struct epoch_tracker_KBI {
741 #ifdef EPOCH_TRACKER_DEBUG
746 } __aligned(sizeof(void *));
748 CTASSERT(sizeof(struct epoch_tracker_KBI) >= sizeof(struct epoch_tracker));
751 epoch_enter_preempt_KBI(epoch_t epoch, epoch_tracker_t et)
753 epoch_enter_preempt(epoch, et);
757 epoch_exit_preempt_KBI(epoch_t epoch, epoch_tracker_t et)
759 epoch_exit_preempt(epoch, et);
763 epoch_enter_KBI(epoch_t epoch)
769 epoch_exit_KBI(epoch_t epoch)