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"
24 #include "time_stats.h"
28 #ifdef CONFIG_BCACHEFS_DEBUG
29 #define EBUG_ON(cond) BUG_ON(cond)
34 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
35 #define CPU_BIG_ENDIAN 0
36 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
37 #define CPU_BIG_ENDIAN 1
42 #define type_is_exact(_val, _type) \
43 __builtin_types_compatible_p(typeof(_val), _type)
45 #define type_is(_val, _type) \
46 (__builtin_types_compatible_p(typeof(_val), _type) || \
47 __builtin_types_compatible_p(typeof(_val), const _type))
49 /* Userspace doesn't align allocations as nicely as the kernel allocators: */
50 static inline size_t buf_pages(void *p, size_t len)
52 return DIV_ROUND_UP(len +
53 ((unsigned long) p & (PAGE_SIZE - 1)),
63 #define DECLARE_HEAP(type, name) HEAP(type) name
65 #define init_heap(heap, _size, gfp) \
68 (heap)->size = (_size); \
69 (heap)->data = kvmalloc((heap)->size * sizeof((heap)->data[0]),\
73 #define free_heap(heap) \
75 kvfree((heap)->data); \
76 (heap)->data = NULL; \
79 #define heap_set_backpointer(h, i, _fn) \
81 void (*fn)(typeof(h), size_t) = _fn; \
86 #define heap_swap(h, i, j, set_backpointer) \
88 swap((h)->data[i], (h)->data[j]); \
89 heap_set_backpointer(h, i, set_backpointer); \
90 heap_set_backpointer(h, j, set_backpointer); \
93 #define heap_peek(h) \
95 EBUG_ON(!(h)->used); \
99 #define heap_full(h) ((h)->used == (h)->size)
101 #define heap_sift_down(h, i, cmp, set_backpointer) \
105 for (; _j * 2 + 1 < (h)->used; _j = _c) { \
107 if (_c + 1 < (h)->used && \
108 cmp(h, (h)->data[_c], (h)->data[_c + 1]) >= 0) \
111 if (cmp(h, (h)->data[_c], (h)->data[_j]) >= 0) \
113 heap_swap(h, _c, _j, set_backpointer); \
117 #define heap_sift_up(h, i, cmp, set_backpointer) \
120 size_t p = (i - 1) / 2; \
121 if (cmp(h, (h)->data[i], (h)->data[p]) >= 0) \
123 heap_swap(h, i, p, set_backpointer); \
128 #define __heap_add(h, d, cmp, set_backpointer) \
130 size_t _i = (h)->used++; \
132 heap_set_backpointer(h, _i, set_backpointer); \
134 heap_sift_up(h, _i, cmp, set_backpointer); \
138 #define heap_add(h, d, cmp, set_backpointer) \
140 bool _r = !heap_full(h); \
142 __heap_add(h, d, cmp, set_backpointer); \
146 #define heap_add_or_replace(h, new, cmp, set_backpointer) \
148 if (!heap_add(h, new, cmp, set_backpointer) && \
149 cmp(h, new, heap_peek(h)) >= 0) { \
150 (h)->data[0] = new; \
151 heap_set_backpointer(h, 0, set_backpointer); \
152 heap_sift_down(h, 0, cmp, set_backpointer); \
156 #define heap_del(h, i, cmp, set_backpointer) \
160 BUG_ON(_i >= (h)->used); \
162 if ((_i) < (h)->used) { \
163 heap_swap(h, _i, (h)->used, set_backpointer); \
164 heap_sift_up(h, _i, cmp, set_backpointer); \
165 heap_sift_down(h, _i, cmp, set_backpointer); \
169 #define heap_pop(h, d, cmp, set_backpointer) \
171 bool _r = (h)->used; \
173 (d) = (h)->data[0]; \
174 heap_del(h, 0, cmp, set_backpointer); \
179 #define heap_resort(heap, cmp, set_backpointer) \
182 for (_i = (ssize_t) (heap)->used / 2 - 1; _i >= 0; --_i) \
183 heap_sift_down(heap, _i, cmp, set_backpointer); \
186 #define ANYSINT_MAX(t) \
187 ((((t) 1 << (sizeof(t) * 8 - 2)) - (t) 1) * (t) 2 + (t) 1)
189 #include "printbuf.h"
191 #define prt_vprintf(_out, ...) bch2_prt_vprintf(_out, __VA_ARGS__)
192 #define prt_printf(_out, ...) bch2_prt_printf(_out, __VA_ARGS__)
193 #define printbuf_str(_buf) bch2_printbuf_str(_buf)
194 #define printbuf_exit(_buf) bch2_printbuf_exit(_buf)
196 #define printbuf_tabstops_reset(_buf) bch2_printbuf_tabstops_reset(_buf)
197 #define printbuf_tabstop_pop(_buf) bch2_printbuf_tabstop_pop(_buf)
198 #define printbuf_tabstop_push(_buf, _n) bch2_printbuf_tabstop_push(_buf, _n)
200 #define printbuf_indent_add(_out, _n) bch2_printbuf_indent_add(_out, _n)
201 #define printbuf_indent_sub(_out, _n) bch2_printbuf_indent_sub(_out, _n)
203 #define prt_newline(_out) bch2_prt_newline(_out)
204 #define prt_tab(_out) bch2_prt_tab(_out)
205 #define prt_tab_rjust(_out) bch2_prt_tab_rjust(_out)
207 #define prt_bytes_indented(...) bch2_prt_bytes_indented(__VA_ARGS__)
208 #define prt_u64(_out, _v) prt_printf(_out, "%llu", (u64) (_v))
209 #define prt_human_readable_u64(...) bch2_prt_human_readable_u64(__VA_ARGS__)
210 #define prt_human_readable_s64(...) bch2_prt_human_readable_s64(__VA_ARGS__)
211 #define prt_units_u64(...) bch2_prt_units_u64(__VA_ARGS__)
212 #define prt_units_s64(...) bch2_prt_units_s64(__VA_ARGS__)
213 #define prt_string_option(...) bch2_prt_string_option(__VA_ARGS__)
214 #define prt_bitflags(...) bch2_prt_bitflags(__VA_ARGS__)
215 #define prt_bitflags_vector(...) bch2_prt_bitflags_vector(__VA_ARGS__)
217 void bch2_pr_time_units(struct printbuf *, u64);
218 void bch2_prt_datetime(struct printbuf *, time64_t);
221 static inline void uuid_unparse_lower(u8 *uuid, char *out)
223 sprintf(out, "%pUb", uuid);
226 #include <uuid/uuid.h>
229 static inline void pr_uuid(struct printbuf *out, u8 *uuid)
233 uuid_unparse_lower(uuid, uuid_str);
234 prt_printf(out, "%s", uuid_str);
237 int bch2_strtoint_h(const char *, int *);
238 int bch2_strtouint_h(const char *, unsigned int *);
239 int bch2_strtoll_h(const char *, long long *);
240 int bch2_strtoull_h(const char *, unsigned long long *);
241 int bch2_strtou64_h(const char *, u64 *);
243 static inline int bch2_strtol_h(const char *cp, long *res)
245 #if BITS_PER_LONG == 32
246 return bch2_strtoint_h(cp, (int *) res);
248 return bch2_strtoll_h(cp, (long long *) res);
252 static inline int bch2_strtoul_h(const char *cp, long *res)
254 #if BITS_PER_LONG == 32
255 return bch2_strtouint_h(cp, (unsigned int *) res);
257 return bch2_strtoull_h(cp, (unsigned long long *) res);
261 #define strtoi_h(cp, res) \
262 ( type_is(*res, int) ? bch2_strtoint_h(cp, (void *) res)\
263 : type_is(*res, long) ? bch2_strtol_h(cp, (void *) res)\
264 : type_is(*res, long long) ? bch2_strtoll_h(cp, (void *) res)\
265 : type_is(*res, unsigned) ? bch2_strtouint_h(cp, (void *) res)\
266 : type_is(*res, unsigned long) ? bch2_strtoul_h(cp, (void *) res)\
267 : type_is(*res, unsigned long long) ? bch2_strtoull_h(cp, (void *) res)\
270 #define strtoul_safe(cp, var) \
273 int _r = kstrtoul(cp, 10, &_v); \
279 #define strtoul_safe_clamp(cp, var, min, max) \
282 int _r = kstrtoul(cp, 10, &_v); \
284 var = clamp_t(typeof(var), _v, min, max); \
288 #define strtoul_safe_restrict(cp, var, min, max) \
291 int _r = kstrtoul(cp, 10, &_v); \
292 if (!_r && _v >= min && _v <= max) \
299 #define snprint(out, var) \
301 type_is(var, int) ? "%i\n" \
302 : type_is(var, unsigned) ? "%u\n" \
303 : type_is(var, long) ? "%li\n" \
304 : type_is(var, unsigned long) ? "%lu\n" \
305 : type_is(var, s64) ? "%lli\n" \
306 : type_is(var, u64) ? "%llu\n" \
307 : type_is(var, char *) ? "%s\n" \
310 bool bch2_is_zero(const void *, size_t);
312 u64 bch2_read_flag_list(char *, const char * const[]);
314 void bch2_prt_u64_base2_nbits(struct printbuf *, u64, unsigned);
315 void bch2_prt_u64_base2(struct printbuf *, u64);
317 void bch2_print_string_as_lines(const char *prefix, const char *lines);
319 typedef DARRAY(unsigned long) bch_stacktrace;
320 int bch2_save_backtrace(bch_stacktrace *stack, struct task_struct *, unsigned, gfp_t);
321 void bch2_prt_backtrace(struct printbuf *, bch_stacktrace *);
322 int bch2_prt_task_backtrace(struct printbuf *, struct task_struct *, unsigned, gfp_t);
324 static inline void prt_bdevname(struct printbuf *out, struct block_device *bdev)
327 prt_printf(out, "%pg", bdev);
329 prt_str(out, bdev->name);
333 void bch2_time_stats_to_text(struct printbuf *, struct bch2_time_stats *);
335 #define ewma_add(ewma, val, weight) \
337 typeof(ewma) _ewma = (ewma); \
338 typeof(weight) _weight = (weight); \
340 (((_ewma << _weight) - _ewma) + (val)) >> _weight; \
343 struct bch_ratelimit {
344 /* Next time we want to do some work, in nanoseconds */
348 * Rate at which we want to do work, in units per nanosecond
349 * The units here correspond to the units passed to
350 * bch2_ratelimit_increment()
355 static inline void bch2_ratelimit_reset(struct bch_ratelimit *d)
357 d->next = local_clock();
360 u64 bch2_ratelimit_delay(struct bch_ratelimit *);
361 void bch2_ratelimit_increment(struct bch_ratelimit *, u64);
363 struct bch_pd_controller {
364 struct bch_ratelimit rate;
365 unsigned long last_update;
368 s64 smoothed_derivative;
370 unsigned p_term_inverse;
374 /* for exporting to sysfs (no effect on behavior) */
376 s64 last_proportional;
381 * If true, the rate will not increase if bch2_ratelimit_delay()
382 * is not being called often enough.
387 void bch2_pd_controller_update(struct bch_pd_controller *, s64, s64, int);
388 void bch2_pd_controller_init(struct bch_pd_controller *);
389 void bch2_pd_controller_debug_to_text(struct printbuf *, struct bch_pd_controller *);
391 #define sysfs_pd_controller_attribute(name) \
392 rw_attribute(name##_rate); \
393 rw_attribute(name##_rate_bytes); \
394 rw_attribute(name##_rate_d_term); \
395 rw_attribute(name##_rate_p_term_inverse); \
396 read_attribute(name##_rate_debug)
398 #define sysfs_pd_controller_files(name) \
399 &sysfs_##name##_rate, \
400 &sysfs_##name##_rate_bytes, \
401 &sysfs_##name##_rate_d_term, \
402 &sysfs_##name##_rate_p_term_inverse, \
403 &sysfs_##name##_rate_debug
405 #define sysfs_pd_controller_show(name, var) \
407 sysfs_hprint(name##_rate, (var)->rate.rate); \
408 sysfs_print(name##_rate_bytes, (var)->rate.rate); \
409 sysfs_print(name##_rate_d_term, (var)->d_term); \
410 sysfs_print(name##_rate_p_term_inverse, (var)->p_term_inverse); \
412 if (attr == &sysfs_##name##_rate_debug) \
413 bch2_pd_controller_debug_to_text(out, var); \
416 #define sysfs_pd_controller_store(name, var) \
418 sysfs_strtoul_clamp(name##_rate, \
419 (var)->rate.rate, 1, UINT_MAX); \
420 sysfs_strtoul_clamp(name##_rate_bytes, \
421 (var)->rate.rate, 1, UINT_MAX); \
422 sysfs_strtoul(name##_rate_d_term, (var)->d_term); \
423 sysfs_strtoul_clamp(name##_rate_p_term_inverse, \
424 (var)->p_term_inverse, 1, INT_MAX); \
427 #define container_of_or_null(ptr, type, member) \
429 typeof(ptr) _ptr = ptr; \
430 _ptr ? container_of(_ptr, type, member) : NULL; \
433 /* Does linear interpolation between powers of two */
434 static inline unsigned fract_exp_two(unsigned x, unsigned fract_bits)
436 unsigned fract = x & ~(~0 << fract_bits);
440 x += (x * fract) >> fract_bits;
445 void bch2_bio_map(struct bio *bio, void *base, size_t);
446 int bch2_bio_alloc_pages(struct bio *, size_t, gfp_t);
448 static inline sector_t bdev_sectors(struct block_device *bdev)
450 return bdev->bd_inode->i_size >> 9;
453 #define closure_bio_submit(bio, cl) \
459 #define kthread_wait(cond) \
464 set_current_state(TASK_INTERRUPTIBLE); \
465 if (kthread_should_stop()) { \
475 set_current_state(TASK_RUNNING); \
479 #define kthread_wait_freezable(cond) \
483 set_current_state(TASK_INTERRUPTIBLE); \
484 if (kthread_should_stop()) { \
495 set_current_state(TASK_RUNNING); \
499 size_t bch2_rand_range(size_t);
501 void memcpy_to_bio(struct bio *, struct bvec_iter, const void *);
502 void memcpy_from_bio(void *, struct bio *, struct bvec_iter);
504 static inline void memcpy_u64s_small(void *dst, const void *src,
514 static inline void __memcpy_u64s(void *dst, const void *src,
520 asm volatile("rep ; movsq"
521 : "=&c" (d0), "=&D" (d1), "=&S" (d2)
522 : "0" (u64s), "1" (dst), "2" (src)
533 static inline void memcpy_u64s(void *dst, const void *src,
536 EBUG_ON(!(dst >= src + u64s * sizeof(u64) ||
537 dst + u64s * sizeof(u64) <= src));
539 __memcpy_u64s(dst, src, u64s);
542 static inline void __memmove_u64s_down(void *dst, const void *src,
545 __memcpy_u64s(dst, src, u64s);
548 static inline void memmove_u64s_down(void *dst, const void *src,
553 __memmove_u64s_down(dst, src, u64s);
556 static inline void __memmove_u64s_down_small(void *dst, const void *src,
559 memcpy_u64s_small(dst, src, u64s);
562 static inline void memmove_u64s_down_small(void *dst, const void *src,
567 __memmove_u64s_down_small(dst, src, u64s);
570 static inline void __memmove_u64s_up_small(void *_dst, const void *_src,
573 u64 *dst = (u64 *) _dst + u64s;
574 u64 *src = (u64 *) _src + u64s;
580 static inline void memmove_u64s_up_small(void *dst, const void *src,
585 __memmove_u64s_up_small(dst, src, u64s);
588 static inline void __memmove_u64s_up(void *_dst, const void *_src,
591 u64 *dst = (u64 *) _dst + u64s - 1;
592 u64 *src = (u64 *) _src + u64s - 1;
597 asm volatile("std ;\n"
600 : "=&c" (d0), "=&D" (d1), "=&S" (d2)
601 : "0" (u64s), "1" (dst), "2" (src)
609 static inline void memmove_u64s_up(void *dst, const void *src,
614 __memmove_u64s_up(dst, src, u64s);
617 static inline void memmove_u64s(void *dst, const void *src,
621 __memmove_u64s_down(dst, src, u64s);
623 __memmove_u64s_up(dst, src, u64s);
626 /* Set the last few bytes up to a u64 boundary given an offset into a buffer. */
627 static inline void memset_u64s_tail(void *s, int c, unsigned bytes)
629 unsigned rem = round_up(bytes, sizeof(u64)) - bytes;
631 memset(s + bytes, c, rem);
634 void sort_cmp_size(void *base, size_t num, size_t size,
635 int (*cmp_func)(const void *, const void *, size_t),
636 void (*swap_func)(void *, void *, size_t));
638 /* just the memmove, doesn't update @_nr */
639 #define __array_insert_item(_array, _nr, _pos) \
640 memmove(&(_array)[(_pos) + 1], \
642 sizeof((_array)[0]) * ((_nr) - (_pos)))
644 #define array_insert_item(_array, _nr, _pos, _new_item) \
646 __array_insert_item(_array, _nr, _pos); \
648 (_array)[(_pos)] = (_new_item); \
651 #define array_remove_items(_array, _nr, _pos, _nr_to_remove) \
653 (_nr) -= (_nr_to_remove); \
654 memmove(&(_array)[(_pos)], \
655 &(_array)[(_pos) + (_nr_to_remove)], \
656 sizeof((_array)[0]) * ((_nr) - (_pos))); \
659 #define array_remove_item(_array, _nr, _pos) \
660 array_remove_items(_array, _nr, _pos, 1)
662 static inline void __move_gap(void *array, size_t element_size,
663 size_t nr, size_t size,
664 size_t old_gap, size_t new_gap)
666 size_t gap_end = old_gap + size - nr;
668 if (new_gap < old_gap) {
669 size_t move = old_gap - new_gap;
671 memmove(array + element_size * (gap_end - move),
672 array + element_size * (old_gap - move),
673 element_size * move);
674 } else if (new_gap > old_gap) {
675 size_t move = new_gap - old_gap;
677 memmove(array + element_size * old_gap,
678 array + element_size * gap_end,
679 element_size * move);
683 /* Move the gap in a gap buffer: */
684 #define move_gap(_d, _new_gap) \
686 BUG_ON(_new_gap > (_d)->nr); \
687 BUG_ON((_d)->gap > (_d)->nr); \
689 __move_gap((_d)->data, sizeof((_d)->data[0]), \
690 (_d)->nr, (_d)->size, (_d)->gap, _new_gap); \
691 (_d)->gap = _new_gap; \
694 #define bubble_sort(_base, _nr, _cmp) \
697 bool _swapped = true; \
699 for (_last= (ssize_t) (_nr) - 1; _last > 0 && _swapped; --_last) {\
701 for (_i = 0; _i < _last; _i++) \
702 if (_cmp((_base)[_i], (_base)[_i + 1]) > 0) { \
703 swap((_base)[_i], (_base)[_i + 1]); \
709 static inline u64 percpu_u64_get(u64 __percpu *src)
714 for_each_possible_cpu(cpu)
715 ret += *per_cpu_ptr(src, cpu);
719 static inline void percpu_u64_set(u64 __percpu *dst, u64 src)
723 for_each_possible_cpu(cpu)
724 *per_cpu_ptr(dst, cpu) = 0;
725 this_cpu_write(*dst, src);
728 static inline void acc_u64s(u64 *acc, const u64 *src, unsigned nr)
732 for (i = 0; i < nr; i++)
736 static inline void acc_u64s_percpu(u64 *acc, const u64 __percpu *src,
741 for_each_possible_cpu(cpu)
742 acc_u64s(acc, per_cpu_ptr(src, cpu), nr);
745 static inline void percpu_memset(void __percpu *p, int c, size_t bytes)
749 for_each_possible_cpu(cpu)
750 memset(per_cpu_ptr(p, cpu), c, bytes);
753 u64 *bch2_acc_percpu_u64s(u64 __percpu *, unsigned);
755 #define cmp_int(l, r) ((l > r) - (l < r))
757 static inline int u8_cmp(u8 l, u8 r)
759 return cmp_int(l, r);
762 static inline int cmp_le32(__le32 l, __le32 r)
764 return cmp_int(le32_to_cpu(l), le32_to_cpu(r));
767 #include <linux/uuid.h>
769 #define QSTR(n) { { { .len = strlen(n) } }, .name = n }
771 static inline bool qstr_eq(const struct qstr l, const struct qstr r)
773 return l.len == r.len && !memcmp(l.name, r.name, l.len);
776 void bch2_darray_str_exit(darray_str *);
777 int bch2_split_devs(const char *, darray_str *);
782 static inline int copy_to_user_errcode(void __user *to, const void *from, unsigned long n)
784 return copy_to_user(to, from, n) ? -EFAULT : 0;
788 static inline int copy_from_user_errcode(void *to, const void __user *from, unsigned long n)
790 return copy_from_user(to, from, n) ? -EFAULT : 0;
795 static inline void __set_bit_le64(size_t bit, __le64 *addr)
797 addr[bit / 64] |= cpu_to_le64(BIT_ULL(bit % 64));
800 #endif /* _BCACHEFS_UTIL_H */