]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/util.h
Update bcachefs sources to 3e0c5b0722 fixup! bcachefs: Btree write buffer
[bcachefs-tools-debian] / libbcachefs / util.h
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _BCACHEFS_UTIL_H
3 #define _BCACHEFS_UTIL_H
4
5 #include <linux/bio.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>
21
22 struct closure;
23
24 #ifdef CONFIG_BCACHEFS_DEBUG
25 #define EBUG_ON(cond)           BUG_ON(cond)
26 #else
27 #define EBUG_ON(cond)
28 #endif
29
30 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
31 #define CPU_BIG_ENDIAN          0
32 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
33 #define CPU_BIG_ENDIAN          1
34 #endif
35
36 /* type hackery */
37
38 #define type_is_exact(_val, _type)                                      \
39         __builtin_types_compatible_p(typeof(_val), _type)
40
41 #define type_is(_val, _type)                                            \
42         (__builtin_types_compatible_p(typeof(_val), _type) ||           \
43          __builtin_types_compatible_p(typeof(_val), const _type))
44
45 /* Userspace doesn't align allocations as nicely as the kernel allocators: */
46 static inline size_t buf_pages(void *p, size_t len)
47 {
48         return DIV_ROUND_UP(len +
49                             ((unsigned long) p & (PAGE_SIZE - 1)),
50                             PAGE_SIZE);
51 }
52
53 static inline void vpfree(void *p, size_t size)
54 {
55         if (is_vmalloc_addr(p))
56                 vfree(p);
57         else
58                 free_pages((unsigned long) p, get_order(size));
59 }
60
61 static inline void *vpmalloc(size_t size, gfp_t gfp_mask)
62 {
63         return (void *) __get_free_pages(gfp_mask|__GFP_NOWARN,
64                                          get_order(size)) ?:
65                 __vmalloc(size, gfp_mask);
66 }
67
68 static inline void kvpfree(void *p, size_t size)
69 {
70         if (size < PAGE_SIZE)
71                 kfree(p);
72         else
73                 vpfree(p, size);
74 }
75
76 static inline void *kvpmalloc(size_t size, gfp_t gfp_mask)
77 {
78         return size < PAGE_SIZE
79                 ? kmalloc(size, gfp_mask)
80                 : vpmalloc(size, gfp_mask);
81 }
82
83 int mempool_init_kvpmalloc_pool(mempool_t *, int, size_t);
84
85 #define HEAP(type)                                                      \
86 struct {                                                                \
87         size_t size, used;                                              \
88         type *data;                                                     \
89 }
90
91 #define DECLARE_HEAP(type, name) HEAP(type) name
92
93 #define init_heap(heap, _size, gfp)                                     \
94 ({                                                                      \
95         (heap)->used = 0;                                               \
96         (heap)->size = (_size);                                         \
97         (heap)->data = kvpmalloc((heap)->size * sizeof((heap)->data[0]),\
98                                  (gfp));                                \
99 })
100
101 #define free_heap(heap)                                                 \
102 do {                                                                    \
103         kvpfree((heap)->data, (heap)->size * sizeof((heap)->data[0]));  \
104         (heap)->data = NULL;                                            \
105 } while (0)
106
107 #define heap_set_backpointer(h, i, _fn)                                 \
108 do {                                                                    \
109         void (*fn)(typeof(h), size_t) = _fn;                            \
110         if (fn)                                                         \
111                 fn(h, i);                                               \
112 } while (0)
113
114 #define heap_swap(h, i, j, set_backpointer)                             \
115 do {                                                                    \
116         swap((h)->data[i], (h)->data[j]);                               \
117         heap_set_backpointer(h, i, set_backpointer);                    \
118         heap_set_backpointer(h, j, set_backpointer);                    \
119 } while (0)
120
121 #define heap_peek(h)                                                    \
122 ({                                                                      \
123         EBUG_ON(!(h)->used);                                            \
124         (h)->data[0];                                                   \
125 })
126
127 #define heap_full(h)    ((h)->used == (h)->size)
128
129 #define heap_sift_down(h, i, cmp, set_backpointer)                      \
130 do {                                                                    \
131         size_t _c, _j = i;                                              \
132                                                                         \
133         for (; _j * 2 + 1 < (h)->used; _j = _c) {                       \
134                 _c = _j * 2 + 1;                                        \
135                 if (_c + 1 < (h)->used &&                               \
136                     cmp(h, (h)->data[_c], (h)->data[_c + 1]) >= 0)      \
137                         _c++;                                           \
138                                                                         \
139                 if (cmp(h, (h)->data[_c], (h)->data[_j]) >= 0)          \
140                         break;                                          \
141                 heap_swap(h, _c, _j, set_backpointer);                  \
142         }                                                               \
143 } while (0)
144
145 #define heap_sift_up(h, i, cmp, set_backpointer)                        \
146 do {                                                                    \
147         while (i) {                                                     \
148                 size_t p = (i - 1) / 2;                                 \
149                 if (cmp(h, (h)->data[i], (h)->data[p]) >= 0)            \
150                         break;                                          \
151                 heap_swap(h, i, p, set_backpointer);                    \
152                 i = p;                                                  \
153         }                                                               \
154 } while (0)
155
156 #define __heap_add(h, d, cmp, set_backpointer)                          \
157 ({                                                                      \
158         size_t _i = (h)->used++;                                        \
159         (h)->data[_i] = d;                                              \
160         heap_set_backpointer(h, _i, set_backpointer);                   \
161                                                                         \
162         heap_sift_up(h, _i, cmp, set_backpointer);                      \
163         _i;                                                             \
164 })
165
166 #define heap_add(h, d, cmp, set_backpointer)                            \
167 ({                                                                      \
168         bool _r = !heap_full(h);                                        \
169         if (_r)                                                         \
170                 __heap_add(h, d, cmp, set_backpointer);                 \
171         _r;                                                             \
172 })
173
174 #define heap_add_or_replace(h, new, cmp, set_backpointer)               \
175 do {                                                                    \
176         if (!heap_add(h, new, cmp, set_backpointer) &&                  \
177             cmp(h, new, heap_peek(h)) >= 0) {                           \
178                 (h)->data[0] = new;                                     \
179                 heap_set_backpointer(h, 0, set_backpointer);            \
180                 heap_sift_down(h, 0, cmp, set_backpointer);             \
181         }                                                               \
182 } while (0)
183
184 #define heap_del(h, i, cmp, set_backpointer)                            \
185 do {                                                                    \
186         size_t _i = (i);                                                \
187                                                                         \
188         BUG_ON(_i >= (h)->used);                                        \
189         (h)->used--;                                                    \
190         if ((_i) < (h)->used) {                                         \
191                 heap_swap(h, _i, (h)->used, set_backpointer);           \
192                 heap_sift_up(h, _i, cmp, set_backpointer);              \
193                 heap_sift_down(h, _i, cmp, set_backpointer);            \
194         }                                                               \
195 } while (0)
196
197 #define heap_pop(h, d, cmp, set_backpointer)                            \
198 ({                                                                      \
199         bool _r = (h)->used;                                            \
200         if (_r) {                                                       \
201                 (d) = (h)->data[0];                                     \
202                 heap_del(h, 0, cmp, set_backpointer);                   \
203         }                                                               \
204         _r;                                                             \
205 })
206
207 #define heap_resort(heap, cmp, set_backpointer)                         \
208 do {                                                                    \
209         ssize_t _i;                                                     \
210         for (_i = (ssize_t) (heap)->used / 2 -  1; _i >= 0; --_i)       \
211                 heap_sift_down(heap, _i, cmp, set_backpointer);         \
212 } while (0)
213
214 #define ANYSINT_MAX(t)                                                  \
215         ((((t) 1 << (sizeof(t) * 8 - 2)) - (t) 1) * (t) 2 + (t) 1)
216
217 #include "printbuf.h"
218
219 #define prt_vprintf(_out, ...)          bch2_prt_vprintf(_out, __VA_ARGS__)
220 #define prt_printf(_out, ...)           bch2_prt_printf(_out, __VA_ARGS__)
221 #define printbuf_str(_buf)              bch2_printbuf_str(_buf)
222 #define printbuf_exit(_buf)             bch2_printbuf_exit(_buf)
223
224 #define printbuf_tabstops_reset(_buf)   bch2_printbuf_tabstops_reset(_buf)
225 #define printbuf_tabstop_pop(_buf)      bch2_printbuf_tabstop_pop(_buf)
226 #define printbuf_tabstop_push(_buf, _n) bch2_printbuf_tabstop_push(_buf, _n)
227
228 #define printbuf_indent_add(_out, _n)   bch2_printbuf_indent_add(_out, _n)
229 #define printbuf_indent_sub(_out, _n)   bch2_printbuf_indent_sub(_out, _n)
230
231 #define prt_newline(_out)               bch2_prt_newline(_out)
232 #define prt_tab(_out)                   bch2_prt_tab(_out)
233 #define prt_tab_rjust(_out)             bch2_prt_tab_rjust(_out)
234
235 #define prt_bytes_indented(...)         bch2_prt_bytes_indented(__VA_ARGS__)
236 #define prt_u64(_out, _v)               prt_printf(_out, "%llu", _v)
237 #define prt_human_readable_u64(...)     bch2_prt_human_readable_u64(__VA_ARGS__)
238 #define prt_human_readable_s64(...)     bch2_prt_human_readable_s64(__VA_ARGS__)
239 #define prt_units_u64(...)              bch2_prt_units_u64(__VA_ARGS__)
240 #define prt_units_s64(...)              bch2_prt_units_s64(__VA_ARGS__)
241 #define prt_string_option(...)          bch2_prt_string_option(__VA_ARGS__)
242 #define prt_bitflags(...)               bch2_prt_bitflags(__VA_ARGS__)
243
244 void bch2_pr_time_units(struct printbuf *, u64);
245
246 #ifdef __KERNEL__
247 static inline void pr_time(struct printbuf *out, u64 time)
248 {
249         prt_printf(out, "%llu", time);
250 }
251 #else
252 #include <time.h>
253 static inline void pr_time(struct printbuf *out, u64 _time)
254 {
255         char time_str[64];
256         time_t time = _time;
257         struct tm *tm = localtime(&time);
258         size_t err = strftime(time_str, sizeof(time_str), "%c", tm);
259         if (!err)
260                 prt_printf(out, "(formatting error)");
261         else
262                 prt_printf(out, "%s", time_str);
263 }
264 #endif
265
266 #ifdef __KERNEL__
267 static inline void uuid_unparse_lower(u8 *uuid, char *out)
268 {
269         sprintf(out, "%pUb", uuid);
270 }
271 #else
272 #include <uuid/uuid.h>
273 #endif
274
275 static inline void pr_uuid(struct printbuf *out, u8 *uuid)
276 {
277         char uuid_str[40];
278
279         uuid_unparse_lower(uuid, uuid_str);
280         prt_printf(out, "%s", uuid_str);
281 }
282
283 int bch2_strtoint_h(const char *, int *);
284 int bch2_strtouint_h(const char *, unsigned int *);
285 int bch2_strtoll_h(const char *, long long *);
286 int bch2_strtoull_h(const char *, unsigned long long *);
287 int bch2_strtou64_h(const char *, u64 *);
288
289 static inline int bch2_strtol_h(const char *cp, long *res)
290 {
291 #if BITS_PER_LONG == 32
292         return bch2_strtoint_h(cp, (int *) res);
293 #else
294         return bch2_strtoll_h(cp, (long long *) res);
295 #endif
296 }
297
298 static inline int bch2_strtoul_h(const char *cp, long *res)
299 {
300 #if BITS_PER_LONG == 32
301         return bch2_strtouint_h(cp, (unsigned int *) res);
302 #else
303         return bch2_strtoull_h(cp, (unsigned long long *) res);
304 #endif
305 }
306
307 #define strtoi_h(cp, res)                                               \
308         ( type_is(*res, int)            ? bch2_strtoint_h(cp, (void *) res)\
309         : type_is(*res, long)           ? bch2_strtol_h(cp, (void *) res)\
310         : type_is(*res, long long)      ? bch2_strtoll_h(cp, (void *) res)\
311         : type_is(*res, unsigned)       ? bch2_strtouint_h(cp, (void *) res)\
312         : type_is(*res, unsigned long)  ? bch2_strtoul_h(cp, (void *) res)\
313         : type_is(*res, unsigned long long) ? bch2_strtoull_h(cp, (void *) res)\
314         : -EINVAL)
315
316 #define strtoul_safe(cp, var)                                           \
317 ({                                                                      \
318         unsigned long _v;                                               \
319         int _r = kstrtoul(cp, 10, &_v);                                 \
320         if (!_r)                                                        \
321                 var = _v;                                               \
322         _r;                                                             \
323 })
324
325 #define strtoul_safe_clamp(cp, var, min, max)                           \
326 ({                                                                      \
327         unsigned long _v;                                               \
328         int _r = kstrtoul(cp, 10, &_v);                                 \
329         if (!_r)                                                        \
330                 var = clamp_t(typeof(var), _v, min, max);               \
331         _r;                                                             \
332 })
333
334 #define strtoul_safe_restrict(cp, var, min, max)                        \
335 ({                                                                      \
336         unsigned long _v;                                               \
337         int _r = kstrtoul(cp, 10, &_v);                                 \
338         if (!_r && _v >= min && _v <= max)                              \
339                 var = _v;                                               \
340         else                                                            \
341                 _r = -EINVAL;                                           \
342         _r;                                                             \
343 })
344
345 #define snprint(out, var)                                               \
346         prt_printf(out,                                                 \
347                    type_is(var, int)            ? "%i\n"                \
348                  : type_is(var, unsigned)       ? "%u\n"                \
349                  : type_is(var, long)           ? "%li\n"               \
350                  : type_is(var, unsigned long)  ? "%lu\n"               \
351                  : type_is(var, s64)            ? "%lli\n"              \
352                  : type_is(var, u64)            ? "%llu\n"              \
353                  : type_is(var, char *)         ? "%s\n"                \
354                  : "%i\n", var)
355
356 bool bch2_is_zero(const void *, size_t);
357
358 u64 bch2_read_flag_list(char *, const char * const[]);
359
360 void bch2_prt_u64_binary(struct printbuf *, u64, unsigned);
361
362 void bch2_print_string_as_lines(const char *prefix, const char *lines);
363 int bch2_prt_backtrace(struct printbuf *, struct task_struct *);
364
365 #define NR_QUANTILES    15
366 #define QUANTILE_IDX(i) inorder_to_eytzinger0(i, NR_QUANTILES)
367 #define QUANTILE_FIRST  eytzinger0_first(NR_QUANTILES)
368 #define QUANTILE_LAST   eytzinger0_last(NR_QUANTILES)
369
370 struct bch2_quantiles {
371         struct bch2_quantile_entry {
372                 u64     m;
373                 u64     step;
374         }               entries[NR_QUANTILES];
375 };
376
377 struct bch2_time_stat_buffer {
378         unsigned        nr;
379         struct bch2_time_stat_buffer_entry {
380                 u64     start;
381                 u64     end;
382         }               entries[32];
383 };
384
385 struct bch2_time_stats {
386         spinlock_t      lock;
387         /* all fields are in nanoseconds */
388         u64             max_duration;
389         u64             min_duration;
390         u64             max_freq;
391         u64             min_freq;
392         u64             last_event;
393         struct bch2_quantiles quantiles;
394
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;
400 };
401
402 #ifndef CONFIG_BCACHEFS_NO_LATENCY_ACCT
403 void __bch2_time_stats_update(struct bch2_time_stats *stats, u64, u64);
404 #else
405 static inline void __bch2_time_stats_update(struct bch2_time_stats *stats, u64 start, u64 end) {}
406 #endif
407
408 static inline void bch2_time_stats_update(struct bch2_time_stats *stats, u64 start)
409 {
410         __bch2_time_stats_update(stats, start, local_clock());
411 }
412
413 void bch2_time_stats_to_text(struct printbuf *, struct bch2_time_stats *);
414
415 void bch2_time_stats_exit(struct bch2_time_stats *);
416 void bch2_time_stats_init(struct bch2_time_stats *);
417
418 #define ewma_add(ewma, val, weight)                                     \
419 ({                                                                      \
420         typeof(ewma) _ewma = (ewma);                                    \
421         typeof(weight) _weight = (weight);                              \
422                                                                         \
423         (((_ewma << _weight) - _ewma) + (val)) >> _weight;              \
424 })
425
426 struct bch_ratelimit {
427         /* Next time we want to do some work, in nanoseconds */
428         u64                     next;
429
430         /*
431          * Rate at which we want to do work, in units per nanosecond
432          * The units here correspond to the units passed to
433          * bch2_ratelimit_increment()
434          */
435         unsigned                rate;
436 };
437
438 static inline void bch2_ratelimit_reset(struct bch_ratelimit *d)
439 {
440         d->next = local_clock();
441 }
442
443 u64 bch2_ratelimit_delay(struct bch_ratelimit *);
444 void bch2_ratelimit_increment(struct bch_ratelimit *, u64);
445
446 struct bch_pd_controller {
447         struct bch_ratelimit    rate;
448         unsigned long           last_update;
449
450         s64                     last_actual;
451         s64                     smoothed_derivative;
452
453         unsigned                p_term_inverse;
454         unsigned                d_smooth;
455         unsigned                d_term;
456
457         /* for exporting to sysfs (no effect on behavior) */
458         s64                     last_derivative;
459         s64                     last_proportional;
460         s64                     last_change;
461         s64                     last_target;
462
463         /* If true, the rate will not increase if bch2_ratelimit_delay()
464          * is not being called often enough. */
465         bool                    backpressure;
466 };
467
468 void bch2_pd_controller_update(struct bch_pd_controller *, s64, s64, int);
469 void bch2_pd_controller_init(struct bch_pd_controller *);
470 void bch2_pd_controller_debug_to_text(struct printbuf *, struct bch_pd_controller *);
471
472 #define sysfs_pd_controller_attribute(name)                             \
473         rw_attribute(name##_rate);                                      \
474         rw_attribute(name##_rate_bytes);                                \
475         rw_attribute(name##_rate_d_term);                               \
476         rw_attribute(name##_rate_p_term_inverse);                       \
477         read_attribute(name##_rate_debug)
478
479 #define sysfs_pd_controller_files(name)                                 \
480         &sysfs_##name##_rate,                                           \
481         &sysfs_##name##_rate_bytes,                                     \
482         &sysfs_##name##_rate_d_term,                                    \
483         &sysfs_##name##_rate_p_term_inverse,                            \
484         &sysfs_##name##_rate_debug
485
486 #define sysfs_pd_controller_show(name, var)                             \
487 do {                                                                    \
488         sysfs_hprint(name##_rate,               (var)->rate.rate);      \
489         sysfs_print(name##_rate_bytes,          (var)->rate.rate);      \
490         sysfs_print(name##_rate_d_term,         (var)->d_term);         \
491         sysfs_print(name##_rate_p_term_inverse, (var)->p_term_inverse); \
492                                                                         \
493         if (attr == &sysfs_##name##_rate_debug)                         \
494                 bch2_pd_controller_debug_to_text(out, var);             \
495 } while (0)
496
497 #define sysfs_pd_controller_store(name, var)                            \
498 do {                                                                    \
499         sysfs_strtoul_clamp(name##_rate,                                \
500                             (var)->rate.rate, 1, UINT_MAX);             \
501         sysfs_strtoul_clamp(name##_rate_bytes,                          \
502                             (var)->rate.rate, 1, UINT_MAX);             \
503         sysfs_strtoul(name##_rate_d_term,       (var)->d_term);         \
504         sysfs_strtoul_clamp(name##_rate_p_term_inverse,                 \
505                             (var)->p_term_inverse, 1, INT_MAX);         \
506 } while (0)
507
508 #define container_of_or_null(ptr, type, member)                         \
509 ({                                                                      \
510         typeof(ptr) _ptr = ptr;                                         \
511         _ptr ? container_of(_ptr, type, member) : NULL;                 \
512 })
513
514 /* Does linear interpolation between powers of two */
515 static inline unsigned fract_exp_two(unsigned x, unsigned fract_bits)
516 {
517         unsigned fract = x & ~(~0 << fract_bits);
518
519         x >>= fract_bits;
520         x   = 1 << x;
521         x  += (x * fract) >> fract_bits;
522
523         return x;
524 }
525
526 void bch2_bio_map(struct bio *bio, void *base, size_t);
527 int bch2_bio_alloc_pages(struct bio *, size_t, gfp_t);
528
529 static inline sector_t bdev_sectors(struct block_device *bdev)
530 {
531         return bdev->bd_inode->i_size >> 9;
532 }
533
534 #define closure_bio_submit(bio, cl)                                     \
535 do {                                                                    \
536         closure_get(cl);                                                \
537         submit_bio(bio);                                                \
538 } while (0)
539
540 #define kthread_wait_freezable(cond)                                    \
541 ({                                                                      \
542         int _ret = 0;                                                   \
543         while (1) {                                                     \
544                 set_current_state(TASK_INTERRUPTIBLE);                  \
545                 if (kthread_should_stop()) {                            \
546                         _ret = -1;                                      \
547                         break;                                          \
548                 }                                                       \
549                                                                         \
550                 if (cond)                                               \
551                         break;                                          \
552                                                                         \
553                 schedule();                                             \
554                 try_to_freeze();                                        \
555         }                                                               \
556         set_current_state(TASK_RUNNING);                                \
557         _ret;                                                           \
558 })
559
560 size_t bch2_rand_range(size_t);
561
562 void memcpy_to_bio(struct bio *, struct bvec_iter, const void *);
563 void memcpy_from_bio(void *, struct bio *, struct bvec_iter);
564
565 static inline void memcpy_u64s_small(void *dst, const void *src,
566                                      unsigned u64s)
567 {
568         u64 *d = dst;
569         const u64 *s = src;
570
571         while (u64s--)
572                 *d++ = *s++;
573 }
574
575 static inline void __memcpy_u64s(void *dst, const void *src,
576                                  unsigned u64s)
577 {
578 #ifdef CONFIG_X86_64
579         long d0, d1, d2;
580         asm volatile("rep ; movsq"
581                      : "=&c" (d0), "=&D" (d1), "=&S" (d2)
582                      : "0" (u64s), "1" (dst), "2" (src)
583                      : "memory");
584 #else
585         u64 *d = dst;
586         const u64 *s = src;
587
588         while (u64s--)
589                 *d++ = *s++;
590 #endif
591 }
592
593 static inline void memcpy_u64s(void *dst, const void *src,
594                                unsigned u64s)
595 {
596         EBUG_ON(!(dst >= src + u64s * sizeof(u64) ||
597                  dst + u64s * sizeof(u64) <= src));
598
599         __memcpy_u64s(dst, src, u64s);
600 }
601
602 static inline void __memmove_u64s_down(void *dst, const void *src,
603                                        unsigned u64s)
604 {
605         __memcpy_u64s(dst, src, u64s);
606 }
607
608 static inline void memmove_u64s_down(void *dst, const void *src,
609                                      unsigned u64s)
610 {
611         EBUG_ON(dst > src);
612
613         __memmove_u64s_down(dst, src, u64s);
614 }
615
616 static inline void __memmove_u64s_down_small(void *dst, const void *src,
617                                        unsigned u64s)
618 {
619         memcpy_u64s_small(dst, src, u64s);
620 }
621
622 static inline void memmove_u64s_down_small(void *dst, const void *src,
623                                      unsigned u64s)
624 {
625         EBUG_ON(dst > src);
626
627         __memmove_u64s_down_small(dst, src, u64s);
628 }
629
630 static inline void __memmove_u64s_up_small(void *_dst, const void *_src,
631                                            unsigned u64s)
632 {
633         u64 *dst = (u64 *) _dst + u64s;
634         u64 *src = (u64 *) _src + u64s;
635
636         while (u64s--)
637                 *--dst = *--src;
638 }
639
640 static inline void memmove_u64s_up_small(void *dst, const void *src,
641                                          unsigned u64s)
642 {
643         EBUG_ON(dst < src);
644
645         __memmove_u64s_up_small(dst, src, u64s);
646 }
647
648 static inline void __memmove_u64s_up(void *_dst, const void *_src,
649                                      unsigned u64s)
650 {
651         u64 *dst = (u64 *) _dst + u64s - 1;
652         u64 *src = (u64 *) _src + u64s - 1;
653
654 #ifdef CONFIG_X86_64
655         long d0, d1, d2;
656         asm volatile("std ;\n"
657                      "rep ; movsq\n"
658                      "cld ;\n"
659                      : "=&c" (d0), "=&D" (d1), "=&S" (d2)
660                      : "0" (u64s), "1" (dst), "2" (src)
661                      : "memory");
662 #else
663         while (u64s--)
664                 *dst-- = *src--;
665 #endif
666 }
667
668 static inline void memmove_u64s_up(void *dst, const void *src,
669                                    unsigned u64s)
670 {
671         EBUG_ON(dst < src);
672
673         __memmove_u64s_up(dst, src, u64s);
674 }
675
676 static inline void memmove_u64s(void *dst, const void *src,
677                                 unsigned u64s)
678 {
679         if (dst < src)
680                 __memmove_u64s_down(dst, src, u64s);
681         else
682                 __memmove_u64s_up(dst, src, u64s);
683 }
684
685 /* Set the last few bytes up to a u64 boundary given an offset into a buffer. */
686 static inline void memset_u64s_tail(void *s, int c, unsigned bytes)
687 {
688         unsigned rem = round_up(bytes, sizeof(u64)) - bytes;
689
690         memset(s + bytes, c, rem);
691 }
692
693 void sort_cmp_size(void *base, size_t num, size_t size,
694           int (*cmp_func)(const void *, const void *, size_t),
695           void (*swap_func)(void *, void *, size_t));
696
697 /* just the memmove, doesn't update @_nr */
698 #define __array_insert_item(_array, _nr, _pos)                          \
699         memmove(&(_array)[(_pos) + 1],                                  \
700                 &(_array)[(_pos)],                                      \
701                 sizeof((_array)[0]) * ((_nr) - (_pos)))
702
703 #define array_insert_item(_array, _nr, _pos, _new_item)                 \
704 do {                                                                    \
705         __array_insert_item(_array, _nr, _pos);                         \
706         (_nr)++;                                                        \
707         (_array)[(_pos)] = (_new_item);                                 \
708 } while (0)
709
710 #define array_remove_items(_array, _nr, _pos, _nr_to_remove)            \
711 do {                                                                    \
712         (_nr) -= (_nr_to_remove);                                       \
713         memmove(&(_array)[(_pos)],                                      \
714                 &(_array)[(_pos) + (_nr_to_remove)],                    \
715                 sizeof((_array)[0]) * ((_nr) - (_pos)));                \
716 } while (0)
717
718 #define array_remove_item(_array, _nr, _pos)                            \
719         array_remove_items(_array, _nr, _pos, 1)
720
721 static inline void __move_gap(void *array, size_t element_size,
722                               size_t nr, size_t size,
723                               size_t old_gap, size_t new_gap)
724 {
725         size_t gap_end = old_gap + size - nr;
726
727         if (new_gap < old_gap) {
728                 size_t move = old_gap - new_gap;
729
730                 memmove(array + element_size * (gap_end - move),
731                         array + element_size * (old_gap - move),
732                                 element_size * move);
733         } else if (new_gap > old_gap) {
734                 size_t move = new_gap - old_gap;
735
736                 memmove(array + element_size * old_gap,
737                         array + element_size * gap_end,
738                                 element_size * move);
739         }
740 }
741
742 /* Move the gap in a gap buffer: */
743 #define move_gap(_array, _nr, _size, _old_gap, _new_gap)        \
744         __move_gap(_array, sizeof(_array[0]), _nr, _size, _old_gap, _new_gap)
745
746 #define bubble_sort(_base, _nr, _cmp)                                   \
747 do {                                                                    \
748         ssize_t _i, _end;                                               \
749         bool _swapped = true;                                           \
750                                                                         \
751         for (_end = (ssize_t) (_nr) - 1; _end > 0 && _swapped; --_end) {\
752                 _swapped = false;                                       \
753                 for (_i = 0; _i < _end; _i++)                           \
754                         if (_cmp((_base)[_i], (_base)[_i + 1]) > 0) {   \
755                                 swap((_base)[_i], (_base)[_i + 1]);     \
756                                 _swapped = true;                        \
757                         }                                               \
758         }                                                               \
759 } while (0)
760
761 static inline u64 percpu_u64_get(u64 __percpu *src)
762 {
763         u64 ret = 0;
764         int cpu;
765
766         for_each_possible_cpu(cpu)
767                 ret += *per_cpu_ptr(src, cpu);
768         return ret;
769 }
770
771 static inline void percpu_u64_set(u64 __percpu *dst, u64 src)
772 {
773         int cpu;
774
775         for_each_possible_cpu(cpu)
776                 *per_cpu_ptr(dst, cpu) = 0;
777         this_cpu_write(*dst, src);
778 }
779
780 static inline void acc_u64s(u64 *acc, const u64 *src, unsigned nr)
781 {
782         unsigned i;
783
784         for (i = 0; i < nr; i++)
785                 acc[i] += src[i];
786 }
787
788 static inline void acc_u64s_percpu(u64 *acc, const u64 __percpu *src,
789                                    unsigned nr)
790 {
791         int cpu;
792
793         for_each_possible_cpu(cpu)
794                 acc_u64s(acc, per_cpu_ptr(src, cpu), nr);
795 }
796
797 static inline void percpu_memset(void __percpu *p, int c, size_t bytes)
798 {
799         int cpu;
800
801         for_each_possible_cpu(cpu)
802                 memset(per_cpu_ptr(p, cpu), c, bytes);
803 }
804
805 u64 *bch2_acc_percpu_u64s(u64 __percpu *, unsigned);
806
807 #define cmp_int(l, r)           ((l > r) - (l < r))
808
809 static inline int u8_cmp(u8 l, u8 r)
810 {
811         return cmp_int(l, r);
812 }
813
814 #endif /* _BCACHEFS_UTIL_H */