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