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