]> git.sesse.net Git - bcachefs-tools-debian/blobdiff - libbcachefs/util.c
Move c_src dirs back to toplevel
[bcachefs-tools-debian] / libbcachefs / util.c
index 1272ea7a7a2864d7f55c989f07b4f85a2ece8144..c2ef7cddaa4fcb0e9de9df263aadd019cc7a4965 100644 (file)
@@ -1,3 +1,4 @@
+// SPDX-License-Identifier: GPL-2.0
 /*
  * random utiility code, for bcache but in theory not specific to bcache
  *
@@ -7,6 +8,7 @@
 
 #include <linux/bio.h>
 #include <linux/blkdev.h>
+#include <linux/console.h>
 #include <linux/ctype.h>
 #include <linux/debugfs.h>
 #include <linux/freezer.h>
 #include <linux/sched/clock.h>
 
 #include "eytzinger.h"
+#include "mean_and_variance.h"
 #include "util.h"
 
-#define simple_strtoint(c, end, base)  simple_strtol(c, end, base)
-#define simple_strtouint(c, end, base) simple_strtoul(c, end, base)
-
 static const char si_units[] = "?kMGTPEZY";
 
-static int __bch2_strtoh(const char *cp, u64 *res,
-                        u64 t_max, bool t_signed)
+/* string_get_size units: */
+static const char *const units_2[] = {
+       "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"
+};
+static const char *const units_10[] = {
+       "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"
+};
+
+static int parse_u64(const char *cp, u64 *res)
 {
-       bool positive = *cp != '-';
-       unsigned u;
+       const char *start = cp;
        u64 v = 0;
 
-       if (*cp == '+' || *cp == '-')
-               cp++;
-
        if (!isdigit(*cp))
                return -EINVAL;
 
@@ -52,22 +55,122 @@ static int __bch2_strtoh(const char *cp, u64 *res,
                cp++;
        } while (isdigit(*cp));
 
+       *res = v;
+       return cp - start;
+}
+
+static int bch2_pow(u64 n, u64 p, u64 *res)
+{
+       *res = 1;
+
+       while (p--) {
+               if (*res > div_u64(U64_MAX, n))
+                       return -ERANGE;
+               *res *= n;
+       }
+       return 0;
+}
+
+static int parse_unit_suffix(const char *cp, u64 *res)
+{
+       const char *start = cp;
+       u64 base = 1024;
+       unsigned u;
+       int ret;
+
+       if (*cp == ' ')
+               cp++;
+
        for (u = 1; u < strlen(si_units); u++)
                if (*cp == si_units[u]) {
                        cp++;
                        goto got_unit;
                }
-       u = 0;
+
+       for (u = 0; u < ARRAY_SIZE(units_2); u++)
+               if (!strncmp(cp, units_2[u], strlen(units_2[u]))) {
+                       cp += strlen(units_2[u]);
+                       goto got_unit;
+               }
+
+       for (u = 0; u < ARRAY_SIZE(units_10); u++)
+               if (!strncmp(cp, units_10[u], strlen(units_10[u]))) {
+                       cp += strlen(units_10[u]);
+                       base = 1000;
+                       goto got_unit;
+               }
+
+       *res = 1;
+       return 0;
 got_unit:
-       if (*cp == '\n')
+       ret = bch2_pow(base, u, res);
+       if (ret)
+               return ret;
+
+       return cp - start;
+}
+
+#define parse_or_ret(cp, _f)                   \
+do {                                           \
+       int _ret = _f;                          \
+       if (_ret < 0)                           \
+               return _ret;                    \
+       cp += _ret;                             \
+} while (0)
+
+static int __bch2_strtou64_h(const char *cp, u64 *res)
+{
+       const char *start = cp;
+       u64 v = 0, b, f_n = 0, f_d = 1;
+       int ret;
+
+       parse_or_ret(cp, parse_u64(cp, &v));
+
+       if (*cp == '.') {
                cp++;
-       if (*cp)
-               return -EINVAL;
+               ret = parse_u64(cp, &f_n);
+               if (ret < 0)
+                       return ret;
+               cp += ret;
+
+               ret = bch2_pow(10, ret, &f_d);
+               if (ret)
+                       return ret;
+       }
+
+       parse_or_ret(cp, parse_unit_suffix(cp, &b));
+
+       if (v > div_u64(U64_MAX, b))
+               return -ERANGE;
+       v *= b;
+
+       if (f_n > div_u64(U64_MAX, b))
+               return -ERANGE;
 
-       if (fls64(v) + u * 10 > 64)
+       f_n = div_u64(f_n * b, f_d);
+       if (v + f_n < v)
                return -ERANGE;
+       v += f_n;
+
+       *res = v;
+       return cp - start;
+}
+
+static int __bch2_strtoh(const char *cp, u64 *res,
+                        u64 t_max, bool t_signed)
+{
+       bool positive = *cp != '-';
+       u64 v = 0;
+
+       if (*cp == '+' || *cp == '-')
+               cp++;
+
+       parse_or_ret(cp, __bch2_strtou64_h(cp, &v));
 
-       v <<= u * 10;
+       if (*cp == '\n')
+               cp++;
+       if (*cp)
+               return -EINVAL;
 
        if (positive) {
                if (v > t_max)
@@ -88,7 +191,7 @@ got_unit:
 #define STRTO_H(name, type)                                    \
 int bch2_ ## name ## _h(const char *cp, type *res)             \
 {                                                              \
-       u64 v;                                                  \
+       u64 v = 0;                                              \
        int ret = __bch2_strtoh(cp, &v, ANYSINT_MAX(type),      \
                        ANYSINT_MAX(type) != ((type) ~0ULL));   \
        *res = v;                                               \
@@ -99,115 +202,178 @@ STRTO_H(strtoint, int)
 STRTO_H(strtouint, unsigned int)
 STRTO_H(strtoll, long long)
 STRTO_H(strtoull, unsigned long long)
+STRTO_H(strtou64, u64)
 
-ssize_t bch2_hprint(char *buf, s64 v)
+u64 bch2_read_flag_list(char *opt, const char * const list[])
 {
-       char dec[4] = "";
-       int u, t = 0;
+       u64 ret = 0;
+       char *p, *s, *d = kstrdup(opt, GFP_KERNEL);
 
-       for (u = 0; v >= 1024 || v <= -1024; u++) {
-               t = v & ~(~0U << 10);
-               v >>= 10;
-       }
+       if (!d)
+               return -ENOMEM;
 
-       if (!u)
-               return sprintf(buf, "%lli", v);
+       s = strim(d);
 
-       /*
-        * 103 is magic: t is in the range [-1023, 1023] and we want
-        * to turn it into [-9, 9]
-        */
-       if (v < 100 && v > -100)
-               scnprintf(dec, sizeof(dec), ".%i", t / 103);
+       while ((p = strsep(&s, ","))) {
+               int flag = match_string(list, -1, p);
+
+               if (flag < 0) {
+                       ret = -1;
+                       break;
+               }
 
-       return sprintf(buf, "%lli%s%c", v, dec, si_units[u]);
+               ret |= 1 << flag;
+       }
+
+       kfree(d);
+
+       return ret;
 }
 
-ssize_t bch2_scnprint_string_list(char *buf, size_t size,
-                                 const char * const list[],
-                                 size_t selected)
+bool bch2_is_zero(const void *_p, size_t n)
 {
-       char *out = buf;
+       const char *p = _p;
        size_t i;
 
-       if (size)
-               *out = '\0';
+       for (i = 0; i < n; i++)
+               if (p[i])
+                       return false;
+       return true;
+}
 
-       for (i = 0; list[i]; i++)
-               out += scnprintf(out, buf + size - out,
-                                i == selected ? "[%s] " : "%s ", list[i]);
+void bch2_prt_u64_binary(struct printbuf *out, u64 v, unsigned nr_bits)
+{
+       while (nr_bits)
+               prt_char(out, '0' + ((v >> --nr_bits) & 1));
+}
 
-       if (out != buf)
-               *--out = '\0';
+void bch2_print_string_as_lines(const char *prefix, const char *lines)
+{
+       const char *p;
 
-       return out - buf;
+       if (!lines) {
+               printk("%s (null)\n", prefix);
+               return;
+       }
+
+       console_lock();
+       while (1) {
+               p = strchrnul(lines, '\n');
+               printk("%s%.*s\n", prefix, (int) (p - lines), lines);
+               if (!*p)
+                       break;
+               lines = p + 1;
+       }
+       console_unlock();
 }
 
-ssize_t bch2_scnprint_flag_list(char *buf, size_t size,
-                               const char * const list[], u64 flags)
+int bch2_save_backtrace(bch_stacktrace *stack, struct task_struct *task, unsigned skipnr)
 {
-       char *out = buf, *end = buf + size;
-       unsigned bit, nr = 0;
+#ifdef CONFIG_STACKTRACE
+       unsigned nr_entries = 0;
+       int ret = 0;
 
-       while (list[nr])
-               nr++;
+       stack->nr = 0;
+       ret = darray_make_room(stack, 32);
+       if (ret)
+               return ret;
 
-       if (size)
-               *out = '\0';
+       if (!down_read_trylock(&task->signal->exec_update_lock))
+               return -1;
 
-       while (flags && (bit = __ffs(flags)) < nr) {
-               out += scnprintf(out, end - out, "%s,", list[bit]);
-               flags ^= 1 << bit;
-       }
+       do {
+               nr_entries = stack_trace_save_tsk(task, stack->data, stack->size, skipnr + 1);
+       } while (nr_entries == stack->size &&
+                !(ret = darray_make_room(stack, stack->size * 2)));
 
-       if (out != buf)
-               *--out = '\0';
+       stack->nr = nr_entries;
+       up_read(&task->signal->exec_update_lock);
 
-       return out - buf;
+       return ret;
+#else
+       return 0;
+#endif
 }
 
-u64 bch2_read_flag_list(char *opt, const char * const list[])
+void bch2_prt_backtrace(struct printbuf *out, bch_stacktrace *stack)
 {
-       u64 ret = 0;
-       char *p, *s, *d = kstrndup(opt, PAGE_SIZE - 1, GFP_KERNEL);
+       darray_for_each(*stack, i) {
+               prt_printf(out, "[<0>] %pB", (void *) *i);
+               prt_newline(out);
+       }
+}
 
-       if (!d)
-               return -ENOMEM;
+int bch2_prt_task_backtrace(struct printbuf *out, struct task_struct *task, unsigned skipnr)
+{
+       bch_stacktrace stack = { 0 };
+       int ret = bch2_save_backtrace(&stack, task, skipnr + 1);
 
-       s = strim(d);
+       bch2_prt_backtrace(out, &stack);
+       darray_exit(&stack);
+       return ret;
+}
 
-       while ((p = strsep(&s, ","))) {
-               int flag = match_string(list, -1, p);
-               if (flag < 0) {
-                       ret = -1;
-                       break;
-               }
+#ifndef __KERNEL__
+#include <time.h>
+void bch2_prt_datetime(struct printbuf *out, time64_t sec)
+{
+       time_t t = sec;
+       char buf[64];
+       ctime_r(&t, buf);
+       strim(buf);
+       prt_str(out, buf);
+}
+#else
+void bch2_prt_datetime(struct printbuf *out, time64_t sec)
+{
+       char buf[64];
+       snprintf(buf, sizeof(buf), "%ptT", &sec);
+       prt_u64(out, sec);
+}
+#endif
 
-               ret |= 1 << flag;
-       }
+static const struct time_unit {
+       const char      *name;
+       u64             nsecs;
+} time_units[] = {
+       { "ns",         1                },
+       { "us",         NSEC_PER_USEC    },
+       { "ms",         NSEC_PER_MSEC    },
+       { "s",          NSEC_PER_SEC     },
+       { "m",          (u64) NSEC_PER_SEC * 60},
+       { "h",          (u64) NSEC_PER_SEC * 3600},
+       { "eon",        U64_MAX          },
+};
 
-       kfree(d);
+static const struct time_unit *pick_time_units(u64 ns)
+{
+       const struct time_unit *u;
 
-       return ret;
+       for (u = time_units;
+            u + 1 < time_units + ARRAY_SIZE(time_units) &&
+            ns >= u[1].nsecs << 1;
+            u++)
+               ;
+
+       return u;
 }
 
-bool bch2_is_zero(const void *_p, size_t n)
+void bch2_pr_time_units(struct printbuf *out, u64 ns)
 {
-       const char *p = _p;
-       size_t i;
+       const struct time_unit *u = pick_time_units(ns);
 
-       for (i = 0; i < n; i++)
-               if (p[i])
-                       return false;
-       return true;
+       prt_printf(out, "%llu %s", div_u64(ns, u->nsecs), u->name);
 }
 
-static void bch2_quantiles_update(struct quantiles *q, u64 v)
+/* time stats: */
+
+#ifndef CONFIG_BCACHEFS_NO_LATENCY_ACCT
+static void bch2_quantiles_update(struct bch2_quantiles *q, u64 v)
 {
        unsigned i = 0;
 
        while (i < ARRAY_SIZE(q->entries)) {
-               struct quantile_entry *e = q->entries + i;
+               struct bch2_quantile_entry *e = q->entries + i;
 
                if (unlikely(!e->step)) {
                        e->m = v;
@@ -232,154 +398,241 @@ static void bch2_quantiles_update(struct quantiles *q, u64 v)
        }
 }
 
-/* time stats: */
-
-static void bch2_time_stats_update_one(struct time_stats *stats,
-                                      u64 start, u64 end)
+static inline void bch2_time_stats_update_one(struct bch2_time_stats *stats,
+                                             u64 start, u64 end)
 {
        u64 duration, freq;
 
-       duration        = time_after64(end, start)
-               ? end - start : 0;
-       freq            = time_after64(end, stats->last_event)
-               ? end - stats->last_event : 0;
-
-       stats->count++;
-
-       stats->average_duration = stats->average_duration
-               ? ewma_add(stats->average_duration, duration, 6)
-               : duration;
+       if (time_after64(end, start)) {
+               duration = end - start;
+               mean_and_variance_update(&stats->duration_stats, duration);
+               mean_and_variance_weighted_update(&stats->duration_stats_weighted, duration);
+               stats->max_duration = max(stats->max_duration, duration);
+               stats->min_duration = min(stats->min_duration, duration);
+               stats->total_duration += duration;
+               bch2_quantiles_update(&stats->quantiles, duration);
+       }
 
-       stats->average_frequency = stats->average_frequency
-               ? ewma_add(stats->average_frequency, freq, 6)
-               : freq;
+       if (time_after64(end, stats->last_event)) {
+               freq = end - stats->last_event;
+               mean_and_variance_update(&stats->freq_stats, freq);
+               mean_and_variance_weighted_update(&stats->freq_stats_weighted, freq);
+               stats->max_freq = max(stats->max_freq, freq);
+               stats->min_freq = min(stats->min_freq, freq);
+               stats->last_event = end;
+       }
+}
 
-       stats->max_duration = max(stats->max_duration, duration);
+static void __bch2_time_stats_clear_buffer(struct bch2_time_stats *stats,
+                                          struct bch2_time_stat_buffer *b)
+{
+       for (struct bch2_time_stat_buffer_entry *i = b->entries;
+            i < b->entries + ARRAY_SIZE(b->entries);
+            i++)
+               bch2_time_stats_update_one(stats, i->start, i->end);
+       b->nr = 0;
+}
 
-       stats->last_event = end;
+static noinline void bch2_time_stats_clear_buffer(struct bch2_time_stats *stats,
+                                                 struct bch2_time_stat_buffer *b)
+{
+       unsigned long flags;
 
-       bch2_quantiles_update(&stats->quantiles, duration);
+       spin_lock_irqsave(&stats->lock, flags);
+       __bch2_time_stats_clear_buffer(stats, b);
+       spin_unlock_irqrestore(&stats->lock, flags);
 }
 
-void __bch2_time_stats_update(struct time_stats *stats, u64 start, u64 end)
+void __bch2_time_stats_update(struct bch2_time_stats *stats, u64 start, u64 end)
 {
        unsigned long flags;
 
+       WARN_ONCE(!stats->duration_stats_weighted.weight ||
+                 !stats->freq_stats_weighted.weight,
+                 "uninitialized time_stats");
+
        if (!stats->buffer) {
                spin_lock_irqsave(&stats->lock, flags);
                bch2_time_stats_update_one(stats, start, end);
 
-               if (stats->average_frequency < 32 &&
-                   stats->count > 1024)
+               if (mean_and_variance_weighted_get_mean(stats->freq_stats_weighted) < 32 &&
+                   stats->duration_stats.n > 1024)
                        stats->buffer =
-                               alloc_percpu_gfp(struct time_stat_buffer,
+                               alloc_percpu_gfp(struct bch2_time_stat_buffer,
                                                 GFP_ATOMIC);
                spin_unlock_irqrestore(&stats->lock, flags);
        } else {
-               struct time_stat_buffer_entry *i;
-               struct time_stat_buffer *b;
+               struct bch2_time_stat_buffer *b;
 
                preempt_disable();
                b = this_cpu_ptr(stats->buffer);
 
                BUG_ON(b->nr >= ARRAY_SIZE(b->entries));
-               b->entries[b->nr++] = (struct time_stat_buffer_entry) {
+               b->entries[b->nr++] = (struct bch2_time_stat_buffer_entry) {
                        .start = start,
                        .end = end
                };
 
-               if (b->nr == ARRAY_SIZE(b->entries)) {
-                       spin_lock_irqsave(&stats->lock, flags);
-                       for (i = b->entries;
-                            i < b->entries + ARRAY_SIZE(b->entries);
-                            i++)
-                               bch2_time_stats_update_one(stats, i->start, i->end);
-                       spin_unlock_irqrestore(&stats->lock, flags);
-
-                       b->nr = 0;
-               }
-
+               if (unlikely(b->nr == ARRAY_SIZE(b->entries)))
+                       bch2_time_stats_clear_buffer(stats, b);
                preempt_enable();
        }
 }
 
-static const struct time_unit {
-       const char      *name;
-       u32             nsecs;
-} time_units[] = {
-       { "ns",         1               },
-       { "us",         NSEC_PER_USEC   },
-       { "ms",         NSEC_PER_MSEC   },
-       { "sec",        NSEC_PER_SEC    },
-};
-
-static const struct time_unit *pick_time_units(u64 ns)
+static void bch2_pr_time_units_aligned(struct printbuf *out, u64 ns)
 {
-       const struct time_unit *u;
-
-       for (u = time_units;
-            u + 1 < time_units + ARRAY_SIZE(time_units) &&
-            ns >= u[1].nsecs << 1;
-            u++)
-               ;
+       const struct time_unit *u = pick_time_units(ns);
 
-       return u;
+       prt_printf(out, "%llu ", div64_u64(ns, u->nsecs));
+       prt_tab_rjust(out);
+       prt_printf(out, "%s", u->name);
 }
 
-static size_t pr_time_units(char *buf, size_t len, u64 ns)
+static inline void pr_name_and_units(struct printbuf *out, const char *name, u64 ns)
 {
-       const struct time_unit *u = pick_time_units(ns);
-
-       return scnprintf(buf, len, "%llu %s", div_u64(ns, u->nsecs), u->name);
+       prt_str(out, name);
+       prt_tab(out);
+       bch2_pr_time_units_aligned(out, ns);
+       prt_newline(out);
 }
 
-size_t bch2_time_stats_print(struct time_stats *stats, char *buf, size_t len)
+#define TABSTOP_SIZE 12
+
+void bch2_time_stats_to_text(struct printbuf *out, struct bch2_time_stats *stats)
 {
-       char *out = buf, *end = buf + len;
        const struct time_unit *u;
-       u64 freq = READ_ONCE(stats->average_frequency);
-       u64 q, last_q = 0;
+       s64 f_mean = 0, d_mean = 0;
+       u64 q, last_q = 0, f_stddev = 0, d_stddev = 0;
        int i;
 
-       out += scnprintf(out, end - out, "count:\t\t%llu\n",
-                        stats->count);
-       out += scnprintf(out, end - out, "rate:\t\t%llu/sec\n",
-                        freq ?  div64_u64(NSEC_PER_SEC, freq) : 0);
+       if (stats->buffer) {
+               int cpu;
 
-       out += scnprintf(out, end - out, "frequency:\t");
-       out += pr_time_units(out, end - out, freq);
+               spin_lock_irq(&stats->lock);
+               for_each_possible_cpu(cpu)
+                       __bch2_time_stats_clear_buffer(stats, per_cpu_ptr(stats->buffer, cpu));
+               spin_unlock_irq(&stats->lock);
+       }
 
-       out += scnprintf(out, end - out, "\navg duration:\t");
-       out += pr_time_units(out, end - out, stats->average_duration);
+       /*
+        * avoid divide by zero
+        */
+       if (stats->freq_stats.n) {
+               f_mean = mean_and_variance_get_mean(stats->freq_stats);
+               f_stddev = mean_and_variance_get_stddev(stats->freq_stats);
+               d_mean = mean_and_variance_get_mean(stats->duration_stats);
+               d_stddev = mean_and_variance_get_stddev(stats->duration_stats);
+       }
 
-       out += scnprintf(out, end - out, "\nmax duration:\t");
-       out += pr_time_units(out, end - out, stats->max_duration);
+       printbuf_tabstop_push(out, out->indent + TABSTOP_SIZE);
+       prt_printf(out, "count:");
+       prt_tab(out);
+       prt_printf(out, "%llu ",
+                        stats->duration_stats.n);
+       printbuf_tabstop_pop(out);
+       prt_newline(out);
+
+       printbuf_tabstops_reset(out);
+
+       printbuf_tabstop_push(out, out->indent + 20);
+       printbuf_tabstop_push(out, TABSTOP_SIZE + 2);
+       printbuf_tabstop_push(out, 0);
+       printbuf_tabstop_push(out, TABSTOP_SIZE + 2);
+
+       prt_tab(out);
+       prt_printf(out, "since mount");
+       prt_tab_rjust(out);
+       prt_tab(out);
+       prt_printf(out, "recent");
+       prt_tab_rjust(out);
+       prt_newline(out);
+
+       printbuf_tabstops_reset(out);
+       printbuf_tabstop_push(out, out->indent + 20);
+       printbuf_tabstop_push(out, TABSTOP_SIZE);
+       printbuf_tabstop_push(out, 2);
+       printbuf_tabstop_push(out, TABSTOP_SIZE);
+
+       prt_printf(out, "duration of events");
+       prt_newline(out);
+       printbuf_indent_add(out, 2);
+
+       pr_name_and_units(out, "min:", stats->min_duration);
+       pr_name_and_units(out, "max:", stats->max_duration);
+       pr_name_and_units(out, "total:", stats->total_duration);
+
+       prt_printf(out, "mean:");
+       prt_tab(out);
+       bch2_pr_time_units_aligned(out, d_mean);
+       prt_tab(out);
+       bch2_pr_time_units_aligned(out, mean_and_variance_weighted_get_mean(stats->duration_stats_weighted));
+       prt_newline(out);
+
+       prt_printf(out, "stddev:");
+       prt_tab(out);
+       bch2_pr_time_units_aligned(out, d_stddev);
+       prt_tab(out);
+       bch2_pr_time_units_aligned(out, mean_and_variance_weighted_get_stddev(stats->duration_stats_weighted));
+
+       printbuf_indent_sub(out, 2);
+       prt_newline(out);
+
+       prt_printf(out, "time between events");
+       prt_newline(out);
+       printbuf_indent_add(out, 2);
+
+       pr_name_and_units(out, "min:", stats->min_freq);
+       pr_name_and_units(out, "max:", stats->max_freq);
+
+       prt_printf(out, "mean:");
+       prt_tab(out);
+       bch2_pr_time_units_aligned(out, f_mean);
+       prt_tab(out);
+       bch2_pr_time_units_aligned(out, mean_and_variance_weighted_get_mean(stats->freq_stats_weighted));
+       prt_newline(out);
+
+       prt_printf(out, "stddev:");
+       prt_tab(out);
+       bch2_pr_time_units_aligned(out, f_stddev);
+       prt_tab(out);
+       bch2_pr_time_units_aligned(out, mean_and_variance_weighted_get_stddev(stats->freq_stats_weighted));
+
+       printbuf_indent_sub(out, 2);
+       prt_newline(out);
+
+       printbuf_tabstops_reset(out);
 
        i = eytzinger0_first(NR_QUANTILES);
        u = pick_time_units(stats->quantiles.entries[i].m);
 
-       out += scnprintf(out, end - out, "\nquantiles (%s):\t", u->name);
+       prt_printf(out, "quantiles (%s):\t", u->name);
        eytzinger0_for_each(i, NR_QUANTILES) {
                bool is_last = eytzinger0_next(i, NR_QUANTILES) == -1;
 
                q = max(stats->quantiles.entries[i].m, last_q);
-               out += scnprintf(out, end - out, "%llu%s",
-                                div_u64(q, u->nsecs),
-                                is_last ? "\n" : " ");
+               prt_printf(out, "%llu ",
+                      div_u64(q, u->nsecs));
+               if (is_last)
+                       prt_newline(out);
                last_q = q;
        }
-
-       return out - buf;
 }
+#else
+void bch2_time_stats_to_text(struct printbuf *out, struct bch2_time_stats *stats) {}
+#endif
 
-void bch2_time_stats_exit(struct time_stats *stats)
+void bch2_time_stats_exit(struct bch2_time_stats *stats)
 {
        free_percpu(stats->buffer);
 }
 
-void bch2_time_stats_init(struct time_stats *stats)
+void bch2_time_stats_init(struct bch2_time_stats *stats)
 {
        memset(stats, 0, sizeof(*stats));
+       stats->duration_stats_weighted.weight = 8;
+       stats->freq_stats_weighted.weight = 8;
+       stats->min_duration = U64_MAX;
+       stats->min_freq = U64_MAX;
        spin_lock_init(&stats->lock);
 }
 
@@ -387,11 +640,9 @@ void bch2_time_stats_init(struct time_stats *stats)
 
 /**
  * bch2_ratelimit_delay() - return how long to delay until the next time to do
- * some work
- *
- * @d - the struct bch_ratelimit to update
- *
- * Returns the amount of time to delay by, in jiffies
+ *             some work
+ * @d:         the struct bch_ratelimit to update
+ * Returns:    the amount of time to delay by, in jiffies
  */
 u64 bch2_ratelimit_delay(struct bch_ratelimit *d)
 {
@@ -404,9 +655,8 @@ u64 bch2_ratelimit_delay(struct bch_ratelimit *d)
 
 /**
  * bch2_ratelimit_increment() - increment @d by the amount of work done
- *
- * @d - the struct bch_ratelimit to update
- * @done - the amount of work done, in arbitrary units
+ * @d:         the struct bch_ratelimit to update
+ * @done:      the amount of work done, in arbitrary units
  */
 void bch2_ratelimit_increment(struct bch_ratelimit *d, u64 done)
 {
@@ -421,27 +671,6 @@ void bch2_ratelimit_increment(struct bch_ratelimit *d, u64 done)
                d->next = now - NSEC_PER_SEC * 2;
 }
 
-int bch2_ratelimit_wait_freezable_stoppable(struct bch_ratelimit *d)
-{
-       bool kthread = (current->flags & PF_KTHREAD) != 0;
-
-       while (1) {
-               u64 delay = bch2_ratelimit_delay(d);
-
-               if (delay)
-                       set_current_state(TASK_INTERRUPTIBLE);
-
-               if (kthread && kthread_should_stop())
-                       return 1;
-
-               if (!delay)
-                       return 0;
-
-               schedule_timeout(delay);
-               try_to_freeze();
-       }
-}
-
 /* pd controller: */
 
 /*
@@ -506,80 +735,79 @@ void bch2_pd_controller_init(struct bch_pd_controller *pd)
        pd->backpressure        = 1;
 }
 
-size_t bch2_pd_controller_print_debug(struct bch_pd_controller *pd, char *buf)
+void bch2_pd_controller_debug_to_text(struct printbuf *out, struct bch_pd_controller *pd)
 {
-       /* 2^64 - 1 is 20 digits, plus null byte */
-       char rate[21];
-       char actual[21];
-       char target[21];
-       char proportional[21];
-       char derivative[21];
-       char change[21];
-       s64 next_io;
-
-       bch2_hprint(rate,       pd->rate.rate);
-       bch2_hprint(actual,     pd->last_actual);
-       bch2_hprint(target,     pd->last_target);
-       bch2_hprint(proportional, pd->last_proportional);
-       bch2_hprint(derivative, pd->last_derivative);
-       bch2_hprint(change,     pd->last_change);
-
-       next_io = div64_s64(pd->rate.next - local_clock(), NSEC_PER_MSEC);
-
-       return sprintf(buf,
-                      "rate:\t\t%s/sec\n"
-                      "target:\t\t%s\n"
-                      "actual:\t\t%s\n"
-                      "proportional:\t%s\n"
-                      "derivative:\t%s\n"
-                      "change:\t\t%s/sec\n"
-                      "next io:\t%llims\n",
-                      rate, target, actual, proportional,
-                      derivative, change, next_io);
+       if (!out->nr_tabstops)
+               printbuf_tabstop_push(out, 20);
+
+       prt_printf(out, "rate:");
+       prt_tab(out);
+       prt_human_readable_s64(out, pd->rate.rate);
+       prt_newline(out);
+
+       prt_printf(out, "target:");
+       prt_tab(out);
+       prt_human_readable_u64(out, pd->last_target);
+       prt_newline(out);
+
+       prt_printf(out, "actual:");
+       prt_tab(out);
+       prt_human_readable_u64(out, pd->last_actual);
+       prt_newline(out);
+
+       prt_printf(out, "proportional:");
+       prt_tab(out);
+       prt_human_readable_s64(out, pd->last_proportional);
+       prt_newline(out);
+
+       prt_printf(out, "derivative:");
+       prt_tab(out);
+       prt_human_readable_s64(out, pd->last_derivative);
+       prt_newline(out);
+
+       prt_printf(out, "change:");
+       prt_tab(out);
+       prt_human_readable_s64(out, pd->last_change);
+       prt_newline(out);
+
+       prt_printf(out, "next io:");
+       prt_tab(out);
+       prt_printf(out, "%llims", div64_s64(pd->rate.next - local_clock(), NSEC_PER_MSEC));
+       prt_newline(out);
 }
 
 /* misc: */
 
-void bch2_bio_map(struct bio *bio, void *base)
+void bch2_bio_map(struct bio *bio, void *base, size_t size)
 {
-       size_t size = bio->bi_iter.bi_size;
-       struct bio_vec *bv = bio->bi_io_vec;
-
-       BUG_ON(!bio->bi_iter.bi_size);
-       BUG_ON(bio->bi_vcnt);
-
-       bv->bv_offset = base ? offset_in_page(base) : 0;
-       goto start;
-
-       for (; size; bio->bi_vcnt++, bv++) {
-               bv->bv_offset   = 0;
-start:         bv->bv_len      = min_t(size_t, PAGE_SIZE - bv->bv_offset,
-                                       size);
-               BUG_ON(bio->bi_vcnt >= bio->bi_max_vecs);
-               if (base) {
-                       bv->bv_page = is_vmalloc_addr(base)
+       while (size) {
+               struct page *page = is_vmalloc_addr(base)
                                ? vmalloc_to_page(base)
                                : virt_to_page(base);
+               unsigned offset = offset_in_page(base);
+               unsigned len = min_t(size_t, PAGE_SIZE - offset, size);
 
-                       base += bv->bv_len;
-               }
-
-               size -= bv->bv_len;
+               BUG_ON(!bio_add_page(bio, page, len, offset));
+               size -= len;
+               base += len;
        }
 }
 
-int bch2_bio_alloc_pages(struct bio *bio, gfp_t gfp_mask)
+int bch2_bio_alloc_pages(struct bio *bio, size_t size, gfp_t gfp_mask)
 {
-       int i;
-       struct bio_vec *bv;
+       while (size) {
+               struct page *page = alloc_pages(gfp_mask, 0);
+               unsigned len = min_t(size_t, PAGE_SIZE, size);
 
-       bio_for_each_segment_all(bv, bio, i) {
-               bv->bv_page = alloc_page(gfp_mask);
-               if (!bv->bv_page) {
-                       while (--bv >= bio->bi_io_vec)
-                               __free_page(bv->bv_page);
+               if (!page)
                        return -ENOMEM;
+
+               if (unlikely(!bio_add_page(bio, page, len, 0))) {
+                       __free_page(page);
+                       break;
                }
+
+               size -= len;
        }
 
        return 0;
@@ -600,15 +828,16 @@ size_t bch2_rand_range(size_t max)
        return rand;
 }
 
-void memcpy_to_bio(struct bio *dst, struct bvec_iter dst_iter, void *src)
+void memcpy_to_bio(struct bio *dst, struct bvec_iter dst_iter, const void *src)
 {
        struct bio_vec bv;
        struct bvec_iter iter;
 
        __bio_for_each_segment(bv, dst, iter, dst_iter) {
-               void *dstp = kmap_atomic(bv.bv_page);
+               void *dstp = kmap_local_page(bv.bv_page);
+
                memcpy(dstp + bv.bv_offset, src, bv.bv_len);
-               kunmap_atomic(dstp);
+               kunmap_local(dstp);
 
                src += bv.bv_len;
        }
@@ -620,30 +849,15 @@ void memcpy_from_bio(void *dst, struct bio *src, struct bvec_iter src_iter)
        struct bvec_iter iter;
 
        __bio_for_each_segment(bv, src, iter, src_iter) {
-               void *srcp = kmap_atomic(bv.bv_page);
+               void *srcp = kmap_local_page(bv.bv_page);
+
                memcpy(dst, srcp + bv.bv_offset, bv.bv_len);
-               kunmap_atomic(srcp);
+               kunmap_local(srcp);
 
                dst += bv.bv_len;
        }
 }
 
-size_t bch_scnmemcpy(char *buf, size_t size, const char *src, size_t len)
-{
-       size_t n;
-
-       if (!size)
-               return 0;
-
-       n = min(size - 1, len);
-       memcpy(buf, src, n);
-       buf[n] = '\0';
-
-       return n;
-}
-
-#include "eytzinger.h"
-
 static int alignment_ok(const void *base, size_t align)
 {
        return IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) ||
@@ -934,3 +1148,63 @@ void eytzinger0_find_test(void)
        kfree(test_array);
 }
 #endif
+
+/*
+ * Accumulate percpu counters onto one cpu's copy - only valid when access
+ * against any percpu counter is guarded against
+ */
+u64 *bch2_acc_percpu_u64s(u64 __percpu *p, unsigned nr)
+{
+       u64 *ret;
+       int cpu;
+
+       /* access to pcpu vars has to be blocked by other locking */
+       preempt_disable();
+       ret = this_cpu_ptr(p);
+       preempt_enable();
+
+       for_each_possible_cpu(cpu) {
+               u64 *i = per_cpu_ptr(p, cpu);
+
+               if (i != ret) {
+                       acc_u64s(ret, i, nr);
+                       memset(i, 0, nr * sizeof(u64));
+               }
+       }
+
+       return ret;
+}
+
+void bch2_darray_str_exit(darray_str *d)
+{
+       darray_for_each(*d, i)
+               kfree(*i);
+       darray_exit(d);
+}
+
+int bch2_split_devs(const char *_dev_name, darray_str *ret)
+{
+       darray_init(ret);
+
+       char *dev_name = kstrdup(_dev_name, GFP_KERNEL), *s = dev_name;
+       if (!dev_name)
+               return -ENOMEM;
+
+       while ((s = strsep(&dev_name, ":"))) {
+               char *p = kstrdup(s, GFP_KERNEL);
+               if (!p)
+                       goto err;
+
+               if (darray_push(ret, p)) {
+                       kfree(p);
+                       goto err;
+               }
+       }
+
+       kfree(dev_name);
+       return 0;
+err:
+       bch2_darray_str_exit(ret);
+       kfree(dev_name);
+       return -ENOMEM;
+}