xref: /linux/fs/bcachefs/util.c (revision b74710eaff314d6afe4fb0bbe9bc7657bf226fd4)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * random utility 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 > div64_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 > div64_u64(U64_MAX, b))
144 		return -ERANGE;
145 	v *= b;
146 
147 	if (f_n > div64_u64(U64_MAX, b))
148 		return -ERANGE;
149 
150 	f_n = div64_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(const 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 |= BIT_ULL(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_base2_nbits(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_prt_u64_base2(struct printbuf *out, u64 v)
251 {
252 	bch2_prt_u64_base2_nbits(out, v, fls64(v) ?: 1);
253 }
254 
255 static bool string_is_spaces(const char *str)
256 {
257 	while (*str) {
258 		if (*str != ' ')
259 			return false;
260 		str++;
261 	}
262 	return true;
263 }
264 
265 void bch2_print_string_as_lines(const char *prefix, const char *lines,
266 				bool nonblocking)
267 {
268 	bool locked = false;
269 	const char *p;
270 
271 	if (!lines) {
272 		printk("%s (null)\n", prefix);
273 		return;
274 	}
275 
276 	if (!nonblocking) {
277 		console_lock();
278 		locked = true;
279 	} else {
280 		locked = console_trylock();
281 	}
282 
283 	while (*lines) {
284 		p = strchrnul(lines, '\n');
285 		if (!*p && string_is_spaces(lines))
286 			break;
287 
288 		printk("%s%.*s\n", prefix, (int) (p - lines), lines);
289 		if (!*p)
290 			break;
291 		lines = p + 1;
292 	}
293 	if (locked)
294 		console_unlock();
295 }
296 
297 int bch2_save_backtrace(bch_stacktrace *stack, struct task_struct *task, unsigned skipnr,
298 			gfp_t gfp)
299 {
300 #ifdef CONFIG_STACKTRACE
301 	unsigned nr_entries = 0;
302 
303 	stack->nr = 0;
304 	int ret = darray_make_room_gfp(stack, 32, gfp);
305 	if (ret)
306 		return ret;
307 
308 	if (!down_read_trylock(&task->signal->exec_update_lock))
309 		return -1;
310 
311 	do {
312 		nr_entries = stack_trace_save_tsk(task, stack->data, stack->size, skipnr + 1);
313 	} while (nr_entries == stack->size &&
314 		 !(ret = darray_make_room_gfp(stack, stack->size * 2, gfp)));
315 
316 	stack->nr = nr_entries;
317 	up_read(&task->signal->exec_update_lock);
318 
319 	return ret;
320 #else
321 	return 0;
322 #endif
323 }
324 
325 void bch2_prt_backtrace(struct printbuf *out, bch_stacktrace *stack)
326 {
327 	darray_for_each(*stack, i) {
328 		prt_printf(out, "[<0>] %pB", (void *) *i);
329 		prt_newline(out);
330 	}
331 }
332 
333 int bch2_prt_task_backtrace(struct printbuf *out, struct task_struct *task, unsigned skipnr, gfp_t gfp)
334 {
335 	bch_stacktrace stack = { 0 };
336 	int ret = bch2_save_backtrace(&stack, task, skipnr + 1, gfp);
337 
338 	bch2_prt_backtrace(out, &stack);
339 	darray_exit(&stack);
340 	return ret;
341 }
342 
343 #ifndef __KERNEL__
344 #include <time.h>
345 void bch2_prt_datetime(struct printbuf *out, time64_t sec)
346 {
347 	time_t t = sec;
348 	char buf[64];
349 	ctime_r(&t, buf);
350 	strim(buf);
351 	prt_str(out, buf);
352 }
353 #else
354 void bch2_prt_datetime(struct printbuf *out, time64_t sec)
355 {
356 	char buf[64];
357 	snprintf(buf, sizeof(buf), "%ptT", &sec);
358 	prt_u64(out, sec);
359 }
360 #endif
361 
362 void bch2_pr_time_units(struct printbuf *out, u64 ns)
363 {
364 	const struct time_unit *u = bch2_pick_time_units(ns);
365 
366 	prt_printf(out, "%llu %s", div64_u64(ns, u->nsecs), u->name);
367 }
368 
369 static void bch2_pr_time_units_aligned(struct printbuf *out, u64 ns)
370 {
371 	const struct time_unit *u = bch2_pick_time_units(ns);
372 
373 	prt_printf(out, "%llu \r%s", div64_u64(ns, u->nsecs), u->name);
374 }
375 
376 static inline void pr_name_and_units(struct printbuf *out, const char *name, u64 ns)
377 {
378 	prt_printf(out, "%s\t", name);
379 	bch2_pr_time_units_aligned(out, ns);
380 	prt_newline(out);
381 }
382 
383 #define TABSTOP_SIZE 12
384 
385 void bch2_time_stats_to_text(struct printbuf *out, struct bch2_time_stats *stats)
386 {
387 	struct quantiles *quantiles = time_stats_to_quantiles(stats);
388 	s64 f_mean = 0, d_mean = 0;
389 	u64 f_stddev = 0, d_stddev = 0;
390 
391 	if (stats->buffer) {
392 		int cpu;
393 
394 		spin_lock_irq(&stats->lock);
395 		for_each_possible_cpu(cpu)
396 			__bch2_time_stats_clear_buffer(stats, per_cpu_ptr(stats->buffer, cpu));
397 		spin_unlock_irq(&stats->lock);
398 	}
399 
400 	/*
401 	 * avoid divide by zero
402 	 */
403 	if (stats->freq_stats.n) {
404 		f_mean = mean_and_variance_get_mean(stats->freq_stats);
405 		f_stddev = mean_and_variance_get_stddev(stats->freq_stats);
406 		d_mean = mean_and_variance_get_mean(stats->duration_stats);
407 		d_stddev = mean_and_variance_get_stddev(stats->duration_stats);
408 	}
409 
410 	printbuf_tabstop_push(out, out->indent + TABSTOP_SIZE);
411 	prt_printf(out, "count:\t%llu\n", stats->duration_stats.n);
412 	printbuf_tabstop_pop(out);
413 
414 	printbuf_tabstops_reset(out);
415 
416 	printbuf_tabstop_push(out, out->indent + 20);
417 	printbuf_tabstop_push(out, TABSTOP_SIZE + 2);
418 	printbuf_tabstop_push(out, 0);
419 	printbuf_tabstop_push(out, TABSTOP_SIZE + 2);
420 
421 	prt_printf(out, "\tsince mount\r\trecent\r\n");
422 
423 	printbuf_tabstops_reset(out);
424 	printbuf_tabstop_push(out, out->indent + 20);
425 	printbuf_tabstop_push(out, TABSTOP_SIZE);
426 	printbuf_tabstop_push(out, 2);
427 	printbuf_tabstop_push(out, TABSTOP_SIZE);
428 
429 	prt_printf(out, "duration of events\n");
430 	printbuf_indent_add(out, 2);
431 
432 	pr_name_and_units(out, "min:", stats->min_duration);
433 	pr_name_and_units(out, "max:", stats->max_duration);
434 	pr_name_and_units(out, "total:", stats->total_duration);
435 
436 	prt_printf(out, "mean:\t");
437 	bch2_pr_time_units_aligned(out, d_mean);
438 	prt_tab(out);
439 	bch2_pr_time_units_aligned(out, mean_and_variance_weighted_get_mean(stats->duration_stats_weighted, TIME_STATS_MV_WEIGHT));
440 	prt_newline(out);
441 
442 	prt_printf(out, "stddev:\t");
443 	bch2_pr_time_units_aligned(out, d_stddev);
444 	prt_tab(out);
445 	bch2_pr_time_units_aligned(out, mean_and_variance_weighted_get_stddev(stats->duration_stats_weighted, TIME_STATS_MV_WEIGHT));
446 
447 	printbuf_indent_sub(out, 2);
448 	prt_newline(out);
449 
450 	prt_printf(out, "time between events\n");
451 	printbuf_indent_add(out, 2);
452 
453 	pr_name_and_units(out, "min:", stats->min_freq);
454 	pr_name_and_units(out, "max:", stats->max_freq);
455 
456 	prt_printf(out, "mean:\t");
457 	bch2_pr_time_units_aligned(out, f_mean);
458 	prt_tab(out);
459 	bch2_pr_time_units_aligned(out, mean_and_variance_weighted_get_mean(stats->freq_stats_weighted, TIME_STATS_MV_WEIGHT));
460 	prt_newline(out);
461 
462 	prt_printf(out, "stddev:\t");
463 	bch2_pr_time_units_aligned(out, f_stddev);
464 	prt_tab(out);
465 	bch2_pr_time_units_aligned(out, mean_and_variance_weighted_get_stddev(stats->freq_stats_weighted, TIME_STATS_MV_WEIGHT));
466 
467 	printbuf_indent_sub(out, 2);
468 	prt_newline(out);
469 
470 	printbuf_tabstops_reset(out);
471 
472 	if (quantiles) {
473 		int i = eytzinger0_first(NR_QUANTILES);
474 		const struct time_unit *u =
475 			bch2_pick_time_units(quantiles->entries[i].m);
476 		u64 last_q = 0;
477 
478 		prt_printf(out, "quantiles (%s):\t", u->name);
479 		eytzinger0_for_each(j, NR_QUANTILES) {
480 			bool is_last = eytzinger0_next(j, NR_QUANTILES) == -1;
481 
482 			u64 q = max(quantiles->entries[j].m, last_q);
483 			prt_printf(out, "%llu ", div64_u64(q, u->nsecs));
484 			if (is_last)
485 				prt_newline(out);
486 			last_q = q;
487 		}
488 	}
489 }
490 
491 /* ratelimit: */
492 
493 /**
494  * bch2_ratelimit_delay() - return how long to delay until the next time to do
495  *		some work
496  * @d:		the struct bch_ratelimit to update
497  * Returns:	the amount of time to delay by, in jiffies
498  */
499 u64 bch2_ratelimit_delay(struct bch_ratelimit *d)
500 {
501 	u64 now = local_clock();
502 
503 	return time_after64(d->next, now)
504 		? nsecs_to_jiffies(d->next - now)
505 		: 0;
506 }
507 
508 /**
509  * bch2_ratelimit_increment() - increment @d by the amount of work done
510  * @d:		the struct bch_ratelimit to update
511  * @done:	the amount of work done, in arbitrary units
512  */
513 void bch2_ratelimit_increment(struct bch_ratelimit *d, u64 done)
514 {
515 	u64 now = local_clock();
516 
517 	d->next += div_u64(done * NSEC_PER_SEC, d->rate);
518 
519 	if (time_before64(now + NSEC_PER_SEC, d->next))
520 		d->next = now + NSEC_PER_SEC;
521 
522 	if (time_after64(now - NSEC_PER_SEC * 2, d->next))
523 		d->next = now - NSEC_PER_SEC * 2;
524 }
525 
526 /* pd controller: */
527 
528 /*
529  * Updates pd_controller. Attempts to scale inputed values to units per second.
530  * @target: desired value
531  * @actual: current value
532  *
533  * @sign: 1 or -1; 1 if increasing the rate makes actual go up, -1 if increasing
534  * it makes actual go down.
535  */
536 void bch2_pd_controller_update(struct bch_pd_controller *pd,
537 			      s64 target, s64 actual, int sign)
538 {
539 	s64 proportional, derivative, change;
540 
541 	unsigned long seconds_since_update = (jiffies - pd->last_update) / HZ;
542 
543 	if (seconds_since_update == 0)
544 		return;
545 
546 	pd->last_update = jiffies;
547 
548 	proportional = actual - target;
549 	proportional *= seconds_since_update;
550 	proportional = div_s64(proportional, pd->p_term_inverse);
551 
552 	derivative = actual - pd->last_actual;
553 	derivative = div_s64(derivative, seconds_since_update);
554 	derivative = ewma_add(pd->smoothed_derivative, derivative,
555 			      (pd->d_term / seconds_since_update) ?: 1);
556 	derivative = derivative * pd->d_term;
557 	derivative = div_s64(derivative, pd->p_term_inverse);
558 
559 	change = proportional + derivative;
560 
561 	/* Don't increase rate if not keeping up */
562 	if (change > 0 &&
563 	    pd->backpressure &&
564 	    time_after64(local_clock(),
565 			 pd->rate.next + NSEC_PER_MSEC))
566 		change = 0;
567 
568 	change *= (sign * -1);
569 
570 	pd->rate.rate = clamp_t(s64, (s64) pd->rate.rate + change,
571 				1, UINT_MAX);
572 
573 	pd->last_actual		= actual;
574 	pd->last_derivative	= derivative;
575 	pd->last_proportional	= proportional;
576 	pd->last_change		= change;
577 	pd->last_target		= target;
578 }
579 
580 void bch2_pd_controller_init(struct bch_pd_controller *pd)
581 {
582 	pd->rate.rate		= 1024;
583 	pd->last_update		= jiffies;
584 	pd->p_term_inverse	= 6000;
585 	pd->d_term		= 30;
586 	pd->d_smooth		= pd->d_term;
587 	pd->backpressure	= 1;
588 }
589 
590 void bch2_pd_controller_debug_to_text(struct printbuf *out, struct bch_pd_controller *pd)
591 {
592 	if (!out->nr_tabstops)
593 		printbuf_tabstop_push(out, 20);
594 
595 	prt_printf(out, "rate:\t");
596 	prt_human_readable_s64(out, pd->rate.rate);
597 	prt_newline(out);
598 
599 	prt_printf(out, "target:\t");
600 	prt_human_readable_u64(out, pd->last_target);
601 	prt_newline(out);
602 
603 	prt_printf(out, "actual:\t");
604 	prt_human_readable_u64(out, pd->last_actual);
605 	prt_newline(out);
606 
607 	prt_printf(out, "proportional:\t");
608 	prt_human_readable_s64(out, pd->last_proportional);
609 	prt_newline(out);
610 
611 	prt_printf(out, "derivative:\t");
612 	prt_human_readable_s64(out, pd->last_derivative);
613 	prt_newline(out);
614 
615 	prt_printf(out, "change:\t");
616 	prt_human_readable_s64(out, pd->last_change);
617 	prt_newline(out);
618 
619 	prt_printf(out, "next io:\t%llims\n", div64_s64(pd->rate.next - local_clock(), NSEC_PER_MSEC));
620 }
621 
622 /* misc: */
623 
624 void bch2_bio_map(struct bio *bio, void *base, size_t size)
625 {
626 	while (size) {
627 		struct page *page = is_vmalloc_addr(base)
628 				? vmalloc_to_page(base)
629 				: virt_to_page(base);
630 		unsigned offset = offset_in_page(base);
631 		unsigned len = min_t(size_t, PAGE_SIZE - offset, size);
632 
633 		BUG_ON(!bio_add_page(bio, page, len, offset));
634 		size -= len;
635 		base += len;
636 	}
637 }
638 
639 int bch2_bio_alloc_pages(struct bio *bio, size_t size, gfp_t gfp_mask)
640 {
641 	while (size) {
642 		struct page *page = alloc_pages(gfp_mask, 0);
643 		unsigned len = min_t(size_t, PAGE_SIZE, size);
644 
645 		if (!page)
646 			return -ENOMEM;
647 
648 		if (unlikely(!bio_add_page(bio, page, len, 0))) {
649 			__free_page(page);
650 			break;
651 		}
652 
653 		size -= len;
654 	}
655 
656 	return 0;
657 }
658 
659 u64 bch2_get_random_u64_below(u64 ceil)
660 {
661 	if (ceil <= U32_MAX)
662 		return __get_random_u32_below(ceil);
663 
664 	/* this is the same (clever) algorithm as in __get_random_u32_below() */
665 	u64 rand = get_random_u64();
666 	u64 mult = ceil * rand;
667 
668 	if (unlikely(mult < ceil)) {
669 		u64 bound;
670 		div64_u64_rem(-ceil, ceil, &bound);
671 		while (unlikely(mult < bound)) {
672 			rand = get_random_u64();
673 			mult = ceil * rand;
674 		}
675 	}
676 
677 	return mul_u64_u64_shr(ceil, rand, 64);
678 }
679 
680 void memcpy_to_bio(struct bio *dst, struct bvec_iter dst_iter, const void *src)
681 {
682 	struct bio_vec bv;
683 	struct bvec_iter iter;
684 
685 	__bio_for_each_segment(bv, dst, iter, dst_iter) {
686 		void *dstp = kmap_local_page(bv.bv_page);
687 
688 		memcpy(dstp + bv.bv_offset, src, bv.bv_len);
689 		kunmap_local(dstp);
690 
691 		src += bv.bv_len;
692 	}
693 }
694 
695 void memcpy_from_bio(void *dst, struct bio *src, struct bvec_iter src_iter)
696 {
697 	struct bio_vec bv;
698 	struct bvec_iter iter;
699 
700 	__bio_for_each_segment(bv, src, iter, src_iter) {
701 		void *srcp = kmap_local_page(bv.bv_page);
702 
703 		memcpy(dst, srcp + bv.bv_offset, bv.bv_len);
704 		kunmap_local(srcp);
705 
706 		dst += bv.bv_len;
707 	}
708 }
709 
710 #ifdef CONFIG_BCACHEFS_DEBUG
711 void bch2_corrupt_bio(struct bio *bio)
712 {
713 	struct bvec_iter iter;
714 	struct bio_vec bv;
715 	unsigned offset = get_random_u32_below(bio->bi_iter.bi_size / sizeof(u64));
716 
717 	bio_for_each_segment(bv, bio, iter) {
718 		unsigned u64s = bv.bv_len / sizeof(u64);
719 
720 		if (offset < u64s) {
721 			u64 *segment = bvec_kmap_local(&bv);
722 			segment[offset] = get_random_u64();
723 			kunmap_local(segment);
724 			return;
725 		}
726 		offset -= u64s;
727 	}
728 }
729 #endif
730 
731 void bch2_bio_to_text(struct printbuf *out, struct bio *bio)
732 {
733 	prt_printf(out, "bi_remaining:\t%u\n",
734 		   atomic_read(&bio->__bi_remaining));
735 	prt_printf(out, "bi_end_io:\t%ps\n",
736 		   bio->bi_end_io);
737 	prt_printf(out, "bi_status:\t%u\n",
738 		   bio->bi_status);
739 }
740 
741 #if 0
742 void eytzinger1_test(void)
743 {
744 	unsigned inorder, size;
745 
746 	pr_info("1 based eytzinger test:\n");
747 
748 	for (size = 2;
749 	     size < 65536;
750 	     size++) {
751 		unsigned extra = eytzinger1_extra(size);
752 
753 		if (!(size % 4096))
754 			pr_info("tree size %u\n", size);
755 
756 		inorder = 1;
757 		eytzinger1_for_each(eytz, size) {
758 			BUG_ON(__inorder_to_eytzinger1(inorder, size, extra) != eytz);
759 			BUG_ON(__eytzinger1_to_inorder(eytz, size, extra) != inorder);
760 			BUG_ON(eytz != eytzinger1_last(size) &&
761 			       eytzinger1_prev(eytzinger1_next(eytz, size), size) != eytz);
762 
763 			inorder++;
764 		}
765 		BUG_ON(inorder - 1 != size);
766 	}
767 }
768 
769 void eytzinger0_test(void)
770 {
771 
772 	unsigned inorder, size;
773 
774 	pr_info("0 based eytzinger test:\n");
775 
776 	for (size = 1;
777 	     size < 65536;
778 	     size++) {
779 		unsigned extra = eytzinger0_extra(size);
780 
781 		if (!(size % 4096))
782 			pr_info("tree size %u\n", size);
783 
784 		inorder = 0;
785 		eytzinger0_for_each(eytz, size) {
786 			BUG_ON(__inorder_to_eytzinger0(inorder, size, extra) != eytz);
787 			BUG_ON(__eytzinger0_to_inorder(eytz, size, extra) != inorder);
788 			BUG_ON(eytz != eytzinger0_last(size) &&
789 			       eytzinger0_prev(eytzinger0_next(eytz, size), size) != eytz);
790 
791 			inorder++;
792 		}
793 		BUG_ON(inorder != size);
794 
795 		inorder = size - 1;
796 		eytzinger0_for_each_prev(eytz, size) {
797 			BUG_ON(eytz != eytzinger0_first(size) &&
798 			       eytzinger0_next(eytzinger0_prev(eytz, size), size) != eytz);
799 
800 			inorder--;
801 		}
802 		BUG_ON(inorder != -1);
803 	}
804 }
805 
806 static inline int cmp_u16(const void *_l, const void *_r)
807 {
808 	const u16 *l = _l, *r = _r;
809 
810 	return (*l > *r) - (*r > *l);
811 }
812 
813 static void eytzinger0_find_test_le(u16 *test_array, unsigned nr, u16 search)
814 {
815 	int r, s;
816 	bool bad;
817 
818 	r = eytzinger0_find_le(test_array, nr,
819 			       sizeof(test_array[0]),
820 			       cmp_u16, &search);
821 	if (r >= 0) {
822 		if (test_array[r] > search) {
823 			bad = true;
824 		} else {
825 			s = eytzinger0_next(r, nr);
826 			bad = s >= 0 && test_array[s] <= search;
827 		}
828 	} else {
829 		s = eytzinger0_last(nr);
830 		bad = s >= 0 && test_array[s] <= search;
831 	}
832 
833 	if (bad) {
834 		s = -1;
835 		eytzinger0_for_each_prev(j, nr) {
836 			if (test_array[j] <= search) {
837 				s = j;
838 				break;
839 			}
840 		}
841 
842 		eytzinger0_for_each(j, nr)
843 			pr_info("[%3u] = %12u\n", j, test_array[j]);
844 		pr_info("find_le(%12u) = %3i should be %3i\n",
845 			search, r, s);
846 		BUG();
847 	}
848 }
849 
850 static void eytzinger0_find_test_gt(u16 *test_array, unsigned nr, u16 search)
851 {
852 	int r, s;
853 	bool bad;
854 
855 	r = eytzinger0_find_gt(test_array, nr,
856 			       sizeof(test_array[0]),
857 			       cmp_u16, &search);
858 	if (r >= 0) {
859 		if (test_array[r] <= search) {
860 			bad = true;
861 		} else {
862 			s = eytzinger0_prev(r, nr);
863 			bad = s >= 0 && test_array[s] > search;
864 		}
865 	} else {
866 		s = eytzinger0_first(nr);
867 		bad = s >= 0 && test_array[s] > search;
868 	}
869 
870 	if (bad) {
871 		s = -1;
872 		eytzinger0_for_each(j, nr) {
873 			if (test_array[j] > search) {
874 				s = j;
875 				break;
876 			}
877 		}
878 
879 		eytzinger0_for_each(j, nr)
880 			pr_info("[%3u] = %12u\n", j, test_array[j]);
881 		pr_info("find_gt(%12u) = %3i should be %3i\n",
882 			search, r, s);
883 		BUG();
884 	}
885 }
886 
887 static void eytzinger0_find_test_ge(u16 *test_array, unsigned nr, u16 search)
888 {
889 	int r, s;
890 	bool bad;
891 
892 	r = eytzinger0_find_ge(test_array, nr,
893 			       sizeof(test_array[0]),
894 			       cmp_u16, &search);
895 	if (r >= 0) {
896 		if (test_array[r] < search) {
897 			bad = true;
898 		} else {
899 			s = eytzinger0_prev(r, nr);
900 			bad = s >= 0 && test_array[s] >= search;
901 		}
902 	} else {
903 		s = eytzinger0_first(nr);
904 		bad = s >= 0 && test_array[s] >= search;
905 	}
906 
907 	if (bad) {
908 		s = -1;
909 		eytzinger0_for_each(j, nr) {
910 			if (test_array[j] >= search) {
911 				s = j;
912 				break;
913 			}
914 		}
915 
916 		eytzinger0_for_each(j, nr)
917 			pr_info("[%3u] = %12u\n", j, test_array[j]);
918 		pr_info("find_ge(%12u) = %3i should be %3i\n",
919 			search, r, s);
920 		BUG();
921 	}
922 }
923 
924 static void eytzinger0_find_test_eq(u16 *test_array, unsigned nr, u16 search)
925 {
926 	unsigned r;
927 	int s;
928 	bool bad;
929 
930 	r = eytzinger0_find(test_array, nr,
931 			    sizeof(test_array[0]),
932 			    cmp_u16, &search);
933 
934 	if (r < nr) {
935 		bad = test_array[r] != search;
936 	} else {
937 		s = eytzinger0_find_le(test_array, nr,
938 				       sizeof(test_array[0]),
939 				       cmp_u16, &search);
940 		bad = s >= 0 && test_array[s] == search;
941 	}
942 
943 	if (bad) {
944 		eytzinger0_for_each(j, nr)
945 			pr_info("[%3u] = %12u\n", j, test_array[j]);
946 		pr_info("find(%12u) = %3i is incorrect\n",
947 			search, r);
948 		BUG();
949 	}
950 }
951 
952 static void eytzinger0_find_test_val(u16 *test_array, unsigned nr, u16 search)
953 {
954 	eytzinger0_find_test_le(test_array, nr, search);
955 	eytzinger0_find_test_gt(test_array, nr, search);
956 	eytzinger0_find_test_ge(test_array, nr, search);
957 	eytzinger0_find_test_eq(test_array, nr, search);
958 }
959 
960 void eytzinger0_find_test(void)
961 {
962 	unsigned i, nr, allocated = 1 << 12;
963 	u16 *test_array = kmalloc_array(allocated, sizeof(test_array[0]), GFP_KERNEL);
964 
965 	for (nr = 1; nr < allocated; nr++) {
966 		u16 prev = 0;
967 
968 		pr_info("testing %u elems\n", nr);
969 
970 		get_random_bytes(test_array, nr * sizeof(test_array[0]));
971 		eytzinger0_sort(test_array, nr, sizeof(test_array[0]), cmp_u16, NULL);
972 
973 		/* verify array is sorted correctly: */
974 		eytzinger0_for_each(j, nr) {
975 			BUG_ON(test_array[j] < prev);
976 			prev = test_array[j];
977 		}
978 
979 		for (i = 0; i < U16_MAX; i += 1 << 12)
980 			eytzinger0_find_test_val(test_array, nr, i);
981 
982 		for (i = 0; i < nr; i++) {
983 			eytzinger0_find_test_val(test_array, nr, test_array[i] - 1);
984 			eytzinger0_find_test_val(test_array, nr, test_array[i]);
985 			eytzinger0_find_test_val(test_array, nr, test_array[i] + 1);
986 		}
987 	}
988 
989 	kfree(test_array);
990 }
991 #endif
992 
993 /*
994  * Accumulate percpu counters onto one cpu's copy - only valid when access
995  * against any percpu counter is guarded against
996  */
997 u64 *bch2_acc_percpu_u64s(u64 __percpu *p, unsigned nr)
998 {
999 	u64 *ret;
1000 	int cpu;
1001 
1002 	/* access to pcpu vars has to be blocked by other locking */
1003 	preempt_disable();
1004 	ret = this_cpu_ptr(p);
1005 	preempt_enable();
1006 
1007 	for_each_possible_cpu(cpu) {
1008 		u64 *i = per_cpu_ptr(p, cpu);
1009 
1010 		if (i != ret) {
1011 			acc_u64s(ret, i, nr);
1012 			memset(i, 0, nr * sizeof(u64));
1013 		}
1014 	}
1015 
1016 	return ret;
1017 }
1018 
1019 void bch2_darray_str_exit(darray_const_str *d)
1020 {
1021 	darray_for_each(*d, i)
1022 		kfree(*i);
1023 	darray_exit(d);
1024 }
1025 
1026 int bch2_split_devs(const char *_dev_name, darray_const_str *ret)
1027 {
1028 	darray_init(ret);
1029 
1030 	char *dev_name, *s, *orig;
1031 
1032 	dev_name = orig = kstrdup(_dev_name, GFP_KERNEL);
1033 	if (!dev_name)
1034 		return -ENOMEM;
1035 
1036 	while ((s = strsep(&dev_name, ":"))) {
1037 		char *p = kstrdup(s, GFP_KERNEL);
1038 		if (!p)
1039 			goto err;
1040 
1041 		if (darray_push(ret, p)) {
1042 			kfree(p);
1043 			goto err;
1044 		}
1045 	}
1046 
1047 	kfree(orig);
1048 	return 0;
1049 err:
1050 	bch2_darray_str_exit(ret);
1051 	kfree(orig);
1052 	return -ENOMEM;
1053 }
1054