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