]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/util.h
Update bcachefs sources to 3704d0779c bcachefs: Improved human readable integer parsing
[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 #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)
360
361 struct quantiles {
362         struct quantile_entry {
363                 u64     m;
364                 u64     step;
365         }               entries[NR_QUANTILES];
366 };
367
368 struct time_stat_buffer {
369         unsigned        nr;
370         struct time_stat_buffer_entry {
371                 u64     start;
372                 u64     end;
373         }               entries[32];
374 };
375
376 struct time_stats {
377         spinlock_t      lock;
378         u64             count;
379         /* all fields are in nanoseconds */
380         u64             average_duration;
381         u64             average_frequency;
382         u64             max_duration;
383         u64             last_event;
384         struct quantiles quantiles;
385
386         struct time_stat_buffer __percpu *buffer;
387 };
388
389 void __bch2_time_stats_update(struct time_stats *stats, u64, u64);
390
391 static inline void bch2_time_stats_update(struct time_stats *stats, u64 start)
392 {
393         __bch2_time_stats_update(stats, start, local_clock());
394 }
395
396 void bch2_time_stats_to_text(struct printbuf *, struct time_stats *);
397
398 void bch2_time_stats_exit(struct time_stats *);
399 void bch2_time_stats_init(struct time_stats *);
400
401 #define ewma_add(ewma, val, weight)                                     \
402 ({                                                                      \
403         typeof(ewma) _ewma = (ewma);                                    \
404         typeof(weight) _weight = (weight);                              \
405                                                                         \
406         (((_ewma << _weight) - _ewma) + (val)) >> _weight;              \
407 })
408
409 struct bch_ratelimit {
410         /* Next time we want to do some work, in nanoseconds */
411         u64                     next;
412
413         /*
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()
417          */
418         unsigned                rate;
419 };
420
421 static inline void bch2_ratelimit_reset(struct bch_ratelimit *d)
422 {
423         d->next = local_clock();
424 }
425
426 u64 bch2_ratelimit_delay(struct bch_ratelimit *);
427 void bch2_ratelimit_increment(struct bch_ratelimit *, u64);
428
429 struct bch_pd_controller {
430         struct bch_ratelimit    rate;
431         unsigned long           last_update;
432
433         s64                     last_actual;
434         s64                     smoothed_derivative;
435
436         unsigned                p_term_inverse;
437         unsigned                d_smooth;
438         unsigned                d_term;
439
440         /* for exporting to sysfs (no effect on behavior) */
441         s64                     last_derivative;
442         s64                     last_proportional;
443         s64                     last_change;
444         s64                     last_target;
445
446         /* If true, the rate will not increase if bch2_ratelimit_delay()
447          * is not being called often enough. */
448         bool                    backpressure;
449 };
450
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 *);
454
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)
461
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
468
469 #define sysfs_pd_controller_show(name, var)                             \
470 do {                                                                    \
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); \
475                                                                         \
476         if (attr == &sysfs_##name##_rate_debug)                         \
477                 bch2_pd_controller_debug_to_text(out, var);             \
478 } while (0)
479
480 #define sysfs_pd_controller_store(name, var)                            \
481 do {                                                                    \
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);         \
489 } while (0)
490
491 #define container_of_or_null(ptr, type, member)                         \
492 ({                                                                      \
493         typeof(ptr) _ptr = ptr;                                         \
494         _ptr ? container_of(_ptr, type, member) : NULL;                 \
495 })
496
497 /* Does linear interpolation between powers of two */
498 static inline unsigned fract_exp_two(unsigned x, unsigned fract_bits)
499 {
500         unsigned fract = x & ~(~0 << fract_bits);
501
502         x >>= fract_bits;
503         x   = 1 << x;
504         x  += (x * fract) >> fract_bits;
505
506         return x;
507 }
508
509 void bch2_bio_map(struct bio *bio, void *base, size_t);
510 int bch2_bio_alloc_pages(struct bio *, size_t, gfp_t);
511
512 static inline sector_t bdev_sectors(struct block_device *bdev)
513 {
514         return bdev->bd_inode->i_size >> 9;
515 }
516
517 #define closure_bio_submit(bio, cl)                                     \
518 do {                                                                    \
519         closure_get(cl);                                                \
520         submit_bio(bio);                                                \
521 } while (0)
522
523 #define kthread_wait_freezable(cond)                                    \
524 ({                                                                      \
525         int _ret = 0;                                                   \
526         while (1) {                                                     \
527                 set_current_state(TASK_INTERRUPTIBLE);                  \
528                 if (kthread_should_stop()) {                            \
529                         _ret = -1;                                      \
530                         break;                                          \
531                 }                                                       \
532                                                                         \
533                 if (cond)                                               \
534                         break;                                          \
535                                                                         \
536                 schedule();                                             \
537                 try_to_freeze();                                        \
538         }                                                               \
539         set_current_state(TASK_RUNNING);                                \
540         _ret;                                                           \
541 })
542
543 size_t bch2_rand_range(size_t);
544
545 void memcpy_to_bio(struct bio *, struct bvec_iter, const void *);
546 void memcpy_from_bio(void *, struct bio *, struct bvec_iter);
547
548 static inline void memcpy_u64s_small(void *dst, const void *src,
549                                      unsigned u64s)
550 {
551         u64 *d = dst;
552         const u64 *s = src;
553
554         while (u64s--)
555                 *d++ = *s++;
556 }
557
558 static inline void __memcpy_u64s(void *dst, const void *src,
559                                  unsigned u64s)
560 {
561 #ifdef CONFIG_X86_64
562         long d0, d1, d2;
563         asm volatile("rep ; movsq"
564                      : "=&c" (d0), "=&D" (d1), "=&S" (d2)
565                      : "0" (u64s), "1" (dst), "2" (src)
566                      : "memory");
567 #else
568         u64 *d = dst;
569         const u64 *s = src;
570
571         while (u64s--)
572                 *d++ = *s++;
573 #endif
574 }
575
576 static inline void memcpy_u64s(void *dst, const void *src,
577                                unsigned u64s)
578 {
579         EBUG_ON(!(dst >= src + u64s * sizeof(u64) ||
580                  dst + u64s * sizeof(u64) <= src));
581
582         __memcpy_u64s(dst, src, u64s);
583 }
584
585 static inline void __memmove_u64s_down(void *dst, const void *src,
586                                        unsigned u64s)
587 {
588         __memcpy_u64s(dst, src, u64s);
589 }
590
591 static inline void memmove_u64s_down(void *dst, const void *src,
592                                      unsigned u64s)
593 {
594         EBUG_ON(dst > src);
595
596         __memmove_u64s_down(dst, src, u64s);
597 }
598
599 static inline void __memmove_u64s_up_small(void *_dst, const void *_src,
600                                            unsigned u64s)
601 {
602         u64 *dst = (u64 *) _dst + u64s;
603         u64 *src = (u64 *) _src + u64s;
604
605         while (u64s--)
606                 *--dst = *--src;
607 }
608
609 static inline void memmove_u64s_up_small(void *dst, const void *src,
610                                          unsigned u64s)
611 {
612         EBUG_ON(dst < src);
613
614         __memmove_u64s_up_small(dst, src, u64s);
615 }
616
617 static inline void __memmove_u64s_up(void *_dst, const void *_src,
618                                      unsigned u64s)
619 {
620         u64 *dst = (u64 *) _dst + u64s - 1;
621         u64 *src = (u64 *) _src + u64s - 1;
622
623 #ifdef CONFIG_X86_64
624         long d0, d1, d2;
625         asm volatile("std ;\n"
626                      "rep ; movsq\n"
627                      "cld ;\n"
628                      : "=&c" (d0), "=&D" (d1), "=&S" (d2)
629                      : "0" (u64s), "1" (dst), "2" (src)
630                      : "memory");
631 #else
632         while (u64s--)
633                 *dst-- = *src--;
634 #endif
635 }
636
637 static inline void memmove_u64s_up(void *dst, const void *src,
638                                    unsigned u64s)
639 {
640         EBUG_ON(dst < src);
641
642         __memmove_u64s_up(dst, src, u64s);
643 }
644
645 static inline void memmove_u64s(void *dst, const void *src,
646                                 unsigned u64s)
647 {
648         if (dst < src)
649                 __memmove_u64s_down(dst, src, u64s);
650         else
651                 __memmove_u64s_up(dst, src, u64s);
652 }
653
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)
656 {
657         unsigned rem = round_up(bytes, sizeof(u64)) - bytes;
658
659         memset(s + bytes, c, rem);
660 }
661
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));
665
666 /* just the memmove, doesn't update @_nr */
667 #define __array_insert_item(_array, _nr, _pos)                          \
668         memmove(&(_array)[(_pos) + 1],                                  \
669                 &(_array)[(_pos)],                                      \
670                 sizeof((_array)[0]) * ((_nr) - (_pos)))
671
672 #define array_insert_item(_array, _nr, _pos, _new_item)                 \
673 do {                                                                    \
674         __array_insert_item(_array, _nr, _pos);                         \
675         (_nr)++;                                                        \
676         (_array)[(_pos)] = (_new_item);                                 \
677 } while (0)
678
679 #define array_remove_items(_array, _nr, _pos, _nr_to_remove)            \
680 do {                                                                    \
681         (_nr) -= (_nr_to_remove);                                       \
682         memmove(&(_array)[(_pos)],                                      \
683                 &(_array)[(_pos) + (_nr_to_remove)],                    \
684                 sizeof((_array)[0]) * ((_nr) - (_pos)));                \
685 } while (0)
686
687 #define array_remove_item(_array, _nr, _pos)                            \
688         array_remove_items(_array, _nr, _pos, 1)
689
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)
693 {
694         size_t gap_end = old_gap + size - nr;
695
696         if (new_gap < old_gap) {
697                 size_t move = old_gap - new_gap;
698
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;
704
705                 memmove(array + element_size * old_gap,
706                         array + element_size * gap_end,
707                                 element_size * move);
708         }
709 }
710
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)
714
715 #define bubble_sort(_base, _nr, _cmp)                                   \
716 do {                                                                    \
717         ssize_t _i, _end;                                               \
718         bool _swapped = true;                                           \
719                                                                         \
720         for (_end = (ssize_t) (_nr) - 1; _end > 0 && _swapped; --_end) {\
721                 _swapped = false;                                       \
722                 for (_i = 0; _i < _end; _i++)                           \
723                         if (_cmp((_base)[_i], (_base)[_i + 1]) > 0) {   \
724                                 swap((_base)[_i], (_base)[_i + 1]);     \
725                                 _swapped = true;                        \
726                         }                                               \
727         }                                                               \
728 } while (0)
729
730 static inline u64 percpu_u64_get(u64 __percpu *src)
731 {
732         u64 ret = 0;
733         int cpu;
734
735         for_each_possible_cpu(cpu)
736                 ret += *per_cpu_ptr(src, cpu);
737         return ret;
738 }
739
740 static inline void percpu_u64_set(u64 __percpu *dst, u64 src)
741 {
742         int cpu;
743
744         for_each_possible_cpu(cpu)
745                 *per_cpu_ptr(dst, cpu) = 0;
746         this_cpu_write(*dst, src);
747 }
748
749 static inline void acc_u64s(u64 *acc, const u64 *src, unsigned nr)
750 {
751         unsigned i;
752
753         for (i = 0; i < nr; i++)
754                 acc[i] += src[i];
755 }
756
757 static inline void acc_u64s_percpu(u64 *acc, const u64 __percpu *src,
758                                    unsigned nr)
759 {
760         int cpu;
761
762         for_each_possible_cpu(cpu)
763                 acc_u64s(acc, per_cpu_ptr(src, cpu), nr);
764 }
765
766 static inline void percpu_memset(void __percpu *p, int c, size_t bytes)
767 {
768         int cpu;
769
770         for_each_possible_cpu(cpu)
771                 memset(per_cpu_ptr(p, cpu), c, bytes);
772 }
773
774 u64 *bch2_acc_percpu_u64s(u64 __percpu *, unsigned);
775
776 #define cmp_int(l, r)           ((l > r) - (l < r))
777
778 static inline int u8_cmp(u8 l, u8 r)
779 {
780         return cmp_int(l, r);
781 }
782
783 #endif /* _BCACHEFS_UTIL_H */