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