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