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