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>
47 #include <sys/sysctl.h>
48 #include <sys/turnstile.h>
50 #include <vm/vm_extern.h>
51 #include <vm/vm_kern.h>
55 static MALLOC_DEFINE(M_EPOCH, "epoch", "epoch based reclamation");
57 /* arbitrary --- needs benchmarking */
58 #define MAX_ADAPTIVE_SPIN 1000
62 #define EPOCH_ALIGN CACHE_LINE_SIZE*2
64 #define EPOCH_ALIGN CACHE_LINE_SIZE
67 CTASSERT(sizeof(epoch_section_t) == sizeof(ck_epoch_section_t));
68 CTASSERT(sizeof(ck_epoch_entry_t) == sizeof(struct epoch_context));
69 SYSCTL_NODE(_kern, OID_AUTO, epoch, CTLFLAG_RW, 0, "epoch information");
70 SYSCTL_NODE(_kern_epoch, OID_AUTO, stats, CTLFLAG_RW, 0, "epoch stats");
74 static counter_u64_t block_count;
75 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, nblocked, CTLFLAG_RW,
76 &block_count, "# of times a thread was in an epoch when epoch_wait was called");
77 static counter_u64_t migrate_count;
78 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, migrations, CTLFLAG_RW,
79 &migrate_count, "# of times thread was migrated to another CPU in epoch_wait");
80 static counter_u64_t turnstile_count;
81 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, ncontended, CTLFLAG_RW,
82 &turnstile_count, "# of times a thread was blocked on a lock in an epoch during an epoch_wait");
83 static counter_u64_t switch_count;
84 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, switches, CTLFLAG_RW,
85 &switch_count, "# of times a thread voluntarily context switched in epoch_wait");
86 static counter_u64_t epoch_call_count;
87 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, epoch_calls, CTLFLAG_RW,
88 &epoch_call_count, "# of times a callback was deferred");
89 static counter_u64_t epoch_call_task_count;
90 SYSCTL_COUNTER_U64(_kern_epoch_stats, OID_AUTO, epoch_call_tasks, CTLFLAG_RW,
91 &epoch_call_task_count, "# of times a callback task was run");
93 TAILQ_HEAD(threadlist, thread);
95 CK_STACK_CONTAINER(struct ck_epoch_entry, stack_entry,
96 ck_epoch_entry_container)
98 typedef struct epoch_record {
99 ck_epoch_record_t er_record;
100 volatile struct threadlist er_tdlist;
101 volatile uint32_t er_gen;
105 struct epoch_pcpu_state {
106 struct epoch_record eps_record;
107 } __aligned(EPOCH_ALIGN);
110 struct ck_epoch e_epoch __aligned(EPOCH_ALIGN);
111 struct epoch_pcpu_state *e_pcpu_dom[MAXMEMDOM] __aligned(EPOCH_ALIGN);
114 struct epoch_pcpu_state *e_pcpu[0];
117 epoch_t allepochs[MAX_EPOCHS];
119 DPCPU_DEFINE(struct grouptask, epoch_cb_task);
120 DPCPU_DEFINE(int, epoch_cb_count);
122 static __read_mostly int domcount[MAXMEMDOM];
123 static __read_mostly int domoffsets[MAXMEMDOM];
124 static __read_mostly int inited;
125 static __read_mostly int epoch_count;
126 __read_mostly epoch_t global_epoch;
127 __read_mostly epoch_t global_epoch_preempt;
129 static void epoch_call_task(void *context __unused);
131 #if defined(__powerpc64__) || defined(__powerpc__) || !defined(NUMA)
132 static bool usedomains = false;
134 static bool usedomains = true;
137 epoch_init(void *arg __unused)
141 block_count = counter_u64_alloc(M_WAITOK);
142 migrate_count = counter_u64_alloc(M_WAITOK);
143 turnstile_count = counter_u64_alloc(M_WAITOK);
144 switch_count = counter_u64_alloc(M_WAITOK);
145 epoch_call_count = counter_u64_alloc(M_WAITOK);
146 epoch_call_task_count = counter_u64_alloc(M_WAITOK);
147 if (usedomains == false)
151 for (domain = 0; domain < vm_ndomains; domain++) {
152 domcount[domain] = CPU_COUNT(&cpuset_domain[domain]);
154 printf("domcount[%d] %d\n", domain, domcount[domain]);
156 for (domain = 1; domain < vm_ndomains; domain++)
157 domoffsets[domain] = domoffsets[domain-1] + domcount[domain-1];
159 for (domain = 0; domain < vm_ndomains; domain++) {
160 if (domcount[domain] == 0) {
167 GROUPTASK_INIT(DPCPU_ID_PTR(cpu, epoch_cb_task), 0, epoch_call_task, NULL);
168 taskqgroup_attach_cpu(qgroup_softirq, DPCPU_ID_PTR(cpu, epoch_cb_task), NULL, cpu, -1, "epoch call task");
171 global_epoch = epoch_alloc(0);
172 global_epoch_preempt = epoch_alloc(EPOCH_PREEMPT);
174 SYSINIT(epoch, SI_SUB_TASKQ + 1, SI_ORDER_FIRST, epoch_init, NULL);
177 epoch_init_numa(epoch_t epoch)
179 int domain, cpu_offset;
180 struct epoch_pcpu_state *eps;
183 for (domain = 0; domain < vm_ndomains; domain++) {
184 eps = malloc_domain(sizeof(*eps)*domcount[domain], M_EPOCH,
185 domain, M_ZERO|M_WAITOK);
186 epoch->e_pcpu_dom[domain] = eps;
187 cpu_offset = domoffsets[domain];
188 for (int i = 0; i < domcount[domain]; i++, eps++) {
189 epoch->e_pcpu[cpu_offset + i] = eps;
190 er = &eps->eps_record;
191 ck_epoch_register(&epoch->e_epoch, &er->er_record, NULL);
192 TAILQ_INIT((struct threadlist *)(uintptr_t)&er->er_tdlist);
193 er->er_cpuid = cpu_offset + i;
199 epoch_init_legacy(epoch_t epoch)
201 struct epoch_pcpu_state *eps;
204 eps = malloc(sizeof(*eps)*mp_ncpus, M_EPOCH, M_ZERO|M_WAITOK);
205 epoch->e_pcpu_dom[0] = eps;
206 for (int i = 0; i < mp_ncpus; i++, eps++) {
207 epoch->e_pcpu[i] = eps;
208 er = &eps->eps_record;
209 ck_epoch_register(&epoch->e_epoch, &er->er_record, NULL);
210 TAILQ_INIT((struct threadlist *)(uintptr_t)&er->er_tdlist);
216 epoch_alloc(int flags)
220 if (__predict_false(!inited))
221 panic("%s called too early in boot", __func__);
222 epoch = malloc(sizeof(struct epoch) + mp_ncpus*sizeof(void*),
223 M_EPOCH, M_ZERO|M_WAITOK);
224 ck_epoch_init(&epoch->e_epoch);
226 epoch_init_numa(epoch);
228 epoch_init_legacy(epoch);
229 MPASS(epoch_count < MAX_EPOCHS-2);
230 epoch->e_flags = flags;
231 epoch->e_idx = epoch_count;
232 allepochs[epoch_count++] = epoch;
237 epoch_free(epoch_t epoch)
241 struct epoch_pcpu_state *eps;
245 eps = epoch->e_pcpu[cpu];
246 MPASS(TAILQ_EMPTY(&eps->eps_record.er_tdlist));
249 allepochs[epoch->e_idx] = NULL;
250 epoch_wait(global_epoch);
252 for (domain = 0; domain < vm_ndomains; domain++)
253 free_domain(epoch->e_pcpu_dom[domain], M_EPOCH);
255 free(epoch->e_pcpu_dom[0], M_EPOCH);
256 free(epoch, M_EPOCH);
259 #define INIT_CHECK(epoch) \
261 if (__predict_false((epoch) == NULL)) \
266 epoch_enter_preempt_internal(epoch_t epoch, struct thread *td)
268 struct epoch_pcpu_state *eps;
270 MPASS(cold || epoch != NULL);
272 MPASS(epoch->e_flags & EPOCH_PREEMPT);
274 td->td_pre_epoch_prio = td->td_priority;
275 eps = epoch->e_pcpu[curcpu];
277 MPASS(td->td_epochnest < UCHAR_MAX - 2);
278 if (td->td_epochnest > 1) {
279 struct thread *curtd;
282 TAILQ_FOREACH(curtd, &eps->eps_record.er_tdlist, td_epochq)
285 KASSERT(found, ("recursing on a second epoch"));
290 TAILQ_INSERT_TAIL(&eps->eps_record.er_tdlist, td, td_epochq);
292 ck_epoch_begin(&eps->eps_record.er_record, (ck_epoch_section_t*)&td->td_epoch_section);
298 epoch_enter(epoch_t epoch)
300 ck_epoch_record_t *record;
303 MPASS(cold || epoch != NULL);
308 record = &epoch->e_pcpu[curcpu]->eps_record.er_record;
309 ck_epoch_begin(record, NULL);
313 epoch_exit_preempt_internal(epoch_t epoch, struct thread *td)
315 struct epoch_pcpu_state *eps;
317 MPASS(td->td_epochnest == 0);
320 eps = epoch->e_pcpu[curcpu];
322 MPASS(epoch->e_flags & EPOCH_PREEMPT);
323 ck_epoch_end(&eps->eps_record.er_record, (ck_epoch_section_t*)&td->td_epoch_section);
324 TAILQ_REMOVE(&eps->eps_record.er_tdlist, td, td_epochq);
325 eps->eps_record.er_gen++;
327 if (__predict_false(td->td_pre_epoch_prio != td->td_priority)) {
329 sched_prio(td, td->td_pre_epoch_prio);
336 epoch_exit(epoch_t epoch)
338 ck_epoch_record_t *record;
343 record = &epoch->e_pcpu[curcpu]->eps_record.er_record;
344 ck_epoch_end(record, NULL);
349 * epoch_block_handler_preempt is a callback from the ck code when another thread is
350 * currently in an epoch section.
353 epoch_block_handler_preempt(struct ck_epoch *global __unused, ck_epoch_record_t *cr,
356 epoch_record_t record;
357 struct thread *td, *tdwait, *owner;
358 struct turnstile *ts;
359 struct lock_object *lock;
362 record = __containerof(cr, struct epoch_record, er_record);
365 counter_u64_add(block_count, 1);
366 if (record->er_cpuid != curcpu) {
368 * If the head of the list is running, we can wait for it
369 * to remove itself from the list and thus save us the
370 * overhead of a migration
372 if ((tdwait = TAILQ_FIRST(&record->er_tdlist)) != NULL &&
373 TD_IS_RUNNING(tdwait)) {
374 gen = record->er_gen;
378 } while (tdwait == TAILQ_FIRST(&record->er_tdlist) &&
379 gen == record->er_gen && TD_IS_RUNNING(tdwait) &&
380 spincount++ < MAX_ADAPTIVE_SPIN);
386 * Being on the same CPU as that of the record on which
387 * we need to wait allows us access to the thread
388 * list associated with that CPU. We can then examine the
389 * oldest thread in the queue and wait on its turnstile
390 * until it resumes and so on until a grace period
394 counter_u64_add(migrate_count, 1);
395 sched_bind(td, record->er_cpuid);
397 * At this point we need to return to the ck code
398 * to scan to see if a grace period has elapsed.
399 * We can't move on to check the thread list, because
400 * in the meantime new threads may have arrived that
401 * in fact belong to a different epoch.
406 * Try to find a thread in an epoch section on this CPU
407 * waiting on a turnstile. Otherwise find the lowest
408 * priority thread (highest prio value) and drop our priority
409 * to match to allow it to run.
411 TAILQ_FOREACH(tdwait, &record->er_tdlist, td_epochq) {
413 * Propagate our priority to any other waiters to prevent us
414 * from starving them. They will have their original priority
415 * restore on exit from epoch_wait().
417 if (!TD_IS_INHIBITED(tdwait) && tdwait->td_priority > td->td_priority) {
421 sched_prio(tdwait, td->td_priority);
422 thread_unlock(tdwait);
426 if (TD_IS_INHIBITED(tdwait) && TD_ON_LOCK(tdwait) &&
427 ((ts = tdwait->td_blocked) != NULL)) {
429 * We unlock td to allow turnstile_wait to reacquire the
430 * the thread lock. Before unlocking it we enter a critical
431 * section to prevent preemption after we reenable interrupts
432 * by dropping the thread lock in order to prevent tdwait
433 * from getting to run.
437 owner = turnstile_lock(ts, &lock);
439 * The owner pointer indicates that the lock succeeded. Only
440 * in case we hold the lock and the turnstile we locked is still
441 * the one that tdwait is blocked on can we continue. Otherwise
442 * The turnstile pointer has been changed out from underneath
443 * us, as in the case where the lock holder has signalled tdwait,
444 * and we need to continue.
446 if (owner != NULL && ts == tdwait->td_blocked) {
447 MPASS(TD_IS_INHIBITED(tdwait) && TD_ON_LOCK(tdwait));
449 turnstile_wait(ts, owner, tdwait->td_tsqueue);
450 counter_u64_add(turnstile_count, 1);
453 } else if (owner != NULL)
454 turnstile_unlock(ts, lock);
457 KASSERT(td->td_locks == 0,
458 ("%d locks held", td->td_locks));
462 * We didn't find any threads actually blocked on a lock
463 * so we have nothing to do except context switch away.
465 counter_u64_add(switch_count, 1);
466 mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
469 * Release the thread lock while yielding to
470 * allow other threads to acquire the lock
471 * pointed to by TDQ_LOCKPTR(td). Else a
472 * deadlock like situation might happen. (HPS)
479 epoch_wait_preempt(epoch_t epoch)
489 locks = curthread->td_locks;
492 MPASS(cold || epoch != NULL);
495 MPASS(epoch->e_flags & EPOCH_PREEMPT);
496 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
497 "epoch_wait() can sleep");
500 KASSERT(td->td_epochnest == 0, ("epoch_wait() in the middle of an epoch section"));
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, NULL);
515 /* restore CPU binding, if any */
516 if (was_bound != 0) {
517 sched_bind(td, old_cpu);
519 /* get thread back to initial CPU, if any */
521 sched_bind(td, old_cpu);
524 /* restore pinned after bind */
525 td->td_pinned = old_pinned;
527 /* restore thread priority */
528 sched_prio(td, old_prio);
531 KASSERT(td->td_locks == locks,
532 ("%d residual locks held", td->td_locks - locks));
536 epoch_block_handler(struct ck_epoch *g __unused, ck_epoch_record_t *c __unused,
543 epoch_wait(epoch_t epoch)
546 MPASS(cold || epoch != NULL);
548 MPASS(epoch->e_flags == 0);
550 ck_epoch_synchronize_wait(&epoch->e_epoch, epoch_block_handler, NULL);
555 epoch_call(epoch_t epoch, epoch_context_t ctx, void (*callback) (epoch_context_t))
557 struct epoch_pcpu_state *eps;
558 ck_epoch_entry_t *cb;
563 /* too early in boot to have epoch set up */
564 if (__predict_false(epoch == NULL))
568 *DPCPU_PTR(epoch_cb_count) += 1;
569 eps = epoch->e_pcpu[curcpu];
570 ck_epoch_call(&eps->eps_record.er_record, cb, (ck_epoch_cb_t*)callback);
578 epoch_call_task(void *arg __unused)
580 ck_stack_entry_t *cursor, *head, *next;
581 ck_epoch_record_t *record;
584 int i, npending, total;
586 ck_stack_init(&cb_stack);
588 epoch_enter(global_epoch);
589 for (total = i = 0; i < epoch_count; i++) {
590 if (__predict_false((epoch = allepochs[i]) == NULL))
592 record = &epoch->e_pcpu[curcpu]->eps_record.er_record;
593 if ((npending = record->n_pending) == 0)
595 ck_epoch_poll_deferred(record, &cb_stack);
596 total += npending - record->n_pending;
598 epoch_exit(global_epoch);
599 *DPCPU_PTR(epoch_cb_count) -= total;
602 counter_u64_add(epoch_call_count, total);
603 counter_u64_add(epoch_call_task_count, 1);
605 head = ck_stack_batch_pop_npsc(&cb_stack);
606 for (cursor = head; cursor != NULL; cursor = next) {
607 struct ck_epoch_entry *entry =
608 ck_epoch_entry_container(cursor);
609 next = CK_STACK_NEXT(cursor);
610 entry->function(entry);
617 return (curthread->td_epochnest != 0);