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