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>
26 #ifdef CONFIG_BCACHEFS_DEBUG
27 #define EBUG_ON(cond) BUG_ON(cond)
32 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
33 #define CPU_BIG_ENDIAN 0
34 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
35 #define CPU_BIG_ENDIAN 1
40 #define type_is_exact(_val, _type) \
41 __builtin_types_compatible_p(typeof(_val), _type)
43 #define type_is(_val, _type) \
44 (__builtin_types_compatible_p(typeof(_val), _type) || \
45 __builtin_types_compatible_p(typeof(_val), const _type))
47 /* Userspace doesn't align allocations as nicely as the kernel allocators: */
48 static inline size_t buf_pages(void *p, size_t len)
50 return DIV_ROUND_UP(len +
51 ((unsigned long) p & (PAGE_SIZE - 1)),
55 static inline void vpfree(void *p, size_t size)
57 if (is_vmalloc_addr(p))
60 free_pages((unsigned long) p, get_order(size));
63 static inline void *vpmalloc_noprof(size_t size, gfp_t gfp_mask)
65 return (void *) get_free_pages_noprof(gfp_mask|__GFP_NOWARN,
67 __vmalloc_noprof(size, gfp_mask);
69 #define vpmalloc(_size, _gfp) alloc_hooks(vpmalloc_noprof(_size, _gfp))
71 static inline void kvpfree(void *p, size_t size)
79 static inline void *kvpmalloc_noprof(size_t size, gfp_t gfp_mask)
81 return size < PAGE_SIZE
82 ? kmalloc_noprof(size, gfp_mask)
83 : vpmalloc_noprof(size, gfp_mask);
85 #define kvpmalloc(_size, _gfp) alloc_hooks(kvpmalloc_noprof(_size, _gfp))
87 int mempool_init_kvpmalloc_pool(mempool_t *, int, size_t);
95 #define DECLARE_HEAP(type, name) HEAP(type) name
97 #define init_heap(heap, _size, gfp) \
100 (heap)->size = (_size); \
101 (heap)->data = kvpmalloc((heap)->size * sizeof((heap)->data[0]),\
105 #define free_heap(heap) \
107 kvpfree((heap)->data, (heap)->size * sizeof((heap)->data[0])); \
108 (heap)->data = NULL; \
111 #define heap_set_backpointer(h, i, _fn) \
113 void (*fn)(typeof(h), size_t) = _fn; \
118 #define heap_swap(h, i, j, set_backpointer) \
120 swap((h)->data[i], (h)->data[j]); \
121 heap_set_backpointer(h, i, set_backpointer); \
122 heap_set_backpointer(h, j, set_backpointer); \
125 #define heap_peek(h) \
127 EBUG_ON(!(h)->used); \
131 #define heap_full(h) ((h)->used == (h)->size)
133 #define heap_sift_down(h, i, cmp, set_backpointer) \
137 for (; _j * 2 + 1 < (h)->used; _j = _c) { \
139 if (_c + 1 < (h)->used && \
140 cmp(h, (h)->data[_c], (h)->data[_c + 1]) >= 0) \
143 if (cmp(h, (h)->data[_c], (h)->data[_j]) >= 0) \
145 heap_swap(h, _c, _j, set_backpointer); \
149 #define heap_sift_up(h, i, cmp, set_backpointer) \
152 size_t p = (i - 1) / 2; \
153 if (cmp(h, (h)->data[i], (h)->data[p]) >= 0) \
155 heap_swap(h, i, p, set_backpointer); \
160 #define __heap_add(h, d, cmp, set_backpointer) \
162 size_t _i = (h)->used++; \
164 heap_set_backpointer(h, _i, set_backpointer); \
166 heap_sift_up(h, _i, cmp, set_backpointer); \
170 #define heap_add(h, d, cmp, set_backpointer) \
172 bool _r = !heap_full(h); \
174 __heap_add(h, d, cmp, set_backpointer); \
178 #define heap_add_or_replace(h, new, cmp, set_backpointer) \
180 if (!heap_add(h, new, cmp, set_backpointer) && \
181 cmp(h, new, heap_peek(h)) >= 0) { \
182 (h)->data[0] = new; \
183 heap_set_backpointer(h, 0, set_backpointer); \
184 heap_sift_down(h, 0, cmp, set_backpointer); \
188 #define heap_del(h, i, cmp, set_backpointer) \
192 BUG_ON(_i >= (h)->used); \
194 if ((_i) < (h)->used) { \
195 heap_swap(h, _i, (h)->used, set_backpointer); \
196 heap_sift_up(h, _i, cmp, set_backpointer); \
197 heap_sift_down(h, _i, cmp, set_backpointer); \
201 #define heap_pop(h, d, cmp, set_backpointer) \
203 bool _r = (h)->used; \
205 (d) = (h)->data[0]; \
206 heap_del(h, 0, cmp, set_backpointer); \
211 #define heap_resort(heap, cmp, set_backpointer) \
214 for (_i = (ssize_t) (heap)->used / 2 - 1; _i >= 0; --_i) \
215 heap_sift_down(heap, _i, cmp, set_backpointer); \
218 #define ANYSINT_MAX(t) \
219 ((((t) 1 << (sizeof(t) * 8 - 2)) - (t) 1) * (t) 2 + (t) 1)
221 #include "printbuf.h"
223 #define prt_vprintf(_out, ...) bch2_prt_vprintf(_out, __VA_ARGS__)
224 #define prt_printf(_out, ...) bch2_prt_printf(_out, __VA_ARGS__)
225 #define printbuf_str(_buf) bch2_printbuf_str(_buf)
226 #define printbuf_exit(_buf) bch2_printbuf_exit(_buf)
228 #define printbuf_tabstops_reset(_buf) bch2_printbuf_tabstops_reset(_buf)
229 #define printbuf_tabstop_pop(_buf) bch2_printbuf_tabstop_pop(_buf)
230 #define printbuf_tabstop_push(_buf, _n) bch2_printbuf_tabstop_push(_buf, _n)
232 #define printbuf_indent_add(_out, _n) bch2_printbuf_indent_add(_out, _n)
233 #define printbuf_indent_sub(_out, _n) bch2_printbuf_indent_sub(_out, _n)
235 #define prt_newline(_out) bch2_prt_newline(_out)
236 #define prt_tab(_out) bch2_prt_tab(_out)
237 #define prt_tab_rjust(_out) bch2_prt_tab_rjust(_out)
239 #define prt_bytes_indented(...) bch2_prt_bytes_indented(__VA_ARGS__)
240 #define prt_u64(_out, _v) prt_printf(_out, "%llu", (u64) (_v))
241 #define prt_human_readable_u64(...) bch2_prt_human_readable_u64(__VA_ARGS__)
242 #define prt_human_readable_s64(...) bch2_prt_human_readable_s64(__VA_ARGS__)
243 #define prt_units_u64(...) bch2_prt_units_u64(__VA_ARGS__)
244 #define prt_units_s64(...) bch2_prt_units_s64(__VA_ARGS__)
245 #define prt_string_option(...) bch2_prt_string_option(__VA_ARGS__)
246 #define prt_bitflags(...) bch2_prt_bitflags(__VA_ARGS__)
248 void bch2_pr_time_units(struct printbuf *, u64);
251 static inline void pr_time(struct printbuf *out, u64 time)
253 prt_printf(out, "%llu", time);
257 static inline void pr_time(struct printbuf *out, u64 _time)
261 struct tm *tm = localtime(&time);
262 size_t err = strftime(time_str, sizeof(time_str), "%c", tm);
264 prt_printf(out, "(formatting error)");
266 prt_printf(out, "%s", time_str);
271 static inline void uuid_unparse_lower(u8 *uuid, char *out)
273 sprintf(out, "%pUb", uuid);
276 #include <uuid/uuid.h>
279 static inline void pr_uuid(struct printbuf *out, u8 *uuid)
283 uuid_unparse_lower(uuid, uuid_str);
284 prt_printf(out, "%s", uuid_str);
287 int bch2_strtoint_h(const char *, int *);
288 int bch2_strtouint_h(const char *, unsigned int *);
289 int bch2_strtoll_h(const char *, long long *);
290 int bch2_strtoull_h(const char *, unsigned long long *);
291 int bch2_strtou64_h(const char *, u64 *);
293 static inline int bch2_strtol_h(const char *cp, long *res)
295 #if BITS_PER_LONG == 32
296 return bch2_strtoint_h(cp, (int *) res);
298 return bch2_strtoll_h(cp, (long long *) res);
302 static inline int bch2_strtoul_h(const char *cp, long *res)
304 #if BITS_PER_LONG == 32
305 return bch2_strtouint_h(cp, (unsigned int *) res);
307 return bch2_strtoull_h(cp, (unsigned long long *) res);
311 #define strtoi_h(cp, res) \
312 ( type_is(*res, int) ? bch2_strtoint_h(cp, (void *) res)\
313 : type_is(*res, long) ? bch2_strtol_h(cp, (void *) res)\
314 : type_is(*res, long long) ? bch2_strtoll_h(cp, (void *) res)\
315 : type_is(*res, unsigned) ? bch2_strtouint_h(cp, (void *) res)\
316 : type_is(*res, unsigned long) ? bch2_strtoul_h(cp, (void *) res)\
317 : type_is(*res, unsigned long long) ? bch2_strtoull_h(cp, (void *) res)\
320 #define strtoul_safe(cp, var) \
323 int _r = kstrtoul(cp, 10, &_v); \
329 #define strtoul_safe_clamp(cp, var, min, max) \
332 int _r = kstrtoul(cp, 10, &_v); \
334 var = clamp_t(typeof(var), _v, min, max); \
338 #define strtoul_safe_restrict(cp, var, min, max) \
341 int _r = kstrtoul(cp, 10, &_v); \
342 if (!_r && _v >= min && _v <= max) \
349 #define snprint(out, var) \
351 type_is(var, int) ? "%i\n" \
352 : type_is(var, unsigned) ? "%u\n" \
353 : type_is(var, long) ? "%li\n" \
354 : type_is(var, unsigned long) ? "%lu\n" \
355 : type_is(var, s64) ? "%lli\n" \
356 : type_is(var, u64) ? "%llu\n" \
357 : type_is(var, char *) ? "%s\n" \
360 bool bch2_is_zero(const void *, size_t);
362 u64 bch2_read_flag_list(char *, const char * const[]);
364 void bch2_prt_u64_binary(struct printbuf *, u64, unsigned);
366 void bch2_print_string_as_lines(const char *prefix, const char *lines);
368 typedef DARRAY(unsigned long) bch_stacktrace;
369 int bch2_save_backtrace(bch_stacktrace *stack, struct task_struct *);
370 void bch2_prt_backtrace(struct printbuf *, bch_stacktrace *);
371 int bch2_prt_task_backtrace(struct printbuf *, struct task_struct *);
373 #define NR_QUANTILES 15
374 #define QUANTILE_IDX(i) inorder_to_eytzinger0(i, NR_QUANTILES)
375 #define QUANTILE_FIRST eytzinger0_first(NR_QUANTILES)
376 #define QUANTILE_LAST eytzinger0_last(NR_QUANTILES)
378 struct bch2_quantiles {
379 struct bch2_quantile_entry {
382 } entries[NR_QUANTILES];
385 struct bch2_time_stat_buffer {
387 struct bch2_time_stat_buffer_entry {
393 struct bch2_time_stats {
395 /* all fields are in nanoseconds */
401 struct bch2_quantiles quantiles;
403 struct mean_and_variance duration_stats;
404 struct mean_and_variance_weighted duration_stats_weighted;
405 struct mean_and_variance freq_stats;
406 struct mean_and_variance_weighted freq_stats_weighted;
407 struct bch2_time_stat_buffer __percpu *buffer;
410 #ifndef CONFIG_BCACHEFS_NO_LATENCY_ACCT
411 void __bch2_time_stats_update(struct bch2_time_stats *stats, u64, u64);
413 static inline void __bch2_time_stats_update(struct bch2_time_stats *stats, u64 start, u64 end) {}
416 static inline void bch2_time_stats_update(struct bch2_time_stats *stats, u64 start)
418 __bch2_time_stats_update(stats, start, local_clock());
421 void bch2_time_stats_to_text(struct printbuf *, struct bch2_time_stats *);
423 void bch2_time_stats_exit(struct bch2_time_stats *);
424 void bch2_time_stats_init(struct bch2_time_stats *);
426 #define ewma_add(ewma, val, weight) \
428 typeof(ewma) _ewma = (ewma); \
429 typeof(weight) _weight = (weight); \
431 (((_ewma << _weight) - _ewma) + (val)) >> _weight; \
434 struct bch_ratelimit {
435 /* Next time we want to do some work, in nanoseconds */
439 * Rate at which we want to do work, in units per nanosecond
440 * The units here correspond to the units passed to
441 * bch2_ratelimit_increment()
446 static inline void bch2_ratelimit_reset(struct bch_ratelimit *d)
448 d->next = local_clock();
451 u64 bch2_ratelimit_delay(struct bch_ratelimit *);
452 void bch2_ratelimit_increment(struct bch_ratelimit *, u64);
454 struct bch_pd_controller {
455 struct bch_ratelimit rate;
456 unsigned long last_update;
459 s64 smoothed_derivative;
461 unsigned p_term_inverse;
465 /* for exporting to sysfs (no effect on behavior) */
467 s64 last_proportional;
472 * If true, the rate will not increase if bch2_ratelimit_delay()
473 * is not being called often enough.
478 void bch2_pd_controller_update(struct bch_pd_controller *, s64, s64, int);
479 void bch2_pd_controller_init(struct bch_pd_controller *);
480 void bch2_pd_controller_debug_to_text(struct printbuf *, struct bch_pd_controller *);
482 #define sysfs_pd_controller_attribute(name) \
483 rw_attribute(name##_rate); \
484 rw_attribute(name##_rate_bytes); \
485 rw_attribute(name##_rate_d_term); \
486 rw_attribute(name##_rate_p_term_inverse); \
487 read_attribute(name##_rate_debug)
489 #define sysfs_pd_controller_files(name) \
490 &sysfs_##name##_rate, \
491 &sysfs_##name##_rate_bytes, \
492 &sysfs_##name##_rate_d_term, \
493 &sysfs_##name##_rate_p_term_inverse, \
494 &sysfs_##name##_rate_debug
496 #define sysfs_pd_controller_show(name, var) \
498 sysfs_hprint(name##_rate, (var)->rate.rate); \
499 sysfs_print(name##_rate_bytes, (var)->rate.rate); \
500 sysfs_print(name##_rate_d_term, (var)->d_term); \
501 sysfs_print(name##_rate_p_term_inverse, (var)->p_term_inverse); \
503 if (attr == &sysfs_##name##_rate_debug) \
504 bch2_pd_controller_debug_to_text(out, var); \
507 #define sysfs_pd_controller_store(name, var) \
509 sysfs_strtoul_clamp(name##_rate, \
510 (var)->rate.rate, 1, UINT_MAX); \
511 sysfs_strtoul_clamp(name##_rate_bytes, \
512 (var)->rate.rate, 1, UINT_MAX); \
513 sysfs_strtoul(name##_rate_d_term, (var)->d_term); \
514 sysfs_strtoul_clamp(name##_rate_p_term_inverse, \
515 (var)->p_term_inverse, 1, INT_MAX); \
518 #define container_of_or_null(ptr, type, member) \
520 typeof(ptr) _ptr = ptr; \
521 _ptr ? container_of(_ptr, type, member) : NULL; \
524 /* Does linear interpolation between powers of two */
525 static inline unsigned fract_exp_two(unsigned x, unsigned fract_bits)
527 unsigned fract = x & ~(~0 << fract_bits);
531 x += (x * fract) >> fract_bits;
536 void bch2_bio_map(struct bio *bio, void *base, size_t);
537 int bch2_bio_alloc_pages_noprof(struct bio *, size_t, gfp_t);
538 #define bch2_bio_alloc_pages(_bio, _size, _gfp) \
539 alloc_hooks(bch2_bio_alloc_pages_noprof(_bio, _size, _gfp))
541 static inline sector_t bdev_sectors(struct block_device *bdev)
543 return bdev->bd_inode->i_size >> 9;
546 #define closure_bio_submit(bio, cl) \
552 #define kthread_wait(cond) \
557 set_current_state(TASK_INTERRUPTIBLE); \
558 if (kthread_should_stop()) { \
568 set_current_state(TASK_RUNNING); \
572 #define kthread_wait_freezable(cond) \
576 set_current_state(TASK_INTERRUPTIBLE); \
577 if (kthread_should_stop()) { \
588 set_current_state(TASK_RUNNING); \
592 size_t bch2_rand_range(size_t);
594 void memcpy_to_bio(struct bio *, struct bvec_iter, const void *);
595 void memcpy_from_bio(void *, struct bio *, struct bvec_iter);
597 static inline void memcpy_u64s_small(void *dst, const void *src,
607 static inline void __memcpy_u64s(void *dst, const void *src,
613 asm volatile("rep ; movsq"
614 : "=&c" (d0), "=&D" (d1), "=&S" (d2)
615 : "0" (u64s), "1" (dst), "2" (src)
626 static inline void memcpy_u64s(void *dst, const void *src,
629 EBUG_ON(!(dst >= src + u64s * sizeof(u64) ||
630 dst + u64s * sizeof(u64) <= src));
632 __memcpy_u64s(dst, src, u64s);
635 static inline void __memmove_u64s_down(void *dst, const void *src,
638 __memcpy_u64s(dst, src, u64s);
641 static inline void memmove_u64s_down(void *dst, const void *src,
646 __memmove_u64s_down(dst, src, u64s);
649 static inline void __memmove_u64s_down_small(void *dst, const void *src,
652 memcpy_u64s_small(dst, src, u64s);
655 static inline void memmove_u64s_down_small(void *dst, const void *src,
660 __memmove_u64s_down_small(dst, src, u64s);
663 static inline void __memmove_u64s_up_small(void *_dst, const void *_src,
666 u64 *dst = (u64 *) _dst + u64s;
667 u64 *src = (u64 *) _src + u64s;
673 static inline void memmove_u64s_up_small(void *dst, const void *src,
678 __memmove_u64s_up_small(dst, src, u64s);
681 static inline void __memmove_u64s_up(void *_dst, const void *_src,
684 u64 *dst = (u64 *) _dst + u64s - 1;
685 u64 *src = (u64 *) _src + u64s - 1;
690 asm volatile("std ;\n"
693 : "=&c" (d0), "=&D" (d1), "=&S" (d2)
694 : "0" (u64s), "1" (dst), "2" (src)
702 static inline void memmove_u64s_up(void *dst, const void *src,
707 __memmove_u64s_up(dst, src, u64s);
710 static inline void memmove_u64s(void *dst, const void *src,
714 __memmove_u64s_down(dst, src, u64s);
716 __memmove_u64s_up(dst, src, u64s);
719 /* Set the last few bytes up to a u64 boundary given an offset into a buffer. */
720 static inline void memset_u64s_tail(void *s, int c, unsigned bytes)
722 unsigned rem = round_up(bytes, sizeof(u64)) - bytes;
724 memset(s + bytes, c, rem);
727 void sort_cmp_size(void *base, size_t num, size_t size,
728 int (*cmp_func)(const void *, const void *, size_t),
729 void (*swap_func)(void *, void *, size_t));
731 /* just the memmove, doesn't update @_nr */
732 #define __array_insert_item(_array, _nr, _pos) \
733 memmove(&(_array)[(_pos) + 1], \
735 sizeof((_array)[0]) * ((_nr) - (_pos)))
737 #define array_insert_item(_array, _nr, _pos, _new_item) \
739 __array_insert_item(_array, _nr, _pos); \
741 (_array)[(_pos)] = (_new_item); \
744 #define array_remove_items(_array, _nr, _pos, _nr_to_remove) \
746 (_nr) -= (_nr_to_remove); \
747 memmove(&(_array)[(_pos)], \
748 &(_array)[(_pos) + (_nr_to_remove)], \
749 sizeof((_array)[0]) * ((_nr) - (_pos))); \
752 #define array_remove_item(_array, _nr, _pos) \
753 array_remove_items(_array, _nr, _pos, 1)
755 static inline void __move_gap(void *array, size_t element_size,
756 size_t nr, size_t size,
757 size_t old_gap, size_t new_gap)
759 size_t gap_end = old_gap + size - nr;
761 if (new_gap < old_gap) {
762 size_t move = old_gap - new_gap;
764 memmove(array + element_size * (gap_end - move),
765 array + element_size * (old_gap - move),
766 element_size * move);
767 } else if (new_gap > old_gap) {
768 size_t move = new_gap - old_gap;
770 memmove(array + element_size * old_gap,
771 array + element_size * gap_end,
772 element_size * move);
776 /* Move the gap in a gap buffer: */
777 #define move_gap(_array, _nr, _size, _old_gap, _new_gap) \
778 __move_gap(_array, sizeof(_array[0]), _nr, _size, _old_gap, _new_gap)
780 #define bubble_sort(_base, _nr, _cmp) \
783 bool _swapped = true; \
785 for (_end = (ssize_t) (_nr) - 1; _end > 0 && _swapped; --_end) {\
787 for (_i = 0; _i < _end; _i++) \
788 if (_cmp((_base)[_i], (_base)[_i + 1]) > 0) { \
789 swap((_base)[_i], (_base)[_i + 1]); \
795 static inline u64 percpu_u64_get(u64 __percpu *src)
800 for_each_possible_cpu(cpu)
801 ret += *per_cpu_ptr(src, cpu);
805 static inline void percpu_u64_set(u64 __percpu *dst, u64 src)
809 for_each_possible_cpu(cpu)
810 *per_cpu_ptr(dst, cpu) = 0;
811 this_cpu_write(*dst, src);
814 static inline void acc_u64s(u64 *acc, const u64 *src, unsigned nr)
818 for (i = 0; i < nr; i++)
822 static inline void acc_u64s_percpu(u64 *acc, const u64 __percpu *src,
827 for_each_possible_cpu(cpu)
828 acc_u64s(acc, per_cpu_ptr(src, cpu), nr);
831 static inline void percpu_memset(void __percpu *p, int c, size_t bytes)
835 for_each_possible_cpu(cpu)
836 memset(per_cpu_ptr(p, cpu), c, bytes);
839 u64 *bch2_acc_percpu_u64s(u64 __percpu *, unsigned);
841 #define cmp_int(l, r) ((l > r) - (l < r))
843 static inline int u8_cmp(u8 l, u8 r)
845 return cmp_int(l, r);
848 static inline int cmp_le32(__le32 l, __le32 r)
850 return cmp_int(le32_to_cpu(l), le32_to_cpu(r));
853 #include <linux/uuid.h>
855 #endif /* _BCACHEFS_UTIL_H */