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