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
// SPDX-License-Identifier: Apache-2.0
//! Goroutine (`G`) and register save area (`Gobuf`) — ported from
//! `runtime/runtime2.go`.
//!
//! Steps 2 and 5 of the porting plan are implemented here together because
//! `G` embeds `Gobuf` directly and they cannot be compiled in isolation.
use Cell;
use ;
use M;
// ---------------------------------------------------------------------------
// Goroutine status — atomicstatus values from runtime/runtime2.go
// ---------------------------------------------------------------------------
/// G was just allocated and has not yet been initialized.
pub const GIDLE: u32 = 0;
/// G is on a run queue, waiting to be scheduled.
pub const GRUNNABLE: u32 = 1;
/// G is currently executing on an M.
pub const GRUNNING: u32 = 2;
/// G is blocked in a system call.
pub const GSYSCALL: u32 = 3;
/// G is parked — blocked on a channel op, mutex, or timer.
pub const GWAITING: u32 = 4;
/// G exited; its stack may be reused.
pub const GDEAD: u32 = 6;
/// G is mid stack-copy (v1: unused — fixed stacks only).
pub const GCOPYSTACK: u32 = 8;
/// G was preempted at an async safe point (v1: unused — cooperative only).
pub const GPREEMPTED: u32 = 9;
/// OR'd with a base status while the GC is scanning the stack (v1: no GC).
pub const GSCAN: u32 = 0x1000;
// ---------------------------------------------------------------------------
// Stack constants — from runtime/stack.go
// ---------------------------------------------------------------------------
/// Sentinel value for `G.stackguard0` that triggers cooperative preemption.
/// Matches Go's `stackPreempt = uintptr(-1300)` in spirit; using `usize::MAX`
/// as a conservative sentinel that is never a valid stack address.
pub const STACK_PREEMPT: usize = usizeMAX;
/// Guard offset from `Stack.lo` placed into `stackguard0` at goroutine start.
/// Equals Go's `stackGuard` for non-Windows 64-bit:
/// `stackNosplit (800) + stackSystem (0) + StackGuardExtraSize (128) = 928`.
/// Revisit when stack growth is ported (step 4).
pub const STACK_GUARD: usize = 928;
// ---------------------------------------------------------------------------
// Stack — goroutine stack bounds
// ---------------------------------------------------------------------------
/// A goroutine's stack bounds. The live region is `[lo, hi)`.
///
/// `#[repr(C)]` because this struct sits at offset 0 of `G` and the assembly
/// (step 3) may need a stable layout if `G` itself becomes `#[repr(C)]`.
pub
// ---------------------------------------------------------------------------
// Gobuf — register save area
// ---------------------------------------------------------------------------
/// Saved register state for a goroutine that is not currently on-CPU.
///
/// `#[repr(C)]` is **mandatory**: `asm_arm64.rs` and `asm_amd64.rs` (step 3)
/// address each field by its byte offset using the `GOBUF_*_OFFSET` constants
/// below. Any change to field order or type **must** update those constants;
/// the compile-time assertions immediately following this struct will catch
/// any mismatch.
///
/// ## Callee-saved register storage
///
/// `mcall` is called by Rust functions that follow the platform calling
/// convention. Those callers expect callee-saved registers (RBX, R12–R15
/// on System V AMD64; RBX, RBP, RDI, RSI, R12–R15, XMM6–15 on Microsoft x64;
/// x19–x28 + d8–d15 on AArch64) to be preserved across the call.
///
/// `mcall_asm` switches the goroutine off the CPU, runs the scheduler, and
/// later — possibly long after, on the same or different M — `gogo_asm`
/// resumes the goroutine at the instruction *immediately after* `call
/// mcall_asm`. Between save and restore the scheduler clobbers every
/// callee-saved register. We therefore save them to `Gobuf` on the way out
/// and restore them on the way in. Without this, a Rust function that
/// holds a live value in (say) RBX across a `gosched()` or channel-blocking
/// `recv()` resumes with garbage in RBX — corrupting any subsequent use
/// (typically: assertion failures, malloc-state corruption, SIGILL, or
/// SIGSEGV with no obvious cause).
///
/// The `regs[..]` array is at the **end** of the struct so the original
/// `GOBUF_*_OFFSET` constants remain stable — no asm offset needs to change.
///
/// Ported from `gobuf` in `runtime/runtime2.go`.
///
/// ## AArch64 layout = main-branch identical
///
/// The `regs` field below is **only added on x86_64**. An earlier attempt to
/// add it for AArch64 too (with matching x19–x28 save/restore in
/// `asm_arm64.rs`) caused the macOS-latest CI runner to hang in
/// `many_goroutines` — root cause not pinpointed. Keeping AArch64 100 %
/// bit-identical to `main` for now; the x86_64 callee-saved fix proceeds.
pub
/// Number of callee-saved GPR slots in [`Gobuf::regs`].
///
/// - System V AMD64: 5 (RBX, R12, R13, R14, R15)
/// - Microsoft x64: 7 (RBX, RDI, RSI, R12, R13, R14, R15)
///
/// Not defined for AArch64 — `Gobuf` on AArch64 has no `regs` field, leaving
/// the struct bit-identical to `main`.
///
/// (Microsoft x64 callee-saved XMM6–15 are not currently saved; goroutine
/// code on Windows that holds vector state across `mcall` may still corrupt.
/// See `mcall_asm` for the open follow-up.)
pub const CALLEE_SAVED_GPR_COUNT: usize = 5;
pub const CALLEE_SAVED_GPR_COUNT: usize = 7;
// Byte offsets into `Gobuf` on a 64-bit target, derived from the
// `#[repr(C)]` layout. Used as immediate constants in `global_asm!` (step 3)
// where Rust `const` values cannot be referenced directly.
pub const GOBUF_SP_OFFSET: usize = 0;
pub const GOBUF_PC_OFFSET: usize = 8;
pub const GOBUF_G_OFFSET: usize = 16;
pub const GOBUF_CTXT_OFFSET: usize = 24;
pub const GOBUF_RET_OFFSET: usize = 32;
pub const GOBUF_LR_OFFSET: usize = 40;
pub const GOBUF_BP_OFFSET: usize = 48;
/// Byte offset of `Gobuf::regs[0]` — the first callee-saved GPR slot.
/// Subsequent slots are at `GOBUF_REGS_OFFSET + i*8`. x86_64 only.
pub const GOBUF_REGS_OFFSET: usize = 56;
// Compile-time verification that the constants match the actual repr(C) layout.
const _: = ;
const _: = ;
// SAFETY: `Gobuf` is passed between threads when the scheduler migrates a G.
// Exactly one M runs a given G at any time, providing the mutual exclusion
// that makes cross-thread pointer passing sound.
unsafe
unsafe
// ---------------------------------------------------------------------------
// WaitReason — why a G is in GWAITING state
// ---------------------------------------------------------------------------
/// The reason a goroutine is parked in `GWAITING`.
///
/// Subset of `waitReason` from `runtime/runtime2.go`; only values relevant
/// to channels, select, mutexes, and timers are included. GC wait reasons
/// are omitted.
pub
// ---------------------------------------------------------------------------
// G — goroutine
// ---------------------------------------------------------------------------
/// A goroutine — the fundamental unit of concurrency.
///
/// Ported from `g` in `runtime/runtime2.go`. This is a strict subset of
/// Go's version; GC, defer, panic, and tracer fields are omitted.
///
/// A `G` is always heap-allocated via `G::new` so the scheduler can hold
/// stable `*mut G` raw pointers across thread migrations. The goroutine's
/// execution stack is a separate `mmap`'d region tracked by `G.stack`; the
/// `G` struct itself lives on the Rust heap.
///
/// ## Memory layout (64-bit, `#[repr(C)]`)
///
/// ```text
/// offset field size
/// ────── ─────────────── ────
/// 0 stack.lo 8 B ← G_STACK_LO_OFFSET (Windows asm)
/// 8 stack.hi 8 B ← G_STACK_HI_OFFSET (Windows asm)
/// 16 stackguard0 8 B
/// 24 m 8 B
/// 32 sched (Gobuf) 56 B 7 fields × 8 B
/// 88 atomicstatus 4 B } packed together — same AtomicU32
/// 92 selectdone 4 B } alignment, no padding between them
/// 96 goid 8 B
/// 104 schedlink 8 B
/// 112 param 8 B
/// 120 waitreason 1 B } packed together — same 1-byte alignment
/// 121 preempt 1 B }
/// 122 [6 B padding] align struct to 8 B
/// ────── ─────────────── ────
/// 128 B total
/// ```
///
/// This is intentionally smaller than Go's `g` struct (~480 B) because we
/// omit GC, defer/panic chain, and tracer fields. Go's published minimum
/// goroutine overhead includes a 2 KiB stack and roughly 392 B of descriptor
/// overhead; our descriptor is 128 B.
///
/// ## Per-goroutine memory (release builds)
///
/// | Platform | Stack | OS guard page | G struct | Total |
/// |---------------|--------|---------------|----------|---------|
/// | Linux x86-64 | 2 KiB | 4 KiB | 128 B | ~6.1 KiB |
/// | Linux AArch64 | 2 KiB | 4 KiB | 128 B | ~6.1 KiB |
/// | macOS x86-64 | 2 KiB | 4 KiB | 128 B | ~6.1 KiB |
/// | macOS AArch64 | 2 KiB | 16 KiB | 128 B | ~18 KiB |
/// | Windows x86-64| 2 KiB | 4 KiB (VEH) | 128 B | ~6.1 KiB |
///
/// The OS guard page accounts for the remaining gap vs. Go's ~2.4 KiB.
/// Eliminating it would require compiler-generated `morestack` checks in
/// every Rust function (not feasible without compiler changes); without them
/// severe stack overflows would silently corrupt adjacent memory rather than
/// crashing cleanly.
///
/// Byte offset of `G.stack.lo` within the G struct. Used by Windows
/// `mcall_asm` to restore TEB StackLimit after switching to g0.
/// `#[repr(C)]` on G guarantees this equals 0.
// Used in `#[cfg(windows)]` inline asm — suppressed on non-Windows.
pub const G_STACK_LO_OFFSET: usize = 0;
/// Byte offset of `G.stack.hi` within the G struct. Used by Windows
/// `mcall_asm` to restore TEB StackBase after switching to g0.
/// `#[repr(C)]` on G guarantees this equals `size_of::<usize>()` = 8.
// Used in `#[cfg(windows)]` inline asm — suppressed on non-Windows.
pub const G_STACK_HI_OFFSET: usize = 8;
// Compile-time verification of G struct layout.
const _: = ;
pub
// SAFETY: The scheduler guarantees at most one M executes a given G at any
// time. That mutual exclusion makes it sound to pass `*mut G` across the
// thread boundary when the scheduler migrates a goroutine.
unsafe
unsafe
// ---------------------------------------------------------------------------
// Per-thread context — current G and g0 Gobuf pointers
// ---------------------------------------------------------------------------
thread_local!
/// Return the goroutine currently running on this OS thread, or `null` on g0.
pub
/// Record `g` as the goroutine running on this OS thread.
/// Called by `gogo` immediately before every context switch.
///
/// # Safety
/// `g` must point to a live, heap-allocated `G` whose ownership has been
/// transferred to the current OS thread by the scheduler.
pub unsafe
/// Record `buf` as g0's `Gobuf` for this OS thread.
/// Called once from `M::new` (step 6) during M initialisation.
///
/// # Safety
/// `buf` must point to the `sched` field of a live g0 `G` that is pinned
/// to this OS thread for its lifetime.
pub unsafe
/// Return g0's `Gobuf` for this OS thread.
/// Returns `null` before `M::new` has been called.
///
/// Called by `systemstack` in `asm_amd64.rs` / `asm_arm64.rs` to locate g0's
/// saved stack pointer before switching to g0's stack.
// used by systemstack (no callers of systemstack yet)
pub
// ---------------------------------------------------------------------------
// Goroutine state-transition helpers — ported from runtime/proc.go
// ---------------------------------------------------------------------------
/// Validate that `from → to` is a legal goroutine status transition.
///
/// GSCAN bits are stripped before the lookup so every scan-combined state
/// (e.g. `GSCAN | GWAITING`) automatically satisfies the table.
/// Atomically transition `gp` from `old_val` to `new_val`.
///
/// Spins while the G holds any `GSCAN` bit — matches Go's `casgstatus` loop
/// that yields to a concurrent GC stack scan before retrying the CAS.
///
/// # Panics (debug)
/// Panics if `old_val → new_val` is not in the valid-transition table.
///
/// # Safety
/// `gp` must point to a live, heap-allocated `G`.
///
/// Ported from `casgstatus` in `runtime/proc.go`.
pub unsafe
/// Transition `gp` from `base_status` to `GSCAN | base_status`.
///
/// Used by the GC to "freeze" a goroutine's stack status while scanning.
/// The goroutine must NOT be modified while the GSCAN bit is held.
///
/// Ported from `castogscanstatus` in `runtime/proc.go`.
// called by scan_stack; GC callers pending
pub unsafe
/// Transition `gp` from `scan_status` (`GSCAN | x`) back to `new_val`.
///
/// Releases the GSCAN freeze after stack scanning is complete.
///
/// Ported from `casfrom_gscanstatus` in `runtime/proc.go`.
// called by scan_stack; GC callers pending
pub unsafe
/// Read the goroutine's current status, stripping any `GSCAN` bit.
///
/// Ported from `readgstatus` in `runtime/proc.go`.
pub unsafe
/// Temporarily freeze `gp`'s stack status for GC stack scanning, invoke
/// `scanner`, then release the freeze.
///
/// Currently a no-op (no garbage collector is implemented); provides the
/// state-machine infrastructure so a future GC can integrate without
/// changing call sites.
///
/// Ported from `scanstack` in `runtime/mgcmark.go`.
// exercises GSCAN state machine; GC callers pending
pub unsafe
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------