bcachefs: Initial commit
[linux-block.git] / fs / bcachefs / util.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * random utiility code, for bcache but in theory not specific to bcache
4  *
5  * Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
6  * Copyright 2012 Google, Inc.
7  */
8
9 #include <linux/bio.h>
10 #include <linux/blkdev.h>
11 #include <linux/ctype.h>
12 #include <linux/debugfs.h>
13 #include <linux/freezer.h>
14 #include <linux/kthread.h>
15 #include <linux/log2.h>
16 #include <linux/math64.h>
17 #include <linux/percpu.h>
18 #include <linux/preempt.h>
19 #include <linux/random.h>
20 #include <linux/seq_file.h>
21 #include <linux/string.h>
22 #include <linux/types.h>
23 #include <linux/sched/clock.h>
24
25 #include "eytzinger.h"
26 #include "util.h"
27
28 #define simple_strtoint(c, end, base)   simple_strtol(c, end, base)
29 #define simple_strtouint(c, end, base)  simple_strtoul(c, end, base)
30
31 static const char si_units[] = "?kMGTPEZY";
32
33 static int __bch2_strtoh(const char *cp, u64 *res,
34                          u64 t_max, bool t_signed)
35 {
36         bool positive = *cp != '-';
37         unsigned u;
38         u64 v = 0;
39
40         if (*cp == '+' || *cp == '-')
41                 cp++;
42
43         if (!isdigit(*cp))
44                 return -EINVAL;
45
46         do {
47                 if (v > U64_MAX / 10)
48                         return -ERANGE;
49                 v *= 10;
50                 if (v > U64_MAX - (*cp - '0'))
51                         return -ERANGE;
52                 v += *cp - '0';
53                 cp++;
54         } while (isdigit(*cp));
55
56         for (u = 1; u < strlen(si_units); u++)
57                 if (*cp == si_units[u]) {
58                         cp++;
59                         goto got_unit;
60                 }
61         u = 0;
62 got_unit:
63         if (*cp == '\n')
64                 cp++;
65         if (*cp)
66                 return -EINVAL;
67
68         if (fls64(v) + u * 10 > 64)
69                 return -ERANGE;
70
71         v <<= u * 10;
72
73         if (positive) {
74                 if (v > t_max)
75                         return -ERANGE;
76         } else {
77                 if (v && !t_signed)
78                         return -ERANGE;
79
80                 if (v > t_max + 1)
81                         return -ERANGE;
82                 v = -v;
83         }
84
85         *res = v;
86         return 0;
87 }
88
89 #define STRTO_H(name, type)                                     \
90 int bch2_ ## name ## _h(const char *cp, type *res)              \
91 {                                                               \
92         u64 v;                                                  \
93         int ret = __bch2_strtoh(cp, &v, ANYSINT_MAX(type),      \
94                         ANYSINT_MAX(type) != ((type) ~0ULL));   \
95         *res = v;                                               \
96         return ret;                                             \
97 }
98
99 STRTO_H(strtoint, int)
100 STRTO_H(strtouint, unsigned int)
101 STRTO_H(strtoll, long long)
102 STRTO_H(strtoull, unsigned long long)
103
104 ssize_t bch2_hprint(char *buf, s64 v)
105 {
106         char dec[4] = "";
107         int u, t = 0;
108
109         for (u = 0; v >= 1024 || v <= -1024; u++) {
110                 t = v & ~(~0U << 10);
111                 v >>= 10;
112         }
113
114         if (!u)
115                 return sprintf(buf, "%lli", v);
116
117         /*
118          * 103 is magic: t is in the range [-1023, 1023] and we want
119          * to turn it into [-9, 9]
120          */
121         if (v < 100 && v > -100)
122                 scnprintf(dec, sizeof(dec), ".%i", t / 103);
123
124         return sprintf(buf, "%lli%s%c", v, dec, si_units[u]);
125 }
126
127 ssize_t bch2_scnprint_string_list(char *buf, size_t size,
128                                   const char * const list[],
129                                   size_t selected)
130 {
131         char *out = buf;
132         size_t i;
133
134         if (size)
135                 *out = '\0';
136
137         for (i = 0; list[i]; i++)
138                 out += scnprintf(out, buf + size - out,
139                                  i == selected ? "[%s] " : "%s ", list[i]);
140
141         if (out != buf)
142                 *--out = '\0';
143
144         return out - buf;
145 }
146
147 ssize_t bch2_scnprint_flag_list(char *buf, size_t size,
148                                 const char * const list[], u64 flags)
149 {
150         char *out = buf, *end = buf + size;
151         unsigned bit, nr = 0;
152
153         while (list[nr])
154                 nr++;
155
156         if (size)
157                 *out = '\0';
158
159         while (flags && (bit = __ffs(flags)) < nr) {
160                 out += scnprintf(out, end - out, "%s,", list[bit]);
161                 flags ^= 1 << bit;
162         }
163
164         if (out != buf)
165                 *--out = '\0';
166
167         return out - buf;
168 }
169
170 u64 bch2_read_flag_list(char *opt, const char * const list[])
171 {
172         u64 ret = 0;
173         char *p, *s, *d = kstrndup(opt, PAGE_SIZE - 1, GFP_KERNEL);
174
175         if (!d)
176                 return -ENOMEM;
177
178         s = strim(d);
179
180         while ((p = strsep(&s, ","))) {
181                 int flag = match_string(list, -1, p);
182                 if (flag < 0) {
183                         ret = -1;
184                         break;
185                 }
186
187                 ret |= 1 << flag;
188         }
189
190         kfree(d);
191
192         return ret;
193 }
194
195 bool bch2_is_zero(const void *_p, size_t n)
196 {
197         const char *p = _p;
198         size_t i;
199
200         for (i = 0; i < n; i++)
201                 if (p[i])
202                         return false;
203         return true;
204 }
205
206 /* time stats: */
207
208 #ifndef CONFIG_BCACHEFS_NO_LATENCY_ACCT
209 static void bch2_quantiles_update(struct bch2_quantiles *q, u64 v)
210 {
211         unsigned i = 0;
212
213         while (i < ARRAY_SIZE(q->entries)) {
214                 struct bch2_quantile_entry *e = q->entries + i;
215
216                 if (unlikely(!e->step)) {
217                         e->m = v;
218                         e->step = max_t(unsigned, v / 2, 1024);
219                 } else if (e->m > v) {
220                         e->m = e->m >= e->step
221                                 ? e->m - e->step
222                                 : 0;
223                 } else if (e->m < v) {
224                         e->m = e->m + e->step > e->m
225                                 ? e->m + e->step
226                                 : U32_MAX;
227                 }
228
229                 if ((e->m > v ? e->m - v : v - e->m) < e->step)
230                         e->step = max_t(unsigned, e->step / 2, 1);
231
232                 if (v >= e->m)
233                         break;
234
235                 i = eytzinger0_child(i, v > e->m);
236         }
237 }
238
239 static void bch2_time_stats_update_one(struct bch2_time_stats *stats,
240                                        u64 start, u64 end)
241 {
242         u64 duration, freq;
243
244         duration        = time_after64(end, start)
245                 ? end - start : 0;
246         freq            = time_after64(end, stats->last_event)
247                 ? end - stats->last_event : 0;
248
249         stats->count++;
250
251         stats->average_duration = stats->average_duration
252                 ? ewma_add(stats->average_duration, duration, 6)
253                 : duration;
254
255         stats->average_frequency = stats->average_frequency
256                 ? ewma_add(stats->average_frequency, freq, 6)
257                 : freq;
258
259         stats->max_duration = max(stats->max_duration, duration);
260
261         stats->last_event = end;
262
263         bch2_quantiles_update(&stats->quantiles, duration);
264 }
265
266 void __bch2_time_stats_update(struct bch2_time_stats *stats, u64 start, u64 end)
267 {
268         unsigned long flags;
269
270         if (!stats->buffer) {
271                 spin_lock_irqsave(&stats->lock, flags);
272                 bch2_time_stats_update_one(stats, start, end);
273
274                 if (stats->average_frequency < 32 &&
275                     stats->count > 1024)
276                         stats->buffer =
277                                 alloc_percpu_gfp(struct bch2_time_stat_buffer,
278                                                  GFP_ATOMIC);
279                 spin_unlock_irqrestore(&stats->lock, flags);
280         } else {
281                 struct bch2_time_stat_buffer_entry *i;
282                 struct bch2_time_stat_buffer *b;
283
284                 preempt_disable();
285                 b = this_cpu_ptr(stats->buffer);
286
287                 BUG_ON(b->nr >= ARRAY_SIZE(b->entries));
288                 b->entries[b->nr++] = (struct bch2_time_stat_buffer_entry) {
289                         .start = start,
290                         .end = end
291                 };
292
293                 if (b->nr == ARRAY_SIZE(b->entries)) {
294                         spin_lock_irqsave(&stats->lock, flags);
295                         for (i = b->entries;
296                              i < b->entries + ARRAY_SIZE(b->entries);
297                              i++)
298                                 bch2_time_stats_update_one(stats, i->start, i->end);
299                         spin_unlock_irqrestore(&stats->lock, flags);
300
301                         b->nr = 0;
302                 }
303
304                 preempt_enable();
305         }
306 }
307 #endif
308
309 static const struct time_unit {
310         const char      *name;
311         u32             nsecs;
312 } time_units[] = {
313         { "ns",         1               },
314         { "us",         NSEC_PER_USEC   },
315         { "ms",         NSEC_PER_MSEC   },
316         { "sec",        NSEC_PER_SEC    },
317 };
318
319 static const struct time_unit *pick_time_units(u64 ns)
320 {
321         const struct time_unit *u;
322
323         for (u = time_units;
324              u + 1 < time_units + ARRAY_SIZE(time_units) &&
325              ns >= u[1].nsecs << 1;
326              u++)
327                 ;
328
329         return u;
330 }
331
332 static size_t pr_time_units(char *buf, size_t len, u64 ns)
333 {
334         const struct time_unit *u = pick_time_units(ns);
335
336         return scnprintf(buf, len, "%llu %s", div_u64(ns, u->nsecs), u->name);
337 }
338
339 size_t bch2_time_stats_print(struct bch2_time_stats *stats, char *buf, size_t len)
340 {
341         char *out = buf, *end = buf + len;
342         const struct time_unit *u;
343         u64 freq = READ_ONCE(stats->average_frequency);
344         u64 q, last_q = 0;
345         int i;
346
347         out += scnprintf(out, end - out, "count:\t\t%llu\n",
348                          stats->count);
349         out += scnprintf(out, end - out, "rate:\t\t%llu/sec\n",
350                          freq ?  div64_u64(NSEC_PER_SEC, freq) : 0);
351
352         out += scnprintf(out, end - out, "frequency:\t");
353         out += pr_time_units(out, end - out, freq);
354
355         out += scnprintf(out, end - out, "\navg duration:\t");
356         out += pr_time_units(out, end - out, stats->average_duration);
357
358         out += scnprintf(out, end - out, "\nmax duration:\t");
359         out += pr_time_units(out, end - out, stats->max_duration);
360
361         i = eytzinger0_first(NR_QUANTILES);
362         u = pick_time_units(stats->quantiles.entries[i].m);
363
364         out += scnprintf(out, end - out, "\nquantiles (%s):\t", u->name);
365         eytzinger0_for_each(i, NR_QUANTILES) {
366                 bool is_last = eytzinger0_next(i, NR_QUANTILES) == -1;
367
368                 q = max(stats->quantiles.entries[i].m, last_q);
369                 out += scnprintf(out, end - out, "%llu%s",
370                                  div_u64(q, u->nsecs),
371                                  is_last ? "\n" : " ");
372                 last_q = q;
373         }
374
375         return out - buf;
376 }
377
378 void bch2_time_stats_exit(struct bch2_time_stats *stats)
379 {
380         free_percpu(stats->buffer);
381 }
382
383 void bch2_time_stats_init(struct bch2_time_stats *stats)
384 {
385         memset(stats, 0, sizeof(*stats));
386         spin_lock_init(&stats->lock);
387 }
388
389 /* ratelimit: */
390
391 /**
392  * bch2_ratelimit_delay() - return how long to delay until the next time to do
393  * some work
394  *
395  * @d - the struct bch_ratelimit to update
396  *
397  * Returns the amount of time to delay by, in jiffies
398  */
399 u64 bch2_ratelimit_delay(struct bch_ratelimit *d)
400 {
401         u64 now = local_clock();
402
403         return time_after64(d->next, now)
404                 ? nsecs_to_jiffies(d->next - now)
405                 : 0;
406 }
407
408 /**
409  * bch2_ratelimit_increment() - increment @d by the amount of work done
410  *
411  * @d - the struct bch_ratelimit to update
412  * @done - the amount of work done, in arbitrary units
413  */
414 void bch2_ratelimit_increment(struct bch_ratelimit *d, u64 done)
415 {
416         u64 now = local_clock();
417
418         d->next += div_u64(done * NSEC_PER_SEC, d->rate);
419
420         if (time_before64(now + NSEC_PER_SEC, d->next))
421                 d->next = now + NSEC_PER_SEC;
422
423         if (time_after64(now - NSEC_PER_SEC * 2, d->next))
424                 d->next = now - NSEC_PER_SEC * 2;
425 }
426
427 int bch2_ratelimit_wait_freezable_stoppable(struct bch_ratelimit *d)
428 {
429         bool kthread = (current->flags & PF_KTHREAD) != 0;
430
431         while (1) {
432                 u64 delay = bch2_ratelimit_delay(d);
433
434                 if (delay)
435                         set_current_state(TASK_INTERRUPTIBLE);
436
437                 if (kthread && kthread_should_stop())
438                         return 1;
439
440                 if (!delay)
441                         return 0;
442
443                 schedule_timeout(delay);
444                 try_to_freeze();
445         }
446 }
447
448 /* pd controller: */
449
450 /*
451  * Updates pd_controller. Attempts to scale inputed values to units per second.
452  * @target: desired value
453  * @actual: current value
454  *
455  * @sign: 1 or -1; 1 if increasing the rate makes actual go up, -1 if increasing
456  * it makes actual go down.
457  */
458 void bch2_pd_controller_update(struct bch_pd_controller *pd,
459                               s64 target, s64 actual, int sign)
460 {
461         s64 proportional, derivative, change;
462
463         unsigned long seconds_since_update = (jiffies - pd->last_update) / HZ;
464
465         if (seconds_since_update == 0)
466                 return;
467
468         pd->last_update = jiffies;
469
470         proportional = actual - target;
471         proportional *= seconds_since_update;
472         proportional = div_s64(proportional, pd->p_term_inverse);
473
474         derivative = actual - pd->last_actual;
475         derivative = div_s64(derivative, seconds_since_update);
476         derivative = ewma_add(pd->smoothed_derivative, derivative,
477                               (pd->d_term / seconds_since_update) ?: 1);
478         derivative = derivative * pd->d_term;
479         derivative = div_s64(derivative, pd->p_term_inverse);
480
481         change = proportional + derivative;
482
483         /* Don't increase rate if not keeping up */
484         if (change > 0 &&
485             pd->backpressure &&
486             time_after64(local_clock(),
487                          pd->rate.next + NSEC_PER_MSEC))
488                 change = 0;
489
490         change *= (sign * -1);
491
492         pd->rate.rate = clamp_t(s64, (s64) pd->rate.rate + change,
493                                 1, UINT_MAX);
494
495         pd->last_actual         = actual;
496         pd->last_derivative     = derivative;
497         pd->last_proportional   = proportional;
498         pd->last_change         = change;
499         pd->last_target         = target;
500 }
501
502 void bch2_pd_controller_init(struct bch_pd_controller *pd)
503 {
504         pd->rate.rate           = 1024;
505         pd->last_update         = jiffies;
506         pd->p_term_inverse      = 6000;
507         pd->d_term              = 30;
508         pd->d_smooth            = pd->d_term;
509         pd->backpressure        = 1;
510 }
511
512 size_t bch2_pd_controller_print_debug(struct bch_pd_controller *pd, char *buf)
513 {
514         /* 2^64 - 1 is 20 digits, plus null byte */
515         char rate[21];
516         char actual[21];
517         char target[21];
518         char proportional[21];
519         char derivative[21];
520         char change[21];
521         s64 next_io;
522
523         bch2_hprint(rate,       pd->rate.rate);
524         bch2_hprint(actual,     pd->last_actual);
525         bch2_hprint(target,     pd->last_target);
526         bch2_hprint(proportional, pd->last_proportional);
527         bch2_hprint(derivative, pd->last_derivative);
528         bch2_hprint(change,     pd->last_change);
529
530         next_io = div64_s64(pd->rate.next - local_clock(), NSEC_PER_MSEC);
531
532         return sprintf(buf,
533                        "rate:\t\t%s/sec\n"
534                        "target:\t\t%s\n"
535                        "actual:\t\t%s\n"
536                        "proportional:\t%s\n"
537                        "derivative:\t%s\n"
538                        "change:\t\t%s/sec\n"
539                        "next io:\t%llims\n",
540                        rate, target, actual, proportional,
541                        derivative, change, next_io);
542 }
543
544 /* misc: */
545
546 void bch2_bio_map(struct bio *bio, void *base)
547 {
548         size_t size = bio->bi_iter.bi_size;
549         struct bio_vec *bv = bio->bi_io_vec;
550
551         BUG_ON(!bio->bi_iter.bi_size);
552         BUG_ON(bio->bi_vcnt);
553
554         bv->bv_offset = base ? offset_in_page(base) : 0;
555         goto start;
556
557         for (; size; bio->bi_vcnt++, bv++) {
558                 bv->bv_offset   = 0;
559 start:          bv->bv_len      = min_t(size_t, PAGE_SIZE - bv->bv_offset,
560                                         size);
561                 BUG_ON(bio->bi_vcnt >= bio->bi_max_vecs);
562                 if (base) {
563                         bv->bv_page = is_vmalloc_addr(base)
564                                 ? vmalloc_to_page(base)
565                                 : virt_to_page(base);
566
567                         base += bv->bv_len;
568                 }
569
570                 size -= bv->bv_len;
571         }
572 }
573
574 int bch2_bio_alloc_pages(struct bio *bio, size_t size, gfp_t gfp_mask)
575 {
576         while (size) {
577                 struct page *page = alloc_pages(gfp_mask, 0);
578                 unsigned len = min_t(size_t, PAGE_SIZE, size);
579
580                 if (!page)
581                         return -ENOMEM;
582
583                 if (unlikely(!bio_add_page(bio, page, len, 0))) {
584                         __free_page(page);
585                         break;
586                 }
587
588                 size -= len;
589         }
590
591         return 0;
592 }
593
594 size_t bch2_rand_range(size_t max)
595 {
596         size_t rand;
597
598         if (!max)
599                 return 0;
600
601         do {
602                 rand = get_random_long();
603                 rand &= roundup_pow_of_two(max) - 1;
604         } while (rand >= max);
605
606         return rand;
607 }
608
609 void memcpy_to_bio(struct bio *dst, struct bvec_iter dst_iter, void *src)
610 {
611         struct bio_vec bv;
612         struct bvec_iter iter;
613
614         __bio_for_each_segment(bv, dst, iter, dst_iter) {
615                 void *dstp = kmap_atomic(bv.bv_page);
616                 memcpy(dstp + bv.bv_offset, src, bv.bv_len);
617                 kunmap_atomic(dstp);
618
619                 src += bv.bv_len;
620         }
621 }
622
623 void memcpy_from_bio(void *dst, struct bio *src, struct bvec_iter src_iter)
624 {
625         struct bio_vec bv;
626         struct bvec_iter iter;
627
628         __bio_for_each_segment(bv, src, iter, src_iter) {
629                 void *srcp = kmap_atomic(bv.bv_page);
630                 memcpy(dst, srcp + bv.bv_offset, bv.bv_len);
631                 kunmap_atomic(srcp);
632
633                 dst += bv.bv_len;
634         }
635 }
636
637 size_t bch_scnmemcpy(char *buf, size_t size, const char *src, size_t len)
638 {
639         size_t n;
640
641         if (!size)
642                 return 0;
643
644         n = min(size - 1, len);
645         memcpy(buf, src, n);
646         buf[n] = '\0';
647
648         return n;
649 }
650
651 #include "eytzinger.h"
652
653 static int alignment_ok(const void *base, size_t align)
654 {
655         return IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) ||
656                 ((unsigned long)base & (align - 1)) == 0;
657 }
658
659 static void u32_swap(void *a, void *b, size_t size)
660 {
661         u32 t = *(u32 *)a;
662         *(u32 *)a = *(u32 *)b;
663         *(u32 *)b = t;
664 }
665
666 static void u64_swap(void *a, void *b, size_t size)
667 {
668         u64 t = *(u64 *)a;
669         *(u64 *)a = *(u64 *)b;
670         *(u64 *)b = t;
671 }
672
673 static void generic_swap(void *a, void *b, size_t size)
674 {
675         char t;
676
677         do {
678                 t = *(char *)a;
679                 *(char *)a++ = *(char *)b;
680                 *(char *)b++ = t;
681         } while (--size > 0);
682 }
683
684 static inline int do_cmp(void *base, size_t n, size_t size,
685                          int (*cmp_func)(const void *, const void *, size_t),
686                          size_t l, size_t r)
687 {
688         return cmp_func(base + inorder_to_eytzinger0(l, n) * size,
689                         base + inorder_to_eytzinger0(r, n) * size,
690                         size);
691 }
692
693 static inline void do_swap(void *base, size_t n, size_t size,
694                            void (*swap_func)(void *, void *, size_t),
695                            size_t l, size_t r)
696 {
697         swap_func(base + inorder_to_eytzinger0(l, n) * size,
698                   base + inorder_to_eytzinger0(r, n) * size,
699                   size);
700 }
701
702 void eytzinger0_sort(void *base, size_t n, size_t size,
703                      int (*cmp_func)(const void *, const void *, size_t),
704                      void (*swap_func)(void *, void *, size_t))
705 {
706         int i, c, r;
707
708         if (!swap_func) {
709                 if (size == 4 && alignment_ok(base, 4))
710                         swap_func = u32_swap;
711                 else if (size == 8 && alignment_ok(base, 8))
712                         swap_func = u64_swap;
713                 else
714                         swap_func = generic_swap;
715         }
716
717         /* heapify */
718         for (i = n / 2 - 1; i >= 0; --i) {
719                 for (r = i; r * 2 + 1 < n; r = c) {
720                         c = r * 2 + 1;
721
722                         if (c + 1 < n &&
723                             do_cmp(base, n, size, cmp_func, c, c + 1) < 0)
724                                 c++;
725
726                         if (do_cmp(base, n, size, cmp_func, r, c) >= 0)
727                                 break;
728
729                         do_swap(base, n, size, swap_func, r, c);
730                 }
731         }
732
733         /* sort */
734         for (i = n - 1; i > 0; --i) {
735                 do_swap(base, n, size, swap_func, 0, i);
736
737                 for (r = 0; r * 2 + 1 < i; r = c) {
738                         c = r * 2 + 1;
739
740                         if (c + 1 < i &&
741                             do_cmp(base, n, size, cmp_func, c, c + 1) < 0)
742                                 c++;
743
744                         if (do_cmp(base, n, size, cmp_func, r, c) >= 0)
745                                 break;
746
747                         do_swap(base, n, size, swap_func, r, c);
748                 }
749         }
750 }
751
752 void sort_cmp_size(void *base, size_t num, size_t size,
753           int (*cmp_func)(const void *, const void *, size_t),
754           void (*swap_func)(void *, void *, size_t size))
755 {
756         /* pre-scale counters for performance */
757         int i = (num/2 - 1) * size, n = num * size, c, r;
758
759         if (!swap_func) {
760                 if (size == 4 && alignment_ok(base, 4))
761                         swap_func = u32_swap;
762                 else if (size == 8 && alignment_ok(base, 8))
763                         swap_func = u64_swap;
764                 else
765                         swap_func = generic_swap;
766         }
767
768         /* heapify */
769         for ( ; i >= 0; i -= size) {
770                 for (r = i; r * 2 + size < n; r  = c) {
771                         c = r * 2 + size;
772                         if (c < n - size &&
773                             cmp_func(base + c, base + c + size, size) < 0)
774                                 c += size;
775                         if (cmp_func(base + r, base + c, size) >= 0)
776                                 break;
777                         swap_func(base + r, base + c, size);
778                 }
779         }
780
781         /* sort */
782         for (i = n - size; i > 0; i -= size) {
783                 swap_func(base, base + i, size);
784                 for (r = 0; r * 2 + size < i; r = c) {
785                         c = r * 2 + size;
786                         if (c < i - size &&
787                             cmp_func(base + c, base + c + size, size) < 0)
788                                 c += size;
789                         if (cmp_func(base + r, base + c, size) >= 0)
790                                 break;
791                         swap_func(base + r, base + c, size);
792                 }
793         }
794 }
795
796 static void mempool_free_vp(void *element, void *pool_data)
797 {
798         size_t size = (size_t) pool_data;
799
800         vpfree(element, size);
801 }
802
803 static void *mempool_alloc_vp(gfp_t gfp_mask, void *pool_data)
804 {
805         size_t size = (size_t) pool_data;
806
807         return vpmalloc(size, gfp_mask);
808 }
809
810 int mempool_init_kvpmalloc_pool(mempool_t *pool, int min_nr, size_t size)
811 {
812         return size < PAGE_SIZE
813                 ? mempool_init_kmalloc_pool(pool, min_nr, size)
814                 : mempool_init(pool, min_nr, mempool_alloc_vp,
815                                mempool_free_vp, (void *) size);
816 }
817
818 #if 0
819 void eytzinger1_test(void)
820 {
821         unsigned inorder, eytz, size;
822
823         pr_info("1 based eytzinger test:");
824
825         for (size = 2;
826              size < 65536;
827              size++) {
828                 unsigned extra = eytzinger1_extra(size);
829
830                 if (!(size % 4096))
831                         pr_info("tree size %u", size);
832
833                 BUG_ON(eytzinger1_prev(0, size) != eytzinger1_last(size));
834                 BUG_ON(eytzinger1_next(0, size) != eytzinger1_first(size));
835
836                 BUG_ON(eytzinger1_prev(eytzinger1_first(size), size)    != 0);
837                 BUG_ON(eytzinger1_next(eytzinger1_last(size), size)     != 0);
838
839                 inorder = 1;
840                 eytzinger1_for_each(eytz, size) {
841                         BUG_ON(__inorder_to_eytzinger1(inorder, size, extra) != eytz);
842                         BUG_ON(__eytzinger1_to_inorder(eytz, size, extra) != inorder);
843                         BUG_ON(eytz != eytzinger1_last(size) &&
844                                eytzinger1_prev(eytzinger1_next(eytz, size), size) != eytz);
845
846                         inorder++;
847                 }
848         }
849 }
850
851 void eytzinger0_test(void)
852 {
853
854         unsigned inorder, eytz, size;
855
856         pr_info("0 based eytzinger test:");
857
858         for (size = 1;
859              size < 65536;
860              size++) {
861                 unsigned extra = eytzinger0_extra(size);
862
863                 if (!(size % 4096))
864                         pr_info("tree size %u", size);
865
866                 BUG_ON(eytzinger0_prev(-1, size) != eytzinger0_last(size));
867                 BUG_ON(eytzinger0_next(-1, size) != eytzinger0_first(size));
868
869                 BUG_ON(eytzinger0_prev(eytzinger0_first(size), size)    != -1);
870                 BUG_ON(eytzinger0_next(eytzinger0_last(size), size)     != -1);
871
872                 inorder = 0;
873                 eytzinger0_for_each(eytz, size) {
874                         BUG_ON(__inorder_to_eytzinger0(inorder, size, extra) != eytz);
875                         BUG_ON(__eytzinger0_to_inorder(eytz, size, extra) != inorder);
876                         BUG_ON(eytz != eytzinger0_last(size) &&
877                                eytzinger0_prev(eytzinger0_next(eytz, size), size) != eytz);
878
879                         inorder++;
880                 }
881         }
882 }
883
884 static inline int cmp_u16(const void *_l, const void *_r, size_t size)
885 {
886         const u16 *l = _l, *r = _r;
887
888         return (*l > *r) - (*r - *l);
889 }
890
891 static void eytzinger0_find_test_val(u16 *test_array, unsigned nr, u16 search)
892 {
893         int i, c1 = -1, c2 = -1;
894         ssize_t r;
895
896         r = eytzinger0_find_le(test_array, nr,
897                                sizeof(test_array[0]),
898                                cmp_u16, &search);
899         if (r >= 0)
900                 c1 = test_array[r];
901
902         for (i = 0; i < nr; i++)
903                 if (test_array[i] <= search && test_array[i] > c2)
904                         c2 = test_array[i];
905
906         if (c1 != c2) {
907                 eytzinger0_for_each(i, nr)
908                         pr_info("[%3u] = %12u", i, test_array[i]);
909                 pr_info("find_le(%2u) -> [%2zi] = %2i should be %2i",
910                         i, r, c1, c2);
911         }
912 }
913
914 void eytzinger0_find_test(void)
915 {
916         unsigned i, nr, allocated = 1 << 12;
917         u16 *test_array = kmalloc_array(allocated, sizeof(test_array[0]), GFP_KERNEL);
918
919         for (nr = 1; nr < allocated; nr++) {
920                 pr_info("testing %u elems", nr);
921
922                 get_random_bytes(test_array, nr * sizeof(test_array[0]));
923                 eytzinger0_sort(test_array, nr, sizeof(test_array[0]), cmp_u16, NULL);
924
925                 /* verify array is sorted correctly: */
926                 eytzinger0_for_each(i, nr)
927                         BUG_ON(i != eytzinger0_last(nr) &&
928                                test_array[i] > test_array[eytzinger0_next(i, nr)]);
929
930                 for (i = 0; i < U16_MAX; i += 1 << 12)
931                         eytzinger0_find_test_val(test_array, nr, i);
932
933                 for (i = 0; i < nr; i++) {
934                         eytzinger0_find_test_val(test_array, nr, test_array[i] - 1);
935                         eytzinger0_find_test_val(test_array, nr, test_array[i]);
936                         eytzinger0_find_test_val(test_array, nr, test_array[i] + 1);
937                 }
938         }
939
940         kfree(test_array);
941 }
942 #endif