]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/util.h
Update bcachefs sources to 8ffb42b3d0 bcachefs: Finish writing journal after journal...
[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                    *buf;
246         unsigned                size;
247         unsigned                pos;
248         unsigned                last_newline;
249         unsigned                last_field;
250         unsigned                indent;
251         enum printbuf_units     units:8;
252         u8                      atomic;
253         bool                    allocation_failure:1;
254         u8                      tabstop;
255         u8                      tabstops[4];
256 };
257
258 #define PRINTBUF ((struct printbuf) { NULL })
259
260 static inline void printbuf_exit(struct printbuf *buf)
261 {
262         kfree(buf->buf);
263         buf->buf = ERR_PTR(-EINTR); /* poison value */
264 }
265
266 static inline void printbuf_reset(struct printbuf *buf)
267 {
268         buf->pos                = 0;
269         buf->last_newline       = 0;
270         buf->last_field         = 0;
271         buf->indent             = 0;
272         buf->tabstop            = 0;
273 }
274
275 static inline size_t printbuf_remaining(struct printbuf *buf)
276 {
277         return buf->size - buf->pos;
278 }
279
280 static inline size_t printbuf_linelen(struct printbuf *buf)
281 {
282         return buf->pos - buf->last_newline;
283 }
284
285 void bch2_pr_buf(struct printbuf *out, const char *fmt, ...);
286
287 #define pr_buf(_out, ...) bch2_pr_buf(_out, __VA_ARGS__)
288
289 static inline void pr_char(struct printbuf *out, char c)
290 {
291         bch2_pr_buf(out, "%c", c);
292 }
293
294 static inline void pr_indent_push(struct printbuf *buf, unsigned spaces)
295 {
296         buf->indent += spaces;
297         while (spaces--)
298                 pr_char(buf, ' ');
299 }
300
301 static inline void pr_indent_pop(struct printbuf *buf, unsigned spaces)
302 {
303         if (buf->last_newline + buf->indent == buf->pos) {
304                 buf->pos -= spaces;
305                 buf->buf[buf->pos] = 0;
306         }
307         buf->indent -= spaces;
308 }
309
310 static inline void pr_newline(struct printbuf *buf)
311 {
312         unsigned i;
313
314         pr_char(buf, '\n');
315
316         buf->last_newline       = buf->pos;
317
318         for (i = 0; i < buf->indent; i++)
319                 pr_char(buf, ' ');
320
321         buf->last_field         = buf->pos;
322         buf->tabstop = 0;
323 }
324
325 static inline void pr_tab(struct printbuf *buf)
326 {
327         BUG_ON(buf->tabstop > ARRAY_SIZE(buf->tabstops));
328
329         while (printbuf_remaining(buf) > 1 &&
330                printbuf_linelen(buf) < buf->tabstops[buf->tabstop])
331                 pr_char(buf, ' ');
332
333         buf->last_field = buf->pos;
334         buf->tabstop++;
335 }
336
337 static inline void pr_tab_rjust(struct printbuf *buf)
338 {
339         ssize_t shift = min_t(ssize_t, buf->tabstops[buf->tabstop] -
340                               printbuf_linelen(buf),
341                               printbuf_remaining(buf));
342         ssize_t move = min_t(ssize_t, buf->pos - buf->last_field,
343                              printbuf_remaining(buf) - shift);
344
345         BUG_ON(buf->tabstop > ARRAY_SIZE(buf->tabstops));
346
347         if (shift > 0) {
348                 memmove(buf->buf + buf->last_field + shift,
349                         buf->buf + buf->last_field,
350                         move);
351                 memset(buf->buf + buf->last_field, ' ', shift);
352                 buf->pos += shift;
353                 buf->buf[buf->pos] = 0;
354         }
355
356         buf->last_field = buf->pos;
357         buf->tabstop++;
358 }
359
360 void bch2_pr_units(struct printbuf *, s64, s64);
361 #define pr_units(...) bch2_pr_units(__VA_ARGS__)
362
363 static inline void pr_sectors(struct printbuf *out, u64 v)
364 {
365         bch2_pr_units(out, v, v << 9);
366 }
367
368 #ifdef __KERNEL__
369 static inline void pr_time(struct printbuf *out, u64 time)
370 {
371         pr_buf(out, "%llu", time);
372 }
373 #else
374 #include <time.h>
375 static inline void pr_time(struct printbuf *out, u64 _time)
376 {
377         char time_str[64];
378         time_t time = _time;
379         struct tm *tm = localtime(&time);
380         size_t err = strftime(time_str, sizeof(time_str), "%c", tm);
381         if (!err)
382                 pr_buf(out, "(formatting error)");
383         else
384                 pr_buf(out, "%s", time_str);
385 }
386 #endif
387
388 #ifdef __KERNEL__
389 static inline void uuid_unparse_lower(u8 *uuid, char *out)
390 {
391         sprintf(out, "%plU", uuid);
392 }
393 #else
394 #include <uuid/uuid.h>
395 #endif
396
397 static inline void pr_uuid(struct printbuf *out, u8 *uuid)
398 {
399         char uuid_str[40];
400
401         uuid_unparse_lower(uuid, uuid_str);
402         pr_buf(out, uuid_str);
403 }
404
405 int bch2_strtoint_h(const char *, int *);
406 int bch2_strtouint_h(const char *, unsigned int *);
407 int bch2_strtoll_h(const char *, long long *);
408 int bch2_strtoull_h(const char *, unsigned long long *);
409 int bch2_strtou64_h(const char *, u64 *);
410
411 static inline int bch2_strtol_h(const char *cp, long *res)
412 {
413 #if BITS_PER_LONG == 32
414         return bch2_strtoint_h(cp, (int *) res);
415 #else
416         return bch2_strtoll_h(cp, (long long *) res);
417 #endif
418 }
419
420 static inline int bch2_strtoul_h(const char *cp, long *res)
421 {
422 #if BITS_PER_LONG == 32
423         return bch2_strtouint_h(cp, (unsigned int *) res);
424 #else
425         return bch2_strtoull_h(cp, (unsigned long long *) res);
426 #endif
427 }
428
429 #define strtoi_h(cp, res)                                               \
430         ( type_is(*res, int)            ? bch2_strtoint_h(cp, (void *) res)\
431         : type_is(*res, long)           ? bch2_strtol_h(cp, (void *) res)\
432         : type_is(*res, long long)      ? bch2_strtoll_h(cp, (void *) res)\
433         : type_is(*res, unsigned)       ? bch2_strtouint_h(cp, (void *) res)\
434         : type_is(*res, unsigned long)  ? bch2_strtoul_h(cp, (void *) res)\
435         : type_is(*res, unsigned long long) ? bch2_strtoull_h(cp, (void *) res)\
436         : -EINVAL)
437
438 #define strtoul_safe(cp, var)                                           \
439 ({                                                                      \
440         unsigned long _v;                                               \
441         int _r = kstrtoul(cp, 10, &_v);                                 \
442         if (!_r)                                                        \
443                 var = _v;                                               \
444         _r;                                                             \
445 })
446
447 #define strtoul_safe_clamp(cp, var, min, max)                           \
448 ({                                                                      \
449         unsigned long _v;                                               \
450         int _r = kstrtoul(cp, 10, &_v);                                 \
451         if (!_r)                                                        \
452                 var = clamp_t(typeof(var), _v, min, max);               \
453         _r;                                                             \
454 })
455
456 #define strtoul_safe_restrict(cp, var, min, max)                        \
457 ({                                                                      \
458         unsigned long _v;                                               \
459         int _r = kstrtoul(cp, 10, &_v);                                 \
460         if (!_r && _v >= min && _v <= max)                              \
461                 var = _v;                                               \
462         else                                                            \
463                 _r = -EINVAL;                                           \
464         _r;                                                             \
465 })
466
467 #define snprint(out, var)                                               \
468         pr_buf(out,                                                     \
469                    type_is(var, int)            ? "%i\n"                \
470                  : type_is(var, unsigned)       ? "%u\n"                \
471                  : type_is(var, long)           ? "%li\n"               \
472                  : type_is(var, unsigned long)  ? "%lu\n"               \
473                  : type_is(var, s64)            ? "%lli\n"              \
474                  : type_is(var, u64)            ? "%llu\n"              \
475                  : type_is(var, char *)         ? "%s\n"                \
476                  : "%i\n", var)
477
478 void bch2_hprint(struct printbuf *, s64);
479
480 bool bch2_is_zero(const void *, size_t);
481
482 void bch2_string_opt_to_text(struct printbuf *,
483                              const char * const [], size_t);
484
485 void bch2_flags_to_text(struct printbuf *, const char * const[], u64);
486 u64 bch2_read_flag_list(char *, const char * const[]);
487
488 #define NR_QUANTILES    15
489 #define QUANTILE_IDX(i) inorder_to_eytzinger0(i, NR_QUANTILES)
490 #define QUANTILE_FIRST  eytzinger0_first(NR_QUANTILES)
491 #define QUANTILE_LAST   eytzinger0_last(NR_QUANTILES)
492
493 struct quantiles {
494         struct quantile_entry {
495                 u64     m;
496                 u64     step;
497         }               entries[NR_QUANTILES];
498 };
499
500 struct time_stat_buffer {
501         unsigned        nr;
502         struct time_stat_buffer_entry {
503                 u64     start;
504                 u64     end;
505         }               entries[32];
506 };
507
508 struct time_stats {
509         spinlock_t      lock;
510         u64             count;
511         /* all fields are in nanoseconds */
512         u64             average_duration;
513         u64             average_frequency;
514         u64             max_duration;
515         u64             last_event;
516         struct quantiles quantiles;
517
518         struct time_stat_buffer __percpu *buffer;
519 };
520
521 void __bch2_time_stats_update(struct time_stats *stats, u64, u64);
522
523 static inline void bch2_time_stats_update(struct time_stats *stats, u64 start)
524 {
525         __bch2_time_stats_update(stats, start, local_clock());
526 }
527
528 void bch2_time_stats_to_text(struct printbuf *, struct time_stats *);
529
530 void bch2_time_stats_exit(struct time_stats *);
531 void bch2_time_stats_init(struct time_stats *);
532
533 #define ewma_add(ewma, val, weight)                                     \
534 ({                                                                      \
535         typeof(ewma) _ewma = (ewma);                                    \
536         typeof(weight) _weight = (weight);                              \
537                                                                         \
538         (((_ewma << _weight) - _ewma) + (val)) >> _weight;              \
539 })
540
541 struct bch_ratelimit {
542         /* Next time we want to do some work, in nanoseconds */
543         u64                     next;
544
545         /*
546          * Rate at which we want to do work, in units per nanosecond
547          * The units here correspond to the units passed to
548          * bch2_ratelimit_increment()
549          */
550         unsigned                rate;
551 };
552
553 static inline void bch2_ratelimit_reset(struct bch_ratelimit *d)
554 {
555         d->next = local_clock();
556 }
557
558 u64 bch2_ratelimit_delay(struct bch_ratelimit *);
559 void bch2_ratelimit_increment(struct bch_ratelimit *, u64);
560
561 struct bch_pd_controller {
562         struct bch_ratelimit    rate;
563         unsigned long           last_update;
564
565         s64                     last_actual;
566         s64                     smoothed_derivative;
567
568         unsigned                p_term_inverse;
569         unsigned                d_smooth;
570         unsigned                d_term;
571
572         /* for exporting to sysfs (no effect on behavior) */
573         s64                     last_derivative;
574         s64                     last_proportional;
575         s64                     last_change;
576         s64                     last_target;
577
578         /* If true, the rate will not increase if bch2_ratelimit_delay()
579          * is not being called often enough. */
580         bool                    backpressure;
581 };
582
583 void bch2_pd_controller_update(struct bch_pd_controller *, s64, s64, int);
584 void bch2_pd_controller_init(struct bch_pd_controller *);
585 void bch2_pd_controller_debug_to_text(struct printbuf *, struct bch_pd_controller *);
586
587 #define sysfs_pd_controller_attribute(name)                             \
588         rw_attribute(name##_rate);                                      \
589         rw_attribute(name##_rate_bytes);                                \
590         rw_attribute(name##_rate_d_term);                               \
591         rw_attribute(name##_rate_p_term_inverse);                       \
592         read_attribute(name##_rate_debug)
593
594 #define sysfs_pd_controller_files(name)                                 \
595         &sysfs_##name##_rate,                                           \
596         &sysfs_##name##_rate_bytes,                                     \
597         &sysfs_##name##_rate_d_term,                                    \
598         &sysfs_##name##_rate_p_term_inverse,                            \
599         &sysfs_##name##_rate_debug
600
601 #define sysfs_pd_controller_show(name, var)                             \
602 do {                                                                    \
603         sysfs_hprint(name##_rate,               (var)->rate.rate);      \
604         sysfs_print(name##_rate_bytes,          (var)->rate.rate);      \
605         sysfs_print(name##_rate_d_term,         (var)->d_term);         \
606         sysfs_print(name##_rate_p_term_inverse, (var)->p_term_inverse); \
607                                                                         \
608         if (attr == &sysfs_##name##_rate_debug)                         \
609                 bch2_pd_controller_debug_to_text(out, var);             \
610 } while (0)
611
612 #define sysfs_pd_controller_store(name, var)                            \
613 do {                                                                    \
614         sysfs_strtoul_clamp(name##_rate,                                \
615                             (var)->rate.rate, 1, UINT_MAX);             \
616         sysfs_strtoul_clamp(name##_rate_bytes,                          \
617                             (var)->rate.rate, 1, UINT_MAX);             \
618         sysfs_strtoul(name##_rate_d_term,       (var)->d_term);         \
619         sysfs_strtoul_clamp(name##_rate_p_term_inverse,                 \
620                             (var)->p_term_inverse, 1, INT_MAX);         \
621 } while (0)
622
623 #define container_of_or_null(ptr, type, member)                         \
624 ({                                                                      \
625         typeof(ptr) _ptr = ptr;                                         \
626         _ptr ? container_of(_ptr, type, member) : NULL;                 \
627 })
628
629 /* Does linear interpolation between powers of two */
630 static inline unsigned fract_exp_two(unsigned x, unsigned fract_bits)
631 {
632         unsigned fract = x & ~(~0 << fract_bits);
633
634         x >>= fract_bits;
635         x   = 1 << x;
636         x  += (x * fract) >> fract_bits;
637
638         return x;
639 }
640
641 void bch2_bio_map(struct bio *bio, void *base, size_t);
642 int bch2_bio_alloc_pages(struct bio *, size_t, gfp_t);
643
644 static inline sector_t bdev_sectors(struct block_device *bdev)
645 {
646         return bdev->bd_inode->i_size >> 9;
647 }
648
649 #define closure_bio_submit(bio, cl)                                     \
650 do {                                                                    \
651         closure_get(cl);                                                \
652         submit_bio(bio);                                                \
653 } while (0)
654
655 #define kthread_wait_freezable(cond)                                    \
656 ({                                                                      \
657         int _ret = 0;                                                   \
658         while (1) {                                                     \
659                 set_current_state(TASK_INTERRUPTIBLE);                  \
660                 if (kthread_should_stop()) {                            \
661                         _ret = -1;                                      \
662                         break;                                          \
663                 }                                                       \
664                                                                         \
665                 if (cond)                                               \
666                         break;                                          \
667                                                                         \
668                 schedule();                                             \
669                 try_to_freeze();                                        \
670         }                                                               \
671         set_current_state(TASK_RUNNING);                                \
672         _ret;                                                           \
673 })
674
675 size_t bch2_rand_range(size_t);
676
677 void memcpy_to_bio(struct bio *, struct bvec_iter, const void *);
678 void memcpy_from_bio(void *, struct bio *, struct bvec_iter);
679
680 static inline void memcpy_u64s_small(void *dst, const void *src,
681                                      unsigned u64s)
682 {
683         u64 *d = dst;
684         const u64 *s = src;
685
686         while (u64s--)
687                 *d++ = *s++;
688 }
689
690 static inline void __memcpy_u64s(void *dst, const void *src,
691                                  unsigned u64s)
692 {
693 #ifdef CONFIG_X86_64
694         long d0, d1, d2;
695         asm volatile("rep ; movsq"
696                      : "=&c" (d0), "=&D" (d1), "=&S" (d2)
697                      : "0" (u64s), "1" (dst), "2" (src)
698                      : "memory");
699 #else
700         u64 *d = dst;
701         const u64 *s = src;
702
703         while (u64s--)
704                 *d++ = *s++;
705 #endif
706 }
707
708 static inline void memcpy_u64s(void *dst, const void *src,
709                                unsigned u64s)
710 {
711         EBUG_ON(!(dst >= src + u64s * sizeof(u64) ||
712                  dst + u64s * sizeof(u64) <= src));
713
714         __memcpy_u64s(dst, src, u64s);
715 }
716
717 static inline void __memmove_u64s_down(void *dst, const void *src,
718                                        unsigned u64s)
719 {
720         __memcpy_u64s(dst, src, u64s);
721 }
722
723 static inline void memmove_u64s_down(void *dst, const void *src,
724                                      unsigned u64s)
725 {
726         EBUG_ON(dst > src);
727
728         __memmove_u64s_down(dst, src, u64s);
729 }
730
731 static inline void __memmove_u64s_up_small(void *_dst, const void *_src,
732                                            unsigned u64s)
733 {
734         u64 *dst = (u64 *) _dst + u64s;
735         u64 *src = (u64 *) _src + u64s;
736
737         while (u64s--)
738                 *--dst = *--src;
739 }
740
741 static inline void memmove_u64s_up_small(void *dst, const void *src,
742                                          unsigned u64s)
743 {
744         EBUG_ON(dst < src);
745
746         __memmove_u64s_up_small(dst, src, u64s);
747 }
748
749 static inline void __memmove_u64s_up(void *_dst, const void *_src,
750                                      unsigned u64s)
751 {
752         u64 *dst = (u64 *) _dst + u64s - 1;
753         u64 *src = (u64 *) _src + u64s - 1;
754
755 #ifdef CONFIG_X86_64
756         long d0, d1, d2;
757         asm volatile("std ;\n"
758                      "rep ; movsq\n"
759                      "cld ;\n"
760                      : "=&c" (d0), "=&D" (d1), "=&S" (d2)
761                      : "0" (u64s), "1" (dst), "2" (src)
762                      : "memory");
763 #else
764         while (u64s--)
765                 *dst-- = *src--;
766 #endif
767 }
768
769 static inline void memmove_u64s_up(void *dst, const void *src,
770                                    unsigned u64s)
771 {
772         EBUG_ON(dst < src);
773
774         __memmove_u64s_up(dst, src, u64s);
775 }
776
777 static inline void memmove_u64s(void *dst, const void *src,
778                                 unsigned u64s)
779 {
780         if (dst < src)
781                 __memmove_u64s_down(dst, src, u64s);
782         else
783                 __memmove_u64s_up(dst, src, u64s);
784 }
785
786 /* Set the last few bytes up to a u64 boundary given an offset into a buffer. */
787 static inline void memset_u64s_tail(void *s, int c, unsigned bytes)
788 {
789         unsigned rem = round_up(bytes, sizeof(u64)) - bytes;
790
791         memset(s + bytes, c, rem);
792 }
793
794 void sort_cmp_size(void *base, size_t num, size_t size,
795           int (*cmp_func)(const void *, const void *, size_t),
796           void (*swap_func)(void *, void *, size_t));
797
798 /* just the memmove, doesn't update @_nr */
799 #define __array_insert_item(_array, _nr, _pos)                          \
800         memmove(&(_array)[(_pos) + 1],                                  \
801                 &(_array)[(_pos)],                                      \
802                 sizeof((_array)[0]) * ((_nr) - (_pos)))
803
804 #define array_insert_item(_array, _nr, _pos, _new_item)                 \
805 do {                                                                    \
806         __array_insert_item(_array, _nr, _pos);                         \
807         (_nr)++;                                                        \
808         (_array)[(_pos)] = (_new_item);                                 \
809 } while (0)
810
811 #define array_remove_items(_array, _nr, _pos, _nr_to_remove)            \
812 do {                                                                    \
813         (_nr) -= (_nr_to_remove);                                       \
814         memmove(&(_array)[(_pos)],                                      \
815                 &(_array)[(_pos) + (_nr_to_remove)],                    \
816                 sizeof((_array)[0]) * ((_nr) - (_pos)));                \
817 } while (0)
818
819 #define array_remove_item(_array, _nr, _pos)                            \
820         array_remove_items(_array, _nr, _pos, 1)
821
822 #define bubble_sort(_base, _nr, _cmp)                                   \
823 do {                                                                    \
824         ssize_t _i, _end;                                               \
825         bool _swapped = true;                                           \
826                                                                         \
827         for (_end = (ssize_t) (_nr) - 1; _end > 0 && _swapped; --_end) {\
828                 _swapped = false;                                       \
829                 for (_i = 0; _i < _end; _i++)                           \
830                         if (_cmp((_base)[_i], (_base)[_i + 1]) > 0) {   \
831                                 swap((_base)[_i], (_base)[_i + 1]);     \
832                                 _swapped = true;                        \
833                         }                                               \
834         }                                                               \
835 } while (0)
836
837 static inline u64 percpu_u64_get(u64 __percpu *src)
838 {
839         u64 ret = 0;
840         int cpu;
841
842         for_each_possible_cpu(cpu)
843                 ret += *per_cpu_ptr(src, cpu);
844         return ret;
845 }
846
847 static inline void percpu_u64_set(u64 __percpu *dst, u64 src)
848 {
849         int cpu;
850
851         for_each_possible_cpu(cpu)
852                 *per_cpu_ptr(dst, cpu) = 0;
853         this_cpu_write(*dst, src);
854 }
855
856 static inline void acc_u64s(u64 *acc, const u64 *src, unsigned nr)
857 {
858         unsigned i;
859
860         for (i = 0; i < nr; i++)
861                 acc[i] += src[i];
862 }
863
864 static inline void acc_u64s_percpu(u64 *acc, const u64 __percpu *src,
865                                    unsigned nr)
866 {
867         int cpu;
868
869         for_each_possible_cpu(cpu)
870                 acc_u64s(acc, per_cpu_ptr(src, cpu), nr);
871 }
872
873 static inline void percpu_memset(void __percpu *p, int c, size_t bytes)
874 {
875         int cpu;
876
877         for_each_possible_cpu(cpu)
878                 memset(per_cpu_ptr(p, cpu), c, bytes);
879 }
880
881 u64 *bch2_acc_percpu_u64s(u64 __percpu *, unsigned);
882
883 #define cmp_int(l, r)           ((l > r) - (l < r))
884
885 static inline int u8_cmp(u8 l, u8 r)
886 {
887         return cmp_int(l, r);
888 }
889
890 #endif /* _BCACHEFS_UTIL_H */