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.
11 * $ time (./read-to-pipe-async -f randfile.gz | gzip -dc > outfile; sync)
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
18 * gcc -Wall -g -O2 -o read-to-pipe-async read-to-pipe-async.c -lpthread
20 * Copyright (C) 2016 Jens Axboe
29 #include <sys/types.h>
40 static int max_us = 10000;
42 static int separate_writer = 1;
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
51 unsigned int plat[PLAT_NR];
52 unsigned int nr_samples;
58 static 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, };
65 pthread_mutex_t done_lock;
66 pthread_cond_t done_cond;
70 struct writer_thread {
71 struct flist_head list;
72 struct flist_head done_list;
74 struct thread_data thread;
77 struct reader_thread {
78 struct flist_head list;
79 struct flist_head done_list;
84 struct thread_data thread;
88 struct flist_head list;
94 struct writer_thread *writer;
95 struct reader_thread *reader;
101 static struct reader_thread reader_thread;
102 static struct writer_thread writer_thread;
104 uint64_t utime_since(const struct timespec *s, const struct timespec *e)
109 sec = e->tv_sec - s->tv_sec;
110 usec = (e->tv_nsec - s->tv_nsec) / 1000;
111 if (sec > 0 && usec < 0) {
116 if (sec < 0 || (sec == 0 && usec < 0))
119 ret = sec * 1000000ULL + usec;
124 static struct work_item *find_seq(struct writer_thread *w, unsigned int seq)
126 struct work_item *work;
127 struct flist_head *entry;
129 if (flist_empty(&w->list))
132 flist_for_each(entry, &w->list) {
133 work = flist_entry(entry, struct work_item, list);
134 if (work->seq == seq)
141 static unsigned int plat_val_to_idx(unsigned int val)
143 unsigned int msb, error_bits, base, offset;
145 /* Find MSB starting from bit 0 */
149 msb = sizeof(val)*8 - __builtin_clz(val) - 1;
152 * MSB <= (PLAT_BITS-1), cannot be rounded off. Use
153 * all bits of the sample as index
155 if (msb <= PLAT_BITS)
158 /* Compute the number of error bits to discard*/
159 error_bits = msb - PLAT_BITS;
161 /* Compute the number of buckets before the group */
162 base = (error_bits + 1) << PLAT_BITS;
165 * Discard the error bits and apply the mask to find the
166 * index for the buckets in the group
168 offset = (PLAT_VAL - 1) & (val >> error_bits);
170 /* Make sure the index does not exceed (array size - 1) */
171 return (base + offset) < (PLAT_NR - 1) ?
172 (base + offset) : (PLAT_NR - 1);
176 * Convert the given index of the bucket array to the value
177 * represented by the bucket
179 static unsigned int plat_idx_to_val(unsigned int idx)
181 unsigned int error_bits, k, base;
183 assert(idx < PLAT_NR);
185 /* MSB <= (PLAT_BITS-1), cannot be rounded off. Use
186 * all bits of the sample as index */
187 if (idx < (PLAT_VAL << 1))
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);
194 /* Find its bucket number of the group */
197 /* Return the mean of the range of the bucket */
198 return base + ((k + 0.5) * (1 << error_bits));
201 static void add_lat(struct stats *s, unsigned int us, const char *name)
211 fprintf(stderr, "%s latency=%u usec\n", name, us);
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);
220 static int write_work(struct work_item *work)
222 struct timespec s, e;
225 clock_gettime(CLOCK_MONOTONIC, &s);
226 ret = write(STDOUT_FILENO, work->buf, work->buf_size);
227 clock_gettime(CLOCK_MONOTONIC, &e);
228 assert(ret == work->buf_size);
230 add_lat(&work->writer->s, utime_since(&s, &e), "write");
231 return work->seq + 1;
234 static void thread_exiting(struct thread_data *thread)
236 __sync_fetch_and_add(&thread->done, 1);
237 pthread_cond_signal(&thread->done_cond);
240 static void *writer_fn(void *data)
242 struct writer_thread *wt = data;
243 struct work_item *work;
244 unsigned int seq = 1;
247 while (!wt->thread.exit || !flist_empty(&wt->list)) {
248 pthread_mutex_lock(&wt->thread.lock);
251 flist_add_tail(&work->list, &wt->done_list);
255 work = find_seq(wt, seq);
257 flist_del_init(&work->list);
259 pthread_cond_wait(&wt->thread.cond, &wt->thread.lock);
261 pthread_mutex_unlock(&wt->thread.lock);
264 seq = write_work(work);
267 thread_exiting(&wt->thread);
271 static void reader_work(struct work_item *work)
273 struct timespec s, e;
279 clock_gettime(CLOCK_MONOTONIC, &s);
281 left = work->buf_size;
285 ret = pread(work->fd, buf, left, off);
287 fprintf(stderr, "zero read\n");
289 } else if (ret < 0) {
290 fprintf(stderr, "errno=%d\n", errno);
298 clock_gettime(CLOCK_MONOTONIC, &e);
300 add_lat(&work->reader->s, utime_since(&s, &e), "read");
302 pthread_cond_signal(&work->cond);
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);
310 struct reader_thread *rt = work->reader;
311 struct work_item *next = NULL;
312 struct flist_head *entry;
315 * Write current work if it matches in sequence.
317 if (work->seq == rt->write_seq)
320 pthread_mutex_lock(&rt->thread.lock);
322 flist_add_tail(&work->list, &rt->done_list);
325 * See if the next work item is here, if so, write it
328 flist_for_each(entry, &rt->done_list) {
329 next = flist_entry(entry, struct work_item, list);
330 if (next->seq == rt->write_seq) {
332 flist_del(&work->list);
337 pthread_mutex_unlock(&rt->thread.lock);
342 __sync_fetch_and_add(&rt->write_seq, 1);
347 static void *reader_one_off(void *data)
353 static void *reader_fn(void *data)
355 struct reader_thread *rt = data;
356 struct work_item *work;
358 while (!rt->thread.exit || !flist_empty(&rt->list)) {
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);
365 pthread_cond_wait(&rt->thread.cond, &rt->thread.lock);
366 pthread_mutex_unlock(&rt->thread.lock);
369 __sync_fetch_and_add(&rt->busy, 1);
371 __sync_fetch_and_sub(&rt->busy, 1);
375 thread_exiting(&rt->thread);
379 static void queue_work(struct reader_thread *rt, struct work_item *work)
382 pthread_mutex_lock(&rt->thread.lock);
383 flist_add_tail(&work->list, &rt->list);
384 pthread_mutex_unlock(&rt->thread.lock);
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);
392 pthread_cond_signal(&rt->thread.cond);
394 int ret = pthread_create(&work->thread, NULL, reader_one_off, work);
396 fprintf(stderr, "pthread_create=%d\n", ret);
398 ret = pthread_detach(work->thread);
400 fprintf(stderr, "pthread_detach=%d\n", ret);
405 static unsigned int calc_percentiles(unsigned int *io_u_plat, unsigned long nr,
406 unsigned int **output)
408 unsigned long sum = 0;
409 unsigned int len, i, j = 0;
410 unsigned int oval_len = 0;
411 unsigned int *ovals = NULL;
415 while (len < PLAT_LIST_MAX && plist[len] != 0.0)
422 * Calculate bucket values, note down max and min values
425 for (i = 0; i < PLAT_NR && !is_last; i++) {
427 while (sum >= (plist[j] / 100.0 * nr)) {
428 assert(plist[j] <= 100.0);
432 ovals = realloc(ovals, oval_len * sizeof(unsigned int));
435 ovals[j] = plat_idx_to_val(i);
436 is_last = (j == len - 1);
448 static void show_latencies(struct stats *s, const char *msg)
450 unsigned int *ovals = NULL;
453 len = calc_percentiles(s->plat, s->nr_samples, &ovals);
455 fprintf(stderr, "Latency percentiles (usec) (%s)\n", msg);
456 for (i = 0; i < len; i++)
457 fprintf(stderr, "\t%2.4fth: %u\n", plist[i], ovals[i]);
463 fprintf(stderr, "\tOver=%u, min=%u, max=%u\n", s->over, s->min, s->max);
466 static void init_thread(struct thread_data *thread)
468 pthread_condattr_t cattr;
471 ret = pthread_condattr_init(&cattr);
473 #ifdef CONFIG_PTHREAD_CONDATTR_SETCLOCK
474 ret = pthread_condattr_setclock(&cattr, CLOCK_MONOTONIC);
477 pthread_cond_init(&thread->cond, &cattr);
478 pthread_cond_init(&thread->done_cond, &cattr);
479 pthread_mutex_init(&thread->lock, NULL);
480 pthread_mutex_init(&thread->done_lock, NULL);
484 static void exit_thread(struct thread_data *thread,
485 void fn(struct writer_thread *),
486 struct writer_thread *wt)
488 __sync_fetch_and_add(&thread->exit, 1);
489 pthread_cond_signal(&thread->cond);
491 while (!thread->done) {
492 pthread_mutex_lock(&thread->done_lock);
497 #ifdef CONFIG_PTHREAD_CONDATTR_SETCLOCK
498 clock_gettime(CLOCK_MONOTONIC, &ts);
500 clock_gettime(CLOCK_REALTIME, &ts);
504 pthread_cond_timedwait(&thread->done_cond, &thread->done_lock, &ts);
507 pthread_cond_wait(&thread->done_cond, &thread->done_lock);
509 pthread_mutex_unlock(&thread->done_lock);
513 static int usage(char *argv[])
515 fprintf(stderr, "%s: [-b blocksize] [-t max usec] [-w separate writer] -f file\n", argv[0]);
519 static int parse_options(int argc, char *argv[])
523 while ((c = getopt(argc, argv, "f:b:t:w:")) != -1) {
528 file = strdup(optarg);
534 max_us = atoi(optarg);
537 separate_writer = atoi(optarg);
538 if (!separate_writer)
539 fprintf(stderr, "inline writing is broken\n");
553 static void prune_done_entries(struct writer_thread *wt)
557 if (flist_empty(&wt->done_list))
560 if (pthread_mutex_trylock(&wt->thread.lock))
563 if (!flist_empty(&wt->done_list))
564 flist_splice_init(&wt->done_list, &list);
565 pthread_mutex_unlock(&wt->thread.lock);
567 while (!flist_empty(&list)) {
568 struct work_item *work;
570 work = flist_first_entry(&list, struct work_item, list);
571 flist_del(&work->list);
573 pthread_cond_destroy(&work->cond);
574 pthread_mutex_destroy(&work->lock);
580 int main(int argc, char *argv[])
582 pthread_condattr_t cattr;
583 struct timespec s, re, we;
584 struct reader_thread *rt;
585 struct writer_thread *wt;
594 if (parse_options(argc, argv))
597 fd = open(file, O_RDONLY);
603 if (fstat(fd, &sb) < 0) {
609 init_thread(&wt->thread);
610 INIT_FLIST_HEAD(&wt->list);
611 INIT_FLIST_HEAD(&wt->done_list);
614 pthread_create(&wt->thread.thread, NULL, writer_fn, wt);
617 init_thread(&rt->thread);
618 INIT_FLIST_HEAD(&rt->list);
619 INIT_FLIST_HEAD(&rt->done_list);
628 ret = pthread_condattr_init(&cattr);
630 #ifdef CONFIG_PTHREAD_CONDATTR_SETCLOCK
631 ret = pthread_condattr_setclock(&cattr, CLOCK_MONOTONIC);
635 clock_gettime(CLOCK_MONOTONIC, &s);
638 struct work_item *work;
642 prune_done_entries(wt);
644 this_len = sb.st_size;
648 work = calloc(1, sizeof(*work));
649 work->buf = malloc(this_len);
650 work->buf_size = this_len;
656 pthread_cond_init(&work->cond, &cattr);
657 pthread_mutex_init(&work->lock, NULL);
659 queue_work(rt, work);
661 #ifdef CONFIG_PTHREAD_CONDATTR_SETCLOCK
662 clock_gettime(CLOCK_MONOTONIC, &ts);
664 clock_gettime(CLOCK_REALTIME, &ts);
666 ts.tv_nsec += max_us * 1000ULL;
667 if (ts.tv_nsec >= 1000000000ULL) {
668 ts.tv_nsec -= 1000000000ULL;
672 pthread_mutex_lock(&work->lock);
673 pthread_cond_timedwait(&work->cond, &work->lock, &ts);
674 pthread_mutex_unlock(&work->lock);
677 sb.st_size -= this_len;
681 exit_thread(&rt->thread, NULL, NULL);
682 clock_gettime(CLOCK_MONOTONIC, &re);
684 exit_thread(&wt->thread, prune_done_entries, wt);
685 clock_gettime(CLOCK_MONOTONIC, &we);
687 show_latencies(&rt->s, "READERS");
688 show_latencies(&wt->s, "WRITERS");
691 elapsed = utime_since(&s, &re);
692 rate = elapsed ? (bytes * 1000UL * 1000UL) / elapsed : 0;
693 fprintf(stderr, "Read rate (KiB/sec) : %lu\n", rate);
694 elapsed = utime_since(&s, &we);
695 rate = elapsed ? (bytes * 1000UL * 1000UL) / elapsed : 0;
696 fprintf(stderr, "Write rate (KiB/sec): %lu\n", rate);