]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/util.c
90796863f7cca6f413139fd4f68ca8452c997686
[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/console.h>
12 #include <linux/ctype.h>
13 #include <linux/debugfs.h>
14 #include <linux/freezer.h>
15 #include <linux/kthread.h>
16 #include <linux/log2.h>
17 #include <linux/math64.h>
18 #include <linux/percpu.h>
19 #include <linux/preempt.h>
20 #include <linux/random.h>
21 #include <linux/seq_file.h>
22 #include <linux/string.h>
23 #include <linux/types.h>
24 #include <linux/sched/clock.h>
25 #include <linux/mean_and_variance.h>
26
27 #include "eytzinger.h"
28 #include "util.h"
29
30 static const char si_units[] = "?kMGTPEZY";
31
32 /* string_get_size units: */
33 static const char *const units_2[] = {
34         "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"
35 };
36 static const char *const units_10[] = {
37         "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"
38 };
39
40 static int parse_u64(const char *cp, u64 *res)
41 {
42         const char *start = cp;
43         u64 v = 0;
44
45         if (!isdigit(*cp))
46                 return -EINVAL;
47
48         do {
49                 if (v > U64_MAX / 10)
50                         return -ERANGE;
51                 v *= 10;
52                 if (v > U64_MAX - (*cp - '0'))
53                         return -ERANGE;
54                 v += *cp - '0';
55                 cp++;
56         } while (isdigit(*cp));
57
58         *res = v;
59         return cp - start;
60 }
61
62 static int bch2_pow(u64 n, u64 p, u64 *res)
63 {
64         *res = 1;
65
66         while (p--) {
67                 if (*res > div_u64(U64_MAX, n))
68                         return -ERANGE;
69                 *res *= n;
70         }
71         return 0;
72 }
73
74 static int parse_unit_suffix(const char *cp, u64 *res)
75 {
76         const char *start = cp;
77         u64 base = 1024;
78         unsigned u;
79         int ret;
80
81         if (*cp == ' ')
82                 cp++;
83
84         for (u = 1; u < strlen(si_units); u++)
85                 if (*cp == si_units[u]) {
86                         cp++;
87                         goto got_unit;
88                 }
89
90         for (u = 0; u < ARRAY_SIZE(units_2); u++)
91                 if (!strncmp(cp, units_2[u], strlen(units_2[u]))) {
92                         cp += strlen(units_2[u]);
93                         goto got_unit;
94                 }
95
96         for (u = 0; u < ARRAY_SIZE(units_10); u++)
97                 if (!strncmp(cp, units_10[u], strlen(units_10[u]))) {
98                         cp += strlen(units_10[u]);
99                         base = 1000;
100                         goto got_unit;
101                 }
102
103         *res = 1;
104         return 0;
105 got_unit:
106         ret = bch2_pow(base, u, res);
107         if (ret)
108                 return ret;
109
110         return cp - start;
111 }
112
113 #define parse_or_ret(cp, _f)                    \
114 do {                                            \
115         int ret = _f;                           \
116         if (ret < 0)                            \
117                 return ret;                     \
118         cp += ret;                              \
119 } while (0)
120
121 static int __bch2_strtou64_h(const char *cp, u64 *res)
122 {
123         const char *start = cp;
124         u64 v = 0, b, f_n = 0, f_d = 1;
125         int ret;
126
127         parse_or_ret(cp, parse_u64(cp, &v));
128
129         if (*cp == '.') {
130                 cp++;
131                 ret = parse_u64(cp, &f_n);
132                 if (ret < 0)
133                         return ret;
134                 cp += ret;
135
136                 ret = bch2_pow(10, ret, &f_d);
137                 if (ret)
138                         return ret;
139         }
140
141         parse_or_ret(cp, parse_unit_suffix(cp, &b));
142
143         if (v > div_u64(U64_MAX, b))
144                 return -ERANGE;
145         v *= b;
146
147         if (f_n > div_u64(U64_MAX, b))
148                 return -ERANGE;
149
150         f_n = div_u64(f_n * b, f_d);
151         if (v + f_n < v)
152                 return -ERANGE;
153         v += f_n;
154
155         *res = v;
156         return cp - start;
157 }
158
159 static int __bch2_strtoh(const char *cp, u64 *res,
160                          u64 t_max, bool t_signed)
161 {
162         bool positive = *cp != '-';
163         u64 v = 0;
164
165         if (*cp == '+' || *cp == '-')
166                 cp++;
167
168         parse_or_ret(cp, __bch2_strtou64_h(cp, &v));
169
170         if (*cp == '\n')
171                 cp++;
172         if (*cp)
173                 return -EINVAL;
174
175         if (positive) {
176                 if (v > t_max)
177                         return -ERANGE;
178         } else {
179                 if (v && !t_signed)
180                         return -ERANGE;
181
182                 if (v > t_max + 1)
183                         return -ERANGE;
184                 v = -v;
185         }
186
187         *res = v;
188         return 0;
189 }
190
191 #define STRTO_H(name, type)                                     \
192 int bch2_ ## name ## _h(const char *cp, type *res)              \
193 {                                                               \
194         u64 v = 0;                                              \
195         int ret = __bch2_strtoh(cp, &v, ANYSINT_MAX(type),      \
196                         ANYSINT_MAX(type) != ((type) ~0ULL));   \
197         *res = v;                                               \
198         return ret;                                             \
199 }
200
201 STRTO_H(strtoint, int)
202 STRTO_H(strtouint, unsigned int)
203 STRTO_H(strtoll, long long)
204 STRTO_H(strtoull, unsigned long long)
205 STRTO_H(strtou64, u64)
206
207 u64 bch2_read_flag_list(char *opt, const char * const list[])
208 {
209         u64 ret = 0;
210         char *p, *s, *d = kstrdup(opt, GFP_KERNEL);
211
212         if (!d)
213                 return -ENOMEM;
214
215         s = strim(d);
216
217         while ((p = strsep(&s, ","))) {
218                 int flag = match_string(list, -1, p);
219                 if (flag < 0) {
220                         ret = -1;
221                         break;
222                 }
223
224                 ret |= 1 << flag;
225         }
226
227         kfree(d);
228
229         return ret;
230 }
231
232 bool bch2_is_zero(const void *_p, size_t n)
233 {
234         const char *p = _p;
235         size_t i;
236
237         for (i = 0; i < n; i++)
238                 if (p[i])
239                         return false;
240         return true;
241 }
242
243 void bch2_prt_u64_binary(struct printbuf *out, u64 v, unsigned nr_bits)
244 {
245         while (nr_bits)
246                 prt_char(out, '0' + ((v >> --nr_bits) & 1));
247 }
248
249 void bch2_print_string_as_lines(const char *prefix, const char *lines)
250 {
251         const char *p;
252
253         if (!lines) {
254                 printk("%s (null)\n", prefix);
255                 return;
256         }
257
258         console_lock();
259         while (1) {
260                 p = strchrnul(lines, '\n');
261                 printk("%s%.*s\n", prefix, (int) (p - lines), lines);
262                 if (!*p)
263                         break;
264                 lines = p + 1;
265         }
266         console_unlock();
267 }
268
269 int bch2_save_backtrace(bch_stacktrace *stack, struct task_struct *task)
270 {
271         unsigned nr_entries = 0;
272         int ret = 0;
273
274         stack->nr = 0;
275         ret = darray_make_room(stack, 32);
276         if (ret)
277                 return ret;
278
279         if (!down_read_trylock(&task->signal->exec_update_lock))
280                 return -1;
281
282         do {
283                 nr_entries = stack_trace_save_tsk(task, stack->data, stack->size, 0);
284         } while (nr_entries == stack->size &&
285                  !(ret = darray_make_room(stack, stack->size * 2)));
286
287         stack->nr = nr_entries;
288         up_read(&task->signal->exec_update_lock);
289
290         return ret;
291 }
292
293 void bch2_prt_backtrace(struct printbuf *out, bch_stacktrace *stack)
294 {
295         unsigned long *i;
296
297         darray_for_each(*stack, i) {
298                 prt_printf(out, "[<0>] %pB", (void *) *i);
299                 prt_newline(out);
300         }
301 }
302
303 int bch2_prt_task_backtrace(struct printbuf *out, struct task_struct *task)
304 {
305         bch_stacktrace stack = { 0 };
306         int ret = bch2_save_backtrace(&stack, task);
307
308         bch2_prt_backtrace(out, &stack);
309         darray_exit(&stack);
310         return ret;
311 }
312
313 /* time stats: */
314
315 #ifndef CONFIG_BCACHEFS_NO_LATENCY_ACCT
316 static void bch2_quantiles_update(struct bch2_quantiles *q, u64 v)
317 {
318         unsigned i = 0;
319
320         while (i < ARRAY_SIZE(q->entries)) {
321                 struct bch2_quantile_entry *e = q->entries + i;
322
323                 if (unlikely(!e->step)) {
324                         e->m = v;
325                         e->step = max_t(unsigned, v / 2, 1024);
326                 } else if (e->m > v) {
327                         e->m = e->m >= e->step
328                                 ? e->m - e->step
329                                 : 0;
330                 } else if (e->m < v) {
331                         e->m = e->m + e->step > e->m
332                                 ? e->m + e->step
333                                 : U32_MAX;
334                 }
335
336                 if ((e->m > v ? e->m - v : v - e->m) < e->step)
337                         e->step = max_t(unsigned, e->step / 2, 1);
338
339                 if (v >= e->m)
340                         break;
341
342                 i = eytzinger0_child(i, v > e->m);
343         }
344 }
345
346 static inline void bch2_time_stats_update_one(struct bch2_time_stats *stats,
347                                               u64 start, u64 end)
348 {
349         u64 duration, freq;
350
351         if (time_after64(end, start)) {
352                 duration = end - start;
353                 stats->duration_stats = mean_and_variance_update(stats->duration_stats, duration);
354                 mean_and_variance_weighted_update(&stats->duration_stats_weighted, duration);
355                 stats->max_duration = max(stats->max_duration, duration);
356                 stats->min_duration = min(stats->min_duration, duration);
357                 bch2_quantiles_update(&stats->quantiles, duration);
358         }
359
360         if (time_after64(end, stats->last_event)) {
361                 freq = end - stats->last_event;
362                 stats->freq_stats = mean_and_variance_update(stats->freq_stats, freq);
363                 mean_and_variance_weighted_update(&stats->freq_stats_weighted, freq);
364                 stats->max_freq = max(stats->max_freq, freq);
365                 stats->min_freq = min(stats->min_freq, freq);
366                 stats->last_event = end;
367         }
368 }
369
370 static noinline void bch2_time_stats_clear_buffer(struct bch2_time_stats *stats,
371                                                   struct bch2_time_stat_buffer *b)
372 {
373         struct bch2_time_stat_buffer_entry *i;
374         unsigned long flags;
375
376         spin_lock_irqsave(&stats->lock, flags);
377         for (i = b->entries;
378              i < b->entries + ARRAY_SIZE(b->entries);
379              i++)
380                 bch2_time_stats_update_one(stats, i->start, i->end);
381         spin_unlock_irqrestore(&stats->lock, flags);
382
383         b->nr = 0;
384 }
385
386 void __bch2_time_stats_update(struct bch2_time_stats *stats, u64 start, u64 end)
387 {
388         unsigned long flags;
389
390         WARN_RATELIMIT(!stats->min_duration || !stats->min_freq,
391                        "time_stats: min_duration = %llu, min_freq = %llu",
392                        stats->min_duration, stats->min_freq);
393
394         if (!stats->buffer) {
395                 spin_lock_irqsave(&stats->lock, flags);
396                 bch2_time_stats_update_one(stats, start, end);
397
398                 if (mean_and_variance_weighted_get_mean(stats->freq_stats_weighted) < 32 &&
399                     stats->duration_stats.n > 1024)
400                         stats->buffer =
401                                 alloc_percpu_gfp(struct bch2_time_stat_buffer,
402                                                  GFP_ATOMIC);
403                 spin_unlock_irqrestore(&stats->lock, flags);
404         } else {
405                 struct bch2_time_stat_buffer *b;
406
407                 preempt_disable();
408                 b = this_cpu_ptr(stats->buffer);
409
410                 BUG_ON(b->nr >= ARRAY_SIZE(b->entries));
411                 b->entries[b->nr++] = (struct bch2_time_stat_buffer_entry) {
412                         .start = start,
413                         .end = end
414                 };
415
416                 if (unlikely(b->nr == ARRAY_SIZE(b->entries)))
417                         bch2_time_stats_clear_buffer(stats, b);
418                 preempt_enable();
419         }
420 }
421 #endif
422
423 static const struct time_unit {
424         const char      *name;
425         u64             nsecs;
426 } time_units[] = {
427         { "ns",         1                },
428         { "us",         NSEC_PER_USEC    },
429         { "ms",         NSEC_PER_MSEC    },
430         { "s",          NSEC_PER_SEC     },
431         { "m",          (u64) NSEC_PER_SEC * 60},
432         { "h",          (u64) NSEC_PER_SEC * 3600},
433         { "eon",        U64_MAX          },
434 };
435
436 static const struct time_unit *pick_time_units(u64 ns)
437 {
438         const struct time_unit *u;
439
440         for (u = time_units;
441              u + 1 < time_units + ARRAY_SIZE(time_units) &&
442              ns >= u[1].nsecs << 1;
443              u++)
444                 ;
445
446         return u;
447 }
448
449 void bch2_pr_time_units(struct printbuf *out, u64 ns)
450 {
451         const struct time_unit *u = pick_time_units(ns);
452
453         prt_printf(out, "%llu %s", div_u64(ns, u->nsecs), u->name);
454 }
455
456 static void bch2_pr_time_units_aligned(struct printbuf *out, u64 ns)
457 {
458         const struct time_unit *u = pick_time_units(ns);
459
460         prt_printf(out, "%llu ", div64_u64(ns, u->nsecs));
461         prt_tab_rjust(out);
462         prt_printf(out, "%s", u->name);
463 }
464
465 #define TABSTOP_SIZE 12
466
467 static inline void pr_name_and_units(struct printbuf *out, const char *name, u64 ns)
468 {
469         prt_str(out, name);
470         prt_tab(out);
471         bch2_pr_time_units_aligned(out, ns);
472         prt_newline(out);
473 }
474
475 void bch2_time_stats_to_text(struct printbuf *out, struct bch2_time_stats *stats)
476 {
477         const struct time_unit *u;
478         s64 f_mean = 0, d_mean = 0;
479         u64 q, last_q = 0, f_stddev = 0, d_stddev = 0;
480         int i;
481         /*
482          * avoid divide by zero
483          */
484         if (stats->freq_stats.n) {
485                 f_mean = mean_and_variance_get_mean(stats->freq_stats);
486                 f_stddev = mean_and_variance_get_stddev(stats->freq_stats);
487                 d_mean = mean_and_variance_get_mean(stats->duration_stats);
488                 d_stddev = mean_and_variance_get_stddev(stats->duration_stats);
489         }
490
491         printbuf_tabstop_push(out, out->indent + TABSTOP_SIZE);
492         prt_printf(out, "count:");
493         prt_tab(out);
494         prt_printf(out, "%llu ",
495                          stats->duration_stats.n);
496         printbuf_tabstop_pop(out);
497         prt_newline(out);
498
499         printbuf_tabstops_reset(out);
500
501         printbuf_tabstop_push(out, out->indent + 20);
502         printbuf_tabstop_push(out, TABSTOP_SIZE + 2);
503         printbuf_tabstop_push(out, 0);
504         printbuf_tabstop_push(out, TABSTOP_SIZE + 2);
505
506         prt_tab(out);
507         prt_printf(out, "since mount");
508         prt_tab_rjust(out);
509         prt_tab(out);
510         prt_printf(out, "recent");
511         prt_tab_rjust(out);
512         prt_newline(out);
513
514         printbuf_tabstops_reset(out);
515         printbuf_tabstop_push(out, out->indent + 20);
516         printbuf_tabstop_push(out, TABSTOP_SIZE);
517         printbuf_tabstop_push(out, 2);
518         printbuf_tabstop_push(out, TABSTOP_SIZE);
519
520         prt_printf(out, "duration of events");
521         prt_newline(out);
522         printbuf_indent_add(out, 2);
523
524         pr_name_and_units(out, "min:", stats->min_duration);
525         pr_name_and_units(out, "max:", stats->max_duration);
526
527         prt_printf(out, "mean:");
528         prt_tab(out);
529         bch2_pr_time_units_aligned(out, d_mean);
530         prt_tab(out);
531         bch2_pr_time_units_aligned(out, mean_and_variance_weighted_get_mean(stats->duration_stats_weighted));
532         prt_newline(out);
533
534         prt_printf(out, "stddev:");
535         prt_tab(out);
536         bch2_pr_time_units_aligned(out, d_stddev);
537         prt_tab(out);
538         bch2_pr_time_units_aligned(out, mean_and_variance_weighted_get_stddev(stats->duration_stats_weighted));
539
540         printbuf_indent_sub(out, 2);
541         prt_newline(out);
542
543         prt_printf(out, "time between events");
544         prt_newline(out);
545         printbuf_indent_add(out, 2);
546
547         pr_name_and_units(out, "min:", stats->min_freq);
548         pr_name_and_units(out, "max:", stats->max_freq);
549
550         prt_printf(out, "mean:");
551         prt_tab(out);
552         bch2_pr_time_units_aligned(out, f_mean);
553         prt_tab(out);
554         bch2_pr_time_units_aligned(out, mean_and_variance_weighted_get_mean(stats->freq_stats_weighted));
555         prt_newline(out);
556
557         prt_printf(out, "stddev:");
558         prt_tab(out);
559         bch2_pr_time_units_aligned(out, f_stddev);
560         prt_tab(out);
561         bch2_pr_time_units_aligned(out, mean_and_variance_weighted_get_stddev(stats->freq_stats_weighted));
562
563         printbuf_indent_sub(out, 2);
564         prt_newline(out);
565
566         printbuf_tabstops_reset(out);
567
568         i = eytzinger0_first(NR_QUANTILES);
569         u = pick_time_units(stats->quantiles.entries[i].m);
570
571         prt_printf(out, "quantiles (%s):\t", u->name);
572         eytzinger0_for_each(i, NR_QUANTILES) {
573                 bool is_last = eytzinger0_next(i, NR_QUANTILES) == -1;
574
575                 q = max(stats->quantiles.entries[i].m, last_q);
576                 prt_printf(out, "%llu ",
577                        div_u64(q, u->nsecs));
578                 if (is_last)
579                         prt_newline(out);
580                 last_q = q;
581         }
582 }
583
584 void bch2_time_stats_exit(struct bch2_time_stats *stats)
585 {
586         free_percpu(stats->buffer);
587 }
588
589 void bch2_time_stats_init(struct bch2_time_stats *stats)
590 {
591         memset(stats, 0, sizeof(*stats));
592         stats->duration_stats_weighted.weight = 8;
593         stats->freq_stats_weighted.weight = 8;
594         stats->min_duration = U64_MAX;
595         stats->min_freq = U64_MAX;
596         spin_lock_init(&stats->lock);
597 }
598
599 /* ratelimit: */
600
601 /**
602  * bch2_ratelimit_delay() - return how long to delay until the next time to do
603  * some work
604  *
605  * @d - the struct bch_ratelimit to update
606  *
607  * Returns the amount of time to delay by, in jiffies
608  */
609 u64 bch2_ratelimit_delay(struct bch_ratelimit *d)
610 {
611         u64 now = local_clock();
612
613         return time_after64(d->next, now)
614                 ? nsecs_to_jiffies(d->next - now)
615                 : 0;
616 }
617
618 /**
619  * bch2_ratelimit_increment() - increment @d by the amount of work done
620  *
621  * @d - the struct bch_ratelimit to update
622  * @done - the amount of work done, in arbitrary units
623  */
624 void bch2_ratelimit_increment(struct bch_ratelimit *d, u64 done)
625 {
626         u64 now = local_clock();
627
628         d->next += div_u64(done * NSEC_PER_SEC, d->rate);
629
630         if (time_before64(now + NSEC_PER_SEC, d->next))
631                 d->next = now + NSEC_PER_SEC;
632
633         if (time_after64(now - NSEC_PER_SEC * 2, d->next))
634                 d->next = now - NSEC_PER_SEC * 2;
635 }
636
637 /* pd controller: */
638
639 /*
640  * Updates pd_controller. Attempts to scale inputed values to units per second.
641  * @target: desired value
642  * @actual: current value
643  *
644  * @sign: 1 or -1; 1 if increasing the rate makes actual go up, -1 if increasing
645  * it makes actual go down.
646  */
647 void bch2_pd_controller_update(struct bch_pd_controller *pd,
648                               s64 target, s64 actual, int sign)
649 {
650         s64 proportional, derivative, change;
651
652         unsigned long seconds_since_update = (jiffies - pd->last_update) / HZ;
653
654         if (seconds_since_update == 0)
655                 return;
656
657         pd->last_update = jiffies;
658
659         proportional = actual - target;
660         proportional *= seconds_since_update;
661         proportional = div_s64(proportional, pd->p_term_inverse);
662
663         derivative = actual - pd->last_actual;
664         derivative = div_s64(derivative, seconds_since_update);
665         derivative = ewma_add(pd->smoothed_derivative, derivative,
666                               (pd->d_term / seconds_since_update) ?: 1);
667         derivative = derivative * pd->d_term;
668         derivative = div_s64(derivative, pd->p_term_inverse);
669
670         change = proportional + derivative;
671
672         /* Don't increase rate if not keeping up */
673         if (change > 0 &&
674             pd->backpressure &&
675             time_after64(local_clock(),
676                          pd->rate.next + NSEC_PER_MSEC))
677                 change = 0;
678
679         change *= (sign * -1);
680
681         pd->rate.rate = clamp_t(s64, (s64) pd->rate.rate + change,
682                                 1, UINT_MAX);
683
684         pd->last_actual         = actual;
685         pd->last_derivative     = derivative;
686         pd->last_proportional   = proportional;
687         pd->last_change         = change;
688         pd->last_target         = target;
689 }
690
691 void bch2_pd_controller_init(struct bch_pd_controller *pd)
692 {
693         pd->rate.rate           = 1024;
694         pd->last_update         = jiffies;
695         pd->p_term_inverse      = 6000;
696         pd->d_term              = 30;
697         pd->d_smooth            = pd->d_term;
698         pd->backpressure        = 1;
699 }
700
701 void bch2_pd_controller_debug_to_text(struct printbuf *out, struct bch_pd_controller *pd)
702 {
703         if (!out->nr_tabstops)
704                 printbuf_tabstop_push(out, 20);
705
706         prt_printf(out, "rate:");
707         prt_tab(out);
708         prt_human_readable_s64(out, pd->rate.rate);
709         prt_newline(out);
710
711         prt_printf(out, "target:");
712         prt_tab(out);
713         prt_human_readable_u64(out, pd->last_target);
714         prt_newline(out);
715
716         prt_printf(out, "actual:");
717         prt_tab(out);
718         prt_human_readable_u64(out, pd->last_actual);
719         prt_newline(out);
720
721         prt_printf(out, "proportional:");
722         prt_tab(out);
723         prt_human_readable_s64(out, pd->last_proportional);
724         prt_newline(out);
725
726         prt_printf(out, "derivative:");
727         prt_tab(out);
728         prt_human_readable_s64(out, pd->last_derivative);
729         prt_newline(out);
730
731         prt_printf(out, "change:");
732         prt_tab(out);
733         prt_human_readable_s64(out, pd->last_change);
734         prt_newline(out);
735
736         prt_printf(out, "next io:");
737         prt_tab(out);
738         prt_printf(out, "%llims", div64_s64(pd->rate.next - local_clock(), NSEC_PER_MSEC));
739         prt_newline(out);
740 }
741
742 /* misc: */
743
744 void bch2_bio_map(struct bio *bio, void *base, size_t size)
745 {
746         while (size) {
747                 struct page *page = is_vmalloc_addr(base)
748                                 ? vmalloc_to_page(base)
749                                 : virt_to_page(base);
750                 unsigned offset = offset_in_page(base);
751                 unsigned len = min_t(size_t, PAGE_SIZE - offset, size);
752
753                 BUG_ON(!bio_add_page(bio, page, len, offset));
754                 size -= len;
755                 base += len;
756         }
757 }
758
759 int bch2_bio_alloc_pages(struct bio *bio, size_t size, gfp_t gfp_mask)
760 {
761         while (size) {
762                 struct page *page = alloc_pages(gfp_mask, 0);
763                 unsigned len = min_t(size_t, PAGE_SIZE, size);
764
765                 if (!page)
766                         return -ENOMEM;
767
768                 if (unlikely(!bio_add_page(bio, page, len, 0))) {
769                         __free_page(page);
770                         break;
771                 }
772
773                 size -= len;
774         }
775
776         return 0;
777 }
778
779 size_t bch2_rand_range(size_t max)
780 {
781         size_t rand;
782
783         if (!max)
784                 return 0;
785
786         do {
787                 rand = get_random_long();
788                 rand &= roundup_pow_of_two(max) - 1;
789         } while (rand >= max);
790
791         return rand;
792 }
793
794 void memcpy_to_bio(struct bio *dst, struct bvec_iter dst_iter, const void *src)
795 {
796         struct bio_vec bv;
797         struct bvec_iter iter;
798
799         __bio_for_each_segment(bv, dst, iter, dst_iter) {
800                 void *dstp = kmap_atomic(bv.bv_page);
801                 memcpy(dstp + bv.bv_offset, src, bv.bv_len);
802                 kunmap_atomic(dstp);
803
804                 src += bv.bv_len;
805         }
806 }
807
808 void memcpy_from_bio(void *dst, struct bio *src, struct bvec_iter src_iter)
809 {
810         struct bio_vec bv;
811         struct bvec_iter iter;
812
813         __bio_for_each_segment(bv, src, iter, src_iter) {
814                 void *srcp = kmap_atomic(bv.bv_page);
815                 memcpy(dst, srcp + bv.bv_offset, bv.bv_len);
816                 kunmap_atomic(srcp);
817
818                 dst += bv.bv_len;
819         }
820 }
821
822 static int alignment_ok(const void *base, size_t align)
823 {
824         return IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) ||
825                 ((unsigned long)base & (align - 1)) == 0;
826 }
827
828 static void u32_swap(void *a, void *b, size_t size)
829 {
830         u32 t = *(u32 *)a;
831         *(u32 *)a = *(u32 *)b;
832         *(u32 *)b = t;
833 }
834
835 static void u64_swap(void *a, void *b, size_t size)
836 {
837         u64 t = *(u64 *)a;
838         *(u64 *)a = *(u64 *)b;
839         *(u64 *)b = t;
840 }
841
842 static void generic_swap(void *a, void *b, size_t size)
843 {
844         char t;
845
846         do {
847                 t = *(char *)a;
848                 *(char *)a++ = *(char *)b;
849                 *(char *)b++ = t;
850         } while (--size > 0);
851 }
852
853 static inline int do_cmp(void *base, size_t n, size_t size,
854                          int (*cmp_func)(const void *, const void *, size_t),
855                          size_t l, size_t r)
856 {
857         return cmp_func(base + inorder_to_eytzinger0(l, n) * size,
858                         base + inorder_to_eytzinger0(r, n) * size,
859                         size);
860 }
861
862 static inline void do_swap(void *base, size_t n, size_t size,
863                            void (*swap_func)(void *, void *, size_t),
864                            size_t l, size_t r)
865 {
866         swap_func(base + inorder_to_eytzinger0(l, n) * size,
867                   base + inorder_to_eytzinger0(r, n) * size,
868                   size);
869 }
870
871 void eytzinger0_sort(void *base, size_t n, size_t size,
872                      int (*cmp_func)(const void *, const void *, size_t),
873                      void (*swap_func)(void *, void *, size_t))
874 {
875         int i, c, r;
876
877         if (!swap_func) {
878                 if (size == 4 && alignment_ok(base, 4))
879                         swap_func = u32_swap;
880                 else if (size == 8 && alignment_ok(base, 8))
881                         swap_func = u64_swap;
882                 else
883                         swap_func = generic_swap;
884         }
885
886         /* heapify */
887         for (i = n / 2 - 1; i >= 0; --i) {
888                 for (r = i; r * 2 + 1 < n; r = c) {
889                         c = r * 2 + 1;
890
891                         if (c + 1 < n &&
892                             do_cmp(base, n, size, cmp_func, c, c + 1) < 0)
893                                 c++;
894
895                         if (do_cmp(base, n, size, cmp_func, r, c) >= 0)
896                                 break;
897
898                         do_swap(base, n, size, swap_func, r, c);
899                 }
900         }
901
902         /* sort */
903         for (i = n - 1; i > 0; --i) {
904                 do_swap(base, n, size, swap_func, 0, i);
905
906                 for (r = 0; r * 2 + 1 < i; r = c) {
907                         c = r * 2 + 1;
908
909                         if (c + 1 < i &&
910                             do_cmp(base, n, size, cmp_func, c, c + 1) < 0)
911                                 c++;
912
913                         if (do_cmp(base, n, size, cmp_func, r, c) >= 0)
914                                 break;
915
916                         do_swap(base, n, size, swap_func, r, c);
917                 }
918         }
919 }
920
921 void sort_cmp_size(void *base, size_t num, size_t size,
922           int (*cmp_func)(const void *, const void *, size_t),
923           void (*swap_func)(void *, void *, size_t size))
924 {
925         /* pre-scale counters for performance */
926         int i = (num/2 - 1) * size, n = num * size, c, r;
927
928         if (!swap_func) {
929                 if (size == 4 && alignment_ok(base, 4))
930                         swap_func = u32_swap;
931                 else if (size == 8 && alignment_ok(base, 8))
932                         swap_func = u64_swap;
933                 else
934                         swap_func = generic_swap;
935         }
936
937         /* heapify */
938         for ( ; i >= 0; i -= size) {
939                 for (r = i; r * 2 + size < n; r  = c) {
940                         c = r * 2 + size;
941                         if (c < n - size &&
942                             cmp_func(base + c, base + c + size, size) < 0)
943                                 c += size;
944                         if (cmp_func(base + r, base + c, size) >= 0)
945                                 break;
946                         swap_func(base + r, base + c, size);
947                 }
948         }
949
950         /* sort */
951         for (i = n - size; i > 0; i -= size) {
952                 swap_func(base, base + i, size);
953                 for (r = 0; r * 2 + size < i; r = c) {
954                         c = r * 2 + size;
955                         if (c < i - size &&
956                             cmp_func(base + c, base + c + size, size) < 0)
957                                 c += size;
958                         if (cmp_func(base + r, base + c, size) >= 0)
959                                 break;
960                         swap_func(base + r, base + c, size);
961                 }
962         }
963 }
964
965 static void mempool_free_vp(void *element, void *pool_data)
966 {
967         size_t size = (size_t) pool_data;
968
969         vpfree(element, size);
970 }
971
972 static void *mempool_alloc_vp(gfp_t gfp_mask, void *pool_data)
973 {
974         size_t size = (size_t) pool_data;
975
976         return vpmalloc(size, gfp_mask);
977 }
978
979 int mempool_init_kvpmalloc_pool(mempool_t *pool, int min_nr, size_t size)
980 {
981         return size < PAGE_SIZE
982                 ? mempool_init_kmalloc_pool(pool, min_nr, size)
983                 : mempool_init(pool, min_nr, mempool_alloc_vp,
984                                mempool_free_vp, (void *) size);
985 }
986
987 #if 0
988 void eytzinger1_test(void)
989 {
990         unsigned inorder, eytz, size;
991
992         pr_info("1 based eytzinger test:");
993
994         for (size = 2;
995              size < 65536;
996              size++) {
997                 unsigned extra = eytzinger1_extra(size);
998
999                 if (!(size % 4096))
1000                         pr_info("tree size %u", size);
1001
1002                 BUG_ON(eytzinger1_prev(0, size) != eytzinger1_last(size));
1003                 BUG_ON(eytzinger1_next(0, size) != eytzinger1_first(size));
1004
1005                 BUG_ON(eytzinger1_prev(eytzinger1_first(size), size)    != 0);
1006                 BUG_ON(eytzinger1_next(eytzinger1_last(size), size)     != 0);
1007
1008                 inorder = 1;
1009                 eytzinger1_for_each(eytz, size) {
1010                         BUG_ON(__inorder_to_eytzinger1(inorder, size, extra) != eytz);
1011                         BUG_ON(__eytzinger1_to_inorder(eytz, size, extra) != inorder);
1012                         BUG_ON(eytz != eytzinger1_last(size) &&
1013                                eytzinger1_prev(eytzinger1_next(eytz, size), size) != eytz);
1014
1015                         inorder++;
1016                 }
1017         }
1018 }
1019
1020 void eytzinger0_test(void)
1021 {
1022
1023         unsigned inorder, eytz, size;
1024
1025         pr_info("0 based eytzinger test:");
1026
1027         for (size = 1;
1028              size < 65536;
1029              size++) {
1030                 unsigned extra = eytzinger0_extra(size);
1031
1032                 if (!(size % 4096))
1033                         pr_info("tree size %u", size);
1034
1035                 BUG_ON(eytzinger0_prev(-1, size) != eytzinger0_last(size));
1036                 BUG_ON(eytzinger0_next(-1, size) != eytzinger0_first(size));
1037
1038                 BUG_ON(eytzinger0_prev(eytzinger0_first(size), size)    != -1);
1039                 BUG_ON(eytzinger0_next(eytzinger0_last(size), size)     != -1);
1040
1041                 inorder = 0;
1042                 eytzinger0_for_each(eytz, size) {
1043                         BUG_ON(__inorder_to_eytzinger0(inorder, size, extra) != eytz);
1044                         BUG_ON(__eytzinger0_to_inorder(eytz, size, extra) != inorder);
1045                         BUG_ON(eytz != eytzinger0_last(size) &&
1046                                eytzinger0_prev(eytzinger0_next(eytz, size), size) != eytz);
1047
1048                         inorder++;
1049                 }
1050         }
1051 }
1052
1053 static inline int cmp_u16(const void *_l, const void *_r, size_t size)
1054 {
1055         const u16 *l = _l, *r = _r;
1056
1057         return (*l > *r) - (*r - *l);
1058 }
1059
1060 static void eytzinger0_find_test_val(u16 *test_array, unsigned nr, u16 search)
1061 {
1062         int i, c1 = -1, c2 = -1;
1063         ssize_t r;
1064
1065         r = eytzinger0_find_le(test_array, nr,
1066                                sizeof(test_array[0]),
1067                                cmp_u16, &search);
1068         if (r >= 0)
1069                 c1 = test_array[r];
1070
1071         for (i = 0; i < nr; i++)
1072                 if (test_array[i] <= search && test_array[i] > c2)
1073                         c2 = test_array[i];
1074
1075         if (c1 != c2) {
1076                 eytzinger0_for_each(i, nr)
1077                         pr_info("[%3u] = %12u", i, test_array[i]);
1078                 pr_info("find_le(%2u) -> [%2zi] = %2i should be %2i",
1079                         i, r, c1, c2);
1080         }
1081 }
1082
1083 void eytzinger0_find_test(void)
1084 {
1085         unsigned i, nr, allocated = 1 << 12;
1086         u16 *test_array = kmalloc_array(allocated, sizeof(test_array[0]), GFP_KERNEL);
1087
1088         for (nr = 1; nr < allocated; nr++) {
1089                 pr_info("testing %u elems", nr);
1090
1091                 get_random_bytes(test_array, nr * sizeof(test_array[0]));
1092                 eytzinger0_sort(test_array, nr, sizeof(test_array[0]), cmp_u16, NULL);
1093
1094                 /* verify array is sorted correctly: */
1095                 eytzinger0_for_each(i, nr)
1096                         BUG_ON(i != eytzinger0_last(nr) &&
1097                                test_array[i] > test_array[eytzinger0_next(i, nr)]);
1098
1099                 for (i = 0; i < U16_MAX; i += 1 << 12)
1100                         eytzinger0_find_test_val(test_array, nr, i);
1101
1102                 for (i = 0; i < nr; i++) {
1103                         eytzinger0_find_test_val(test_array, nr, test_array[i] - 1);
1104                         eytzinger0_find_test_val(test_array, nr, test_array[i]);
1105                         eytzinger0_find_test_val(test_array, nr, test_array[i] + 1);
1106                 }
1107         }
1108
1109         kfree(test_array);
1110 }
1111 #endif
1112
1113 /*
1114  * Accumulate percpu counters onto one cpu's copy - only valid when access
1115  * against any percpu counter is guarded against
1116  */
1117 u64 *bch2_acc_percpu_u64s(u64 __percpu *p, unsigned nr)
1118 {
1119         u64 *ret;
1120         int cpu;
1121
1122         /* access to pcpu vars has to be blocked by other locking */
1123         preempt_disable();
1124         ret = this_cpu_ptr(p);
1125         preempt_enable();
1126
1127         for_each_possible_cpu(cpu) {
1128                 u64 *i = per_cpu_ptr(p, cpu);
1129
1130                 if (i != ret) {
1131                         acc_u64s(ret, i, nr);
1132                         memset(i, 0, nr * sizeof(u64));
1133                 }
1134         }
1135
1136         return ret;
1137 }