dtact 0.1.5

Dtact: A non-preemptive, stackful coroutine runtime featuring a lock-free context arena, P2P mesh scheduling, and architecture-specific assembly switchers. Designed for hardware-level control and non-blocking heterogeneous orchestration.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
use crate::dta_scheduler::TopologyMode;
use crate::memory_management::SafetyLevel;
use core::ffi::c_void;

/// Opaque handle representing a spawned Dtact fiber.
#[allow(non_camel_case_types)]
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct dtact_handle_t(pub u64);

/// Configuration structure for initializing the Dtact runtime from C.
#[repr(C)]
pub struct dtact_config_t {
    /// Number of hardware worker threads. Set to 0 for auto-detection.
    pub workers: u32,
    /// Memory safety level (0-2).
    pub safety_level: u8,
    /// Topology mode (0: `P2PMesh`, 1: Global).
    pub topology_mode: u8,
    /// Maximum number of concurrent fibers. Set to 0 for default (4096).
    pub fiber_capacity: u32,
    /// Stack size per fiber in bytes. Set to 0 for default (512KB).
    pub stack_size: u32,
}

/// Advanced options for spawning a fiber from C FFI.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct dtact_spawn_options_t {
    /// 0: Low, 1: Normal, 2: High, 3: Critical
    pub priority: u8,
    /// 0: `SameCore`, 1: `SameCCX`, 2: `SameNUMA`, 3: Any
    pub affinity: u8,
    /// 0: Compute, 1: IO, 2: Memory, 3: System
    pub kind: u8,
    /// 0: `CrossThreadFloat`, 1: `CrossThreadNoFloat`, 2: `SameThreadFloat`, 3: `SameThreadNoFloat`
    pub switcher: u8,
}

/// Returns the recommended default options for the Dtact runtime.
#[unsafe(no_mangle)]
pub const extern "C" fn dtact_default_spawn_options() -> dtact_spawn_options_t {
    dtact_spawn_options_t {
        priority: 1, // Normal
        affinity: 0, // SameCore
        kind: 0,     // Compute
        switcher: 0, // CrossThreadFloat
    }
}

/// Returns the recommended default configuration for the Dtact runtime.
#[unsafe(no_mangle)]
pub const extern "C" fn dtact_default_config() -> dtact_config_t {
    dtact_config_t {
        workers: 0,        // Auto-detect
        safety_level: 1,   // Safety1
        topology_mode: 0,  // P2PMesh
        fiber_capacity: 0, // Default 4096
        stack_size: 0,     // Default 512KB
    }
}

/// Initializes the global Dtact runtime singleton.
///
/// # Safety
/// * This function should be called once at application startup.
/// * `cfg` must be a valid, non-null pointer to a `dtact_config_t` structure.
///
/// # Panics
/// * Panics if the runtime is already initialized or if memory allocation fails.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn dtact_init(cfg: *const dtact_config_t) -> *mut c_void {
    let cfg = unsafe { &*cfg };
    let workers = if cfg.workers == 0 {
        std::thread::available_parallelism().map_or(1, std::num::NonZero::get)
    } else {
        cfg.workers as usize
    };

    let safety = match cfg.safety_level {
        0 => SafetyLevel::Safety0,
        2 => SafetyLevel::Safety2,
        _ => SafetyLevel::Safety1,
    };

    let topology = match cfg.topology_mode {
        1 => TopologyMode::Global,
        _ => TopologyMode::P2PMesh,
    };

    let capacity = if cfg.fiber_capacity == 0 {
        4096
    } else {
        cfg.fiber_capacity
    };
    let stack_size = if cfg.stack_size == 0 {
        512 * 1024
    } else {
        cfg.stack_size as usize
    };

    crate::GLOBAL_RUNTIME.get_or_init(|| {
        let scheduler = crate::dta_scheduler::DtaScheduler::new(workers, topology);
        let pool = crate::memory_management::ContextPool::new(capacity, stack_size, safety, 0)
            .expect("DTA-V3 FFI Initialization Failed");
        crate::Runtime {
            scheduler,
            pool,
            started: core::sync::atomic::AtomicBool::new(false),
            shutdown: core::sync::atomic::AtomicBool::new(false),
        }
    });

    // Return a dummy pointer as "runtime handle" for C
    core::ptr::null_mut()
}

/// Critical failure handler. Aborts the process if a fiber attempts to
/// return without properly terminating via the runtime.
#[unsafe(no_mangle)]
pub extern "C" fn dtact_abort() -> ! {
    eprintln!("DTA-V3 Critical: Fiber attempted to 'return' instead of yielding. Stack corrupted.");
    std::process::abort();
}

/// Frees an argument pointer previously allocated for a fiber.
///
/// # Safety
/// * `arg` must be a valid pointer previously allocated by the C allocator (e.g. `malloc`).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn dtact_free_arg(arg: *mut c_void) {
    if !arg.is_null() {
        unsafe {
            // Assumes standard C allocator (malloc/free)
            libc::free(arg);
        }
    }
}

/// Launches a C-function as a DTA-V3 stackful Fiber.
///
/// # Safety
/// * `func` must be a valid function pointer.
/// * `arg` must point to memory that remains valid for the entire duration of the fiber's execution.
///   Since the fiber is launched asynchronously, the caller's stack may return before the fiber starts.
///   **Critical**: `arg` must be heap-allocated (and freed within the fiber) or static.
///
/// # Panics
/// * Panics if the runtime is not initialized.
/// * Panics if the context pool is exhausted.
#[unsafe(no_mangle)]
#[allow(clippy::cast_possible_truncation)]
pub unsafe extern "C" fn dtact_fiber_launch(
    func: extern "C" fn(*mut c_void),
    arg: *mut c_void,
) -> dtact_handle_t {
    let runtime = crate::GLOBAL_RUNTIME
        .get()
        .expect("Dtact Runtime not initialized");
    let pool = &runtime.pool;
    let ctx_id = pool.alloc_context().expect("Context pool exhausted - OOM");

    let ctx_ptr = pool.get_context_ptr(ctx_id);
    #[allow(clippy::cast_possible_truncation)]
    let current_core = crate::api::topology::current().core_id as usize;

    unsafe {
        (*ctx_ptr).state.store(
            crate::memory_management::FiberStatus::Running as u32,
            core::sync::atomic::Ordering::Release,
        );
        (*ctx_ptr).origin_core = current_core as u16;
        (*ctx_ptr).fiber_index = ctx_id;
        (*ctx_ptr).switch_fn = crate::context_switch::switch_context_cross_thread_float;

        (*ctx_ptr).closure_ptr = arg.cast::<()>();
        (*ctx_ptr).trampoline =
            core::mem::transmute::<extern "C" fn(*mut c_void), unsafe extern "C" fn()>(func);

        // Unified Trampoline for C-Functions
        (*ctx_ptr).invoke_closure = |ptr| {
            // In C-FFI, we don't need the ctx here, we just call the trampoline with ptr (which is closure_ptr)
            let ctx_ptr = crate::future_bridge::CURRENT_FIBER.with(std::cell::Cell::get);
            if let Some(ctx) = unsafe { ctx_ptr.as_ref() } {
                let f: extern "C" fn(*mut c_void) = unsafe { core::mem::transmute(ctx.trampoline) };
                f(ptr.cast::<c_void>());
            }
        };

        // 3. ABI-Compliant Stack Alignment & Poisoning
        // We leave 72 bytes for Shadow Space (Windows) and Future safety.
        // -72 ensures that RSP is 16-byte aligned + 8, which is required by the Windows x64 ABI.
        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        let stack_top = (ctx_ptr as usize & !0xF) - 72;
        #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
        let stack_top = (ctx_ptr as usize & !0xF) - 80;

        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        let stack_top_ptr = stack_top as *mut u64;

        // Place a "poison" return address on the stack.
        // If the fiber function ever attempts to 'ret', it will jump here and abort.
        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        core::ptr::write(stack_top_ptr, dtact_abort as *const () as u64);

        let stack_top = stack_top as *mut u8;

        #[cfg(target_arch = "x86_64")]
        {
            (*ctx_ptr).regs.gprs[0] = stack_top as u64; // RSP
            (*ctx_ptr).regs.gprs[7] = crate::api::fiber_entry_point as *const () as u64; // RIP
            #[cfg(windows)]
            {
                let limit = (ctx_ptr as usize).saturating_sub(pool.slot_size);
                (*ctx_ptr).regs.gprs[10] = ctx_ptr as u64; // Stack Base
                (*ctx_ptr).regs.gprs[11] = limit as u64; // Stack Limit
                (*ctx_ptr).regs.gprs[12] = limit as u64; // DeallocationStack
                (*ctx_ptr).regs.gprs[13] = !0; // ExceptionList
            }
        }
        #[cfg(target_arch = "aarch64")]
        {
            (*ctx_ptr).regs.gprs[12] = stack_top as u64; // SP
            (*ctx_ptr).regs.gprs[11] = crate::api::fiber_entry_point as *const () as u64; // x30 (LR)
            #[cfg(windows)]
            {
                let limit = (ctx_ptr as usize).saturating_sub(pool.slot_size);
                (*ctx_ptr).regs.gprs[13] = ctx_ptr as u64; // Stack Base
                (*ctx_ptr).regs.gprs[14] = limit as u64; // Stack Limit
                (*ctx_ptr).regs.gprs[15] = limit as u64; // DeallocationStack
            }
        }
        #[cfg(target_arch = "riscv64")]
        {
            (*ctx_ptr).regs.gprs[0] = stack_top as u64; // SP
            (*ctx_ptr).regs.gprs[13] = crate::api::fiber_entry_point as *const () as u64; // RA
        }
        (*ctx_ptr).cleanup_fn = None;
    }

    let r#gen = u64::from(unsafe {
        (*ctx_ptr)
            .generation
            .load(core::sync::atomic::Ordering::Acquire)
    });
    crate::wake_fiber(current_core, ctx_id);

    // Handle Layout: [1-bit Valid | 15-bit Generation | 16-bit CoreID | 32-bit ContextID]
    dtact_handle_t(
        u64::from(ctx_id) | ((current_core as u64) << 32) | ((r#gen & 0x7FFF) << 48) | (1 << 63),
    )
}

/// Launches a C-function as a DTA-V3 stackful Fiber with advanced options.
#[unsafe(no_mangle)]
#[allow(clippy::cast_possible_truncation)]
pub unsafe extern "C" fn dtact_fiber_launch_ext(
    func: extern "C" fn(*mut c_void),
    arg: *mut c_void,
    options: *const dtact_spawn_options_t,
) -> dtact_handle_t {
    let runtime = crate::GLOBAL_RUNTIME
        .get()
        .expect("Dtact Runtime not initialized");
    let pool = &runtime.pool;
    let ctx_id = pool.alloc_context().expect("Context pool exhausted - OOM");

    let ctx_ptr = pool.get_context_ptr(ctx_id);
    let current_core = crate::api::topology::current().core_id as usize;

    let opts = if options.is_null() {
        dtact_default_spawn_options()
    } else {
        unsafe { *options }
    };

    unsafe {
        (*ctx_ptr).state.store(
            crate::memory_management::FiberStatus::Running as u32,
            core::sync::atomic::Ordering::Release,
        );
        (*ctx_ptr).origin_core = current_core as u16;
        (*ctx_ptr).fiber_index = ctx_id;

        (*ctx_ptr).switch_fn = match opts.switcher {
            1 => crate::context_switch::switch_context_cross_thread_no_float,
            2 => crate::context_switch::switch_context_same_thread_float,
            3 => crate::context_switch::switch_context_same_thread_no_float,
            _ => crate::context_switch::switch_context_cross_thread_float,
        };

        (*ctx_ptr).kind = match opts.kind {
            1 => crate::common_types::WorkloadKind::IO,
            2 => crate::common_types::WorkloadKind::Memory,
            3 => crate::common_types::WorkloadKind::System,
            _ => crate::common_types::WorkloadKind::Compute,
        };

        (*ctx_ptr).adaptive_spin_count = match (*ctx_ptr).kind {
            crate::common_types::WorkloadKind::Compute => 1000,
            crate::common_types::WorkloadKind::IO => 100,
            crate::common_types::WorkloadKind::Memory => 500,
            crate::common_types::WorkloadKind::System => 200,
        };

        (*ctx_ptr).closure_ptr = arg.cast::<()>();
        (*ctx_ptr).trampoline =
            core::mem::transmute::<extern "C" fn(*mut c_void), unsafe extern "C" fn()>(func);

        (*ctx_ptr).invoke_closure = |ptr| {
            let ctx_ptr = crate::future_bridge::CURRENT_FIBER.with(std::cell::Cell::get);
            if let Some(ctx) = unsafe { ctx_ptr.as_ref() } {
                let f: extern "C" fn(*mut c_void) = unsafe { core::mem::transmute(ctx.trampoline) };
                f(ptr.cast::<c_void>());
            }
        };

        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        let stack_top = (ctx_ptr as usize & !0xF) - 72;
        #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
        let stack_top = (ctx_ptr as usize & !0xF) - 80;

        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        let stack_top_ptr = stack_top as *mut u64;
        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        core::ptr::write(stack_top_ptr, dtact_abort as *const () as u64);
        let stack_top = stack_top as *mut u8;

        #[cfg(target_arch = "x86_64")]
        {
            (*ctx_ptr).regs.gprs[0] = stack_top as u64;
            (*ctx_ptr).regs.gprs[7] = crate::api::fiber_entry_point as *const () as u64;
            #[cfg(windows)]
            {
                let limit = (ctx_ptr as usize).saturating_sub(pool.slot_size);
                (*ctx_ptr).regs.gprs[10] = ctx_ptr as u64;
                (*ctx_ptr).regs.gprs[11] = limit as u64;
                (*ctx_ptr).regs.gprs[12] = limit as u64;
                (*ctx_ptr).regs.gprs[13] = !0;
            }
        }
        #[cfg(target_arch = "aarch64")]
        {
            (*ctx_ptr).regs.gprs[12] = stack_top as u64;
            (*ctx_ptr).regs.gprs[11] = crate::api::fiber_entry_point as *const () as u64;
            #[cfg(windows)]
            {
                let limit = (ctx_ptr as usize).saturating_sub(pool.slot_size);
                (*ctx_ptr).regs.gprs[13] = ctx_ptr as u64;
                (*ctx_ptr).regs.gprs[14] = limit as u64;
                (*ctx_ptr).regs.gprs[15] = limit as u64;
            }
        }
        #[cfg(target_arch = "riscv64")]
        {
            (*ctx_ptr).regs.gprs[0] = stack_top as u64;
            (*ctx_ptr).regs.gprs[13] = crate::api::fiber_entry_point as *const () as u64;
        }
        (*ctx_ptr).cleanup_fn = None;
    }

    let r#gen = u64::from(unsafe {
        (*ctx_ptr)
            .generation
            .load(core::sync::atomic::Ordering::Acquire)
    });
    crate::wake_fiber(current_core, ctx_id);

    dtact_handle_t(
        u64::from(ctx_id) | ((current_core as u64) << 32) | ((r#gen & 0x7FFF) << 48) | (1 << 63),
    )
}

/// Launches a C-function as a DTA-V3 stackful Fiber with an ownership cleanup callback.
///
/// # Safety
/// * `func` and `cleanup` must be valid function pointers.
/// * `cleanup` will be called with `arg` once the fiber has finished execution.
///
/// # Panics
/// * Panics if the runtime is not initialized.
/// * Panics if the context pool is exhausted.
#[unsafe(no_mangle)]
#[allow(clippy::cast_possible_truncation)]
pub unsafe extern "C" fn dtact_fiber_launch_with_cleanup(
    func: extern "C" fn(*mut c_void),
    arg: *mut c_void,
    cleanup: unsafe extern "C" fn(*mut c_void),
) -> dtact_handle_t {
    let runtime = crate::GLOBAL_RUNTIME
        .get()
        .expect("Dtact Runtime not initialized");
    let pool = &runtime.pool;
    let ctx_id = pool.alloc_context().expect("Context pool exhausted - OOM");

    let ctx_ptr = pool.get_context_ptr(ctx_id);
    #[allow(clippy::cast_possible_truncation)]
    let current_core = crate::api::topology::current().core_id as usize;

    unsafe {
        (*ctx_ptr).state.store(
            crate::memory_management::FiberStatus::Running as u32,
            core::sync::atomic::Ordering::Release,
        );
        (*ctx_ptr).origin_core = current_core as u16;
        (*ctx_ptr).fiber_index = ctx_id;
        (*ctx_ptr).switch_fn = crate::context_switch::switch_context_cross_thread_float;

        (*ctx_ptr).closure_ptr = arg.cast::<()>();
        (*ctx_ptr).trampoline =
            core::mem::transmute::<extern "C" fn(*mut c_void), unsafe extern "C" fn()>(func);
        (*ctx_ptr).cleanup_fn = Some(core::mem::transmute::<
            unsafe extern "C" fn(*mut c_void),
            unsafe extern "C" fn(*mut ()),
        >(cleanup));

        // Unified Trampoline for C-Functions
        (*ctx_ptr).invoke_closure = |ptr| {
            let ctx_ptr = crate::future_bridge::CURRENT_FIBER.with(std::cell::Cell::get);
            if let Some(ctx) = unsafe { ctx_ptr.as_ref() } {
                let f: extern "C" fn(*mut c_void) = unsafe {
                    core::mem::transmute::<unsafe extern "C" fn(), extern "C" fn(*mut c_void)>(
                        ctx.trampoline,
                    )
                };
                f(ptr.cast::<c_void>());
            }
        };

        // ABI-Compliant Stack Alignment & Poisoning
        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        let stack_top = (ctx_ptr as usize & !0xF) - 72;
        #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
        let stack_top = (ctx_ptr as usize & !0xF) - 80;

        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        let stack_top_ptr = stack_top as *mut u64;
        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        core::ptr::write(stack_top_ptr, dtact_abort as *const () as u64);

        let stack_top = stack_top as *mut u8;

        #[cfg(target_arch = "x86_64")]
        {
            (*ctx_ptr).regs.gprs[0] = stack_top as u64; // RSP
            (*ctx_ptr).regs.gprs[7] = crate::api::fiber_entry_point as *const () as u64; // RIP
            #[cfg(windows)]
            {
                let limit = (ctx_ptr as usize).saturating_sub(pool.slot_size);
                (*ctx_ptr).regs.gprs[10] = ctx_ptr as u64; // Stack Base
                (*ctx_ptr).regs.gprs[11] = limit as u64; // Stack Limit
                (*ctx_ptr).regs.gprs[12] = limit as u64; // DeallocationStack
                (*ctx_ptr).regs.gprs[13] = !0; // ExceptionList
            }
        }
        #[cfg(target_arch = "aarch64")]
        {
            (*ctx_ptr).regs.gprs[12] = stack_top as u64; // SP
            (*ctx_ptr).regs.gprs[11] = crate::api::fiber_entry_point as *const () as u64; // x30 (LR)
            #[cfg(windows)]
            {
                let limit = (ctx_ptr as usize).saturating_sub(pool.slot_size);
                (*ctx_ptr).regs.gprs[13] = ctx_ptr as u64; // Stack Base
                (*ctx_ptr).regs.gprs[14] = limit as u64; // Stack Limit
                (*ctx_ptr).regs.gprs[15] = limit as u64; // DeallocationStack
            }
        }
        #[cfg(target_arch = "riscv64")]
        {
            (*ctx_ptr).regs.gprs[0] = stack_top as u64; // SP
            (*ctx_ptr).regs.gprs[13] = crate::api::fiber_entry_point as *const () as u64; // RA
        }
    }

    let r#gen = u64::from(unsafe {
        (*ctx_ptr)
            .generation
            .load(core::sync::atomic::Ordering::Acquire)
    });

    crate::wake_fiber(current_core, ctx_id);
    dtact_handle_t(
        u64::from(ctx_id) | ((current_core as u64) << 32) | ((r#gen & 0x7FFF) << 48) | (1 << 63),
    )
}

/// Launches a C-function as a DTA-V3 stackful Fiber with an ownership cleanup callback and options.
#[unsafe(no_mangle)]
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::too_many_lines)]
pub unsafe extern "C" fn dtact_fiber_launch_with_cleanup_ext(
    func: extern "C" fn(*mut c_void),
    arg: *mut c_void,
    cleanup: unsafe extern "C" fn(*mut c_void),
    options: *const dtact_spawn_options_t,
) -> dtact_handle_t {
    let runtime = crate::GLOBAL_RUNTIME
        .get()
        .expect("Dtact Runtime not initialized");
    let pool = &runtime.pool;
    let ctx_id = pool.alloc_context().expect("Context pool exhausted - OOM");

    let ctx_ptr = pool.get_context_ptr(ctx_id);
    let current_core = crate::api::topology::current().core_id as usize;

    let opts = if options.is_null() {
        dtact_default_spawn_options()
    } else {
        unsafe { *options }
    };

    unsafe {
        (*ctx_ptr).state.store(
            crate::memory_management::FiberStatus::Running as u32,
            core::sync::atomic::Ordering::Release,
        );
        (*ctx_ptr).origin_core = current_core as u16;
        (*ctx_ptr).fiber_index = ctx_id;

        (*ctx_ptr).switch_fn = match opts.switcher {
            1 => crate::context_switch::switch_context_cross_thread_no_float,
            2 => crate::context_switch::switch_context_same_thread_float,
            3 => crate::context_switch::switch_context_same_thread_no_float,
            _ => crate::context_switch::switch_context_cross_thread_float,
        };

        (*ctx_ptr).kind = match opts.kind {
            1 => crate::common_types::WorkloadKind::IO,
            2 => crate::common_types::WorkloadKind::Memory,
            3 => crate::common_types::WorkloadKind::System,
            _ => crate::common_types::WorkloadKind::Compute,
        };

        (*ctx_ptr).adaptive_spin_count = match (*ctx_ptr).kind {
            crate::common_types::WorkloadKind::Compute => 1000,
            crate::common_types::WorkloadKind::IO => 100,
            crate::common_types::WorkloadKind::Memory => 500,
            crate::common_types::WorkloadKind::System => 200,
        };

        (*ctx_ptr).closure_ptr = arg.cast::<()>();
        (*ctx_ptr).trampoline =
            core::mem::transmute::<extern "C" fn(*mut c_void), unsafe extern "C" fn()>(func);
        (*ctx_ptr).cleanup_fn = Some(core::mem::transmute::<
            unsafe extern "C" fn(*mut c_void),
            unsafe extern "C" fn(*mut ()),
        >(cleanup));

        (*ctx_ptr).invoke_closure = |ptr| {
            let ctx_ptr = crate::future_bridge::CURRENT_FIBER.with(std::cell::Cell::get);
            if let Some(ctx) = unsafe { ctx_ptr.as_ref() } {
                let f: extern "C" fn(*mut c_void) = unsafe {
                    core::mem::transmute::<unsafe extern "C" fn(), extern "C" fn(*mut c_void)>(
                        ctx.trampoline,
                    )
                };
                f(ptr.cast::<c_void>());
            }
        };

        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        let stack_top = (ctx_ptr as usize & !0xF) - 72;
        #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
        let stack_top = (ctx_ptr as usize & !0xF) - 80;

        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        let stack_top_ptr = stack_top as *mut u64;
        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        core::ptr::write(stack_top_ptr, dtact_abort as *const () as u64);
        let stack_top = stack_top as *mut u8;

        #[cfg(target_arch = "x86_64")]
        {
            (*ctx_ptr).regs.gprs[0] = stack_top as u64;
            (*ctx_ptr).regs.gprs[7] = crate::api::fiber_entry_point as *const () as u64;
            #[cfg(windows)]
            {
                let limit = (ctx_ptr as usize).saturating_sub(pool.slot_size);
                (*ctx_ptr).regs.gprs[10] = ctx_ptr as u64;
                (*ctx_ptr).regs.gprs[11] = limit as u64;
                (*ctx_ptr).regs.gprs[12] = limit as u64;
                (*ctx_ptr).regs.gprs[13] = !0;
            }
        }
        #[cfg(target_arch = "aarch64")]
        {
            (*ctx_ptr).regs.gprs[12] = stack_top as u64;
            (*ctx_ptr).regs.gprs[11] = crate::api::fiber_entry_point as *const () as u64;
            #[cfg(windows)]
            {
                let limit = (ctx_ptr as usize).saturating_sub(pool.slot_size);
                (*ctx_ptr).regs.gprs[13] = ctx_ptr as u64;
                (*ctx_ptr).regs.gprs[14] = limit as u64;
                (*ctx_ptr).regs.gprs[15] = limit as u64;
            }
        }
        #[cfg(target_arch = "riscv64")]
        {
            (*ctx_ptr).regs.gprs[0] = stack_top as u64;
            (*ctx_ptr).regs.gprs[13] = crate::api::fiber_entry_point as *const () as u64;
        }
    }

    let r#gen = u64::from(unsafe {
        (*ctx_ptr)
            .generation
            .load(core::sync::atomic::Ordering::Acquire)
    });
    crate::wake_fiber(current_core, ctx_id);

    dtact_handle_t(
        u64::from(ctx_id) | ((current_core as u64) << 32) | ((r#gen & 0x7FFF) << 48) | (1 << 63),
    )
}

/// Blocks the current thread until the specified fiber terminates.
///
/// If called from a Dtact fiber, this will natively yield the physical core.
/// If called from a non-managed thread (e.g., C main), this uses a tiered
/// spin-loop and futex-wait strategy for zero-CPU idling.
///
/// # Panics
/// * Panics if the runtime is not initialized.
#[unsafe(no_mangle)]
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::too_many_lines)]
pub extern "C" fn dtact_await(handle: dtact_handle_t) {
    let handle_val = handle.0 & !(1 << 63); // Strip sentinel bit
    let target_ctx_id = (handle_val & 0xFFFF_FFFF) as u32;
    let handle_gen = ((handle_val >> 48) & 0x7FFF) as u16; // Mask out sentinel bit
    let runtime = crate::GLOBAL_RUNTIME
        .get()
        .expect("Runtime not initialized");
    let pool = &runtime.pool;
    let target_ctx = pool.get_context_ptr(target_ctx_id);

    let ctx_ptr = crate::future_bridge::CURRENT_FIBER.with(std::cell::Cell::get);

    if ctx_ptr.is_null() {
        // ===== NON-FIBER PATH (C main thread, host thread) =====
        // Tiered strategy: spin-loop -> futex_wait
        let mut spins = 0u32;
        loop {
            let (_current_gen, status) = unsafe {
                let g1 = (*target_ctx)
                    .generation
                    .load(core::sync::atomic::Ordering::Acquire) as u16;
                // On AArch64, we need a fence to ensure 'generation' and 'state' loads are not reordered.
                #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
                core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);
                let status = (*target_ctx)
                    .state
                    .load(core::sync::atomic::Ordering::Acquire);
                #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
                core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);
                let g2 = (*target_ctx)
                    .generation
                    .load(core::sync::atomic::Ordering::Acquire) as u16;

                // If generation changed during our read, or it's already a different generation,
                // we know the target fiber has finished.
                if (g1 & 0x7FFF) != handle_gen || (g2 & 0x7FFF) != handle_gen {
                    break;
                }
                (g1 & 0x7FFF, status)
            };

            if status == crate::memory_management::FiberStatus::Finished as u32 {
                break;
            }

            if spins < 1000 {
                core::hint::spin_loop();
                spins += 1;
            } else {
                // To prevent ABA-induced permanent deadlocks (where the context is recycled
                // and state returns to 'Running' before we enter the futex), we use yield_now
                // as a robust fallback. This ensures the host thread eventually re-checks
                // the generation counter.
                std::thread::yield_now();
                spins = 500; // Reset to a middle-tier spin before next yield
            }
        }
        return;
    }

    // ===== FIBER PATH (called from within a running fiber) =====
    loop {
        // Ensure we are in Running state before checking target.
        // We use swap to safely clear any Notified state from a previous wake event.
        unsafe {
            (*ctx_ptr).state.swap(
                crate::memory_management::FiberStatus::Running as u32,
                core::sync::atomic::Ordering::AcqRel,
            );
        }

        // 0. Check target state and generation
        let (current_gen, status) = unsafe {
            (
                ((*target_ctx)
                    .generation
                    .load(core::sync::atomic::Ordering::Acquire) as u16)
                    & 0x7FFF,
                (*target_ctx)
                    .state
                    .load(core::sync::atomic::Ordering::Acquire),
            )
        };

        if current_gen != handle_gen
            || status == crate::memory_management::FiberStatus::Finished as u32
        {
            // Target already finished (or context recycled), clear waiter and break
            unsafe {
                (*target_ctx)
                    .waiter_handle
                    .store(0, core::sync::atomic::Ordering::Relaxed);
            }
            break;
        }

        // 1. Register the current fiber as a waiter for the target fiber
        let current_worker = crate::future_bridge::CURRENT_WORKER_ID.with(std::cell::Cell::get);
        let current_ctx_id = unsafe { u64::from((*ctx_ptr).fiber_index) };
        let my_handle = current_ctx_id | ((current_worker as u64) << 32) | (1 << 63);

        // Register the current fiber as a waiter for the target fiber.
        // We use swap(SeqCst) as a full memory barrier to ensure visibility before state re-check.
        // On x86, this is implemented as LOCK XCHG which is more efficient than store + mfence.
        unsafe {
            (*target_ctx)
                .waiter_handle
                .swap(my_handle, core::sync::atomic::Ordering::SeqCst);
        }

        // 2. Double-check target state after registering waiter
        let (current_gen_post, status_post) = unsafe {
            (
                ((*target_ctx)
                    .generation
                    .load(core::sync::atomic::Ordering::Acquire) as u16)
                    & 0x7FFF,
                (*target_ctx)
                    .state
                    .load(core::sync::atomic::Ordering::Acquire),
            )
        };

        if current_gen_post != handle_gen
            || status_post == crate::memory_management::FiberStatus::Finished as u32
        {
            // Completed between check and waiter registration
            unsafe {
                (*target_ctx)
                    .waiter_handle
                    .store(0, core::sync::atomic::Ordering::Relaxed);
            }
            break;
        }

        // 3. Try to transition to Suspending and suspend
        unsafe {
            let ctx = &mut *ctx_ptr;
            if ctx
                .state
                .compare_exchange(
                    crate::memory_management::FiberStatus::Running as u32,
                    crate::memory_management::FiberStatus::Suspending as u32,
                    core::sync::atomic::Ordering::Release,
                    core::sync::atomic::Ordering::Acquire,
                )
                .is_ok()
            {
                (ctx.switch_fn)(&raw mut ctx.regs, &raw const ctx.executor_regs);
            }
        }
    }
}

/// Signals all worker threads to shutdown and waits for them to terminate.
/// This call blocks until all hardware worker threads have exited.
///
/// # Panics
/// * Panics if the runtime is not initialized.
#[unsafe(no_mangle)]
pub extern "C" fn dtact_run(_rt: *mut c_void) {
    let runtime = crate::GLOBAL_RUNTIME
        .get()
        .expect("Dtact Runtime not initialized");
    let scheduler = &runtime.scheduler;
    let workers_count = scheduler.workers.len();
    let mut handles = alloc::vec::Vec::with_capacity(workers_count);

    for i in 0..workers_count {
        let handle = std::thread::spawn(move || {
            if let Some(runtime) = crate::GLOBAL_RUNTIME.get() {
                crate::dta_scheduler::DtaScheduler::run_worker_static(
                    &runtime.scheduler,
                    i,
                    &runtime.pool,
                    &runtime.shutdown,
                );
            }
        });
        handles.push(handle);
    }

    for h in handles {
        let _ = h.join();
    }
}

/// Signals the cooperative shutdown of all Dtact worker threads.
#[unsafe(no_mangle)]
pub extern "C" fn dtact_shutdown() {
    if let Some(runtime) = crate::GLOBAL_RUNTIME.get() {
        runtime
            .shutdown
            .store(true, core::sync::atomic::Ordering::SeqCst);

        // Wake all workers to ensure they see the shutdown signal
        for i in 0..runtime.scheduler.workers.len() {
            unsafe {
                let worker = &*runtime.scheduler.workers[i].get();
                worker
                    .event_signal
                    .fetch_add(1, core::sync::atomic::Ordering::SeqCst);
                crate::utils::futex_wake(
                    (&raw const worker.event_signal).cast::<core::sync::atomic::AtomicU32>(),
                );
            }
        }
    }
}