1 /* SPDX-License-Identifier: GPL-2.0 u*/
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/printbuf.h>
15 #include <linux/percpu.h>
16 #include <linux/preempt.h>
17 #include <linux/ratelimit.h>
18 #include <linux/slab.h>
19 #include <linux/vmalloc.h>
20 #include <linux/workqueue.h>
24 #ifdef CONFIG_BCACHEFS_DEBUG
26 #define EBUG_ON(cond) BUG_ON(cond)
27 #define atomic_dec_bug(v) BUG_ON(atomic_dec_return(v) < 0)
28 #define atomic_inc_bug(v, i) BUG_ON(atomic_inc_return(v) <= i)
29 #define atomic_sub_bug(i, v) BUG_ON(atomic_sub_return(i, v) < 0)
30 #define atomic_add_bug(i, v) BUG_ON(atomic_add_return(i, v) < 0)
31 #define atomic_long_dec_bug(v) BUG_ON(atomic_long_dec_return(v) < 0)
32 #define atomic_long_sub_bug(i, v) BUG_ON(atomic_long_sub_return(i, v) < 0)
33 #define atomic64_dec_bug(v) BUG_ON(atomic64_dec_return(v) < 0)
34 #define atomic64_inc_bug(v, i) BUG_ON(atomic64_inc_return(v) <= i)
35 #define atomic64_sub_bug(i, v) BUG_ON(atomic64_sub_return(i, v) < 0)
36 #define atomic64_add_bug(i, v) BUG_ON(atomic64_add_return(i, v) < 0)
41 #define atomic_dec_bug(v) atomic_dec(v)
42 #define atomic_inc_bug(v, i) atomic_inc(v)
43 #define atomic_sub_bug(i, v) atomic_sub(i, v)
44 #define atomic_add_bug(i, v) atomic_add(i, v)
45 #define atomic_long_dec_bug(v) atomic_long_dec(v)
46 #define atomic_long_sub_bug(i, v) atomic_long_sub(i, v)
47 #define atomic64_dec_bug(v) atomic64_dec(v)
48 #define atomic64_inc_bug(v, i) atomic64_inc(v)
49 #define atomic64_sub_bug(i, v) atomic64_sub(i, v)
50 #define atomic64_add_bug(i, v) atomic64_add(i, v)
54 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
55 #define CPU_BIG_ENDIAN 0
56 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
57 #define CPU_BIG_ENDIAN 1
62 #define type_is_exact(_val, _type) \
63 __builtin_types_compatible_p(typeof(_val), _type)
65 #define type_is(_val, _type) \
66 (__builtin_types_compatible_p(typeof(_val), _type) || \
67 __builtin_types_compatible_p(typeof(_val), const _type))
69 /* Userspace doesn't align allocations as nicely as the kernel allocators: */
70 static inline size_t buf_pages(void *p, size_t len)
72 return DIV_ROUND_UP(len +
73 ((unsigned long) p & (PAGE_SIZE - 1)),
77 static inline void vpfree(void *p, size_t size)
79 if (is_vmalloc_addr(p))
82 free_pages((unsigned long) p, get_order(size));
85 static inline void *vpmalloc(size_t size, gfp_t gfp_mask)
87 return (void *) __get_free_pages(gfp_mask|__GFP_NOWARN,
89 __vmalloc(size, gfp_mask);
92 static inline void kvpfree(void *p, size_t size)
100 static inline void *kvpmalloc(size_t size, gfp_t gfp_mask)
102 return size < PAGE_SIZE
103 ? kmalloc(size, gfp_mask)
104 : vpmalloc(size, gfp_mask);
107 int mempool_init_kvpmalloc_pool(mempool_t *, int, size_t);
115 #define DECLARE_HEAP(type, name) HEAP(type) name
117 #define init_heap(heap, _size, gfp) \
120 (heap)->size = (_size); \
121 (heap)->data = kvpmalloc((heap)->size * sizeof((heap)->data[0]),\
125 #define free_heap(heap) \
127 kvpfree((heap)->data, (heap)->size * sizeof((heap)->data[0])); \
128 (heap)->data = NULL; \
131 #define heap_set_backpointer(h, i, _fn) \
133 void (*fn)(typeof(h), size_t) = _fn; \
138 #define heap_swap(h, i, j, set_backpointer) \
140 swap((h)->data[i], (h)->data[j]); \
141 heap_set_backpointer(h, i, set_backpointer); \
142 heap_set_backpointer(h, j, set_backpointer); \
145 #define heap_peek(h) \
147 EBUG_ON(!(h)->used); \
151 #define heap_full(h) ((h)->used == (h)->size)
153 #define heap_sift_down(h, i, cmp, set_backpointer) \
157 for (; _j * 2 + 1 < (h)->used; _j = _c) { \
159 if (_c + 1 < (h)->used && \
160 cmp(h, (h)->data[_c], (h)->data[_c + 1]) >= 0) \
163 if (cmp(h, (h)->data[_c], (h)->data[_j]) >= 0) \
165 heap_swap(h, _c, _j, set_backpointer); \
169 #define heap_sift_up(h, i, cmp, set_backpointer) \
172 size_t p = (i - 1) / 2; \
173 if (cmp(h, (h)->data[i], (h)->data[p]) >= 0) \
175 heap_swap(h, i, p, set_backpointer); \
180 #define __heap_add(h, d, cmp, set_backpointer) \
182 size_t _i = (h)->used++; \
184 heap_set_backpointer(h, _i, set_backpointer); \
186 heap_sift_up(h, _i, cmp, set_backpointer); \
190 #define heap_add(h, d, cmp, set_backpointer) \
192 bool _r = !heap_full(h); \
194 __heap_add(h, d, cmp, set_backpointer); \
198 #define heap_add_or_replace(h, new, cmp, set_backpointer) \
200 if (!heap_add(h, new, cmp, set_backpointer) && \
201 cmp(h, new, heap_peek(h)) >= 0) { \
202 (h)->data[0] = new; \
203 heap_set_backpointer(h, 0, set_backpointer); \
204 heap_sift_down(h, 0, cmp, set_backpointer); \
208 #define heap_del(h, i, cmp, set_backpointer) \
212 BUG_ON(_i >= (h)->used); \
214 if ((_i) < (h)->used) { \
215 heap_swap(h, _i, (h)->used, set_backpointer); \
216 heap_sift_up(h, _i, cmp, set_backpointer); \
217 heap_sift_down(h, _i, cmp, set_backpointer); \
221 #define heap_pop(h, d, cmp, set_backpointer) \
223 bool _r = (h)->used; \
225 (d) = (h)->data[0]; \
226 heap_del(h, 0, cmp, set_backpointer); \
231 #define heap_resort(heap, cmp, set_backpointer) \
234 for (_i = (ssize_t) (heap)->used / 2 - 1; _i >= 0; --_i) \
235 heap_sift_down(heap, _i, cmp, set_backpointer); \
238 #define ANYSINT_MAX(t) \
239 ((((t) 1 << (sizeof(t) * 8 - 2)) - (t) 1) * (t) 2 + (t) 1)
243 static inline void pr_time(struct printbuf *out, u64 time)
245 prt_printf(out, "%llu", time);
249 static inline void pr_time(struct printbuf *out, u64 _time)
253 struct tm *tm = localtime(&time);
254 size_t err = strftime(time_str, sizeof(time_str), "%c", tm);
256 prt_printf(out, "(formatting error)");
258 prt_printf(out, "%s", time_str);
263 static inline void uuid_unparse_lower(u8 *uuid, char *out)
265 sprintf(out, "%pUb", uuid);
268 #include <uuid/uuid.h>
271 static inline void pr_uuid(struct printbuf *out, u8 *uuid)
275 uuid_unparse_lower(uuid, uuid_str);
276 prt_printf(out, "%s", uuid_str);
279 int bch2_strtoint_h(const char *, int *);
280 int bch2_strtouint_h(const char *, unsigned int *);
281 int bch2_strtoll_h(const char *, long long *);
282 int bch2_strtoull_h(const char *, unsigned long long *);
283 int bch2_strtou64_h(const char *, u64 *);
285 static inline int bch2_strtol_h(const char *cp, long *res)
287 #if BITS_PER_LONG == 32
288 return bch2_strtoint_h(cp, (int *) res);
290 return bch2_strtoll_h(cp, (long long *) res);
294 static inline int bch2_strtoul_h(const char *cp, long *res)
296 #if BITS_PER_LONG == 32
297 return bch2_strtouint_h(cp, (unsigned int *) res);
299 return bch2_strtoull_h(cp, (unsigned long long *) res);
303 #define strtoi_h(cp, res) \
304 ( type_is(*res, int) ? bch2_strtoint_h(cp, (void *) res)\
305 : type_is(*res, long) ? bch2_strtol_h(cp, (void *) res)\
306 : type_is(*res, long long) ? bch2_strtoll_h(cp, (void *) res)\
307 : type_is(*res, unsigned) ? bch2_strtouint_h(cp, (void *) res)\
308 : type_is(*res, unsigned long) ? bch2_strtoul_h(cp, (void *) res)\
309 : type_is(*res, unsigned long long) ? bch2_strtoull_h(cp, (void *) res)\
312 #define strtoul_safe(cp, var) \
315 int _r = kstrtoul(cp, 10, &_v); \
321 #define strtoul_safe_clamp(cp, var, min, max) \
324 int _r = kstrtoul(cp, 10, &_v); \
326 var = clamp_t(typeof(var), _v, min, max); \
330 #define strtoul_safe_restrict(cp, var, min, max) \
333 int _r = kstrtoul(cp, 10, &_v); \
334 if (!_r && _v >= min && _v <= max) \
341 #define snprint(out, var) \
343 type_is(var, int) ? "%i\n" \
344 : type_is(var, unsigned) ? "%u\n" \
345 : type_is(var, long) ? "%li\n" \
346 : type_is(var, unsigned long) ? "%lu\n" \
347 : type_is(var, s64) ? "%lli\n" \
348 : type_is(var, u64) ? "%llu\n" \
349 : type_is(var, char *) ? "%s\n" \
352 bool bch2_is_zero(const void *, size_t);
354 u64 bch2_read_flag_list(char *, const char * const[]);
356 #define NR_QUANTILES 15
357 #define QUANTILE_IDX(i) inorder_to_eytzinger0(i, NR_QUANTILES)
358 #define QUANTILE_FIRST eytzinger0_first(NR_QUANTILES)
359 #define QUANTILE_LAST eytzinger0_last(NR_QUANTILES)
362 struct quantile_entry {
365 } entries[NR_QUANTILES];
368 struct time_stat_buffer {
370 struct time_stat_buffer_entry {
379 /* all fields are in nanoseconds */
380 u64 average_duration;
381 u64 average_frequency;
384 struct quantiles quantiles;
386 struct time_stat_buffer __percpu *buffer;
389 void __bch2_time_stats_update(struct time_stats *stats, u64, u64);
391 static inline void bch2_time_stats_update(struct time_stats *stats, u64 start)
393 __bch2_time_stats_update(stats, start, local_clock());
396 void bch2_time_stats_to_text(struct printbuf *, struct time_stats *);
398 void bch2_time_stats_exit(struct time_stats *);
399 void bch2_time_stats_init(struct time_stats *);
401 #define ewma_add(ewma, val, weight) \
403 typeof(ewma) _ewma = (ewma); \
404 typeof(weight) _weight = (weight); \
406 (((_ewma << _weight) - _ewma) + (val)) >> _weight; \
409 struct bch_ratelimit {
410 /* Next time we want to do some work, in nanoseconds */
414 * Rate at which we want to do work, in units per nanosecond
415 * The units here correspond to the units passed to
416 * bch2_ratelimit_increment()
421 static inline void bch2_ratelimit_reset(struct bch_ratelimit *d)
423 d->next = local_clock();
426 u64 bch2_ratelimit_delay(struct bch_ratelimit *);
427 void bch2_ratelimit_increment(struct bch_ratelimit *, u64);
429 struct bch_pd_controller {
430 struct bch_ratelimit rate;
431 unsigned long last_update;
434 s64 smoothed_derivative;
436 unsigned p_term_inverse;
440 /* for exporting to sysfs (no effect on behavior) */
442 s64 last_proportional;
446 /* If true, the rate will not increase if bch2_ratelimit_delay()
447 * is not being called often enough. */
451 void bch2_pd_controller_update(struct bch_pd_controller *, s64, s64, int);
452 void bch2_pd_controller_init(struct bch_pd_controller *);
453 void bch2_pd_controller_debug_to_text(struct printbuf *, struct bch_pd_controller *);
455 #define sysfs_pd_controller_attribute(name) \
456 rw_attribute(name##_rate); \
457 rw_attribute(name##_rate_bytes); \
458 rw_attribute(name##_rate_d_term); \
459 rw_attribute(name##_rate_p_term_inverse); \
460 read_attribute(name##_rate_debug)
462 #define sysfs_pd_controller_files(name) \
463 &sysfs_##name##_rate, \
464 &sysfs_##name##_rate_bytes, \
465 &sysfs_##name##_rate_d_term, \
466 &sysfs_##name##_rate_p_term_inverse, \
467 &sysfs_##name##_rate_debug
469 #define sysfs_pd_controller_show(name, var) \
471 sysfs_hprint(name##_rate, (var)->rate.rate); \
472 sysfs_print(name##_rate_bytes, (var)->rate.rate); \
473 sysfs_print(name##_rate_d_term, (var)->d_term); \
474 sysfs_print(name##_rate_p_term_inverse, (var)->p_term_inverse); \
476 if (attr == &sysfs_##name##_rate_debug) \
477 bch2_pd_controller_debug_to_text(out, var); \
480 #define sysfs_pd_controller_store(name, var) \
482 sysfs_strtoul_clamp(name##_rate, \
483 (var)->rate.rate, 1, UINT_MAX); \
484 sysfs_strtoul_clamp(name##_rate_bytes, \
485 (var)->rate.rate, 1, UINT_MAX); \
486 sysfs_strtoul(name##_rate_d_term, (var)->d_term); \
487 sysfs_strtoul_clamp(name##_rate_p_term_inverse, \
488 (var)->p_term_inverse, 1, INT_MAX); \
491 #define container_of_or_null(ptr, type, member) \
493 typeof(ptr) _ptr = ptr; \
494 _ptr ? container_of(_ptr, type, member) : NULL; \
497 /* Does linear interpolation between powers of two */
498 static inline unsigned fract_exp_two(unsigned x, unsigned fract_bits)
500 unsigned fract = x & ~(~0 << fract_bits);
504 x += (x * fract) >> fract_bits;
509 void bch2_bio_map(struct bio *bio, void *base, size_t);
510 int bch2_bio_alloc_pages(struct bio *, size_t, gfp_t);
512 static inline sector_t bdev_sectors(struct block_device *bdev)
514 return bdev->bd_inode->i_size >> 9;
517 #define closure_bio_submit(bio, cl) \
523 #define kthread_wait_freezable(cond) \
527 set_current_state(TASK_INTERRUPTIBLE); \
528 if (kthread_should_stop()) { \
539 set_current_state(TASK_RUNNING); \
543 size_t bch2_rand_range(size_t);
545 void memcpy_to_bio(struct bio *, struct bvec_iter, const void *);
546 void memcpy_from_bio(void *, struct bio *, struct bvec_iter);
548 static inline void memcpy_u64s_small(void *dst, const void *src,
558 static inline void __memcpy_u64s(void *dst, const void *src,
563 asm volatile("rep ; movsq"
564 : "=&c" (d0), "=&D" (d1), "=&S" (d2)
565 : "0" (u64s), "1" (dst), "2" (src)
576 static inline void memcpy_u64s(void *dst, const void *src,
579 EBUG_ON(!(dst >= src + u64s * sizeof(u64) ||
580 dst + u64s * sizeof(u64) <= src));
582 __memcpy_u64s(dst, src, u64s);
585 static inline void __memmove_u64s_down(void *dst, const void *src,
588 __memcpy_u64s(dst, src, u64s);
591 static inline void memmove_u64s_down(void *dst, const void *src,
596 __memmove_u64s_down(dst, src, u64s);
599 static inline void __memmove_u64s_up_small(void *_dst, const void *_src,
602 u64 *dst = (u64 *) _dst + u64s;
603 u64 *src = (u64 *) _src + u64s;
609 static inline void memmove_u64s_up_small(void *dst, const void *src,
614 __memmove_u64s_up_small(dst, src, u64s);
617 static inline void __memmove_u64s_up(void *_dst, const void *_src,
620 u64 *dst = (u64 *) _dst + u64s - 1;
621 u64 *src = (u64 *) _src + u64s - 1;
625 asm volatile("std ;\n"
628 : "=&c" (d0), "=&D" (d1), "=&S" (d2)
629 : "0" (u64s), "1" (dst), "2" (src)
637 static inline void memmove_u64s_up(void *dst, const void *src,
642 __memmove_u64s_up(dst, src, u64s);
645 static inline void memmove_u64s(void *dst, const void *src,
649 __memmove_u64s_down(dst, src, u64s);
651 __memmove_u64s_up(dst, src, u64s);
654 /* Set the last few bytes up to a u64 boundary given an offset into a buffer. */
655 static inline void memset_u64s_tail(void *s, int c, unsigned bytes)
657 unsigned rem = round_up(bytes, sizeof(u64)) - bytes;
659 memset(s + bytes, c, rem);
662 void sort_cmp_size(void *base, size_t num, size_t size,
663 int (*cmp_func)(const void *, const void *, size_t),
664 void (*swap_func)(void *, void *, size_t));
666 /* just the memmove, doesn't update @_nr */
667 #define __array_insert_item(_array, _nr, _pos) \
668 memmove(&(_array)[(_pos) + 1], \
670 sizeof((_array)[0]) * ((_nr) - (_pos)))
672 #define array_insert_item(_array, _nr, _pos, _new_item) \
674 __array_insert_item(_array, _nr, _pos); \
676 (_array)[(_pos)] = (_new_item); \
679 #define array_remove_items(_array, _nr, _pos, _nr_to_remove) \
681 (_nr) -= (_nr_to_remove); \
682 memmove(&(_array)[(_pos)], \
683 &(_array)[(_pos) + (_nr_to_remove)], \
684 sizeof((_array)[0]) * ((_nr) - (_pos))); \
687 #define array_remove_item(_array, _nr, _pos) \
688 array_remove_items(_array, _nr, _pos, 1)
690 static inline void __move_gap(void *array, size_t element_size,
691 size_t nr, size_t size,
692 size_t old_gap, size_t new_gap)
694 size_t gap_end = old_gap + size - nr;
696 if (new_gap < old_gap) {
697 size_t move = old_gap - new_gap;
699 memmove(array + element_size * (gap_end - move),
700 array + element_size * (old_gap - move),
701 element_size * move);
702 } else if (new_gap > old_gap) {
703 size_t move = new_gap - old_gap;
705 memmove(array + element_size * old_gap,
706 array + element_size * gap_end,
707 element_size * move);
711 /* Move the gap in a gap buffer: */
712 #define move_gap(_array, _nr, _size, _old_gap, _new_gap) \
713 __move_gap(_array, sizeof(_array[0]), _nr, _size, _old_gap, _new_gap)
715 #define bubble_sort(_base, _nr, _cmp) \
718 bool _swapped = true; \
720 for (_end = (ssize_t) (_nr) - 1; _end > 0 && _swapped; --_end) {\
722 for (_i = 0; _i < _end; _i++) \
723 if (_cmp((_base)[_i], (_base)[_i + 1]) > 0) { \
724 swap((_base)[_i], (_base)[_i + 1]); \
730 static inline u64 percpu_u64_get(u64 __percpu *src)
735 for_each_possible_cpu(cpu)
736 ret += *per_cpu_ptr(src, cpu);
740 static inline void percpu_u64_set(u64 __percpu *dst, u64 src)
744 for_each_possible_cpu(cpu)
745 *per_cpu_ptr(dst, cpu) = 0;
746 this_cpu_write(*dst, src);
749 static inline void acc_u64s(u64 *acc, const u64 *src, unsigned nr)
753 for (i = 0; i < nr; i++)
757 static inline void acc_u64s_percpu(u64 *acc, const u64 __percpu *src,
762 for_each_possible_cpu(cpu)
763 acc_u64s(acc, per_cpu_ptr(src, cpu), nr);
766 static inline void percpu_memset(void __percpu *p, int c, size_t bytes)
770 for_each_possible_cpu(cpu)
771 memset(per_cpu_ptr(p, cpu), c, bytes);
774 u64 *bch2_acc_percpu_u64s(u64 __percpu *, unsigned);
776 #define cmp_int(l, r) ((l > r) - (l < r))
778 static inline int u8_cmp(u8 l, u8 r)
780 return cmp_int(l, r);
783 #endif /* _BCACHEFS_UTIL_H */