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