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