-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintegration_linux_test.go
More file actions
3237 lines (2812 loc) · 89.5 KB
/
integration_linux_test.go
File metadata and controls
3237 lines (2812 loc) · 89.5 KB
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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ©Hayabusa Cloud Co., Ltd. 2026. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
//go:build linux
package uring_test
import (
"errors"
"fmt"
"net"
"os"
"path/filepath"
"sync"
"sync/atomic"
"testing"
"time"
"unsafe"
"code.hybscloud.com/iox"
"code.hybscloud.com/sock"
"code.hybscloud.com/uring"
"code.hybscloud.com/zcall"
)
func logRingDiagnostics(t *testing.T, label string, ring *uring.Uring) {
t.Helper()
t.Logf("%s: ringFD=%d sqEntries=%d cqEntries=%d sqeBytes=%d sqAvailable=%d cqPending=%d notifySucceed=%t multiIssuers=%t",
label,
ring.RingFD(),
ring.Features.SQEntries,
ring.Features.CQEntries,
ring.Features.SQEBytes,
ring.SQAvailable(),
ring.CQPending(),
ring.NotifySucceed,
ring.MultiIssuers,
)
info, err := ring.QueryOpcodes()
if err != nil {
t.Logf("%s: QueryOpcodes unavailable: %v", label, err)
return
}
t.Logf("%s: query ringSetupFlags=0x%x featureFlags=0x%x registerOps=%d requestOps=%d",
label,
info.RingSetupFlags,
info.FeatureFlags,
info.NrRegisterOpcodes,
info.NrRequestOpcodes,
)
}
func skipIfXattrUnsupported(t *testing.T, op string, res int32) {
t.Helper()
if res == -int32(zcall.ENOTSUP) || res == -int32(zcall.EOPNOTSUPP) {
t.Skipf("%s not supported on this filesystem: res=%d", op, res)
}
}
// =============================================================================
// Integration Tests: Complete submit->wait->complete cycles
// =============================================================================
func TestUringNopCycle(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions)
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
// Note: Uring doesn't have a Destroy method; OS reclaims resources on exit
ctx := uring.PackDirect(uring.IORING_OP_NOP, 0, 0, 0)
if err := ring.Nop(ctx); err != nil {
t.Fatalf("Nop: %v", err)
}
ev, ok := waitForOp(t, ring, uring.IORING_OP_NOP, time.Second)
if !ok {
t.Fatal("NOP operation did not complete")
}
if ev.Res < 0 {
t.Errorf("NOP failed with result: %d", ev.Res)
}
}
func TestUringIntrospection(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions)
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
// Initially, SQ should be fully available
initial := ring.SQAvailable()
if initial != ring.Features.SQEntries {
t.Errorf("SQAvailable: got %d, want %d", initial, ring.Features.SQEntries)
}
// CQ should be empty
if pending := ring.CQPending(); pending != 0 {
t.Errorf("CQPending: got %d, want 0", pending)
}
// Submit some NOPs
const numOps = 10
for i := range numOps {
ctx := uring.PackDirect(uring.IORING_OP_NOP, 0, uint16(i), 0)
if err := ring.Nop(ctx); err != nil {
t.Fatalf("Nop[%d]: %v", i, err)
}
}
// SQAvailable should decrease
afterSubmit := ring.SQAvailable()
if afterSubmit >= initial {
t.Errorf("SQAvailable should decrease after submit: before=%d, after=%d", initial, afterSubmit)
}
// Wait for completions and verify CQPending changes
cqes := make([]uring.CQEView, 16)
deadline := time.Now().Add(time.Second)
completed := 0
b := iox.Backoff{}
for completed < numOps && time.Now().Before(deadline) {
n, err := ring.Wait(cqes)
if err != nil && !errors.Is(err, iox.ErrWouldBlock) {
t.Fatalf("Wait: %v", err)
}
completed += n
b.Wait()
}
if completed != numOps {
t.Errorf("completed: got %d, want %d", completed, numOps)
}
t.Logf("SQAvailable: initial=%d, afterSubmit=%d, final=%d", initial, afterSubmit, ring.SQAvailable())
t.Logf("Completed %d operations", completed)
}
func TestUringTimeoutCycle(t *testing.T) {
// Skip under race detection - io_uring timeout completions are unreliable
// in WSL2 when race detector overhead is present. The kernel delivers the
// timeout CQE but the polling loop may miss it due to timing changes.
if raceEnabled {
t.Skip("skipping: io_uring timeout unreliable with race detector in WSL2")
}
ring, err := uring.New(testMinimalBufferOptions, func(opt *uring.Options) {
opt.NotifySucceed = true // Request a CQE for every successful operation.
opt.MultiIssuers = true // Exercise the shared-submit configuration.
})
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
ctx := uring.PackDirect(uring.IORING_OP_TIMEOUT, 0, 0, 0)
start := time.Now()
if err := ring.Timeout(ctx, 20*time.Millisecond); err != nil {
t.Fatalf("Timeout: %v", err)
}
ev, ok := waitForOp(t, ring, uring.IORING_OP_TIMEOUT, time.Second)
if !ok {
t.Fatal("Timeout operation did not complete")
}
elapsed := time.Since(start)
if elapsed < 15*time.Millisecond {
t.Errorf("Timeout completed too fast: %v", elapsed)
}
_ = ev
}
// TestTimeoutUpdate validates the IORING_TIMEOUT_UPDATE flag.
// Timeout update allows modifying an existing timeout's expiration in-place.
func TestTimeoutUpdate(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions)
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
const targetUserData = uint16(42)
// Submit a long timeout (60s) that we'll update to be shorter
timeoutCtx := uring.PackDirect(uring.IORING_OP_TIMEOUT, 0, targetUserData, 0)
if err := ring.Timeout(timeoutCtx, 60*time.Second); err != nil {
t.Fatalf("Timeout: %v", err)
}
t.Log("Submitted 60s timeout with userData=42")
// Update the timeout to 10ms
updateCtx := uring.PackDirect(uring.IORING_OP_TIMEOUT_REMOVE, 0, 1, 0)
if err := ring.TimeoutUpdate(updateCtx, timeoutCtx.Raw(), 10*time.Millisecond, false); err != nil {
t.Fatalf("TimeoutUpdate: %v", err)
}
t.Log("Submitted TimeoutUpdate to change to 10ms")
// Collect CQEs - should get update result and eventually the timeout
cqes := make([]uring.CQEView, 8)
start := time.Now()
updateFound := false
for i := 0; i < 10; i++ {
n, _ := ring.Wait(cqes)
for j := 0; j < n; j++ {
op := cqes[j].Op()
res := cqes[j].Res
t.Logf("CQE: op=%d res=%d", op, res)
if op == uring.IORING_OP_TIMEOUT_REMOVE {
if res == 0 {
updateFound = true
t.Log("TimeoutUpdate succeeded")
} else if res < 0 {
const ENOENT = 2
if -res == ENOENT {
t.Log("Timeout already expired or not found")
} else {
t.Logf("TimeoutUpdate error: %d", res)
}
}
}
}
if updateFound {
break
}
time.Sleep(5 * time.Millisecond)
}
elapsed := time.Since(start)
t.Logf("Elapsed: %v", elapsed)
// Verify the API signature works
t.Run("APISignature", func(t *testing.T) {
ctx := uring.PackDirect(uring.IORING_OP_TIMEOUT_REMOVE, 0, 1, 0)
// Test both relative and absolute modes
_ = ring.TimeoutUpdate(ctx, 0, time.Second, false) // relative
_ = ring.TimeoutUpdate(ctx, 0, time.Second, true) // absolute
t.Log("API signature verified")
})
}
func TestTimeoutRemove(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions, func(opt *uring.Options) {
opt.NotifySucceed = true
opt.MultiIssuers = true
})
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
timeoutCtx := uring.PackDirect(uring.IORING_OP_TIMEOUT, 0, 0, 0)
if err := ring.Timeout(timeoutCtx, time.Minute); err != nil {
t.Fatalf("Timeout: %v", err)
}
removeCtx := uring.PackDirect(uring.IORING_OP_TIMEOUT_REMOVE, 0, 0, 0)
if err := ring.TimeoutRemove(removeCtx, timeoutCtx.Raw()); err != nil {
t.Fatalf("TimeoutRemove: %v", err)
}
cqes := make([]uring.CQEView, 8)
deadline := time.Now().Add(time.Second)
timeoutRemoved := false
timeoutCanceled := false
b := iox.Backoff{}
for time.Now().Before(deadline) && (!timeoutRemoved || !timeoutCanceled) {
n, err := ring.Wait(cqes)
if err != nil &&
!errors.Is(err, iox.ErrWouldBlock) &&
!errors.Is(err, uring.ErrExists) {
t.Fatalf("Wait: %v", err)
}
for i := 0; i < n; i++ {
switch cqes[i].Op() {
case uring.IORING_OP_TIMEOUT_REMOVE:
if cqes[i].Res != 0 {
t.Fatalf("TimeoutRemove CQE res = %d, want 0", cqes[i].Res)
}
timeoutRemoved = true
case uring.IORING_OP_TIMEOUT:
if cqes[i].Res != -int32(zcall.ECANCELED) {
t.Fatalf("Timeout CQE res = %d, want %d", cqes[i].Res, -int32(zcall.ECANCELED))
}
timeoutCanceled = true
}
}
b.Wait()
}
if !timeoutRemoved || !timeoutCanceled {
t.Fatalf("timeout removal incomplete: remove=%t timeout=%t", timeoutRemoved, timeoutCanceled)
}
}
func TestUringLinkTimeoutCycle(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions, func(opt *uring.Options) {
opt.NotifySucceed = true
opt.MultiIssuers = true
})
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
nopCtx := uring.PackDirect(uring.IORING_OP_NOP, 0, 0, 0)
if err := ring.Nop(nopCtx, uring.WithFlags(uring.IOSQE_IO_LINK)); err != nil {
t.Fatalf("Nop: %v", err)
}
timeoutCtx := uring.PackDirect(uring.IORING_OP_LINK_TIMEOUT, 0, 0, 0)
if err := ring.LinkTimeout(timeoutCtx, 100*time.Millisecond); err != nil {
t.Fatalf("LinkTimeout: %v", err)
}
cqes := make([]uring.CQEView, 8)
deadline := time.Now().Add(time.Second)
nopDone := false
timeoutDone := false
b := iox.Backoff{}
for time.Now().Before(deadline) && (!nopDone || !timeoutDone) {
n, err := ring.Wait(cqes)
if err != nil &&
!errors.Is(err, iox.ErrWouldBlock) &&
!errors.Is(err, uring.ErrExists) {
t.Fatalf("Wait: %v", err)
}
for i := 0; i < n; i++ {
switch cqes[i].Op() {
case uring.IORING_OP_NOP:
if cqes[i].Res != 0 {
t.Fatalf("NOP CQE res = %d, want 0", cqes[i].Res)
}
nopDone = true
case uring.IORING_OP_LINK_TIMEOUT:
if cqes[i].Res != -int32(zcall.ECANCELED) {
t.Fatalf("LinkTimeout CQE res = %d, want %d", cqes[i].Res, -int32(zcall.ECANCELED))
}
timeoutDone = true
}
}
b.Wait()
}
if !nopDone || !timeoutDone {
t.Fatalf("linked timeout incomplete: nop=%t timeout=%t", nopDone, timeoutDone)
}
}
func TestUringFileReadWriteCycle(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions, func(opt *uring.Options) {
opt.NotifySucceed = true // Request a CQE for every successful operation.
opt.MultiIssuers = true // Exercise the shared-submit configuration.
})
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
f, err := os.CreateTemp("", "uring_test_*")
if err != nil {
t.Fatalf("CreateTemp: %v", err)
}
defer os.Remove(f.Name())
defer f.Close()
fd := int32(f.Fd())
testData := []byte("Hello, io_uring!")
// Write
writeCtx := uring.PackDirect(uring.IORING_OP_WRITE, 0, 0, fd)
if err := ring.Write(writeCtx, testData); err != nil {
t.Fatalf("Write: %v", err)
}
ev, ok := waitForOp(t, ring, uring.IORING_OP_WRITE, time.Second)
if !ok {
t.Fatal("Write operation did not complete")
}
if ev.Res < 0 {
t.Fatalf("Write failed: %d", ev.Res)
}
if int(ev.Res) != len(testData) {
t.Errorf("Write: got %d, want %d", ev.Res, len(testData))
}
// Seek and Read
f.Seek(0, 0)
readBuf := make([]byte, len(testData))
readCtx := uring.PackDirect(uring.IORING_OP_READ, 0, 0, fd)
if err := ring.Read(readCtx, readBuf); err != nil {
t.Fatalf("Read: %v", err)
}
ev, ok = waitForOp(t, ring, uring.IORING_OP_READ, time.Second)
if !ok {
t.Fatal("Read operation did not complete")
}
if ev.Res < 0 {
t.Fatalf("Read failed: %d", ev.Res)
}
if string(readBuf) != string(testData) {
t.Errorf("Data mismatch: got %q, want %q", readBuf, testData)
}
}
// =============================================================================
// Socket Tests using sock primitives
// =============================================================================
func TestUringTCPSocketCycle(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions)
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
// Create TCP4 socket via io_uring
ctx := uring.PackDirect(uring.IORING_OP_SOCKET, 0, 0, 0)
if err := ring.TCP4Socket(ctx); err != nil {
t.Fatalf("TCP4Socket: %v", err)
}
ev, ok := waitForOp(t, ring, uring.IORING_OP_SOCKET, time.Second)
if !ok {
t.Fatal("Socket creation did not complete")
}
if ev.Res < 0 {
t.Fatalf("Socket creation failed: %d", ev.Res)
}
socketFD := ev.Res
// Close socket via io_uring
closeCtx := uring.PackDirect(uring.IORING_OP_CLOSE, 0, 0, socketFD)
mustCloseAndWait(t, ring, closeCtx, time.Second, "TCP4 socket")
}
func TestUringTCPBindListenAccept(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions)
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
// Create server socket
serverCtx := uring.PackDirect(uring.IORING_OP_SOCKET, 0, 0, 0)
if err := ring.TCP4Socket(serverCtx); err != nil {
t.Fatalf("TCP4Socket: %v", err)
}
ev, ok := waitForOp(t, ring, uring.IORING_OP_SOCKET, time.Second)
if !ok || ev.Res < 0 {
t.Fatalf("Server socket creation failed")
}
serverFD := ev.Res
// Bind using sock.TCPAddr with IPv4LoopBack
bindAddr := &sock.TCPAddr{IP: sock.IPv4LoopBack, Port: 0} // Port 0 = ephemeral
bindCtx := uring.PackDirect(uring.IORING_OP_BIND, 0, 0, serverFD)
if err := ring.Bind(bindCtx, bindAddr); err != nil {
t.Fatalf("Bind: %v", err)
}
ev, ok = waitForOp(t, ring, uring.IORING_OP_BIND, time.Second)
if !ok {
t.Fatal("Bind did not complete")
}
if ev.Res < 0 {
t.Fatalf("Bind failed: %d", ev.Res)
}
// Listen
listenCtx := uring.PackDirect(uring.IORING_OP_LISTEN, 0, 0, serverFD)
if err := ring.Listen(listenCtx); err != nil {
t.Fatalf("Listen: %v", err)
}
ev, ok = waitForOp(t, ring, uring.IORING_OP_LISTEN, time.Second)
if !ok {
t.Fatal("Listen did not complete")
}
if ev.Res < 0 {
t.Fatalf("Listen failed: %d", ev.Res)
}
// Clean up - close server socket
closeCtx := uring.PackDirect(uring.IORING_OP_CLOSE, 0, 0, serverFD)
mustCloseAndWait(t, ring, closeCtx, time.Second, "server socket")
}
func TestUringUDPSocketCycle(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions)
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
ctx := uring.PackDirect(uring.IORING_OP_SOCKET, 0, 0, 0)
if err := ring.UDP4Socket(ctx); err != nil {
t.Fatalf("UDP4Socket: %v", err)
}
ev, ok := waitForOp(t, ring, uring.IORING_OP_SOCKET, time.Second)
if !ok || ev.Res < 0 {
t.Fatal("UDP socket creation failed")
}
closeCtx := uring.PackDirect(uring.IORING_OP_CLOSE, 0, 0, ev.Res)
mustCloseAndWait(t, ring, closeCtx, time.Second, "UDP4 socket")
}
func TestUringUnixSocketCycle(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions)
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
ctx := uring.PackDirect(uring.IORING_OP_SOCKET, 0, 0, 0)
if err := ring.UnixSocket(ctx); err != nil {
t.Fatalf("UnixSocket: %v", err)
}
ev, ok := waitForOp(t, ring, uring.IORING_OP_SOCKET, time.Second)
if !ok || ev.Res < 0 {
t.Fatal("Unix socket creation failed")
}
closeCtx := uring.PackDirect(uring.IORING_OP_CLOSE, 0, 0, ev.Res)
mustCloseAndWait(t, ring, closeCtx, time.Second, "Unix socket")
}
// =============================================================================
// Poll Tests
// =============================================================================
func TestUringPollAddCycle(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions, func(opt *uring.Options) {
opt.NotifySucceed = true // Request a CQE for every successful operation.
opt.MultiIssuers = true // Exercise the shared-submit configuration.
})
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
r, w, err := os.Pipe()
if err != nil {
t.Fatalf("Pipe: %v", err)
}
defer r.Close()
defer w.Close()
pollCtx := uring.PackDirect(uring.IORING_OP_POLL_ADD, 0, 0, int32(r.Fd()))
if err := ring.PollAdd(pollCtx, uring.EPOLLIN); err != nil {
t.Fatalf("PollAdd: %v", err)
}
// Make pipe readable
go func() {
time.Sleep(10 * time.Millisecond)
w.Write([]byte("test"))
}()
ev, ok := waitForOp(t, ring, uring.IORING_OP_POLL_ADD, time.Second)
if !ok {
t.Fatal("Poll did not complete")
}
if ev.Res < 0 {
t.Errorf("Poll failed: %d", ev.Res)
}
}
// =============================================================================
// Stress Tests: Multi-goroutine concurrent submissions
// =============================================================================
func TestUringConcurrentNops(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions, func(opt *uring.Options) {
opt.Entries = uring.EntriesMedium
opt.MultiIssuers = true
})
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
const numGoroutines = 8
const numOpsPerGoroutine = 100
var wg sync.WaitGroup
var submitted atomic.Int64
for g := 0; g < numGoroutines; g++ {
wg.Add(1)
go func(gid int) {
defer wg.Done()
for i := 0; i < numOpsPerGoroutine; i++ {
ctx := uring.PackDirect(uring.IORING_OP_NOP, 0, 0, int32(gid*1000+i))
if err := ring.Nop(ctx); err == nil {
submitted.Add(1)
}
}
}(g)
}
wg.Wait()
totalSubmitted := submitted.Load()
t.Logf("Submitted: %d", totalSubmitted)
if totalSubmitted < int64(numGoroutines*numOpsPerGoroutine/2) {
t.Errorf("Too few submissions: %d", totalSubmitted)
}
// Wait for completions
cqes := make([]uring.CQEView, 256)
var completed int64
deadline := time.Now().Add(5 * time.Second)
b := iox.Backoff{}
for completed < totalSubmitted && time.Now().Before(deadline) {
n, err := ring.Wait(cqes)
if err != nil && !errors.Is(err, iox.ErrWouldBlock) {
t.Fatalf("Wait: %v", err)
}
completed += int64(n)
b.Wait()
}
t.Logf("Completed: %d", completed)
}
func TestUringConcurrentFileOps(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions, func(opt *uring.Options) {
opt.Entries = uring.EntriesMedium
opt.MultiIssuers = true
opt.NotifySucceed = true // Request a CQE for every successful operation.
})
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
const numGoroutines = 4
const numOpsPerGoroutine = 25
files := make([]*os.File, numGoroutines)
for i := 0; i < numGoroutines; i++ {
f, err := os.CreateTemp("", "uring_stress_*")
if err != nil {
t.Fatalf("CreateTemp: %v", err)
}
files[i] = f
defer os.Remove(f.Name())
defer f.Close()
}
var wg sync.WaitGroup
var submitted atomic.Int64
for g := 0; g < numGoroutines; g++ {
wg.Add(1)
go func(gid int) {
defer wg.Done()
fd := int32(files[gid].Fd())
for i := 0; i < numOpsPerGoroutine; i++ {
data := []byte("stress test data\n")
ctx := uring.PackDirect(uring.IORING_OP_WRITE, 0, 0, fd)
if err := ring.Write(ctx, data); err == nil {
submitted.Add(1)
}
}
}(g)
}
wg.Wait()
totalSubmitted := submitted.Load()
t.Logf("Submitted %d write operations", totalSubmitted)
cqes := make([]uring.CQEView, 256)
var completed int64
deadline := time.Now().Add(5 * time.Second)
b := iox.Backoff{}
for completed < totalSubmitted && time.Now().Before(deadline) {
n, err := ring.Wait(cqes)
if err != nil && !errors.Is(err, iox.ErrWouldBlock) {
t.Fatalf("Wait: %v", err)
}
for j := 0; j < n; j++ {
if cqes[j].Op() == uring.IORING_OP_WRITE {
completed++
}
}
b.Wait()
}
t.Logf("Completed: %d", completed)
}
// =============================================================================
// Baseline Feature Tests
// =============================================================================
func TestFeatureDetection(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions, func(opt *uring.Options) {
opt.Entries = uring.EntriesSmall
})
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
t.Logf("SQ Entries: %d", ring.Features.SQEntries)
t.Logf("CQ Entries: %d", ring.Features.CQEntries)
if ring.Features.SQEntries == 0 {
t.Error("SQEntries should be non-zero")
}
if ring.Features.CQEntries == 0 {
t.Error("CQEntries should be non-zero")
}
}
// =============================================================================
// Linux 6.18+ Baseline Operation Tests
// =============================================================================
func TestUringEpollWait(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions, func(opt *uring.Options) {
opt.Entries = uring.EntriesSmall
})
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
t.Log("EpollWait is part of the Linux 6.18+ baseline")
}
func TestUringPipe(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions, func(opt *uring.Options) {
opt.Entries = uring.EntriesSmall
})
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
// Buffer for the two file descriptors (read end, write end)
var fds [2]int32
ctx := uring.PackDirect(uring.IORING_OP_PIPE, 0, 0, 0)
if err := ring.Pipe(ctx, &fds, 0); err != nil {
t.Fatalf("Pipe: %v", err)
}
ev, ok := waitForOp(t, ring, uring.IORING_OP_PIPE, time.Second)
if !ok {
t.Fatal("Pipe operation did not complete")
}
if ev.Res < 0 {
t.Errorf("Pipe creation failed: %d", ev.Res)
} else {
t.Logf("Pipe created: read_fd=%d, write_fd=%d", fds[0], fds[1])
// Verify we got valid file descriptors
if fds[0] <= 0 || fds[1] <= 0 {
t.Errorf("Invalid file descriptors: read=%d, write=%d", fds[0], fds[1])
}
}
}
// =============================================================================
// Resize Rings Tests
// =============================================================================
func TestResizeRings(t *testing.T) {
if isWSL2() {
t.Skip("ResizeRings is not reliable on WSL2 kernels")
}
// Create a single-issuer ring (has DEFER_TASKRUN by default)
ring, err := uring.New(testMinimalBufferOptions, func(opt *uring.Options) {
opt.Entries = uring.EntriesSmall // 512 entries
// Single issuer mode is default, which sets DEFER_TASKRUN
})
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
logRingDiagnostics(t, "ResizeRings/start", ring)
// Try to resize to larger CQ ring
err = ring.ResizeRings(0, 2048) // Keep SQ, grow CQ to 2048
if err != nil {
logRingDiagnostics(t, "ResizeRings/failure", ring)
t.Fatalf("ResizeRings: %v (requested newSQ=%d newCQ=%d)", err, 0, 2048)
}
logRingDiagnostics(t, "ResizeRings/after", ring)
// Verify the ring still works after resize
ctx := uring.PackDirect(uring.IORING_OP_NOP, 0, 0, 0)
if err := ring.Nop(ctx); err != nil {
t.Fatalf("Nop after resize: %v", err)
}
ev, ok := waitForOp(t, ring, uring.IORING_OP_NOP, time.Second)
if !ok {
t.Fatal("NOP did not complete after resize")
}
if ev.Res < 0 {
t.Errorf("NOP failed after resize: %d", ev.Res)
}
t.Log("ResizeRings succeeded - ring functional after CQ resize to 2048")
}
// TestBufRingMMAP tests kernel-allocated buffer ring registration.
// In MMAP mode, the kernel allocates the ring memory and we map it into userspace.
func TestBufRingMMAP(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions)
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
// Try to register a buffer ring with MMAP mode
const (
groupID = 100
entries = 16
)
bufRing, err := ring.RegisterBufRingMMAP(entries, groupID)
if err != nil {
t.Fatalf("RegisterBufRingMMAP: %v", err)
}
if bufRing == nil {
t.Fatal("RegisterBufRingMMAP returned nil ring")
}
t.Logf("Buffer ring MMAP registered: groupID=%d, entries=%d", groupID, entries)
t.Log("Buffer ring MMAP test passed")
}
func TestRegisterBufRingRejectsInvalidEntries(t *testing.T) {
apis := []struct {
name string
call func(ring *uring.Uring, entries int, groupID uint16) error
}{
{
name: "MMAP",
call: func(ring *uring.Uring, entries int, groupID uint16) error {
_, err := ring.RegisterBufRingMMAP(entries, groupID)
return err
},
},
{
name: "Incremental",
call: func(ring *uring.Uring, entries int, groupID uint16) error {
_, err := ring.RegisterBufRingIncremental(entries, groupID)
return err
},
},
{
name: "WithFlags",
call: func(ring *uring.Uring, entries int, groupID uint16) error {
_, err := ring.RegisterBufRingWithFlags(entries, groupID, 0)
return err
},
},
}
for _, api := range apis {
t.Run(api.name, func(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions)
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
for i, entries := range []int{0, (1 << 15) + 1} {
groupID := uint16(200 + i)
err := api.call(ring, entries, groupID)
if !errors.Is(err, uring.ErrInvalidParam) {
t.Fatalf("entries=%d: got %v, want %v", entries, err, uring.ErrInvalidParam)
}
}
})
}
}
// TestQueryOpcodes tests the io_uring query interface (Linux 6.19+).
// This allows querying kernel capabilities at runtime.
func TestQueryOpcodes(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions)
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
// Query supported opcodes
info, err := ring.QueryOpcodes()
if err != nil {
// EINVAL or ENOSYS expected on kernel < 6.19
t.Skipf("QueryOpcodes not supported: %v (requires kernel 6.19+)", err)
}
t.Logf("Query interface available:")
t.Logf(" NrRequestOpcodes: %d", info.NrRequestOpcodes)
t.Logf(" NrRegisterOpcodes: %d", info.NrRegisterOpcodes)
t.Logf(" FeatureFlags: 0x%x", info.FeatureFlags)
t.Logf(" RingSetupFlags: 0x%x", info.RingSetupFlags)
t.Logf(" NrQueryOpcodes: %d", info.NrQueryOpcodes)
// Verify reasonable values
if info.NrRequestOpcodes < 50 {
t.Logf("Note: NrRequestOpcodes=%d seems low", info.NrRequestOpcodes)
}
t.Log("Query interface test passed")
}
// TestRegisterFiles tests fixed file registration.
func TestRegisterFiles(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions, func(opt *uring.Options) {
opt.Entries = uring.EntriesSmall
})
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
// Create a temporary file
f, err := os.CreateTemp("", "uring-test-*")
if err != nil {
t.Fatalf("CreateTemp: %v", err)
}
defer os.Remove(f.Name())
defer f.Close()
fd := int32(f.Fd())
// Test RegisterFiles
err = ring.RegisterFiles([]int32{fd})
if err != nil {
t.Fatalf("RegisterFiles: %v", err)
}
// Verify count
if ring.RegisteredFileCount() != 1 {
t.Errorf("expected 1 registered file, got %d", ring.RegisteredFileCount())
}
// Test double registration (should fail with ErrExists)
err = ring.RegisterFiles([]int32{fd})
if err != uring.ErrExists {
t.Errorf("expected ErrExists on double register, got %v", err)
}
// Unregister
err = ring.UnregisterFiles()
if err != nil {
t.Fatalf("UnregisterFiles: %v", err)
}
// Verify count after unregister
if ring.RegisteredFileCount() != 0 {
t.Errorf("expected 0 registered files after unregister, got %d", ring.RegisteredFileCount())
}
t.Log("RegisterFiles test passed")
}
// TestRegisterFilesSparse tests sparse file registration.
func TestRegisterFilesSparse(t *testing.T) {
ring, err := uring.New(testMinimalBufferOptions, func(opt *uring.Options) {
opt.Entries = uring.EntriesSmall
})
if err != nil {
t.Fatalf("New: %v", err)
}
mustStartRing(t, ring)
// Test sparse registration
err = ring.RegisterFilesSparse(16)
if err != nil {
t.Fatalf("RegisterFilesSparse: %v", err)
}
// Verify count
if ring.RegisteredFileCount() != 16 {
t.Errorf("expected 16 registered files, got %d", ring.RegisteredFileCount())
}
// Create a temporary file
f, err := os.CreateTemp("", "uring-test-sparse-*")