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>
23 #ifdef CONFIG_BCACHEFS_DEBUG
25 #define EBUG_ON(cond) BUG_ON(cond)
26 #define atomic_dec_bug(v) BUG_ON(atomic_dec_return(v) < 0)
27 #define atomic_inc_bug(v, i) BUG_ON(atomic_inc_return(v) <= i)
28 #define atomic_sub_bug(i, v) BUG_ON(atomic_sub_return(i, v) < 0)
29 #define atomic_add_bug(i, v) BUG_ON(atomic_add_return(i, v) < 0)
30 #define atomic_long_dec_bug(v) BUG_ON(atomic_long_dec_return(v) < 0)
31 #define atomic_long_sub_bug(i, v) BUG_ON(atomic_long_sub_return(i, v) < 0)
32 #define atomic64_dec_bug(v) BUG_ON(atomic64_dec_return(v) < 0)
33 #define atomic64_inc_bug(v, i) BUG_ON(atomic64_inc_return(v) <= i)
34 #define atomic64_sub_bug(i, v) BUG_ON(atomic64_sub_return(i, v) < 0)
35 #define atomic64_add_bug(i, v) BUG_ON(atomic64_add_return(i, v) < 0)
40 #define atomic_dec_bug(v) atomic_dec(v)
41 #define atomic_inc_bug(v, i) atomic_inc(v)
42 #define atomic_sub_bug(i, v) atomic_sub(i, v)
43 #define atomic_add_bug(i, v) atomic_add(i, v)
44 #define atomic_long_dec_bug(v) atomic_long_dec(v)
45 #define atomic_long_sub_bug(i, v) atomic_long_sub(i, v)
46 #define atomic64_dec_bug(v) atomic64_dec(v)
47 #define atomic64_inc_bug(v, i) atomic64_inc(v)
48 #define atomic64_sub_bug(i, v) atomic64_sub(i, v)
49 #define atomic64_add_bug(i, v) atomic64_add(i, v)
53 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
54 #define CPU_BIG_ENDIAN 0
55 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
56 #define CPU_BIG_ENDIAN 1
61 #define type_is_exact(_val, _type) \
62 __builtin_types_compatible_p(typeof(_val), _type)
64 #define type_is(_val, _type) \
65 (__builtin_types_compatible_p(typeof(_val), _type) || \
66 __builtin_types_compatible_p(typeof(_val), const _type))
68 /* Userspace doesn't align allocations as nicely as the kernel allocators: */
69 static inline size_t buf_pages(void *p, size_t len)
71 return DIV_ROUND_UP(len +
72 ((unsigned long) p & (PAGE_SIZE - 1)),
76 static inline void vpfree(void *p, size_t size)
78 if (is_vmalloc_addr(p))
81 free_pages((unsigned long) p, get_order(size));
84 static inline void *vpmalloc(size_t size, gfp_t gfp_mask)
86 return (void *) __get_free_pages(gfp_mask|__GFP_NOWARN,
88 __vmalloc(size, gfp_mask);
91 static inline void kvpfree(void *p, size_t size)
99 static inline void *kvpmalloc(size_t size, gfp_t gfp_mask)
101 return size < PAGE_SIZE
102 ? kmalloc(size, gfp_mask)
103 : vpmalloc(size, gfp_mask);
106 int mempool_init_kvpmalloc_pool(mempool_t *, int, size_t);
114 #define DECLARE_HEAP(type, name) HEAP(type) name
116 #define init_heap(heap, _size, gfp) \
119 (heap)->size = (_size); \
120 (heap)->data = kvpmalloc((heap)->size * sizeof((heap)->data[0]),\
124 #define free_heap(heap) \
126 kvpfree((heap)->data, (heap)->size * sizeof((heap)->data[0])); \
127 (heap)->data = NULL; \
130 #define heap_set_backpointer(h, i, _fn) \
132 void (*fn)(typeof(h), size_t) = _fn; \
137 #define heap_swap(h, i, j, set_backpointer) \
139 swap((h)->data[i], (h)->data[j]); \
140 heap_set_backpointer(h, i, set_backpointer); \
141 heap_set_backpointer(h, j, set_backpointer); \
144 #define heap_peek(h) \
146 EBUG_ON(!(h)->used); \
150 #define heap_full(h) ((h)->used == (h)->size)
152 #define heap_sift_down(h, i, cmp, set_backpointer) \
156 for (; _j * 2 + 1 < (h)->used; _j = _c) { \
158 if (_c + 1 < (h)->used && \
159 cmp(h, (h)->data[_c], (h)->data[_c + 1]) >= 0) \
162 if (cmp(h, (h)->data[_c], (h)->data[_j]) >= 0) \
164 heap_swap(h, _c, _j, set_backpointer); \
168 #define heap_sift_up(h, i, cmp, set_backpointer) \
171 size_t p = (i - 1) / 2; \
172 if (cmp(h, (h)->data[i], (h)->data[p]) >= 0) \
174 heap_swap(h, i, p, set_backpointer); \
179 #define __heap_add(h, d, cmp, set_backpointer) \
181 size_t _i = (h)->used++; \
183 heap_set_backpointer(h, _i, set_backpointer); \
185 heap_sift_up(h, _i, cmp, set_backpointer); \
189 #define heap_add(h, d, cmp, set_backpointer) \
191 bool _r = !heap_full(h); \
193 __heap_add(h, d, cmp, set_backpointer); \
197 #define heap_add_or_replace(h, new, cmp, set_backpointer) \
199 if (!heap_add(h, new, cmp, set_backpointer) && \
200 cmp(h, new, heap_peek(h)) >= 0) { \
201 (h)->data[0] = new; \
202 heap_set_backpointer(h, 0, set_backpointer); \
203 heap_sift_down(h, 0, cmp, set_backpointer); \
207 #define heap_del(h, i, cmp, set_backpointer) \
211 BUG_ON(_i >= (h)->used); \
213 heap_swap(h, _i, (h)->used, set_backpointer); \
214 heap_sift_up(h, _i, cmp, set_backpointer); \
215 heap_sift_down(h, _i, cmp, set_backpointer); \
218 #define heap_pop(h, d, cmp, set_backpointer) \
220 bool _r = (h)->used; \
222 (d) = (h)->data[0]; \
223 heap_del(h, 0, cmp, set_backpointer); \
228 #define heap_resort(heap, cmp, set_backpointer) \
231 for (_i = (ssize_t) (heap)->used / 2 - 1; _i >= 0; --_i) \
232 heap_sift_down(heap, _i, cmp, set_backpointer); \
235 #define ANYSINT_MAX(t) \
236 ((((t) 1 << (sizeof(t) * 8 - 2)) - (t) 1) * (t) 2 + (t) 1)
238 enum printbuf_units {
240 PRINTBUF_UNITS_BYTES,
241 PRINTBUF_UNITS_HUMAN_READABLE,
248 unsigned last_newline;
251 enum printbuf_units units:8;
253 bool allocation_failure:1;
258 #define PRINTBUF ((struct printbuf) { NULL })
260 static inline void printbuf_exit(struct printbuf *buf)
263 buf->buf = ERR_PTR(-EINTR); /* poison value */
266 static inline void printbuf_reset(struct printbuf *buf)
269 buf->last_newline = 0;
275 static inline size_t printbuf_remaining(struct printbuf *buf)
277 return buf->size - buf->pos;
280 static inline size_t printbuf_linelen(struct printbuf *buf)
282 return buf->pos - buf->last_newline;
285 void bch2_pr_buf(struct printbuf *out, const char *fmt, ...);
287 #define pr_buf(_out, ...) bch2_pr_buf(_out, __VA_ARGS__)
289 static inline void pr_char(struct printbuf *out, char c)
291 bch2_pr_buf(out, "%c", c);
294 static inline void pr_indent_push(struct printbuf *buf, unsigned spaces)
296 buf->indent += spaces;
301 static inline void pr_indent_pop(struct printbuf *buf, unsigned spaces)
303 buf->indent -= spaces;
306 static inline void pr_newline(struct printbuf *buf)
312 buf->last_newline = buf->pos;
314 for (i = 0; i < buf->indent; i++)
317 buf->last_field = buf->pos;
321 static inline void pr_tab(struct printbuf *buf)
323 BUG_ON(buf->tabstop > ARRAY_SIZE(buf->tabstops));
325 while (printbuf_remaining(buf) > 1 &&
326 printbuf_linelen(buf) < buf->tabstops[buf->tabstop])
329 buf->last_field = buf->pos;
333 static inline void pr_tab_rjust(struct printbuf *buf)
335 ssize_t shift = min_t(ssize_t, buf->tabstops[buf->tabstop] -
336 printbuf_linelen(buf),
337 printbuf_remaining(buf));
338 ssize_t move = min_t(ssize_t, buf->pos - buf->last_field,
339 printbuf_remaining(buf) - shift);
341 BUG_ON(buf->tabstop > ARRAY_SIZE(buf->tabstops));
344 memmove(buf->buf + buf->last_field + shift,
345 buf->buf + buf->last_field,
347 memset(buf->buf + buf->last_field, ' ', shift);
349 buf->buf[buf->pos] = 0;
352 buf->last_field = buf->pos;
356 void bch2_pr_units(struct printbuf *, s64, s64);
357 #define pr_units(...) bch2_pr_units(__VA_ARGS__)
359 static inline void pr_sectors(struct printbuf *out, u64 v)
361 bch2_pr_units(out, v, v << 9);
365 static inline void pr_time(struct printbuf *out, u64 time)
367 pr_buf(out, "%llu", time);
371 static inline void pr_time(struct printbuf *out, u64 _time)
375 struct tm *tm = localtime(&time);
376 size_t err = strftime(time_str, sizeof(time_str), "%c", tm);
378 pr_buf(out, "(formatting error)");
380 pr_buf(out, "%s", time_str);
385 static inline void uuid_unparse_lower(u8 *uuid, char *out)
387 sprintf(out, "%plU", uuid);
390 #include <uuid/uuid.h>
393 static inline void pr_uuid(struct printbuf *out, u8 *uuid)
397 uuid_unparse_lower(uuid, uuid_str);
398 pr_buf(out, uuid_str);
401 int bch2_strtoint_h(const char *, int *);
402 int bch2_strtouint_h(const char *, unsigned int *);
403 int bch2_strtoll_h(const char *, long long *);
404 int bch2_strtoull_h(const char *, unsigned long long *);
405 int bch2_strtou64_h(const char *, u64 *);
407 static inline int bch2_strtol_h(const char *cp, long *res)
409 #if BITS_PER_LONG == 32
410 return bch2_strtoint_h(cp, (int *) res);
412 return bch2_strtoll_h(cp, (long long *) res);
416 static inline int bch2_strtoul_h(const char *cp, long *res)
418 #if BITS_PER_LONG == 32
419 return bch2_strtouint_h(cp, (unsigned int *) res);
421 return bch2_strtoull_h(cp, (unsigned long long *) res);
425 #define strtoi_h(cp, res) \
426 ( type_is(*res, int) ? bch2_strtoint_h(cp, (void *) res)\
427 : type_is(*res, long) ? bch2_strtol_h(cp, (void *) res)\
428 : type_is(*res, long long) ? bch2_strtoll_h(cp, (void *) res)\
429 : type_is(*res, unsigned) ? bch2_strtouint_h(cp, (void *) res)\
430 : type_is(*res, unsigned long) ? bch2_strtoul_h(cp, (void *) res)\
431 : type_is(*res, unsigned long long) ? bch2_strtoull_h(cp, (void *) res)\
434 #define strtoul_safe(cp, var) \
437 int _r = kstrtoul(cp, 10, &_v); \
443 #define strtoul_safe_clamp(cp, var, min, max) \
446 int _r = kstrtoul(cp, 10, &_v); \
448 var = clamp_t(typeof(var), _v, min, max); \
452 #define strtoul_safe_restrict(cp, var, min, max) \
455 int _r = kstrtoul(cp, 10, &_v); \
456 if (!_r && _v >= min && _v <= max) \
463 #define snprint(out, var) \
465 type_is(var, int) ? "%i\n" \
466 : type_is(var, unsigned) ? "%u\n" \
467 : type_is(var, long) ? "%li\n" \
468 : type_is(var, unsigned long) ? "%lu\n" \
469 : type_is(var, s64) ? "%lli\n" \
470 : type_is(var, u64) ? "%llu\n" \
471 : type_is(var, char *) ? "%s\n" \
474 void bch2_hprint(struct printbuf *, s64);
476 bool bch2_is_zero(const void *, size_t);
478 void bch2_string_opt_to_text(struct printbuf *,
479 const char * const [], size_t);
481 void bch2_flags_to_text(struct printbuf *, const char * const[], u64);
482 u64 bch2_read_flag_list(char *, const char * const[]);
484 #define NR_QUANTILES 15
485 #define QUANTILE_IDX(i) inorder_to_eytzinger0(i, NR_QUANTILES)
486 #define QUANTILE_FIRST eytzinger0_first(NR_QUANTILES)
487 #define QUANTILE_LAST eytzinger0_last(NR_QUANTILES)
490 struct quantile_entry {
493 } entries[NR_QUANTILES];
496 struct time_stat_buffer {
498 struct time_stat_buffer_entry {
507 /* all fields are in nanoseconds */
508 u64 average_duration;
509 u64 average_frequency;
512 struct quantiles quantiles;
514 struct time_stat_buffer __percpu *buffer;
517 void __bch2_time_stats_update(struct time_stats *stats, u64, u64);
519 static inline void bch2_time_stats_update(struct time_stats *stats, u64 start)
521 __bch2_time_stats_update(stats, start, local_clock());
524 void bch2_time_stats_to_text(struct printbuf *, struct time_stats *);
526 void bch2_time_stats_exit(struct time_stats *);
527 void bch2_time_stats_init(struct time_stats *);
529 #define ewma_add(ewma, val, weight) \
531 typeof(ewma) _ewma = (ewma); \
532 typeof(weight) _weight = (weight); \
534 (((_ewma << _weight) - _ewma) + (val)) >> _weight; \
537 struct bch_ratelimit {
538 /* Next time we want to do some work, in nanoseconds */
542 * Rate at which we want to do work, in units per nanosecond
543 * The units here correspond to the units passed to
544 * bch2_ratelimit_increment()
549 static inline void bch2_ratelimit_reset(struct bch_ratelimit *d)
551 d->next = local_clock();
554 u64 bch2_ratelimit_delay(struct bch_ratelimit *);
555 void bch2_ratelimit_increment(struct bch_ratelimit *, u64);
557 struct bch_pd_controller {
558 struct bch_ratelimit rate;
559 unsigned long last_update;
562 s64 smoothed_derivative;
564 unsigned p_term_inverse;
568 /* for exporting to sysfs (no effect on behavior) */
570 s64 last_proportional;
574 /* If true, the rate will not increase if bch2_ratelimit_delay()
575 * is not being called often enough. */
579 void bch2_pd_controller_update(struct bch_pd_controller *, s64, s64, int);
580 void bch2_pd_controller_init(struct bch_pd_controller *);
581 void bch2_pd_controller_debug_to_text(struct printbuf *, struct bch_pd_controller *);
583 #define sysfs_pd_controller_attribute(name) \
584 rw_attribute(name##_rate); \
585 rw_attribute(name##_rate_bytes); \
586 rw_attribute(name##_rate_d_term); \
587 rw_attribute(name##_rate_p_term_inverse); \
588 read_attribute(name##_rate_debug)
590 #define sysfs_pd_controller_files(name) \
591 &sysfs_##name##_rate, \
592 &sysfs_##name##_rate_bytes, \
593 &sysfs_##name##_rate_d_term, \
594 &sysfs_##name##_rate_p_term_inverse, \
595 &sysfs_##name##_rate_debug
597 #define sysfs_pd_controller_show(name, var) \
599 sysfs_hprint(name##_rate, (var)->rate.rate); \
600 sysfs_print(name##_rate_bytes, (var)->rate.rate); \
601 sysfs_print(name##_rate_d_term, (var)->d_term); \
602 sysfs_print(name##_rate_p_term_inverse, (var)->p_term_inverse); \
604 if (attr == &sysfs_##name##_rate_debug) \
605 bch2_pd_controller_debug_to_text(out, var); \
608 #define sysfs_pd_controller_store(name, var) \
610 sysfs_strtoul_clamp(name##_rate, \
611 (var)->rate.rate, 1, UINT_MAX); \
612 sysfs_strtoul_clamp(name##_rate_bytes, \
613 (var)->rate.rate, 1, UINT_MAX); \
614 sysfs_strtoul(name##_rate_d_term, (var)->d_term); \
615 sysfs_strtoul_clamp(name##_rate_p_term_inverse, \
616 (var)->p_term_inverse, 1, INT_MAX); \
619 #define container_of_or_null(ptr, type, member) \
621 typeof(ptr) _ptr = ptr; \
622 _ptr ? container_of(_ptr, type, member) : NULL; \
625 /* Does linear interpolation between powers of two */
626 static inline unsigned fract_exp_two(unsigned x, unsigned fract_bits)
628 unsigned fract = x & ~(~0 << fract_bits);
632 x += (x * fract) >> fract_bits;
637 void bch2_bio_map(struct bio *bio, void *base, size_t);
638 int bch2_bio_alloc_pages(struct bio *, size_t, gfp_t);
640 static inline sector_t bdev_sectors(struct block_device *bdev)
642 return bdev->bd_inode->i_size >> 9;
645 #define closure_bio_submit(bio, cl) \
651 #define kthread_wait_freezable(cond) \
655 set_current_state(TASK_INTERRUPTIBLE); \
656 if (kthread_should_stop()) { \
667 set_current_state(TASK_RUNNING); \
671 size_t bch2_rand_range(size_t);
673 void memcpy_to_bio(struct bio *, struct bvec_iter, const void *);
674 void memcpy_from_bio(void *, struct bio *, struct bvec_iter);
676 static inline void memcpy_u64s_small(void *dst, const void *src,
686 static inline void __memcpy_u64s(void *dst, const void *src,
691 asm volatile("rep ; movsq"
692 : "=&c" (d0), "=&D" (d1), "=&S" (d2)
693 : "0" (u64s), "1" (dst), "2" (src)
704 static inline void memcpy_u64s(void *dst, const void *src,
707 EBUG_ON(!(dst >= src + u64s * sizeof(u64) ||
708 dst + u64s * sizeof(u64) <= src));
710 __memcpy_u64s(dst, src, u64s);
713 static inline void __memmove_u64s_down(void *dst, const void *src,
716 __memcpy_u64s(dst, src, u64s);
719 static inline void memmove_u64s_down(void *dst, const void *src,
724 __memmove_u64s_down(dst, src, u64s);
727 static inline void __memmove_u64s_up_small(void *_dst, const void *_src,
730 u64 *dst = (u64 *) _dst + u64s;
731 u64 *src = (u64 *) _src + u64s;
737 static inline void memmove_u64s_up_small(void *dst, const void *src,
742 __memmove_u64s_up_small(dst, src, u64s);
745 static inline void __memmove_u64s_up(void *_dst, const void *_src,
748 u64 *dst = (u64 *) _dst + u64s - 1;
749 u64 *src = (u64 *) _src + u64s - 1;
753 asm volatile("std ;\n"
756 : "=&c" (d0), "=&D" (d1), "=&S" (d2)
757 : "0" (u64s), "1" (dst), "2" (src)
765 static inline void memmove_u64s_up(void *dst, const void *src,
770 __memmove_u64s_up(dst, src, u64s);
773 static inline void memmove_u64s(void *dst, const void *src,
777 __memmove_u64s_down(dst, src, u64s);
779 __memmove_u64s_up(dst, src, u64s);
782 /* Set the last few bytes up to a u64 boundary given an offset into a buffer. */
783 static inline void memset_u64s_tail(void *s, int c, unsigned bytes)
785 unsigned rem = round_up(bytes, sizeof(u64)) - bytes;
787 memset(s + bytes, c, rem);
790 void sort_cmp_size(void *base, size_t num, size_t size,
791 int (*cmp_func)(const void *, const void *, size_t),
792 void (*swap_func)(void *, void *, size_t));
794 /* just the memmove, doesn't update @_nr */
795 #define __array_insert_item(_array, _nr, _pos) \
796 memmove(&(_array)[(_pos) + 1], \
798 sizeof((_array)[0]) * ((_nr) - (_pos)))
800 #define array_insert_item(_array, _nr, _pos, _new_item) \
802 __array_insert_item(_array, _nr, _pos); \
804 (_array)[(_pos)] = (_new_item); \
807 #define array_remove_items(_array, _nr, _pos, _nr_to_remove) \
809 (_nr) -= (_nr_to_remove); \
810 memmove(&(_array)[(_pos)], \
811 &(_array)[(_pos) + (_nr_to_remove)], \
812 sizeof((_array)[0]) * ((_nr) - (_pos))); \
815 #define array_remove_item(_array, _nr, _pos) \
816 array_remove_items(_array, _nr, _pos, 1)
818 #define bubble_sort(_base, _nr, _cmp) \
821 bool _swapped = true; \
823 for (_end = (ssize_t) (_nr) - 1; _end > 0 && _swapped; --_end) {\
825 for (_i = 0; _i < _end; _i++) \
826 if (_cmp((_base)[_i], (_base)[_i + 1]) > 0) { \
827 swap((_base)[_i], (_base)[_i + 1]); \
833 static inline u64 percpu_u64_get(u64 __percpu *src)
838 for_each_possible_cpu(cpu)
839 ret += *per_cpu_ptr(src, cpu);
843 static inline void percpu_u64_set(u64 __percpu *dst, u64 src)
847 for_each_possible_cpu(cpu)
848 *per_cpu_ptr(dst, cpu) = 0;
849 this_cpu_write(*dst, src);
852 static inline void acc_u64s(u64 *acc, const u64 *src, unsigned nr)
856 for (i = 0; i < nr; i++)
860 static inline void acc_u64s_percpu(u64 *acc, const u64 __percpu *src,
865 for_each_possible_cpu(cpu)
866 acc_u64s(acc, per_cpu_ptr(src, cpu), nr);
869 static inline void percpu_memset(void __percpu *p, int c, size_t bytes)
873 for_each_possible_cpu(cpu)
874 memset(per_cpu_ptr(p, cpu), c, bytes);
877 u64 *bch2_acc_percpu_u64s(u64 __percpu *, unsigned);
879 #define cmp_int(l, r) ((l > r) - (l < r))
881 static inline int u8_cmp(u8 l, u8 r)
883 return cmp_int(l, r);
886 #endif /* _BCACHEFS_UTIL_H */