]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/util.c
Update bcachefs sources to 5963d1b1a4 bcacehfs: Fix bch2_get_alloc_in_memory_pos()
[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 static void bch2_quantiles_update(struct quantiles *q, u64 v)
244 {
245         unsigned i = 0;
246
247         while (i < ARRAY_SIZE(q->entries)) {
248                 struct quantile_entry *e = q->entries + i;
249
250                 if (unlikely(!e->step)) {
251                         e->m = v;
252                         e->step = max_t(unsigned, v / 2, 1024);
253                 } else if (e->m > v) {
254                         e->m = e->m >= e->step
255                                 ? e->m - e->step
256                                 : 0;
257                 } else if (e->m < v) {
258                         e->m = e->m + e->step > e->m
259                                 ? e->m + e->step
260                                 : U32_MAX;
261                 }
262
263                 if ((e->m > v ? e->m - v : v - e->m) < e->step)
264                         e->step = max_t(unsigned, e->step / 2, 1);
265
266                 if (v >= e->m)
267                         break;
268
269                 i = eytzinger0_child(i, v > e->m);
270         }
271 }
272
273 void bch2_prt_u64_binary(struct printbuf *out, u64 v, unsigned nr_bits)
274 {
275         while (nr_bits)
276                 prt_char(out, '0' + ((v >> --nr_bits) & 1));
277 }
278
279 void bch2_print_string_as_lines(const char *prefix, const char *lines)
280 {
281         const char *p;
282
283         if (!lines) {
284                 printk("%s (null)\n", prefix);
285                 return;
286         }
287
288         console_lock();
289         while (1) {
290                 p = strchrnul(lines, '\n');
291                 printk("%s%.*s\n", prefix, (int) (p - lines), lines);
292                 if (!*p)
293                         break;
294                 lines = p + 1;
295                 prefix = KERN_CONT;
296         }
297         console_unlock();
298 }
299
300 int bch2_prt_backtrace(struct printbuf *out, struct task_struct *task)
301 {
302         unsigned long entries[32];
303         unsigned i, nr_entries;
304         int ret;
305
306         ret = down_read_killable(&task->signal->exec_update_lock);
307         if (ret)
308                 return ret;
309
310         nr_entries = stack_trace_save_tsk(task, entries, ARRAY_SIZE(entries), 0);
311         for (i = 0; i < nr_entries; i++) {
312                 prt_printf(out, "[<0>] %pB", (void *)entries[i]);
313                 prt_newline(out);
314         }
315
316         up_read(&task->signal->exec_update_lock);
317         return 0;
318 }
319
320 /* time stats: */
321
322 static inline void bch2_time_stats_update_one(struct time_stats *stats,
323                                               u64 start, u64 end)
324 {
325         u64 duration, freq;
326
327         if (time_after64(end, start)) {
328                 duration = end - start;
329                 stats->duration_stats = mean_and_variance_update_inlined(stats->duration_stats,
330                                                                  duration);
331                 stats->duration_stats_weighted = mean_and_variance_weighted_update(
332                         stats->duration_stats_weighted,
333                         duration);
334                 stats->max_duration = max(stats->max_duration, duration);
335                 stats->min_duration = min(stats->min_duration, duration);
336                 bch2_quantiles_update(&stats->quantiles, duration);
337         }
338
339         if (time_after64(end, stats->last_event)) {
340                 freq = end - stats->last_event;
341                 stats->freq_stats = mean_and_variance_update_inlined(stats->freq_stats, freq);
342                 stats->freq_stats_weighted = mean_and_variance_weighted_update(
343                         stats->freq_stats_weighted,
344                         freq);
345                 stats->max_freq = max(stats->max_freq, freq);
346                 stats->min_freq = min(stats->min_freq, freq);
347                 stats->last_event = end;
348         }
349 }
350
351 static noinline void bch2_time_stats_clear_buffer(struct time_stats *stats,
352                                                   struct time_stat_buffer *b)
353 {
354         struct time_stat_buffer_entry *i;
355         unsigned long flags;
356
357         spin_lock_irqsave(&stats->lock, flags);
358         for (i = b->entries;
359              i < b->entries + ARRAY_SIZE(b->entries);
360              i++)
361                 bch2_time_stats_update_one(stats, i->start, i->end);
362         spin_unlock_irqrestore(&stats->lock, flags);
363
364         b->nr = 0;
365 }
366
367 void __bch2_time_stats_update(struct time_stats *stats, u64 start, u64 end)
368 {
369         unsigned long flags;
370
371         WARN_RATELIMIT(!stats->min_duration || !stats->min_freq,
372                        "time_stats: min_duration = %llu, min_freq = %llu",
373                        stats->min_duration, stats->min_freq);
374
375         if (!stats->buffer) {
376                 spin_lock_irqsave(&stats->lock, flags);
377                 bch2_time_stats_update_one(stats, start, end);
378
379                 if (mean_and_variance_weighted_get_mean(stats->freq_stats_weighted) < 32 &&
380                     stats->duration_stats.n > 1024)
381                         stats->buffer =
382                                 alloc_percpu_gfp(struct time_stat_buffer,
383                                                  GFP_ATOMIC);
384                 spin_unlock_irqrestore(&stats->lock, flags);
385         } else {
386                 struct time_stat_buffer *b;
387
388                 preempt_disable();
389                 b = this_cpu_ptr(stats->buffer);
390
391                 BUG_ON(b->nr >= ARRAY_SIZE(b->entries));
392                 b->entries[b->nr++] = (struct time_stat_buffer_entry) {
393                         .start = start,
394                         .end = end
395                 };
396
397                 if (unlikely(b->nr == ARRAY_SIZE(b->entries)))
398                         bch2_time_stats_clear_buffer(stats, b);
399                 preempt_enable();
400         }
401 }
402
403 static const struct time_unit {
404         const char      *name;
405         u64             nsecs;
406 } time_units[] = {
407         { "ns",         1                },
408         { "us",         NSEC_PER_USEC    },
409         { "ms",         NSEC_PER_MSEC    },
410         { "s",          NSEC_PER_SEC     },
411         { "m",          NSEC_PER_SEC * 60},
412         { "h",          NSEC_PER_SEC * 3600},
413         { "eon",        U64_MAX          },
414 };
415
416 static const struct time_unit *pick_time_units(u64 ns)
417 {
418         const struct time_unit *u;
419
420         for (u = time_units;
421              u + 1 < time_units + ARRAY_SIZE(time_units) &&
422              ns >= u[1].nsecs << 1;
423              u++)
424                 ;
425
426         return u;
427 }
428
429 static void pr_time_units(struct printbuf *out, u64 ns)
430 {
431         const struct time_unit *u = pick_time_units(ns);
432
433         prt_printf(out, "%llu ", div64_u64(ns, u->nsecs));
434         prt_tab_rjust(out);
435         prt_printf(out, "%s", u->name);
436 }
437
438 #define TABSTOP_SIZE 12
439
440 static inline void pr_name_and_units(struct printbuf *out, const char *name, u64 ns)
441 {
442         prt_str(out, name);
443         prt_tab(out);
444         pr_time_units(out, ns);
445         prt_newline(out);
446 }
447
448 void bch2_time_stats_to_text(struct printbuf *out, struct time_stats *stats)
449 {
450         const struct time_unit *u;
451         s64 f_mean = 0, d_mean = 0;
452         u64 q, last_q = 0, f_stddev = 0, d_stddev = 0;
453         int i;
454         /*
455          * avoid divide by zero
456          */
457         if (stats->freq_stats.n) {
458                 f_mean = mean_and_variance_get_mean(stats->freq_stats);
459                 f_stddev = mean_and_variance_get_stddev(stats->freq_stats);
460                 d_mean = mean_and_variance_get_mean(stats->duration_stats);
461                 d_stddev = mean_and_variance_get_stddev(stats->duration_stats);
462         }
463
464         printbuf_tabstop_push(out, out->indent + TABSTOP_SIZE);
465         prt_printf(out, "count:");
466         prt_tab(out);
467         prt_printf(out, "%llu ",
468                          stats->duration_stats.n);
469         printbuf_tabstop_pop(out);
470         prt_newline(out);
471
472         printbuf_tabstops_reset(out);
473
474         printbuf_tabstop_push(out, out->indent + 20);
475         printbuf_tabstop_push(out, TABSTOP_SIZE + 2);
476         printbuf_tabstop_push(out, 0);
477         printbuf_tabstop_push(out, TABSTOP_SIZE + 2);
478
479         prt_tab(out);
480         prt_printf(out, "since mount");
481         prt_tab_rjust(out);
482         prt_tab(out);
483         prt_printf(out, "recent");
484         prt_tab_rjust(out);
485         prt_newline(out);
486
487         printbuf_tabstops_reset(out);
488         printbuf_tabstop_push(out, out->indent + 20);
489         printbuf_tabstop_push(out, TABSTOP_SIZE);
490         printbuf_tabstop_push(out, 2);
491         printbuf_tabstop_push(out, TABSTOP_SIZE);
492
493         prt_printf(out, "duration of events");
494         prt_newline(out);
495         printbuf_indent_add(out, 2);
496
497         pr_name_and_units(out, "min:", stats->min_duration);
498         pr_name_and_units(out, "max:", stats->max_duration);
499
500         prt_printf(out, "mean:");
501         prt_tab(out);
502         pr_time_units(out, d_mean);
503         prt_tab(out);
504         pr_time_units(out, mean_and_variance_weighted_get_mean(stats->duration_stats_weighted));
505         prt_newline(out);
506
507         prt_printf(out, "stddev:");
508         prt_tab(out);
509         pr_time_units(out, d_stddev);
510         prt_tab(out);
511         pr_time_units(out, mean_and_variance_weighted_get_stddev(stats->duration_stats_weighted));
512
513         printbuf_indent_sub(out, 2);
514         prt_newline(out);
515
516         prt_printf(out, "time between events");
517         prt_newline(out);
518         printbuf_indent_add(out, 2);
519
520         pr_name_and_units(out, "min:", stats->min_freq);
521         pr_name_and_units(out, "max:", stats->max_freq);
522
523         prt_printf(out, "mean:");
524         prt_tab(out);
525         pr_time_units(out, f_mean);
526         prt_tab(out);
527         pr_time_units(out, mean_and_variance_weighted_get_mean(stats->freq_stats_weighted));
528         prt_newline(out);
529
530         prt_printf(out, "stddev:");
531         prt_tab(out);
532         pr_time_units(out, f_stddev);
533         prt_tab(out);
534         pr_time_units(out, mean_and_variance_weighted_get_stddev(stats->freq_stats_weighted));
535
536         printbuf_indent_sub(out, 2);
537         prt_newline(out);
538
539         printbuf_tabstops_reset(out);
540
541         i = eytzinger0_first(NR_QUANTILES);
542         u = pick_time_units(stats->quantiles.entries[i].m);
543
544         prt_printf(out, "quantiles (%s):\t", u->name);
545         eytzinger0_for_each(i, NR_QUANTILES) {
546                 bool is_last = eytzinger0_next(i, NR_QUANTILES) == -1;
547
548                 q = max(stats->quantiles.entries[i].m, last_q);
549                 prt_printf(out, "%llu ",
550                        div_u64(q, u->nsecs));
551                 if (is_last)
552                         prt_newline(out);
553                 last_q = q;
554         }
555 }
556
557 void bch2_time_stats_exit(struct time_stats *stats)
558 {
559         free_percpu(stats->buffer);
560 }
561
562 void bch2_time_stats_init(struct time_stats *stats)
563 {
564         memset(stats, 0, sizeof(*stats));
565         stats->duration_stats_weighted.w = 8;
566         stats->freq_stats_weighted.w = 8;
567         stats->min_duration = U64_MAX;
568         stats->min_freq = U64_MAX;
569         spin_lock_init(&stats->lock);
570 }
571
572 /* ratelimit: */
573
574 /**
575  * bch2_ratelimit_delay() - return how long to delay until the next time to do
576  * some work
577  *
578  * @d - the struct bch_ratelimit to update
579  *
580  * Returns the amount of time to delay by, in jiffies
581  */
582 u64 bch2_ratelimit_delay(struct bch_ratelimit *d)
583 {
584         u64 now = local_clock();
585
586         return time_after64(d->next, now)
587                 ? nsecs_to_jiffies(d->next - now)
588                 : 0;
589 }
590
591 /**
592  * bch2_ratelimit_increment() - increment @d by the amount of work done
593  *
594  * @d - the struct bch_ratelimit to update
595  * @done - the amount of work done, in arbitrary units
596  */
597 void bch2_ratelimit_increment(struct bch_ratelimit *d, u64 done)
598 {
599         u64 now = local_clock();
600
601         d->next += div_u64(done * NSEC_PER_SEC, d->rate);
602
603         if (time_before64(now + NSEC_PER_SEC, d->next))
604                 d->next = now + NSEC_PER_SEC;
605
606         if (time_after64(now - NSEC_PER_SEC * 2, d->next))
607                 d->next = now - NSEC_PER_SEC * 2;
608 }
609
610 /* pd controller: */
611
612 /*
613  * Updates pd_controller. Attempts to scale inputed values to units per second.
614  * @target: desired value
615  * @actual: current value
616  *
617  * @sign: 1 or -1; 1 if increasing the rate makes actual go up, -1 if increasing
618  * it makes actual go down.
619  */
620 void bch2_pd_controller_update(struct bch_pd_controller *pd,
621                               s64 target, s64 actual, int sign)
622 {
623         s64 proportional, derivative, change;
624
625         unsigned long seconds_since_update = (jiffies - pd->last_update) / HZ;
626
627         if (seconds_since_update == 0)
628                 return;
629
630         pd->last_update = jiffies;
631
632         proportional = actual - target;
633         proportional *= seconds_since_update;
634         proportional = div_s64(proportional, pd->p_term_inverse);
635
636         derivative = actual - pd->last_actual;
637         derivative = div_s64(derivative, seconds_since_update);
638         derivative = ewma_add(pd->smoothed_derivative, derivative,
639                               (pd->d_term / seconds_since_update) ?: 1);
640         derivative = derivative * pd->d_term;
641         derivative = div_s64(derivative, pd->p_term_inverse);
642
643         change = proportional + derivative;
644
645         /* Don't increase rate if not keeping up */
646         if (change > 0 &&
647             pd->backpressure &&
648             time_after64(local_clock(),
649                          pd->rate.next + NSEC_PER_MSEC))
650                 change = 0;
651
652         change *= (sign * -1);
653
654         pd->rate.rate = clamp_t(s64, (s64) pd->rate.rate + change,
655                                 1, UINT_MAX);
656
657         pd->last_actual         = actual;
658         pd->last_derivative     = derivative;
659         pd->last_proportional   = proportional;
660         pd->last_change         = change;
661         pd->last_target         = target;
662 }
663
664 void bch2_pd_controller_init(struct bch_pd_controller *pd)
665 {
666         pd->rate.rate           = 1024;
667         pd->last_update         = jiffies;
668         pd->p_term_inverse      = 6000;
669         pd->d_term              = 30;
670         pd->d_smooth            = pd->d_term;
671         pd->backpressure        = 1;
672 }
673
674 void bch2_pd_controller_debug_to_text(struct printbuf *out, struct bch_pd_controller *pd)
675 {
676         if (!out->nr_tabstops)
677                 printbuf_tabstop_push(out, 20);
678
679         prt_printf(out, "rate:");
680         prt_tab(out);
681         prt_human_readable_s64(out, pd->rate.rate);
682         prt_newline(out);
683
684         prt_printf(out, "target:");
685         prt_tab(out);
686         prt_human_readable_u64(out, pd->last_target);
687         prt_newline(out);
688
689         prt_printf(out, "actual:");
690         prt_tab(out);
691         prt_human_readable_u64(out, pd->last_actual);
692         prt_newline(out);
693
694         prt_printf(out, "proportional:");
695         prt_tab(out);
696         prt_human_readable_s64(out, pd->last_proportional);
697         prt_newline(out);
698
699         prt_printf(out, "derivative:");
700         prt_tab(out);
701         prt_human_readable_s64(out, pd->last_derivative);
702         prt_newline(out);
703
704         prt_printf(out, "change:");
705         prt_tab(out);
706         prt_human_readable_s64(out, pd->last_change);
707         prt_newline(out);
708
709         prt_printf(out, "next io:");
710         prt_tab(out);
711         prt_printf(out, "%llims", div64_s64(pd->rate.next - local_clock(), NSEC_PER_MSEC));
712         prt_newline(out);
713 }
714
715 /* misc: */
716
717 void bch2_bio_map(struct bio *bio, void *base, size_t size)
718 {
719         while (size) {
720                 struct page *page = is_vmalloc_addr(base)
721                                 ? vmalloc_to_page(base)
722                                 : virt_to_page(base);
723                 unsigned offset = offset_in_page(base);
724                 unsigned len = min_t(size_t, PAGE_SIZE - offset, size);
725
726                 BUG_ON(!bio_add_page(bio, page, len, offset));
727                 size -= len;
728                 base += len;
729         }
730 }
731
732 int bch2_bio_alloc_pages(struct bio *bio, size_t size, gfp_t gfp_mask)
733 {
734         while (size) {
735                 struct page *page = alloc_page(gfp_mask);
736                 unsigned len = min_t(size_t, PAGE_SIZE, size);
737
738                 if (!page)
739                         return -ENOMEM;
740
741                 if (unlikely(!bio_add_page(bio, page, len, 0))) {
742                         __free_page(page);
743                         break;
744                 }
745
746                 size -= len;
747         }
748
749         return 0;
750 }
751
752 size_t bch2_rand_range(size_t max)
753 {
754         size_t rand;
755
756         if (!max)
757                 return 0;
758
759         do {
760                 rand = get_random_long();
761                 rand &= roundup_pow_of_two(max) - 1;
762         } while (rand >= max);
763
764         return rand;
765 }
766
767 void memcpy_to_bio(struct bio *dst, struct bvec_iter dst_iter, const void *src)
768 {
769         struct bio_vec bv;
770         struct bvec_iter iter;
771
772         __bio_for_each_segment(bv, dst, iter, dst_iter) {
773                 void *dstp = kmap_atomic(bv.bv_page);
774                 memcpy(dstp + bv.bv_offset, src, bv.bv_len);
775                 kunmap_atomic(dstp);
776
777                 src += bv.bv_len;
778         }
779 }
780
781 void memcpy_from_bio(void *dst, struct bio *src, struct bvec_iter src_iter)
782 {
783         struct bio_vec bv;
784         struct bvec_iter iter;
785
786         __bio_for_each_segment(bv, src, iter, src_iter) {
787                 void *srcp = kmap_atomic(bv.bv_page);
788                 memcpy(dst, srcp + bv.bv_offset, bv.bv_len);
789                 kunmap_atomic(srcp);
790
791                 dst += bv.bv_len;
792         }
793 }
794
795 static int alignment_ok(const void *base, size_t align)
796 {
797         return IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) ||
798                 ((unsigned long)base & (align - 1)) == 0;
799 }
800
801 static void u32_swap(void *a, void *b, size_t size)
802 {
803         u32 t = *(u32 *)a;
804         *(u32 *)a = *(u32 *)b;
805         *(u32 *)b = t;
806 }
807
808 static void u64_swap(void *a, void *b, size_t size)
809 {
810         u64 t = *(u64 *)a;
811         *(u64 *)a = *(u64 *)b;
812         *(u64 *)b = t;
813 }
814
815 static void generic_swap(void *a, void *b, size_t size)
816 {
817         char t;
818
819         do {
820                 t = *(char *)a;
821                 *(char *)a++ = *(char *)b;
822                 *(char *)b++ = t;
823         } while (--size > 0);
824 }
825
826 static inline int do_cmp(void *base, size_t n, size_t size,
827                          int (*cmp_func)(const void *, const void *, size_t),
828                          size_t l, size_t r)
829 {
830         return cmp_func(base + inorder_to_eytzinger0(l, n) * size,
831                         base + inorder_to_eytzinger0(r, n) * size,
832                         size);
833 }
834
835 static inline void do_swap(void *base, size_t n, size_t size,
836                            void (*swap_func)(void *, void *, size_t),
837                            size_t l, size_t r)
838 {
839         swap_func(base + inorder_to_eytzinger0(l, n) * size,
840                   base + inorder_to_eytzinger0(r, n) * size,
841                   size);
842 }
843
844 void eytzinger0_sort(void *base, size_t n, size_t size,
845                      int (*cmp_func)(const void *, const void *, size_t),
846                      void (*swap_func)(void *, void *, size_t))
847 {
848         int i, c, r;
849
850         if (!swap_func) {
851                 if (size == 4 && alignment_ok(base, 4))
852                         swap_func = u32_swap;
853                 else if (size == 8 && alignment_ok(base, 8))
854                         swap_func = u64_swap;
855                 else
856                         swap_func = generic_swap;
857         }
858
859         /* heapify */
860         for (i = n / 2 - 1; i >= 0; --i) {
861                 for (r = i; r * 2 + 1 < n; r = c) {
862                         c = r * 2 + 1;
863
864                         if (c + 1 < n &&
865                             do_cmp(base, n, size, cmp_func, c, c + 1) < 0)
866                                 c++;
867
868                         if (do_cmp(base, n, size, cmp_func, r, c) >= 0)
869                                 break;
870
871                         do_swap(base, n, size, swap_func, r, c);
872                 }
873         }
874
875         /* sort */
876         for (i = n - 1; i > 0; --i) {
877                 do_swap(base, n, size, swap_func, 0, i);
878
879                 for (r = 0; r * 2 + 1 < i; r = c) {
880                         c = r * 2 + 1;
881
882                         if (c + 1 < i &&
883                             do_cmp(base, n, size, cmp_func, c, c + 1) < 0)
884                                 c++;
885
886                         if (do_cmp(base, n, size, cmp_func, r, c) >= 0)
887                                 break;
888
889                         do_swap(base, n, size, swap_func, r, c);
890                 }
891         }
892 }
893
894 void sort_cmp_size(void *base, size_t num, size_t size,
895           int (*cmp_func)(const void *, const void *, size_t),
896           void (*swap_func)(void *, void *, size_t size))
897 {
898         /* pre-scale counters for performance */
899         int i = (num/2 - 1) * size, n = num * size, c, r;
900
901         if (!swap_func) {
902                 if (size == 4 && alignment_ok(base, 4))
903                         swap_func = u32_swap;
904                 else if (size == 8 && alignment_ok(base, 8))
905                         swap_func = u64_swap;
906                 else
907                         swap_func = generic_swap;
908         }
909
910         /* heapify */
911         for ( ; i >= 0; i -= size) {
912                 for (r = i; r * 2 + size < n; r  = c) {
913                         c = r * 2 + size;
914                         if (c < n - size &&
915                             cmp_func(base + c, base + c + size, size) < 0)
916                                 c += size;
917                         if (cmp_func(base + r, base + c, size) >= 0)
918                                 break;
919                         swap_func(base + r, base + c, size);
920                 }
921         }
922
923         /* sort */
924         for (i = n - size; i > 0; i -= size) {
925                 swap_func(base, base + i, size);
926                 for (r = 0; r * 2 + size < i; r = c) {
927                         c = r * 2 + size;
928                         if (c < i - size &&
929                             cmp_func(base + c, base + c + size, size) < 0)
930                                 c += size;
931                         if (cmp_func(base + r, base + c, size) >= 0)
932                                 break;
933                         swap_func(base + r, base + c, size);
934                 }
935         }
936 }
937
938 static void mempool_free_vp(void *element, void *pool_data)
939 {
940         size_t size = (size_t) pool_data;
941
942         vpfree(element, size);
943 }
944
945 static void *mempool_alloc_vp(gfp_t gfp_mask, void *pool_data)
946 {
947         size_t size = (size_t) pool_data;
948
949         return vpmalloc(size, gfp_mask);
950 }
951
952 int mempool_init_kvpmalloc_pool(mempool_t *pool, int min_nr, size_t size)
953 {
954         return size < PAGE_SIZE
955                 ? mempool_init_kmalloc_pool(pool, min_nr, size)
956                 : mempool_init(pool, min_nr, mempool_alloc_vp,
957                                mempool_free_vp, (void *) size);
958 }
959
960 #if 0
961 void eytzinger1_test(void)
962 {
963         unsigned inorder, eytz, size;
964
965         pr_info("1 based eytzinger test:");
966
967         for (size = 2;
968              size < 65536;
969              size++) {
970                 unsigned extra = eytzinger1_extra(size);
971
972                 if (!(size % 4096))
973                         pr_info("tree size %u", size);
974
975                 BUG_ON(eytzinger1_prev(0, size) != eytzinger1_last(size));
976                 BUG_ON(eytzinger1_next(0, size) != eytzinger1_first(size));
977
978                 BUG_ON(eytzinger1_prev(eytzinger1_first(size), size)    != 0);
979                 BUG_ON(eytzinger1_next(eytzinger1_last(size), size)     != 0);
980
981                 inorder = 1;
982                 eytzinger1_for_each(eytz, size) {
983                         BUG_ON(__inorder_to_eytzinger1(inorder, size, extra) != eytz);
984                         BUG_ON(__eytzinger1_to_inorder(eytz, size, extra) != inorder);
985                         BUG_ON(eytz != eytzinger1_last(size) &&
986                                eytzinger1_prev(eytzinger1_next(eytz, size), size) != eytz);
987
988                         inorder++;
989                 }
990         }
991 }
992
993 void eytzinger0_test(void)
994 {
995
996         unsigned inorder, eytz, size;
997
998         pr_info("0 based eytzinger test:");
999
1000         for (size = 1;
1001              size < 65536;
1002              size++) {
1003                 unsigned extra = eytzinger0_extra(size);
1004
1005                 if (!(size % 4096))
1006                         pr_info("tree size %u", size);
1007
1008                 BUG_ON(eytzinger0_prev(-1, size) != eytzinger0_last(size));
1009                 BUG_ON(eytzinger0_next(-1, size) != eytzinger0_first(size));
1010
1011                 BUG_ON(eytzinger0_prev(eytzinger0_first(size), size)    != -1);
1012                 BUG_ON(eytzinger0_next(eytzinger0_last(size), size)     != -1);
1013
1014                 inorder = 0;
1015                 eytzinger0_for_each(eytz, size) {
1016                         BUG_ON(__inorder_to_eytzinger0(inorder, size, extra) != eytz);
1017                         BUG_ON(__eytzinger0_to_inorder(eytz, size, extra) != inorder);
1018                         BUG_ON(eytz != eytzinger0_last(size) &&
1019                                eytzinger0_prev(eytzinger0_next(eytz, size), size) != eytz);
1020
1021                         inorder++;
1022                 }
1023         }
1024 }
1025
1026 static inline int cmp_u16(const void *_l, const void *_r, size_t size)
1027 {
1028         const u16 *l = _l, *r = _r;
1029
1030         return (*l > *r) - (*r - *l);
1031 }
1032
1033 static void eytzinger0_find_test_val(u16 *test_array, unsigned nr, u16 search)
1034 {
1035         int i, c1 = -1, c2 = -1;
1036         ssize_t r;
1037
1038         r = eytzinger0_find_le(test_array, nr,
1039                                sizeof(test_array[0]),
1040                                cmp_u16, &search);
1041         if (r >= 0)
1042                 c1 = test_array[r];
1043
1044         for (i = 0; i < nr; i++)
1045                 if (test_array[i] <= search && test_array[i] > c2)
1046                         c2 = test_array[i];
1047
1048         if (c1 != c2) {
1049                 eytzinger0_for_each(i, nr)
1050                         pr_info("[%3u] = %12u", i, test_array[i]);
1051                 pr_info("find_le(%2u) -> [%2zi] = %2i should be %2i",
1052                         i, r, c1, c2);
1053         }
1054 }
1055
1056 void eytzinger0_find_test(void)
1057 {
1058         unsigned i, nr, allocated = 1 << 12;
1059         u16 *test_array = kmalloc_array(allocated, sizeof(test_array[0]), GFP_KERNEL);
1060
1061         for (nr = 1; nr < allocated; nr++) {
1062                 pr_info("testing %u elems", nr);
1063
1064                 get_random_bytes(test_array, nr * sizeof(test_array[0]));
1065                 eytzinger0_sort(test_array, nr, sizeof(test_array[0]), cmp_u16, NULL);
1066
1067                 /* verify array is sorted correctly: */
1068                 eytzinger0_for_each(i, nr)
1069                         BUG_ON(i != eytzinger0_last(nr) &&
1070                                test_array[i] > test_array[eytzinger0_next(i, nr)]);
1071
1072                 for (i = 0; i < U16_MAX; i += 1 << 12)
1073                         eytzinger0_find_test_val(test_array, nr, i);
1074
1075                 for (i = 0; i < nr; i++) {
1076                         eytzinger0_find_test_val(test_array, nr, test_array[i] - 1);
1077                         eytzinger0_find_test_val(test_array, nr, test_array[i]);
1078                         eytzinger0_find_test_val(test_array, nr, test_array[i] + 1);
1079                 }
1080         }
1081
1082         kfree(test_array);
1083 }
1084 #endif
1085
1086 /*
1087  * Accumulate percpu counters onto one cpu's copy - only valid when access
1088  * against any percpu counter is guarded against
1089  */
1090 u64 *bch2_acc_percpu_u64s(u64 __percpu *p, unsigned nr)
1091 {
1092         u64 *ret;
1093         int cpu;
1094
1095         /* access to pcpu vars has to be blocked by other locking */
1096         preempt_disable();
1097         ret = this_cpu_ptr(p);
1098         preempt_enable();
1099
1100         for_each_possible_cpu(cpu) {
1101                 u64 *i = per_cpu_ptr(p, cpu);
1102
1103                 if (i != ret) {
1104                         acc_u64s(ret, i, nr);
1105                         memset(i, 0, nr * sizeof(u64));
1106                 }
1107         }
1108
1109         return ret;
1110 }