-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblkbench.c
More file actions
1852 lines (1654 loc) · 54.3 KB
/
Copy pathblkbench.c
File metadata and controls
1852 lines (1654 loc) · 54.3 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
/*
* blkbench - minimal-overhead I/O benchmarking tool using libblkio
*
* Benchmarks vhost-user-blk backends (and other libblkio drivers) with
* busy-loop polling, per-request latency tracking, and fio-style output.
*/
#define _GNU_SOURCE
#include <blkio.h>
#include <errno.h>
#include <getopt.h>
#include <math.h>
#include <pthread.h>
#include <sched.h>
#include <stdatomic.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
/* ── Constants ─────────────────────────────────────────────────────── */
#define VERSION "1.0.0"
#define HIST_BUCKETS 32 /* log2 histogram: bucket i = [2^i, 2^(i+1)) ns; 0 = <1us */
#define NS_PER_SEC 1000000000ULL
#define NS_PER_US 1000ULL
#define NS_PER_MS 1000000ULL
/* ── I/O pattern enum ──────────────────────────────────────────────── */
enum rw_mode {
RW_READ,
RW_WRITE,
RW_RANDREAD,
RW_RANDWRITE,
RW_READWRITE,
RW_RANDRW,
RW_VERIFY_FLUSH,
RW_VERIFY_PIPELINE,
};
/* ── Per-request slot (passed as user_data) ────────────────────────── */
struct req_slot {
uint64_t submit_ns;
uint64_t offset;
bool is_write;
int index;
};
/* ── Per-worker stats ──────────────────────────────────────────────── */
struct worker_stats {
/* Counters read by reporter thread while workers run — must be atomic.
* All accesses use memory_order_relaxed (single writer per field). */
_Atomic uint64_t ios_done;
_Atomic uint64_t bytes_done;
_Atomic uint64_t read_ios;
_Atomic uint64_t write_ios;
_Atomic uint64_t read_bytes;
_Atomic uint64_t write_bytes;
/* Remaining fields: only read after workers are joined */
uint64_t errors;
uint64_t flushes;
uint64_t lat_min_ns;
uint64_t lat_max_ns;
uint64_t lat_sum_ns;
uint64_t hist[HIST_BUCKETS];
};
/* Relaxed helpers for single-writer atomic counters */
#define STAT_LOAD(field) atomic_load_explicit(&(field), memory_order_relaxed)
#define STAT_STORE(field, val) atomic_store_explicit(&(field), (val), memory_order_relaxed)
#define STAT_ADD(field, val) STAT_STORE(field, STAT_LOAD(field) + (val))
#define STAT_INC(field) STAT_ADD(field, 1)
/* ── Parsed arguments ──────────────────────────────────────────────── */
struct bench_args {
const char *path;
const char *driver;
enum rw_mode rw;
uint64_t bs;
int iodepth;
int numjobs;
int runtime;
uint64_t size;
uint64_t offset;
int rwmixread;
int ramp_time;
int sync_n;
int queue_size; /* set to iodepth automatically */
bool json_output;
int direct;
int verify_min_sectors;
int verify_max_sectors;
bool verify_inject_fault;
int eta_interval; /* seconds between progress lines; 0 = disabled */
};
/* ── Worker context ────────────────────────────────────────────────── */
struct worker_ctx {
int job_index;
struct blkioq *queue;
struct blkio_mem_region region;
struct bench_args *args;
struct worker_stats stats;
uint64_t prng_state;
uint64_t seq_offset;
int write_counter;
/* timing */
uint64_t start_ns;
uint64_t ramp_end_ns;
uint64_t end_ns;
};
/* ── CPU usage ─────────────────────────────────────────────────────── */
struct cpu_usage {
uint64_t utime_ticks;
uint64_t stime_ticks;
uint64_t wall_ns;
};
/* ── Helpers ───────────────────────────────────────────────────────── */
static uint64_t now_ns(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * NS_PER_SEC + (uint64_t)ts.tv_nsec;
}
static int hist_bucket(uint64_t lat_ns)
{
if (lat_ns < NS_PER_US)
return 0;
/* bucket i covers [2^(i-1) us, 2^i us) for i >= 1, stored as ns */
int b = 1;
uint64_t threshold = 2 * NS_PER_US;
while (b < HIST_BUCKETS - 1 && lat_ns >= threshold) {
b++;
threshold <<= 1;
}
return b;
}
static uint64_t hist_bucket_upper_ns(int b)
{
if (b == 0)
return NS_PER_US;
return NS_PER_US << b;
}
static uint64_t percentile_from_hist(const uint64_t *hist, uint64_t total, double pct)
{
uint64_t target = (uint64_t)ceil((double)total * pct / 100.0);
uint64_t cumulative = 0;
for (int i = 0; i < HIST_BUCKETS; i++) {
cumulative += hist[i];
if (cumulative >= target)
return hist_bucket_upper_ns(i);
}
return hist_bucket_upper_ns(HIST_BUCKETS - 1);
}
static uint64_t xorshift64(uint64_t *state)
{
uint64_t x = *state;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
*state = x;
return x;
}
static void stats_reset(struct worker_stats *s)
{
STAT_STORE(s->ios_done, 0);
STAT_STORE(s->bytes_done, 0);
STAT_STORE(s->read_ios, 0);
STAT_STORE(s->write_ios, 0);
STAT_STORE(s->read_bytes, 0);
STAT_STORE(s->write_bytes, 0);
s->errors = 0;
s->flushes = 0;
s->lat_min_ns = UINT64_MAX;
s->lat_max_ns = 0;
s->lat_sum_ns = 0;
memset(s->hist, 0, sizeof(s->hist));
}
static void stats_record(struct worker_stats *s, uint64_t lat_ns, uint64_t bs, bool is_write)
{
STAT_INC(s->ios_done);
STAT_ADD(s->bytes_done, bs);
if (is_write) {
STAT_INC(s->write_ios);
STAT_ADD(s->write_bytes, bs);
} else {
STAT_INC(s->read_ios);
STAT_ADD(s->read_bytes, bs);
}
s->lat_sum_ns += lat_ns;
if (lat_ns < s->lat_min_ns)
s->lat_min_ns = lat_ns;
if (lat_ns > s->lat_max_ns)
s->lat_max_ns = lat_ns;
s->hist[hist_bucket(lat_ns)]++;
}
static void stats_merge(struct worker_stats *dst, const struct worker_stats *src)
{
/* Called after workers are joined, so no concurrent writers.
* Still need STAT_LOAD/STAT_ADD because fields are _Atomic. */
STAT_ADD(dst->ios_done, STAT_LOAD(src->ios_done));
STAT_ADD(dst->bytes_done, STAT_LOAD(src->bytes_done));
STAT_ADD(dst->read_ios, STAT_LOAD(src->read_ios));
STAT_ADD(dst->write_ios, STAT_LOAD(src->write_ios));
STAT_ADD(dst->read_bytes, STAT_LOAD(src->read_bytes));
STAT_ADD(dst->write_bytes, STAT_LOAD(src->write_bytes));
dst->errors += src->errors;
dst->flushes += src->flushes;
dst->lat_sum_ns += src->lat_sum_ns;
if (src->lat_min_ns < dst->lat_min_ns)
dst->lat_min_ns = src->lat_min_ns;
if (src->lat_max_ns > dst->lat_max_ns)
dst->lat_max_ns = src->lat_max_ns;
for (int i = 0; i < HIST_BUCKETS; i++)
dst->hist[i] += src->hist[i];
}
/* ── CRC32 (IEEE polynomial, lookup table) ─────────────────────────── */
static uint32_t crc32_table[256];
static bool crc32_table_init;
static void crc32_init(void)
{
if (crc32_table_init)
return;
for (uint32_t i = 0; i < 256; i++) {
uint32_t c = i;
for (int j = 0; j < 8; j++)
c = (c >> 1) ^ (c & 1 ? 0xEDB88320U : 0);
crc32_table[i] = c;
}
crc32_table_init = true;
}
static uint32_t crc32_compute(const void *data, size_t len)
{
const unsigned char *p = data;
uint32_t crc = 0xFFFFFFFF;
for (size_t i = 0; i < len; i++)
crc = (crc >> 8) ^ crc32_table[(crc ^ p[i]) & 0xFF];
return crc ^ 0xFFFFFFFF;
}
/* ── Shared sector allocator for verify-flush mode ─────────────────── */
struct sector_alloc {
pthread_mutex_t lock;
uint64_t next_offset; /* next available byte offset */
uint64_t limit; /* upper bound (offset + size) */
uint64_t sector_size; /* typically = bs */
};
static void sector_alloc_init(struct sector_alloc *sa, uint64_t base, uint64_t size,
uint64_t sector_size)
{
pthread_mutex_init(&sa->lock, NULL);
sa->next_offset = base;
sa->limit = base + size;
sa->sector_size = sector_size;
}
/* Returns starting offset, or UINT64_MAX if exhausted */
static uint64_t sector_alloc_get(struct sector_alloc *sa, int n_sectors)
{
uint64_t need = (uint64_t)n_sectors * sa->sector_size;
pthread_mutex_lock(&sa->lock);
uint64_t off = sa->next_offset;
if (off + need > sa->limit) {
pthread_mutex_unlock(&sa->lock);
return UINT64_MAX;
}
sa->next_offset = off + need;
pthread_mutex_unlock(&sa->lock);
return off;
}
static void sector_alloc_destroy(struct sector_alloc *sa)
{
pthread_mutex_destroy(&sa->lock);
}
/* ── Verify-flush: per-region record ──────────────────────────────── */
struct verify_record {
uint64_t offset;
uint32_t n_sectors;
uint32_t crc;
};
/* ── SPSC ring buffer for verify-pipeline inter-thread handoff ──── */
#define PIPELINE_RING_SIZE 256 /* must be power of 2 */
struct pipeline_entry {
uint64_t offset;
uint32_t crc;
};
struct pipeline_ring {
_Alignas(64) atomic_uint head; /* written by producer */
_Alignas(64) atomic_uint tail; /* written by consumer */
struct pipeline_entry entries[PIPELINE_RING_SIZE];
};
static void pipeline_ring_init(struct pipeline_ring *r)
{
atomic_store_explicit(&r->head, 0, memory_order_relaxed);
atomic_store_explicit(&r->tail, 0, memory_order_relaxed);
}
/* Push entry; spins if full. Returns false if stop_flag is set. */
static bool pipeline_ring_push(struct pipeline_ring *r, const struct pipeline_entry *e,
const atomic_bool *stop_flag)
{
unsigned h = atomic_load_explicit(&r->head, memory_order_relaxed);
for (;;) {
unsigned t = atomic_load_explicit(&r->tail, memory_order_acquire);
if (h - t < PIPELINE_RING_SIZE)
break;
if (atomic_load_explicit(stop_flag, memory_order_relaxed))
return false;
/* spin */
}
r->entries[h & (PIPELINE_RING_SIZE - 1)] = *e;
atomic_store_explicit(&r->head, h + 1, memory_order_release);
return true;
}
/* Pop entry; spins if empty. Returns false if stop_flag is set and ring empty. */
static bool pipeline_ring_pop(struct pipeline_ring *r, struct pipeline_entry *e,
const atomic_bool *stop_flag)
{
unsigned t = atomic_load_explicit(&r->tail, memory_order_relaxed);
for (;;) {
unsigned h = atomic_load_explicit(&r->head, memory_order_acquire);
if (h != t)
break;
if (atomic_load_explicit(stop_flag, memory_order_relaxed))
return false;
/* spin */
}
*e = r->entries[t & (PIPELINE_RING_SIZE - 1)];
atomic_store_explicit(&r->tail, t + 1, memory_order_release);
return true;
}
/* Non-blocking pop: returns true if an entry was available. */
static bool pipeline_ring_try_pop(struct pipeline_ring *r, struct pipeline_entry *e)
{
unsigned t = atomic_load_explicit(&r->tail, memory_order_relaxed);
unsigned h = atomic_load_explicit(&r->head, memory_order_acquire);
if (h == t)
return false;
*e = r->entries[t & (PIPELINE_RING_SIZE - 1)];
atomic_store_explicit(&r->tail, t + 1, memory_order_release);
return true;
}
/* ── Verify-pipeline shared context ────────────────────────────────── */
struct pipeline_ctx {
struct sector_alloc *alloc;
struct pipeline_ring *rings; /* array of numjobs rings */
atomic_bool stop_flag; /* set when runtime expires */
int numjobs;
};
/* ── Verify-flush worker thread ───────────────────────────────────── */
/*
* Helper: drain exactly n_ios completions from the queue.
* Returns number of I/O errors.
*/
static int do_io_drain(struct blkioq *q, struct blkio_completion *comps, int max_comps, int n_ios)
{
int errs = 0;
int outstanding = n_ios;
while (outstanding > 0) {
int n = blkioq_do_io(q, comps, 1, max_comps, NULL);
if (n < 0)
return outstanding;
for (int i = 0; i < n; i++) {
if (comps[i].ret != 0)
errs++;
outstanding--;
}
}
return errs;
}
static void *verify_flush_thread(void *arg)
{
struct worker_ctx *w = arg;
struct bench_args *a = w->args;
struct blkioq *q = w->queue;
unsigned char *base = (unsigned char *)w->region.addr;
struct sector_alloc *sa = (struct sector_alloc *)(uintptr_t)w->prng_state;
uint64_t bs = a->bs;
int max_sec = a->verify_max_sectors;
int max_comps = max_sec > a->iodepth ? max_sec : a->iodepth;
struct blkio_completion *comps = calloc(max_comps, sizeof(*comps));
if (!comps) {
fprintf(stderr, "verify job %d: alloc failed\n", w->job_index);
return NULL;
}
size_t rec_cap = 256;
size_t rec_count = 0;
struct verify_record *recs = malloc(rec_cap * sizeof(*recs));
if (!recs) {
fprintf(stderr, "verify job %d: alloc failed\n", w->job_index);
free(comps);
return NULL;
}
uint64_t prng = 0x853c49e6748fea9bULL ^ (uint64_t)(w->job_index + 1);
int range = a->verify_max_sectors - a->verify_min_sectors + 1;
int total_writes = 0;
stats_reset(&w->stats);
/*
* Stage 1: Write one region at a time, drain before next.
*/
for (;;) {
int n_sec = a->verify_min_sectors;
if (range > 1)
n_sec += (int)(xorshift64(&prng) % (uint64_t)range);
uint64_t off = sector_alloc_get(sa, n_sec);
if (off == UINT64_MAX)
break;
size_t total_bytes = (size_t)n_sec * bs;
unsigned char *buf = base;
for (size_t i = 0; i + 8 <= total_bytes; i += 8) {
uint64_t val = off + i;
memcpy(buf + i, &val, 8);
}
uint32_t crc = crc32_compute(buf, total_bytes);
if (rec_count >= rec_cap) {
rec_cap *= 2;
struct verify_record *new_recs = realloc(recs, rec_cap * sizeof(*recs));
if (!new_recs) {
fprintf(stderr, "verify job %d: realloc failed\n", w->job_index);
break;
}
recs = new_recs;
}
recs[rec_count++] = (struct verify_record){
.offset = off,
.n_sectors = (uint32_t)n_sec,
.crc = crc,
};
for (int s = 0; s < n_sec; s++)
blkioq_write(q, off + (uint64_t)s * bs, buf + (size_t)s * bs, bs, NULL, 0);
int errs = do_io_drain(q, comps, max_comps, n_sec);
if (errs) {
fprintf(stderr, "verify job %d: %d write error(s) at offset %lu\n",
w->job_index, errs, (unsigned long)off);
w->stats.errors += (uint64_t)errs;
}
total_writes += n_sec;
STAT_ADD(w->stats.write_ios, (uint64_t)n_sec);
STAT_ADD(w->stats.write_bytes, (uint64_t)n_sec * bs);
STAT_ADD(w->stats.ios_done, (uint64_t)n_sec);
STAT_ADD(w->stats.bytes_done, (uint64_t)n_sec * bs);
}
/*
* Stage 2: Flush
*/
blkioq_flush(q, NULL, 0);
int ferr = do_io_drain(q, comps, max_comps, 1);
if (ferr) {
fprintf(stderr, "verify job %d: flush failed\n", w->job_index);
w->stats.errors++;
}
w->stats.flushes++;
/*
* Stage 3: Verify - re-read each region and check CRC
*/
int mismatches = 0;
for (size_t r = 0; r < rec_count; r++) {
struct verify_record *rec = &recs[r];
size_t total_bytes = (size_t)rec->n_sectors * bs;
unsigned char *buf = base;
for (uint32_t s = 0; s < rec->n_sectors; s++)
blkioq_read(q, rec->offset + (uint64_t)s * bs, buf + (size_t)s * bs, bs,
NULL, 0);
int errs = do_io_drain(q, comps, max_comps, (int)rec->n_sectors);
if (errs) {
fprintf(stderr, "verify job %d: %d read error(s) at offset %lu\n",
w->job_index, errs, (unsigned long)rec->offset);
w->stats.errors += (uint64_t)errs;
}
STAT_ADD(w->stats.read_ios, rec->n_sectors);
STAT_ADD(w->stats.read_bytes, (uint64_t)rec->n_sectors * bs);
STAT_ADD(w->stats.ios_done, rec->n_sectors);
STAT_ADD(w->stats.bytes_done, (uint64_t)rec->n_sectors * bs);
/* Fault injection: flip one byte in first region to test detection */
if (a->verify_inject_fault && r == 0)
buf[0] ^= 0xFF;
uint32_t actual_crc = crc32_compute(buf, total_bytes);
if (actual_crc != rec->crc) {
fprintf(stderr,
"VERIFY FAIL: job %d, offset %lu, %u sectors: "
"expected crc 0x%08x, got 0x%08x\n",
w->job_index, (unsigned long)rec->offset, rec->n_sectors, rec->crc,
actual_crc);
mismatches++;
w->stats.errors++;
}
}
if (mismatches == 0)
printf("verify job %d: OK - %zu regions (%d writes) verified\n", w->job_index,
rec_count, total_writes);
else
printf("verify job %d: FAILED - %d/%zu regions mismatched\n", w->job_index,
mismatches, rec_count);
free(recs);
free(comps);
return NULL;
}
/* ── Verify-pipeline worker thread ─────────────────────────────────── */
static void *verify_pipeline_thread(void *arg)
{
struct worker_ctx *w = arg;
struct bench_args *a = w->args;
struct blkioq *q = w->queue;
unsigned char *base = (unsigned char *)w->region.addr;
struct pipeline_ctx *pctx = (struct pipeline_ctx *)(uintptr_t)w->prng_state;
uint64_t bs = a->bs;
int nj = pctx->numjobs;
int me = w->job_index;
/* Ring I send to: next thread in circular order (or self if nj==1) */
struct pipeline_ring *send_ring = &pctx->rings[me];
/* Ring I receive from: previous thread */
struct pipeline_ring *recv_ring = &pctx->rings[(me - 1 + nj) % nj];
struct blkio_completion comp;
stats_reset(&w->stats);
uint64_t start_ns = now_ns();
uint64_t end_ns = start_ns + (uint64_t)a->runtime * NS_PER_SEC;
uint64_t total_writes = 0, total_verifies = 0, mismatches = 0;
/* Use two buffer slots: slot 0 for writing, slot 1 for reading */
unsigned char *wbuf = base;
unsigned char *rbuf = base + bs;
while (now_ns() < end_ns) {
/* Step 1: Allocate a sector, write it */
uint64_t off = sector_alloc_get(pctx->alloc, 1);
if (off == UINT64_MAX)
break;
/* Fill with offset-seeded pattern */
for (size_t i = 0; i + 8 <= bs; i += 8) {
uint64_t val = off + i;
memcpy(wbuf + i, &val, 8);
}
uint32_t crc = crc32_compute(wbuf, bs);
/* Write the sector */
blkioq_write(q, off, wbuf, bs, NULL, 0);
int errs = do_io_drain(q, &comp, 1, 1);
if (errs) {
w->stats.errors++;
continue;
}
total_writes++;
STAT_INC(w->stats.write_ios);
STAT_ADD(w->stats.write_bytes, bs);
STAT_INC(w->stats.ios_done);
STAT_ADD(w->stats.bytes_done, bs);
/* Step 2: Send (offset, crc) to next thread's ring */
struct pipeline_entry e = {.offset = off, .crc = crc};
if (nj > 1) {
if (!pipeline_ring_push(send_ring, &e, &pctx->stop_flag))
break;
}
/* Step 3: Receive (offset, crc) from previous thread and verify */
struct pipeline_entry recv;
bool got;
if (nj == 1) {
/* Degenerate: verify our own write immediately */
recv = e;
got = true;
} else {
got = pipeline_ring_pop(recv_ring, &recv, &pctx->stop_flag);
}
if (!got)
break;
/* Read the sector */
blkioq_read(q, recv.offset, rbuf, bs, NULL, 0);
errs = do_io_drain(q, &comp, 1, 1);
if (errs) {
w->stats.errors++;
continue;
}
STAT_INC(w->stats.read_ios);
STAT_ADD(w->stats.read_bytes, bs);
STAT_INC(w->stats.ios_done);
STAT_ADD(w->stats.bytes_done, bs);
/* Fault injection: flip one byte on first verify */
if (a->verify_inject_fault && total_verifies == 0)
rbuf[0] ^= 0xFF;
uint32_t actual_crc = crc32_compute(rbuf, bs);
if (actual_crc != recv.crc) {
fprintf(stderr,
"VERIFY FAIL: job %d, offset %lu: "
"expected crc 0x%08x, got 0x%08x\n",
me, (unsigned long)recv.offset, recv.crc, actual_crc);
mismatches++;
w->stats.errors++;
}
total_verifies++;
}
/* Signal stop so other threads don't spin forever */
atomic_store_explicit(&pctx->stop_flag, true, memory_order_relaxed);
/* Drain any remaining entries from recv ring (verify them) */
if (nj > 1) {
struct pipeline_entry recv;
while (pipeline_ring_try_pop(recv_ring, &recv)) {
blkioq_read(q, recv.offset, rbuf, bs, NULL, 0);
int errs = do_io_drain(q, &comp, 1, 1);
if (errs) {
w->stats.errors++;
continue;
}
STAT_INC(w->stats.read_ios);
STAT_ADD(w->stats.read_bytes, bs);
STAT_INC(w->stats.ios_done);
STAT_ADD(w->stats.bytes_done, bs);
uint32_t actual_crc = crc32_compute(rbuf, bs);
if (actual_crc != recv.crc) {
fprintf(stderr,
"VERIFY FAIL: job %d, offset %lu: "
"expected crc 0x%08x, got 0x%08x\n",
me, (unsigned long)recv.offset, recv.crc, actual_crc);
mismatches++;
w->stats.errors++;
}
total_verifies++;
}
}
if (mismatches == 0)
printf("pipeline job %d: OK - %lu writes, %lu verifies\n", me,
(unsigned long)total_writes, (unsigned long)total_verifies);
else
printf("pipeline job %d: FAILED - %lu mismatches in %lu verifies\n", me,
(unsigned long)mismatches, (unsigned long)total_verifies);
return NULL;
}
/* ── Workload generation ───────────────────────────────────────────── */
static bool mode_is_random(enum rw_mode m)
{
return m == RW_RANDREAD || m == RW_RANDWRITE || m == RW_RANDRW;
}
static bool mode_is_mixed(enum rw_mode m)
{
return m == RW_READWRITE || m == RW_RANDRW;
}
static bool mode_is_write_only(enum rw_mode m)
{
return m == RW_WRITE || m == RW_RANDWRITE;
}
static uint64_t next_offset(struct worker_ctx *w)
{
struct bench_args *a = w->args;
uint64_t io_range = a->size;
uint64_t n_blocks = io_range / a->bs;
if (n_blocks == 0)
n_blocks = 1;
if (mode_is_random(a->rw)) {
uint64_t block = xorshift64(&w->prng_state) % n_blocks;
return a->offset + block * a->bs;
}
/* sequential: wrap at aligned boundary to avoid IO extending beyond region */
uint64_t off = a->offset + w->seq_offset;
w->seq_offset += a->bs;
if (w->seq_offset >= n_blocks * a->bs)
w->seq_offset = 0;
return off;
}
static bool next_is_write(struct worker_ctx *w)
{
struct bench_args *a = w->args;
if (mode_is_write_only(a->rw))
return true;
if (!mode_is_mixed(a->rw))
return false;
/* mixed: write with probability (100 - rwmixread)% */
return (xorshift64(&w->prng_state) % 100) >= (uint64_t)a->rwmixread;
}
/* ── I/O loop (hot path) ──────────────────────────────────────────── */
static void *worker_thread(void *arg)
{
struct worker_ctx *w = arg;
struct bench_args *a = w->args;
struct blkioq *q = w->queue;
unsigned char *base = (unsigned char *)w->region.addr;
int depth = a->iodepth;
struct req_slot *slots = calloc(depth, sizeof(struct req_slot));
struct blkio_completion *comps = calloc(depth, sizeof(struct blkio_completion));
if (!slots || !comps) {
fprintf(stderr, "worker %d: alloc failed\n", w->job_index);
free(slots);
free(comps);
return NULL;
}
stats_reset(&w->stats);
struct timespec zero_timeout = {0, 0};
bool ramped = (a->ramp_time == 0);
/* Pre-fill: queue iodepth initial requests */
int outstanding = 0;
for (int i = 0; i < depth; i++) {
slots[i].index = i;
slots[i].is_write = next_is_write(w);
slots[i].offset = next_offset(w);
slots[i].submit_ns = now_ns();
void *buf = base + (size_t)i * a->bs;
if (slots[i].is_write)
blkioq_write(q, slots[i].offset, buf, a->bs, &slots[i], 0);
else
blkioq_read(q, slots[i].offset, buf, a->bs, &slots[i], 0);
outstanding++;
}
w->start_ns = now_ns();
w->ramp_end_ns = w->start_ns + (uint64_t)a->ramp_time * NS_PER_SEC;
w->end_ns = w->start_ns + (uint64_t)(a->ramp_time + a->runtime) * NS_PER_SEC;
/* Main I/O loop */
for (;;) {
int n = blkioq_do_io(q, comps, 0, depth, &zero_timeout);
if (n < 0) {
w->stats.errors++;
outstanding = 0; /* can't drain after error */
break;
}
uint64_t t = now_ns();
/* Check ramp */
if (!ramped && t >= w->ramp_end_ns) {
stats_reset(&w->stats);
ramped = true;
}
/* Check end */
if (t >= w->end_ns) {
/* Process completions but don't requeue */
for (int i = 0; i < n; i++) {
struct req_slot *s = comps[i].user_data;
if (!s) {
outstanding--;
continue; /* flush completion */
}
outstanding--;
if (comps[i].ret != 0) {
w->stats.errors++;
continue;
}
uint64_t lat = t - s->submit_ns;
stats_record(&w->stats, lat, a->bs, s->is_write);
}
break;
}
for (int i = 0; i < n; i++) {
struct req_slot *s = comps[i].user_data;
if (!s) {
outstanding--;
continue; /* flush completion */
}
if (comps[i].ret != 0) {
w->stats.errors++;
/* still re-queue to maintain depth */
} else {
uint64_t lat = t - s->submit_ns;
stats_record(&w->stats, lat, a->bs, s->is_write);
}
/* flush after N writes */
if (a->sync_n > 0 && s->is_write) {
w->write_counter++;
if (w->write_counter >= a->sync_n) {
w->write_counter = 0;
blkioq_flush(q, NULL, 0);
outstanding++;
w->stats.flushes++;
}
}
/* Re-queue */
s->is_write = next_is_write(w);
s->offset = next_offset(w);
s->submit_ns = now_ns();
void *buf = base + (size_t)s->index * a->bs;
if (s->is_write)
blkioq_write(q, s->offset, buf, a->bs, s, 0);
else
blkioq_read(q, s->offset, buf, a->bs, s, 0);
}
}
/* Drain remaining in-flight IOs before returning */
while (outstanding > 0) {
int n = blkioq_do_io(q, comps, 1, depth, NULL);
if (n < 0)
break;
outstanding -= n;
}
free(slots);
free(comps);
return NULL;
}
/* ── Forward declarations for reporter ─────────────────────────────── */
static void format_iops(double iops, char *buf, size_t len);
static bool mode_is_mixed(enum rw_mode m);
static bool mode_is_write_only(enum rw_mode m);
/* ── Progress reporter thread ──────────────────────────────────────── */
struct reporter_ctx {
struct worker_ctx *workers;
struct bench_args *args;
uint64_t measure_start_ns; /* start of measurement (after ramp) */
atomic_bool stop;
};
static void *reporter_thread(void *arg)
{
struct reporter_ctx *r = arg;
struct bench_args *a = r->args;
int nj = a->numjobs;
int interval_ms = a->eta_interval * 1000;
bool is_mixed = mode_is_mixed(a->rw);
uint64_t measure_start = r->measure_start_ns;
/* Sleep through ramp period */
while (now_ns() < measure_start) {
if (atomic_load_explicit(&r->stop, memory_order_relaxed))
return NULL;
struct timespec ramp_ts = {0, 100 * 1000000L}; /* 100ms */
nanosleep(&ramp_ts, NULL);
}
/* Previous snapshot for delta computation */
uint64_t prev_ios = 0, prev_bytes = 0;
uint64_t prev_read_bytes = 0, prev_write_bytes = 0;
uint64_t prev_read_ios = 0, prev_write_ios = 0;
while (!atomic_load_explicit(&r->stop, memory_order_relaxed)) {
struct timespec ts = {
.tv_sec = interval_ms / 1000,
.tv_nsec = (long)(interval_ms % 1000) * 1000000L,
};
nanosleep(&ts, NULL);
if (atomic_load_explicit(&r->stop, memory_order_relaxed))
break;
/* Snapshot worker counters (relaxed atomics — no torn reads) */
uint64_t cur_ios = 0, cur_bytes = 0;
uint64_t cur_read_bytes = 0, cur_write_bytes = 0;
uint64_t cur_read_ios = 0, cur_write_ios = 0;
for (int i = 0; i < nj; i++) {
cur_ios += STAT_LOAD(r->workers[i].stats.ios_done);
cur_bytes += STAT_LOAD(r->workers[i].stats.bytes_done);
cur_read_bytes += STAT_LOAD(r->workers[i].stats.read_bytes);
cur_write_bytes += STAT_LOAD(r->workers[i].stats.write_bytes);
cur_read_ios += STAT_LOAD(r->workers[i].stats.read_ios);
cur_write_ios += STAT_LOAD(r->workers[i].stats.write_ios);
}
uint64_t t = now_ns();
double elapsed_sec = (double)(t - measure_start) / (double)NS_PER_SEC;
/* Delta stats for this interval */
uint64_t d_ios = cur_ios - prev_ios;
uint64_t d_bytes = cur_bytes - prev_bytes;
double interval_sec = (double)a->eta_interval;
double iops = (double)d_ios / interval_sec;
double bw_mib = (double)d_bytes / interval_sec / (1024.0 * 1024.0);
/* Progress and ETA */
double pct = elapsed_sec / (double)a->runtime * 100.0;
if (pct > 100.0)
pct = 100.0;
double remain = (double)a->runtime - elapsed_sec;
if (remain < 0)
remain = 0;
int eta_min = (int)remain / 60;
int eta_sec = (int)remain % 60;
char iops_str[32];
format_iops(iops, iops_str, sizeof(iops_str));
if (is_mixed) {
uint64_t d_rbytes = cur_read_bytes - prev_read_bytes;
uint64_t d_wbytes = cur_write_bytes - prev_write_bytes;
uint64_t d_rios = cur_read_ios - prev_read_ios;
uint64_t d_wios = cur_write_ios - prev_write_ios;
double r_bw = (double)d_rbytes / interval_sec / (1024.0 * 1024.0);
double w_bw = (double)d_wbytes / interval_sec / (1024.0 * 1024.0);
char r_iops_str[32], w_iops_str[32];
format_iops((double)d_rios / interval_sec, r_iops_str, sizeof(r_iops_str));
format_iops((double)d_wios / interval_sec, w_iops_str, sizeof(w_iops_str));
fprintf(stderr,
"[%3.0fs][%5.1f%%] r=%.0fMiB/s %s IOPS, "
"w=%.0fMiB/s %s IOPS [eta %02dm:%02ds]\n",
elapsed_sec, pct, r_bw, r_iops_str, w_bw, w_iops_str, eta_min,
eta_sec);
} else {
const char *dir = mode_is_write_only(a->rw) ? "w" : "r";
fprintf(stderr,
"[%3.0fs][%5.1f%%] %s=%.0fMiB/s, %s IOPS [eta %02dm:%02ds]\n",
elapsed_sec, pct, dir, bw_mib, iops_str, eta_min, eta_sec);
}
prev_ios = cur_ios;
prev_bytes = cur_bytes;
prev_read_bytes = cur_read_bytes;
prev_write_bytes = cur_write_bytes;
prev_read_ios = cur_read_ios;
prev_write_ios = cur_write_ios;
}
return NULL;
}