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