]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/util.h
Rename from bcache-tools to bcachefs-tools
[bcachefs-tools-debian] / libbcachefs / util.h
1 #ifndef _BCACHE_UTIL_H
2 #define _BCACHE_UTIL_H
3
4 #include <linux/bio.h>
5 #include <linux/blkdev.h>
6 #include <linux/closure.h>
7 #include <linux/errno.h>
8 #include <linux/blkdev.h>
9 #include <linux/freezer.h>
10 #include <linux/kernel.h>
11 #include <linux/llist.h>
12 #include <linux/ratelimit.h>
13 #include <linux/slab.h>
14 #include <linux/vmalloc.h>
15 #include <linux/workqueue.h>
16
17 #define PAGE_SECTOR_SHIFT       (PAGE_SHIFT - 9)
18 #define PAGE_SECTORS            (1UL << PAGE_SECTOR_SHIFT)
19
20 struct closure;
21
22 #ifdef CONFIG_BCACHEFS_DEBUG
23
24 #define EBUG_ON(cond)           BUG_ON(cond)
25 #define atomic_dec_bug(v)       BUG_ON(atomic_dec_return(v) < 0)
26 #define atomic_inc_bug(v, i)    BUG_ON(atomic_inc_return(v) <= i)
27 #define atomic_sub_bug(i, v)    BUG_ON(atomic_sub_return(i, v) < 0)
28 #define atomic_add_bug(i, v)    BUG_ON(atomic_add_return(i, v) < 0)
29 #define atomic_long_dec_bug(v)          BUG_ON(atomic_long_dec_return(v) < 0)
30 #define atomic_long_sub_bug(i, v)       BUG_ON(atomic_long_sub_return(i, v) < 0)
31 #define atomic64_dec_bug(v)     BUG_ON(atomic64_dec_return(v) < 0)
32 #define atomic64_inc_bug(v, i)  BUG_ON(atomic64_inc_return(v) <= i)
33 #define atomic64_sub_bug(i, v)  BUG_ON(atomic64_sub_return(i, v) < 0)
34 #define atomic64_add_bug(i, v)  BUG_ON(atomic64_add_return(i, v) < 0)
35
36 #define memcpy(_dst, _src, _len)                                        \
37 do {                                                                    \
38         BUG_ON(!((void *) (_dst) >= (void *) (_src) + (_len) ||         \
39                  (void *) (_dst) + (_len) <= (void *) (_src)));         \
40         memcpy(_dst, _src, _len);                                       \
41 } while (0)
42
43 #else /* DEBUG */
44
45 #define EBUG_ON(cond)
46 #define atomic_dec_bug(v)       atomic_dec(v)
47 #define atomic_inc_bug(v, i)    atomic_inc(v)
48 #define atomic_sub_bug(i, v)    atomic_sub(i, v)
49 #define atomic_add_bug(i, v)    atomic_add(i, v)
50 #define atomic_long_dec_bug(v)          atomic_long_dec(v)
51 #define atomic_long_sub_bug(i, v)       atomic_long_sub(i, v)
52 #define atomic64_dec_bug(v)     atomic64_dec(v)
53 #define atomic64_inc_bug(v, i)  atomic64_inc(v)
54 #define atomic64_sub_bug(i, v)  atomic64_sub(i, v)
55 #define atomic64_add_bug(i, v)  atomic64_add(i, v)
56
57 #endif
58
59 #ifndef __CHECKER__
60 #define __flatten __attribute__((flatten))
61 #else
62 /* sparse doesn't know about attribute((flatten)) */
63 #define __flatten
64 #endif
65
66 #ifdef __LITTLE_ENDIAN
67 #define CPU_BIG_ENDIAN          0
68 #else
69 #define CPU_BIG_ENDIAN          1
70 #endif
71
72 /* type hackery */
73
74 #define type_is_exact(_val, _type)                                      \
75         __builtin_types_compatible_p(typeof(_val), _type)
76
77 #define type_is(_val, _type)                                            \
78         (__builtin_types_compatible_p(typeof(_val), _type) ||           \
79          __builtin_types_compatible_p(typeof(_val), const _type))
80
81 static inline void *kvmalloc(size_t bytes, gfp_t gfp)
82 {
83         if (bytes <= PAGE_SIZE ||
84             !(gfp & GFP_KERNEL))
85                 return kmalloc(bytes, gfp);
86
87         return ((bytes <= KMALLOC_MAX_SIZE)
88                 ? kmalloc(bytes, gfp|__GFP_NOWARN)
89                 : NULL) ?:
90                 vmalloc(bytes);
91 }
92
93 #define DECLARE_HEAP(type, name)                                        \
94         struct {                                                        \
95                 size_t size, used;                                      \
96                 type *data;                                             \
97         } name
98
99 #define init_heap(heap, _size, gfp)                                     \
100 ({                                                                      \
101         size_t _bytes;                                                  \
102         (heap)->used = 0;                                               \
103         (heap)->size = (_size);                                         \
104         _bytes = (heap)->size * sizeof(*(heap)->data);                  \
105         (heap)->data = kvmalloc(_bytes, (gfp));                         \
106         (heap)->data;                                                   \
107 })
108
109 #define free_heap(heap)                                                 \
110 do {                                                                    \
111         kvfree((heap)->data);                                           \
112         (heap)->data = NULL;                                            \
113 } while (0)
114
115 #define heap_swap(h, i, j)      swap((h)->data[i], (h)->data[j])
116
117 #define heap_sift(h, i, cmp)                                            \
118 do {                                                                    \
119         size_t _r, _j = i;                                              \
120                                                                         \
121         for (; _j * 2 + 1 < (h)->used; _j = _r) {                       \
122                 _r = _j * 2 + 1;                                        \
123                 if (_r + 1 < (h)->used &&                               \
124                     cmp((h)->data[_r], (h)->data[_r + 1]))              \
125                         _r++;                                           \
126                                                                         \
127                 if (cmp((h)->data[_r], (h)->data[_j]))                  \
128                         break;                                          \
129                 heap_swap(h, _r, _j);                                   \
130         }                                                               \
131 } while (0)
132
133 #define heap_sift_down(h, i, cmp)                                       \
134 do {                                                                    \
135         while (i) {                                                     \
136                 size_t p = (i - 1) / 2;                                 \
137                 if (cmp((h)->data[i], (h)->data[p]))                    \
138                         break;                                          \
139                 heap_swap(h, i, p);                                     \
140                 i = p;                                                  \
141         }                                                               \
142 } while (0)
143
144 #define heap_add(h, d, cmp)                                             \
145 ({                                                                      \
146         bool _r = !heap_full(h);                                        \
147         if (_r) {                                                       \
148                 size_t _i = (h)->used++;                                \
149                 (h)->data[_i] = d;                                      \
150                                                                         \
151                 heap_sift_down(h, _i, cmp);                             \
152                 heap_sift(h, _i, cmp);                                  \
153         }                                                               \
154         _r;                                                             \
155 })
156
157 #define heap_del(h, i, cmp)                                             \
158 do {                                                                    \
159         size_t _i = (i);                                                \
160                                                                         \
161         BUG_ON(_i >= (h)->used);                                        \
162         (h)->used--;                                                    \
163         heap_swap(h, _i, (h)->used);                                    \
164         heap_sift_down(h, _i, cmp);                                     \
165         heap_sift(h, _i, cmp);                                          \
166 } while (0)
167
168 #define heap_pop(h, d, cmp)                                             \
169 ({                                                                      \
170         bool _r = (h)->used;                                            \
171         if (_r) {                                                       \
172                 (d) = (h)->data[0];                                     \
173                 heap_del(h, 0, cmp);                                    \
174         }                                                               \
175         _r;                                                             \
176 })
177
178 #define heap_peek(h)                                                    \
179 ({                                                                      \
180         EBUG_ON(!(h)->used);                                            \
181         (h)->data[0];                                                   \
182 })
183
184 #define heap_full(h)    ((h)->used == (h)->size)
185
186 #define heap_resort(heap, cmp)                                          \
187 do {                                                                    \
188         ssize_t _i;                                                     \
189         for (_i = (ssize_t) (heap)->used / 2 -  1; _i >= 0; --_i)       \
190                 heap_sift(heap, _i, cmp);                               \
191 } while (0)
192
193 /*
194  * Simple array based allocator - preallocates a number of elements and you can
195  * never allocate more than that, also has no locking.
196  *
197  * Handy because if you know you only need a fixed number of elements you don't
198  * have to worry about memory allocation failure, and sometimes a mempool isn't
199  * what you want.
200  *
201  * We treat the free elements as entries in a singly linked list, and the
202  * freelist as a stack - allocating and freeing push and pop off the freelist.
203  */
204
205 #define DECLARE_ARRAY_ALLOCATOR(type, name, size)                       \
206         struct {                                                        \
207                 type    *freelist;                                      \
208                 type    data[size];                                     \
209         } name
210
211 #define array_alloc(array)                                              \
212 ({                                                                      \
213         typeof((array)->freelist) _ret = (array)->freelist;             \
214                                                                         \
215         if (_ret)                                                       \
216                 (array)->freelist = *((typeof((array)->freelist) *) _ret);\
217                                                                         \
218         _ret;                                                           \
219 })
220
221 #define array_free(array, ptr)                                          \
222 do {                                                                    \
223         typeof((array)->freelist) _ptr = ptr;                           \
224                                                                         \
225         *((typeof((array)->freelist) *) _ptr) = (array)->freelist;      \
226         (array)->freelist = _ptr;                                       \
227 } while (0)
228
229 #define array_allocator_init(array)                                     \
230 do {                                                                    \
231         typeof((array)->freelist) _i;                                   \
232                                                                         \
233         BUILD_BUG_ON(sizeof((array)->data[0]) < sizeof(void *));        \
234         (array)->freelist = NULL;                                       \
235                                                                         \
236         for (_i = (array)->data;                                        \
237              _i < (array)->data + ARRAY_SIZE((array)->data);            \
238              _i++)                                                      \
239                 array_free(array, _i);                                  \
240 } while (0)
241
242 #define array_freelist_empty(array)     ((array)->freelist == NULL)
243
244 #define ANYSINT_MAX(t)                                                  \
245         ((((t) 1 << (sizeof(t) * 8 - 2)) - (t) 1) * (t) 2 + (t) 1)
246
247 int bch2_strtoint_h(const char *, int *);
248 int bch2_strtouint_h(const char *, unsigned int *);
249 int bch2_strtoll_h(const char *, long long *);
250 int bch2_strtoull_h(const char *, unsigned long long *);
251
252 static inline int bch2_strtol_h(const char *cp, long *res)
253 {
254 #if BITS_PER_LONG == 32
255         return bch2_strtoint_h(cp, (int *) res);
256 #else
257         return bch2_strtoll_h(cp, (long long *) res);
258 #endif
259 }
260
261 static inline int bch2_strtoul_h(const char *cp, long *res)
262 {
263 #if BITS_PER_LONG == 32
264         return bch2_strtouint_h(cp, (unsigned int *) res);
265 #else
266         return bch2_strtoull_h(cp, (unsigned long long *) res);
267 #endif
268 }
269
270 #define strtoi_h(cp, res)                                               \
271         ( type_is(*res, int)            ? bch2_strtoint_h(cp, (void *) res)\
272         : type_is(*res, long)           ? bch2_strtol_h(cp, (void *) res)\
273         : type_is(*res, long long)      ? bch2_strtoll_h(cp, (void *) res)\
274         : type_is(*res, unsigned)       ? bch2_strtouint_h(cp, (void *) res)\
275         : type_is(*res, unsigned long)  ? bch2_strtoul_h(cp, (void *) res)\
276         : type_is(*res, unsigned long long) ? bch2_strtoull_h(cp, (void *) res)\
277         : -EINVAL)
278
279 #define strtoul_safe(cp, var)                                           \
280 ({                                                                      \
281         unsigned long _v;                                               \
282         int _r = kstrtoul(cp, 10, &_v);                                 \
283         if (!_r)                                                        \
284                 var = _v;                                               \
285         _r;                                                             \
286 })
287
288 #define strtoul_safe_clamp(cp, var, min, max)                           \
289 ({                                                                      \
290         unsigned long _v;                                               \
291         int _r = kstrtoul(cp, 10, &_v);                                 \
292         if (!_r)                                                        \
293                 var = clamp_t(typeof(var), _v, min, max);               \
294         _r;                                                             \
295 })
296
297 #define strtoul_safe_restrict(cp, var, min, max)                        \
298 ({                                                                      \
299         unsigned long _v;                                               \
300         int _r = kstrtoul(cp, 10, &_v);                                 \
301         if (!_r && _v >= min && _v <= max)                              \
302                 var = _v;                                               \
303         else                                                            \
304                 _r = -EINVAL;                                           \
305         _r;                                                             \
306 })
307
308 #define snprint(buf, size, var)                                         \
309         snprintf(buf, size,                                             \
310                    type_is(var, int)            ? "%i\n"                \
311                  : type_is(var, unsigned)       ? "%u\n"                \
312                  : type_is(var, long)           ? "%li\n"               \
313                  : type_is(var, unsigned long)  ? "%lu\n"               \
314                  : type_is(var, s64)            ? "%lli\n"              \
315                  : type_is(var, u64)            ? "%llu\n"              \
316                  : type_is(var, char *)         ? "%s\n"                \
317                  : "%i\n", var)
318
319 ssize_t bch2_hprint(char *buf, s64 v);
320
321 bool bch2_is_zero(const void *, size_t);
322
323 ssize_t bch2_snprint_string_list(char *buf, size_t size, const char * const list[],
324                             size_t selected);
325
326 ssize_t bch2_read_string_list(const char *buf, const char * const list[]);
327
328 struct time_stats {
329         spinlock_t      lock;
330         u64             count;
331         /*
332          * all fields are in nanoseconds, averages are ewmas stored left shifted
333          * by 8
334          */
335         u64             last_duration;
336         u64             max_duration;
337         u64             average_duration;
338         u64             average_frequency;
339         u64             last;
340 };
341
342 void bch2_time_stats_clear(struct time_stats *stats);
343 void __bch2_time_stats_update(struct time_stats *stats, u64 time);
344 void bch2_time_stats_update(struct time_stats *stats, u64 time);
345
346 static inline unsigned local_clock_us(void)
347 {
348         return local_clock() >> 10;
349 }
350
351 #define NSEC_PER_ns                     1L
352 #define NSEC_PER_us                     NSEC_PER_USEC
353 #define NSEC_PER_ms                     NSEC_PER_MSEC
354 #define NSEC_PER_sec                    NSEC_PER_SEC
355
356 #define __print_time_stat(stats, name, stat, units)                     \
357         sysfs_print(name ## _ ## stat ## _ ## units,                    \
358                     div_u64((stats)->stat >> 8, NSEC_PER_ ## units))
359
360 #define sysfs_print_time_stats(stats, name,                             \
361                                frequency_units,                         \
362                                duration_units)                          \
363 do {                                                                    \
364         __print_time_stat(stats, name,                                  \
365                           average_frequency,    frequency_units);       \
366         __print_time_stat(stats, name,                                  \
367                           average_duration,     duration_units);        \
368         sysfs_print(name ## _ ##count, (stats)->count);                 \
369         sysfs_print(name ## _ ##last_duration ## _ ## duration_units,   \
370                         div_u64((stats)->last_duration,                 \
371                                 NSEC_PER_ ## duration_units));          \
372         sysfs_print(name ## _ ##max_duration ## _ ## duration_units,    \
373                         div_u64((stats)->max_duration,                  \
374                                 NSEC_PER_ ## duration_units));          \
375                                                                         \
376         sysfs_print(name ## _last_ ## frequency_units, (stats)->last    \
377                     ? div_s64(local_clock() - (stats)->last,            \
378                               NSEC_PER_ ## frequency_units)             \
379                     : -1LL);                                            \
380 } while (0)
381
382 #define sysfs_clear_time_stats(stats, name)                             \
383 do {                                                                    \
384         if (attr == &sysfs_ ## name ## _clear)                          \
385                 bch2_time_stats_clear(stats);                           \
386 } while (0)
387
388 #define sysfs_time_stats_attribute(name,                                \
389                                    frequency_units,                     \
390                                    duration_units)                      \
391 write_attribute(name ## _clear);                                        \
392 read_attribute(name ## _count);                                         \
393 read_attribute(name ## _average_frequency_ ## frequency_units);         \
394 read_attribute(name ## _average_duration_ ## duration_units);           \
395 read_attribute(name ## _last_duration_ ## duration_units);              \
396 read_attribute(name ## _max_duration_ ## duration_units);               \
397 read_attribute(name ## _last_ ## frequency_units)
398
399 #define sysfs_time_stats_attribute_list(name,                           \
400                                         frequency_units,                \
401                                         duration_units)                 \
402 &sysfs_ ## name ## _clear,                                              \
403 &sysfs_ ## name ## _count,                                              \
404 &sysfs_ ## name ## _average_frequency_ ## frequency_units,              \
405 &sysfs_ ## name ## _average_duration_ ## duration_units,                \
406 &sysfs_ ## name ## _last_duration_ ## duration_units,                   \
407 &sysfs_ ## name ## _max_duration_ ## duration_units,                    \
408 &sysfs_ ## name ## _last_ ## frequency_units,
409
410 #define ewma_add(ewma, val, weight)                                     \
411 ({                                                                      \
412         typeof(ewma) _ewma = (ewma);                                    \
413         typeof(weight) _weight = (weight);                              \
414                                                                         \
415         (((_ewma << _weight) - _ewma) + (val)) >> _weight;              \
416 })
417
418 struct bch_ratelimit {
419         /* Next time we want to do some work, in nanoseconds */
420         u64                     next;
421
422         /*
423          * Rate at which we want to do work, in units per nanosecond
424          * The units here correspond to the units passed to
425          * bch2_ratelimit_increment()
426          */
427         unsigned                rate;
428 };
429
430 static inline void bch2_ratelimit_reset(struct bch_ratelimit *d)
431 {
432         d->next = local_clock();
433 }
434
435 u64 bch2_ratelimit_delay(struct bch_ratelimit *);
436 void bch2_ratelimit_increment(struct bch_ratelimit *, u64);
437 int bch2_ratelimit_wait_freezable_stoppable(struct bch_ratelimit *);
438
439 struct bch_pd_controller {
440         struct bch_ratelimit    rate;
441         unsigned long           last_update;
442
443         s64                     last_actual;
444         s64                     smoothed_derivative;
445
446         unsigned                p_term_inverse;
447         unsigned                d_smooth;
448         unsigned                d_term;
449
450         /* for exporting to sysfs (no effect on behavior) */
451         s64                     last_derivative;
452         s64                     last_proportional;
453         s64                     last_change;
454         s64                     last_target;
455
456         /* If true, the rate will not increase if bch2_ratelimit_delay()
457          * is not being called often enough. */
458         bool                    backpressure;
459 };
460
461 void bch2_pd_controller_update(struct bch_pd_controller *, s64, s64, int);
462 void bch2_pd_controller_init(struct bch_pd_controller *);
463 size_t bch2_pd_controller_print_debug(struct bch_pd_controller *, char *);
464
465 #define sysfs_pd_controller_attribute(name)                             \
466         rw_attribute(name##_rate);                                      \
467         rw_attribute(name##_rate_bytes);                                \
468         rw_attribute(name##_rate_d_term);                               \
469         rw_attribute(name##_rate_p_term_inverse);                       \
470         read_attribute(name##_rate_debug)
471
472 #define sysfs_pd_controller_files(name)                                 \
473         &sysfs_##name##_rate,                                           \
474         &sysfs_##name##_rate_bytes,                                     \
475         &sysfs_##name##_rate_d_term,                                    \
476         &sysfs_##name##_rate_p_term_inverse,                            \
477         &sysfs_##name##_rate_debug
478
479 #define sysfs_pd_controller_show(name, var)                             \
480 do {                                                                    \
481         sysfs_hprint(name##_rate,               (var)->rate.rate);      \
482         sysfs_print(name##_rate_bytes,          (var)->rate.rate);      \
483         sysfs_print(name##_rate_d_term,         (var)->d_term);         \
484         sysfs_print(name##_rate_p_term_inverse, (var)->p_term_inverse); \
485                                                                         \
486         if (attr == &sysfs_##name##_rate_debug)                         \
487                 return bch2_pd_controller_print_debug(var, buf);                \
488 } while (0)
489
490 #define sysfs_pd_controller_store(name, var)                            \
491 do {                                                                    \
492         sysfs_strtoul_clamp(name##_rate,                                \
493                             (var)->rate.rate, 1, UINT_MAX);             \
494         sysfs_strtoul_clamp(name##_rate_bytes,                          \
495                             (var)->rate.rate, 1, UINT_MAX);             \
496         sysfs_strtoul(name##_rate_d_term,       (var)->d_term);         \
497         sysfs_strtoul_clamp(name##_rate_p_term_inverse,                 \
498                             (var)->p_term_inverse, 1, INT_MAX);         \
499 } while (0)
500
501 #define __DIV_SAFE(n, d, zero)                                          \
502 ({                                                                      \
503         typeof(n) _n = (n);                                             \
504         typeof(d) _d = (d);                                             \
505         _d ? _n / _d : zero;                                            \
506 })
507
508 #define DIV_SAFE(n, d)  __DIV_SAFE(n, d, 0)
509
510 #define container_of_or_null(ptr, type, member)                         \
511 ({                                                                      \
512         typeof(ptr) _ptr = ptr;                                         \
513         _ptr ? container_of(_ptr, type, member) : NULL;                 \
514 })
515
516 #define RB_INSERT(root, new, member, cmp)                               \
517 ({                                                                      \
518         __label__ dup;                                                  \
519         struct rb_node **n = &(root)->rb_node, *parent = NULL;          \
520         typeof(new) this;                                               \
521         int res, ret = -1;                                              \
522                                                                         \
523         while (*n) {                                                    \
524                 parent = *n;                                            \
525                 this = container_of(*n, typeof(*(new)), member);        \
526                 res = cmp(new, this);                                   \
527                 if (!res)                                               \
528                         goto dup;                                       \
529                 n = res < 0                                             \
530                         ? &(*n)->rb_left                                \
531                         : &(*n)->rb_right;                              \
532         }                                                               \
533                                                                         \
534         rb_link_node(&(new)->member, parent, n);                        \
535         rb_insert_color(&(new)->member, root);                          \
536         ret = 0;                                                        \
537 dup:                                                                    \
538         ret;                                                            \
539 })
540
541 #define RB_SEARCH(root, search, member, cmp)                            \
542 ({                                                                      \
543         struct rb_node *n = (root)->rb_node;                            \
544         typeof(&(search)) this, ret = NULL;                             \
545         int res;                                                        \
546                                                                         \
547         while (n) {                                                     \
548                 this = container_of(n, typeof(search), member);         \
549                 res = cmp(&(search), this);                             \
550                 if (!res) {                                             \
551                         ret = this;                                     \
552                         break;                                          \
553                 }                                                       \
554                 n = res < 0                                             \
555                         ? n->rb_left                                    \
556                         : n->rb_right;                                  \
557         }                                                               \
558         ret;                                                            \
559 })
560
561 #define RB_GREATER(root, search, member, cmp)                           \
562 ({                                                                      \
563         struct rb_node *n = (root)->rb_node;                            \
564         typeof(&(search)) this, ret = NULL;                             \
565         int res;                                                        \
566                                                                         \
567         while (n) {                                                     \
568                 this = container_of(n, typeof(search), member);         \
569                 res = cmp(&(search), this);                             \
570                 if (res < 0) {                                          \
571                         ret = this;                                     \
572                         n = n->rb_left;                                 \
573                 } else                                                  \
574                         n = n->rb_right;                                \
575         }                                                               \
576         ret;                                                            \
577 })
578
579 #define RB_FIRST(root, type, member)                                    \
580         container_of_or_null(rb_first(root), type, member)
581
582 #define RB_LAST(root, type, member)                                     \
583         container_of_or_null(rb_last(root), type, member)
584
585 #define RB_NEXT(ptr, member)                                            \
586         container_of_or_null(rb_next(&(ptr)->member), typeof(*ptr), member)
587
588 #define RB_PREV(ptr, member)                                            \
589         container_of_or_null(rb_prev(&(ptr)->member), typeof(*ptr), member)
590
591 /* Does linear interpolation between powers of two */
592 static inline unsigned fract_exp_two(unsigned x, unsigned fract_bits)
593 {
594         unsigned fract = x & ~(~0 << fract_bits);
595
596         x >>= fract_bits;
597         x   = 1 << x;
598         x  += (x * fract) >> fract_bits;
599
600         return x;
601 }
602
603 void bch2_bio_map(struct bio *bio, void *base);
604
605 static inline sector_t bdev_sectors(struct block_device *bdev)
606 {
607         return bdev->bd_inode->i_size >> 9;
608 }
609
610 #define closure_bio_submit(bio, cl)                                     \
611 do {                                                                    \
612         closure_get(cl);                                                \
613         submit_bio(bio);                                                \
614 } while (0)
615
616 #define kthread_wait_freezable(cond)                                    \
617 ({                                                                      \
618         int _ret = 0;                                                   \
619         while (1) {                                                     \
620                 set_current_state(TASK_INTERRUPTIBLE);                  \
621                 if (kthread_should_stop()) {                            \
622                         _ret = -1;                                      \
623                         break;                                          \
624                 }                                                       \
625                                                                         \
626                 if (cond)                                               \
627                         break;                                          \
628                                                                         \
629                 schedule();                                             \
630                 try_to_freeze();                                        \
631         }                                                               \
632         set_current_state(TASK_RUNNING);                                \
633         _ret;                                                           \
634 })
635
636 size_t bch2_rand_range(size_t);
637
638 void memcpy_to_bio(struct bio *, struct bvec_iter, void *);
639 void memcpy_from_bio(void *, struct bio *, struct bvec_iter);
640
641 static inline void __memcpy_u64s(void *dst, const void *src,
642                                  unsigned u64s)
643 {
644 #ifdef CONFIG_X86_64
645         long d0, d1, d2;
646         asm volatile("rep ; movsq"
647                      : "=&c" (d0), "=&D" (d1), "=&S" (d2)
648                      : "0" (u64s), "1" (dst), "2" (src)
649                      : "memory");
650 #else
651         u64 *d = dst;
652         const u64 *s = src;
653
654         while (u64s--)
655                 *d++ = *s++;
656 #endif
657 }
658
659 static inline void memcpy_u64s(void *dst, const void *src,
660                                unsigned u64s)
661 {
662         EBUG_ON(!(dst >= src + u64s * sizeof(u64) ||
663                  dst + u64s * sizeof(u64) <= src));
664
665         __memcpy_u64s(dst, src, u64s);
666 }
667
668 static inline void __memmove_u64s_down(void *dst, const void *src,
669                                        unsigned u64s)
670 {
671         __memcpy_u64s(dst, src, u64s);
672 }
673
674 static inline void memmove_u64s_down(void *dst, const void *src,
675                                      unsigned u64s)
676 {
677         EBUG_ON(dst > src);
678
679         __memmove_u64s_down(dst, src, u64s);
680 }
681
682 static inline void __memmove_u64s_up(void *_dst, const void *_src,
683                                      unsigned u64s)
684 {
685         u64 *dst = (u64 *) _dst + u64s - 1;
686         u64 *src = (u64 *) _src + u64s - 1;
687
688 #ifdef CONFIG_X86_64
689         long d0, d1, d2;
690         asm volatile("std ;\n"
691                      "rep ; movsq\n"
692                      "cld ;\n"
693                      : "=&c" (d0), "=&D" (d1), "=&S" (d2)
694                      : "0" (u64s), "1" (dst), "2" (src)
695                      : "memory");
696 #else
697         while (u64s--)
698                 *dst-- = *src--;
699 #endif
700 }
701
702 static inline void memmove_u64s_up(void *dst, const void *src,
703                                    unsigned u64s)
704 {
705         EBUG_ON(dst < src);
706
707         __memmove_u64s_up(dst, src, u64s);
708 }
709
710 static inline void memmove_u64s(void *dst, const void *src,
711                                 unsigned u64s)
712 {
713         if (dst < src)
714                 __memmove_u64s_down(dst, src, u64s);
715         else
716                 __memmove_u64s_up(dst, src, u64s);
717 }
718
719 static inline struct bio_vec next_contig_bvec(struct bio *bio,
720                                               struct bvec_iter *iter)
721 {
722         struct bio_vec bv = bio_iter_iovec(bio, *iter);
723
724         bio_advance_iter(bio, iter, bv.bv_len);
725 #ifndef CONFIG_HIGHMEM
726         while (iter->bi_size) {
727                 struct bio_vec next = bio_iter_iovec(bio, *iter);
728
729                 if (page_address(bv.bv_page) + bv.bv_offset + bv.bv_len !=
730                     page_address(next.bv_page) + next.bv_offset)
731                         break;
732
733                 bv.bv_len += next.bv_len;
734                 bio_advance_iter(bio, iter, next.bv_len);
735         }
736 #endif
737         return bv;
738 }
739
740 #define __bio_for_each_contig_segment(bv, bio, iter, start)             \
741         for (iter = (start);                                            \
742              (iter).bi_size &&                                          \
743                 ((bv = next_contig_bvec((bio), &(iter))), 1);)
744
745 #define bio_for_each_contig_segment(bv, bio, iter)                      \
746         __bio_for_each_contig_segment(bv, bio, iter, (bio)->bi_iter)
747
748 #endif /* _BCACHE_UTIL_H */