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>
44 #include <sys/sched.h>
46 #include <sys/sysctl.h>
47 #include <sys/turnstile.h>
49 #include <vm/vm_extern.h>
50 #include <vm/vm_kern.h>
54 static MALLOC_DEFINE(M_EPOCH, "epoch", "epoch based reclamation");
56 /* arbitrary --- needs benchmarking */
57 #define MAX_ADAPTIVE_SPIN 5000
59 #define EPOCH_EXITING 0x1
61 #define EPOCH_ALIGN CACHE_LINE_SIZE*2
63 #define EPOCH_ALIGN CACHE_LINE_SIZE
66 SYSCTL_NODE(_kern, OID_AUTO, epoch, CTLFLAG_RW, 0, "epoch information");
67 SYSCTL_NODE(_kern_epoch, OID_AUTO, stats, CTLFLAG_RW, 0, "epoch stats");
69 static int poll_intvl;
70 SYSCTL_INT(_kern_epoch, OID_AUTO, poll_intvl, CTLFLAG_RWTUN,
71 &poll_intvl, 0, "# of ticks to wait between garbage collecting deferred frees");
73 static counter_u64_t block_count;
74 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, nblocked, CTLFLAG_RW,
75 &block_count, "# of times a thread was in an epoch when epoch_wait was called");
76 static counter_u64_t migrate_count;
77 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, migrations, CTLFLAG_RW,
78 &migrate_count, "# of times thread was migrated to another CPU in epoch_wait");
79 static counter_u64_t turnstile_count;
80 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, ncontended, CTLFLAG_RW,
81 &turnstile_count, "# of times a thread was blocked on a lock in an epoch during an epoch_wait");
82 static counter_u64_t switch_count;
83 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, switches, CTLFLAG_RW,
84 &switch_count, "# of times a thread voluntarily context switched in epoch_wait");
86 typedef struct epoch_cb {
87 void (*ec_callback)(epoch_context_t);
88 STAILQ_ENTRY(epoch_cb) ec_link;
91 TAILQ_HEAD(threadlist, thread);
93 typedef struct epoch_record {
94 ck_epoch_record_t er_record;
95 volatile struct threadlist er_tdlist;
96 volatile uint32_t er_gen;
100 struct epoch_pcpu_state {
101 struct epoch_record eps_record;
102 STAILQ_HEAD(, epoch_cb) eps_cblist;
103 } __aligned(EPOCH_ALIGN);
106 struct ck_epoch e_epoch __aligned(EPOCH_ALIGN);
107 struct grouptask e_gtask;
108 struct callout e_timer;
111 /* make sure that immutable data doesn't overlap with the gtask, callout, and mutex*/
112 struct epoch_pcpu_state *e_pcpu_dom[MAXMEMDOM] __aligned(EPOCH_ALIGN);
113 counter_u64_t e_frees;
114 uint64_t e_free_last;
115 struct epoch_pcpu_state *e_pcpu[0];
118 static __read_mostly int domcount[MAXMEMDOM];
119 static __read_mostly int domoffsets[MAXMEMDOM];
120 static __read_mostly int inited;
121 __read_mostly epoch_t global_epoch;
123 static void epoch_call_task(void *context);
125 #if defined(__powerpc64__) || defined(__powerpc__) || !defined(NUMA)
126 static bool usedomains = false;
128 static bool usedomains = true;
131 epoch_init(void *arg __unused)
138 block_count = counter_u64_alloc(M_WAITOK);
139 migrate_count = counter_u64_alloc(M_WAITOK);
140 turnstile_count = counter_u64_alloc(M_WAITOK);
141 switch_count = counter_u64_alloc(M_WAITOK);
142 if (usedomains == false)
146 for (domain = 0; domain < vm_ndomains; domain++) {
147 domcount[domain] = CPU_COUNT(&cpuset_domain[domain]);
149 printf("domcount[%d] %d\n", domain, domcount[domain]);
151 for (domain = 1; domain < vm_ndomains; domain++)
152 domoffsets[domain] = domoffsets[domain-1] + domcount[domain-1];
154 for (domain = 0; domain < vm_ndomains; domain++) {
155 if (domcount[domain] == 0) {
162 global_epoch = epoch_alloc();
164 SYSINIT(epoch, SI_SUB_TASKQ + 1, SI_ORDER_FIRST, epoch_init, NULL);
167 epoch_init_numa(epoch_t epoch)
169 int domain, cpu_offset;
170 struct epoch_pcpu_state *eps;
173 for (domain = 0; domain < vm_ndomains; domain++) {
174 eps = malloc_domain(sizeof(*eps)*domcount[domain], M_EPOCH,
175 domain, M_ZERO|M_WAITOK);
176 epoch->e_pcpu_dom[domain] = eps;
177 cpu_offset = domoffsets[domain];
178 for (int i = 0; i < domcount[domain]; i++, eps++) {
179 epoch->e_pcpu[cpu_offset + i] = eps;
180 er = &eps->eps_record;
181 STAILQ_INIT(&eps->eps_cblist);
182 ck_epoch_register(&epoch->e_epoch, &er->er_record, NULL);
183 TAILQ_INIT((struct threadlist *)(uintptr_t)&er->er_tdlist);
184 er->er_cpuid = cpu_offset + i;
190 epoch_init_legacy(epoch_t epoch)
192 struct epoch_pcpu_state *eps;
195 eps = malloc(sizeof(*eps)*mp_ncpus, M_EPOCH, M_ZERO|M_WAITOK);
196 epoch->e_pcpu_dom[0] = eps;
197 for (int i = 0; i < mp_ncpus; i++, eps++) {
198 epoch->e_pcpu[i] = eps;
199 er = &eps->eps_record;
200 ck_epoch_register(&epoch->e_epoch, &er->er_record, NULL);
201 TAILQ_INIT((struct threadlist *)(uintptr_t)&er->er_tdlist);
202 STAILQ_INIT(&eps->eps_cblist);
208 epoch_callout(void *arg)
214 frees = counter_u64_fetch(epoch->e_frees);
215 /* pick some better value */
216 if (frees - epoch->e_free_last > 10) {
217 GROUPTASK_ENQUEUE(&epoch->e_gtask);
218 epoch->e_free_last = frees;
220 if ((epoch->e_flags & EPOCH_EXITING) == 0)
221 callout_reset(&epoch->e_timer, poll_intvl, epoch_callout, epoch);
229 if (__predict_false(!inited))
230 panic("%s called too early in boot", __func__);
231 epoch = malloc(sizeof(struct epoch) + mp_ncpus*sizeof(void*),
232 M_EPOCH, M_ZERO|M_WAITOK);
233 ck_epoch_init(&epoch->e_epoch);
234 epoch->e_frees = counter_u64_alloc(M_WAITOK);
235 mtx_init(&epoch->e_lock, "epoch callout", NULL, MTX_DEF);
236 callout_init_mtx(&epoch->e_timer, &epoch->e_lock, 0);
237 taskqgroup_config_gtask_init(epoch, &epoch->e_gtask, epoch_call_task, "epoch call task");
239 epoch_init_numa(epoch);
241 epoch_init_legacy(epoch);
242 callout_reset(&epoch->e_timer, poll_intvl, epoch_callout, epoch);
247 epoch_free(epoch_t epoch)
251 struct epoch_pcpu_state *eps;
255 eps = epoch->e_pcpu[cpu];
256 MPASS(TAILQ_EMPTY(&eps->eps_record.er_tdlist));
259 mtx_lock(&epoch->e_lock);
260 epoch->e_flags |= EPOCH_EXITING;
261 mtx_unlock(&epoch->e_lock);
263 * Execute any lingering callbacks
265 GROUPTASK_ENQUEUE(&epoch->e_gtask);
266 gtaskqueue_drain(epoch->e_gtask.gt_taskqueue, &epoch->e_gtask.gt_task);
267 callout_drain(&epoch->e_timer);
268 mtx_destroy(&epoch->e_lock);
269 counter_u64_free(epoch->e_frees);
270 taskqgroup_config_gtask_deinit(&epoch->e_gtask);
272 for (domain = 0; domain < vm_ndomains; domain++)
273 free_domain(epoch->e_pcpu_dom[domain], M_EPOCH);
275 free(epoch->e_pcpu_dom[0], M_EPOCH);
276 free(epoch, M_EPOCH);
279 #define INIT_CHECK(epoch) \
281 if (__predict_false((epoch) == NULL)) \
286 epoch_enter(epoch_t epoch)
288 struct epoch_pcpu_state *eps;
295 eps = epoch->e_pcpu[curcpu];
297 MPASS(td->td_epochnest < UCHAR_MAX - 2);
298 if (td->td_epochnest == 1)
299 TAILQ_INSERT_TAIL(&eps->eps_record.er_tdlist, td, td_epochq);
301 if (td->td_epochnest > 1) {
302 struct thread *curtd;
305 TAILQ_FOREACH(curtd, &eps->eps_record.er_tdlist, td_epochq)
308 KASSERT(found, ("recursing on a second epoch"));
312 ck_epoch_begin(&eps->eps_record.er_record, NULL);
317 epoch_exit(epoch_t epoch)
319 struct epoch_pcpu_state *eps;
324 MPASS(td->td_epochnest);
326 eps = epoch->e_pcpu[curcpu];
328 ck_epoch_end(&eps->eps_record.er_record, NULL);
330 if (td->td_epochnest == 0)
331 TAILQ_REMOVE(&eps->eps_record.er_tdlist, td, td_epochq);
332 eps->eps_record.er_gen++;
337 * epoch_block_handler is a callback from the ck code when another thread is
338 * currently in an epoch section.
341 epoch_block_handler(struct ck_epoch *global __unused, ck_epoch_record_t *cr,
344 epoch_record_t record;
345 struct epoch_pcpu_state *eps;
346 struct thread *td, *tdwait, *owner;
347 struct turnstile *ts;
348 struct lock_object *lock;
352 record = __containerof(cr, struct epoch_record, er_record);
355 counter_u64_add(block_count, 1);
356 if (record->er_cpuid != curcpu) {
358 * If the head of the list is running, we can wait for it
359 * to remove itself from the list and thus save us the
360 * overhead of a migration
362 if ((tdwait = TAILQ_FIRST(&record->er_tdlist)) != NULL &&
363 TD_IS_RUNNING(tdwait)) {
364 gen = record->er_gen;
368 } while (tdwait == TAILQ_FIRST(&record->er_tdlist) &&
369 gen == record->er_gen && TD_IS_RUNNING(tdwait) &&
370 spincount++ < MAX_ADAPTIVE_SPIN);
376 * Being on the same CPU as that of the record on which
377 * we need to wait allows us access to the thread
378 * list associated with that CPU. We can then examine the
379 * oldest thread in the queue and wait on its turnstile
380 * until it resumes and so on until a grace period
384 counter_u64_add(migrate_count, 1);
385 sched_bind(td, record->er_cpuid);
387 * At this point we need to return to the ck code
388 * to scan to see if a grace period has elapsed.
389 * We can't move on to check the thread list, because
390 * in the meantime new threads may have arrived that
391 * in fact belong to a different epoch.
396 * Try to find a thread in an epoch section on this CPU
397 * waiting on a turnstile. Otherwise find the lowest
398 * priority thread (highest prio value) and drop our priority
399 * to match to allow it to run.
401 TAILQ_FOREACH(tdwait, &record->er_tdlist, td_epochq) {
403 * Propagate our priority to any other waiters to prevent us
404 * from starving them. They will have their original priority
405 * restore on exit from epoch_wait().
407 if (!TD_IS_INHIBITED(tdwait) && tdwait->td_priority > td->td_priority) {
409 sched_prio(tdwait, td->td_priority);
410 thread_unlock(tdwait);
412 if (TD_IS_INHIBITED(tdwait) && TD_ON_LOCK(tdwait) &&
413 ((ts = tdwait->td_blocked) != NULL)) {
415 * We unlock td to allow turnstile_wait to reacquire the
416 * the thread lock. Before unlocking it we enter a critical
417 * section to prevent preemption after we reenable interrupts
418 * by dropping the thread lock in order to prevent tdwait
419 * from getting to run.
423 owner = turnstile_lock(ts, &lock);
425 * The owner pointer indicates that the lock succeeded. Only
426 * in case we hold the lock and the turnstile we locked is still
427 * the one that tdwait is blocked on can we continue. Otherwise
428 * The turnstile pointer has been changed out from underneath
429 * us, as in the case where the lock holder has signalled tdwait,
430 * and we need to continue.
432 if (owner != NULL && ts == tdwait->td_blocked) {
433 MPASS(TD_IS_INHIBITED(tdwait) && TD_ON_LOCK(tdwait));
435 turnstile_wait(ts, owner, tdwait->td_tsqueue);
436 counter_u64_add(turnstile_count, 1);
439 } else if (owner != NULL)
440 turnstile_unlock(ts, lock);
443 KASSERT(td->td_locks == 0,
444 ("%d locks held", td->td_locks));
448 * We didn't find any threads actually blocked on a lock
449 * so we have nothing to do except context switch away.
451 counter_u64_add(switch_count, 1);
452 mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
455 * Release the thread lock while yielding to
456 * allow other threads to acquire the lock
457 * pointed to by TDQ_LOCKPTR(td). Else a
458 * deadlock like situation might happen. (HPS)
465 epoch_wait(epoch_t epoch)
475 locks = curthread->td_locks;
479 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
480 "epoch_wait() can sleep");
483 KASSERT(td->td_epochnest == 0, ("epoch_wait() in the middle of an epoch section"));
488 old_cpu = PCPU_GET(cpuid);
489 old_pinned = td->td_pinned;
490 old_prio = td->td_priority;
491 was_bound = sched_is_bound(td);
494 sched_bind(td, old_cpu);
496 ck_epoch_synchronize_wait(&epoch->e_epoch, epoch_block_handler, NULL);
498 /* restore CPU binding, if any */
499 if (was_bound != 0) {
500 sched_bind(td, old_cpu);
502 /* get thread back to initial CPU, if any */
504 sched_bind(td, old_cpu);
507 /* restore pinned after bind */
508 td->td_pinned = old_pinned;
510 /* restore thread priority */
511 sched_prio(td, old_prio);
514 KASSERT(td->td_locks == locks,
515 ("%d residual locks held", td->td_locks - locks));
519 epoch_call(epoch_t epoch, epoch_context_t ctx, void (*callback) (epoch_context_t))
521 struct epoch_pcpu_state *eps;
527 /* too early in boot to have epoch set up */
528 if (__predict_false(epoch == NULL)) {
532 MPASS(cb->ec_callback == NULL);
533 MPASS(cb->ec_link.stqe_next == NULL);
534 cb->ec_callback = callback;
535 counter_u64_add(epoch->e_frees, 1);
538 eps = epoch->e_pcpu[curcpu];
539 STAILQ_INSERT_HEAD(&eps->eps_cblist, cb, ec_link);
544 epoch_call_task(void *context)
546 struct epoch_pcpu_state *eps;
551 STAILQ_HEAD(, epoch_cb) tmp_head;
554 STAILQ_INIT(&tmp_head);
559 eps = epoch->e_pcpu[cpu];
560 if (!STAILQ_EMPTY(&eps->eps_cblist))
561 STAILQ_CONCAT(&tmp_head, &eps->eps_cblist);
567 while ((cb = STAILQ_FIRST(&tmp_head)) != NULL) {
568 STAILQ_REMOVE_HEAD(&tmp_head, ec_link);
569 cb->ec_callback((void*)cb);
576 return (curthread->td_epochnest != 0);