2 * random utiility code, for bcache but in theory not specific to bcache
4 * Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
5 * Copyright 2012 Google, Inc.
9 #include <linux/blkdev.h>
10 #include <linux/ctype.h>
11 #include <linux/debugfs.h>
12 #include <linux/freezer.h>
13 #include <linux/kthread.h>
14 #include <linux/log2.h>
15 #include <linux/math64.h>
16 #include <linux/percpu.h>
17 #include <linux/preempt.h>
18 #include <linux/random.h>
19 #include <linux/seq_file.h>
20 #include <linux/string.h>
21 #include <linux/types.h>
22 #include <linux/sched/clock.h>
24 #include "eytzinger.h"
27 #define simple_strtoint(c, end, base) simple_strtol(c, end, base)
28 #define simple_strtouint(c, end, base) simple_strtoul(c, end, base)
30 static const char si_units[] = "?kMGTPEZY";
32 static int __bch2_strtoh(const char *cp, u64 *res,
33 u64 t_max, bool t_signed)
35 bool positive = *cp != '-';
39 if (*cp == '+' || *cp == '-')
49 if (v > U64_MAX - (*cp - '0'))
53 } while (isdigit(*cp));
55 for (u = 1; u < strlen(si_units); u++)
56 if (*cp == si_units[u]) {
67 if (fls64(v) + u * 10 > 64)
88 #define STRTO_H(name, type) \
89 int bch2_ ## name ## _h(const char *cp, type *res) \
92 int ret = __bch2_strtoh(cp, &v, ANYSINT_MAX(type), \
93 ANYSINT_MAX(type) != ((type) ~0ULL)); \
98 STRTO_H(strtoint, int)
99 STRTO_H(strtouint, unsigned int)
100 STRTO_H(strtoll, long long)
101 STRTO_H(strtoull, unsigned long long)
103 ssize_t bch2_hprint(char *buf, s64 v)
108 for (u = 0; v >= 1024 || v <= -1024; u++) {
109 t = v & ~(~0U << 10);
114 return sprintf(buf, "%lli", v);
117 * 103 is magic: t is in the range [-1023, 1023] and we want
118 * to turn it into [-9, 9]
120 if (v < 100 && v > -100)
121 scnprintf(dec, sizeof(dec), ".%i", t / 103);
123 return sprintf(buf, "%lli%s%c", v, dec, si_units[u]);
126 ssize_t bch2_scnprint_string_list(char *buf, size_t size,
127 const char * const list[],
136 for (i = 0; list[i]; i++)
137 out += scnprintf(out, buf + size - out,
138 i == selected ? "[%s] " : "%s ", list[i]);
146 ssize_t bch2_scnprint_flag_list(char *buf, size_t size,
147 const char * const list[], u64 flags)
149 char *out = buf, *end = buf + size;
150 unsigned bit, nr = 0;
158 while (flags && (bit = __ffs(flags)) < nr) {
159 out += scnprintf(out, end - out, "%s,", list[bit]);
169 u64 bch2_read_flag_list(char *opt, const char * const list[])
172 char *p, *s, *d = kstrndup(opt, PAGE_SIZE - 1, GFP_KERNEL);
179 while ((p = strsep(&s, ","))) {
180 int flag = match_string(list, -1, p);
194 bool bch2_is_zero(const void *_p, size_t n)
199 for (i = 0; i < n; i++)
205 static void bch2_quantiles_update(struct quantiles *q, u64 v)
209 while (i < ARRAY_SIZE(q->entries)) {
210 struct quantile_entry *e = q->entries + i;
212 if (unlikely(!e->step)) {
214 e->step = max_t(unsigned, v / 2, 1024);
215 } else if (e->m > v) {
216 e->m = e->m >= e->step
219 } else if (e->m < v) {
220 e->m = e->m + e->step > e->m
225 if ((e->m > v ? e->m - v : v - e->m) < e->step)
226 e->step = max_t(unsigned, e->step / 2, 1);
231 i = eytzinger0_child(i, v > e->m);
237 static void bch2_time_stats_update_one(struct time_stats *stats,
242 duration = time_after64(end, start)
244 freq = time_after64(end, stats->last_event)
245 ? end - stats->last_event : 0;
249 stats->average_duration = stats->average_duration
250 ? ewma_add(stats->average_duration, duration, 6)
253 stats->average_frequency = stats->average_frequency
254 ? ewma_add(stats->average_frequency, freq, 6)
257 stats->max_duration = max(stats->max_duration, duration);
259 stats->last_event = end;
261 bch2_quantiles_update(&stats->quantiles, duration);
264 void __bch2_time_stats_update(struct time_stats *stats, u64 start, u64 end)
268 if (!stats->buffer) {
269 spin_lock_irqsave(&stats->lock, flags);
270 bch2_time_stats_update_one(stats, start, end);
272 if (stats->average_frequency < 32 &&
275 alloc_percpu_gfp(struct time_stat_buffer,
277 spin_unlock_irqrestore(&stats->lock, flags);
279 struct time_stat_buffer_entry *i;
280 struct time_stat_buffer *b;
283 b = this_cpu_ptr(stats->buffer);
285 BUG_ON(b->nr >= ARRAY_SIZE(b->entries));
286 b->entries[b->nr++] = (struct time_stat_buffer_entry) {
291 if (b->nr == ARRAY_SIZE(b->entries)) {
292 spin_lock_irqsave(&stats->lock, flags);
294 i < b->entries + ARRAY_SIZE(b->entries);
296 bch2_time_stats_update_one(stats, i->start, i->end);
297 spin_unlock_irqrestore(&stats->lock, flags);
306 static const struct time_unit {
311 { "us", NSEC_PER_USEC },
312 { "ms", NSEC_PER_MSEC },
313 { "sec", NSEC_PER_SEC },
316 static const struct time_unit *pick_time_units(u64 ns)
318 const struct time_unit *u;
321 u + 1 < time_units + ARRAY_SIZE(time_units) &&
322 ns >= u[1].nsecs << 1;
329 static size_t pr_time_units(char *buf, size_t len, u64 ns)
331 const struct time_unit *u = pick_time_units(ns);
333 return scnprintf(buf, len, "%llu %s", div_u64(ns, u->nsecs), u->name);
336 size_t bch2_time_stats_print(struct time_stats *stats, char *buf, size_t len)
338 char *out = buf, *end = buf + len;
339 const struct time_unit *u;
340 u64 freq = READ_ONCE(stats->average_frequency);
344 out += scnprintf(out, end - out, "count:\t\t%llu\n",
346 out += scnprintf(out, end - out, "rate:\t\t%llu/sec\n",
347 freq ? div64_u64(NSEC_PER_SEC, freq) : 0);
349 out += scnprintf(out, end - out, "frequency:\t");
350 out += pr_time_units(out, end - out, freq);
352 out += scnprintf(out, end - out, "\navg duration:\t");
353 out += pr_time_units(out, end - out, stats->average_duration);
355 out += scnprintf(out, end - out, "\nmax duration:\t");
356 out += pr_time_units(out, end - out, stats->max_duration);
358 i = eytzinger0_first(NR_QUANTILES);
359 u = pick_time_units(stats->quantiles.entries[i].m);
361 out += scnprintf(out, end - out, "\nquantiles (%s):\t", u->name);
362 eytzinger0_for_each(i, NR_QUANTILES) {
363 bool is_last = eytzinger0_next(i, NR_QUANTILES) == -1;
365 q = max(stats->quantiles.entries[i].m, last_q);
366 out += scnprintf(out, end - out, "%llu%s",
367 div_u64(q, u->nsecs),
368 is_last ? "\n" : " ");
375 void bch2_time_stats_exit(struct time_stats *stats)
377 free_percpu(stats->buffer);
380 void bch2_time_stats_init(struct time_stats *stats)
382 memset(stats, 0, sizeof(*stats));
383 spin_lock_init(&stats->lock);
389 * bch2_ratelimit_delay() - return how long to delay until the next time to do
392 * @d - the struct bch_ratelimit to update
394 * Returns the amount of time to delay by, in jiffies
396 u64 bch2_ratelimit_delay(struct bch_ratelimit *d)
398 u64 now = local_clock();
400 return time_after64(d->next, now)
401 ? nsecs_to_jiffies(d->next - now)
406 * bch2_ratelimit_increment() - increment @d by the amount of work done
408 * @d - the struct bch_ratelimit to update
409 * @done - the amount of work done, in arbitrary units
411 void bch2_ratelimit_increment(struct bch_ratelimit *d, u64 done)
413 u64 now = local_clock();
415 d->next += div_u64(done * NSEC_PER_SEC, d->rate);
417 if (time_before64(now + NSEC_PER_SEC, d->next))
418 d->next = now + NSEC_PER_SEC;
420 if (time_after64(now - NSEC_PER_SEC * 2, d->next))
421 d->next = now - NSEC_PER_SEC * 2;
427 * Updates pd_controller. Attempts to scale inputed values to units per second.
428 * @target: desired value
429 * @actual: current value
431 * @sign: 1 or -1; 1 if increasing the rate makes actual go up, -1 if increasing
432 * it makes actual go down.
434 void bch2_pd_controller_update(struct bch_pd_controller *pd,
435 s64 target, s64 actual, int sign)
437 s64 proportional, derivative, change;
439 unsigned long seconds_since_update = (jiffies - pd->last_update) / HZ;
441 if (seconds_since_update == 0)
444 pd->last_update = jiffies;
446 proportional = actual - target;
447 proportional *= seconds_since_update;
448 proportional = div_s64(proportional, pd->p_term_inverse);
450 derivative = actual - pd->last_actual;
451 derivative = div_s64(derivative, seconds_since_update);
452 derivative = ewma_add(pd->smoothed_derivative, derivative,
453 (pd->d_term / seconds_since_update) ?: 1);
454 derivative = derivative * pd->d_term;
455 derivative = div_s64(derivative, pd->p_term_inverse);
457 change = proportional + derivative;
459 /* Don't increase rate if not keeping up */
462 time_after64(local_clock(),
463 pd->rate.next + NSEC_PER_MSEC))
466 change *= (sign * -1);
468 pd->rate.rate = clamp_t(s64, (s64) pd->rate.rate + change,
471 pd->last_actual = actual;
472 pd->last_derivative = derivative;
473 pd->last_proportional = proportional;
474 pd->last_change = change;
475 pd->last_target = target;
478 void bch2_pd_controller_init(struct bch_pd_controller *pd)
480 pd->rate.rate = 1024;
481 pd->last_update = jiffies;
482 pd->p_term_inverse = 6000;
484 pd->d_smooth = pd->d_term;
485 pd->backpressure = 1;
488 size_t bch2_pd_controller_print_debug(struct bch_pd_controller *pd, char *buf)
490 /* 2^64 - 1 is 20 digits, plus null byte */
494 char proportional[21];
499 bch2_hprint(rate, pd->rate.rate);
500 bch2_hprint(actual, pd->last_actual);
501 bch2_hprint(target, pd->last_target);
502 bch2_hprint(proportional, pd->last_proportional);
503 bch2_hprint(derivative, pd->last_derivative);
504 bch2_hprint(change, pd->last_change);
506 next_io = div64_s64(pd->rate.next - local_clock(), NSEC_PER_MSEC);
512 "proportional:\t%s\n"
514 "change:\t\t%s/sec\n"
515 "next io:\t%llims\n",
516 rate, target, actual, proportional,
517 derivative, change, next_io);
522 void bch2_bio_map(struct bio *bio, void *base)
524 size_t size = bio->bi_iter.bi_size;
525 struct bio_vec *bv = bio->bi_io_vec;
527 BUG_ON(!bio->bi_iter.bi_size);
528 BUG_ON(bio->bi_vcnt);
530 bv->bv_offset = base ? offset_in_page(base) : 0;
533 for (; size; bio->bi_vcnt++, bv++) {
535 start: bv->bv_len = min_t(size_t, PAGE_SIZE - bv->bv_offset,
537 BUG_ON(bio->bi_vcnt >= bio->bi_max_vecs);
539 bv->bv_page = is_vmalloc_addr(base)
540 ? vmalloc_to_page(base)
541 : virt_to_page(base);
550 int bch2_bio_alloc_pages(struct bio *bio, gfp_t gfp_mask)
555 bio_for_each_segment_all(bv, bio, i) {
556 bv->bv_page = alloc_page(gfp_mask);
558 while (--bv >= bio->bi_io_vec)
559 __free_page(bv->bv_page);
567 size_t bch2_rand_range(size_t max)
575 rand = get_random_long();
576 rand &= roundup_pow_of_two(max) - 1;
577 } while (rand >= max);
582 void memcpy_to_bio(struct bio *dst, struct bvec_iter dst_iter, void *src)
585 struct bvec_iter iter;
587 __bio_for_each_segment(bv, dst, iter, dst_iter) {
588 void *dstp = kmap_atomic(bv.bv_page);
589 memcpy(dstp + bv.bv_offset, src, bv.bv_len);
596 void memcpy_from_bio(void *dst, struct bio *src, struct bvec_iter src_iter)
599 struct bvec_iter iter;
601 __bio_for_each_segment(bv, src, iter, src_iter) {
602 void *srcp = kmap_atomic(bv.bv_page);
603 memcpy(dst, srcp + bv.bv_offset, bv.bv_len);
610 size_t bch_scnmemcpy(char *buf, size_t size, const char *src, size_t len)
617 n = min(size - 1, len);
624 #include "eytzinger.h"
626 static int alignment_ok(const void *base, size_t align)
628 return IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) ||
629 ((unsigned long)base & (align - 1)) == 0;
632 static void u32_swap(void *a, void *b, size_t size)
635 *(u32 *)a = *(u32 *)b;
639 static void u64_swap(void *a, void *b, size_t size)
642 *(u64 *)a = *(u64 *)b;
646 static void generic_swap(void *a, void *b, size_t size)
652 *(char *)a++ = *(char *)b;
654 } while (--size > 0);
657 static inline int do_cmp(void *base, size_t n, size_t size,
658 int (*cmp_func)(const void *, const void *, size_t),
661 return cmp_func(base + inorder_to_eytzinger0(l, n) * size,
662 base + inorder_to_eytzinger0(r, n) * size,
666 static inline void do_swap(void *base, size_t n, size_t size,
667 void (*swap_func)(void *, void *, size_t),
670 swap_func(base + inorder_to_eytzinger0(l, n) * size,
671 base + inorder_to_eytzinger0(r, n) * size,
675 void eytzinger0_sort(void *base, size_t n, size_t size,
676 int (*cmp_func)(const void *, const void *, size_t),
677 void (*swap_func)(void *, void *, size_t))
682 if (size == 4 && alignment_ok(base, 4))
683 swap_func = u32_swap;
684 else if (size == 8 && alignment_ok(base, 8))
685 swap_func = u64_swap;
687 swap_func = generic_swap;
691 for (i = n / 2 - 1; i >= 0; --i) {
692 for (r = i; r * 2 + 1 < n; r = c) {
696 do_cmp(base, n, size, cmp_func, c, c + 1) < 0)
699 if (do_cmp(base, n, size, cmp_func, r, c) >= 0)
702 do_swap(base, n, size, swap_func, r, c);
707 for (i = n - 1; i > 0; --i) {
708 do_swap(base, n, size, swap_func, 0, i);
710 for (r = 0; r * 2 + 1 < i; r = c) {
714 do_cmp(base, n, size, cmp_func, c, c + 1) < 0)
717 if (do_cmp(base, n, size, cmp_func, r, c) >= 0)
720 do_swap(base, n, size, swap_func, r, c);
725 void sort_cmp_size(void *base, size_t num, size_t size,
726 int (*cmp_func)(const void *, const void *, size_t),
727 void (*swap_func)(void *, void *, size_t size))
729 /* pre-scale counters for performance */
730 int i = (num/2 - 1) * size, n = num * size, c, r;
733 if (size == 4 && alignment_ok(base, 4))
734 swap_func = u32_swap;
735 else if (size == 8 && alignment_ok(base, 8))
736 swap_func = u64_swap;
738 swap_func = generic_swap;
742 for ( ; i >= 0; i -= size) {
743 for (r = i; r * 2 + size < n; r = c) {
746 cmp_func(base + c, base + c + size, size) < 0)
748 if (cmp_func(base + r, base + c, size) >= 0)
750 swap_func(base + r, base + c, size);
755 for (i = n - size; i > 0; i -= size) {
756 swap_func(base, base + i, size);
757 for (r = 0; r * 2 + size < i; r = c) {
760 cmp_func(base + c, base + c + size, size) < 0)
762 if (cmp_func(base + r, base + c, size) >= 0)
764 swap_func(base + r, base + c, size);
769 static void mempool_free_vp(void *element, void *pool_data)
771 size_t size = (size_t) pool_data;
773 vpfree(element, size);
776 static void *mempool_alloc_vp(gfp_t gfp_mask, void *pool_data)
778 size_t size = (size_t) pool_data;
780 return vpmalloc(size, gfp_mask);
783 int mempool_init_kvpmalloc_pool(mempool_t *pool, int min_nr, size_t size)
785 return size < PAGE_SIZE
786 ? mempool_init_kmalloc_pool(pool, min_nr, size)
787 : mempool_init(pool, min_nr, mempool_alloc_vp,
788 mempool_free_vp, (void *) size);
792 void eytzinger1_test(void)
794 unsigned inorder, eytz, size;
796 pr_info("1 based eytzinger test:");
801 unsigned extra = eytzinger1_extra(size);
804 pr_info("tree size %u", size);
806 BUG_ON(eytzinger1_prev(0, size) != eytzinger1_last(size));
807 BUG_ON(eytzinger1_next(0, size) != eytzinger1_first(size));
809 BUG_ON(eytzinger1_prev(eytzinger1_first(size), size) != 0);
810 BUG_ON(eytzinger1_next(eytzinger1_last(size), size) != 0);
813 eytzinger1_for_each(eytz, size) {
814 BUG_ON(__inorder_to_eytzinger1(inorder, size, extra) != eytz);
815 BUG_ON(__eytzinger1_to_inorder(eytz, size, extra) != inorder);
816 BUG_ON(eytz != eytzinger1_last(size) &&
817 eytzinger1_prev(eytzinger1_next(eytz, size), size) != eytz);
824 void eytzinger0_test(void)
827 unsigned inorder, eytz, size;
829 pr_info("0 based eytzinger test:");
834 unsigned extra = eytzinger0_extra(size);
837 pr_info("tree size %u", size);
839 BUG_ON(eytzinger0_prev(-1, size) != eytzinger0_last(size));
840 BUG_ON(eytzinger0_next(-1, size) != eytzinger0_first(size));
842 BUG_ON(eytzinger0_prev(eytzinger0_first(size), size) != -1);
843 BUG_ON(eytzinger0_next(eytzinger0_last(size), size) != -1);
846 eytzinger0_for_each(eytz, size) {
847 BUG_ON(__inorder_to_eytzinger0(inorder, size, extra) != eytz);
848 BUG_ON(__eytzinger0_to_inorder(eytz, size, extra) != inorder);
849 BUG_ON(eytz != eytzinger0_last(size) &&
850 eytzinger0_prev(eytzinger0_next(eytz, size), size) != eytz);
857 static inline int cmp_u16(const void *_l, const void *_r, size_t size)
859 const u16 *l = _l, *r = _r;
861 return (*l > *r) - (*r - *l);
864 static void eytzinger0_find_test_val(u16 *test_array, unsigned nr, u16 search)
866 int i, c1 = -1, c2 = -1;
869 r = eytzinger0_find_le(test_array, nr,
870 sizeof(test_array[0]),
875 for (i = 0; i < nr; i++)
876 if (test_array[i] <= search && test_array[i] > c2)
880 eytzinger0_for_each(i, nr)
881 pr_info("[%3u] = %12u", i, test_array[i]);
882 pr_info("find_le(%2u) -> [%2zi] = %2i should be %2i",
887 void eytzinger0_find_test(void)
889 unsigned i, nr, allocated = 1 << 12;
890 u16 *test_array = kmalloc_array(allocated, sizeof(test_array[0]), GFP_KERNEL);
892 for (nr = 1; nr < allocated; nr++) {
893 pr_info("testing %u elems", nr);
895 get_random_bytes(test_array, nr * sizeof(test_array[0]));
896 eytzinger0_sort(test_array, nr, sizeof(test_array[0]), cmp_u16, NULL);
898 /* verify array is sorted correctly: */
899 eytzinger0_for_each(i, nr)
900 BUG_ON(i != eytzinger0_last(nr) &&
901 test_array[i] > test_array[eytzinger0_next(i, nr)]);
903 for (i = 0; i < U16_MAX; i += 1 << 12)
904 eytzinger0_find_test_val(test_array, nr, i);
906 for (i = 0; i < nr; i++) {
907 eytzinger0_find_test_val(test_array, nr, test_array[i] - 1);
908 eytzinger0_find_test_val(test_array, nr, test_array[i]);
909 eytzinger0_find_test_val(test_array, nr, test_array[i] + 1);