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 u64 bch2_read_flag_list(char *opt, const char * const list[])
105 char *p, *s, *d = kstrdup(opt, GFP_KERNEL);
112 while ((p = strsep(&s, ","))) {
113 int flag = match_string(list, -1, p);
127 bool bch2_is_zero(const void *_p, size_t n)
132 for (i = 0; i < n; i++)
138 static void bch2_quantiles_update(struct quantiles *q, u64 v)
142 while (i < ARRAY_SIZE(q->entries)) {
143 struct quantile_entry *e = q->entries + i;
145 if (unlikely(!e->step)) {
147 e->step = max_t(unsigned, v / 2, 1024);
148 } else if (e->m > v) {
149 e->m = e->m >= e->step
152 } else if (e->m < v) {
153 e->m = e->m + e->step > e->m
158 if ((e->m > v ? e->m - v : v - e->m) < e->step)
159 e->step = max_t(unsigned, e->step / 2, 1);
164 i = eytzinger0_child(i, v > e->m);
170 static void bch2_time_stats_update_one(struct time_stats *stats,
175 duration = time_after64(end, start)
177 freq = time_after64(end, stats->last_event)
178 ? end - stats->last_event : 0;
182 stats->average_duration = stats->average_duration
183 ? ewma_add(stats->average_duration, duration, 6)
186 stats->average_frequency = stats->average_frequency
187 ? ewma_add(stats->average_frequency, freq, 6)
190 stats->max_duration = max(stats->max_duration, duration);
192 stats->last_event = end;
194 bch2_quantiles_update(&stats->quantiles, duration);
197 void __bch2_time_stats_update(struct time_stats *stats, u64 start, u64 end)
201 if (!stats->buffer) {
202 spin_lock_irqsave(&stats->lock, flags);
203 bch2_time_stats_update_one(stats, start, end);
205 if (stats->average_frequency < 32 &&
208 alloc_percpu_gfp(struct time_stat_buffer,
210 spin_unlock_irqrestore(&stats->lock, flags);
212 struct time_stat_buffer_entry *i;
213 struct time_stat_buffer *b;
216 b = this_cpu_ptr(stats->buffer);
218 BUG_ON(b->nr >= ARRAY_SIZE(b->entries));
219 b->entries[b->nr++] = (struct time_stat_buffer_entry) {
224 if (b->nr == ARRAY_SIZE(b->entries)) {
225 spin_lock_irqsave(&stats->lock, flags);
227 i < b->entries + ARRAY_SIZE(b->entries);
229 bch2_time_stats_update_one(stats, i->start, i->end);
230 spin_unlock_irqrestore(&stats->lock, flags);
239 static const struct time_unit {
244 { "us", NSEC_PER_USEC },
245 { "ms", NSEC_PER_MSEC },
246 { "sec", NSEC_PER_SEC },
249 static const struct time_unit *pick_time_units(u64 ns)
251 const struct time_unit *u;
254 u + 1 < time_units + ARRAY_SIZE(time_units) &&
255 ns >= u[1].nsecs << 1;
262 static void pr_time_units(struct printbuf *out, u64 ns)
264 const struct time_unit *u = pick_time_units(ns);
266 prt_printf(out, "%llu %s", div_u64(ns, u->nsecs), u->name);
269 void bch2_time_stats_to_text(struct printbuf *out, struct time_stats *stats)
271 const struct time_unit *u;
272 u64 freq = READ_ONCE(stats->average_frequency);
276 prt_printf(out, "count:\t\t%llu\n",
278 prt_printf(out, "rate:\t\t%llu/sec\n",
279 freq ? div64_u64(NSEC_PER_SEC, freq) : 0);
281 prt_printf(out, "frequency:\t");
282 pr_time_units(out, freq);
284 prt_printf(out, "\navg duration:\t");
285 pr_time_units(out, stats->average_duration);
287 prt_printf(out, "\nmax duration:\t");
288 pr_time_units(out, stats->max_duration);
290 i = eytzinger0_first(NR_QUANTILES);
291 u = pick_time_units(stats->quantiles.entries[i].m);
293 prt_printf(out, "\nquantiles (%s):\t", u->name);
294 eytzinger0_for_each(i, NR_QUANTILES) {
295 bool is_last = eytzinger0_next(i, NR_QUANTILES) == -1;
297 q = max(stats->quantiles.entries[i].m, last_q);
298 prt_printf(out, "%llu%s",
299 div_u64(q, u->nsecs),
300 is_last ? "\n" : " ");
305 void bch2_time_stats_exit(struct time_stats *stats)
307 free_percpu(stats->buffer);
310 void bch2_time_stats_init(struct time_stats *stats)
312 memset(stats, 0, sizeof(*stats));
313 spin_lock_init(&stats->lock);
319 * bch2_ratelimit_delay() - return how long to delay until the next time to do
322 * @d - the struct bch_ratelimit to update
324 * Returns the amount of time to delay by, in jiffies
326 u64 bch2_ratelimit_delay(struct bch_ratelimit *d)
328 u64 now = local_clock();
330 return time_after64(d->next, now)
331 ? nsecs_to_jiffies(d->next - now)
336 * bch2_ratelimit_increment() - increment @d by the amount of work done
338 * @d - the struct bch_ratelimit to update
339 * @done - the amount of work done, in arbitrary units
341 void bch2_ratelimit_increment(struct bch_ratelimit *d, u64 done)
343 u64 now = local_clock();
345 d->next += div_u64(done * NSEC_PER_SEC, d->rate);
347 if (time_before64(now + NSEC_PER_SEC, d->next))
348 d->next = now + NSEC_PER_SEC;
350 if (time_after64(now - NSEC_PER_SEC * 2, d->next))
351 d->next = now - NSEC_PER_SEC * 2;
357 * Updates pd_controller. Attempts to scale inputed values to units per second.
358 * @target: desired value
359 * @actual: current value
361 * @sign: 1 or -1; 1 if increasing the rate makes actual go up, -1 if increasing
362 * it makes actual go down.
364 void bch2_pd_controller_update(struct bch_pd_controller *pd,
365 s64 target, s64 actual, int sign)
367 s64 proportional, derivative, change;
369 unsigned long seconds_since_update = (jiffies - pd->last_update) / HZ;
371 if (seconds_since_update == 0)
374 pd->last_update = jiffies;
376 proportional = actual - target;
377 proportional *= seconds_since_update;
378 proportional = div_s64(proportional, pd->p_term_inverse);
380 derivative = actual - pd->last_actual;
381 derivative = div_s64(derivative, seconds_since_update);
382 derivative = ewma_add(pd->smoothed_derivative, derivative,
383 (pd->d_term / seconds_since_update) ?: 1);
384 derivative = derivative * pd->d_term;
385 derivative = div_s64(derivative, pd->p_term_inverse);
387 change = proportional + derivative;
389 /* Don't increase rate if not keeping up */
392 time_after64(local_clock(),
393 pd->rate.next + NSEC_PER_MSEC))
396 change *= (sign * -1);
398 pd->rate.rate = clamp_t(s64, (s64) pd->rate.rate + change,
401 pd->last_actual = actual;
402 pd->last_derivative = derivative;
403 pd->last_proportional = proportional;
404 pd->last_change = change;
405 pd->last_target = target;
408 void bch2_pd_controller_init(struct bch_pd_controller *pd)
410 pd->rate.rate = 1024;
411 pd->last_update = jiffies;
412 pd->p_term_inverse = 6000;
414 pd->d_smooth = pd->d_term;
415 pd->backpressure = 1;
418 void bch2_pd_controller_debug_to_text(struct printbuf *out, struct bch_pd_controller *pd)
420 out->tabstops[0] = 20;
422 prt_printf(out, "rate:");
424 prt_human_readable_s64(out, pd->rate.rate);
427 prt_printf(out, "target:");
429 prt_human_readable_u64(out, pd->last_target);
432 prt_printf(out, "actual:");
434 prt_human_readable_u64(out, pd->last_actual);
437 prt_printf(out, "proportional:");
439 prt_human_readable_s64(out, pd->last_proportional);
442 prt_printf(out, "derivative:");
444 prt_human_readable_s64(out, pd->last_derivative);
447 prt_printf(out, "change:");
449 prt_human_readable_s64(out, pd->last_change);
452 prt_printf(out, "next io:");
454 prt_printf(out, "%llims", div64_s64(pd->rate.next - local_clock(), NSEC_PER_MSEC));
460 void bch2_bio_map(struct bio *bio, void *base, size_t size)
463 struct page *page = is_vmalloc_addr(base)
464 ? vmalloc_to_page(base)
465 : virt_to_page(base);
466 unsigned offset = offset_in_page(base);
467 unsigned len = min_t(size_t, PAGE_SIZE - offset, size);
469 BUG_ON(!bio_add_page(bio, page, len, offset));
475 int bch2_bio_alloc_pages(struct bio *bio, size_t size, gfp_t gfp_mask)
478 struct page *page = alloc_page(gfp_mask);
479 unsigned len = min_t(size_t, PAGE_SIZE, size);
484 if (unlikely(!bio_add_page(bio, page, len, 0))) {
495 size_t bch2_rand_range(size_t max)
503 rand = get_random_long();
504 rand &= roundup_pow_of_two(max) - 1;
505 } while (rand >= max);
510 void memcpy_to_bio(struct bio *dst, struct bvec_iter dst_iter, const void *src)
513 struct bvec_iter iter;
515 __bio_for_each_segment(bv, dst, iter, dst_iter) {
516 void *dstp = kmap_atomic(bv.bv_page);
517 memcpy(dstp + bv.bv_offset, src, bv.bv_len);
524 void memcpy_from_bio(void *dst, struct bio *src, struct bvec_iter src_iter)
527 struct bvec_iter iter;
529 __bio_for_each_segment(bv, src, iter, src_iter) {
530 void *srcp = kmap_atomic(bv.bv_page);
531 memcpy(dst, srcp + bv.bv_offset, bv.bv_len);
538 #include "eytzinger.h"
540 static int alignment_ok(const void *base, size_t align)
542 return IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) ||
543 ((unsigned long)base & (align - 1)) == 0;
546 static void u32_swap(void *a, void *b, size_t size)
549 *(u32 *)a = *(u32 *)b;
553 static void u64_swap(void *a, void *b, size_t size)
556 *(u64 *)a = *(u64 *)b;
560 static void generic_swap(void *a, void *b, size_t size)
566 *(char *)a++ = *(char *)b;
568 } while (--size > 0);
571 static inline int do_cmp(void *base, size_t n, size_t size,
572 int (*cmp_func)(const void *, const void *, size_t),
575 return cmp_func(base + inorder_to_eytzinger0(l, n) * size,
576 base + inorder_to_eytzinger0(r, n) * size,
580 static inline void do_swap(void *base, size_t n, size_t size,
581 void (*swap_func)(void *, void *, size_t),
584 swap_func(base + inorder_to_eytzinger0(l, n) * size,
585 base + inorder_to_eytzinger0(r, n) * size,
589 void eytzinger0_sort(void *base, size_t n, size_t size,
590 int (*cmp_func)(const void *, const void *, size_t),
591 void (*swap_func)(void *, void *, size_t))
596 if (size == 4 && alignment_ok(base, 4))
597 swap_func = u32_swap;
598 else if (size == 8 && alignment_ok(base, 8))
599 swap_func = u64_swap;
601 swap_func = generic_swap;
605 for (i = n / 2 - 1; i >= 0; --i) {
606 for (r = i; r * 2 + 1 < n; r = c) {
610 do_cmp(base, n, size, cmp_func, c, c + 1) < 0)
613 if (do_cmp(base, n, size, cmp_func, r, c) >= 0)
616 do_swap(base, n, size, swap_func, r, c);
621 for (i = n - 1; i > 0; --i) {
622 do_swap(base, n, size, swap_func, 0, i);
624 for (r = 0; r * 2 + 1 < i; r = c) {
628 do_cmp(base, n, size, cmp_func, c, c + 1) < 0)
631 if (do_cmp(base, n, size, cmp_func, r, c) >= 0)
634 do_swap(base, n, size, swap_func, r, c);
639 void sort_cmp_size(void *base, size_t num, size_t size,
640 int (*cmp_func)(const void *, const void *, size_t),
641 void (*swap_func)(void *, void *, size_t size))
643 /* pre-scale counters for performance */
644 int i = (num/2 - 1) * size, n = num * size, c, r;
647 if (size == 4 && alignment_ok(base, 4))
648 swap_func = u32_swap;
649 else if (size == 8 && alignment_ok(base, 8))
650 swap_func = u64_swap;
652 swap_func = generic_swap;
656 for ( ; i >= 0; i -= size) {
657 for (r = i; r * 2 + size < n; r = c) {
660 cmp_func(base + c, base + c + size, size) < 0)
662 if (cmp_func(base + r, base + c, size) >= 0)
664 swap_func(base + r, base + c, size);
669 for (i = n - size; i > 0; i -= size) {
670 swap_func(base, base + i, size);
671 for (r = 0; r * 2 + size < i; r = c) {
674 cmp_func(base + c, base + c + size, size) < 0)
676 if (cmp_func(base + r, base + c, size) >= 0)
678 swap_func(base + r, base + c, size);
683 static void mempool_free_vp(void *element, void *pool_data)
685 size_t size = (size_t) pool_data;
687 vpfree(element, size);
690 static void *mempool_alloc_vp(gfp_t gfp_mask, void *pool_data)
692 size_t size = (size_t) pool_data;
694 return vpmalloc(size, gfp_mask);
697 int mempool_init_kvpmalloc_pool(mempool_t *pool, int min_nr, size_t size)
699 return size < PAGE_SIZE
700 ? mempool_init_kmalloc_pool(pool, min_nr, size)
701 : mempool_init(pool, min_nr, mempool_alloc_vp,
702 mempool_free_vp, (void *) size);
706 void eytzinger1_test(void)
708 unsigned inorder, eytz, size;
710 pr_info("1 based eytzinger test:");
715 unsigned extra = eytzinger1_extra(size);
718 pr_info("tree size %u", size);
720 BUG_ON(eytzinger1_prev(0, size) != eytzinger1_last(size));
721 BUG_ON(eytzinger1_next(0, size) != eytzinger1_first(size));
723 BUG_ON(eytzinger1_prev(eytzinger1_first(size), size) != 0);
724 BUG_ON(eytzinger1_next(eytzinger1_last(size), size) != 0);
727 eytzinger1_for_each(eytz, size) {
728 BUG_ON(__inorder_to_eytzinger1(inorder, size, extra) != eytz);
729 BUG_ON(__eytzinger1_to_inorder(eytz, size, extra) != inorder);
730 BUG_ON(eytz != eytzinger1_last(size) &&
731 eytzinger1_prev(eytzinger1_next(eytz, size), size) != eytz);
738 void eytzinger0_test(void)
741 unsigned inorder, eytz, size;
743 pr_info("0 based eytzinger test:");
748 unsigned extra = eytzinger0_extra(size);
751 pr_info("tree size %u", size);
753 BUG_ON(eytzinger0_prev(-1, size) != eytzinger0_last(size));
754 BUG_ON(eytzinger0_next(-1, size) != eytzinger0_first(size));
756 BUG_ON(eytzinger0_prev(eytzinger0_first(size), size) != -1);
757 BUG_ON(eytzinger0_next(eytzinger0_last(size), size) != -1);
760 eytzinger0_for_each(eytz, size) {
761 BUG_ON(__inorder_to_eytzinger0(inorder, size, extra) != eytz);
762 BUG_ON(__eytzinger0_to_inorder(eytz, size, extra) != inorder);
763 BUG_ON(eytz != eytzinger0_last(size) &&
764 eytzinger0_prev(eytzinger0_next(eytz, size), size) != eytz);
771 static inline int cmp_u16(const void *_l, const void *_r, size_t size)
773 const u16 *l = _l, *r = _r;
775 return (*l > *r) - (*r - *l);
778 static void eytzinger0_find_test_val(u16 *test_array, unsigned nr, u16 search)
780 int i, c1 = -1, c2 = -1;
783 r = eytzinger0_find_le(test_array, nr,
784 sizeof(test_array[0]),
789 for (i = 0; i < nr; i++)
790 if (test_array[i] <= search && test_array[i] > c2)
794 eytzinger0_for_each(i, nr)
795 pr_info("[%3u] = %12u", i, test_array[i]);
796 pr_info("find_le(%2u) -> [%2zi] = %2i should be %2i",
801 void eytzinger0_find_test(void)
803 unsigned i, nr, allocated = 1 << 12;
804 u16 *test_array = kmalloc_array(allocated, sizeof(test_array[0]), GFP_KERNEL);
806 for (nr = 1; nr < allocated; nr++) {
807 pr_info("testing %u elems", nr);
809 get_random_bytes(test_array, nr * sizeof(test_array[0]));
810 eytzinger0_sort(test_array, nr, sizeof(test_array[0]), cmp_u16, NULL);
812 /* verify array is sorted correctly: */
813 eytzinger0_for_each(i, nr)
814 BUG_ON(i != eytzinger0_last(nr) &&
815 test_array[i] > test_array[eytzinger0_next(i, nr)]);
817 for (i = 0; i < U16_MAX; i += 1 << 12)
818 eytzinger0_find_test_val(test_array, nr, i);
820 for (i = 0; i < nr; i++) {
821 eytzinger0_find_test_val(test_array, nr, test_array[i] - 1);
822 eytzinger0_find_test_val(test_array, nr, test_array[i]);
823 eytzinger0_find_test_val(test_array, nr, test_array[i] + 1);
832 * Accumulate percpu counters onto one cpu's copy - only valid when access
833 * against any percpu counter is guarded against
835 u64 *bch2_acc_percpu_u64s(u64 __percpu *p, unsigned nr)
840 /* access to pcpu vars has to be blocked by other locking */
842 ret = this_cpu_ptr(p);
845 for_each_possible_cpu(cpu) {
846 u64 *i = per_cpu_ptr(p, cpu);
849 acc_u64s(ret, i, nr);
850 memset(i, 0, nr * sizeof(u64));