t/read-to-pipe-async: synchronization fixes
[fio.git] / t / read-to-pipe-async.c
CommitLineData
6d5a9bc2
JA
1/*
2 * Read a file and write the contents to stdout. If a given read takes
3 * longer than 'max_us' time, then we schedule a new thread to handle
4 * the next read. This avoids the coordinated omission problem, where
5 * one request appears to take a long time, but in reality a lot of
6 * requests would have been slow, but we don't notice since new submissions
7 * are not being issued if just 1 is held up.
8 *
9 * One test case:
10 *
11 * $ time (./read-to-pipe-async -f randfile.gz | gzip -dc > outfile; sync)
12 *
13 * This will read randfile.gz and log the latencies of doing so, while
14 * piping the output to gzip to decompress it. Any latencies over max_us
15 * are logged when they happen, and latency buckets are displayed at the
16 * end of the run
17 *
18 * gcc -Wall -g -O2 -o read-to-pipe-async read-to-pipe-async.c -lpthread
19 *
20 * Copyright (C) 2016 Jens Axboe
21 *
22 */
23#include <stdio.h>
24#include <stdlib.h>
25#include <unistd.h>
26#include <fcntl.h>
27#include <sys/time.h>
28#include <sys/types.h>
29#include <sys/stat.h>
30#include <inttypes.h>
31#include <string.h>
32#include <pthread.h>
33#include <errno.h>
34#include <assert.h>
27386101 35#include <time.h>
6d5a9bc2
JA
36
37#include "../flist.h"
38
39static int bs = 4096;
40static int max_us = 10000;
41static char *file;
42static int separate_writer = 1;
43
44#define PLAT_BITS 8
45#define PLAT_VAL (1 << PLAT_BITS)
46#define PLAT_GROUP_NR 19
47#define PLAT_NR (PLAT_GROUP_NR * PLAT_VAL)
48#define PLAT_LIST_MAX 20
49
50struct stats {
51 unsigned int plat[PLAT_NR];
52 unsigned int nr_samples;
53 unsigned int max;
54 unsigned int min;
55 unsigned int over;
56};
57
58static double plist[PLAT_LIST_MAX] = { 50.0, 75.0, 90.0, 95.0, 99.0, 99.5, 99.9, 99.99, 99.999, 99.9999, };
59
60struct thread_data {
61 int exit;
62 int done;
63 pthread_mutex_t lock;
64 pthread_cond_t cond;
65 pthread_mutex_t done_lock;
66 pthread_cond_t done_cond;
67 pthread_t thread;
68};
69
70struct writer_thread {
71 struct flist_head list;
72 struct flist_head done_list;
73 struct stats s;
74 struct thread_data thread;
75};
76
77struct reader_thread {
78 struct flist_head list;
79 struct flist_head done_list;
80 int started;
81 int busy;
82 int write_seq;
83 struct stats s;
84 struct thread_data thread;
85};
86
87struct work_item {
88 struct flist_head list;
89 void *buf;
90 size_t buf_size;
91 off_t off;
92 int fd;
93 int seq;
94 struct writer_thread *writer;
95 struct reader_thread *reader;
96 pthread_mutex_t lock;
97 pthread_cond_t cond;
98 pthread_t thread;
99};
100
101static struct reader_thread reader_thread;
102static struct writer_thread writer_thread;
103
104uint64_t utime_since(const struct timeval *s, const struct timeval *e)
105{
106 long sec, usec;
107 uint64_t ret;
108
109 sec = e->tv_sec - s->tv_sec;
110 usec = e->tv_usec - s->tv_usec;
111 if (sec > 0 && usec < 0) {
112 sec--;
113 usec += 1000000;
114 }
115
116 if (sec < 0 || (sec == 0 && usec < 0))
117 return 0;
118
119 ret = sec * 1000000ULL + usec;
120
121 return ret;
122}
123
124static struct work_item *find_seq(struct writer_thread *w, unsigned int seq)
125{
126 struct work_item *work;
127 struct flist_head *entry;
128
129 if (flist_empty(&w->list))
130 return NULL;
131
132 flist_for_each(entry, &w->list) {
133 work = flist_entry(entry, struct work_item, list);
134 if (work->seq == seq)
135 return work;
136 }
137
138 return NULL;
139}
140
141static unsigned int plat_val_to_idx(unsigned int val)
142{
143 unsigned int msb, error_bits, base, offset;
144
145 /* Find MSB starting from bit 0 */
146 if (val == 0)
147 msb = 0;
148 else
149 msb = sizeof(val)*8 - __builtin_clz(val) - 1;
150
151 /*
152 * MSB <= (PLAT_BITS-1), cannot be rounded off. Use
153 * all bits of the sample as index
154 */
155 if (msb <= PLAT_BITS)
156 return val;
157
158 /* Compute the number of error bits to discard*/
159 error_bits = msb - PLAT_BITS;
160
161 /* Compute the number of buckets before the group */
162 base = (error_bits + 1) << PLAT_BITS;
163
164 /*
165 * Discard the error bits and apply the mask to find the
166 * index for the buckets in the group
167 */
168 offset = (PLAT_VAL - 1) & (val >> error_bits);
169
170 /* Make sure the index does not exceed (array size - 1) */
171 return (base + offset) < (PLAT_NR - 1) ?
172 (base + offset) : (PLAT_NR - 1);
173}
174
175/*
176 * Convert the given index of the bucket array to the value
177 * represented by the bucket
178 */
179static unsigned int plat_idx_to_val(unsigned int idx)
180{
181 unsigned int error_bits, k, base;
182
183 assert(idx < PLAT_NR);
184
185 /* MSB <= (PLAT_BITS-1), cannot be rounded off. Use
186 * all bits of the sample as index */
187 if (idx < (PLAT_VAL << 1))
188 return idx;
189
190 /* Find the group and compute the minimum value of that group */
191 error_bits = (idx >> PLAT_BITS) - 1;
192 base = 1 << (error_bits + PLAT_BITS);
193
194 /* Find its bucket number of the group */
195 k = idx % PLAT_VAL;
196
197 /* Return the mean of the range of the bucket */
198 return base + ((k + 0.5) * (1 << error_bits));
199}
200
201static void add_lat(struct stats *s, unsigned int us, const char *name)
202{
203 int lat_index = 0;
204
205 if (us > s->max)
206 s->max = us;
207 if (us < s->min)
208 s->min = us;
209
210 if (us > max_us) {
211 fprintf(stderr, "%s latency=%u usec\n", name, us);
212 s->over++;
213 }
214
215 lat_index = plat_val_to_idx(us);
216 __sync_fetch_and_add(&s->plat[lat_index], 1);
217 __sync_fetch_and_add(&s->nr_samples, 1);
218}
219
220static int write_work(struct work_item *work)
221{
222 struct timeval s, e;
223 ssize_t ret;
224
225 gettimeofday(&s, NULL);
226 ret = write(STDOUT_FILENO, work->buf, work->buf_size);
227 gettimeofday(&e, NULL);
228 assert(ret == work->buf_size);
229
230 add_lat(&work->writer->s, utime_since(&s, &e), "write");
231 return work->seq + 1;
232}
233
28cacec4
JA
234static void thread_exiting(struct thread_data *thread)
235{
236 __sync_fetch_and_add(&thread->done, 1);
237 pthread_cond_signal(&thread->done_cond);
238}
239
6d5a9bc2
JA
240static void *writer_fn(void *data)
241{
242 struct writer_thread *wt = data;
243 struct work_item *work;
244 unsigned int seq = 1;
245
246 work = NULL;
247 while (!wt->thread.exit || !flist_empty(&wt->list)) {
248 pthread_mutex_lock(&wt->thread.lock);
249
250 if (work) {
251 flist_add_tail(&work->list, &wt->done_list);
252 work = NULL;
253 }
254
255 work = find_seq(wt, seq);
256 if (work)
257 flist_del_init(&work->list);
258 else
259 pthread_cond_wait(&wt->thread.cond, &wt->thread.lock);
260
261 pthread_mutex_unlock(&wt->thread.lock);
262
263 if (work)
264 seq = write_work(work);
265 }
266
28cacec4 267 thread_exiting(&wt->thread);
6d5a9bc2
JA
268 return NULL;
269}
270
271static void reader_work(struct work_item *work)
272{
273 struct timeval s, e;
274 ssize_t ret;
275 size_t left;
276 void *buf;
277 off_t off;
278
279 gettimeofday(&s, NULL);
280
281 left = work->buf_size;
282 buf = work->buf;
283 off = work->off;
284 while (left) {
285 ret = pread(work->fd, buf, left, off);
286 if (!ret) {
287 fprintf(stderr, "zero read\n");
288 break;
289 } else if (ret < 0) {
290 fprintf(stderr, "errno=%d\n", errno);
291 break;
292 }
293 left -= ret;
294 off += ret;
295 buf += ret;
296 }
297
298 gettimeofday(&e, NULL);
299
300 add_lat(&work->reader->s, utime_since(&s, &e), "read");
301
302 pthread_cond_signal(&work->cond);
303
304 if (separate_writer) {
305 pthread_mutex_lock(&work->writer->thread.lock);
306 flist_add_tail(&work->list, &work->writer->list);
307 pthread_mutex_unlock(&work->writer->thread.lock);
308 pthread_cond_signal(&work->writer->thread.cond);
309 } else {
310 struct reader_thread *rt = work->reader;
311 struct work_item *next = NULL;
312 struct flist_head *entry;
313
314 /*
315 * Write current work if it matches in sequence.
316 */
317 if (work->seq == rt->write_seq)
318 goto write_it;
319
320 pthread_mutex_lock(&rt->thread.lock);
321
322 flist_add_tail(&work->list, &rt->done_list);
323
324 /*
325 * See if the next work item is here, if so, write it
326 */
327 work = NULL;
328 flist_for_each(entry, &rt->done_list) {
329 next = flist_entry(entry, struct work_item, list);
330 if (next->seq == rt->write_seq) {
331 work = next;
332 flist_del(&work->list);
333 break;
334 }
335 }
336
337 pthread_mutex_unlock(&rt->thread.lock);
338
339 if (work) {
340write_it:
341 write_work(work);
342 __sync_fetch_and_add(&rt->write_seq, 1);
343 }
344 }
345}
346
347static void *reader_one_off(void *data)
348{
349 reader_work(data);
350 return NULL;
351}
352
353static void *reader_fn(void *data)
354{
355 struct reader_thread *rt = data;
356 struct work_item *work;
357
358 while (!rt->thread.exit || !flist_empty(&rt->list)) {
359 work = NULL;
360 pthread_mutex_lock(&rt->thread.lock);
361 if (!flist_empty(&rt->list)) {
362 work = flist_first_entry(&rt->list, struct work_item, list);
363 flist_del_init(&work->list);
364 } else
365 pthread_cond_wait(&rt->thread.cond, &rt->thread.lock);
366 pthread_mutex_unlock(&rt->thread.lock);
367
368 if (work) {
28cacec4 369 __sync_fetch_and_add(&rt->busy, 1);
6d5a9bc2 370 reader_work(work);
28cacec4 371 __sync_fetch_and_sub(&rt->busy, 1);
6d5a9bc2
JA
372 }
373 }
374
28cacec4 375 thread_exiting(&rt->thread);
6d5a9bc2
JA
376 return NULL;
377}
378
379static void queue_work(struct reader_thread *rt, struct work_item *work)
380{
381 if (!rt->started) {
382 pthread_mutex_lock(&rt->thread.lock);
383 flist_add_tail(&work->list, &rt->list);
384 pthread_mutex_unlock(&rt->thread.lock);
385
386 rt->started = 1;
387 pthread_create(&rt->thread.thread, NULL, reader_fn, rt);
388 } else if (!rt->busy && !pthread_mutex_trylock(&rt->thread.lock)) {
389 flist_add_tail(&work->list, &rt->list);
390 pthread_mutex_unlock(&rt->thread.lock);
391
392 pthread_cond_signal(&rt->thread.cond);
393 } else {
394 int ret = pthread_create(&work->thread, NULL, reader_one_off, work);
395 if (ret)
396 fprintf(stderr, "pthread_create=%d\n", ret);
397 else
398 pthread_detach(work->thread);
399 }
400}
401
402static unsigned int calc_percentiles(unsigned int *io_u_plat, unsigned long nr,
403 unsigned int **output)
404{
405 unsigned long sum = 0;
406 unsigned int len, i, j = 0;
407 unsigned int oval_len = 0;
408 unsigned int *ovals = NULL;
409 int is_last;
410
411 len = 0;
412 while (len < PLAT_LIST_MAX && plist[len] != 0.0)
413 len++;
414
415 if (!len)
416 return 0;
417
418 /*
419 * Calculate bucket values, note down max and min values
420 */
421 is_last = 0;
422 for (i = 0; i < PLAT_NR && !is_last; i++) {
423 sum += io_u_plat[i];
424 while (sum >= (plist[j] / 100.0 * nr)) {
425 assert(plist[j] <= 100.0);
426
427 if (j == oval_len) {
428 oval_len += 100;
429 ovals = realloc(ovals, oval_len * sizeof(unsigned int));
430 }
431
432 ovals[j] = plat_idx_to_val(i);
433 is_last = (j == len - 1);
434 if (is_last)
435 break;
436
437 j++;
438 }
439 }
440
441 *output = ovals;
442 return len;
443}
444
445static void show_latencies(struct stats *s, const char *msg)
446{
447 unsigned int *ovals = NULL;
448 unsigned int len, i;
449
450 len = calc_percentiles(s->plat, s->nr_samples, &ovals);
451 if (len) {
452 fprintf(stderr, "Latency percentiles (usec) (%s)\n", msg);
453 for (i = 0; i < len; i++)
454 fprintf(stderr, "\t%2.4fth: %u\n", plist[i], ovals[i]);
455 }
456
457 if (ovals)
458 free(ovals);
459
460 fprintf(stderr, "\tOver=%u, min=%u, max=%u\n", s->over, s->min, s->max);
461}
462
463static void init_thread(struct thread_data *thread)
464{
465 pthread_cond_init(&thread->cond, NULL);
466 pthread_cond_init(&thread->done_cond, NULL);
467 pthread_mutex_init(&thread->lock, NULL);
468 pthread_mutex_init(&thread->done_lock, NULL);
469 thread->exit = 0;
470}
471
472static void exit_thread(struct thread_data *thread,
473 void fn(struct writer_thread *),
474 struct writer_thread *wt)
475{
28cacec4 476 __sync_fetch_and_add(&thread->exit, 1);
6d5a9bc2
JA
477 pthread_cond_signal(&thread->cond);
478
479 while (!thread->done) {
480 pthread_mutex_lock(&thread->done_lock);
481
482 if (fn) {
483 struct timespec t;
484
485 clock_gettime(CLOCK_REALTIME, &t);
486 t.tv_sec++;
487
488
489 pthread_cond_timedwait(&thread->done_cond, &thread->done_lock, &t);
490 fn(wt);
491 } else
492 pthread_cond_wait(&thread->done_cond, &thread->done_lock);
493
494 pthread_mutex_unlock(&thread->done_lock);
495 }
496}
497
498static int usage(char *argv[])
499{
500 fprintf(stderr, "%s: [-b blocksize] [-t max usec] [-w separate writer] -f file\n", argv[0]);
501 return 1;
502}
503
504static int parse_options(int argc, char *argv[])
505{
506 int c;
507
508 while ((c = getopt(argc, argv, "f:b:t:w:")) != -1) {
509 switch (c) {
510 case 'f':
511 file = strdup(optarg);
512 break;
513 case 'b':
514 bs = atoi(optarg);
515 break;
516 case 't':
517 max_us = atoi(optarg);
518 break;
519 case 'w':
520 separate_writer = atoi(optarg);
521 if (!separate_writer)
522 fprintf(stderr, "inline writing is broken\n");
523 break;
524 case '?':
525 default:
526 return usage(argv);
527 }
528 }
529
530 if (!file)
531 return usage(argv);
532
533 return 0;
534}
535
536static void prune_done_entries(struct writer_thread *wt)
537{
538 FLIST_HEAD(list);
539
540 if (flist_empty(&wt->done_list))
541 return;
542
543 if (pthread_mutex_trylock(&wt->thread.lock))
544 return;
545
546 if (!flist_empty(&wt->done_list))
547 flist_splice_init(&wt->done_list, &list);
548 pthread_mutex_unlock(&wt->thread.lock);
549
550 while (!flist_empty(&list)) {
551 struct work_item *work;
552
553 work = flist_first_entry(&list, struct work_item, list);
554 flist_del(&work->list);
555
556 pthread_cond_destroy(&work->cond);
557 pthread_mutex_destroy(&work->lock);
558 free(work->buf);
559 free(work);
560 }
561}
562
563int main(int argc, char *argv[])
564{
565 struct timeval s, re, we;
566 struct reader_thread *rt;
567 struct writer_thread *wt;
568 unsigned long rate;
569 struct stat sb;
570 size_t bytes;
571 off_t off;
572 int fd, seq;
573
574 if (parse_options(argc, argv))
575 return 1;
576
577 fd = open(file, O_RDONLY);
578 if (fd < 0) {
579 perror("open");
580 return 2;
581 }
582
583 if (fstat(fd, &sb) < 0) {
584 perror("stat");
585 return 3;
586 }
587
588 wt = &writer_thread;
589 init_thread(&wt->thread);
590 INIT_FLIST_HEAD(&wt->list);
591 INIT_FLIST_HEAD(&wt->done_list);
592 wt->s.max = 0;
593 wt->s.min = -1U;
594 pthread_create(&wt->thread.thread, NULL, writer_fn, wt);
595
596 rt = &reader_thread;
597 init_thread(&rt->thread);
598 INIT_FLIST_HEAD(&rt->list);
599 INIT_FLIST_HEAD(&rt->done_list);
600 rt->s.max = 0;
601 rt->s.min = -1U;
602 rt->write_seq = 1;
603
604 off = 0;
605 seq = 0;
606 bytes = 0;
607
608 gettimeofday(&s, NULL);
609
610 while (sb.st_size) {
611 struct work_item *work;
612 size_t this_len;
613 struct timespec t;
614
615 prune_done_entries(wt);
616
617 this_len = sb.st_size;
618 if (this_len > bs)
619 this_len = bs;
620
621 work = calloc(1, sizeof(*work));
622 work->buf = malloc(this_len);
623 work->buf_size = this_len;
624 work->off = off;
625 work->fd = fd;
626 work->seq = ++seq;
627 work->writer = wt;
628 work->reader = rt;
629 pthread_cond_init(&work->cond, NULL);
630 pthread_mutex_init(&work->lock, NULL);
631
632 queue_work(rt, work);
633
634 clock_gettime(CLOCK_REALTIME, &t);
635 t.tv_nsec += max_us * 1000ULL;
636 if (t.tv_nsec >= 1000000000ULL) {
637 t.tv_nsec -= 1000000000ULL;
638 t.tv_sec++;
639 }
640
641 pthread_mutex_lock(&work->lock);
642 pthread_cond_timedwait(&work->cond, &work->lock, &t);
643 pthread_mutex_unlock(&work->lock);
644
645 off += this_len;
646 sb.st_size -= this_len;
647 bytes += this_len;
648 }
649
650 exit_thread(&rt->thread, NULL, NULL);
651 gettimeofday(&re, NULL);
652
653 exit_thread(&wt->thread, prune_done_entries, wt);
654 gettimeofday(&we, NULL);
655
656 show_latencies(&rt->s, "READERS");
657 show_latencies(&wt->s, "WRITERS");
658
659 bytes /= 1024;
660 rate = (bytes * 1000UL * 1000UL) / utime_since(&s, &re);
661 fprintf(stderr, "Read rate (KB/sec) : %lu\n", rate);
662 rate = (bytes * 1000UL * 1000UL) / utime_since(&s, &we);
663 fprintf(stderr, "Write rate (KB/sec): %lu\n", rate);
664
665 close(fd);
666 return 0;
667}