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