-
Notifications
You must be signed in to change notification settings - Fork 0
/
mediatester.c
1169 lines (1120 loc) · 39.4 KB
/
mediatester.c
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
/* Media tester
*
* Fills a block device or data stream with reprocucible pseudorandom bytes or
* reads such a block device or data stream to verify the same pseudorandom
* bytes written before are still present. Both write and verification mode
* try to make use of the available CPU cores to create the pseudorandom data
* data as quickly as possible in parallel, and double buffering is employed
* to allow disk I/O to run (mostly) in parallel, too. */
#define VERSION_INFO \
"Version 2022.42\n" \
"Copyright (c) 2017-2022 Guenther Brunthaler. All rights reserved." \
"\n" \
"This program is free software.\n" \
"Distribution is permitted under the terms of the GPLv3."
#if !defined __STDC_VERSION__ || __STDC_VERSION__ < 199901
#error "This source file requires a C99 compliant C compiler!"
#endif
#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS < 64
#undef _FILE_OFFSET_BITS
#endif
#ifndef _FILE_OFFSET_BITS
/* Feature-test macro which, if supported by the platform (such as glibc on
* 32-bit Linux), will make lseek() and off_t support 64 bit offsets. */
#define _FILE_OFFSET_BITS 64
#endif
#ifndef _GNU_SOURCE
/* Enable the following required definitions:
* MAP_ANONYMOUS <sys/mman.h>
* SYS_ioprio_set <sys/syscall.h> */
#define _GNU_SOURCE
#endif
#include <r4g/r4g_u0ywydbuiziuzssqsi5l0mdid.h>
#include <dim_sdbrke8ae851uitgzm4nv3ea2.h>
#include <getopt_nh7lll77vb62ycgwzwf30zlln.h>
#include <pearson.h>
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>
#include <stddef.h>
#include <assert.h>
#include <errno.h>
#include <signal.h>
#include <time.h>
#include <stdarg.h>
#include <inttypes.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/times.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/resource.h>
#include <linux/fs.h>
#include <linux/ioprio.h>
/* TWO such buffers will be allocated. */
#define APPROXIMATE_BUFFER_SIZE (16ul << 20)
/* Global variables, grouped in a struct for easier tracking. */
static struct {
enum {
mode_write, mode_verify, mode_compare, mode_diff
} mode;
int shutdown_requested /* = 0; */;
uint8_t *shared_buffer, *shared_buffers[2];
uint8_t const *shared_buffer_stop;
size_t blksz /* = 0; */;
size_t work_segments;
size_t work_segment_sz;
size_t shared_buffer_size;
uint_fast64_t pos; /* Current position for next working segment. */
uint_fast64_t start_pos; /* Initial starting offset. */
uint_fast64_t first_error_pos; /* Only valid if num_errors != 0. */
uint_fast32_t num_errors; /* Count of differing bytes. */
unsigned active_threads; /* Number of threads not waiting for more work. */
pthread_mutex_t workers_mutex; /* Serialize access to THIS struct. */
pthread_cond_t workers_wakeup_call; /* Wake up threads for more work. */
pthread_key_t resource_context; /* For r4g_c1(). */
} tgs; /* Thread global storage */
static char const msg_malloc_error[]= {
"Memory allocation failure!"
};
r4g *r4g_c1(void) {
r4g *rc;
if (rc= pthread_getspecific(tgs.resource_context)) return rc;
abort();
}
char const *new_r4g_thread_context_c0(void) {
r4g *rc;
if (!(rc= calloc(1, sizeof *rc))) return msg_malloc_error;
if (!pthread_setspecific(tgs.resource_context, rc)) return 0;
return "Could not set up per-thread resource context!";
}
static char const msg_exotic_error[]= {
"Unexpected error! (This should normally never happen.)"
};
static char const msg_write_error[]= {"Write error!"};
static void pthread_mutex_lock_c1(pthread_mutex_t *mutex) {
if (!pthread_mutex_lock(mutex)) return;
ERROR_C1("Could not lock mutex!");
}
static void pthread_cond_broadcast_c1(pthread_cond_t *cond) {
if (!pthread_cond_broadcast(cond)) return;
ERROR_C1("Could not wake up worker threads!");
}
static void pthread_cond_wait_c1(
pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex
) {
if (!pthread_cond_wait(cond, mutex)) return;
ERROR_C1("Could not wait for condition variable!");
}
static void pthread_mutex_unlock_c1(pthread_mutex_t *mutex) {
if (!pthread_mutex_unlock(mutex)) return;
ERROR_C1("Could not unlock mutex!");
}
static void *malloc_c1(size_t bytes) {
void *buffer;
if (!(buffer= malloc(bytes))) ERROR_C1(msg_malloc_error);
return buffer;
}
static void printf_c1(char const *format, ...) {
va_list args;
int error;
va_start(args, format);
error= vprintf(format, args) < 0;
va_end(args);
if (error) ERROR_C1(msg_write_error);
}
static void fprintf_c1(FILE *s, char const *format, ...) {
va_list args;
int error;
va_start(args, format);
error= vfprintf(s, format, args) < 0;
va_end(args);
if (error) ERROR_C1(msg_write_error);
}
struct mutex_resource {
int procured;
pthread_mutex_t *mutex;
r4g_dtor dtor, *saved;
};
static void mutex_unlocker_dtor(r4g *rc) {
R4G_DEFINE_INIT_RPTR(struct mutex_resource, *r=, rc, dtor);
int procured= r->procured;
pthread_mutex_t *mutex= r->mutex;
rc->rlist= r->saved;
free(r);
if (procured) pthread_mutex_unlock_c1(mutex);
}
/* Returns the address of a status variable which must reflect the current
* locking state of the mutex. Zero means unlocked (and is also the initial
* setting). The caller needs to update this status in order to track the
* current state of the mutex. A resource is added to the current resource
* list which will unlock the mutex when the status indicates it is currently
* locked at the time when the destructor of the resource will be invoked. */
static int *mutex_unlocker_c5(pthread_mutex_t *mutex) {
r4g *rc= r4g_c1();
struct mutex_resource *r= malloc_c1(sizeof *r);
r->procured= 0;
r->mutex= mutex;
r->saved= rc->rlist; r->dtor= &mutex_unlocker_dtor; rc->rlist= &r->dtor;
return &r->procured;
}
static void *writer_thread(void *unused_dummy) {
r4g *rc;
int *workers_mutex_procured;
(void)unused_dummy;
{
char const *error;
if (error= new_r4g_thread_context_c0()) return (void *)error;
}
rc= r4g_c1();
workers_mutex_procured= mutex_unlocker_c5(&tgs.workers_mutex);
assert(!*workers_mutex_procured);
/* Lock the mutex before acessing the global work state variables. */
pthread_mutex_lock_c1(&tgs.workers_mutex);
*workers_mutex_procured= 1;
++tgs.active_threads; /* We just have started. */
/* Thread main loop. */
for (;;) {
assert(*workers_mutex_procured);
assert(tgs.active_threads >= 1);
if (tgs.shutdown_requested) {
shutdown:
--tgs.active_threads;
break;
}
if (tgs.shared_buffer == tgs.shared_buffer_stop) {
/* All worker segments have already been assigned to some
* thread. */
if (tgs.active_threads == 1) {
/* And we are the first/last thread running! Let's do I/O then.
* We switch the buffer first, and let then the other threads
* fill the next buffer while we write out the old buffer's
* contents. */
uint8_t const *out;
size_t left;
uint_fast64_t pos;
/* Switch buffers so other threads can resume working. */
if (
tgs.shared_buffer - (left= tgs.shared_buffer_size)
== tgs.shared_buffers[0]
) {
out= tgs.shared_buffers[0];
tgs.shared_buffer= tgs.shared_buffers[1];
} else {
out= tgs.shared_buffers[1];
assert(tgs.shared_buffer - left == out);
tgs.shared_buffer= tgs.shared_buffers[0];
}
pos= tgs.pos - left;
tgs.shared_buffer_stop= tgs.shared_buffer + left;
assert(*workers_mutex_procured);
*workers_mutex_procured= 0;
pthread_mutex_unlock_c1(&tgs.workers_mutex);
/* Wake up the other threads so they can start working on the
* other buffer. */
pthread_cond_broadcast_c1(&tgs.workers_wakeup_call);
/* Write out the old buffer while the other threads already fill
* the new buffer. */
for (;;) {
ssize_t written;
if ((written= write(STDOUT_FILENO, out, left)) <= 0) {
if (written == 0) break;
if (written != -1) {
unlikely_error: ERROR_C1(msg_exotic_error);
}
/* The write() has failed. Examine why. */
switch (errno) {
case ENOSPC: /* We filled up the filesystem. */
case EPIPE: /* Output stream has ended. */
case EDQUOT: /* Quota has been reached. */
case EFBIG: /* Maximum file/device size reached. */
/* Those are all considered "good" reasons why the
* write() has failed. */
assert(left > 0);
goto finished;
case EINTR: continue; /* Interrupted write(). */
}
assert(pos >= tgs.start_pos);
(void)fprintf(
stderr
, "Write error at byte offset %" PRIuFAST64 "!\n"
"(Output did start at byte offset %" PRIuFAST64 ")\n"
"Total bytes written so far: %" PRIuFAST64 "\n"
, pos, tgs.start_pos, pos - tgs.start_pos
);
error_c1(rc, msg_write_error);
}
if ((size_t)written > left) goto unlikely_error;
out+= (size_t)written;
pos+= (uint_fast64_t)written;
left-= (size_t)written;
}
finished:
assert(!*workers_mutex_procured);
pthread_mutex_lock_c1(&tgs.workers_mutex);
*workers_mutex_procured= 1;
if (left) {
/* Output data sink does not accept any more data - we are
* done. Try to write some statistics to standard error. */
assert(pos >= tgs.start_pos);
fprintf_c1(
stderr
, "\n"
"Success!\n"
"\n"
"Output stopped at byte offset %" PRIuFAST64 "!\n"
"(Output did start at byte offset %" PRIuFAST64 ")\n"
"Total bytes written: %" PRIuFAST64 "\n"
, pos, tgs.start_pos, pos - tgs.start_pos
);
/* Initiate successful termination. */
tgs.shutdown_requested= 1;
/* Make sure any sleeping threads will wake up to learn
* about the shutdown request. */
pthread_cond_broadcast_c1(&tgs.workers_wakeup_call);
goto shutdown;
}
} else {
assert(tgs.active_threads >= 2);
/* We have nothing to do, but other worker threads are still
* active. Just wait until there is again possibly something to
* do. */
--tgs.active_threads;
assert(*workers_mutex_procured);
*workers_mutex_procured= 0;
/* Unlock mutex, wait for a broadcast, then lock mutex again. */
pthread_cond_wait_c1(
&tgs.workers_wakeup_call, &tgs.workers_mutex
);
*workers_mutex_procured= 1;
++tgs.active_threads;
}
} else {
/* There is more work to do. Seize the next work segment. */
pearnd_offset po;
uint8_t *work_segment= tgs.shared_buffer;
tgs.shared_buffer+= tgs.work_segment_sz;
pearnd_seek(&po, tgs.pos);
tgs.pos+= tgs.work_segment_sz;
/* Allow other threads to seize work segments as well. */
*workers_mutex_procured= 0;
pthread_mutex_unlock_c1(&tgs.workers_mutex);
/* Do every worker thread's primary job: Process its work
* segment. */
pearnd_generate(work_segment, tgs.work_segment_sz, &po);
/* See whether we can get the next job. */
pthread_mutex_lock_c1(&tgs.workers_mutex);
*workers_mutex_procured= 1;
}
}
release_c1(rc);
return (void *)rc->static_error_message;
}
static void *reader_thread(void *unused_dummy) {
r4g *rc;
int *workers_mutex_procured;
(void)unused_dummy;
{
char const *error;
if (error= new_r4g_thread_context_c0()) return (void *)error;
}
rc= r4g_c1();
workers_mutex_procured= mutex_unlocker_c5(&tgs.workers_mutex);
assert(!*workers_mutex_procured);
/* Lock the mutex before acessing the global work state variables. */
pthread_mutex_lock_c1(&tgs.workers_mutex);
*workers_mutex_procured= 1;
++tgs.active_threads; /* We just have started. */
/* Thread main loop. */
for (;;) {
assert(*workers_mutex_procured);
assert(tgs.active_threads >= 1);
error_c1(rc, "Verify mode has not been implemented yet!");
}
release_c1(rc);
return (void *)rc->static_error_message;
}
static uint_fast64_t atou64(char const *numeric) {
uint_fast64_t result;
int converted;
if (
sscanf(numeric, "%" SCNuFAST64 "%n", &result, &converted) != 1
|| (size_t)converted != strlen(numeric)
) {
ERROR_C1("Invalid number!");
}
return result;
}
struct FILE_mallocated_resource {
FILE *handle;
r4g_dtor dtor, *saved;
};
static void FILE_mallocated_dtor(r4g *rc) {
R4G_DEFINE_INIT_RPTR(struct FILE_mallocated_resource, *r=, rc, dtor);
FILE *fh= r->handle;
rc->rlist= r->saved;
free(r);
if (fh && fclose(fh)) error_c1(rc, "Error while closing file!");
}
static void load_seed(char const *seed_file) {
struct FILE_mallocated_resource *f= malloc_c1(sizeof *f);
FILE *fh;
r4g *rc;
r4g_dtor *marker;
f->saved= marker= (rc= r4g_c1())->rlist; f->dtor= &FILE_mallocated_dtor;
rc->rlist= &f->dtor;
if (!(f->handle= fh= fopen(seed_file, "rb"))) {
rd_err: error_c1(rc, "Cannot read seed file!");
}
{
#define MAX_SEED_BYTES 256
char seed[MAX_SEED_BYTES + 1]; /* 1 byte larger than actually allowed. */
#undef MAX_SEED_BYTES
size_t read;
if ((read= fread(seed, sizeof *seed, DIM(seed), fh)) == DIM(seed)) {
error_c1(
rc, "Key file for seeding the PRNG is larger than supported!"
);
}
if (ferror(fh)) goto rd_err;
assert(feof(fh));
if (!read) error_c1(rc, "Seed file must not be empty!");
pearnd_init(seed, read);
}
release_to_c1(rc, marker);
}
static void slow_comparison(void) {
uint_fast64_t differences= 0;
uint_fast64_t pos;
pearnd_offset po;
uint8_t *const reference= tgs.shared_buffers[1];
/* Write a header. */
fprintf_c1(stderr, "\nEX RD A %-8s BYTE OFFSET\n", "XOR");
pearnd_seek(&po, pos= tgs.pos);
for (;;) {
uint8_t *in= tgs.shared_buffer;
size_t left= tgs.shared_buffer_size;
/* Read the next buffer full of input data. */
for (;;) {
ssize_t did_read;
if ((did_read= read(STDIN_FILENO, in, left)) <= 0) {
if (did_read == 0) break;
if (did_read != -1) {
unlikely_error: ERROR_C1(msg_exotic_error);
}
/* The write() has failed. Examine why. */
switch (errno) {
case EFBIG: /* Maximum file/device size reached. */
/* This is considered a "good" reason why the read() has
* failed. */
assert(left > 0);
goto finished;
case EINTR: continue; /* Interrupted read(). */
}
assert(pos >= tgs.start_pos);
(void)fprintf(
stderr
, "Read error at byte offset %" PRIuFAST64 "!\n"
"(Reading did start at byte offset %" PRIuFAST64 ")\n"
"Total bytes read so far: %" PRIuFAST64 "\n"
, pos, tgs.start_pos, pos - tgs.start_pos
);
ERROR_C1("Read error!");
}
if ((size_t)did_read > left) goto unlikely_error;
in+= (size_t)did_read;
pos+= (uint_fast64_t)did_read;
left-= (size_t)did_read;
}
assert(left <= tgs.shared_buffer_size);
pos-= left= tgs.shared_buffer_size - left;
if (left == 0) break;
assert(left >= 1);
/* Generate a full buffer of comparison data. */
pearnd_generate(reference, tgs.shared_buffer_size, &po);
/* Compare buffer contents. */
in= tgs.shared_buffer;
{
size_t i;
for (i= 0; i < left; ++i) {
if (tgs.mode == mode_diff && in[i] == reference[i]) continue;
{
char octet[8];
unsigned rd= in[i];
{
unsigned xor= rd ^ reference[i];
unsigned i, mask= 1;
for (i= 8; i--; mask+= mask) {
octet[i]= xor & mask ? '1' : '0';
}
if (xor) ++differences;
}
printf_c1(
"%02x %02x %c %8s %" PRIuFAST64 "\n"
, (unsigned)reference[i], rd
, rd >= 0x20 && rd < 0x7f ? rd : '.'
, octet, pos + i
);
}
}
}
pos+= left;
}
finished:
assert(pos >= tgs.start_pos);
fprintf_c1(
stderr
, "\n"
"Comparison complete!\n"
"\n"
"Reading stopped at byte offset %" PRIuFAST64 "!\n"
"(Reading did start at byte offset %" PRIuFAST64 ")\n"
"Different bytes encountered: %" PRIuFAST64 "\n"
"Total bytes compared: %" PRIuFAST64 "\n"
, pos, tgs.start_pos, differences, pos - tgs.start_pos
);
}
static char const usage[]=
"Usage: %s [ <options> ... ] <mode> <seed_file> [ <starting_offset> ]\n"
"\n"
"where\n"
"\n"
"<mode>: One of the following commands\n"
" write - write PRNG stream to standard output at offset\n"
" verify - compare PRNG data against stream from standard input\n"
" compare - Like verify but show every byte ('should' and 'is')\n"
" diff - Like compare but report only differing bytes\n"
"<seed_file>: a binary (or text) file up to 256 bytes PRNG seed\n"
"<starting_offset>: byte offset where to start writing/verifying\n"
"\n"
"Standard input or output should be a block device or a file. When\n"
"writing to a file, writing stops when there is no more free space\n"
"left in the filesystem containing the file, or when the file has\n"
"reached the maximum file size supported by the filesystem.\n"
"\n"
"The <seed_file> determines which pseudo-random sequence of bytes\n"
"will be written to or will be expected to be read from the file\n"
"or device. The same <seed_file> needs to be used for a 'write'\n"
"command and its matching 'verify' command.\n"
"\n"
"The contents of <seed_file> are arbitrary and should be created\n"
"by something like this:\n"
"\n"
"$ dd if=/dev/random bs=1 count=16 > my_seed_file.bin\n"
"\n"
"<options>:\n"
"\n"
"-t <n>: Use <n> CPU threads for write/verify commands instead of\n"
"the autodetected number of available processor cores\n"
"\n"
"-N: Don't be nice. By default, the program will behave as if it\n"
"had been invoked via 'nice' and 'ionice -n 6'. With -N, the\n"
"program will not do this and keep its initial niceness settings.\n"
"\n"
"-F: Don't flush the device's cache when reading from a block\n"
"device. This makes comparison of small block devices less\n"
"reliable, because one never can be sure whether the data read\n"
"came actually from the device or rather from the cache. However,\n"
"flushing device buffers is a privileged operation, so\n"
"unprivileged users can never read from a block device without\n"
"this option, even if they are the owner of the device.\n"
"\n"
"-V: Display version information\n"
"\n"
"-h: Display this help\n"
"\n"
"General usage procedure:\n"
"\n"
"1. Generate a seed file to be used with all following steps\n"
"\n"
"2. Fill the block device to be tested using the 'write' command\n"
"\n"
" 'write' can also fill a filesystem, using up all space. This\n"
" allows to check how much uncompressible data can really be\n"
" stored there, and whether the file has actually been written\n"
" correctly (i. e. whether the filesystem works as it should).\n"
"\n"
"3. Use 'verify' command to check for differences\n"
"\n"
" This reads back the data which has been written before and\n"
" checks whether it is still the same. This should be the case\n"
" if everything is fine.\n"
" \n"
" If it is not, 'verify' stops and reports the offset where the\n"
" first different byte was detected.\n"
" \n"
" Differences mean that the storage medium or filesystem either\n"
" does not reliably write data, or it does not reliably read\n"
" data, or it is lying about its supposed storage capacity.\n"
" Either way, such differences are always a bad sign.\n"
" \n"
" To scan for more differences, you can run the 'verify' command\n"
" again, starting at a higher byte offset.\n"
"\n"
"4. If 'verify' stopped at differences, use 'compare' or 'diff'\n"
" to show them.\n"
"\n"
" For every byte offset, 'compare' shows the byte value which\n"
" was expected, the byte value actually read back, the ASCII\n"
" character corresponding to the value read back, and the bit\n"
" differences (XOR) between both bytes.\n"
" \n"
" 'diff' does the same, but only writes output lines for bytes\n"
" which actually differ. (It will therefore never display the\n"
" XOR-value '00000000'.)\n"
" \n"
" This means 'diff' does basically the same as 'verify', but it\n"
" is much, much slower. And unlike 'verify', 'diff' will not\n"
" stop comparing when differences have been found.\n"
" \n"
" Therefore, always use 'verify' first to determine where bytes\n"
" start to differ, then use 'diff' or 'compare' to look what\n"
" exactly is different.\n"
" \n"
" 'compare' and 'diff' do not stop output by themselves before\n"
" the end of the file/device has been reached. Their output\n"
" should therefore be piped through 'head' or 'more' in order\n"
" to limit the number of lines displayed.\n"
"\n"
VERSION_INFO "\n"
;
struct error_reporting_static_resource {
r4g_dtor dtor, *saved;
char const *argv0;
};
static void error_reporting_dtor(r4g *rc) {
char const *em= 0;
R4G_DEFINE_INIT_RPTR( \
struct error_reporting_static_resource, *c=, rc, dtor \
);
rc->rlist= c->saved;
if (rc->errors) {
if (!(em= rc->static_error_message)) em= msg_exotic_error;
if (!*em) em= 0;
}
if (em) {
(void)fprintf(stderr, "%s failed: %s\n", c->argv0, em);
clear_error_c1(rc);
}
}
struct minimal_resource {
r4g_dtor dtor, *saved;
};
static void resource_context_thread_key_dtor(r4g *rc) {
R4G_DEFINE_INIT_RPTR(struct minimal_resource, *r=, rc, dtor);
/* Clear out slot for main thread context because it has not been
* allocated dynamically and should therefore not be passed to the
* thread key's per-thread slot destructor. */
int bad= pthread_setspecific(tgs.resource_context, 0);
rc->rlist= r->saved;
if (pthread_key_delete(tgs.resource_context) || bad) {
error_c1(rc, msg_exotic_error);
}
}
struct pthread_mutex_static_resource {
pthread_mutex_t *mutex;
r4g_dtor dtor, *saved;
};
static void pthread_mutex_static_dtor(r4g *rc) {
R4G_DEFINE_INIT_RPTR(struct pthread_mutex_static_resource, *r=, rc, dtor);
rc->rlist= r->saved;
if (pthread_mutex_destroy(r->mutex)) ERROR_C1(msg_exotic_error);
}
struct pthread_cond_static_resource {
pthread_cond_t *cond;
r4g_dtor dtor, *saved;
};
static void pthread_cond_static_dtor(r4g *rc) {
R4G_DEFINE_INIT_RPTR(struct pthread_cond_static_resource, *r=, rc, dtor);
rc->rlist= r->saved;
if (pthread_cond_destroy(r->cond)) ERROR_C1(msg_exotic_error);
}
static void shared_buffers_dtor(r4g *rc) {
{
unsigned i;
for (i= (unsigned)DIM(tgs.shared_buffers); i--; ) {
if (tgs.shared_buffers[i]) {
void *old= tgs.shared_buffers[i]; tgs.shared_buffers[i]= 0;
if (munmap(old, tgs.shared_buffer_size)) {
error_c1(rc, msg_exotic_error);
}
}
}
}
{
R4G_DEFINE_INIT_RPTR(struct minimal_resource, *r=, rc, dtor);
rc->rlist= r->saved;
}
}
struct cancel_threads_static_resource {
unsigned threads;
pthread_t *tid;
char *tvalid;
r4g_dtor dtor, *saved;
};
static void cancel_threads_dtor(r4g *rc) {
R4G_DEFINE_INIT_RPTR(struct cancel_threads_static_resource, *r=, rc, dtor);
{
unsigned i;
for (i= r->threads; i--; ) {
if (r->tvalid[i]) {
r->tvalid[i]= 0;
if (rc->errors) {
if (pthread_cancel(r->tid[i])) {
error_c1(rc, "Could not terminate child thread!");
}
}
{
void *thread_error;
if (pthread_join(r->tid[i], &thread_error)) {
error_c1(
rc, "Failure waiting for child thread to terminate!"
);
}
if (thread_error && thread_error != PTHREAD_CANCELED) {
error_c1(rc, thread_error);
}
}
}
}
}
rc->rlist= r->saved;
}
struct mallocated_resource {
void *buffer;
r4g_dtor dtor, *saved;
};
static void mallocated_dtor(r4g *rc) {
R4G_DEFINE_INIT_RPTR(struct mallocated_resource, *r=, rc, dtor);
void *buffer= r->buffer;
rc->rlist= r->saved;
free(r);
free(buffer);
}
static void *calloc_c5(size_t num_elements, size_t element_size) {
struct mallocated_resource *r= malloc_c1(sizeof *r);
r4g *rc;
r->saved= (rc= r4g_c1())->rlist;
r->dtor= &mallocated_dtor; rc->rlist= &r->dtor;
if (!(r->buffer= calloc(num_elements, element_size))) {
error_c1(rc, msg_malloc_error);
}
return r->buffer;
}
struct report_times_static_resource {
struct timespec started;
r4g_dtor dtor, *saved;
};
static void report_times(char const *name, time_t seconds) {
fprintf_c1(
stderr
, "%s\t%lu seconds = %.1f minutes = %.2f hours\n"
, name
, (unsigned long)seconds
, seconds / 60.
, seconds / (60. * 60)
);
}
static void report_times_dtor(r4g *rc) {
R4G_DEFINE_INIT_RPTR(struct report_times_static_resource, *r=, rc, dtor);
struct timespec real;
struct rusage ru;
rc->rlist= r->saved;
if (clock_gettime(CLOCK_MONOTONIC, &real) < 0) goto unlikely_error;
real.tv_sec-= r->started.tv_sec + (
real.tv_nsec < r->started.tv_nsec /* borrow */
);
if (getrusage(RUSAGE_SELF, &ru) < 0) unlikely_error: ERROR_C1(0);
fprintf_c1(stderr, "\n");
report_times("real", real.tv_sec);
report_times("user", ru.ru_utime.tv_sec);
report_times("sys", ru.ru_stime.tv_sec);
}
#define CEIL_DIV(num, den) (((num) + (den) - 1) / (den))
int main(int argc, char **argv) {
static unsigned threads;
static pthread_t *tid;
static char *tvalid;
static r4g m;
char const *argv0;
int never_flush= 0;
(void)setlocale(LC_ALL, ""); /* Enable locale if supported. */
{
static struct error_reporting_static_resource r;
r.argv0= argv0= argc ? argv[0] : "<unnamed program>";
r.saved= m.rlist; r.dtor= &error_reporting_dtor; m.rlist= &r.dtor;
}
if (pthread_key_create(&tgs.resource_context, free)) {
error_c1(
&m, "Could not allocate a new slot for thread-local storage!"
);
}
{
static struct minimal_resource r;
r.saved= m.rlist; r.dtor= &resource_context_thread_key_dtor;
m.rlist= &r.dtor;
}
if (pthread_setspecific(tgs.resource_context, &m)) {
error_c1(
&m, "Could not set error-handling context for main thread!"
);
}
{
int optind;
int be_nice= 1;
{
int opt, optpos;
char const *optarg;
optind= optpos= 0;
while (opt= getopt_simplest(&optind, &optpos, argc, argv)) {
switch (opt) {
case 't':
if (
!(
optarg= getopt_simplest_mand_arg(
&optind, &optpos, argc, argv
)
)
) {
getopt_simplest_perror_missing_arg(opt);
goto error_shown;
}
{
int converted;
if (
sscanf(
optarg, "%u%n", &threads, &converted
) != 1
|| (size_t)converted != strlen(optarg)
) {
error_c1(&m, "Invalid numeric option argument!");
}
}
break;
case 'N': be_nice= 0; break;
case 'V': printf_c1("%s\n", VERSION_INFO); goto cleanup;
case 'h': printf_c1(usage, argv0); goto cleanup;
case 'F': never_flush= 1; break;
default:
getopt_simplest_perror_opt(opt);
goto error_shown;
}
}
}
/* Process arguments. */
if (optind == argc) goto bad_arguments;
{
char const *cmd;
if (!strcmp(cmd= argv[optind++], "write")) tgs.mode= mode_write;
else if (!strcmp(cmd, "verify")) tgs.mode= mode_verify;
else if (!strcmp(cmd, "compare")) tgs.mode= mode_compare;
else if (!strcmp(cmd, "diff")) tgs.mode= mode_diff;
else goto bad_arguments;
}
if (optind == argc) goto bad_arguments;
load_seed(argv[optind++]);
if (optind < argc) {
tgs.pos= atou64(argv[optind++]);
}
if (optind != argc) {
bad_arguments:
{
FILE *out;
{
struct stat st;
out=
isatty(STDOUT_FILENO)
|| fstat(STDOUT_FILENO, &st) == 0 && S_ISFIFO(st.st_mode)
? stdout
: stderr
;
}
(void)fprintf(out, "%s\n\n", "Invalid arguments!");
(void)fprintf(out, usage, argv0);
}
error_shown:
m.static_error_message= "";
m.errors= 1;
goto cleanup;
}
if (be_nice) {
errno= 0;
if (nice(10) == -1 && errno) {
error_c1(
&m, "Could not make the process nice in terms of CPU usage!"
);
}
if (
/* Set second-lowest available best-effort I/O priority. This
* allows to user to set an even lower best-effort priority, even
* though by default all other processes will have a higher I/O
* priority. */
syscall(
SYS_ioprio_set, IOPRIO_WHO_PROCESS, getpid()
, IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 7 - 1))
) {
error_c1(
&m, "Could not make the process nice in terms of I/O priority!"
);
}
}
}
/* Ignore SIGPIPE because we want it as a possible errno from write(). */
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) goto unlikely_error;
/* Preset global variables for interthread communication. */
tgs.work_segments= 64;
if (pthread_mutex_init(&tgs.workers_mutex, 0)) goto unlikely_error;
{
static struct pthread_mutex_static_resource r;
r.mutex= &tgs.workers_mutex;
r.saved= m.rlist; r.dtor= &pthread_mutex_static_dtor;
m.rlist= &r.dtor;
}
if (pthread_cond_init(&tgs.workers_wakeup_call, 0)) goto unlikely_error;
{
static struct pthread_cond_static_resource r;
r.cond= &tgs.workers_wakeup_call;
r.saved= m.rlist; r.dtor= &pthread_cond_static_dtor;
m.rlist= &r.dtor;
}
/* Determine the best I/O block size, defaulting to the value preset
* earlier. */
{
struct stat st;
int fd;
mode_t mode;
if (
fstat(
fd= tgs.mode != mode_write ? STDIN_FILENO : STDOUT_FILENO
, &st
)
) {
error_c1(&m, "Cannot examine file descriptor to be used for I/O!");
}
if (S_ISBLK(mode= st.st_mode)) {
/* It's a block device. */
{
int logical;
if (ioctl(fd, BLKSSZGET, &logical) < 0) {
error_c1(&m, "Unable to determine logical sector size!");
}
if ((size_t)logical > tgs.blksz) tgs.blksz= (size_t)logical;
}
{
int physical;
if (ioctl(fd, BLKPBSZGET, &physical) < 0) {
error_c1(&m, "Unable to determine physical sector size!");
}
if ((size_t)physical > tgs.blksz) tgs.blksz= (size_t)physical;
}
{
int optimal;
if (ioctl(fd, BLKIOOPT, &optimal) < 0) {
error_c1(&m, "Unable to determine optimal sector size!");
}
if ((size_t)optimal > tgs.blksz) tgs.blksz= (size_t)optimal;
}
if (
!never_flush && tgs.mode != mode_write && ioctl(fd, BLKFLSBUF) < 0
) {
error_c1(
&m, "Unable to flush device buffer before starting operation!"
);
}
}
if (!tgs.blksz) {
/* Some other kind of data source/sink. Assume the maximum of the
* MMU page size, the atomic pipe size and the fallback value. */
long page_size;
if ((page_size= sysconf(_SC_PAGESIZE)) == -1) {
unlikely_error: error_c1(&m, msg_exotic_error);
}
if ((size_t)page_size > tgs.blksz) tgs.blksz= (size_t)page_size;
if (PIPE_BUF > tgs.blksz) tgs.blksz= PIPE_BUF;
}
}
{
size_t bmask= 512; /* <blksz> must be a power of 2 >= this value. */
while (bmask < tgs.blksz) {
size_t nmask;
if (!((nmask= bmask + bmask) > bmask)) {
error_c1(&m, "Could not determine a suitable I/O block size");
}
bmask= nmask;
}
tgs.blksz= bmask;
}
if (tgs.start_pos= tgs.pos) {