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