]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/util.h
Merge pull request #38 from jnsaff/patch-1
[bcachefs-tools-debian] / libbcachefs / util.h
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _BCACHEFS_UTIL_H
3 #define _BCACHEFS_UTIL_H
4
5 #include <linux/bio.h>
6 #include <linux/blkdev.h>
7 #include <linux/closure.h>
8 #include <linux/errno.h>
9 #include <linux/freezer.h>
10 #include <linux/kernel.h>
11 #include <linux/sched/clock.h>
12 #include <linux/llist.h>
13 #include <linux/log2.h>
14 #include <linux/percpu.h>
15 #include <linux/preempt.h>
16 #include <linux/ratelimit.h>
17 #include <linux/slab.h>
18 #include <linux/vmalloc.h>
19 #include <linux/workqueue.h>
20
21 #define PAGE_SECTOR_SHIFT       (PAGE_SHIFT - 9)
22 #define PAGE_SECTORS            (1UL << PAGE_SECTOR_SHIFT)
23
24 struct closure;
25
26 #ifdef CONFIG_BCACHEFS_DEBUG
27
28 #define EBUG_ON(cond)           BUG_ON(cond)
29 #define atomic_dec_bug(v)       BUG_ON(atomic_dec_return(v) < 0)
30 #define atomic_inc_bug(v, i)    BUG_ON(atomic_inc_return(v) <= i)
31 #define atomic_sub_bug(i, v)    BUG_ON(atomic_sub_return(i, v) < 0)
32 #define atomic_add_bug(i, v)    BUG_ON(atomic_add_return(i, v) < 0)
33 #define atomic_long_dec_bug(v)          BUG_ON(atomic_long_dec_return(v) < 0)
34 #define atomic_long_sub_bug(i, v)       BUG_ON(atomic_long_sub_return(i, v) < 0)
35 #define atomic64_dec_bug(v)     BUG_ON(atomic64_dec_return(v) < 0)
36 #define atomic64_inc_bug(v, i)  BUG_ON(atomic64_inc_return(v) <= i)
37 #define atomic64_sub_bug(i, v)  BUG_ON(atomic64_sub_return(i, v) < 0)
38 #define atomic64_add_bug(i, v)  BUG_ON(atomic64_add_return(i, v) < 0)
39
40 #define memcpy(dst, src, len)                                           \
41 ({                                                                      \
42         void *_dst = (dst);                                             \
43         const void *_src = (src);                                       \
44         size_t _len = (len);                                            \
45                                                                         \
46         BUG_ON(!((void *) (_dst) >= (void *) (_src) + (_len) ||         \
47                  (void *) (_dst) + (_len) <= (void *) (_src)));         \
48         memcpy(_dst, _src, _len);                                       \
49 })
50
51 #else /* DEBUG */
52
53 #define EBUG_ON(cond)
54 #define atomic_dec_bug(v)       atomic_dec(v)
55 #define atomic_inc_bug(v, i)    atomic_inc(v)
56 #define atomic_sub_bug(i, v)    atomic_sub(i, v)
57 #define atomic_add_bug(i, v)    atomic_add(i, v)
58 #define atomic_long_dec_bug(v)          atomic_long_dec(v)
59 #define atomic_long_sub_bug(i, v)       atomic_long_sub(i, v)
60 #define atomic64_dec_bug(v)     atomic64_dec(v)
61 #define atomic64_inc_bug(v, i)  atomic64_inc(v)
62 #define atomic64_sub_bug(i, v)  atomic64_sub(i, v)
63 #define atomic64_add_bug(i, v)  atomic64_add(i, v)
64
65 #endif
66
67 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
68 #define CPU_BIG_ENDIAN          0
69 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
70 #define CPU_BIG_ENDIAN          1
71 #endif
72
73 /* type hackery */
74
75 #define type_is_exact(_val, _type)                                      \
76         __builtin_types_compatible_p(typeof(_val), _type)
77
78 #define type_is(_val, _type)                                            \
79         (__builtin_types_compatible_p(typeof(_val), _type) ||           \
80          __builtin_types_compatible_p(typeof(_val), const _type))
81
82 /* Userspace doesn't align allocations as nicely as the kernel allocators: */
83 static inline size_t buf_pages(void *p, size_t len)
84 {
85         return DIV_ROUND_UP(len +
86                             ((unsigned long) p & (PAGE_SIZE - 1)),
87                             PAGE_SIZE);
88 }
89
90 static inline void vpfree(void *p, size_t size)
91 {
92         if (is_vmalloc_addr(p))
93                 vfree(p);
94         else
95                 free_pages((unsigned long) p, get_order(size));
96 }
97
98 static inline void *vpmalloc(size_t size, gfp_t gfp_mask)
99 {
100         return (void *) __get_free_pages(gfp_mask|__GFP_NOWARN,
101                                          get_order(size)) ?:
102                 __vmalloc(size, gfp_mask);
103 }
104
105 static inline void kvpfree(void *p, size_t size)
106 {
107         if (size < PAGE_SIZE)
108                 kfree(p);
109         else
110                 vpfree(p, size);
111 }
112
113 static inline void *kvpmalloc(size_t size, gfp_t gfp_mask)
114 {
115         return size < PAGE_SIZE
116                 ? kmalloc(size, gfp_mask)
117                 : vpmalloc(size, gfp_mask);
118 }
119
120 int mempool_init_kvpmalloc_pool(mempool_t *, int, size_t);
121
122 #define HEAP(type)                                                      \
123 struct {                                                                \
124         size_t size, used;                                              \
125         type *data;                                                     \
126 }
127
128 #define DECLARE_HEAP(type, name) HEAP(type) name
129
130 #define init_heap(heap, _size, gfp)                                     \
131 ({                                                                      \
132         (heap)->used = 0;                                               \
133         (heap)->size = (_size);                                         \
134         (heap)->data = kvpmalloc((heap)->size * sizeof((heap)->data[0]),\
135                                  (gfp));                                \
136 })
137
138 #define free_heap(heap)                                                 \
139 do {                                                                    \
140         kvpfree((heap)->data, (heap)->size * sizeof((heap)->data[0]));  \
141         (heap)->data = NULL;                                            \
142 } while (0)
143
144 #define heap_set_backpointer(h, i, _fn)                                 \
145 do {                                                                    \
146         void (*fn)(typeof(h), size_t) = _fn;                            \
147         if (fn)                                                         \
148                 fn(h, i);                                               \
149 } while (0)
150
151 #define heap_swap(h, i, j, set_backpointer)                             \
152 do {                                                                    \
153         swap((h)->data[i], (h)->data[j]);                               \
154         heap_set_backpointer(h, i, set_backpointer);                    \
155         heap_set_backpointer(h, j, set_backpointer);                    \
156 } while (0)
157
158 #define heap_peek(h)                                                    \
159 ({                                                                      \
160         EBUG_ON(!(h)->used);                                            \
161         (h)->data[0];                                                   \
162 })
163
164 #define heap_full(h)    ((h)->used == (h)->size)
165
166 #define heap_sift_down(h, i, cmp, set_backpointer)                      \
167 do {                                                                    \
168         size_t _c, _j = i;                                              \
169                                                                         \
170         for (; _j * 2 + 1 < (h)->used; _j = _c) {                       \
171                 _c = _j * 2 + 1;                                        \
172                 if (_c + 1 < (h)->used &&                               \
173                     cmp(h, (h)->data[_c], (h)->data[_c + 1]) >= 0)      \
174                         _c++;                                           \
175                                                                         \
176                 if (cmp(h, (h)->data[_c], (h)->data[_j]) >= 0)          \
177                         break;                                          \
178                 heap_swap(h, _c, _j, set_backpointer);                  \
179         }                                                               \
180 } while (0)
181
182 #define heap_sift_up(h, i, cmp, set_backpointer)                        \
183 do {                                                                    \
184         while (i) {                                                     \
185                 size_t p = (i - 1) / 2;                                 \
186                 if (cmp(h, (h)->data[i], (h)->data[p]) >= 0)            \
187                         break;                                          \
188                 heap_swap(h, i, p, set_backpointer);                    \
189                 i = p;                                                  \
190         }                                                               \
191 } while (0)
192
193 #define __heap_add(h, d, cmp, set_backpointer)                          \
194 ({                                                                      \
195         size_t _i = (h)->used++;                                        \
196         (h)->data[_i] = d;                                              \
197         heap_set_backpointer(h, _i, set_backpointer);                   \
198                                                                         \
199         heap_sift_up(h, _i, cmp, set_backpointer);                      \
200         _i;                                                             \
201 })
202
203 #define heap_add(h, d, cmp, set_backpointer)                            \
204 ({                                                                      \
205         bool _r = !heap_full(h);                                        \
206         if (_r)                                                         \
207                 __heap_add(h, d, cmp, set_backpointer);                 \
208         _r;                                                             \
209 })
210
211 #define heap_add_or_replace(h, new, cmp, set_backpointer)               \
212 do {                                                                    \
213         if (!heap_add(h, new, cmp, set_backpointer) &&                  \
214             cmp(h, new, heap_peek(h)) >= 0) {                           \
215                 (h)->data[0] = new;                                     \
216                 heap_set_backpointer(h, 0, set_backpointer);            \
217                 heap_sift_down(h, 0, cmp, set_backpointer);             \
218         }                                                               \
219 } while (0)
220
221 #define heap_del(h, i, cmp, set_backpointer)                            \
222 do {                                                                    \
223         size_t _i = (i);                                                \
224                                                                         \
225         BUG_ON(_i >= (h)->used);                                        \
226         (h)->used--;                                                    \
227         heap_swap(h, _i, (h)->used, set_backpointer);                   \
228         heap_sift_up(h, _i, cmp, set_backpointer);                      \
229         heap_sift_down(h, _i, cmp, set_backpointer);                    \
230 } while (0)
231
232 #define heap_pop(h, d, cmp, set_backpointer)                            \
233 ({                                                                      \
234         bool _r = (h)->used;                                            \
235         if (_r) {                                                       \
236                 (d) = (h)->data[0];                                     \
237                 heap_del(h, 0, cmp, set_backpointer);                   \
238         }                                                               \
239         _r;                                                             \
240 })
241
242 #define heap_resort(heap, cmp, set_backpointer)                         \
243 do {                                                                    \
244         ssize_t _i;                                                     \
245         for (_i = (ssize_t) (heap)->used / 2 -  1; _i >= 0; --_i)       \
246                 heap_sift_down(heap, _i, cmp, set_backpointer);         \
247 } while (0)
248
249 #define ANYSINT_MAX(t)                                                  \
250         ((((t) 1 << (sizeof(t) * 8 - 2)) - (t) 1) * (t) 2 + (t) 1)
251
252 struct printbuf {
253         char            *pos;
254         char            *end;
255 };
256
257 static inline size_t printbuf_remaining(struct printbuf *buf)
258 {
259         return buf->end - buf->pos;
260 }
261
262 #define _PBUF(_buf, _len)                                               \
263         ((struct printbuf) {                                            \
264                 .pos    = _buf,                                         \
265                 .end    = _buf + _len,                                  \
266         })
267
268 #define PBUF(_buf) _PBUF(_buf, sizeof(_buf))
269
270 #define pr_buf(_out, ...)                                               \
271 do {                                                                    \
272         (_out)->pos += scnprintf((_out)->pos, printbuf_remaining(_out), \
273                                  __VA_ARGS__);                          \
274 } while (0)
275
276 void bch_scnmemcpy(struct printbuf *, const char *, size_t);
277
278 int bch2_strtoint_h(const char *, int *);
279 int bch2_strtouint_h(const char *, unsigned int *);
280 int bch2_strtoll_h(const char *, long long *);
281 int bch2_strtoull_h(const char *, unsigned long long *);
282 int bch2_strtou64_h(const char *, u64 *);
283
284 static inline int bch2_strtol_h(const char *cp, long *res)
285 {
286 #if BITS_PER_LONG == 32
287         return bch2_strtoint_h(cp, (int *) res);
288 #else
289         return bch2_strtoll_h(cp, (long long *) res);
290 #endif
291 }
292
293 static inline int bch2_strtoul_h(const char *cp, long *res)
294 {
295 #if BITS_PER_LONG == 32
296         return bch2_strtouint_h(cp, (unsigned int *) res);
297 #else
298         return bch2_strtoull_h(cp, (unsigned long long *) res);
299 #endif
300 }
301
302 #define strtoi_h(cp, res)                                               \
303         ( type_is(*res, int)            ? bch2_strtoint_h(cp, (void *) res)\
304         : type_is(*res, long)           ? bch2_strtol_h(cp, (void *) res)\
305         : type_is(*res, long long)      ? bch2_strtoll_h(cp, (void *) res)\
306         : type_is(*res, unsigned)       ? bch2_strtouint_h(cp, (void *) res)\
307         : type_is(*res, unsigned long)  ? bch2_strtoul_h(cp, (void *) res)\
308         : type_is(*res, unsigned long long) ? bch2_strtoull_h(cp, (void *) res)\
309         : -EINVAL)
310
311 #define strtoul_safe(cp, var)                                           \
312 ({                                                                      \
313         unsigned long _v;                                               \
314         int _r = kstrtoul(cp, 10, &_v);                                 \
315         if (!_r)                                                        \
316                 var = _v;                                               \
317         _r;                                                             \
318 })
319
320 #define strtoul_safe_clamp(cp, var, min, max)                           \
321 ({                                                                      \
322         unsigned long _v;                                               \
323         int _r = kstrtoul(cp, 10, &_v);                                 \
324         if (!_r)                                                        \
325                 var = clamp_t(typeof(var), _v, min, max);               \
326         _r;                                                             \
327 })
328
329 #define strtoul_safe_restrict(cp, var, min, max)                        \
330 ({                                                                      \
331         unsigned long _v;                                               \
332         int _r = kstrtoul(cp, 10, &_v);                                 \
333         if (!_r && _v >= min && _v <= max)                              \
334                 var = _v;                                               \
335         else                                                            \
336                 _r = -EINVAL;                                           \
337         _r;                                                             \
338 })
339
340 #define snprint(buf, size, var)                                         \
341         snprintf(buf, size,                                             \
342                    type_is(var, int)            ? "%i\n"                \
343                  : type_is(var, unsigned)       ? "%u\n"                \
344                  : type_is(var, long)           ? "%li\n"               \
345                  : type_is(var, unsigned long)  ? "%lu\n"               \
346                  : type_is(var, s64)            ? "%lli\n"              \
347                  : type_is(var, u64)            ? "%llu\n"              \
348                  : type_is(var, char *)         ? "%s\n"                \
349                  : "%i\n", var)
350
351 void bch2_hprint(struct printbuf *, s64);
352
353 bool bch2_is_zero(const void *, size_t);
354
355 void bch2_string_opt_to_text(struct printbuf *,
356                              const char * const [], size_t);
357
358 void bch2_flags_to_text(struct printbuf *, const char * const[], u64);
359 u64 bch2_read_flag_list(char *, const char * const[]);
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 size_t bch2_pd_controller_print_debug(struct bch_pd_controller *, char *);
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                 return bch2_pd_controller_print_debug(var, buf);                \
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 #define bubble_sort(_base, _nr, _cmp)                                   \
696 do {                                                                    \
697         ssize_t _i, _end;                                               \
698         bool _swapped = true;                                           \
699                                                                         \
700         for (_end = (ssize_t) (_nr) - 1; _end > 0 && _swapped; --_end) {\
701                 _swapped = false;                                       \
702                 for (_i = 0; _i < _end; _i++)                           \
703                         if (_cmp((_base)[_i], (_base)[_i + 1]) > 0) {   \
704                                 swap((_base)[_i], (_base)[_i + 1]);     \
705                                 _swapped = true;                        \
706                         }                                               \
707         }                                                               \
708 } while (0)
709
710 static inline u64 percpu_u64_get(u64 __percpu *src)
711 {
712         u64 ret = 0;
713         int cpu;
714
715         for_each_possible_cpu(cpu)
716                 ret += *per_cpu_ptr(src, cpu);
717         return ret;
718 }
719
720 static inline void percpu_u64_set(u64 __percpu *dst, u64 src)
721 {
722         int cpu;
723
724         for_each_possible_cpu(cpu)
725                 *per_cpu_ptr(dst, cpu) = 0;
726
727         preempt_disable();
728         *this_cpu_ptr(dst) = src;
729         preempt_enable();
730 }
731
732 static inline void acc_u64s(u64 *acc, const u64 *src, unsigned nr)
733 {
734         unsigned i;
735
736         for (i = 0; i < nr; i++)
737                 acc[i] += src[i];
738 }
739
740 static inline void acc_u64s_percpu(u64 *acc, const u64 __percpu *src,
741                                    unsigned nr)
742 {
743         int cpu;
744
745         for_each_possible_cpu(cpu)
746                 acc_u64s(acc, per_cpu_ptr(src, cpu), nr);
747 }
748
749 static inline void percpu_memset(void __percpu *p, int c, size_t bytes)
750 {
751         int cpu;
752
753         for_each_possible_cpu(cpu)
754                 memset(per_cpu_ptr(p, cpu), c, bytes);
755 }
756
757 u64 *bch2_acc_percpu_u64s(u64 __percpu *, unsigned);
758
759 #define cmp_int(l, r)           ((l > r) - (l < r))
760
761 #endif /* _BCACHEFS_UTIL_H */