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>
21 #include "mean_and_variance.h"
27 #ifdef CONFIG_BCACHEFS_DEBUG
28 #define EBUG_ON(cond) BUG_ON(cond)
33 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
34 #define CPU_BIG_ENDIAN 0
35 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
36 #define CPU_BIG_ENDIAN 1
41 #define type_is_exact(_val, _type) \
42 __builtin_types_compatible_p(typeof(_val), _type)
44 #define type_is(_val, _type) \
45 (__builtin_types_compatible_p(typeof(_val), _type) || \
46 __builtin_types_compatible_p(typeof(_val), const _type))
48 /* Userspace doesn't align allocations as nicely as the kernel allocators: */
49 static inline size_t buf_pages(void *p, size_t len)
51 return DIV_ROUND_UP(len +
52 ((unsigned long) p & (PAGE_SIZE - 1)),
56 static inline void vpfree(void *p, size_t size)
58 if (is_vmalloc_addr(p))
61 free_pages((unsigned long) p, get_order(size));
64 static inline void *vpmalloc(size_t size, gfp_t gfp_mask)
66 return (void *) __get_free_pages(gfp_mask|__GFP_NOWARN,
68 __vmalloc(size, gfp_mask);
71 static inline void kvpfree(void *p, size_t size)
79 static inline void *kvpmalloc(size_t size, gfp_t gfp_mask)
81 return size < PAGE_SIZE
82 ? kmalloc(size, gfp_mask)
83 : vpmalloc(size, gfp_mask);
86 int mempool_init_kvpmalloc_pool(mempool_t *, int, size_t);
94 #define DECLARE_HEAP(type, name) HEAP(type) name
96 #define init_heap(heap, _size, gfp) \
99 (heap)->size = (_size); \
100 (heap)->data = kvpmalloc((heap)->size * sizeof((heap)->data[0]),\
104 #define free_heap(heap) \
106 kvpfree((heap)->data, (heap)->size * sizeof((heap)->data[0])); \
107 (heap)->data = NULL; \
110 #define heap_set_backpointer(h, i, _fn) \
112 void (*fn)(typeof(h), size_t) = _fn; \
117 #define heap_swap(h, i, j, set_backpointer) \
119 swap((h)->data[i], (h)->data[j]); \
120 heap_set_backpointer(h, i, set_backpointer); \
121 heap_set_backpointer(h, j, set_backpointer); \
124 #define heap_peek(h) \
126 EBUG_ON(!(h)->used); \
130 #define heap_full(h) ((h)->used == (h)->size)
132 #define heap_sift_down(h, i, cmp, set_backpointer) \
136 for (; _j * 2 + 1 < (h)->used; _j = _c) { \
138 if (_c + 1 < (h)->used && \
139 cmp(h, (h)->data[_c], (h)->data[_c + 1]) >= 0) \
142 if (cmp(h, (h)->data[_c], (h)->data[_j]) >= 0) \
144 heap_swap(h, _c, _j, set_backpointer); \
148 #define heap_sift_up(h, i, cmp, set_backpointer) \
151 size_t p = (i - 1) / 2; \
152 if (cmp(h, (h)->data[i], (h)->data[p]) >= 0) \
154 heap_swap(h, i, p, set_backpointer); \
159 #define __heap_add(h, d, cmp, set_backpointer) \
161 size_t _i = (h)->used++; \
163 heap_set_backpointer(h, _i, set_backpointer); \
165 heap_sift_up(h, _i, cmp, set_backpointer); \
169 #define heap_add(h, d, cmp, set_backpointer) \
171 bool _r = !heap_full(h); \
173 __heap_add(h, d, cmp, set_backpointer); \
177 #define heap_add_or_replace(h, new, cmp, set_backpointer) \
179 if (!heap_add(h, new, cmp, set_backpointer) && \
180 cmp(h, new, heap_peek(h)) >= 0) { \
181 (h)->data[0] = new; \
182 heap_set_backpointer(h, 0, set_backpointer); \
183 heap_sift_down(h, 0, cmp, set_backpointer); \
187 #define heap_del(h, i, cmp, set_backpointer) \
191 BUG_ON(_i >= (h)->used); \
193 if ((_i) < (h)->used) { \
194 heap_swap(h, _i, (h)->used, set_backpointer); \
195 heap_sift_up(h, _i, cmp, set_backpointer); \
196 heap_sift_down(h, _i, cmp, set_backpointer); \
200 #define heap_pop(h, d, cmp, set_backpointer) \
202 bool _r = (h)->used; \
204 (d) = (h)->data[0]; \
205 heap_del(h, 0, cmp, set_backpointer); \
210 #define heap_resort(heap, cmp, set_backpointer) \
213 for (_i = (ssize_t) (heap)->used / 2 - 1; _i >= 0; --_i) \
214 heap_sift_down(heap, _i, cmp, set_backpointer); \
217 #define ANYSINT_MAX(t) \
218 ((((t) 1 << (sizeof(t) * 8 - 2)) - (t) 1) * (t) 2 + (t) 1)
220 #include "printbuf.h"
222 #define prt_vprintf(_out, ...) bch2_prt_vprintf(_out, __VA_ARGS__)
223 #define prt_printf(_out, ...) bch2_prt_printf(_out, __VA_ARGS__)
224 #define printbuf_str(_buf) bch2_printbuf_str(_buf)
225 #define printbuf_exit(_buf) bch2_printbuf_exit(_buf)
227 #define printbuf_tabstops_reset(_buf) bch2_printbuf_tabstops_reset(_buf)
228 #define printbuf_tabstop_pop(_buf) bch2_printbuf_tabstop_pop(_buf)
229 #define printbuf_tabstop_push(_buf, _n) bch2_printbuf_tabstop_push(_buf, _n)
231 #define printbuf_indent_add(_out, _n) bch2_printbuf_indent_add(_out, _n)
232 #define printbuf_indent_sub(_out, _n) bch2_printbuf_indent_sub(_out, _n)
234 #define prt_newline(_out) bch2_prt_newline(_out)
235 #define prt_tab(_out) bch2_prt_tab(_out)
236 #define prt_tab_rjust(_out) bch2_prt_tab_rjust(_out)
238 #define prt_bytes_indented(...) bch2_prt_bytes_indented(__VA_ARGS__)
239 #define prt_u64(_out, _v) prt_printf(_out, "%llu", (u64) (_v))
240 #define prt_human_readable_u64(...) bch2_prt_human_readable_u64(__VA_ARGS__)
241 #define prt_human_readable_s64(...) bch2_prt_human_readable_s64(__VA_ARGS__)
242 #define prt_units_u64(...) bch2_prt_units_u64(__VA_ARGS__)
243 #define prt_units_s64(...) bch2_prt_units_s64(__VA_ARGS__)
244 #define prt_string_option(...) bch2_prt_string_option(__VA_ARGS__)
245 #define prt_bitflags(...) bch2_prt_bitflags(__VA_ARGS__)
246 #define prt_bitflags_vector(...) bch2_prt_bitflags_vector(__VA_ARGS__)
248 void bch2_pr_time_units(struct printbuf *, u64);
249 void bch2_prt_datetime(struct printbuf *, time64_t);
252 static inline void uuid_unparse_lower(u8 *uuid, char *out)
254 sprintf(out, "%pUb", uuid);
257 #include <uuid/uuid.h>
260 static inline void pr_uuid(struct printbuf *out, u8 *uuid)
264 uuid_unparse_lower(uuid, uuid_str);
265 prt_printf(out, "%s", uuid_str);
268 int bch2_strtoint_h(const char *, int *);
269 int bch2_strtouint_h(const char *, unsigned int *);
270 int bch2_strtoll_h(const char *, long long *);
271 int bch2_strtoull_h(const char *, unsigned long long *);
272 int bch2_strtou64_h(const char *, u64 *);
274 static inline int bch2_strtol_h(const char *cp, long *res)
276 #if BITS_PER_LONG == 32
277 return bch2_strtoint_h(cp, (int *) res);
279 return bch2_strtoll_h(cp, (long long *) res);
283 static inline int bch2_strtoul_h(const char *cp, long *res)
285 #if BITS_PER_LONG == 32
286 return bch2_strtouint_h(cp, (unsigned int *) res);
288 return bch2_strtoull_h(cp, (unsigned long long *) res);
292 #define strtoi_h(cp, res) \
293 ( type_is(*res, int) ? bch2_strtoint_h(cp, (void *) res)\
294 : type_is(*res, long) ? bch2_strtol_h(cp, (void *) res)\
295 : type_is(*res, long long) ? bch2_strtoll_h(cp, (void *) res)\
296 : type_is(*res, unsigned) ? bch2_strtouint_h(cp, (void *) res)\
297 : type_is(*res, unsigned long) ? bch2_strtoul_h(cp, (void *) res)\
298 : type_is(*res, unsigned long long) ? bch2_strtoull_h(cp, (void *) res)\
301 #define strtoul_safe(cp, var) \
304 int _r = kstrtoul(cp, 10, &_v); \
310 #define strtoul_safe_clamp(cp, var, min, max) \
313 int _r = kstrtoul(cp, 10, &_v); \
315 var = clamp_t(typeof(var), _v, min, max); \
319 #define strtoul_safe_restrict(cp, var, min, max) \
322 int _r = kstrtoul(cp, 10, &_v); \
323 if (!_r && _v >= min && _v <= max) \
330 #define snprint(out, var) \
332 type_is(var, int) ? "%i\n" \
333 : type_is(var, unsigned) ? "%u\n" \
334 : type_is(var, long) ? "%li\n" \
335 : type_is(var, unsigned long) ? "%lu\n" \
336 : type_is(var, s64) ? "%lli\n" \
337 : type_is(var, u64) ? "%llu\n" \
338 : type_is(var, char *) ? "%s\n" \
341 bool bch2_is_zero(const void *, size_t);
343 u64 bch2_read_flag_list(char *, const char * const[]);
345 void bch2_prt_u64_base2_nbits(struct printbuf *, u64, unsigned);
346 void bch2_prt_u64_base2(struct printbuf *, u64);
348 void bch2_print_string_as_lines(const char *prefix, const char *lines);
350 typedef DARRAY(unsigned long) bch_stacktrace;
351 int bch2_save_backtrace(bch_stacktrace *stack, struct task_struct *, unsigned, gfp_t);
352 void bch2_prt_backtrace(struct printbuf *, bch_stacktrace *);
353 int bch2_prt_task_backtrace(struct printbuf *, struct task_struct *, unsigned, gfp_t);
355 static inline void prt_bdevname(struct printbuf *out, struct block_device *bdev)
358 prt_printf(out, "%pg", bdev);
360 prt_str(out, bdev->name);
364 #define NR_QUANTILES 15
365 #define QUANTILE_IDX(i) inorder_to_eytzinger0(i, NR_QUANTILES)
366 #define QUANTILE_FIRST eytzinger0_first(NR_QUANTILES)
367 #define QUANTILE_LAST eytzinger0_last(NR_QUANTILES)
369 struct bch2_quantiles {
370 struct bch2_quantile_entry {
373 } entries[NR_QUANTILES];
376 struct bch2_time_stat_buffer {
378 struct bch2_time_stat_buffer_entry {
384 struct bch2_time_stats {
386 /* 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)
407 __bch2_time_stats_update(stats, start, local_clock());
410 static inline bool track_event_change(struct bch2_time_stats *stats,
415 bch2_time_stats_update(stats, *start);
418 *start = local_clock() ?: 1;
426 static inline void __bch2_time_stats_update(struct bch2_time_stats *stats, u64 start, u64 end) {}
427 static inline void bch2_time_stats_update(struct bch2_time_stats *stats, u64 start) {}
428 static inline bool track_event_change(struct bch2_time_stats *stats,
431 bool ret = v && !*start;
437 void bch2_time_stats_to_text(struct printbuf *, struct bch2_time_stats *);
439 void bch2_time_stats_exit(struct bch2_time_stats *);
440 void bch2_time_stats_init(struct bch2_time_stats *);
442 #define ewma_add(ewma, val, weight) \
444 typeof(ewma) _ewma = (ewma); \
445 typeof(weight) _weight = (weight); \
447 (((_ewma << _weight) - _ewma) + (val)) >> _weight; \
450 struct bch_ratelimit {
451 /* Next time we want to do some work, in nanoseconds */
455 * Rate at which we want to do work, in units per nanosecond
456 * The units here correspond to the units passed to
457 * bch2_ratelimit_increment()
462 static inline void bch2_ratelimit_reset(struct bch_ratelimit *d)
464 d->next = local_clock();
467 u64 bch2_ratelimit_delay(struct bch_ratelimit *);
468 void bch2_ratelimit_increment(struct bch_ratelimit *, u64);
470 struct bch_pd_controller {
471 struct bch_ratelimit rate;
472 unsigned long last_update;
475 s64 smoothed_derivative;
477 unsigned p_term_inverse;
481 /* for exporting to sysfs (no effect on behavior) */
483 s64 last_proportional;
488 * If true, the rate will not increase if bch2_ratelimit_delay()
489 * is not being called often enough.
494 void bch2_pd_controller_update(struct bch_pd_controller *, s64, s64, int);
495 void bch2_pd_controller_init(struct bch_pd_controller *);
496 void bch2_pd_controller_debug_to_text(struct printbuf *, struct bch_pd_controller *);
498 #define sysfs_pd_controller_attribute(name) \
499 rw_attribute(name##_rate); \
500 rw_attribute(name##_rate_bytes); \
501 rw_attribute(name##_rate_d_term); \
502 rw_attribute(name##_rate_p_term_inverse); \
503 read_attribute(name##_rate_debug)
505 #define sysfs_pd_controller_files(name) \
506 &sysfs_##name##_rate, \
507 &sysfs_##name##_rate_bytes, \
508 &sysfs_##name##_rate_d_term, \
509 &sysfs_##name##_rate_p_term_inverse, \
510 &sysfs_##name##_rate_debug
512 #define sysfs_pd_controller_show(name, var) \
514 sysfs_hprint(name##_rate, (var)->rate.rate); \
515 sysfs_print(name##_rate_bytes, (var)->rate.rate); \
516 sysfs_print(name##_rate_d_term, (var)->d_term); \
517 sysfs_print(name##_rate_p_term_inverse, (var)->p_term_inverse); \
519 if (attr == &sysfs_##name##_rate_debug) \
520 bch2_pd_controller_debug_to_text(out, var); \
523 #define sysfs_pd_controller_store(name, var) \
525 sysfs_strtoul_clamp(name##_rate, \
526 (var)->rate.rate, 1, UINT_MAX); \
527 sysfs_strtoul_clamp(name##_rate_bytes, \
528 (var)->rate.rate, 1, UINT_MAX); \
529 sysfs_strtoul(name##_rate_d_term, (var)->d_term); \
530 sysfs_strtoul_clamp(name##_rate_p_term_inverse, \
531 (var)->p_term_inverse, 1, INT_MAX); \
534 #define container_of_or_null(ptr, type, member) \
536 typeof(ptr) _ptr = ptr; \
537 _ptr ? container_of(_ptr, type, member) : NULL; \
540 /* Does linear interpolation between powers of two */
541 static inline unsigned fract_exp_two(unsigned x, unsigned fract_bits)
543 unsigned fract = x & ~(~0 << fract_bits);
547 x += (x * fract) >> fract_bits;
552 void bch2_bio_map(struct bio *bio, void *base, size_t);
553 int bch2_bio_alloc_pages(struct bio *, size_t, gfp_t);
555 static inline sector_t bdev_sectors(struct block_device *bdev)
557 return bdev->bd_inode->i_size >> 9;
560 #define closure_bio_submit(bio, cl) \
566 #define kthread_wait(cond) \
571 set_current_state(TASK_INTERRUPTIBLE); \
572 if (kthread_should_stop()) { \
582 set_current_state(TASK_RUNNING); \
586 #define kthread_wait_freezable(cond) \
590 set_current_state(TASK_INTERRUPTIBLE); \
591 if (kthread_should_stop()) { \
602 set_current_state(TASK_RUNNING); \
606 size_t bch2_rand_range(size_t);
608 void memcpy_to_bio(struct bio *, struct bvec_iter, const void *);
609 void memcpy_from_bio(void *, struct bio *, struct bvec_iter);
611 static inline void memcpy_u64s_small(void *dst, const void *src,
621 static inline void __memcpy_u64s(void *dst, const void *src,
627 asm volatile("rep ; movsq"
628 : "=&c" (d0), "=&D" (d1), "=&S" (d2)
629 : "0" (u64s), "1" (dst), "2" (src)
640 static inline void memcpy_u64s(void *dst, const void *src,
643 EBUG_ON(!(dst >= src + u64s * sizeof(u64) ||
644 dst + u64s * sizeof(u64) <= src));
646 __memcpy_u64s(dst, src, u64s);
649 static inline void __memmove_u64s_down(void *dst, const void *src,
652 __memcpy_u64s(dst, src, u64s);
655 static inline void memmove_u64s_down(void *dst, const void *src,
660 __memmove_u64s_down(dst, src, u64s);
663 static inline void __memmove_u64s_down_small(void *dst, const void *src,
666 memcpy_u64s_small(dst, src, u64s);
669 static inline void memmove_u64s_down_small(void *dst, const void *src,
674 __memmove_u64s_down_small(dst, src, u64s);
677 static inline void __memmove_u64s_up_small(void *_dst, const void *_src,
680 u64 *dst = (u64 *) _dst + u64s;
681 u64 *src = (u64 *) _src + u64s;
687 static inline void memmove_u64s_up_small(void *dst, const void *src,
692 __memmove_u64s_up_small(dst, src, u64s);
695 static inline void __memmove_u64s_up(void *_dst, const void *_src,
698 u64 *dst = (u64 *) _dst + u64s - 1;
699 u64 *src = (u64 *) _src + u64s - 1;
704 asm volatile("std ;\n"
707 : "=&c" (d0), "=&D" (d1), "=&S" (d2)
708 : "0" (u64s), "1" (dst), "2" (src)
716 static inline void memmove_u64s_up(void *dst, const void *src,
721 __memmove_u64s_up(dst, src, u64s);
724 static inline void memmove_u64s(void *dst, const void *src,
728 __memmove_u64s_down(dst, src, u64s);
730 __memmove_u64s_up(dst, src, u64s);
733 /* Set the last few bytes up to a u64 boundary given an offset into a buffer. */
734 static inline void memset_u64s_tail(void *s, int c, unsigned bytes)
736 unsigned rem = round_up(bytes, sizeof(u64)) - bytes;
738 memset(s + bytes, c, rem);
741 void sort_cmp_size(void *base, size_t num, size_t size,
742 int (*cmp_func)(const void *, const void *, size_t),
743 void (*swap_func)(void *, void *, size_t));
745 /* just the memmove, doesn't update @_nr */
746 #define __array_insert_item(_array, _nr, _pos) \
747 memmove(&(_array)[(_pos) + 1], \
749 sizeof((_array)[0]) * ((_nr) - (_pos)))
751 #define array_insert_item(_array, _nr, _pos, _new_item) \
753 __array_insert_item(_array, _nr, _pos); \
755 (_array)[(_pos)] = (_new_item); \
758 #define array_remove_items(_array, _nr, _pos, _nr_to_remove) \
760 (_nr) -= (_nr_to_remove); \
761 memmove(&(_array)[(_pos)], \
762 &(_array)[(_pos) + (_nr_to_remove)], \
763 sizeof((_array)[0]) * ((_nr) - (_pos))); \
766 #define array_remove_item(_array, _nr, _pos) \
767 array_remove_items(_array, _nr, _pos, 1)
769 static inline void __move_gap(void *array, size_t element_size,
770 size_t nr, size_t size,
771 size_t old_gap, size_t new_gap)
773 size_t gap_end = old_gap + size - nr;
775 if (new_gap < old_gap) {
776 size_t move = old_gap - new_gap;
778 memmove(array + element_size * (gap_end - move),
779 array + element_size * (old_gap - move),
780 element_size * move);
781 } else if (new_gap > old_gap) {
782 size_t move = new_gap - old_gap;
784 memmove(array + element_size * old_gap,
785 array + element_size * gap_end,
786 element_size * move);
790 /* Move the gap in a gap buffer: */
791 #define move_gap(_array, _nr, _size, _old_gap, _new_gap) \
792 __move_gap(_array, sizeof(_array[0]), _nr, _size, _old_gap, _new_gap)
794 #define bubble_sort(_base, _nr, _cmp) \
797 bool _swapped = true; \
799 for (_last= (ssize_t) (_nr) - 1; _last > 0 && _swapped; --_last) {\
801 for (_i = 0; _i < _last; _i++) \
802 if (_cmp((_base)[_i], (_base)[_i + 1]) > 0) { \
803 swap((_base)[_i], (_base)[_i + 1]); \
809 static inline u64 percpu_u64_get(u64 __percpu *src)
814 for_each_possible_cpu(cpu)
815 ret += *per_cpu_ptr(src, cpu);
819 static inline void percpu_u64_set(u64 __percpu *dst, u64 src)
823 for_each_possible_cpu(cpu)
824 *per_cpu_ptr(dst, cpu) = 0;
825 this_cpu_write(*dst, src);
828 static inline void acc_u64s(u64 *acc, const u64 *src, unsigned nr)
832 for (i = 0; i < nr; i++)
836 static inline void acc_u64s_percpu(u64 *acc, const u64 __percpu *src,
841 for_each_possible_cpu(cpu)
842 acc_u64s(acc, per_cpu_ptr(src, cpu), nr);
845 static inline void percpu_memset(void __percpu *p, int c, size_t bytes)
849 for_each_possible_cpu(cpu)
850 memset(per_cpu_ptr(p, cpu), c, bytes);
853 u64 *bch2_acc_percpu_u64s(u64 __percpu *, unsigned);
855 #define cmp_int(l, r) ((l > r) - (l < r))
857 static inline int u8_cmp(u8 l, u8 r)
859 return cmp_int(l, r);
862 static inline int cmp_le32(__le32 l, __le32 r)
864 return cmp_int(le32_to_cpu(l), le32_to_cpu(r));
867 #include <linux/uuid.h>
869 #define QSTR(n) { { { .len = strlen(n) } }, .name = n }
871 static inline bool qstr_eq(const struct qstr l, const struct qstr r)
873 return l.len == r.len && !memcmp(l.name, r.name, l.len);
876 void bch2_darray_str_exit(darray_str *);
877 int bch2_split_devs(const char *, darray_str *);
879 #endif /* _BCACHEFS_UTIL_H */