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