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