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