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