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