]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/util.h
Update bcachefs sources to 6a20aede29 bcachefs: Fix quotas + snapshots
[bcachefs-tools-debian] / libbcachefs / util.h
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _BCACHEFS_UTIL_H
3 #define _BCACHEFS_UTIL_H
4
5 #include <linux/bio.h>
6 #include <linux/blkdev.h>
7 #include <linux/closure.h>
8 #include <linux/errno.h>
9 #include <linux/freezer.h>
10 #include <linux/kernel.h>
11 #include <linux/sched/clock.h>
12 #include <linux/llist.h>
13 #include <linux/log2.h>
14 #include <linux/percpu.h>
15 #include <linux/preempt.h>
16 #include <linux/ratelimit.h>
17 #include <linux/slab.h>
18 #include <linux/vmalloc.h>
19 #include <linux/workqueue.h>
20 #include <linux/mean_and_variance.h>
21
22 #include "darray.h"
23
24 struct closure;
25
26 #ifdef CONFIG_BCACHEFS_DEBUG
27 #define EBUG_ON(cond)           BUG_ON(cond)
28 #else
29 #define EBUG_ON(cond)
30 #endif
31
32 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
33 #define CPU_BIG_ENDIAN          0
34 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
35 #define CPU_BIG_ENDIAN          1
36 #endif
37
38 /* type hackery */
39
40 #define type_is_exact(_val, _type)                                      \
41         __builtin_types_compatible_p(typeof(_val), _type)
42
43 #define type_is(_val, _type)                                            \
44         (__builtin_types_compatible_p(typeof(_val), _type) ||           \
45          __builtin_types_compatible_p(typeof(_val), const _type))
46
47 /* Userspace doesn't align allocations as nicely as the kernel allocators: */
48 static inline size_t buf_pages(void *p, size_t len)
49 {
50         return DIV_ROUND_UP(len +
51                             ((unsigned long) p & (PAGE_SIZE - 1)),
52                             PAGE_SIZE);
53 }
54
55 static inline void vpfree(void *p, size_t size)
56 {
57         if (is_vmalloc_addr(p))
58                 vfree(p);
59         else
60                 free_pages((unsigned long) p, get_order(size));
61 }
62
63 static inline void *vpmalloc(size_t size, gfp_t gfp_mask)
64 {
65         return (void *) __get_free_pages(gfp_mask|__GFP_NOWARN,
66                                          get_order(size)) ?:
67                 __vmalloc(size, gfp_mask);
68 }
69
70 static inline void kvpfree(void *p, size_t size)
71 {
72         if (size < PAGE_SIZE)
73                 kfree(p);
74         else
75                 vpfree(p, size);
76 }
77
78 static inline void *kvpmalloc(size_t size, gfp_t gfp_mask)
79 {
80         return size < PAGE_SIZE
81                 ? kmalloc(size, gfp_mask)
82                 : vpmalloc(size, gfp_mask);
83 }
84
85 int mempool_init_kvpmalloc_pool(mempool_t *, int, size_t);
86
87 #define HEAP(type)                                                      \
88 struct {                                                                \
89         size_t size, used;                                              \
90         type *data;                                                     \
91 }
92
93 #define DECLARE_HEAP(type, name) HEAP(type) name
94
95 #define init_heap(heap, _size, gfp)                                     \
96 ({                                                                      \
97         (heap)->used = 0;                                               \
98         (heap)->size = (_size);                                         \
99         (heap)->data = kvpmalloc((heap)->size * sizeof((heap)->data[0]),\
100                                  (gfp));                                \
101 })
102
103 #define free_heap(heap)                                                 \
104 do {                                                                    \
105         kvpfree((heap)->data, (heap)->size * sizeof((heap)->data[0]));  \
106         (heap)->data = NULL;                                            \
107 } while (0)
108
109 #define heap_set_backpointer(h, i, _fn)                                 \
110 do {                                                                    \
111         void (*fn)(typeof(h), size_t) = _fn;                            \
112         if (fn)                                                         \
113                 fn(h, i);                                               \
114 } while (0)
115
116 #define heap_swap(h, i, j, set_backpointer)                             \
117 do {                                                                    \
118         swap((h)->data[i], (h)->data[j]);                               \
119         heap_set_backpointer(h, i, set_backpointer);                    \
120         heap_set_backpointer(h, j, set_backpointer);                    \
121 } while (0)
122
123 #define heap_peek(h)                                                    \
124 ({                                                                      \
125         EBUG_ON(!(h)->used);                                            \
126         (h)->data[0];                                                   \
127 })
128
129 #define heap_full(h)    ((h)->used == (h)->size)
130
131 #define heap_sift_down(h, i, cmp, set_backpointer)                      \
132 do {                                                                    \
133         size_t _c, _j = i;                                              \
134                                                                         \
135         for (; _j * 2 + 1 < (h)->used; _j = _c) {                       \
136                 _c = _j * 2 + 1;                                        \
137                 if (_c + 1 < (h)->used &&                               \
138                     cmp(h, (h)->data[_c], (h)->data[_c + 1]) >= 0)      \
139                         _c++;                                           \
140                                                                         \
141                 if (cmp(h, (h)->data[_c], (h)->data[_j]) >= 0)          \
142                         break;                                          \
143                 heap_swap(h, _c, _j, set_backpointer);                  \
144         }                                                               \
145 } while (0)
146
147 #define heap_sift_up(h, i, cmp, set_backpointer)                        \
148 do {                                                                    \
149         while (i) {                                                     \
150                 size_t p = (i - 1) / 2;                                 \
151                 if (cmp(h, (h)->data[i], (h)->data[p]) >= 0)            \
152                         break;                                          \
153                 heap_swap(h, i, p, set_backpointer);                    \
154                 i = p;                                                  \
155         }                                                               \
156 } while (0)
157
158 #define __heap_add(h, d, cmp, set_backpointer)                          \
159 ({                                                                      \
160         size_t _i = (h)->used++;                                        \
161         (h)->data[_i] = d;                                              \
162         heap_set_backpointer(h, _i, set_backpointer);                   \
163                                                                         \
164         heap_sift_up(h, _i, cmp, set_backpointer);                      \
165         _i;                                                             \
166 })
167
168 #define heap_add(h, d, cmp, set_backpointer)                            \
169 ({                                                                      \
170         bool _r = !heap_full(h);                                        \
171         if (_r)                                                         \
172                 __heap_add(h, d, cmp, set_backpointer);                 \
173         _r;                                                             \
174 })
175
176 #define heap_add_or_replace(h, new, cmp, set_backpointer)               \
177 do {                                                                    \
178         if (!heap_add(h, new, cmp, set_backpointer) &&                  \
179             cmp(h, new, heap_peek(h)) >= 0) {                           \
180                 (h)->data[0] = new;                                     \
181                 heap_set_backpointer(h, 0, set_backpointer);            \
182                 heap_sift_down(h, 0, cmp, set_backpointer);             \
183         }                                                               \
184 } while (0)
185
186 #define heap_del(h, i, cmp, set_backpointer)                            \
187 do {                                                                    \
188         size_t _i = (i);                                                \
189                                                                         \
190         BUG_ON(_i >= (h)->used);                                        \
191         (h)->used--;                                                    \
192         if ((_i) < (h)->used) {                                         \
193                 heap_swap(h, _i, (h)->used, set_backpointer);           \
194                 heap_sift_up(h, _i, cmp, set_backpointer);              \
195                 heap_sift_down(h, _i, cmp, set_backpointer);            \
196         }                                                               \
197 } while (0)
198
199 #define heap_pop(h, d, cmp, set_backpointer)                            \
200 ({                                                                      \
201         bool _r = (h)->used;                                            \
202         if (_r) {                                                       \
203                 (d) = (h)->data[0];                                     \
204                 heap_del(h, 0, cmp, set_backpointer);                   \
205         }                                                               \
206         _r;                                                             \
207 })
208
209 #define heap_resort(heap, cmp, set_backpointer)                         \
210 do {                                                                    \
211         ssize_t _i;                                                     \
212         for (_i = (ssize_t) (heap)->used / 2 -  1; _i >= 0; --_i)       \
213                 heap_sift_down(heap, _i, cmp, set_backpointer);         \
214 } while (0)
215
216 #define ANYSINT_MAX(t)                                                  \
217         ((((t) 1 << (sizeof(t) * 8 - 2)) - (t) 1) * (t) 2 + (t) 1)
218
219 #include "printbuf.h"
220
221 #define prt_vprintf(_out, ...)          bch2_prt_vprintf(_out, __VA_ARGS__)
222 #define prt_printf(_out, ...)           bch2_prt_printf(_out, __VA_ARGS__)
223 #define printbuf_str(_buf)              bch2_printbuf_str(_buf)
224 #define printbuf_exit(_buf)             bch2_printbuf_exit(_buf)
225
226 #define printbuf_tabstops_reset(_buf)   bch2_printbuf_tabstops_reset(_buf)
227 #define printbuf_tabstop_pop(_buf)      bch2_printbuf_tabstop_pop(_buf)
228 #define printbuf_tabstop_push(_buf, _n) bch2_printbuf_tabstop_push(_buf, _n)
229
230 #define printbuf_indent_add(_out, _n)   bch2_printbuf_indent_add(_out, _n)
231 #define printbuf_indent_sub(_out, _n)   bch2_printbuf_indent_sub(_out, _n)
232
233 #define prt_newline(_out)               bch2_prt_newline(_out)
234 #define prt_tab(_out)                   bch2_prt_tab(_out)
235 #define prt_tab_rjust(_out)             bch2_prt_tab_rjust(_out)
236
237 #define prt_bytes_indented(...)         bch2_prt_bytes_indented(__VA_ARGS__)
238 #define prt_u64(_out, _v)               prt_printf(_out, "%llu", (u64) (_v))
239 #define prt_human_readable_u64(...)     bch2_prt_human_readable_u64(__VA_ARGS__)
240 #define prt_human_readable_s64(...)     bch2_prt_human_readable_s64(__VA_ARGS__)
241 #define prt_units_u64(...)              bch2_prt_units_u64(__VA_ARGS__)
242 #define prt_units_s64(...)              bch2_prt_units_s64(__VA_ARGS__)
243 #define prt_string_option(...)          bch2_prt_string_option(__VA_ARGS__)
244 #define prt_bitflags(...)               bch2_prt_bitflags(__VA_ARGS__)
245
246 void bch2_pr_time_units(struct printbuf *, u64);
247
248 #ifdef __KERNEL__
249 static inline void pr_time(struct printbuf *out, u64 time)
250 {
251         prt_printf(out, "%llu", time);
252 }
253 #else
254 #include <time.h>
255 static inline void pr_time(struct printbuf *out, u64 _time)
256 {
257         char time_str[64];
258         time_t time = _time;
259         struct tm *tm = localtime(&time);
260         size_t err = strftime(time_str, sizeof(time_str), "%c", tm);
261         if (!err)
262                 prt_printf(out, "(formatting error)");
263         else
264                 prt_printf(out, "%s", time_str);
265 }
266 #endif
267
268 #ifdef __KERNEL__
269 static inline void uuid_unparse_lower(u8 *uuid, char *out)
270 {
271         sprintf(out, "%pUb", uuid);
272 }
273 #else
274 #include <uuid/uuid.h>
275 #endif
276
277 static inline void pr_uuid(struct printbuf *out, u8 *uuid)
278 {
279         char uuid_str[40];
280
281         uuid_unparse_lower(uuid, uuid_str);
282         prt_printf(out, "%s", uuid_str);
283 }
284
285 int bch2_strtoint_h(const char *, int *);
286 int bch2_strtouint_h(const char *, unsigned int *);
287 int bch2_strtoll_h(const char *, long long *);
288 int bch2_strtoull_h(const char *, unsigned long long *);
289 int bch2_strtou64_h(const char *, u64 *);
290
291 static inline int bch2_strtol_h(const char *cp, long *res)
292 {
293 #if BITS_PER_LONG == 32
294         return bch2_strtoint_h(cp, (int *) res);
295 #else
296         return bch2_strtoll_h(cp, (long long *) res);
297 #endif
298 }
299
300 static inline int bch2_strtoul_h(const char *cp, long *res)
301 {
302 #if BITS_PER_LONG == 32
303         return bch2_strtouint_h(cp, (unsigned int *) res);
304 #else
305         return bch2_strtoull_h(cp, (unsigned long long *) res);
306 #endif
307 }
308
309 #define strtoi_h(cp, res)                                               \
310         ( type_is(*res, int)            ? bch2_strtoint_h(cp, (void *) res)\
311         : type_is(*res, long)           ? bch2_strtol_h(cp, (void *) res)\
312         : type_is(*res, long long)      ? bch2_strtoll_h(cp, (void *) res)\
313         : type_is(*res, unsigned)       ? bch2_strtouint_h(cp, (void *) res)\
314         : type_is(*res, unsigned long)  ? bch2_strtoul_h(cp, (void *) res)\
315         : type_is(*res, unsigned long long) ? bch2_strtoull_h(cp, (void *) res)\
316         : -EINVAL)
317
318 #define strtoul_safe(cp, var)                                           \
319 ({                                                                      \
320         unsigned long _v;                                               \
321         int _r = kstrtoul(cp, 10, &_v);                                 \
322         if (!_r)                                                        \
323                 var = _v;                                               \
324         _r;                                                             \
325 })
326
327 #define strtoul_safe_clamp(cp, var, min, max)                           \
328 ({                                                                      \
329         unsigned long _v;                                               \
330         int _r = kstrtoul(cp, 10, &_v);                                 \
331         if (!_r)                                                        \
332                 var = clamp_t(typeof(var), _v, min, max);               \
333         _r;                                                             \
334 })
335
336 #define strtoul_safe_restrict(cp, var, min, max)                        \
337 ({                                                                      \
338         unsigned long _v;                                               \
339         int _r = kstrtoul(cp, 10, &_v);                                 \
340         if (!_r && _v >= min && _v <= max)                              \
341                 var = _v;                                               \
342         else                                                            \
343                 _r = -EINVAL;                                           \
344         _r;                                                             \
345 })
346
347 #define snprint(out, var)                                               \
348         prt_printf(out,                                                 \
349                    type_is(var, int)            ? "%i\n"                \
350                  : type_is(var, unsigned)       ? "%u\n"                \
351                  : type_is(var, long)           ? "%li\n"               \
352                  : type_is(var, unsigned long)  ? "%lu\n"               \
353                  : type_is(var, s64)            ? "%lli\n"              \
354                  : type_is(var, u64)            ? "%llu\n"              \
355                  : type_is(var, char *)         ? "%s\n"                \
356                  : "%i\n", var)
357
358 bool bch2_is_zero(const void *, size_t);
359
360 u64 bch2_read_flag_list(char *, const char * const[]);
361
362 void bch2_prt_u64_binary(struct printbuf *, u64, unsigned);
363
364 void bch2_print_string_as_lines(const char *prefix, const char *lines);
365
366 typedef DARRAY(unsigned long) bch_stacktrace;
367 int bch2_save_backtrace(bch_stacktrace *stack, struct task_struct *);
368 void bch2_prt_backtrace(struct printbuf *, bch_stacktrace *);
369 int bch2_prt_task_backtrace(struct printbuf *, struct task_struct *);
370
371 #define NR_QUANTILES    15
372 #define QUANTILE_IDX(i) inorder_to_eytzinger0(i, NR_QUANTILES)
373 #define QUANTILE_FIRST  eytzinger0_first(NR_QUANTILES)
374 #define QUANTILE_LAST   eytzinger0_last(NR_QUANTILES)
375
376 struct bch2_quantiles {
377         struct bch2_quantile_entry {
378                 u64     m;
379                 u64     step;
380         }               entries[NR_QUANTILES];
381 };
382
383 struct bch2_time_stat_buffer {
384         unsigned        nr;
385         struct bch2_time_stat_buffer_entry {
386                 u64     start;
387                 u64     end;
388         }               entries[32];
389 };
390
391 struct bch2_time_stats {
392         spinlock_t      lock;
393         /* all fields are in nanoseconds */
394         u64             max_duration;
395         u64             min_duration;
396         u64             max_freq;
397         u64             min_freq;
398         u64             last_event;
399         struct bch2_quantiles quantiles;
400
401         struct mean_and_variance          duration_stats;
402         struct mean_and_variance_weighted duration_stats_weighted;
403         struct mean_and_variance          freq_stats;
404         struct mean_and_variance_weighted freq_stats_weighted;
405         struct bch2_time_stat_buffer __percpu *buffer;
406 };
407
408 #ifndef CONFIG_BCACHEFS_NO_LATENCY_ACCT
409 void __bch2_time_stats_update(struct bch2_time_stats *stats, u64, u64);
410 #else
411 static inline void __bch2_time_stats_update(struct bch2_time_stats *stats, u64 start, u64 end) {}
412 #endif
413
414 static inline void bch2_time_stats_update(struct bch2_time_stats *stats, u64 start)
415 {
416         __bch2_time_stats_update(stats, start, local_clock());
417 }
418
419 void bch2_time_stats_to_text(struct printbuf *, struct bch2_time_stats *);
420
421 void bch2_time_stats_exit(struct bch2_time_stats *);
422 void bch2_time_stats_init(struct bch2_time_stats *);
423
424 #define ewma_add(ewma, val, weight)                                     \
425 ({                                                                      \
426         typeof(ewma) _ewma = (ewma);                                    \
427         typeof(weight) _weight = (weight);                              \
428                                                                         \
429         (((_ewma << _weight) - _ewma) + (val)) >> _weight;              \
430 })
431
432 struct bch_ratelimit {
433         /* Next time we want to do some work, in nanoseconds */
434         u64                     next;
435
436         /*
437          * Rate at which we want to do work, in units per nanosecond
438          * The units here correspond to the units passed to
439          * bch2_ratelimit_increment()
440          */
441         unsigned                rate;
442 };
443
444 static inline void bch2_ratelimit_reset(struct bch_ratelimit *d)
445 {
446         d->next = local_clock();
447 }
448
449 u64 bch2_ratelimit_delay(struct bch_ratelimit *);
450 void bch2_ratelimit_increment(struct bch_ratelimit *, u64);
451
452 struct bch_pd_controller {
453         struct bch_ratelimit    rate;
454         unsigned long           last_update;
455
456         s64                     last_actual;
457         s64                     smoothed_derivative;
458
459         unsigned                p_term_inverse;
460         unsigned                d_smooth;
461         unsigned                d_term;
462
463         /* for exporting to sysfs (no effect on behavior) */
464         s64                     last_derivative;
465         s64                     last_proportional;
466         s64                     last_change;
467         s64                     last_target;
468
469         /* If true, the rate will not increase if bch2_ratelimit_delay()
470          * is not being called often enough. */
471         bool                    backpressure;
472 };
473
474 void bch2_pd_controller_update(struct bch_pd_controller *, s64, s64, int);
475 void bch2_pd_controller_init(struct bch_pd_controller *);
476 void bch2_pd_controller_debug_to_text(struct printbuf *, struct bch_pd_controller *);
477
478 #define sysfs_pd_controller_attribute(name)                             \
479         rw_attribute(name##_rate);                                      \
480         rw_attribute(name##_rate_bytes);                                \
481         rw_attribute(name##_rate_d_term);                               \
482         rw_attribute(name##_rate_p_term_inverse);                       \
483         read_attribute(name##_rate_debug)
484
485 #define sysfs_pd_controller_files(name)                                 \
486         &sysfs_##name##_rate,                                           \
487         &sysfs_##name##_rate_bytes,                                     \
488         &sysfs_##name##_rate_d_term,                                    \
489         &sysfs_##name##_rate_p_term_inverse,                            \
490         &sysfs_##name##_rate_debug
491
492 #define sysfs_pd_controller_show(name, var)                             \
493 do {                                                                    \
494         sysfs_hprint(name##_rate,               (var)->rate.rate);      \
495         sysfs_print(name##_rate_bytes,          (var)->rate.rate);      \
496         sysfs_print(name##_rate_d_term,         (var)->d_term);         \
497         sysfs_print(name##_rate_p_term_inverse, (var)->p_term_inverse); \
498                                                                         \
499         if (attr == &sysfs_##name##_rate_debug)                         \
500                 bch2_pd_controller_debug_to_text(out, var);             \
501 } while (0)
502
503 #define sysfs_pd_controller_store(name, var)                            \
504 do {                                                                    \
505         sysfs_strtoul_clamp(name##_rate,                                \
506                             (var)->rate.rate, 1, UINT_MAX);             \
507         sysfs_strtoul_clamp(name##_rate_bytes,                          \
508                             (var)->rate.rate, 1, UINT_MAX);             \
509         sysfs_strtoul(name##_rate_d_term,       (var)->d_term);         \
510         sysfs_strtoul_clamp(name##_rate_p_term_inverse,                 \
511                             (var)->p_term_inverse, 1, INT_MAX);         \
512 } while (0)
513
514 #define container_of_or_null(ptr, type, member)                         \
515 ({                                                                      \
516         typeof(ptr) _ptr = ptr;                                         \
517         _ptr ? container_of(_ptr, type, member) : NULL;                 \
518 })
519
520 /* Does linear interpolation between powers of two */
521 static inline unsigned fract_exp_two(unsigned x, unsigned fract_bits)
522 {
523         unsigned fract = x & ~(~0 << fract_bits);
524
525         x >>= fract_bits;
526         x   = 1 << x;
527         x  += (x * fract) >> fract_bits;
528
529         return x;
530 }
531
532 void bch2_bio_map(struct bio *bio, void *base, size_t);
533 int bch2_bio_alloc_pages(struct bio *, size_t, gfp_t);
534
535 static inline sector_t bdev_sectors(struct block_device *bdev)
536 {
537         return bdev->bd_inode->i_size >> 9;
538 }
539
540 #define closure_bio_submit(bio, cl)                                     \
541 do {                                                                    \
542         closure_get(cl);                                                \
543         submit_bio(bio);                                                \
544 } while (0)
545
546 #define kthread_wait(cond)                                              \
547 ({                                                                      \
548         int _ret = 0;                                                   \
549                                                                         \
550         while (1) {                                                     \
551                 set_current_state(TASK_INTERRUPTIBLE);                  \
552                 if (kthread_should_stop()) {                            \
553                         _ret = -1;                                      \
554                         break;                                          \
555                 }                                                       \
556                                                                         \
557                 if (cond)                                               \
558                         break;                                          \
559                                                                         \
560                 schedule();                                             \
561         }                                                               \
562         set_current_state(TASK_RUNNING);                                \
563         _ret;                                                           \
564 })
565
566 #define kthread_wait_freezable(cond)                                    \
567 ({                                                                      \
568         int _ret = 0;                                                   \
569         while (1) {                                                     \
570                 set_current_state(TASK_INTERRUPTIBLE);                  \
571                 if (kthread_should_stop()) {                            \
572                         _ret = -1;                                      \
573                         break;                                          \
574                 }                                                       \
575                                                                         \
576                 if (cond)                                               \
577                         break;                                          \
578                                                                         \
579                 schedule();                                             \
580                 try_to_freeze();                                        \
581         }                                                               \
582         set_current_state(TASK_RUNNING);                                \
583         _ret;                                                           \
584 })
585
586 size_t bch2_rand_range(size_t);
587
588 void memcpy_to_bio(struct bio *, struct bvec_iter, const void *);
589 void memcpy_from_bio(void *, struct bio *, struct bvec_iter);
590
591 static inline void memcpy_u64s_small(void *dst, const void *src,
592                                      unsigned u64s)
593 {
594         u64 *d = dst;
595         const u64 *s = src;
596
597         while (u64s--)
598                 *d++ = *s++;
599 }
600
601 static inline void __memcpy_u64s(void *dst, const void *src,
602                                  unsigned u64s)
603 {
604 #ifdef CONFIG_X86_64
605         long d0, d1, d2;
606         asm volatile("rep ; movsq"
607                      : "=&c" (d0), "=&D" (d1), "=&S" (d2)
608                      : "0" (u64s), "1" (dst), "2" (src)
609                      : "memory");
610 #else
611         u64 *d = dst;
612         const u64 *s = src;
613
614         while (u64s--)
615                 *d++ = *s++;
616 #endif
617 }
618
619 static inline void memcpy_u64s(void *dst, const void *src,
620                                unsigned u64s)
621 {
622         EBUG_ON(!(dst >= src + u64s * sizeof(u64) ||
623                  dst + u64s * sizeof(u64) <= src));
624
625         __memcpy_u64s(dst, src, u64s);
626 }
627
628 static inline void __memmove_u64s_down(void *dst, const void *src,
629                                        unsigned u64s)
630 {
631         __memcpy_u64s(dst, src, u64s);
632 }
633
634 static inline void memmove_u64s_down(void *dst, const void *src,
635                                      unsigned u64s)
636 {
637         EBUG_ON(dst > src);
638
639         __memmove_u64s_down(dst, src, u64s);
640 }
641
642 static inline void __memmove_u64s_down_small(void *dst, const void *src,
643                                        unsigned u64s)
644 {
645         memcpy_u64s_small(dst, src, u64s);
646 }
647
648 static inline void memmove_u64s_down_small(void *dst, const void *src,
649                                      unsigned u64s)
650 {
651         EBUG_ON(dst > src);
652
653         __memmove_u64s_down_small(dst, src, u64s);
654 }
655
656 static inline void __memmove_u64s_up_small(void *_dst, const void *_src,
657                                            unsigned u64s)
658 {
659         u64 *dst = (u64 *) _dst + u64s;
660         u64 *src = (u64 *) _src + u64s;
661
662         while (u64s--)
663                 *--dst = *--src;
664 }
665
666 static inline void memmove_u64s_up_small(void *dst, const void *src,
667                                          unsigned u64s)
668 {
669         EBUG_ON(dst < src);
670
671         __memmove_u64s_up_small(dst, src, u64s);
672 }
673
674 static inline void __memmove_u64s_up(void *_dst, const void *_src,
675                                      unsigned u64s)
676 {
677         u64 *dst = (u64 *) _dst + u64s - 1;
678         u64 *src = (u64 *) _src + u64s - 1;
679
680 #ifdef CONFIG_X86_64
681         long d0, d1, d2;
682         asm volatile("std ;\n"
683                      "rep ; movsq\n"
684                      "cld ;\n"
685                      : "=&c" (d0), "=&D" (d1), "=&S" (d2)
686                      : "0" (u64s), "1" (dst), "2" (src)
687                      : "memory");
688 #else
689         while (u64s--)
690                 *dst-- = *src--;
691 #endif
692 }
693
694 static inline void memmove_u64s_up(void *dst, const void *src,
695                                    unsigned u64s)
696 {
697         EBUG_ON(dst < src);
698
699         __memmove_u64s_up(dst, src, u64s);
700 }
701
702 static inline void memmove_u64s(void *dst, const void *src,
703                                 unsigned u64s)
704 {
705         if (dst < src)
706                 __memmove_u64s_down(dst, src, u64s);
707         else
708                 __memmove_u64s_up(dst, src, u64s);
709 }
710
711 /* Set the last few bytes up to a u64 boundary given an offset into a buffer. */
712 static inline void memset_u64s_tail(void *s, int c, unsigned bytes)
713 {
714         unsigned rem = round_up(bytes, sizeof(u64)) - bytes;
715
716         memset(s + bytes, c, rem);
717 }
718
719 void sort_cmp_size(void *base, size_t num, size_t size,
720           int (*cmp_func)(const void *, const void *, size_t),
721           void (*swap_func)(void *, void *, size_t));
722
723 /* just the memmove, doesn't update @_nr */
724 #define __array_insert_item(_array, _nr, _pos)                          \
725         memmove(&(_array)[(_pos) + 1],                                  \
726                 &(_array)[(_pos)],                                      \
727                 sizeof((_array)[0]) * ((_nr) - (_pos)))
728
729 #define array_insert_item(_array, _nr, _pos, _new_item)                 \
730 do {                                                                    \
731         __array_insert_item(_array, _nr, _pos);                         \
732         (_nr)++;                                                        \
733         (_array)[(_pos)] = (_new_item);                                 \
734 } while (0)
735
736 #define array_remove_items(_array, _nr, _pos, _nr_to_remove)            \
737 do {                                                                    \
738         (_nr) -= (_nr_to_remove);                                       \
739         memmove(&(_array)[(_pos)],                                      \
740                 &(_array)[(_pos) + (_nr_to_remove)],                    \
741                 sizeof((_array)[0]) * ((_nr) - (_pos)));                \
742 } while (0)
743
744 #define array_remove_item(_array, _nr, _pos)                            \
745         array_remove_items(_array, _nr, _pos, 1)
746
747 static inline void __move_gap(void *array, size_t element_size,
748                               size_t nr, size_t size,
749                               size_t old_gap, size_t new_gap)
750 {
751         size_t gap_end = old_gap + size - nr;
752
753         if (new_gap < old_gap) {
754                 size_t move = old_gap - new_gap;
755
756                 memmove(array + element_size * (gap_end - move),
757                         array + element_size * (old_gap - move),
758                                 element_size * move);
759         } else if (new_gap > old_gap) {
760                 size_t move = new_gap - old_gap;
761
762                 memmove(array + element_size * old_gap,
763                         array + element_size * gap_end,
764                                 element_size * move);
765         }
766 }
767
768 /* Move the gap in a gap buffer: */
769 #define move_gap(_array, _nr, _size, _old_gap, _new_gap)        \
770         __move_gap(_array, sizeof(_array[0]), _nr, _size, _old_gap, _new_gap)
771
772 #define bubble_sort(_base, _nr, _cmp)                                   \
773 do {                                                                    \
774         ssize_t _i, _end;                                               \
775         bool _swapped = true;                                           \
776                                                                         \
777         for (_end = (ssize_t) (_nr) - 1; _end > 0 && _swapped; --_end) {\
778                 _swapped = false;                                       \
779                 for (_i = 0; _i < _end; _i++)                           \
780                         if (_cmp((_base)[_i], (_base)[_i + 1]) > 0) {   \
781                                 swap((_base)[_i], (_base)[_i + 1]);     \
782                                 _swapped = true;                        \
783                         }                                               \
784         }                                                               \
785 } while (0)
786
787 static inline u64 percpu_u64_get(u64 __percpu *src)
788 {
789         u64 ret = 0;
790         int cpu;
791
792         for_each_possible_cpu(cpu)
793                 ret += *per_cpu_ptr(src, cpu);
794         return ret;
795 }
796
797 static inline void percpu_u64_set(u64 __percpu *dst, u64 src)
798 {
799         int cpu;
800
801         for_each_possible_cpu(cpu)
802                 *per_cpu_ptr(dst, cpu) = 0;
803         this_cpu_write(*dst, src);
804 }
805
806 static inline void acc_u64s(u64 *acc, const u64 *src, unsigned nr)
807 {
808         unsigned i;
809
810         for (i = 0; i < nr; i++)
811                 acc[i] += src[i];
812 }
813
814 static inline void acc_u64s_percpu(u64 *acc, const u64 __percpu *src,
815                                    unsigned nr)
816 {
817         int cpu;
818
819         for_each_possible_cpu(cpu)
820                 acc_u64s(acc, per_cpu_ptr(src, cpu), nr);
821 }
822
823 static inline void percpu_memset(void __percpu *p, int c, size_t bytes)
824 {
825         int cpu;
826
827         for_each_possible_cpu(cpu)
828                 memset(per_cpu_ptr(p, cpu), c, bytes);
829 }
830
831 u64 *bch2_acc_percpu_u64s(u64 __percpu *, unsigned);
832
833 #define cmp_int(l, r)           ((l > r) - (l < r))
834
835 static inline int u8_cmp(u8 l, u8 r)
836 {
837         return cmp_int(l, r);
838 }
839
840 #include <linux/uuid.h>
841
842 static inline int uuid_le_cmp(const uuid_le u1, const uuid_le u2)
843 {
844         return memcmp(&u1, &u2, sizeof(uuid_le));
845 }
846
847 #endif /* _BCACHEFS_UTIL_H */