1 // SPDX-License-Identifier: GPL-2.0
3 * random utiility code, for bcache but in theory not specific to bcache
5 * Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
6 * Copyright 2012 Google, Inc.
10 #include <linux/blkdev.h>
11 #include <linux/console.h>
12 #include <linux/ctype.h>
13 #include <linux/debugfs.h>
14 #include <linux/freezer.h>
15 #include <linux/kthread.h>
16 #include <linux/log2.h>
17 #include <linux/math64.h>
18 #include <linux/percpu.h>
19 #include <linux/preempt.h>
20 #include <linux/random.h>
21 #include <linux/seq_file.h>
22 #include <linux/string.h>
23 #include <linux/types.h>
24 #include <linux/sched/clock.h>
26 #include "eytzinger.h"
29 static const char si_units[] = "?kMGTPEZY";
31 /* string_get_size units: */
32 static const char *const units_2[] = {
33 "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"
35 static const char *const units_10[] = {
36 "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"
39 static int parse_u64(const char *cp, u64 *res)
41 const char *start = cp;
51 if (v > U64_MAX - (*cp - '0'))
55 } while (isdigit(*cp));
61 static int bch2_pow(u64 n, u64 p, u64 *res)
66 if (*res > div_u64(U64_MAX, n))
73 static int parse_unit_suffix(const char *cp, u64 *res)
75 const char *start = cp;
83 for (u = 1; u < strlen(si_units); u++)
84 if (*cp == si_units[u]) {
89 for (u = 0; u < ARRAY_SIZE(units_2); u++)
90 if (!strncmp(cp, units_2[u], strlen(units_2[u]))) {
91 cp += strlen(units_2[u]);
95 for (u = 0; u < ARRAY_SIZE(units_10); u++)
96 if (!strncmp(cp, units_10[u], strlen(units_10[u]))) {
97 cp += strlen(units_10[u]);
105 ret = bch2_pow(base, u, res);
112 #define parse_or_ret(cp, _f) \
120 static int __bch2_strtou64_h(const char *cp, u64 *res)
122 const char *start = cp;
123 u64 v = 0, b, f_n = 0, f_d = 1;
126 parse_or_ret(cp, parse_u64(cp, &v));
130 ret = parse_u64(cp, &f_n);
135 ret = bch2_pow(10, ret, &f_d);
140 parse_or_ret(cp, parse_unit_suffix(cp, &b));
142 if (v > div_u64(U64_MAX, b))
146 if (f_n > div_u64(U64_MAX, b))
149 f_n = div_u64(f_n * b, f_d);
158 static int __bch2_strtoh(const char *cp, u64 *res,
159 u64 t_max, bool t_signed)
161 bool positive = *cp != '-';
164 if (*cp == '+' || *cp == '-')
167 parse_or_ret(cp, __bch2_strtou64_h(cp, &v));
190 #define STRTO_H(name, type) \
191 int bch2_ ## name ## _h(const char *cp, type *res) \
194 int ret = __bch2_strtoh(cp, &v, ANYSINT_MAX(type), \
195 ANYSINT_MAX(type) != ((type) ~0ULL)); \
200 STRTO_H(strtoint, int)
201 STRTO_H(strtouint, unsigned int)
202 STRTO_H(strtoll, long long)
203 STRTO_H(strtoull, unsigned long long)
204 STRTO_H(strtou64, u64)
206 u64 bch2_read_flag_list(char *opt, const char * const list[])
209 char *p, *s, *d = kstrdup(opt, GFP_KERNEL);
216 while ((p = strsep(&s, ","))) {
217 int flag = match_string(list, -1, p);
231 bool bch2_is_zero(const void *_p, size_t n)
236 for (i = 0; i < n; i++)
242 static void bch2_quantiles_update(struct quantiles *q, u64 v)
246 while (i < ARRAY_SIZE(q->entries)) {
247 struct quantile_entry *e = q->entries + i;
249 if (unlikely(!e->step)) {
251 e->step = max_t(unsigned, v / 2, 1024);
252 } else if (e->m > v) {
253 e->m = e->m >= e->step
256 } else if (e->m < v) {
257 e->m = e->m + e->step > e->m
262 if ((e->m > v ? e->m - v : v - e->m) < e->step)
263 e->step = max_t(unsigned, e->step / 2, 1);
268 i = eytzinger0_child(i, v > e->m);
272 void bch2_prt_u64_binary(struct printbuf *out, u64 v, unsigned nr_bits)
275 prt_char(out, '0' + ((v >> --nr_bits) & 1));
278 void bch2_print_string_as_lines(const char *prefix, const char *lines)
283 printk("%s (null)\n", prefix);
289 p = strchrnul(lines, '\n');
290 printk("%s%.*s\n", prefix, (int) (p - lines), lines);
301 static void bch2_time_stats_update_one(struct time_stats *stats,
306 duration = time_after64(end, start)
308 freq = time_after64(end, stats->last_event)
309 ? end - stats->last_event : 0;
313 stats->average_duration = stats->average_duration
314 ? ewma_add(stats->average_duration, duration, 6)
317 stats->average_frequency = stats->average_frequency
318 ? ewma_add(stats->average_frequency, freq, 6)
321 stats->max_duration = max(stats->max_duration, duration);
323 stats->last_event = end;
325 bch2_quantiles_update(&stats->quantiles, duration);
328 void __bch2_time_stats_update(struct time_stats *stats, u64 start, u64 end)
332 if (!stats->buffer) {
333 spin_lock_irqsave(&stats->lock, flags);
334 bch2_time_stats_update_one(stats, start, end);
336 if (stats->average_frequency < 32 &&
339 alloc_percpu_gfp(struct time_stat_buffer,
341 spin_unlock_irqrestore(&stats->lock, flags);
343 struct time_stat_buffer_entry *i;
344 struct time_stat_buffer *b;
347 b = this_cpu_ptr(stats->buffer);
349 BUG_ON(b->nr >= ARRAY_SIZE(b->entries));
350 b->entries[b->nr++] = (struct time_stat_buffer_entry) {
355 if (b->nr == ARRAY_SIZE(b->entries)) {
356 spin_lock_irqsave(&stats->lock, flags);
358 i < b->entries + ARRAY_SIZE(b->entries);
360 bch2_time_stats_update_one(stats, i->start, i->end);
361 spin_unlock_irqrestore(&stats->lock, flags);
370 static const struct time_unit {
375 { "us", NSEC_PER_USEC },
376 { "ms", NSEC_PER_MSEC },
377 { "sec", NSEC_PER_SEC },
380 static const struct time_unit *pick_time_units(u64 ns)
382 const struct time_unit *u;
385 u + 1 < time_units + ARRAY_SIZE(time_units) &&
386 ns >= u[1].nsecs << 1;
393 static void pr_time_units(struct printbuf *out, u64 ns)
395 const struct time_unit *u = pick_time_units(ns);
397 prt_printf(out, "%llu %s", div_u64(ns, u->nsecs), u->name);
400 void bch2_time_stats_to_text(struct printbuf *out, struct time_stats *stats)
402 const struct time_unit *u;
403 u64 freq = READ_ONCE(stats->average_frequency);
407 prt_printf(out, "count:\t\t%llu",
410 prt_printf(out, "rate:\t\t%llu/sec",
411 freq ? div64_u64(NSEC_PER_SEC, freq) : 0);
414 prt_printf(out, "frequency:\t");
415 pr_time_units(out, freq);
418 prt_printf(out, "avg duration:\t");
419 pr_time_units(out, stats->average_duration);
422 prt_printf(out, "max duration:\t");
423 pr_time_units(out, stats->max_duration);
425 i = eytzinger0_first(NR_QUANTILES);
426 u = pick_time_units(stats->quantiles.entries[i].m);
429 prt_printf(out, "quantiles (%s):\t", u->name);
430 eytzinger0_for_each(i, NR_QUANTILES) {
431 bool is_last = eytzinger0_next(i, NR_QUANTILES) == -1;
433 q = max(stats->quantiles.entries[i].m, last_q);
434 prt_printf(out, "%llu ",
435 div_u64(q, u->nsecs));
442 void bch2_time_stats_exit(struct time_stats *stats)
444 free_percpu(stats->buffer);
447 void bch2_time_stats_init(struct time_stats *stats)
449 memset(stats, 0, sizeof(*stats));
450 spin_lock_init(&stats->lock);
456 * bch2_ratelimit_delay() - return how long to delay until the next time to do
459 * @d - the struct bch_ratelimit to update
461 * Returns the amount of time to delay by, in jiffies
463 u64 bch2_ratelimit_delay(struct bch_ratelimit *d)
465 u64 now = local_clock();
467 return time_after64(d->next, now)
468 ? nsecs_to_jiffies(d->next - now)
473 * bch2_ratelimit_increment() - increment @d by the amount of work done
475 * @d - the struct bch_ratelimit to update
476 * @done - the amount of work done, in arbitrary units
478 void bch2_ratelimit_increment(struct bch_ratelimit *d, u64 done)
480 u64 now = local_clock();
482 d->next += div_u64(done * NSEC_PER_SEC, d->rate);
484 if (time_before64(now + NSEC_PER_SEC, d->next))
485 d->next = now + NSEC_PER_SEC;
487 if (time_after64(now - NSEC_PER_SEC * 2, d->next))
488 d->next = now - NSEC_PER_SEC * 2;
494 * Updates pd_controller. Attempts to scale inputed values to units per second.
495 * @target: desired value
496 * @actual: current value
498 * @sign: 1 or -1; 1 if increasing the rate makes actual go up, -1 if increasing
499 * it makes actual go down.
501 void bch2_pd_controller_update(struct bch_pd_controller *pd,
502 s64 target, s64 actual, int sign)
504 s64 proportional, derivative, change;
506 unsigned long seconds_since_update = (jiffies - pd->last_update) / HZ;
508 if (seconds_since_update == 0)
511 pd->last_update = jiffies;
513 proportional = actual - target;
514 proportional *= seconds_since_update;
515 proportional = div_s64(proportional, pd->p_term_inverse);
517 derivative = actual - pd->last_actual;
518 derivative = div_s64(derivative, seconds_since_update);
519 derivative = ewma_add(pd->smoothed_derivative, derivative,
520 (pd->d_term / seconds_since_update) ?: 1);
521 derivative = derivative * pd->d_term;
522 derivative = div_s64(derivative, pd->p_term_inverse);
524 change = proportional + derivative;
526 /* Don't increase rate if not keeping up */
529 time_after64(local_clock(),
530 pd->rate.next + NSEC_PER_MSEC))
533 change *= (sign * -1);
535 pd->rate.rate = clamp_t(s64, (s64) pd->rate.rate + change,
538 pd->last_actual = actual;
539 pd->last_derivative = derivative;
540 pd->last_proportional = proportional;
541 pd->last_change = change;
542 pd->last_target = target;
545 void bch2_pd_controller_init(struct bch_pd_controller *pd)
547 pd->rate.rate = 1024;
548 pd->last_update = jiffies;
549 pd->p_term_inverse = 6000;
551 pd->d_smooth = pd->d_term;
552 pd->backpressure = 1;
555 void bch2_pd_controller_debug_to_text(struct printbuf *out, struct bch_pd_controller *pd)
557 if (!out->nr_tabstops)
558 printbuf_tabstop_push(out, 20);
560 prt_printf(out, "rate:");
562 prt_human_readable_s64(out, pd->rate.rate);
565 prt_printf(out, "target:");
567 prt_human_readable_u64(out, pd->last_target);
570 prt_printf(out, "actual:");
572 prt_human_readable_u64(out, pd->last_actual);
575 prt_printf(out, "proportional:");
577 prt_human_readable_s64(out, pd->last_proportional);
580 prt_printf(out, "derivative:");
582 prt_human_readable_s64(out, pd->last_derivative);
585 prt_printf(out, "change:");
587 prt_human_readable_s64(out, pd->last_change);
590 prt_printf(out, "next io:");
592 prt_printf(out, "%llims", div64_s64(pd->rate.next - local_clock(), NSEC_PER_MSEC));
598 void bch2_bio_map(struct bio *bio, void *base, size_t size)
601 struct page *page = is_vmalloc_addr(base)
602 ? vmalloc_to_page(base)
603 : virt_to_page(base);
604 unsigned offset = offset_in_page(base);
605 unsigned len = min_t(size_t, PAGE_SIZE - offset, size);
607 BUG_ON(!bio_add_page(bio, page, len, offset));
613 int bch2_bio_alloc_pages(struct bio *bio, size_t size, gfp_t gfp_mask)
616 struct page *page = alloc_page(gfp_mask);
617 unsigned len = min_t(size_t, PAGE_SIZE, size);
622 if (unlikely(!bio_add_page(bio, page, len, 0))) {
633 size_t bch2_rand_range(size_t max)
641 rand = get_random_long();
642 rand &= roundup_pow_of_two(max) - 1;
643 } while (rand >= max);
648 void memcpy_to_bio(struct bio *dst, struct bvec_iter dst_iter, const void *src)
651 struct bvec_iter iter;
653 __bio_for_each_segment(bv, dst, iter, dst_iter) {
654 void *dstp = kmap_atomic(bv.bv_page);
655 memcpy(dstp + bv.bv_offset, src, bv.bv_len);
662 void memcpy_from_bio(void *dst, struct bio *src, struct bvec_iter src_iter)
665 struct bvec_iter iter;
667 __bio_for_each_segment(bv, src, iter, src_iter) {
668 void *srcp = kmap_atomic(bv.bv_page);
669 memcpy(dst, srcp + bv.bv_offset, bv.bv_len);
676 #include "eytzinger.h"
678 static int alignment_ok(const void *base, size_t align)
680 return IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) ||
681 ((unsigned long)base & (align - 1)) == 0;
684 static void u32_swap(void *a, void *b, size_t size)
687 *(u32 *)a = *(u32 *)b;
691 static void u64_swap(void *a, void *b, size_t size)
694 *(u64 *)a = *(u64 *)b;
698 static void generic_swap(void *a, void *b, size_t size)
704 *(char *)a++ = *(char *)b;
706 } while (--size > 0);
709 static inline int do_cmp(void *base, size_t n, size_t size,
710 int (*cmp_func)(const void *, const void *, size_t),
713 return cmp_func(base + inorder_to_eytzinger0(l, n) * size,
714 base + inorder_to_eytzinger0(r, n) * size,
718 static inline void do_swap(void *base, size_t n, size_t size,
719 void (*swap_func)(void *, void *, size_t),
722 swap_func(base + inorder_to_eytzinger0(l, n) * size,
723 base + inorder_to_eytzinger0(r, n) * size,
727 void eytzinger0_sort(void *base, size_t n, size_t size,
728 int (*cmp_func)(const void *, const void *, size_t),
729 void (*swap_func)(void *, void *, size_t))
734 if (size == 4 && alignment_ok(base, 4))
735 swap_func = u32_swap;
736 else if (size == 8 && alignment_ok(base, 8))
737 swap_func = u64_swap;
739 swap_func = generic_swap;
743 for (i = n / 2 - 1; i >= 0; --i) {
744 for (r = i; r * 2 + 1 < n; r = c) {
748 do_cmp(base, n, size, cmp_func, c, c + 1) < 0)
751 if (do_cmp(base, n, size, cmp_func, r, c) >= 0)
754 do_swap(base, n, size, swap_func, r, c);
759 for (i = n - 1; i > 0; --i) {
760 do_swap(base, n, size, swap_func, 0, i);
762 for (r = 0; r * 2 + 1 < i; r = c) {
766 do_cmp(base, n, size, cmp_func, c, c + 1) < 0)
769 if (do_cmp(base, n, size, cmp_func, r, c) >= 0)
772 do_swap(base, n, size, swap_func, r, c);
777 void sort_cmp_size(void *base, size_t num, size_t size,
778 int (*cmp_func)(const void *, const void *, size_t),
779 void (*swap_func)(void *, void *, size_t size))
781 /* pre-scale counters for performance */
782 int i = (num/2 - 1) * size, n = num * size, c, r;
785 if (size == 4 && alignment_ok(base, 4))
786 swap_func = u32_swap;
787 else if (size == 8 && alignment_ok(base, 8))
788 swap_func = u64_swap;
790 swap_func = generic_swap;
794 for ( ; i >= 0; i -= size) {
795 for (r = i; r * 2 + size < n; r = c) {
798 cmp_func(base + c, base + c + size, size) < 0)
800 if (cmp_func(base + r, base + c, size) >= 0)
802 swap_func(base + r, base + c, size);
807 for (i = n - size; i > 0; i -= size) {
808 swap_func(base, base + i, size);
809 for (r = 0; r * 2 + size < i; r = c) {
812 cmp_func(base + c, base + c + size, size) < 0)
814 if (cmp_func(base + r, base + c, size) >= 0)
816 swap_func(base + r, base + c, size);
821 static void mempool_free_vp(void *element, void *pool_data)
823 size_t size = (size_t) pool_data;
825 vpfree(element, size);
828 static void *mempool_alloc_vp(gfp_t gfp_mask, void *pool_data)
830 size_t size = (size_t) pool_data;
832 return vpmalloc(size, gfp_mask);
835 int mempool_init_kvpmalloc_pool(mempool_t *pool, int min_nr, size_t size)
837 return size < PAGE_SIZE
838 ? mempool_init_kmalloc_pool(pool, min_nr, size)
839 : mempool_init(pool, min_nr, mempool_alloc_vp,
840 mempool_free_vp, (void *) size);
844 void eytzinger1_test(void)
846 unsigned inorder, eytz, size;
848 pr_info("1 based eytzinger test:");
853 unsigned extra = eytzinger1_extra(size);
856 pr_info("tree size %u", size);
858 BUG_ON(eytzinger1_prev(0, size) != eytzinger1_last(size));
859 BUG_ON(eytzinger1_next(0, size) != eytzinger1_first(size));
861 BUG_ON(eytzinger1_prev(eytzinger1_first(size), size) != 0);
862 BUG_ON(eytzinger1_next(eytzinger1_last(size), size) != 0);
865 eytzinger1_for_each(eytz, size) {
866 BUG_ON(__inorder_to_eytzinger1(inorder, size, extra) != eytz);
867 BUG_ON(__eytzinger1_to_inorder(eytz, size, extra) != inorder);
868 BUG_ON(eytz != eytzinger1_last(size) &&
869 eytzinger1_prev(eytzinger1_next(eytz, size), size) != eytz);
876 void eytzinger0_test(void)
879 unsigned inorder, eytz, size;
881 pr_info("0 based eytzinger test:");
886 unsigned extra = eytzinger0_extra(size);
889 pr_info("tree size %u", size);
891 BUG_ON(eytzinger0_prev(-1, size) != eytzinger0_last(size));
892 BUG_ON(eytzinger0_next(-1, size) != eytzinger0_first(size));
894 BUG_ON(eytzinger0_prev(eytzinger0_first(size), size) != -1);
895 BUG_ON(eytzinger0_next(eytzinger0_last(size), size) != -1);
898 eytzinger0_for_each(eytz, size) {
899 BUG_ON(__inorder_to_eytzinger0(inorder, size, extra) != eytz);
900 BUG_ON(__eytzinger0_to_inorder(eytz, size, extra) != inorder);
901 BUG_ON(eytz != eytzinger0_last(size) &&
902 eytzinger0_prev(eytzinger0_next(eytz, size), size) != eytz);
909 static inline int cmp_u16(const void *_l, const void *_r, size_t size)
911 const u16 *l = _l, *r = _r;
913 return (*l > *r) - (*r - *l);
916 static void eytzinger0_find_test_val(u16 *test_array, unsigned nr, u16 search)
918 int i, c1 = -1, c2 = -1;
921 r = eytzinger0_find_le(test_array, nr,
922 sizeof(test_array[0]),
927 for (i = 0; i < nr; i++)
928 if (test_array[i] <= search && test_array[i] > c2)
932 eytzinger0_for_each(i, nr)
933 pr_info("[%3u] = %12u", i, test_array[i]);
934 pr_info("find_le(%2u) -> [%2zi] = %2i should be %2i",
939 void eytzinger0_find_test(void)
941 unsigned i, nr, allocated = 1 << 12;
942 u16 *test_array = kmalloc_array(allocated, sizeof(test_array[0]), GFP_KERNEL);
944 for (nr = 1; nr < allocated; nr++) {
945 pr_info("testing %u elems", nr);
947 get_random_bytes(test_array, nr * sizeof(test_array[0]));
948 eytzinger0_sort(test_array, nr, sizeof(test_array[0]), cmp_u16, NULL);
950 /* verify array is sorted correctly: */
951 eytzinger0_for_each(i, nr)
952 BUG_ON(i != eytzinger0_last(nr) &&
953 test_array[i] > test_array[eytzinger0_next(i, nr)]);
955 for (i = 0; i < U16_MAX; i += 1 << 12)
956 eytzinger0_find_test_val(test_array, nr, i);
958 for (i = 0; i < nr; i++) {
959 eytzinger0_find_test_val(test_array, nr, test_array[i] - 1);
960 eytzinger0_find_test_val(test_array, nr, test_array[i]);
961 eytzinger0_find_test_val(test_array, nr, test_array[i] + 1);
970 * Accumulate percpu counters onto one cpu's copy - only valid when access
971 * against any percpu counter is guarded against
973 u64 *bch2_acc_percpu_u64s(u64 __percpu *p, unsigned nr)
978 /* access to pcpu vars has to be blocked by other locking */
980 ret = this_cpu_ptr(p);
983 for_each_possible_cpu(cpu) {
984 u64 *i = per_cpu_ptr(p, cpu);
987 acc_u64s(ret, i, nr);
988 memset(i, 0, nr * sizeof(u64));