1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _BCACHEFS_UTIL_H
3 #define _BCACHEFS_UTIL_H
6 #include <linux/blkdev.h>
7 #include <linux/closure.h>
8 #include <linux/errno.h>
9 #include <linux/freezer.h>
10 #include <linux/kernel.h>
11 #include <linux/sched/clock.h>
12 #include <linux/llist.h>
13 #include <linux/log2.h>
14 #include <linux/percpu.h>
15 #include <linux/preempt.h>
16 #include <linux/ratelimit.h>
17 #include <linux/slab.h>
18 #include <linux/vmalloc.h>
19 #include <linux/workqueue.h>
20 #include <linux/mean_and_variance.h>
24 #ifdef CONFIG_BCACHEFS_DEBUG
25 #define EBUG_ON(cond) BUG_ON(cond)
30 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
31 #define CPU_BIG_ENDIAN 0
32 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
33 #define CPU_BIG_ENDIAN 1
38 #define type_is_exact(_val, _type) \
39 __builtin_types_compatible_p(typeof(_val), _type)
41 #define type_is(_val, _type) \
42 (__builtin_types_compatible_p(typeof(_val), _type) || \
43 __builtin_types_compatible_p(typeof(_val), const _type))
45 /* Userspace doesn't align allocations as nicely as the kernel allocators: */
46 static inline size_t buf_pages(void *p, size_t len)
48 return DIV_ROUND_UP(len +
49 ((unsigned long) p & (PAGE_SIZE - 1)),
53 static inline void vpfree(void *p, size_t size)
55 if (is_vmalloc_addr(p))
58 free_pages((unsigned long) p, get_order(size));
61 static inline void *vpmalloc(size_t size, gfp_t gfp_mask)
63 return (void *) __get_free_pages(gfp_mask|__GFP_NOWARN,
65 __vmalloc(size, gfp_mask);
68 static inline void kvpfree(void *p, size_t size)
76 static inline void *kvpmalloc(size_t size, gfp_t gfp_mask)
78 return size < PAGE_SIZE
79 ? kmalloc(size, gfp_mask)
80 : vpmalloc(size, gfp_mask);
83 int mempool_init_kvpmalloc_pool(mempool_t *, int, size_t);
91 #define DECLARE_HEAP(type, name) HEAP(type) name
93 #define init_heap(heap, _size, gfp) \
96 (heap)->size = (_size); \
97 (heap)->data = kvpmalloc((heap)->size * sizeof((heap)->data[0]),\
101 #define free_heap(heap) \
103 kvpfree((heap)->data, (heap)->size * sizeof((heap)->data[0])); \
104 (heap)->data = NULL; \
107 #define heap_set_backpointer(h, i, _fn) \
109 void (*fn)(typeof(h), size_t) = _fn; \
114 #define heap_swap(h, i, j, set_backpointer) \
116 swap((h)->data[i], (h)->data[j]); \
117 heap_set_backpointer(h, i, set_backpointer); \
118 heap_set_backpointer(h, j, set_backpointer); \
121 #define heap_peek(h) \
123 EBUG_ON(!(h)->used); \
127 #define heap_full(h) ((h)->used == (h)->size)
129 #define heap_sift_down(h, i, cmp, set_backpointer) \
133 for (; _j * 2 + 1 < (h)->used; _j = _c) { \
135 if (_c + 1 < (h)->used && \
136 cmp(h, (h)->data[_c], (h)->data[_c + 1]) >= 0) \
139 if (cmp(h, (h)->data[_c], (h)->data[_j]) >= 0) \
141 heap_swap(h, _c, _j, set_backpointer); \
145 #define heap_sift_up(h, i, cmp, set_backpointer) \
148 size_t p = (i - 1) / 2; \
149 if (cmp(h, (h)->data[i], (h)->data[p]) >= 0) \
151 heap_swap(h, i, p, set_backpointer); \
156 #define __heap_add(h, d, cmp, set_backpointer) \
158 size_t _i = (h)->used++; \
160 heap_set_backpointer(h, _i, set_backpointer); \
162 heap_sift_up(h, _i, cmp, set_backpointer); \
166 #define heap_add(h, d, cmp, set_backpointer) \
168 bool _r = !heap_full(h); \
170 __heap_add(h, d, cmp, set_backpointer); \
174 #define heap_add_or_replace(h, new, cmp, set_backpointer) \
176 if (!heap_add(h, new, cmp, set_backpointer) && \
177 cmp(h, new, heap_peek(h)) >= 0) { \
178 (h)->data[0] = new; \
179 heap_set_backpointer(h, 0, set_backpointer); \
180 heap_sift_down(h, 0, cmp, set_backpointer); \
184 #define heap_del(h, i, cmp, set_backpointer) \
188 BUG_ON(_i >= (h)->used); \
190 if ((_i) < (h)->used) { \
191 heap_swap(h, _i, (h)->used, set_backpointer); \
192 heap_sift_up(h, _i, cmp, set_backpointer); \
193 heap_sift_down(h, _i, cmp, set_backpointer); \
197 #define heap_pop(h, d, cmp, set_backpointer) \
199 bool _r = (h)->used; \
201 (d) = (h)->data[0]; \
202 heap_del(h, 0, cmp, set_backpointer); \
207 #define heap_resort(heap, cmp, set_backpointer) \
210 for (_i = (ssize_t) (heap)->used / 2 - 1; _i >= 0; --_i) \
211 heap_sift_down(heap, _i, cmp, set_backpointer); \
214 #define ANYSINT_MAX(t) \
215 ((((t) 1 << (sizeof(t) * 8 - 2)) - (t) 1) * (t) 2 + (t) 1)
217 #include "printbuf.h"
219 #define prt_vprintf(_out, ...) bch2_prt_vprintf(_out, __VA_ARGS__)
220 #define prt_printf(_out, ...) bch2_prt_printf(_out, __VA_ARGS__)
221 #define printbuf_str(_buf) bch2_printbuf_str(_buf)
222 #define printbuf_exit(_buf) bch2_printbuf_exit(_buf)
224 #define printbuf_tabstops_reset(_buf) bch2_printbuf_tabstops_reset(_buf)
225 #define printbuf_tabstop_pop(_buf) bch2_printbuf_tabstop_pop(_buf)
226 #define printbuf_tabstop_push(_buf, _n) bch2_printbuf_tabstop_push(_buf, _n)
228 #define printbuf_indent_add(_out, _n) bch2_printbuf_indent_add(_out, _n)
229 #define printbuf_indent_sub(_out, _n) bch2_printbuf_indent_sub(_out, _n)
231 #define prt_newline(_out) bch2_prt_newline(_out)
232 #define prt_tab(_out) bch2_prt_tab(_out)
233 #define prt_tab_rjust(_out) bch2_prt_tab_rjust(_out)
235 #define prt_bytes_indented(...) bch2_prt_bytes_indented(__VA_ARGS__)
236 #define prt_u64(_out, _v) prt_printf(_out, "%llu", _v)
237 #define prt_human_readable_u64(...) bch2_prt_human_readable_u64(__VA_ARGS__)
238 #define prt_human_readable_s64(...) bch2_prt_human_readable_s64(__VA_ARGS__)
239 #define prt_units_u64(...) bch2_prt_units_u64(__VA_ARGS__)
240 #define prt_units_s64(...) bch2_prt_units_s64(__VA_ARGS__)
241 #define prt_string_option(...) bch2_prt_string_option(__VA_ARGS__)
242 #define prt_bitflags(...) bch2_prt_bitflags(__VA_ARGS__)
244 void bch2_pr_time_units(struct printbuf *, u64);
247 static inline void pr_time(struct printbuf *out, u64 time)
249 prt_printf(out, "%llu", time);
253 static inline void pr_time(struct printbuf *out, u64 _time)
257 struct tm *tm = localtime(&time);
258 size_t err = strftime(time_str, sizeof(time_str), "%c", tm);
260 prt_printf(out, "(formatting error)");
262 prt_printf(out, "%s", time_str);
267 static inline void uuid_unparse_lower(u8 *uuid, char *out)
269 sprintf(out, "%pUb", uuid);
272 #include <uuid/uuid.h>
275 static inline void pr_uuid(struct printbuf *out, u8 *uuid)
279 uuid_unparse_lower(uuid, uuid_str);
280 prt_printf(out, "%s", uuid_str);
283 int bch2_strtoint_h(const char *, int *);
284 int bch2_strtouint_h(const char *, unsigned int *);
285 int bch2_strtoll_h(const char *, long long *);
286 int bch2_strtoull_h(const char *, unsigned long long *);
287 int bch2_strtou64_h(const char *, u64 *);
289 static inline int bch2_strtol_h(const char *cp, long *res)
291 #if BITS_PER_LONG == 32
292 return bch2_strtoint_h(cp, (int *) res);
294 return bch2_strtoll_h(cp, (long long *) res);
298 static inline int bch2_strtoul_h(const char *cp, long *res)
300 #if BITS_PER_LONG == 32
301 return bch2_strtouint_h(cp, (unsigned int *) res);
303 return bch2_strtoull_h(cp, (unsigned long long *) res);
307 #define strtoi_h(cp, res) \
308 ( type_is(*res, int) ? bch2_strtoint_h(cp, (void *) res)\
309 : type_is(*res, long) ? bch2_strtol_h(cp, (void *) res)\
310 : type_is(*res, long long) ? bch2_strtoll_h(cp, (void *) res)\
311 : type_is(*res, unsigned) ? bch2_strtouint_h(cp, (void *) res)\
312 : type_is(*res, unsigned long) ? bch2_strtoul_h(cp, (void *) res)\
313 : type_is(*res, unsigned long long) ? bch2_strtoull_h(cp, (void *) res)\
316 #define strtoul_safe(cp, var) \
319 int _r = kstrtoul(cp, 10, &_v); \
325 #define strtoul_safe_clamp(cp, var, min, max) \
328 int _r = kstrtoul(cp, 10, &_v); \
330 var = clamp_t(typeof(var), _v, min, max); \
334 #define strtoul_safe_restrict(cp, var, min, max) \
337 int _r = kstrtoul(cp, 10, &_v); \
338 if (!_r && _v >= min && _v <= max) \
345 #define snprint(out, var) \
347 type_is(var, int) ? "%i\n" \
348 : type_is(var, unsigned) ? "%u\n" \
349 : type_is(var, long) ? "%li\n" \
350 : type_is(var, unsigned long) ? "%lu\n" \
351 : type_is(var, s64) ? "%lli\n" \
352 : type_is(var, u64) ? "%llu\n" \
353 : type_is(var, char *) ? "%s\n" \
356 bool bch2_is_zero(const void *, size_t);
358 u64 bch2_read_flag_list(char *, const char * const[]);
360 void bch2_prt_u64_binary(struct printbuf *, u64, unsigned);
362 void bch2_print_string_as_lines(const char *prefix, const char *lines);
363 int bch2_prt_backtrace(struct printbuf *, struct task_struct *);
365 #define NR_QUANTILES 15
366 #define QUANTILE_IDX(i) inorder_to_eytzinger0(i, NR_QUANTILES)
367 #define QUANTILE_FIRST eytzinger0_first(NR_QUANTILES)
368 #define QUANTILE_LAST eytzinger0_last(NR_QUANTILES)
370 struct bch2_quantiles {
371 struct bch2_quantile_entry {
374 } entries[NR_QUANTILES];
377 struct bch2_time_stat_buffer {
379 struct bch2_time_stat_buffer_entry {
385 struct bch2_time_stats {
387 /* all fields are in nanoseconds */
393 struct bch2_quantiles quantiles;
395 struct mean_and_variance duration_stats;
396 struct mean_and_variance_weighted duration_stats_weighted;
397 struct mean_and_variance freq_stats;
398 struct mean_and_variance_weighted freq_stats_weighted;
399 struct bch2_time_stat_buffer __percpu *buffer;
402 #ifndef CONFIG_BCACHEFS_NO_LATENCY_ACCT
403 void __bch2_time_stats_update(struct bch2_time_stats *stats, u64, u64);
405 static inline void __bch2_time_stats_update(struct bch2_time_stats *stats, u64 start, u64 end) {}
408 static inline void bch2_time_stats_update(struct bch2_time_stats *stats, u64 start)
410 __bch2_time_stats_update(stats, start, local_clock());
413 void bch2_time_stats_to_text(struct printbuf *, struct bch2_time_stats *);
415 void bch2_time_stats_exit(struct bch2_time_stats *);
416 void bch2_time_stats_init(struct bch2_time_stats *);
418 #define ewma_add(ewma, val, weight) \
420 typeof(ewma) _ewma = (ewma); \
421 typeof(weight) _weight = (weight); \
423 (((_ewma << _weight) - _ewma) + (val)) >> _weight; \
426 struct bch_ratelimit {
427 /* Next time we want to do some work, in nanoseconds */
431 * Rate at which we want to do work, in units per nanosecond
432 * The units here correspond to the units passed to
433 * bch2_ratelimit_increment()
438 static inline void bch2_ratelimit_reset(struct bch_ratelimit *d)
440 d->next = local_clock();
443 u64 bch2_ratelimit_delay(struct bch_ratelimit *);
444 void bch2_ratelimit_increment(struct bch_ratelimit *, u64);
446 struct bch_pd_controller {
447 struct bch_ratelimit rate;
448 unsigned long last_update;
451 s64 smoothed_derivative;
453 unsigned p_term_inverse;
457 /* for exporting to sysfs (no effect on behavior) */
459 s64 last_proportional;
463 /* If true, the rate will not increase if bch2_ratelimit_delay()
464 * is not being called often enough. */
468 void bch2_pd_controller_update(struct bch_pd_controller *, s64, s64, int);
469 void bch2_pd_controller_init(struct bch_pd_controller *);
470 void bch2_pd_controller_debug_to_text(struct printbuf *, struct bch_pd_controller *);
472 #define sysfs_pd_controller_attribute(name) \
473 rw_attribute(name##_rate); \
474 rw_attribute(name##_rate_bytes); \
475 rw_attribute(name##_rate_d_term); \
476 rw_attribute(name##_rate_p_term_inverse); \
477 read_attribute(name##_rate_debug)
479 #define sysfs_pd_controller_files(name) \
480 &sysfs_##name##_rate, \
481 &sysfs_##name##_rate_bytes, \
482 &sysfs_##name##_rate_d_term, \
483 &sysfs_##name##_rate_p_term_inverse, \
484 &sysfs_##name##_rate_debug
486 #define sysfs_pd_controller_show(name, var) \
488 sysfs_hprint(name##_rate, (var)->rate.rate); \
489 sysfs_print(name##_rate_bytes, (var)->rate.rate); \
490 sysfs_print(name##_rate_d_term, (var)->d_term); \
491 sysfs_print(name##_rate_p_term_inverse, (var)->p_term_inverse); \
493 if (attr == &sysfs_##name##_rate_debug) \
494 bch2_pd_controller_debug_to_text(out, var); \
497 #define sysfs_pd_controller_store(name, var) \
499 sysfs_strtoul_clamp(name##_rate, \
500 (var)->rate.rate, 1, UINT_MAX); \
501 sysfs_strtoul_clamp(name##_rate_bytes, \
502 (var)->rate.rate, 1, UINT_MAX); \
503 sysfs_strtoul(name##_rate_d_term, (var)->d_term); \
504 sysfs_strtoul_clamp(name##_rate_p_term_inverse, \
505 (var)->p_term_inverse, 1, INT_MAX); \
508 #define container_of_or_null(ptr, type, member) \
510 typeof(ptr) _ptr = ptr; \
511 _ptr ? container_of(_ptr, type, member) : NULL; \
514 /* Does linear interpolation between powers of two */
515 static inline unsigned fract_exp_two(unsigned x, unsigned fract_bits)
517 unsigned fract = x & ~(~0 << fract_bits);
521 x += (x * fract) >> fract_bits;
526 void bch2_bio_map(struct bio *bio, void *base, size_t);
527 int bch2_bio_alloc_pages(struct bio *, size_t, gfp_t);
529 static inline sector_t bdev_sectors(struct block_device *bdev)
531 return bdev->bd_inode->i_size >> 9;
534 #define closure_bio_submit(bio, cl) \
540 #define kthread_wait_freezable(cond) \
544 set_current_state(TASK_INTERRUPTIBLE); \
545 if (kthread_should_stop()) { \
556 set_current_state(TASK_RUNNING); \
560 size_t bch2_rand_range(size_t);
562 void memcpy_to_bio(struct bio *, struct bvec_iter, const void *);
563 void memcpy_from_bio(void *, struct bio *, struct bvec_iter);
565 static inline void memcpy_u64s_small(void *dst, const void *src,
575 static inline void __memcpy_u64s(void *dst, const void *src,
580 asm volatile("rep ; movsq"
581 : "=&c" (d0), "=&D" (d1), "=&S" (d2)
582 : "0" (u64s), "1" (dst), "2" (src)
593 static inline void memcpy_u64s(void *dst, const void *src,
596 EBUG_ON(!(dst >= src + u64s * sizeof(u64) ||
597 dst + u64s * sizeof(u64) <= src));
599 __memcpy_u64s(dst, src, u64s);
602 static inline void __memmove_u64s_down(void *dst, const void *src,
605 __memcpy_u64s(dst, src, u64s);
608 static inline void memmove_u64s_down(void *dst, const void *src,
613 __memmove_u64s_down(dst, src, u64s);
616 static inline void __memmove_u64s_down_small(void *dst, const void *src,
619 memcpy_u64s_small(dst, src, u64s);
622 static inline void memmove_u64s_down_small(void *dst, const void *src,
627 __memmove_u64s_down_small(dst, src, u64s);
630 static inline void __memmove_u64s_up_small(void *_dst, const void *_src,
633 u64 *dst = (u64 *) _dst + u64s;
634 u64 *src = (u64 *) _src + u64s;
640 static inline void memmove_u64s_up_small(void *dst, const void *src,
645 __memmove_u64s_up_small(dst, src, u64s);
648 static inline void __memmove_u64s_up(void *_dst, const void *_src,
651 u64 *dst = (u64 *) _dst + u64s - 1;
652 u64 *src = (u64 *) _src + u64s - 1;
656 asm volatile("std ;\n"
659 : "=&c" (d0), "=&D" (d1), "=&S" (d2)
660 : "0" (u64s), "1" (dst), "2" (src)
668 static inline void memmove_u64s_up(void *dst, const void *src,
673 __memmove_u64s_up(dst, src, u64s);
676 static inline void memmove_u64s(void *dst, const void *src,
680 __memmove_u64s_down(dst, src, u64s);
682 __memmove_u64s_up(dst, src, u64s);
685 /* Set the last few bytes up to a u64 boundary given an offset into a buffer. */
686 static inline void memset_u64s_tail(void *s, int c, unsigned bytes)
688 unsigned rem = round_up(bytes, sizeof(u64)) - bytes;
690 memset(s + bytes, c, rem);
693 void sort_cmp_size(void *base, size_t num, size_t size,
694 int (*cmp_func)(const void *, const void *, size_t),
695 void (*swap_func)(void *, void *, size_t));
697 /* just the memmove, doesn't update @_nr */
698 #define __array_insert_item(_array, _nr, _pos) \
699 memmove(&(_array)[(_pos) + 1], \
701 sizeof((_array)[0]) * ((_nr) - (_pos)))
703 #define array_insert_item(_array, _nr, _pos, _new_item) \
705 __array_insert_item(_array, _nr, _pos); \
707 (_array)[(_pos)] = (_new_item); \
710 #define array_remove_items(_array, _nr, _pos, _nr_to_remove) \
712 (_nr) -= (_nr_to_remove); \
713 memmove(&(_array)[(_pos)], \
714 &(_array)[(_pos) + (_nr_to_remove)], \
715 sizeof((_array)[0]) * ((_nr) - (_pos))); \
718 #define array_remove_item(_array, _nr, _pos) \
719 array_remove_items(_array, _nr, _pos, 1)
721 static inline void __move_gap(void *array, size_t element_size,
722 size_t nr, size_t size,
723 size_t old_gap, size_t new_gap)
725 size_t gap_end = old_gap + size - nr;
727 if (new_gap < old_gap) {
728 size_t move = old_gap - new_gap;
730 memmove(array + element_size * (gap_end - move),
731 array + element_size * (old_gap - move),
732 element_size * move);
733 } else if (new_gap > old_gap) {
734 size_t move = new_gap - old_gap;
736 memmove(array + element_size * old_gap,
737 array + element_size * gap_end,
738 element_size * move);
742 /* Move the gap in a gap buffer: */
743 #define move_gap(_array, _nr, _size, _old_gap, _new_gap) \
744 __move_gap(_array, sizeof(_array[0]), _nr, _size, _old_gap, _new_gap)
746 #define bubble_sort(_base, _nr, _cmp) \
749 bool _swapped = true; \
751 for (_end = (ssize_t) (_nr) - 1; _end > 0 && _swapped; --_end) {\
753 for (_i = 0; _i < _end; _i++) \
754 if (_cmp((_base)[_i], (_base)[_i + 1]) > 0) { \
755 swap((_base)[_i], (_base)[_i + 1]); \
761 static inline u64 percpu_u64_get(u64 __percpu *src)
766 for_each_possible_cpu(cpu)
767 ret += *per_cpu_ptr(src, cpu);
771 static inline void percpu_u64_set(u64 __percpu *dst, u64 src)
775 for_each_possible_cpu(cpu)
776 *per_cpu_ptr(dst, cpu) = 0;
777 this_cpu_write(*dst, src);
780 static inline void acc_u64s(u64 *acc, const u64 *src, unsigned nr)
784 for (i = 0; i < nr; i++)
788 static inline void acc_u64s_percpu(u64 *acc, const u64 __percpu *src,
793 for_each_possible_cpu(cpu)
794 acc_u64s(acc, per_cpu_ptr(src, cpu), nr);
797 static inline void percpu_memset(void __percpu *p, int c, size_t bytes)
801 for_each_possible_cpu(cpu)
802 memset(per_cpu_ptr(p, cpu), c, bytes);
805 u64 *bch2_acc_percpu_u64s(u64 __percpu *, unsigned);
807 #define cmp_int(l, r) ((l > r) - (l < r))
809 static inline int u8_cmp(u8 l, u8 r)
811 return cmp_int(l, r);
814 #endif /* _BCACHEFS_UTIL_H */