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/ctype.h>
12 #include <linux/debugfs.h>
13 #include <linux/freezer.h>
14 #include <linux/kthread.h>
15 #include <linux/log2.h>
16 #include <linux/math64.h>
17 #include <linux/percpu.h>
18 #include <linux/preempt.h>
19 #include <linux/random.h>
20 #include <linux/seq_file.h>
21 #include <linux/string.h>
22 #include <linux/types.h>
23 #include <linux/sched/clock.h>
25 #include "eytzinger.h"
28 static const char si_units[] = "?kMGTPEZY";
30 static int __bch2_strtoh(const char *cp, u64 *res,
31 u64 t_max, bool t_signed)
33 bool positive = *cp != '-';
37 if (*cp == '+' || *cp == '-')
47 if (v > U64_MAX - (*cp - '0'))
51 } while (isdigit(*cp));
53 for (u = 1; u < strlen(si_units); u++)
54 if (*cp == si_units[u]) {
65 if (fls64(v) + u * 10 > 64)
86 #define STRTO_H(name, type) \
87 int bch2_ ## name ## _h(const char *cp, type *res) \
90 int ret = __bch2_strtoh(cp, &v, ANYSINT_MAX(type), \
91 ANYSINT_MAX(type) != ((type) ~0ULL)); \
96 STRTO_H(strtoint, int)
97 STRTO_H(strtouint, unsigned int)
98 STRTO_H(strtoll, long long)
99 STRTO_H(strtoull, unsigned long long)
100 STRTO_H(strtou64, u64)
102 void bch2_hprint(struct printbuf *buf, s64 v)
106 for (u = 0; v >= 1024 || v <= -1024; u++) {
107 t = v & ~(~0U << 10);
111 pr_buf(buf, "%lli", v);
114 * 103 is magic: t is in the range [-1023, 1023] and we want
115 * to turn it into [-9, 9]
117 if (u && v < 100 && v > -100)
118 pr_buf(buf, ".%i", t / 103);
120 pr_buf(buf, "%c", si_units[u]);
123 void bch2_string_opt_to_text(struct printbuf *out,
124 const char * const list[],
129 for (i = 0; list[i]; i++)
130 pr_buf(out, i == selected ? "[%s] " : "%s ", list[i]);
133 void bch2_flags_to_text(struct printbuf *out,
134 const char * const list[], u64 flags)
136 unsigned bit, nr = 0;
139 if (out->pos != out->end)
145 while (flags && (bit = __ffs(flags)) < nr) {
149 pr_buf(out, "%s", list[bit]);
154 u64 bch2_read_flag_list(char *opt, const char * const list[])
157 char *p, *s, *d = kstrndup(opt, PAGE_SIZE - 1, GFP_KERNEL);
164 while ((p = strsep(&s, ","))) {
165 int flag = match_string(list, -1, p);
179 bool bch2_is_zero(const void *_p, size_t n)
184 for (i = 0; i < n; i++)
190 static void bch2_quantiles_update(struct quantiles *q, u64 v)
194 while (i < ARRAY_SIZE(q->entries)) {
195 struct quantile_entry *e = q->entries + i;
197 if (unlikely(!e->step)) {
199 e->step = max_t(unsigned, v / 2, 1024);
200 } else if (e->m > v) {
201 e->m = e->m >= e->step
204 } else if (e->m < v) {
205 e->m = e->m + e->step > e->m
210 if ((e->m > v ? e->m - v : v - e->m) < e->step)
211 e->step = max_t(unsigned, e->step / 2, 1);
216 i = eytzinger0_child(i, v > e->m);
222 static void bch2_time_stats_update_one(struct time_stats *stats,
227 duration = time_after64(end, start)
229 freq = time_after64(end, stats->last_event)
230 ? end - stats->last_event : 0;
234 stats->average_duration = stats->average_duration
235 ? ewma_add(stats->average_duration, duration, 6)
238 stats->average_frequency = stats->average_frequency
239 ? ewma_add(stats->average_frequency, freq, 6)
242 stats->max_duration = max(stats->max_duration, duration);
244 stats->last_event = end;
246 bch2_quantiles_update(&stats->quantiles, duration);
249 void __bch2_time_stats_update(struct time_stats *stats, u64 start, u64 end)
253 if (!stats->buffer) {
254 spin_lock_irqsave(&stats->lock, flags);
255 bch2_time_stats_update_one(stats, start, end);
257 if (stats->average_frequency < 32 &&
260 alloc_percpu_gfp(struct time_stat_buffer,
262 spin_unlock_irqrestore(&stats->lock, flags);
264 struct time_stat_buffer_entry *i;
265 struct time_stat_buffer *b;
268 b = this_cpu_ptr(stats->buffer);
270 BUG_ON(b->nr >= ARRAY_SIZE(b->entries));
271 b->entries[b->nr++] = (struct time_stat_buffer_entry) {
276 if (b->nr == ARRAY_SIZE(b->entries)) {
277 spin_lock_irqsave(&stats->lock, flags);
279 i < b->entries + ARRAY_SIZE(b->entries);
281 bch2_time_stats_update_one(stats, i->start, i->end);
282 spin_unlock_irqrestore(&stats->lock, flags);
291 static const struct time_unit {
296 { "us", NSEC_PER_USEC },
297 { "ms", NSEC_PER_MSEC },
298 { "sec", NSEC_PER_SEC },
301 static const struct time_unit *pick_time_units(u64 ns)
303 const struct time_unit *u;
306 u + 1 < time_units + ARRAY_SIZE(time_units) &&
307 ns >= u[1].nsecs << 1;
314 static void pr_time_units(struct printbuf *out, u64 ns)
316 const struct time_unit *u = pick_time_units(ns);
318 pr_buf(out, "%llu %s", div_u64(ns, u->nsecs), u->name);
321 size_t bch2_time_stats_print(struct time_stats *stats, char *buf, size_t len)
323 struct printbuf out = _PBUF(buf, len);
324 const struct time_unit *u;
325 u64 freq = READ_ONCE(stats->average_frequency);
329 pr_buf(&out, "count:\t\t%llu\n",
331 pr_buf(&out, "rate:\t\t%llu/sec\n",
332 freq ? div64_u64(NSEC_PER_SEC, freq) : 0);
334 pr_buf(&out, "frequency:\t");
335 pr_time_units(&out, freq);
337 pr_buf(&out, "\navg duration:\t");
338 pr_time_units(&out, stats->average_duration);
340 pr_buf(&out, "\nmax duration:\t");
341 pr_time_units(&out, stats->max_duration);
343 i = eytzinger0_first(NR_QUANTILES);
344 u = pick_time_units(stats->quantiles.entries[i].m);
346 pr_buf(&out, "\nquantiles (%s):\t", u->name);
347 eytzinger0_for_each(i, NR_QUANTILES) {
348 bool is_last = eytzinger0_next(i, NR_QUANTILES) == -1;
350 q = max(stats->quantiles.entries[i].m, last_q);
351 pr_buf(&out, "%llu%s",
352 div_u64(q, u->nsecs),
353 is_last ? "\n" : " ");
357 return out.pos - buf;
360 void bch2_time_stats_exit(struct time_stats *stats)
362 free_percpu(stats->buffer);
365 void bch2_time_stats_init(struct time_stats *stats)
367 memset(stats, 0, sizeof(*stats));
368 spin_lock_init(&stats->lock);
374 * bch2_ratelimit_delay() - return how long to delay until the next time to do
377 * @d - the struct bch_ratelimit to update
379 * Returns the amount of time to delay by, in jiffies
381 u64 bch2_ratelimit_delay(struct bch_ratelimit *d)
383 u64 now = local_clock();
385 return time_after64(d->next, now)
386 ? nsecs_to_jiffies(d->next - now)
391 * bch2_ratelimit_increment() - increment @d by the amount of work done
393 * @d - the struct bch_ratelimit to update
394 * @done - the amount of work done, in arbitrary units
396 void bch2_ratelimit_increment(struct bch_ratelimit *d, u64 done)
398 u64 now = local_clock();
400 d->next += div_u64(done * NSEC_PER_SEC, d->rate);
402 if (time_before64(now + NSEC_PER_SEC, d->next))
403 d->next = now + NSEC_PER_SEC;
405 if (time_after64(now - NSEC_PER_SEC * 2, d->next))
406 d->next = now - NSEC_PER_SEC * 2;
412 * Updates pd_controller. Attempts to scale inputed values to units per second.
413 * @target: desired value
414 * @actual: current value
416 * @sign: 1 or -1; 1 if increasing the rate makes actual go up, -1 if increasing
417 * it makes actual go down.
419 void bch2_pd_controller_update(struct bch_pd_controller *pd,
420 s64 target, s64 actual, int sign)
422 s64 proportional, derivative, change;
424 unsigned long seconds_since_update = (jiffies - pd->last_update) / HZ;
426 if (seconds_since_update == 0)
429 pd->last_update = jiffies;
431 proportional = actual - target;
432 proportional *= seconds_since_update;
433 proportional = div_s64(proportional, pd->p_term_inverse);
435 derivative = actual - pd->last_actual;
436 derivative = div_s64(derivative, seconds_since_update);
437 derivative = ewma_add(pd->smoothed_derivative, derivative,
438 (pd->d_term / seconds_since_update) ?: 1);
439 derivative = derivative * pd->d_term;
440 derivative = div_s64(derivative, pd->p_term_inverse);
442 change = proportional + derivative;
444 /* Don't increase rate if not keeping up */
447 time_after64(local_clock(),
448 pd->rate.next + NSEC_PER_MSEC))
451 change *= (sign * -1);
453 pd->rate.rate = clamp_t(s64, (s64) pd->rate.rate + change,
456 pd->last_actual = actual;
457 pd->last_derivative = derivative;
458 pd->last_proportional = proportional;
459 pd->last_change = change;
460 pd->last_target = target;
463 void bch2_pd_controller_init(struct bch_pd_controller *pd)
465 pd->rate.rate = 1024;
466 pd->last_update = jiffies;
467 pd->p_term_inverse = 6000;
469 pd->d_smooth = pd->d_term;
470 pd->backpressure = 1;
473 size_t bch2_pd_controller_print_debug(struct bch_pd_controller *pd, char *buf)
475 /* 2^64 - 1 is 20 digits, plus null byte */
479 char proportional[21];
484 bch2_hprint(&PBUF(rate), pd->rate.rate);
485 bch2_hprint(&PBUF(actual), pd->last_actual);
486 bch2_hprint(&PBUF(target), pd->last_target);
487 bch2_hprint(&PBUF(proportional), pd->last_proportional);
488 bch2_hprint(&PBUF(derivative), pd->last_derivative);
489 bch2_hprint(&PBUF(change), pd->last_change);
491 next_io = div64_s64(pd->rate.next - local_clock(), NSEC_PER_MSEC);
497 "proportional:\t%s\n"
499 "change:\t\t%s/sec\n"
500 "next io:\t%llims\n",
501 rate, target, actual, proportional,
502 derivative, change, next_io);
507 void bch2_bio_map(struct bio *bio, void *base, size_t size)
510 struct page *page = is_vmalloc_addr(base)
511 ? vmalloc_to_page(base)
512 : virt_to_page(base);
513 unsigned offset = offset_in_page(base);
514 unsigned len = min_t(size_t, PAGE_SIZE - offset, size);
516 BUG_ON(!bio_add_page(bio, page, len, offset));
522 int bch2_bio_alloc_pages(struct bio *bio, size_t size, gfp_t gfp_mask)
525 struct page *page = alloc_page(gfp_mask);
526 unsigned len = min(PAGE_SIZE, size);
531 BUG_ON(!bio_add_page(bio, page, len, 0));
538 size_t bch2_rand_range(size_t max)
546 rand = get_random_long();
547 rand &= roundup_pow_of_two(max) - 1;
548 } while (rand >= max);
553 void memcpy_to_bio(struct bio *dst, struct bvec_iter dst_iter, void *src)
556 struct bvec_iter iter;
558 __bio_for_each_segment(bv, dst, iter, dst_iter) {
559 void *dstp = kmap_atomic(bv.bv_page);
560 memcpy(dstp + bv.bv_offset, src, bv.bv_len);
567 void memcpy_from_bio(void *dst, struct bio *src, struct bvec_iter src_iter)
570 struct bvec_iter iter;
572 __bio_for_each_segment(bv, src, iter, src_iter) {
573 void *srcp = kmap_atomic(bv.bv_page);
574 memcpy(dst, srcp + bv.bv_offset, bv.bv_len);
581 void bch_scnmemcpy(struct printbuf *out,
582 const char *src, size_t len)
584 size_t n = printbuf_remaining(out);
588 memcpy(out->pos, src, n);
594 #include "eytzinger.h"
596 static int alignment_ok(const void *base, size_t align)
598 return IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) ||
599 ((unsigned long)base & (align - 1)) == 0;
602 static void u32_swap(void *a, void *b, size_t size)
605 *(u32 *)a = *(u32 *)b;
609 static void u64_swap(void *a, void *b, size_t size)
612 *(u64 *)a = *(u64 *)b;
616 static void generic_swap(void *a, void *b, size_t size)
622 *(char *)a++ = *(char *)b;
624 } while (--size > 0);
627 static inline int do_cmp(void *base, size_t n, size_t size,
628 int (*cmp_func)(const void *, const void *, size_t),
631 return cmp_func(base + inorder_to_eytzinger0(l, n) * size,
632 base + inorder_to_eytzinger0(r, n) * size,
636 static inline void do_swap(void *base, size_t n, size_t size,
637 void (*swap_func)(void *, void *, size_t),
640 swap_func(base + inorder_to_eytzinger0(l, n) * size,
641 base + inorder_to_eytzinger0(r, n) * size,
645 void eytzinger0_sort(void *base, size_t n, size_t size,
646 int (*cmp_func)(const void *, const void *, size_t),
647 void (*swap_func)(void *, void *, size_t))
652 if (size == 4 && alignment_ok(base, 4))
653 swap_func = u32_swap;
654 else if (size == 8 && alignment_ok(base, 8))
655 swap_func = u64_swap;
657 swap_func = generic_swap;
661 for (i = n / 2 - 1; i >= 0; --i) {
662 for (r = i; r * 2 + 1 < n; r = c) {
666 do_cmp(base, n, size, cmp_func, c, c + 1) < 0)
669 if (do_cmp(base, n, size, cmp_func, r, c) >= 0)
672 do_swap(base, n, size, swap_func, r, c);
677 for (i = n - 1; i > 0; --i) {
678 do_swap(base, n, size, swap_func, 0, i);
680 for (r = 0; r * 2 + 1 < i; r = c) {
684 do_cmp(base, n, size, cmp_func, c, c + 1) < 0)
687 if (do_cmp(base, n, size, cmp_func, r, c) >= 0)
690 do_swap(base, n, size, swap_func, r, c);
695 void sort_cmp_size(void *base, size_t num, size_t size,
696 int (*cmp_func)(const void *, const void *, size_t),
697 void (*swap_func)(void *, void *, size_t size))
699 /* pre-scale counters for performance */
700 int i = (num/2 - 1) * size, n = num * size, c, r;
703 if (size == 4 && alignment_ok(base, 4))
704 swap_func = u32_swap;
705 else if (size == 8 && alignment_ok(base, 8))
706 swap_func = u64_swap;
708 swap_func = generic_swap;
712 for ( ; i >= 0; i -= size) {
713 for (r = i; r * 2 + size < n; r = c) {
716 cmp_func(base + c, base + c + size, size) < 0)
718 if (cmp_func(base + r, base + c, size) >= 0)
720 swap_func(base + r, base + c, size);
725 for (i = n - size; i > 0; i -= size) {
726 swap_func(base, base + i, size);
727 for (r = 0; r * 2 + size < i; r = c) {
730 cmp_func(base + c, base + c + size, size) < 0)
732 if (cmp_func(base + r, base + c, size) >= 0)
734 swap_func(base + r, base + c, size);
739 static void mempool_free_vp(void *element, void *pool_data)
741 size_t size = (size_t) pool_data;
743 vpfree(element, size);
746 static void *mempool_alloc_vp(gfp_t gfp_mask, void *pool_data)
748 size_t size = (size_t) pool_data;
750 return vpmalloc(size, gfp_mask);
753 int mempool_init_kvpmalloc_pool(mempool_t *pool, int min_nr, size_t size)
755 return size < PAGE_SIZE
756 ? mempool_init_kmalloc_pool(pool, min_nr, size)
757 : mempool_init(pool, min_nr, mempool_alloc_vp,
758 mempool_free_vp, (void *) size);
762 void eytzinger1_test(void)
764 unsigned inorder, eytz, size;
766 pr_info("1 based eytzinger test:");
771 unsigned extra = eytzinger1_extra(size);
774 pr_info("tree size %u", size);
776 BUG_ON(eytzinger1_prev(0, size) != eytzinger1_last(size));
777 BUG_ON(eytzinger1_next(0, size) != eytzinger1_first(size));
779 BUG_ON(eytzinger1_prev(eytzinger1_first(size), size) != 0);
780 BUG_ON(eytzinger1_next(eytzinger1_last(size), size) != 0);
783 eytzinger1_for_each(eytz, size) {
784 BUG_ON(__inorder_to_eytzinger1(inorder, size, extra) != eytz);
785 BUG_ON(__eytzinger1_to_inorder(eytz, size, extra) != inorder);
786 BUG_ON(eytz != eytzinger1_last(size) &&
787 eytzinger1_prev(eytzinger1_next(eytz, size), size) != eytz);
794 void eytzinger0_test(void)
797 unsigned inorder, eytz, size;
799 pr_info("0 based eytzinger test:");
804 unsigned extra = eytzinger0_extra(size);
807 pr_info("tree size %u", size);
809 BUG_ON(eytzinger0_prev(-1, size) != eytzinger0_last(size));
810 BUG_ON(eytzinger0_next(-1, size) != eytzinger0_first(size));
812 BUG_ON(eytzinger0_prev(eytzinger0_first(size), size) != -1);
813 BUG_ON(eytzinger0_next(eytzinger0_last(size), size) != -1);
816 eytzinger0_for_each(eytz, size) {
817 BUG_ON(__inorder_to_eytzinger0(inorder, size, extra) != eytz);
818 BUG_ON(__eytzinger0_to_inorder(eytz, size, extra) != inorder);
819 BUG_ON(eytz != eytzinger0_last(size) &&
820 eytzinger0_prev(eytzinger0_next(eytz, size), size) != eytz);
827 static inline int cmp_u16(const void *_l, const void *_r, size_t size)
829 const u16 *l = _l, *r = _r;
831 return (*l > *r) - (*r - *l);
834 static void eytzinger0_find_test_val(u16 *test_array, unsigned nr, u16 search)
836 int i, c1 = -1, c2 = -1;
839 r = eytzinger0_find_le(test_array, nr,
840 sizeof(test_array[0]),
845 for (i = 0; i < nr; i++)
846 if (test_array[i] <= search && test_array[i] > c2)
850 eytzinger0_for_each(i, nr)
851 pr_info("[%3u] = %12u", i, test_array[i]);
852 pr_info("find_le(%2u) -> [%2zi] = %2i should be %2i",
857 void eytzinger0_find_test(void)
859 unsigned i, nr, allocated = 1 << 12;
860 u16 *test_array = kmalloc_array(allocated, sizeof(test_array[0]), GFP_KERNEL);
862 for (nr = 1; nr < allocated; nr++) {
863 pr_info("testing %u elems", nr);
865 get_random_bytes(test_array, nr * sizeof(test_array[0]));
866 eytzinger0_sort(test_array, nr, sizeof(test_array[0]), cmp_u16, NULL);
868 /* verify array is sorted correctly: */
869 eytzinger0_for_each(i, nr)
870 BUG_ON(i != eytzinger0_last(nr) &&
871 test_array[i] > test_array[eytzinger0_next(i, nr)]);
873 for (i = 0; i < U16_MAX; i += 1 << 12)
874 eytzinger0_find_test_val(test_array, nr, i);
876 for (i = 0; i < nr; i++) {
877 eytzinger0_find_test_val(test_array, nr, test_array[i] - 1);
878 eytzinger0_find_test_val(test_array, nr, test_array[i]);
879 eytzinger0_find_test_val(test_array, nr, test_array[i] + 1);
888 * Accumulate percpu counters onto one cpu's copy - only valid when access
889 * against any percpu counter is guarded against
891 u64 *bch2_acc_percpu_u64s(u64 __percpu *p, unsigned nr)
897 ret = this_cpu_ptr(p);
900 for_each_possible_cpu(cpu) {
901 u64 *i = per_cpu_ptr(p, cpu);
904 acc_u64s(ret, i, nr);
905 memset(i, 0, nr * sizeof(u64));