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