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