]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/util.c
Update bcachefs sources to 3704d0779c bcachefs: Improved human readable integer parsing
[bcachefs-tools-debian] / libbcachefs / util.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * random utiility code, for bcache but in theory not specific to bcache
4  *
5  * Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
6  * Copyright 2012 Google, Inc.
7  */
8
9 #include <linux/bio.h>
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>
24
25 #include "eytzinger.h"
26 #include "util.h"
27
28 static const char si_units[] = "?kMGTPEZY";
29
30 /* string_get_size units: */
31 static const char *const units_2[] = {
32         "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"
33 };
34 static const char *const units_10[] = {
35         "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"
36 };
37
38 static int parse_u64(const char *cp, u64 *res)
39 {
40         const char *start = cp;
41         u64 v = 0;
42
43         if (!isdigit(*cp))
44                 return -EINVAL;
45
46         do {
47                 if (v > U64_MAX / 10)
48                         return -ERANGE;
49                 v *= 10;
50                 if (v > U64_MAX - (*cp - '0'))
51                         return -ERANGE;
52                 v += *cp - '0';
53                 cp++;
54         } while (isdigit(*cp));
55
56         *res = v;
57         return cp - start;
58 }
59
60 static int bch2_pow(u64 n, u64 p, u64 *res)
61 {
62         *res = 1;
63
64         while (p--) {
65                 if (*res > div_u64(U64_MAX, n))
66                         return -ERANGE;
67                 *res *= n;
68         }
69         return 0;
70 }
71
72 static int parse_unit_suffix(const char *cp, u64 *res)
73 {
74         const char *start = cp;
75         u64 base = 1024;
76         unsigned u;
77         int ret;
78
79         if (*cp == ' ')
80                 cp++;
81
82         for (u = 1; u < strlen(si_units); u++)
83                 if (*cp == si_units[u]) {
84                         cp++;
85                         goto got_unit;
86                 }
87
88         for (u = 0; u < ARRAY_SIZE(units_2); u++)
89                 if (!strncmp(cp, units_2[u], strlen(units_2[u]))) {
90                         cp += strlen(units_2[u]);
91                         goto got_unit;
92                 }
93
94         for (u = 0; u < ARRAY_SIZE(units_10); u++)
95                 if (!strncmp(cp, units_10[u], strlen(units_10[u]))) {
96                         cp += strlen(units_10[u]);
97                         base = 1000;
98                         goto got_unit;
99                 }
100
101         *res = 1;
102         return 0;
103 got_unit:
104         ret = bch2_pow(base, u, res);
105         if (ret)
106                 return ret;
107
108         return cp - start;
109 }
110
111 #define parse_or_ret(cp, _f)                    \
112 do {                                            \
113         int ret = _f;                           \
114         if (ret < 0)                            \
115                 return ret;                     \
116         cp += ret;                              \
117 } while (0)
118
119 static int __bch2_strtou64_h(const char *cp, u64 *res)
120 {
121         const char *start = cp;
122         u64 v = 0, b, f_n = 0, f_d = 1;
123         int ret;
124
125         parse_or_ret(cp, parse_u64(cp, &v));
126
127         if (*cp == '.') {
128                 cp++;
129                 ret = parse_u64(cp, &f_n);
130                 if (ret < 0)
131                         return ret;
132                 cp += ret;
133
134                 ret = bch2_pow(10, ret, &f_d);
135                 if (ret)
136                         return ret;
137         }
138
139         parse_or_ret(cp, parse_unit_suffix(cp, &b));
140
141         if (v > div_u64(U64_MAX, b))
142                 return -ERANGE;
143         v *= b;
144
145         if (f_n > div_u64(U64_MAX, b))
146                 return -ERANGE;
147
148         if (v + (f_n * b) / f_d < v)
149                 return -ERANGE;
150         v += (f_n * b) / f_d;
151
152         *res = v;
153         return cp - start;
154 }
155
156 static int __bch2_strtoh(const char *cp, u64 *res,
157                          u64 t_max, bool t_signed)
158 {
159         bool positive = *cp != '-';
160         u64 v = 0;
161
162         if (*cp == '+' || *cp == '-')
163                 cp++;
164
165         parse_or_ret(cp, __bch2_strtou64_h(cp, &v));
166
167         if (*cp == '\n')
168                 cp++;
169         if (*cp)
170                 return -EINVAL;
171
172         if (positive) {
173                 if (v > t_max)
174                         return -ERANGE;
175         } else {
176                 if (v && !t_signed)
177                         return -ERANGE;
178
179                 if (v > t_max + 1)
180                         return -ERANGE;
181                 v = -v;
182         }
183
184         *res = v;
185         return 0;
186 }
187
188 #define STRTO_H(name, type)                                     \
189 int bch2_ ## name ## _h(const char *cp, type *res)              \
190 {                                                               \
191         u64 v = 0;                                              \
192         int ret = __bch2_strtoh(cp, &v, ANYSINT_MAX(type),      \
193                         ANYSINT_MAX(type) != ((type) ~0ULL));   \
194         *res = v;                                               \
195         return ret;                                             \
196 }
197
198 STRTO_H(strtoint, int)
199 STRTO_H(strtouint, unsigned int)
200 STRTO_H(strtoll, long long)
201 STRTO_H(strtoull, unsigned long long)
202 STRTO_H(strtou64, u64)
203
204 u64 bch2_read_flag_list(char *opt, const char * const list[])
205 {
206         u64 ret = 0;
207         char *p, *s, *d = kstrdup(opt, GFP_KERNEL);
208
209         if (!d)
210                 return -ENOMEM;
211
212         s = strim(d);
213
214         while ((p = strsep(&s, ","))) {
215                 int flag = match_string(list, -1, p);
216                 if (flag < 0) {
217                         ret = -1;
218                         break;
219                 }
220
221                 ret |= 1 << flag;
222         }
223
224         kfree(d);
225
226         return ret;
227 }
228
229 bool bch2_is_zero(const void *_p, size_t n)
230 {
231         const char *p = _p;
232         size_t i;
233
234         for (i = 0; i < n; i++)
235                 if (p[i])
236                         return false;
237         return true;
238 }
239
240 static void bch2_quantiles_update(struct quantiles *q, u64 v)
241 {
242         unsigned i = 0;
243
244         while (i < ARRAY_SIZE(q->entries)) {
245                 struct quantile_entry *e = q->entries + i;
246
247                 if (unlikely(!e->step)) {
248                         e->m = v;
249                         e->step = max_t(unsigned, v / 2, 1024);
250                 } else if (e->m > v) {
251                         e->m = e->m >= e->step
252                                 ? e->m - e->step
253                                 : 0;
254                 } else if (e->m < v) {
255                         e->m = e->m + e->step > e->m
256                                 ? e->m + e->step
257                                 : U32_MAX;
258                 }
259
260                 if ((e->m > v ? e->m - v : v - e->m) < e->step)
261                         e->step = max_t(unsigned, e->step / 2, 1);
262
263                 if (v >= e->m)
264                         break;
265
266                 i = eytzinger0_child(i, v > e->m);
267         }
268 }
269
270 /* time stats: */
271
272 static void bch2_time_stats_update_one(struct time_stats *stats,
273                                        u64 start, u64 end)
274 {
275         u64 duration, freq;
276
277         duration        = time_after64(end, start)
278                 ? end - start : 0;
279         freq            = time_after64(end, stats->last_event)
280                 ? end - stats->last_event : 0;
281
282         stats->count++;
283
284         stats->average_duration = stats->average_duration
285                 ? ewma_add(stats->average_duration, duration, 6)
286                 : duration;
287
288         stats->average_frequency = stats->average_frequency
289                 ? ewma_add(stats->average_frequency, freq, 6)
290                 : freq;
291
292         stats->max_duration = max(stats->max_duration, duration);
293
294         stats->last_event = end;
295
296         bch2_quantiles_update(&stats->quantiles, duration);
297 }
298
299 void __bch2_time_stats_update(struct time_stats *stats, u64 start, u64 end)
300 {
301         unsigned long flags;
302
303         if (!stats->buffer) {
304                 spin_lock_irqsave(&stats->lock, flags);
305                 bch2_time_stats_update_one(stats, start, end);
306
307                 if (stats->average_frequency < 32 &&
308                     stats->count > 1024)
309                         stats->buffer =
310                                 alloc_percpu_gfp(struct time_stat_buffer,
311                                                  GFP_ATOMIC);
312                 spin_unlock_irqrestore(&stats->lock, flags);
313         } else {
314                 struct time_stat_buffer_entry *i;
315                 struct time_stat_buffer *b;
316
317                 preempt_disable();
318                 b = this_cpu_ptr(stats->buffer);
319
320                 BUG_ON(b->nr >= ARRAY_SIZE(b->entries));
321                 b->entries[b->nr++] = (struct time_stat_buffer_entry) {
322                         .start = start,
323                         .end = end
324                 };
325
326                 if (b->nr == ARRAY_SIZE(b->entries)) {
327                         spin_lock_irqsave(&stats->lock, flags);
328                         for (i = b->entries;
329                              i < b->entries + ARRAY_SIZE(b->entries);
330                              i++)
331                                 bch2_time_stats_update_one(stats, i->start, i->end);
332                         spin_unlock_irqrestore(&stats->lock, flags);
333
334                         b->nr = 0;
335                 }
336
337                 preempt_enable();
338         }
339 }
340
341 static const struct time_unit {
342         const char      *name;
343         u32             nsecs;
344 } time_units[] = {
345         { "ns",         1               },
346         { "us",         NSEC_PER_USEC   },
347         { "ms",         NSEC_PER_MSEC   },
348         { "sec",        NSEC_PER_SEC    },
349 };
350
351 static const struct time_unit *pick_time_units(u64 ns)
352 {
353         const struct time_unit *u;
354
355         for (u = time_units;
356              u + 1 < time_units + ARRAY_SIZE(time_units) &&
357              ns >= u[1].nsecs << 1;
358              u++)
359                 ;
360
361         return u;
362 }
363
364 static void pr_time_units(struct printbuf *out, u64 ns)
365 {
366         const struct time_unit *u = pick_time_units(ns);
367
368         prt_printf(out, "%llu %s", div_u64(ns, u->nsecs), u->name);
369 }
370
371 void bch2_time_stats_to_text(struct printbuf *out, struct time_stats *stats)
372 {
373         const struct time_unit *u;
374         u64 freq = READ_ONCE(stats->average_frequency);
375         u64 q, last_q = 0;
376         int i;
377
378         prt_printf(out, "count:\t\t%llu\n",
379                          stats->count);
380         prt_printf(out, "rate:\t\t%llu/sec\n",
381                freq ?  div64_u64(NSEC_PER_SEC, freq) : 0);
382
383         prt_printf(out, "frequency:\t");
384         pr_time_units(out, freq);
385
386         prt_printf(out, "\navg duration:\t");
387         pr_time_units(out, stats->average_duration);
388
389         prt_printf(out, "\nmax duration:\t");
390         pr_time_units(out, stats->max_duration);
391
392         i = eytzinger0_first(NR_QUANTILES);
393         u = pick_time_units(stats->quantiles.entries[i].m);
394
395         prt_printf(out, "\nquantiles (%s):\t", u->name);
396         eytzinger0_for_each(i, NR_QUANTILES) {
397                 bool is_last = eytzinger0_next(i, NR_QUANTILES) == -1;
398
399                 q = max(stats->quantiles.entries[i].m, last_q);
400                 prt_printf(out, "%llu%s",
401                        div_u64(q, u->nsecs),
402                        is_last ? "\n" : " ");
403                 last_q = q;
404         }
405 }
406
407 void bch2_time_stats_exit(struct time_stats *stats)
408 {
409         free_percpu(stats->buffer);
410 }
411
412 void bch2_time_stats_init(struct time_stats *stats)
413 {
414         memset(stats, 0, sizeof(*stats));
415         spin_lock_init(&stats->lock);
416 }
417
418 /* ratelimit: */
419
420 /**
421  * bch2_ratelimit_delay() - return how long to delay until the next time to do
422  * some work
423  *
424  * @d - the struct bch_ratelimit to update
425  *
426  * Returns the amount of time to delay by, in jiffies
427  */
428 u64 bch2_ratelimit_delay(struct bch_ratelimit *d)
429 {
430         u64 now = local_clock();
431
432         return time_after64(d->next, now)
433                 ? nsecs_to_jiffies(d->next - now)
434                 : 0;
435 }
436
437 /**
438  * bch2_ratelimit_increment() - increment @d by the amount of work done
439  *
440  * @d - the struct bch_ratelimit to update
441  * @done - the amount of work done, in arbitrary units
442  */
443 void bch2_ratelimit_increment(struct bch_ratelimit *d, u64 done)
444 {
445         u64 now = local_clock();
446
447         d->next += div_u64(done * NSEC_PER_SEC, d->rate);
448
449         if (time_before64(now + NSEC_PER_SEC, d->next))
450                 d->next = now + NSEC_PER_SEC;
451
452         if (time_after64(now - NSEC_PER_SEC * 2, d->next))
453                 d->next = now - NSEC_PER_SEC * 2;
454 }
455
456 /* pd controller: */
457
458 /*
459  * Updates pd_controller. Attempts to scale inputed values to units per second.
460  * @target: desired value
461  * @actual: current value
462  *
463  * @sign: 1 or -1; 1 if increasing the rate makes actual go up, -1 if increasing
464  * it makes actual go down.
465  */
466 void bch2_pd_controller_update(struct bch_pd_controller *pd,
467                               s64 target, s64 actual, int sign)
468 {
469         s64 proportional, derivative, change;
470
471         unsigned long seconds_since_update = (jiffies - pd->last_update) / HZ;
472
473         if (seconds_since_update == 0)
474                 return;
475
476         pd->last_update = jiffies;
477
478         proportional = actual - target;
479         proportional *= seconds_since_update;
480         proportional = div_s64(proportional, pd->p_term_inverse);
481
482         derivative = actual - pd->last_actual;
483         derivative = div_s64(derivative, seconds_since_update);
484         derivative = ewma_add(pd->smoothed_derivative, derivative,
485                               (pd->d_term / seconds_since_update) ?: 1);
486         derivative = derivative * pd->d_term;
487         derivative = div_s64(derivative, pd->p_term_inverse);
488
489         change = proportional + derivative;
490
491         /* Don't increase rate if not keeping up */
492         if (change > 0 &&
493             pd->backpressure &&
494             time_after64(local_clock(),
495                          pd->rate.next + NSEC_PER_MSEC))
496                 change = 0;
497
498         change *= (sign * -1);
499
500         pd->rate.rate = clamp_t(s64, (s64) pd->rate.rate + change,
501                                 1, UINT_MAX);
502
503         pd->last_actual         = actual;
504         pd->last_derivative     = derivative;
505         pd->last_proportional   = proportional;
506         pd->last_change         = change;
507         pd->last_target         = target;
508 }
509
510 void bch2_pd_controller_init(struct bch_pd_controller *pd)
511 {
512         pd->rate.rate           = 1024;
513         pd->last_update         = jiffies;
514         pd->p_term_inverse      = 6000;
515         pd->d_term              = 30;
516         pd->d_smooth            = pd->d_term;
517         pd->backpressure        = 1;
518 }
519
520 void bch2_pd_controller_debug_to_text(struct printbuf *out, struct bch_pd_controller *pd)
521 {
522         out->tabstops[0] = 20;
523
524         prt_printf(out, "rate:");
525         prt_tab(out);
526         prt_human_readable_s64(out, pd->rate.rate);
527         prt_newline(out);
528
529         prt_printf(out, "target:");
530         prt_tab(out);
531         prt_human_readable_u64(out, pd->last_target);
532         prt_newline(out);
533
534         prt_printf(out, "actual:");
535         prt_tab(out);
536         prt_human_readable_u64(out, pd->last_actual);
537         prt_newline(out);
538
539         prt_printf(out, "proportional:");
540         prt_tab(out);
541         prt_human_readable_s64(out, pd->last_proportional);
542         prt_newline(out);
543
544         prt_printf(out, "derivative:");
545         prt_tab(out);
546         prt_human_readable_s64(out, pd->last_derivative);
547         prt_newline(out);
548
549         prt_printf(out, "change:");
550         prt_tab(out);
551         prt_human_readable_s64(out, pd->last_change);
552         prt_newline(out);
553
554         prt_printf(out, "next io:");
555         prt_tab(out);
556         prt_printf(out, "%llims", div64_s64(pd->rate.next - local_clock(), NSEC_PER_MSEC));
557         prt_newline(out);
558 }
559
560 /* misc: */
561
562 void bch2_bio_map(struct bio *bio, void *base, size_t size)
563 {
564         while (size) {
565                 struct page *page = is_vmalloc_addr(base)
566                                 ? vmalloc_to_page(base)
567                                 : virt_to_page(base);
568                 unsigned offset = offset_in_page(base);
569                 unsigned len = min_t(size_t, PAGE_SIZE - offset, size);
570
571                 BUG_ON(!bio_add_page(bio, page, len, offset));
572                 size -= len;
573                 base += len;
574         }
575 }
576
577 int bch2_bio_alloc_pages(struct bio *bio, size_t size, gfp_t gfp_mask)
578 {
579         while (size) {
580                 struct page *page = alloc_page(gfp_mask);
581                 unsigned len = min_t(size_t, PAGE_SIZE, size);
582
583                 if (!page)
584                         return -ENOMEM;
585
586                 if (unlikely(!bio_add_page(bio, page, len, 0))) {
587                         __free_page(page);
588                         break;
589                 }
590
591                 size -= len;
592         }
593
594         return 0;
595 }
596
597 size_t bch2_rand_range(size_t max)
598 {
599         size_t rand;
600
601         if (!max)
602                 return 0;
603
604         do {
605                 rand = get_random_long();
606                 rand &= roundup_pow_of_two(max) - 1;
607         } while (rand >= max);
608
609         return rand;
610 }
611
612 void memcpy_to_bio(struct bio *dst, struct bvec_iter dst_iter, const void *src)
613 {
614         struct bio_vec bv;
615         struct bvec_iter iter;
616
617         __bio_for_each_segment(bv, dst, iter, dst_iter) {
618                 void *dstp = kmap_atomic(bv.bv_page);
619                 memcpy(dstp + bv.bv_offset, src, bv.bv_len);
620                 kunmap_atomic(dstp);
621
622                 src += bv.bv_len;
623         }
624 }
625
626 void memcpy_from_bio(void *dst, struct bio *src, struct bvec_iter src_iter)
627 {
628         struct bio_vec bv;
629         struct bvec_iter iter;
630
631         __bio_for_each_segment(bv, src, iter, src_iter) {
632                 void *srcp = kmap_atomic(bv.bv_page);
633                 memcpy(dst, srcp + bv.bv_offset, bv.bv_len);
634                 kunmap_atomic(srcp);
635
636                 dst += bv.bv_len;
637         }
638 }
639
640 #include "eytzinger.h"
641
642 static int alignment_ok(const void *base, size_t align)
643 {
644         return IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) ||
645                 ((unsigned long)base & (align - 1)) == 0;
646 }
647
648 static void u32_swap(void *a, void *b, size_t size)
649 {
650         u32 t = *(u32 *)a;
651         *(u32 *)a = *(u32 *)b;
652         *(u32 *)b = t;
653 }
654
655 static void u64_swap(void *a, void *b, size_t size)
656 {
657         u64 t = *(u64 *)a;
658         *(u64 *)a = *(u64 *)b;
659         *(u64 *)b = t;
660 }
661
662 static void generic_swap(void *a, void *b, size_t size)
663 {
664         char t;
665
666         do {
667                 t = *(char *)a;
668                 *(char *)a++ = *(char *)b;
669                 *(char *)b++ = t;
670         } while (--size > 0);
671 }
672
673 static inline int do_cmp(void *base, size_t n, size_t size,
674                          int (*cmp_func)(const void *, const void *, size_t),
675                          size_t l, size_t r)
676 {
677         return cmp_func(base + inorder_to_eytzinger0(l, n) * size,
678                         base + inorder_to_eytzinger0(r, n) * size,
679                         size);
680 }
681
682 static inline void do_swap(void *base, size_t n, size_t size,
683                            void (*swap_func)(void *, void *, size_t),
684                            size_t l, size_t r)
685 {
686         swap_func(base + inorder_to_eytzinger0(l, n) * size,
687                   base + inorder_to_eytzinger0(r, n) * size,
688                   size);
689 }
690
691 void eytzinger0_sort(void *base, size_t n, size_t size,
692                      int (*cmp_func)(const void *, const void *, size_t),
693                      void (*swap_func)(void *, void *, size_t))
694 {
695         int i, c, r;
696
697         if (!swap_func) {
698                 if (size == 4 && alignment_ok(base, 4))
699                         swap_func = u32_swap;
700                 else if (size == 8 && alignment_ok(base, 8))
701                         swap_func = u64_swap;
702                 else
703                         swap_func = generic_swap;
704         }
705
706         /* heapify */
707         for (i = n / 2 - 1; i >= 0; --i) {
708                 for (r = i; r * 2 + 1 < n; r = c) {
709                         c = r * 2 + 1;
710
711                         if (c + 1 < n &&
712                             do_cmp(base, n, size, cmp_func, c, c + 1) < 0)
713                                 c++;
714
715                         if (do_cmp(base, n, size, cmp_func, r, c) >= 0)
716                                 break;
717
718                         do_swap(base, n, size, swap_func, r, c);
719                 }
720         }
721
722         /* sort */
723         for (i = n - 1; i > 0; --i) {
724                 do_swap(base, n, size, swap_func, 0, i);
725
726                 for (r = 0; r * 2 + 1 < i; r = c) {
727                         c = r * 2 + 1;
728
729                         if (c + 1 < i &&
730                             do_cmp(base, n, size, cmp_func, c, c + 1) < 0)
731                                 c++;
732
733                         if (do_cmp(base, n, size, cmp_func, r, c) >= 0)
734                                 break;
735
736                         do_swap(base, n, size, swap_func, r, c);
737                 }
738         }
739 }
740
741 void sort_cmp_size(void *base, size_t num, size_t size,
742           int (*cmp_func)(const void *, const void *, size_t),
743           void (*swap_func)(void *, void *, size_t size))
744 {
745         /* pre-scale counters for performance */
746         int i = (num/2 - 1) * size, n = num * size, c, r;
747
748         if (!swap_func) {
749                 if (size == 4 && alignment_ok(base, 4))
750                         swap_func = u32_swap;
751                 else if (size == 8 && alignment_ok(base, 8))
752                         swap_func = u64_swap;
753                 else
754                         swap_func = generic_swap;
755         }
756
757         /* heapify */
758         for ( ; i >= 0; i -= size) {
759                 for (r = i; r * 2 + size < n; r  = c) {
760                         c = r * 2 + size;
761                         if (c < n - size &&
762                             cmp_func(base + c, base + c + size, size) < 0)
763                                 c += size;
764                         if (cmp_func(base + r, base + c, size) >= 0)
765                                 break;
766                         swap_func(base + r, base + c, size);
767                 }
768         }
769
770         /* sort */
771         for (i = n - size; i > 0; i -= size) {
772                 swap_func(base, base + i, size);
773                 for (r = 0; r * 2 + size < i; r = c) {
774                         c = r * 2 + size;
775                         if (c < i - size &&
776                             cmp_func(base + c, base + c + size, size) < 0)
777                                 c += size;
778                         if (cmp_func(base + r, base + c, size) >= 0)
779                                 break;
780                         swap_func(base + r, base + c, size);
781                 }
782         }
783 }
784
785 static void mempool_free_vp(void *element, void *pool_data)
786 {
787         size_t size = (size_t) pool_data;
788
789         vpfree(element, size);
790 }
791
792 static void *mempool_alloc_vp(gfp_t gfp_mask, void *pool_data)
793 {
794         size_t size = (size_t) pool_data;
795
796         return vpmalloc(size, gfp_mask);
797 }
798
799 int mempool_init_kvpmalloc_pool(mempool_t *pool, int min_nr, size_t size)
800 {
801         return size < PAGE_SIZE
802                 ? mempool_init_kmalloc_pool(pool, min_nr, size)
803                 : mempool_init(pool, min_nr, mempool_alloc_vp,
804                                mempool_free_vp, (void *) size);
805 }
806
807 #if 0
808 void eytzinger1_test(void)
809 {
810         unsigned inorder, eytz, size;
811
812         pr_info("1 based eytzinger test:");
813
814         for (size = 2;
815              size < 65536;
816              size++) {
817                 unsigned extra = eytzinger1_extra(size);
818
819                 if (!(size % 4096))
820                         pr_info("tree size %u", size);
821
822                 BUG_ON(eytzinger1_prev(0, size) != eytzinger1_last(size));
823                 BUG_ON(eytzinger1_next(0, size) != eytzinger1_first(size));
824
825                 BUG_ON(eytzinger1_prev(eytzinger1_first(size), size)    != 0);
826                 BUG_ON(eytzinger1_next(eytzinger1_last(size), size)     != 0);
827
828                 inorder = 1;
829                 eytzinger1_for_each(eytz, size) {
830                         BUG_ON(__inorder_to_eytzinger1(inorder, size, extra) != eytz);
831                         BUG_ON(__eytzinger1_to_inorder(eytz, size, extra) != inorder);
832                         BUG_ON(eytz != eytzinger1_last(size) &&
833                                eytzinger1_prev(eytzinger1_next(eytz, size), size) != eytz);
834
835                         inorder++;
836                 }
837         }
838 }
839
840 void eytzinger0_test(void)
841 {
842
843         unsigned inorder, eytz, size;
844
845         pr_info("0 based eytzinger test:");
846
847         for (size = 1;
848              size < 65536;
849              size++) {
850                 unsigned extra = eytzinger0_extra(size);
851
852                 if (!(size % 4096))
853                         pr_info("tree size %u", size);
854
855                 BUG_ON(eytzinger0_prev(-1, size) != eytzinger0_last(size));
856                 BUG_ON(eytzinger0_next(-1, size) != eytzinger0_first(size));
857
858                 BUG_ON(eytzinger0_prev(eytzinger0_first(size), size)    != -1);
859                 BUG_ON(eytzinger0_next(eytzinger0_last(size), size)     != -1);
860
861                 inorder = 0;
862                 eytzinger0_for_each(eytz, size) {
863                         BUG_ON(__inorder_to_eytzinger0(inorder, size, extra) != eytz);
864                         BUG_ON(__eytzinger0_to_inorder(eytz, size, extra) != inorder);
865                         BUG_ON(eytz != eytzinger0_last(size) &&
866                                eytzinger0_prev(eytzinger0_next(eytz, size), size) != eytz);
867
868                         inorder++;
869                 }
870         }
871 }
872
873 static inline int cmp_u16(const void *_l, const void *_r, size_t size)
874 {
875         const u16 *l = _l, *r = _r;
876
877         return (*l > *r) - (*r - *l);
878 }
879
880 static void eytzinger0_find_test_val(u16 *test_array, unsigned nr, u16 search)
881 {
882         int i, c1 = -1, c2 = -1;
883         ssize_t r;
884
885         r = eytzinger0_find_le(test_array, nr,
886                                sizeof(test_array[0]),
887                                cmp_u16, &search);
888         if (r >= 0)
889                 c1 = test_array[r];
890
891         for (i = 0; i < nr; i++)
892                 if (test_array[i] <= search && test_array[i] > c2)
893                         c2 = test_array[i];
894
895         if (c1 != c2) {
896                 eytzinger0_for_each(i, nr)
897                         pr_info("[%3u] = %12u", i, test_array[i]);
898                 pr_info("find_le(%2u) -> [%2zi] = %2i should be %2i",
899                         i, r, c1, c2);
900         }
901 }
902
903 void eytzinger0_find_test(void)
904 {
905         unsigned i, nr, allocated = 1 << 12;
906         u16 *test_array = kmalloc_array(allocated, sizeof(test_array[0]), GFP_KERNEL);
907
908         for (nr = 1; nr < allocated; nr++) {
909                 pr_info("testing %u elems", nr);
910
911                 get_random_bytes(test_array, nr * sizeof(test_array[0]));
912                 eytzinger0_sort(test_array, nr, sizeof(test_array[0]), cmp_u16, NULL);
913
914                 /* verify array is sorted correctly: */
915                 eytzinger0_for_each(i, nr)
916                         BUG_ON(i != eytzinger0_last(nr) &&
917                                test_array[i] > test_array[eytzinger0_next(i, nr)]);
918
919                 for (i = 0; i < U16_MAX; i += 1 << 12)
920                         eytzinger0_find_test_val(test_array, nr, i);
921
922                 for (i = 0; i < nr; i++) {
923                         eytzinger0_find_test_val(test_array, nr, test_array[i] - 1);
924                         eytzinger0_find_test_val(test_array, nr, test_array[i]);
925                         eytzinger0_find_test_val(test_array, nr, test_array[i] + 1);
926                 }
927         }
928
929         kfree(test_array);
930 }
931 #endif
932
933 /*
934  * Accumulate percpu counters onto one cpu's copy - only valid when access
935  * against any percpu counter is guarded against
936  */
937 u64 *bch2_acc_percpu_u64s(u64 __percpu *p, unsigned nr)
938 {
939         u64 *ret;
940         int cpu;
941
942         /* access to pcpu vars has to be blocked by other locking */
943         preempt_disable();
944         ret = this_cpu_ptr(p);
945         preempt_enable();
946
947         for_each_possible_cpu(cpu) {
948                 u64 *i = per_cpu_ptr(p, cpu);
949
950                 if (i != ret) {
951                         acc_u64s(ret, i, nr);
952                         memset(i, 0, nr * sizeof(u64));
953                 }
954         }
955
956         return ret;
957 }