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