| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
|
| 3 |
#include <pthread.h> |
| 4 |
#include <setjmp.h> |
| 5 |
#include <sys/mman.h> |
| 6 |
#include <sys/resource.h> |
| 7 |
#include <sys/uio.h> |
| 8 |
#include <threads.h> |
| 9 |
#include <ucontext.h> |
| 10 |
#include <unistd.h> |
| 11 |
|
| 12 |
#if HAVE_VALGRIND_VALGRIND_H |
| 13 |
#include <valgrind/valgrind.h> |
| 14 |
#endif |
| 15 |
|
| 16 |
#include "sd-event.h" |
| 17 |
#include "sd-future.h" |
| 18 |
|
| 19 |
#include "alloc-util.h" |
| 20 |
#include "architecture.h" |
| 21 |
#include "errno-util.h" |
| 22 |
#include "event-future.h" |
| 23 |
#include "fiber-ops.h" |
| 24 |
#include "log-context.h" |
| 25 |
#include "log.h" |
| 26 |
#include "memory-util.h" |
| 27 |
#include "pthread-util.h" |
| 28 |
#include "time-util.h" |
| 29 |
|
| 30 |
#if HAS_FEATURE_ADDRESS_SANITIZER |
| 31 |
#include <sanitizer/common_interface_defs.h> |
| 32 |
#endif |
| 33 |
|
| 34 |
/* glibc's _FORTIFY_SOURCE wraps siglongjmp() with __longjmp_chk, which asserts that the target SP is below |
| 35 |
* the current SP. That assumption is incompatible with fiber switching, where the target SP lives on a |
| 36 |
* separately-mmap'd stack and can be at any address relative to the caller. The fortify redirect happens |
| 37 |
* in <setjmp.h>'s declaration of siglongjmp; we sidestep it by declaring our own alias that links |
| 38 |
* directly to the unchecked "siglongjmp" symbol. musl doesn't fortify setjmp.h, so the alias is a plain |
| 39 |
* synonym there. */ |
| 40 |
_noreturn_ extern void siglongjmp_unchecked(sigjmp_buf env, int val) __asm__("siglongjmp"); |
| 41 |
|
| 42 |
static thread_local Fiber *current_fiber = NULL; |
| 43 |
|
| 44 |
typedef enum FiberState { |
| 45 |
FIBER_STATE_INITIAL, |
| 46 |
FIBER_STATE_READY, |
| 47 |
FIBER_STATE_SUSPENDED, |
| 48 |
FIBER_STATE_CANCELLED, |
| 49 |
FIBER_STATE_COMPLETED, |
| 50 |
_FIBER_STATE_MAX, |
| 51 |
_FIBER_STATE_INVALID = -EINVAL, |
| 52 |
} FiberState; |
| 53 |
|
| 54 |
typedef struct Fiber { |
| 55 |
struct iovec stack; |
| 56 |
sigjmp_buf context; /* Where to jump to when entering or resuming the fiber. */ |
| 57 |
sigjmp_buf resume_context; /* Where to jump back to when the fiber yields or completes. */ |
| 58 |
|
| 59 |
/* Caller's stack range, recorded by fiber_run() on each entry so the fiber's siglongjmp back |
| 60 |
* out (in fiber_swap() or the trampoline's terminate path) can hand AddressSanitizer the |
| 61 |
* destination stack info. With ucontext this comes for free via uc_link/uc_stack; sigjmp_buf |
| 62 |
* is opaque and doesn't carry it. */ |
| 63 |
struct iovec resume_stack; |
| 64 |
|
| 65 |
FiberState state; |
| 66 |
int result; /* Either resume error code or final return value */ |
| 67 |
|
| 68 |
sd_future *floating; /* Self-ref held while the fiber is floating; dropped on resolve. */ |
| 69 |
|
| 70 |
sd_event *event; |
| 71 |
sd_event_source *defer_event_source; |
| 72 |
sd_event_source *exit_event_source; |
| 73 |
|
| 74 |
char *name; |
| 75 |
int64_t priority; |
| 76 |
sd_fiber_func_t func; |
| 77 |
void *userdata; |
| 78 |
sd_fiber_destroy_t destroy; |
| 79 |
|
| 80 |
/* Storage for the swap performed in fiber_run(): while the fiber is suspended these hold the |
| 81 |
* fiber's own log state; while it is running they hold the caller's log state. The active state |
| 82 |
* always lives in the thread-locals in log.c / log-context.c. */ |
| 83 |
LIST_HEAD(LogContext, log_context); |
| 84 |
size_t log_context_num_fields; |
| 85 |
const char *log_prefix; |
| 86 |
|
| 87 |
#if HAVE_VALGRIND_VALGRIND_H |
| 88 |
unsigned stack_id; |
| 89 |
#endif |
| 90 |
} Fiber; |
| 91 |
|
| 92 |
static Fiber* fiber_get_current(void) { |
| 93 |
return current_fiber; |
| 94 |
} |
| 95 |
|
| 96 |
static void fiber_set_current(Fiber *f) { |
| 97 |
current_fiber = f; |
| 98 |
} |
| 99 |
|
| 100 |
static int fiber_allocate_stack(size_t size, void **ret) { |
| 101 |
void *stack = NULL; |
| 102 |
int r; |
| 103 |
|
| 104 |
/* The effective stack size is one page less than the given size, because we have to use |
| 105 |
* one page as the guard page for the stack. */ |
| 106 |
|
| 107 |
assert(size > 0 && size % page_size() == 0); |
| 108 |
assert(ret); |
| 109 |
|
| 110 |
stack = mmap(/* addr= */ NULL, size, |
| 111 |
PROT_READ | PROT_WRITE, |
| 112 |
MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, |
| 113 |
/* fd= */ -EBADF, /* offset= */ 0); |
| 114 |
if (stack == MAP_FAILED) |
| 115 |
return -errno; |
| 116 |
|
| 117 |
/* Place the guard page where stack overflow will hit it: the high end on architectures |
| 118 |
* where the stack grows up (PA-RISC), the low end everywhere else. fiber_stack_usable() |
| 119 |
* mirrors this with the inverse offset. */ |
| 120 |
void *guard = STACK_GROWS_UP ? (uint8_t*) stack + size - page_size() : stack; |
| 121 |
|
| 122 |
/* Prefer MADV_GUARD_INSTALL (Linux 6.13+): unlike mprotect(PROT_NONE) it doesn't split |
| 123 |
* the VMA, so guard installation skips the mmap-lock contention and per-guard VMA cost. |
| 124 |
* Fall back to mprotect on older kernels, which return EINVAL for unknown advice. |
| 125 |
* FIXME: delete when baseline above 6.13. */ |
| 126 |
r = RET_NERRNO(madvise(guard, page_size(), MADV_GUARD_INSTALL)); |
| 127 |
if (r == -EINVAL) |
| 128 |
r = RET_NERRNO(mprotect(guard, page_size(), PROT_NONE)); |
| 129 |
if (r < 0) { |
| 130 |
(void) munmap(stack, size); |
| 131 |
return r; |
| 132 |
} |
| 133 |
|
| 134 |
*ret = TAKE_PTR(stack); |
| 135 |
return 0; |
| 136 |
} |
| 137 |
|
| 138 |
/* Usable stack range of a fiber: the full mmap region minus the guard page. Single source of |
| 139 |
* truth for the layout assumed by fiber_allocate_stack(); every consumer (ucontext ss_sp, |
| 140 |
* ASAN handoff iovecs, Valgrind stack registration) goes through here. |
| 141 |
* |
| 142 |
* iov_base is the lowest usable byte regardless of growth direction — that matches POSIX's |
| 143 |
* definition of stack_t.ss_sp, so libc's makecontext() handles the direction for us. Only the |
| 144 |
* guard page placement (and hence iov_base's offset within the mapping) varies. */ |
| 145 |
static struct iovec fiber_stack_usable(const struct iovec *stack) { |
| 146 |
assert(stack); |
| 147 |
assert(stack->iov_len > page_size()); |
| 148 |
return (struct iovec) { |
| 149 |
.iov_base = STACK_GROWS_UP ? stack->iov_base : (uint8_t*) stack->iov_base + page_size(), |
| 150 |
.iov_len = stack->iov_len - page_size(), |
| 151 |
}; |
| 152 |
} |
| 153 |
|
| 154 |
static inline void start_switch_stack(void **fake_stack_save, const struct iovec *dest) { |
| 155 |
#if HAS_FEATURE_ADDRESS_SANITIZER |
| 156 |
__sanitizer_start_switch_fiber(fake_stack_save, |
| 157 |
dest ? dest->iov_base : NULL, |
| 158 |
dest ? dest->iov_len : 0); |
| 159 |
#endif |
| 160 |
} |
| 161 |
|
| 162 |
static inline void finish_switch_stack(void *fake_stack_save) { |
| 163 |
#if HAS_FEATURE_ADDRESS_SANITIZER |
| 164 |
__sanitizer_finish_switch_fiber(fake_stack_save, NULL, NULL); |
| 165 |
#endif |
| 166 |
} |
| 167 |
|
| 168 |
/* Refresh f->resume_stack from whoever is currently the running fiber, so the next siglongjmp() out |
| 169 |
* of f (in the trampoline or fiber_swap()) can hand the right destination stack to ASAN. Must be |
| 170 |
* called before fiber_set_current(f) — relies on fiber_get_current() returning the caller. */ |
| 171 |
static void fiber_set_resume_stack(Fiber *f, Fiber *resume) { |
| 172 |
assert(f); |
| 173 |
|
| 174 |
if (resume) |
| 175 |
f->resume_stack = fiber_stack_usable(&resume->stack); |
| 176 |
else |
| 177 |
f->resume_stack = (struct iovec) {}; |
| 178 |
} |
| 179 |
|
| 180 |
_noreturn_ static void fiber_entry_point(void) { |
| 181 |
Fiber *f = ASSERT_PTR(fiber_get_current()); |
| 182 |
void *fake_stack_save = NULL; |
| 183 |
|
| 184 |
assert(f->func); |
| 185 |
assert(IN_SET(f->state, FIBER_STATE_INITIAL, FIBER_STATE_READY, FIBER_STATE_CANCELLED)); |
| 186 |
|
| 187 |
finish_switch_stack(NULL); |
| 188 |
|
| 189 |
/* Capture our resumable point on the fiber's stack, then bounce back to whoever last set |
| 190 |
* f->resume_context. On bootstrap that's fiber_bootstrap(); on every subsequent yield it's |
| 191 |
* the most recent fiber_run(). sigsetjmp(buf, 0) skips the signal-mask save: switching is |
| 192 |
* thread-shared with respect to signal masks. */ |
| 193 |
if (sigsetjmp(f->context, /* savemask= */ 0) == 0) { |
| 194 |
start_switch_stack(&fake_stack_save, &f->resume_stack); |
| 195 |
siglongjmp_unchecked(f->resume_context, /* val= */ 1); |
| 196 |
} |
| 197 |
|
| 198 |
/* Re-entered for real via fiber_run()'s siglongjmp(f->context). */ |
| 199 |
finish_switch_stack(fake_stack_save); |
| 200 |
|
| 201 |
/* Block scope so the cleanups attached to LOG_SET_PREFIX / LOG_CONTEXT_PUSH_KEY_VALUE fire |
| 202 |
* before the siglongjmp below — siglongjmp skips _cleanup_ attributes, so we have to make |
| 203 |
* sure the scope ends via a normal control-flow path first. */ |
| 204 |
{ |
| 205 |
LOG_SET_PREFIX(f->name); |
| 206 |
LOG_CONTEXT_PUSH_KEY_VALUE("FIBER=", f->name); |
| 207 |
|
| 208 |
f->result = f->state == FIBER_STATE_CANCELLED ? -ECANCELED : f->func(f->userdata); |
| 209 |
f->state = FIBER_STATE_COMPLETED; |
| 210 |
} |
| 211 |
|
| 212 |
/* Pass NULL fake_stack_save to discard the fiber's fake stack since the fiber is done. */ |
| 213 |
start_switch_stack(NULL, &f->resume_stack); |
| 214 |
|
| 215 |
/* Bounce back to whichever fiber_run() call most recently entered us. resume_context is |
| 216 |
* per-fiber so nested fiber_run() — e.g. a bus method dispatched as a fiber handler while |
| 217 |
* sd_event_loop() itself runs in a fiber — is safe. */ |
| 218 |
siglongjmp_unchecked(f->resume_context, 1); |
| 219 |
assert_not_reached(); |
| 220 |
} |
| 221 |
|
| 222 |
static int fiber_init(Fiber *f) { |
| 223 |
ucontext_t old_uc, uc; |
| 224 |
void *fake_stack_save = NULL; |
| 225 |
|
| 226 |
assert(f); |
| 227 |
|
| 228 |
if (getcontext(&uc) < 0) |
| 229 |
return -errno; |
| 230 |
|
| 231 |
struct iovec fiber_stack = fiber_stack_usable(&f->stack); |
| 232 |
|
| 233 |
uc.uc_link = NULL; /* Unused: trampoline siglongjmps out instead of returning. */ |
| 234 |
uc.uc_stack.ss_sp = fiber_stack.iov_base; |
| 235 |
uc.uc_stack.ss_size = fiber_stack.iov_len; |
| 236 |
uc.uc_stack.ss_flags = 0; |
| 237 |
|
| 238 |
Fiber *prev = fiber_get_current(); |
| 239 |
fiber_set_current(f); |
| 240 |
|
| 241 |
makecontext(&uc, fiber_entry_point, /* argc= */ 0); |
| 242 |
|
| 243 |
fiber_set_resume_stack(f, prev); |
| 244 |
if (sigsetjmp(f->resume_context, /* savemask= */ 0) == 0) { |
| 245 |
start_switch_stack(&fake_stack_save, &fiber_stack); |
| 246 |
if (swapcontext(&old_uc, &uc) < 0) { |
| 247 |
finish_switch_stack(fake_stack_save); |
| 248 |
fiber_set_current(prev); |
| 249 |
return -errno; |
| 250 |
} |
| 251 |
assert_not_reached(); /* Trampoline siglongjmps back; swapcontext doesn't return. */ |
| 252 |
} |
| 253 |
|
| 254 |
finish_switch_stack(fake_stack_save); |
| 255 |
|
| 256 |
fiber_set_current(prev); |
| 257 |
return 0; |
| 258 |
} |
| 259 |
|
| 260 |
/* Swap the thread-local log prefix and log context with the values stashed in f. While the fiber is |
| 261 |
* suspended, f holds the fiber's own log state; while it's running, f holds the caller's log state. The |
| 262 |
* swap is its own inverse, so the same call drives both directions. */ |
| 263 |
static void fiber_swap_log_state(Fiber *f) { |
| 264 |
assert(f); |
| 265 |
log_prefix_swap(&f->log_prefix); |
| 266 |
log_context_swap(&f->log_context, &f->log_context_num_fields); |
| 267 |
} |
| 268 |
|
| 269 |
static void reset_current_fiber(void) { |
| 270 |
/* Restore the caller's log state stashed in the running fiber (if any) before clearing |
| 271 |
* current_fiber. Without this, the child of a fork() that happened mid-fiber would inherit the |
| 272 |
* fiber's log prefix / context list in its thread-locals even though no fiber is running. */ |
| 273 |
Fiber *f = fiber_get_current(); |
| 274 |
if (f) { |
| 275 |
fiber_swap_log_state(f); |
| 276 |
fiber_ops_set(NULL); |
| 277 |
} |
| 278 |
fiber_set_current(NULL); |
| 279 |
} |
| 280 |
|
| 281 |
static sd_event_source* fiber_current_event_source(Fiber *f) { |
| 282 |
assert(f); |
| 283 |
assert(f->state != FIBER_STATE_COMPLETED); |
| 284 |
assert(f->event); |
| 285 |
|
| 286 |
return sd_event_get_state(f->event) == SD_EVENT_EXITING ? f->exit_event_source : f->defer_event_source; |
| 287 |
} |
| 288 |
|
| 289 |
static int atfork_ret; |
| 290 |
|
| 291 |
static void install_atfork(void) { |
| 292 |
/* __register_atfork() either returns 0 or -ENOMEM, in its glibc implementation. Since it's |
| 293 |
* only half-documented (glibc doesn't document it but LSB does — though only superficially) |
| 294 |
* we'll check for errors only in the most generic fashion possible. */ |
| 295 |
atfork_ret = pthread_atfork(/* prepare= */ NULL, /* parent= */ NULL, reset_current_fiber); |
| 296 |
if (atfork_ret != 0) |
| 297 |
log_debug_errno(atfork_ret, "pthread_atfork() failed: %m"); |
| 298 |
} |
| 299 |
|
| 300 |
static void fiber_resolve(sd_future *f) { |
| 301 |
Fiber *fiber = ASSERT_PTR(sd_future_get_private(ASSERT_PTR(f))); |
| 302 |
|
| 303 |
fiber->defer_event_source = sd_event_source_disable_unref(fiber->defer_event_source); |
| 304 |
fiber->exit_event_source = sd_event_source_disable_unref(fiber->exit_event_source); |
| 305 |
/* The floating self-ref (if any) is potentially the last ref keeping the fiber alive — moving it |
| 306 |
* into a local _cleanup_ slot ensures sd_future_resolve() runs callbacks and waiters while f is |
| 307 |
* still valid; the local's cleanup drops the ref afterwards, at which point no further f->... |
| 308 |
* access can happen. */ |
| 309 |
_unused_ _cleanup_(sd_future_unrefp) sd_future *floating = TAKE_PTR(fiber->floating); |
| 310 |
sd_future_resolve(f, fiber->result); |
| 311 |
} |
| 312 |
|
| 313 |
static const FiberOps fiber_ops = { |
| 314 |
.ppoll = sd_fiber_ppoll, |
| 315 |
.read = sd_fiber_read, |
| 316 |
.write = sd_fiber_write, |
| 317 |
.timeout = sd_fiber_timeout, |
| 318 |
.cancel_wait_unref = sd_future_cancel_wait_unref, |
| 319 |
}; |
| 320 |
|
| 321 |
static void fiber_enter(Fiber *fiber, Fiber *prev, void **fake_stack_save) { |
| 322 |
fiber_set_current(fiber); |
| 323 |
fiber_swap_log_state(fiber); |
| 324 |
if (!prev) |
| 325 |
fiber_ops_set(&fiber_ops); |
| 326 |
|
| 327 |
struct iovec fiber_stack = fiber_stack_usable(&fiber->stack); |
| 328 |
start_switch_stack(fake_stack_save, &fiber_stack); |
| 329 |
fiber_set_resume_stack(fiber, prev); |
| 330 |
} |
| 331 |
|
| 332 |
static void fiber_leave(Fiber *fiber, Fiber *prev, void *fake_stack_save) { |
| 333 |
finish_switch_stack(fake_stack_save); |
| 334 |
if (!prev) |
| 335 |
fiber_ops_set(NULL); |
| 336 |
fiber_swap_log_state(fiber); |
| 337 |
fiber_set_current(prev); |
| 338 |
} |
| 339 |
|
| 340 |
static int fiber_run(sd_future *f) { |
| 341 |
Fiber *fiber = ASSERT_PTR(sd_future_get_private(ASSERT_PTR(f))); |
| 342 |
int r; |
| 343 |
|
| 344 |
if (fiber->state == FIBER_STATE_COMPLETED) |
| 345 |
return -ESTALE; |
| 346 |
|
| 347 |
assert(IN_SET(fiber->state, FIBER_STATE_INITIAL, FIBER_STATE_READY, FIBER_STATE_CANCELLED)); |
| 348 |
|
| 349 |
static pthread_once_t atfork_once = PTHREAD_ONCE_INIT; |
| 350 |
r = pthread_once(&atfork_once, install_atfork); |
| 351 |
if (r != 0) |
| 352 |
return -r; |
| 353 |
if (atfork_ret != 0) |
| 354 |
return -atfork_ret; |
| 355 |
|
| 356 |
LOG_SET_PREFIX(fiber->name); |
| 357 |
LOG_CONTEXT_PUSH_KEY_VALUE("FIBER=", fiber->name); |
| 358 |
|
| 359 |
log_debug("Scheduling fiber"); |
| 360 |
|
| 361 |
/* Save the previously-current fiber (if any) so we can restore it when this fiber yields or |
| 362 |
* completes. This matters when fiber_run() is invoked from within another fiber (e.g. an |
| 363 |
* sd-event dispatch that happens to be running inside a fiber context itself): the |
| 364 |
* LOG_SET_PREFIX/LOG_CONTEXT_PUSH above attached to whichever fiber was current at that moment, |
| 365 |
* and their scope-level cleanup must see the same fiber_get_current() when it runs to detach |
| 366 |
* them from the correct list. */ |
| 367 |
Fiber *prev = fiber_get_current(); |
| 368 |
void *fake_stack_save = NULL; |
| 369 |
fiber_enter(fiber, prev, &fake_stack_save); |
| 370 |
|
| 371 |
/* This is where we start executing the fiber. Once it yields, we continue here as if nothing |
| 372 |
* happened. resume_context captures this point; the fiber siglongjmps back to it. */ |
| 373 |
if (sigsetjmp(fiber->resume_context, 0) == 0) |
| 374 |
siglongjmp_unchecked(fiber->context, 1); |
| 375 |
|
| 376 |
fiber_leave(fiber, prev, fake_stack_save); |
| 377 |
|
| 378 |
switch (fiber->state) { |
| 379 |
|
| 380 |
case FIBER_STATE_COMPLETED: |
| 381 |
if (fiber->result < 0 && fiber->result != -ECANCELED) |
| 382 |
log_debug_errno(fiber->result, "Fiber failed with error: %m"); |
| 383 |
else |
| 384 |
log_debug("Fiber finished executing"); |
| 385 |
|
| 386 |
fiber_resolve(f); |
| 387 |
break; |
| 388 |
|
| 389 |
case FIBER_STATE_CANCELLED: |
| 390 |
case FIBER_STATE_READY: |
| 391 |
log_debug("Fiber yielded execution"); |
| 392 |
|
| 393 |
r = sd_event_source_set_enabled(fiber_current_event_source(fiber), SD_EVENT_ONESHOT); |
| 394 |
if (r < 0) |
| 395 |
return r; |
| 396 |
break; |
| 397 |
|
| 398 |
case FIBER_STATE_SUSPENDED: |
| 399 |
log_debug("Fiber suspended execution"); |
| 400 |
/* Fiber is waiting for something - don't re-queue it */ |
| 401 |
break; |
| 402 |
|
| 403 |
default: |
| 404 |
assert_not_reached(); |
| 405 |
} |
| 406 |
|
| 407 |
return 0; |
| 408 |
} |
| 409 |
|
| 410 |
static int fiber_cancel(sd_future *f) { |
| 411 |
Fiber *fiber = ASSERT_PTR(sd_future_get_private(ASSERT_PTR(f))); |
| 412 |
int r; |
| 413 |
|
| 414 |
assert(fiber != fiber_get_current()); |
| 415 |
|
| 416 |
if (IN_SET(fiber->state, FIBER_STATE_COMPLETED, FIBER_STATE_CANCELLED)) |
| 417 |
return 0; |
| 418 |
|
| 419 |
if (fiber->state == FIBER_STATE_INITIAL) { |
| 420 |
/* The fiber's stack was allocated but never entered, so there are no scope-level cleanups |
| 421 |
* waiting to run. Skip the dispatch round-trip that would just have fiber_entry_point() |
| 422 |
* fall straight through with -ECANCELED, and settle the future right here — mirroring the |
| 423 |
* FIBER_STATE_COMPLETED branch of fiber_run(). */ |
| 424 |
fiber->result = -ECANCELED; |
| 425 |
fiber->state = FIBER_STATE_COMPLETED; |
| 426 |
fiber_resolve(f); |
| 427 |
return 1; |
| 428 |
} |
| 429 |
|
| 430 |
/* Once we cancel a fiber, we want to immediately resume it with -ECANCELED. */ |
| 431 |
r = sd_event_source_set_enabled(fiber_current_event_source(fiber), SD_EVENT_ONESHOT); |
| 432 |
if (r < 0) |
| 433 |
return r; |
| 434 |
|
| 435 |
fiber->state = FIBER_STATE_CANCELLED; |
| 436 |
|
| 437 |
return 1; |
| 438 |
} |
| 439 |
|
| 440 |
static int fiber_on_defer(sd_event_source *s, void *userdata) { |
| 441 |
sd_future *f = ASSERT_PTR(userdata); |
| 442 |
return fiber_run(f); |
| 443 |
} |
| 444 |
|
| 445 |
static int fiber_on_exit(sd_event_source *s, void *userdata) { |
| 446 |
sd_future *f = ASSERT_PTR(userdata); |
| 447 |
Fiber *fiber = ASSERT_PTR(sd_future_get_private(f)); |
| 448 |
int r; |
| 449 |
|
| 450 |
/* The fiber may already have completed via the regular defer path before sd_event_exit() |
| 451 |
* fires the exit source; in that case there's nothing left to drive and we'd otherwise |
| 452 |
* trip fiber_run()'s -ESTALE return, which sd_event would log spuriously and disable the |
| 453 |
* source for. */ |
| 454 |
if (fiber->state == FIBER_STATE_COMPLETED) |
| 455 |
return 0; |
| 456 |
|
| 457 |
/* If fiber_cancel() returned 1 the fiber was just marked cancelled and its deferred/exit event |
| 458 |
* source was re-armed; we let the event loop dispatch that source on the next iteration so it goes |
| 459 |
* through the normal fiber_on_defer/fiber_on_exit path rather than running it recursively here. */ |
| 460 |
r = fiber_cancel(f); |
| 461 |
if (r != 0) |
| 462 |
return r; |
| 463 |
|
| 464 |
return fiber_run(f); |
| 465 |
} |
| 466 |
|
| 467 |
static void* fiber_alloc(void) { |
| 468 |
return new0(Fiber, 1); |
| 469 |
} |
| 470 |
|
| 471 |
static void fiber_free(sd_future *f) { |
| 472 |
Fiber *fiber = ASSERT_PTR(sd_future_get_private(f)); |
| 473 |
|
| 474 |
/* To make sure all memory is deallocated, the fiber has to have completed by the time we free it to |
| 475 |
* make sure its stack has finished unwinding (which will invoke the registered cleanup functions). |
| 476 |
* As this function may get called when not running on a fiber ourselves, we can't guarantee here |
| 477 |
* that we can run the fiber to completion ourselves, so we insist that this happens before we get |
| 478 |
* here. To ensure fibers are cleaned up before exiting the event loop, exit handlers are added for |
| 479 |
* fibers created outside of existing fibers. For fibers created within running fibers, unwinding the |
| 480 |
* outer fiber should take care of cleaning up any created child fibers (for example using |
| 481 |
* sd_future_cancel_wait_unref()). |
| 482 |
* |
| 483 |
* FIBER_STATE_INITIAL is also accepted: the stack was allocated but never entered, so there are no |
| 484 |
* registered cleanups to run. This covers the partial-construction failure path in sd_fiber_new() |
| 485 |
* as well as fibers that are unrefed before the event loop ever dispatches them. */ |
| 486 |
assert(IN_SET(fiber->state, FIBER_STATE_INITIAL, FIBER_STATE_COMPLETED)); |
| 487 |
|
| 488 |
if (fiber->destroy) |
| 489 |
fiber->destroy(fiber->userdata); |
| 490 |
|
| 491 |
#if HAVE_VALGRIND_VALGRIND_H |
| 492 |
if (fiber->stack.iov_base) |
| 493 |
VALGRIND_STACK_DEREGISTER(fiber->stack_id); |
| 494 |
#endif |
| 495 |
|
| 496 |
if (fiber->stack.iov_base) |
| 497 |
(void) munmap(fiber->stack.iov_base, fiber->stack.iov_len); |
| 498 |
|
| 499 |
sd_event_source_disable_unref(fiber->defer_event_source); |
| 500 |
sd_event_source_disable_unref(fiber->exit_event_source); |
| 501 |
sd_event_unref(fiber->event); |
| 502 |
|
| 503 |
free(fiber->name); |
| 504 |
free(fiber); |
| 505 |
} |
| 506 |
|
| 507 |
sd_future* sd_fiber_get_current(void) { |
| 508 |
Fiber *f = fiber_get_current(); |
| 509 |
if (!f) |
| 510 |
return NULL; |
| 511 |
|
| 512 |
return sd_event_source_get_userdata(fiber_current_event_source(f)); |
| 513 |
} |
| 514 |
|
| 515 |
int sd_fiber_is_running(void) { |
| 516 |
return !!fiber_get_current(); |
| 517 |
} |
| 518 |
|
| 519 |
sd_event* sd_fiber_get_event(void) { |
| 520 |
Fiber *f = fiber_get_current(); |
| 521 |
assert_return(f, NULL); |
| 522 |
return f->event; |
| 523 |
} |
| 524 |
|
| 525 |
int sd_fiber_get_priority(int64_t *ret) { |
| 526 |
Fiber *f = fiber_get_current(); |
| 527 |
|
| 528 |
assert_return(ret, -EINVAL); |
| 529 |
assert_return(f, -ESRCH); |
| 530 |
|
| 531 |
*ret = f->priority; |
| 532 |
return 0; |
| 533 |
} |
| 534 |
|
| 535 |
static int fiber_swap(FiberState state) { |
| 536 |
Fiber *f = ASSERT_PTR(fiber_get_current()); |
| 537 |
|
| 538 |
f->state = state; |
| 539 |
|
| 540 |
void *fake_stack_save = NULL; |
| 541 |
|
| 542 |
if (sigsetjmp(f->context, 0) == 0) { |
| 543 |
start_switch_stack(&fake_stack_save, &f->resume_stack); |
| 544 |
siglongjmp_unchecked(f->resume_context, 1); |
| 545 |
} |
| 546 |
|
| 547 |
finish_switch_stack(fake_stack_save); |
| 548 |
|
| 549 |
/* When we get here, we've been resumed. */ |
| 550 |
|
| 551 |
if (f->state == FIBER_STATE_CANCELLED) |
| 552 |
return -ECANCELED; |
| 553 |
|
| 554 |
/* sd_fiber_resume() stashes the resumer's value (an async wakeup error from a deadline |
| 555 |
* timer, an io_uring CQE result, etc.) into f->result for us to surface here. Consume it |
| 556 |
* unconditionally so it doesn't pollute subsequent suspends or the fiber's eventual return |
| 557 |
* value — both negative errors and positive payloads (byte counts, accepted fds, revents |
| 558 |
* masks) are valid resume values. */ |
| 559 |
return TAKE_GENERIC(f->result, int, 0); |
| 560 |
} |
| 561 |
|
| 562 |
int sd_fiber_yield(void) { |
| 563 |
assert_return(fiber_get_current(), -ESRCH); |
| 564 |
return fiber_swap(FIBER_STATE_READY); |
| 565 |
} |
| 566 |
|
| 567 |
int sd_fiber_suspend(void) { |
| 568 |
assert_return(fiber_get_current(), -ESRCH); |
| 569 |
return fiber_swap(FIBER_STATE_SUSPENDED); |
| 570 |
} |
| 571 |
|
| 572 |
static int fiber_set_priority(sd_future *f, int64_t priority) { |
| 573 |
Fiber *fiber = ASSERT_PTR(sd_future_get_private(ASSERT_PTR(f))); |
| 574 |
int r = 0; |
| 575 |
|
| 576 |
if (fiber->defer_event_source) |
| 577 |
RET_GATHER(r, sd_event_source_set_priority(fiber->defer_event_source, priority)); |
| 578 |
|
| 579 |
if (fiber->exit_event_source) |
| 580 |
RET_GATHER(r, sd_event_source_set_priority(fiber->exit_event_source, priority)); |
| 581 |
|
| 582 |
if (r >= 0) |
| 583 |
fiber->priority = priority; |
| 584 |
|
| 585 |
return r; |
| 586 |
} |
| 587 |
|
| 588 |
static const sd_future_ops fiber_future_ops; |
| 589 |
|
| 590 |
int sd_fiber_resume(sd_future *f, int result) { |
| 591 |
assert_return(f, -EINVAL); |
| 592 |
assert_return(sd_future_get_ops(f) == &fiber_future_ops, -EINVAL); |
| 593 |
|
| 594 |
Fiber *fiber = ASSERT_PTR(sd_future_get_private(f)); |
| 595 |
|
| 596 |
if (fiber->state != FIBER_STATE_SUSPENDED) |
| 597 |
return 0; |
| 598 |
|
| 599 |
/* Stash the result so fiber_swap() returns it from sd_fiber_suspend(). */ |
| 600 |
fiber->result = result; |
| 601 |
fiber->state = FIBER_STATE_READY; |
| 602 |
return sd_event_source_set_enabled(fiber_current_event_source(fiber), SD_EVENT_ONESHOT); |
| 603 |
} |
| 604 |
|
| 605 |
/* The fiber_future ops pass the Fiber pointer through as the future's private state. The fiber resolves |
| 606 |
* its own future once it finishes running, so fiber_cancel() intentionally does not resolve. */ |
| 607 |
static const sd_future_ops fiber_future_ops = { |
| 608 |
.size = sizeof(sd_future_ops), |
| 609 |
.alloc = fiber_alloc, |
| 610 |
.free = fiber_free, |
| 611 |
.cancel = fiber_cancel, |
| 612 |
.set_priority = fiber_set_priority, |
| 613 |
}; |
| 614 |
|
| 615 |
int sd_fiber_new(sd_event *e, const char *name, sd_fiber_func_t func, void *userdata, sd_fiber_destroy_t destroy, sd_future **ret) { |
| 616 |
int r; |
| 617 |
|
| 618 |
assert_return(e, -EINVAL); |
| 619 |
assert_return(name, -EINVAL); |
| 620 |
assert_return(func, -EINVAL); |
| 621 |
|
| 622 |
if (IN_SET(sd_event_get_state(e), SD_EVENT_EXITING, SD_EVENT_FINISHED)) |
| 623 |
return -ECANCELED; |
| 624 |
|
| 625 |
_cleanup_(sd_future_unrefp) sd_future *f = NULL; |
| 626 |
r = sd_future_new(&fiber_future_ops, &f); |
| 627 |
if (r < 0) |
| 628 |
return r; |
| 629 |
|
| 630 |
Fiber *fiber = ASSERT_PTR(sd_future_get_private(f)); |
| 631 |
|
| 632 |
struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY }; |
| 633 |
if (getrlimit(RLIMIT_STACK, &rl) < 0) |
| 634 |
log_debug_errno(errno, "Reading RLIMIT_STACK failed, ignoring: %m"); |
| 635 |
if (rl.rlim_cur == RLIM_INFINITY) |
| 636 |
rl.rlim_cur = 8U * U64_MB; /* Same as the default thread stack size */ |
| 637 |
|
| 638 |
/* Reserve room for the guard page so the usable region stays above PTHREAD_STACK_MIN, which |
| 639 |
* is what libc/pthread routines (e.g. TLS setup on musl) assume. */ |
| 640 |
size_t stack_len = ROUND_UP(rl.rlim_cur, page_size()); |
| 641 |
if (stack_len < (size_t) PTHREAD_STACK_MIN + page_size()) |
| 642 |
stack_len = ROUND_UP((size_t) PTHREAD_STACK_MIN + page_size(), page_size()); |
| 643 |
|
| 644 |
*fiber = (Fiber) { |
| 645 |
.stack.iov_len = stack_len, |
| 646 |
.state = FIBER_STATE_INITIAL, |
| 647 |
.name = strdup(name), |
| 648 |
.func = func, |
| 649 |
.userdata = userdata, |
| 650 |
.event = sd_event_ref(e), |
| 651 |
}; |
| 652 |
if (!fiber->name) |
| 653 |
return -ENOMEM; |
| 654 |
|
| 655 |
r = fiber_allocate_stack(fiber->stack.iov_len, &fiber->stack.iov_base); |
| 656 |
if (r < 0) |
| 657 |
return r; |
| 658 |
|
| 659 |
#if HAVE_VALGRIND_VALGRIND_H |
| 660 |
/* Register the usable stack range (above the guard page) before fiber_bootstrap() so the |
| 661 |
* trampoline's first sigsetjmp doesn't trip Valgrind's stack-tracking heuristics. */ |
| 662 |
struct iovec usable = fiber_stack_usable(&fiber->stack); |
| 663 |
fiber->stack_id = VALGRIND_STACK_REGISTER( |
| 664 |
usable.iov_base, |
| 665 |
(uint8_t*) usable.iov_base + usable.iov_len); |
| 666 |
#endif |
| 667 |
|
| 668 |
r = fiber_init(fiber); |
| 669 |
if (r < 0) |
| 670 |
return r; |
| 671 |
|
| 672 |
/* Execution of the fiber is driven by two event sources, one deferred, one exit. The exit event |
| 673 |
* source kicks in when sd_event_exit() is called, as from that point onwards only exit event |
| 674 |
* sources will be dispatched. */ |
| 675 |
|
| 676 |
r = sd_event_add_defer(e, &fiber->defer_event_source, fiber_on_defer, f); |
| 677 |
if (r < 0) |
| 678 |
return r; |
| 679 |
|
| 680 |
r = sd_event_source_set_description(fiber->defer_event_source, fiber->name); |
| 681 |
if (r < 0) |
| 682 |
return r; |
| 683 |
|
| 684 |
r = sd_event_add_exit(e, &fiber->exit_event_source, fiber_on_exit, f); |
| 685 |
if (r < 0) |
| 686 |
return r; |
| 687 |
|
| 688 |
r = sd_event_source_set_description(fiber->exit_event_source, fiber->name); |
| 689 |
if (r < 0) |
| 690 |
return r; |
| 691 |
|
| 692 |
/* If we're on a fiber, we'll rely on the parent fiber to cancel this fiber if the event loop is |
| 693 |
* exiting. Otherwise, we'll trigger cancellation of this fiber via the exit event source. Why cancel |
| 694 |
* via the exit event source? We can only run the fiber while the event loop is active, so we need to |
| 695 |
* make sure all fibers finish running before the event loop is finished, which an exit event source |
| 696 |
* allows us to do. */ |
| 697 |
r = sd_event_source_set_enabled(fiber->exit_event_source, sd_fiber_is_running() ? SD_EVENT_OFF : SD_EVENT_ONESHOT); |
| 698 |
if (r < 0) |
| 699 |
return r; |
| 700 |
|
| 701 |
/* Stays in FIBER_STATE_INITIAL until the event loop first dispatches it via fiber_run(). */ |
| 702 |
|
| 703 |
if (ret) |
| 704 |
*ret = TAKE_PTR(f); |
| 705 |
else { |
| 706 |
/* Fire-and-forget: the fiber is guaranteed to resolve (via completion, cancellation, or |
| 707 |
* the event loop exit handler), so making the future floating cleans it up. */ |
| 708 |
r = sd_fiber_set_floating(f, true); |
| 709 |
if (r < 0) |
| 710 |
return r; |
| 711 |
} |
| 712 |
|
| 713 |
/* We only take ownership of the given userdata pointer on success so assign the destroy callback |
| 714 |
* at the very end so we don't clean up the userdata pointer on failure. */ |
| 715 |
fiber->destroy = destroy; |
| 716 |
|
| 717 |
return 0; |
| 718 |
} |
| 719 |
|
| 720 |
int sd_fiber_set_floating(sd_future *f, int b) { |
| 721 |
assert_return(f, -EINVAL); |
| 722 |
assert_return(sd_future_get_ops(f) == &fiber_future_ops, -EINVAL); |
| 723 |
|
| 724 |
Fiber *fiber = ASSERT_PTR(sd_future_get_private(f)); |
| 725 |
|
| 726 |
if (!!fiber->floating == !!b) |
| 727 |
return 0; |
| 728 |
|
| 729 |
/* The floating self-ref keeps the future alive until the fiber resolves; fiber_run() drops it |
| 730 |
* in the COMPLETED branch. Only valid for fiber futures because fibers uniquely guarantee |
| 731 |
* resolution (via completion, cancellation, or the event loop exit handler). */ |
| 732 |
if (b) |
| 733 |
fiber->floating = sd_future_ref(f); |
| 734 |
else |
| 735 |
fiber->floating = sd_future_unref(fiber->floating); |
| 736 |
|
| 737 |
return 0; |
| 738 |
} |
| 739 |
|
| 740 |
int sd_fiber_get_floating(sd_future *f) { |
| 741 |
assert_return(f, -EINVAL); |
| 742 |
assert_return(sd_future_get_ops(f) == &fiber_future_ops, -EINVAL); |
| 743 |
|
| 744 |
Fiber *fiber = ASSERT_PTR(sd_future_get_private(f)); |
| 745 |
return !!fiber->floating; |
| 746 |
} |
| 747 |
|
| 748 |
int sd_fiber_sleep(uint64_t usec) { |
| 749 |
Fiber *f = fiber_get_current(); |
| 750 |
int r; |
| 751 |
|
| 752 |
if (!f) |
| 753 |
return usleep_safe(usec); |
| 754 |
|
| 755 |
if (usec == 0) |
| 756 |
return sd_fiber_yield(); |
| 757 |
|
| 758 |
/* Match usleep_safe(USEC_INFINITY): suspend indefinitely. Passing USEC_INFINITY to |
| 759 |
* sd_event_add_time_relative() would overflow into -EOVERFLOW. */ |
| 760 |
if (usec == USEC_INFINITY) |
| 761 |
return sd_fiber_suspend(); |
| 762 |
|
| 763 |
assert(f->event); |
| 764 |
|
| 765 |
_cleanup_(sd_future_cancel_wait_unrefp) sd_future *timer = NULL; |
| 766 |
r = future_new_time_relative( |
| 767 |
f->event, |
| 768 |
CLOCK_MONOTONIC, |
| 769 |
usec, |
| 770 |
/* accuracy= */ 1, |
| 771 |
/* result= */ 0, |
| 772 |
&timer); |
| 773 |
if (r < 0) |
| 774 |
return r; |
| 775 |
|
| 776 |
return sd_fiber_suspend(); |
| 777 |
} |
| 778 |
|
| 779 |
int sd_fiber_await(sd_future *target) { |
| 780 |
sd_future *f = sd_fiber_get_current(); |
| 781 |
int r; |
| 782 |
|
| 783 |
assert_return(f, -ESRCH); |
| 784 |
assert_return(target, -EINVAL); |
| 785 |
assert_return(target != f, -EDEADLK); |
| 786 |
|
| 787 |
Fiber *fiber = ASSERT_PTR(sd_future_get_private(f)); |
| 788 |
|
| 789 |
if (sd_future_state(target) == SD_FUTURE_RESOLVED) |
| 790 |
return sd_future_result(target); |
| 791 |
|
| 792 |
/* Note that we do allow waiting for other fibers when the event loop is exiting, since waiting for |
| 793 |
* other fibers does not require adding new event sources to the event loop. */ |
| 794 |
if (sd_event_get_state(fiber->event) == SD_EVENT_FINISHED) |
| 795 |
return -ECANCELED; |
| 796 |
|
| 797 |
_cleanup_(sd_future_cancel_wait_unrefp) sd_future *wait = NULL; |
| 798 |
r = sd_future_new_wait(target, &wait); |
| 799 |
if (r < 0) |
| 800 |
return r; |
| 801 |
|
| 802 |
return sd_fiber_suspend(); |
| 803 |
} |
| 804 |
|
| 805 |
sd_future* sd_fiber_timeout(uint64_t timeout) { |
| 806 |
Fiber *fiber = fiber_get_current(); |
| 807 |
int r; |
| 808 |
|
| 809 |
assert_return(fiber, NULL); |
| 810 |
|
| 811 |
if (timeout == USEC_INFINITY) |
| 812 |
return NULL; |
| 813 |
|
| 814 |
sd_future *timer; |
| 815 |
r = future_new_time_relative( |
| 816 |
fiber->event, |
| 817 |
CLOCK_MONOTONIC, |
| 818 |
timeout, |
| 819 |
/* accuracy= */ 1, |
| 820 |
/* result= */ -ETIME, |
| 821 |
&timer); |
| 822 |
if (r < 0) |
| 823 |
return NULL; /* On allocation failure no timer is armed and the scope becomes a no-op. |
| 824 |
* Errors here are rare; if the caller cares they can compare to NULL. */ |
| 825 |
|
| 826 |
return timer; |
| 827 |
} |