Fix some bugs when testing opensds ansible
[stor4nfv.git] / src / ceph / src / crush / mapper.c
1 /*
2  * Ceph - scalable distributed file system
3  *
4  * Copyright (C) 2015 Intel Corporation All Rights Reserved
5  *
6  * This is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License version 2.1, as published by the Free Software
9  * Foundation.  See file COPYING.
10  *
11  */
12
13 #ifdef __KERNEL__
14 # include <linux/string.h>
15 # include <linux/slab.h>
16 # include <linux/bug.h>
17 # include <linux/kernel.h>
18 # include <linux/crush/crush.h>
19 # include <linux/crush/hash.h>
20 #else
21 # include "crush_compat.h"
22 # include "crush.h"
23 # include "hash.h"
24 #endif
25 #include "crush_ln_table.h"
26 #include "mapper.h"
27
28 #define dprintk(args...) /* printf(args) */
29
30 /*
31  * Implement the core CRUSH mapping algorithm.
32  */
33
34 /**
35  * crush_find_rule - find a crush_rule id for a given ruleset, type, and size.
36  * @map: the crush_map
37  * @ruleset: the storage ruleset id (user defined)
38  * @type: storage ruleset type (user defined)
39  * @size: output set size
40  */
41 int crush_find_rule(const struct crush_map *map, int ruleset, int type, int size)
42 {
43         __u32 i;
44
45         for (i = 0; i < map->max_rules; i++) {
46                 if (map->rules[i] &&
47                     map->rules[i]->mask.ruleset == ruleset &&
48                     map->rules[i]->mask.type == type &&
49                     map->rules[i]->mask.min_size <= size &&
50                     map->rules[i]->mask.max_size >= size)
51                         return i;
52         }
53         return -1;
54 }
55
56 /*
57  * bucket choose methods
58  *
59  * For each bucket algorithm, we have a "choose" method that, given a
60  * crush input @x and replica position (usually, position in output set) @r,
61  * will produce an item in the bucket.
62  */
63
64 /*
65  * Choose based on a random permutation of the bucket.
66  *
67  * We used to use some prime number arithmetic to do this, but it
68  * wasn't very random, and had some other bad behaviors.  Instead, we
69  * calculate an actual random permutation of the bucket members.
70  * Since this is expensive, we optimize for the r=0 case, which
71  * captures the vast majority of calls.
72  */
73 static int bucket_perm_choose(const struct crush_bucket *bucket,
74                               struct crush_work_bucket *work,
75                               int x, int r)
76 {
77         unsigned int pr = r % bucket->size;
78         unsigned int i, s;
79
80         /* start a new permutation if @x has changed */
81         if (work->perm_x != (__u32)x || work->perm_n == 0) {
82                 dprintk("bucket %d new x=%d\n", bucket->id, x);
83                 work->perm_x = x;
84
85                 /* optimize common r=0 case */
86                 if (pr == 0) {
87                         s = crush_hash32_3(bucket->hash, x, bucket->id, 0) %
88                                 bucket->size;
89                         work->perm[0] = s;
90                         work->perm_n = 0xffff;   /* magic value, see below */
91                         goto out;
92                 }
93
94                 for (i = 0; i < bucket->size; i++)
95                         work->perm[i] = i;
96                 work->perm_n = 0;
97         } else if (work->perm_n == 0xffff) {
98                 /* clean up after the r=0 case above */
99                 for (i = 1; i < bucket->size; i++)
100                         work->perm[i] = i;
101                 work->perm[work->perm[0]] = 0;
102                 work->perm_n = 1;
103         }
104
105         /* calculate permutation up to pr */
106         for (i = 0; i < work->perm_n; i++)
107                 dprintk(" perm_choose have %d: %d\n", i, work->perm[i]);
108         while (work->perm_n <= pr) {
109                 unsigned int p = work->perm_n;
110                 /* no point in swapping the final entry */
111                 if (p < bucket->size - 1) {
112                         i = crush_hash32_3(bucket->hash, x, bucket->id, p) %
113                                 (bucket->size - p);
114                         if (i) {
115                                 unsigned int t = work->perm[p + i];
116                                 work->perm[p + i] = work->perm[p];
117                                 work->perm[p] = t;
118                         }
119                         dprintk(" perm_choose swap %d with %d\n", p, p+i);
120                 }
121                 work->perm_n++;
122         }
123         for (i = 0; i < bucket->size; i++)
124                 dprintk(" perm_choose  %d: %d\n", i, work->perm[i]);
125
126         s = work->perm[pr];
127 out:
128         dprintk(" perm_choose %d sz=%d x=%d r=%d (%d) s=%d\n", bucket->id,
129                 bucket->size, x, r, pr, s);
130         return bucket->items[s];
131 }
132
133 /* uniform */
134 static int bucket_uniform_choose(const struct crush_bucket_uniform *bucket,
135                                  struct crush_work_bucket *work, int x, int r)
136 {
137         return bucket_perm_choose(&bucket->h, work, x, r);
138 }
139
140 /* list */
141 static int bucket_list_choose(const struct crush_bucket_list *bucket,
142                               int x, int r)
143 {
144         int i;
145
146         for (i = bucket->h.size-1; i >= 0; i--) {
147                 __u64 w = crush_hash32_4(bucket->h.hash, x, bucket->h.items[i],
148                                          r, bucket->h.id);
149                 w &= 0xffff;
150                 dprintk("list_choose i=%d x=%d r=%d item %d weight %x "
151                         "sw %x rand %llx",
152                         i, x, r, bucket->h.items[i], bucket->item_weights[i],
153                         bucket->sum_weights[i], w);
154                 w *= bucket->sum_weights[i];
155                 w = w >> 16;
156                 /*dprintk(" scaled %llx\n", w);*/
157                 if (w < bucket->item_weights[i]) {
158                         return bucket->h.items[i];
159                 }
160         }
161
162         dprintk("bad list sums for bucket %d\n", bucket->h.id);
163         return bucket->h.items[0];
164 }
165
166
167 /* (binary) tree */
168 static int height(int n)
169 {
170         int h = 0;
171         while ((n & 1) == 0) {
172                 h++;
173                 n = n >> 1;
174         }
175         return h;
176 }
177
178 static int left(int x)
179 {
180         int h = height(x);
181         return x - (1 << (h-1));
182 }
183
184 static int right(int x)
185 {
186         int h = height(x);
187         return x + (1 << (h-1));
188 }
189
190 static int terminal(int x)
191 {
192         return x & 1;
193 }
194
195 static int bucket_tree_choose(const struct crush_bucket_tree *bucket,
196                               int x, int r)
197 {
198         int n;
199         __u32 w;
200         __u64 t;
201
202         /* start at root */
203         n = bucket->num_nodes >> 1;
204
205         while (!terminal(n)) {
206                 int l;
207                 /* pick point in [0, w) */
208                 w = bucket->node_weights[n];
209                 t = (__u64)crush_hash32_4(bucket->h.hash, x, n, r,
210                                           bucket->h.id) * (__u64)w;
211                 t = t >> 32;
212
213                 /* descend to the left or right? */
214                 l = left(n);
215                 if (t < bucket->node_weights[l])
216                         n = l;
217                 else
218                         n = right(n);
219         }
220
221         return bucket->h.items[n >> 1];
222 }
223
224
225 /* straw */
226
227 static int bucket_straw_choose(const struct crush_bucket_straw *bucket,
228                                int x, int r)
229 {
230         __u32 i;
231         int high = 0;
232         __u64 high_draw = 0;
233         __u64 draw;
234
235         for (i = 0; i < bucket->h.size; i++) {
236                 draw = crush_hash32_3(bucket->h.hash, x, bucket->h.items[i], r);
237                 draw &= 0xffff;
238                 draw *= bucket->straws[i];
239                 if (i == 0 || draw > high_draw) {
240                         high = i;
241                         high_draw = draw;
242                 }
243         }
244         return bucket->h.items[high];
245 }
246
247 /* compute 2^44*log2(input+1) */
248 static __u64 crush_ln(unsigned int xin)
249 {
250         unsigned int x = xin;
251         int iexpon, index1, index2;
252         __u64 RH, LH, LL, xl64, result;
253
254         x++;
255
256         /* normalize input */
257         iexpon = 15;
258
259         // figure out number of bits we need to shift and
260         // do it in one step instead of iteratively
261         if (!(x & 0x18000)) {
262           int bits = __builtin_clz(x & 0x1FFFF) - 16;
263           x <<= bits;
264           iexpon = 15 - bits;
265         }
266
267         index1 = (x >> 8) << 1;
268         /* RH ~ 2^56/index1 */
269         RH = __RH_LH_tbl[index1 - 256];
270         /* LH ~ 2^48 * log2(index1/256) */
271         LH = __RH_LH_tbl[index1 + 1 - 256];
272
273         /* RH*x ~ 2^48 * (2^15 + xf), xf<2^8 */
274         xl64 = (__s64)x * RH;
275         xl64 >>= 48;
276
277         result = iexpon;
278         result <<= (12 + 32);
279
280         index2 = xl64 & 0xff;
281         /* LL ~ 2^48*log2(1.0+index2/2^15) */
282         LL = __LL_tbl[index2];
283
284         LH = LH + LL;
285
286         LH >>= (48 - 12 - 32);
287         result += LH;
288
289         return result;
290 }
291
292
293 /*
294  * straw2
295  *
296  * for reference, see:
297  *
298  * http://en.wikipedia.org/wiki/Exponential_distribution#Distribution_of_the_minimum_of_exponential_random_variables
299  *
300  */
301
302 static inline __u32 *get_choose_arg_weights(const struct crush_bucket_straw2 *bucket,
303                                             const struct crush_choose_arg *arg,
304                                             int position)
305 {
306   if ((arg == NULL) ||
307       (arg->weight_set == NULL))
308     return bucket->item_weights;
309   if (position >= arg->weight_set_size)
310     position = arg->weight_set_size - 1;
311   return arg->weight_set[position].weights;
312 }
313
314 static inline __s32 *get_choose_arg_ids(const struct crush_bucket_straw2 *bucket,
315                                         const struct crush_choose_arg *arg)
316 {
317   if ((arg == NULL) || (arg->ids == NULL))
318     return bucket->h.items;
319   return arg->ids;
320 }
321
322 static int bucket_straw2_choose(const struct crush_bucket_straw2 *bucket,
323                                 int x, int r, const struct crush_choose_arg *arg,
324                                 int position)
325 {
326         unsigned int i, high = 0;
327         unsigned int u;
328         __s64 ln, draw, high_draw = 0;
329         __u32 *weights = get_choose_arg_weights(bucket, arg, position);
330         __s32 *ids = get_choose_arg_ids(bucket, arg);
331         for (i = 0; i < bucket->h.size; i++) {
332                 dprintk("weight 0x%x item %d\n", weights[i], ids[i]);
333                 if (weights[i]) {
334                         u = crush_hash32_3(bucket->h.hash, x, ids[i], r);
335                         u &= 0xffff;
336
337                         /*
338                          * for some reason slightly less than 0x10000 produces
339                          * a slightly more accurate distribution... probably a
340                          * rounding effect.
341                          *
342                          * the natural log lookup table maps [0,0xffff]
343                          * (corresponding to real numbers [1/0x10000, 1] to
344                          * [0, 0xffffffffffff] (corresponding to real numbers
345                          * [-11.090355,0]).
346                          */
347                         ln = crush_ln(u) - 0x1000000000000ll;
348
349                         /*
350                          * divide by 16.16 fixed-point weight.  note
351                          * that the ln value is negative, so a larger
352                          * weight means a larger (less negative) value
353                          * for draw.
354                          */
355                         draw = div64_s64(ln, weights[i]);
356                 } else {
357                         draw = S64_MIN;
358                 }
359
360                 if (i == 0 || draw > high_draw) {
361                         high = i;
362                         high_draw = draw;
363                 }
364         }
365
366         return bucket->h.items[high];
367 }
368
369
370 static int crush_bucket_choose(const struct crush_bucket *in,
371                                struct crush_work_bucket *work,
372                                int x, int r,
373                                const struct crush_choose_arg *arg,
374                                int position)
375 {
376         dprintk(" crush_bucket_choose %d x=%d r=%d\n", in->id, x, r);
377         BUG_ON(in->size == 0);
378         switch (in->alg) {
379         case CRUSH_BUCKET_UNIFORM:
380                 return bucket_uniform_choose(
381                         (const struct crush_bucket_uniform *)in,
382                         work, x, r);
383         case CRUSH_BUCKET_LIST:
384                 return bucket_list_choose((const struct crush_bucket_list *)in,
385                                           x, r);
386         case CRUSH_BUCKET_TREE:
387                 return bucket_tree_choose((const struct crush_bucket_tree *)in,
388                                           x, r);
389         case CRUSH_BUCKET_STRAW:
390                 return bucket_straw_choose(
391                         (const struct crush_bucket_straw *)in,
392                         x, r);
393         case CRUSH_BUCKET_STRAW2:
394                 return bucket_straw2_choose(
395                         (const struct crush_bucket_straw2 *)in,
396                         x, r, arg, position);
397         default:
398                 dprintk("unknown bucket %d alg %d\n", in->id, in->alg);
399                 return in->items[0];
400         }
401 }
402
403 /*
404  * true if device is marked "out" (failed, fully offloaded)
405  * of the cluster
406  */
407 static int is_out(const struct crush_map *map,
408                   const __u32 *weight, int weight_max,
409                   int item, int x)
410 {
411         if (item >= weight_max)
412                 return 1;
413         if (weight[item] >= 0x10000)
414                 return 0;
415         if (weight[item] == 0)
416                 return 1;
417         if ((crush_hash32_2(CRUSH_HASH_RJENKINS1, x, item) & 0xffff)
418             < weight[item])
419                 return 0;
420         return 1;
421 }
422
423 /**
424  * crush_choose_firstn - choose numrep distinct items of given type
425  * @map: the crush_map
426  * @bucket: the bucket we are choose an item from
427  * @x: crush input value
428  * @numrep: the number of items to choose
429  * @type: the type of item to choose
430  * @out: pointer to output vector
431  * @outpos: our position in that vector
432  * @out_size: size of the out vector
433  * @tries: number of attempts to make
434  * @recurse_tries: number of attempts to have recursive chooseleaf make
435  * @local_retries: localized retries
436  * @local_fallback_retries: localized fallback retries
437  * @recurse_to_leaf: true if we want one device under each item of given type (chooseleaf instead of choose)
438  * @stable: stable mode starts rep=0 in the recursive call for all replicas
439  * @vary_r: pass r to recursive calls
440  * @out2: second output vector for leaf items (if @recurse_to_leaf)
441  * @parent_r: r value passed from the parent
442  */
443 static int crush_choose_firstn(const struct crush_map *map,
444                                struct crush_work *work,
445                                const struct crush_bucket *bucket,
446                                const __u32 *weight, int weight_max,
447                                int x, int numrep, int type,
448                                int *out, int outpos,
449                                int out_size,
450                                unsigned int tries,
451                                unsigned int recurse_tries,
452                                unsigned int local_retries,
453                                unsigned int local_fallback_retries,
454                                int recurse_to_leaf,
455                                unsigned int vary_r,
456                                unsigned int stable,
457                                int *out2,
458                                int parent_r,
459                                const struct crush_choose_arg *choose_args)
460 {
461         int rep;
462         unsigned int ftotal, flocal;
463         int retry_descent, retry_bucket, skip_rep;
464         const struct crush_bucket *in = bucket;
465         int r;
466         int i;
467         int item = 0;
468         int itemtype;
469         int collide, reject;
470         int count = out_size;
471
472         dprintk("CHOOSE%s bucket %d x %d outpos %d numrep %d tries %d \
473 recurse_tries %d local_retries %d local_fallback_retries %d \
474 parent_r %d stable %d\n",
475                 recurse_to_leaf ? "_LEAF" : "",
476                 bucket->id, x, outpos, numrep,
477                 tries, recurse_tries, local_retries, local_fallback_retries,
478                 parent_r, stable);
479
480         for (rep = stable ? 0 : outpos; rep < numrep && count > 0 ; rep++) {
481                 /* keep trying until we get a non-out, non-colliding item */
482                 ftotal = 0;
483                 skip_rep = 0;
484                 do {
485                         retry_descent = 0;
486                         in = bucket;              /* initial bucket */
487
488                         /* choose through intervening buckets */
489                         flocal = 0;
490                         do {
491                                 collide = 0;
492                                 retry_bucket = 0;
493                                 r = rep + parent_r;
494                                 /* r' = r + f_total */
495                                 r += ftotal;
496
497                                 /* bucket choose */
498                                 if (in->size == 0) {
499                                         reject = 1;
500                                         goto reject;
501                                 }
502                                 if (local_fallback_retries > 0 &&
503                                     flocal >= (in->size>>1) &&
504                                     flocal > local_fallback_retries)
505                                         item = bucket_perm_choose(
506                                                 in, work->work[-1-in->id],
507                                                 x, r);
508                                 else
509                                         item = crush_bucket_choose(
510                                                 in, work->work[-1-in->id],
511                                                 x, r,
512                                                 (choose_args ? &choose_args[-1-in->id] : 0),
513                                                 outpos);
514                                 if (item >= map->max_devices) {
515                                         dprintk("   bad item %d\n", item);
516                                         skip_rep = 1;
517                                         break;
518                                 }
519
520                                 /* desired type? */
521                                 if (item < 0)
522                                         itemtype = map->buckets[-1-item]->type;
523                                 else
524                                         itemtype = 0;
525                                 dprintk("  item %d type %d\n", item, itemtype);
526
527                                 /* keep going? */
528                                 if (itemtype != type) {
529                                         if (item >= 0 ||
530                                             (-1-item) >= map->max_buckets) {
531                                                 dprintk("   bad item type %d\n", type);
532                                                 skip_rep = 1;
533                                                 break;
534                                         }
535                                         in = map->buckets[-1-item];
536                                         retry_bucket = 1;
537                                         continue;
538                                 }
539
540                                 /* collision? */
541                                 for (i = 0; i < outpos; i++) {
542                                         if (out[i] == item) {
543                                                 collide = 1;
544                                                 break;
545                                         }
546                                 }
547
548                                 reject = 0;
549                                 if (!collide && recurse_to_leaf) {
550                                         if (item < 0) {
551                                                 int sub_r;
552                                                 if (vary_r)
553                                                         sub_r = r >> (vary_r-1);
554                                                 else
555                                                         sub_r = 0;
556                                                 if (crush_choose_firstn(
557                                                             map,
558                                                             work,
559                                                             map->buckets[-1-item],
560                                                             weight, weight_max,
561                                                             x, stable ? 1 : outpos+1, 0,
562                                                             out2, outpos, count,
563                                                             recurse_tries, 0,
564                                                             local_retries,
565                                                             local_fallback_retries,
566                                                             0,
567                                                             vary_r,
568                                                             stable,
569                                                             NULL,
570                                                             sub_r,
571                                                             choose_args) <= outpos)
572                                                         /* didn't get leaf */
573                                                         reject = 1;
574                                         } else {
575                                                 /* we already have a leaf! */
576                                                 out2[outpos] = item;
577                                         }
578                                 }
579
580                                 if (!reject && !collide) {
581                                         /* out? */
582                                         if (itemtype == 0)
583                                                 reject = is_out(map, weight,
584                                                                 weight_max,
585                                                                 item, x);
586                                 }
587
588 reject:
589                                 if (reject || collide) {
590                                         ftotal++;
591                                         flocal++;
592
593                                         if (collide && flocal <= local_retries)
594                                                 /* retry locally a few times */
595                                                 retry_bucket = 1;
596                                         else if (local_fallback_retries > 0 &&
597                                                  flocal <= in->size + local_fallback_retries)
598                                                 /* exhaustive bucket search */
599                                                 retry_bucket = 1;
600                                         else if (ftotal < tries)
601                                                 /* then retry descent */
602                                                 retry_descent = 1;
603                                         else
604                                                 /* else give up */
605                                                 skip_rep = 1;
606                                         dprintk("  reject %d  collide %d  "
607                                                 "ftotal %u  flocal %u\n",
608                                                 reject, collide, ftotal,
609                                                 flocal);
610                                 }
611                         } while (retry_bucket);
612                 } while (retry_descent);
613
614                 if (skip_rep) {
615                         dprintk("skip rep\n");
616                         continue;
617                 }
618
619                 dprintk("CHOOSE got %d\n", item);
620                 out[outpos] = item;
621                 outpos++;
622                 count--;
623 #ifndef __KERNEL__
624                 if (map->choose_tries && ftotal <= map->choose_total_tries)
625                         map->choose_tries[ftotal]++;
626 #endif
627         }
628
629         dprintk("CHOOSE returns %d\n", outpos);
630         return outpos;
631 }
632
633
634 /**
635  * crush_choose_indep: alternative breadth-first positionally stable mapping
636  *
637  */
638 static void crush_choose_indep(const struct crush_map *map,
639                                struct crush_work *work,
640                                const struct crush_bucket *bucket,
641                                const __u32 *weight, int weight_max,
642                                int x, int left, int numrep, int type,
643                                int *out, int outpos,
644                                unsigned int tries,
645                                unsigned int recurse_tries,
646                                int recurse_to_leaf,
647                                int *out2,
648                                int parent_r,
649                                const struct crush_choose_arg *choose_args)
650 {
651         const struct crush_bucket *in = bucket;
652         int endpos = outpos + left;
653         int rep;
654         unsigned int ftotal;
655         int r;
656         int i;
657         int item = 0;
658         int itemtype;
659         int collide;
660
661         dprintk("CHOOSE%s INDEP bucket %d x %d outpos %d numrep %d\n", recurse_to_leaf ? "_LEAF" : "",
662                 bucket->id, x, outpos, numrep);
663
664         /* initially my result is undefined */
665         for (rep = outpos; rep < endpos; rep++) {
666                 out[rep] = CRUSH_ITEM_UNDEF;
667                 if (out2)
668                         out2[rep] = CRUSH_ITEM_UNDEF;
669         }
670
671         for (ftotal = 0; left > 0 && ftotal < tries; ftotal++) {
672 #ifdef DEBUG_INDEP
673                 if (out2 && ftotal) {
674                         dprintk("%u %d a: ", ftotal, left);
675                         for (rep = outpos; rep < endpos; rep++) {
676                                 dprintk(" %d", out[rep]);
677                         }
678                         dprintk("\n");
679                         dprintk("%u %d b: ", ftotal, left);
680                         for (rep = outpos; rep < endpos; rep++) {
681                                 dprintk(" %d", out2[rep]);
682                         }
683                         dprintk("\n");
684                 }
685 #endif
686                 for (rep = outpos; rep < endpos; rep++) {
687                         if (out[rep] != CRUSH_ITEM_UNDEF)
688                                 continue;
689
690                         in = bucket;  /* initial bucket */
691
692                         /* choose through intervening buckets */
693                         for (;;) {
694                                 /* note: we base the choice on the position
695                                  * even in the nested call.  that means that
696                                  * if the first layer chooses the same bucket
697                                  * in a different position, we will tend to
698                                  * choose a different item in that bucket.
699                                  * this will involve more devices in data
700                                  * movement and tend to distribute the load.
701                                  */
702                                 r = rep + parent_r;
703
704                                 /* be careful */
705                                 if (in->alg == CRUSH_BUCKET_UNIFORM &&
706                                     in->size % numrep == 0)
707                                         /* r'=r+(n+1)*f_total */
708                                         r += (numrep+1) * ftotal;
709                                 else
710                                         /* r' = r + n*f_total */
711                                         r += numrep * ftotal;
712
713                                 /* bucket choose */
714                                 if (in->size == 0) {
715                                         dprintk("   empty bucket\n");
716                                         break;
717                                 }
718
719                                 item = crush_bucket_choose(
720                                         in, work->work[-1-in->id],
721                                         x, r,
722                                         (choose_args ? &choose_args[-1-in->id] : 0),
723                                         outpos);
724                                 if (item >= map->max_devices) {
725                                         dprintk("   bad item %d\n", item);
726                                         out[rep] = CRUSH_ITEM_NONE;
727                                         if (out2)
728                                                 out2[rep] = CRUSH_ITEM_NONE;
729                                         left--;
730                                         break;
731                                 }
732
733                                 /* desired type? */
734                                 if (item < 0)
735                                         itemtype = map->buckets[-1-item]->type;
736                                 else
737                                         itemtype = 0;
738                                 dprintk("  item %d type %d\n", item, itemtype);
739
740                                 /* keep going? */
741                                 if (itemtype != type) {
742                                         if (item >= 0 ||
743                                             (-1-item) >= map->max_buckets) {
744                                                 dprintk("   bad item type %d\n", type);
745                                                 out[rep] = CRUSH_ITEM_NONE;
746                                                 if (out2)
747                                                         out2[rep] =
748                                                                 CRUSH_ITEM_NONE;
749                                                 left--;
750                                                 break;
751                                         }
752                                         in = map->buckets[-1-item];
753                                         continue;
754                                 }
755
756                                 /* collision? */
757                                 collide = 0;
758                                 for (i = outpos; i < endpos; i++) {
759                                         if (out[i] == item) {
760                                                 collide = 1;
761                                                 break;
762                                         }
763                                 }
764                                 if (collide)
765                                         break;
766
767                                 if (recurse_to_leaf) {
768                                         if (item < 0) {
769                                                 crush_choose_indep(
770                                                         map,
771                                                         work,
772                                                         map->buckets[-1-item],
773                                                         weight, weight_max,
774                                                         x, 1, numrep, 0,
775                                                         out2, rep,
776                                                         recurse_tries, 0,
777                                                         0, NULL, r, choose_args);
778                                                 if (out2[rep] == CRUSH_ITEM_NONE) {
779                                                         /* placed nothing; no leaf */
780                                                         break;
781                                                 }
782                                         } else {
783                                                 /* we already have a leaf! */
784                                                 out2[rep] = item;
785                                         }
786                                 }
787
788                                 /* out? */
789                                 if (itemtype == 0 &&
790                                     is_out(map, weight, weight_max, item, x))
791                                         break;
792
793                                 /* yay! */
794                                 out[rep] = item;
795                                 left--;
796                                 break;
797                         }
798                 }
799         }
800         for (rep = outpos; rep < endpos; rep++) {
801                 if (out[rep] == CRUSH_ITEM_UNDEF) {
802                         out[rep] = CRUSH_ITEM_NONE;
803                 }
804                 if (out2 && out2[rep] == CRUSH_ITEM_UNDEF) {
805                         out2[rep] = CRUSH_ITEM_NONE;
806                 }
807         }
808 #ifndef __KERNEL__
809         if (map->choose_tries && ftotal <= map->choose_total_tries)
810                 map->choose_tries[ftotal]++;
811 #endif
812 #ifdef DEBUG_INDEP
813         if (out2) {
814                 dprintk("%u %d a: ", ftotal, left);
815                 for (rep = outpos; rep < endpos; rep++) {
816                         dprintk(" %d", out[rep]);
817                 }
818                 dprintk("\n");
819                 dprintk("%u %d b: ", ftotal, left);
820                 for (rep = outpos; rep < endpos; rep++) {
821                         dprintk(" %d", out2[rep]);
822                 }
823                 dprintk("\n");
824         }
825 #endif
826 }
827
828
829 /* This takes a chunk of memory and sets it up to be a shiny new
830    working area for a CRUSH placement computation. It must be called
831    on any newly allocated memory before passing it in to
832    crush_do_rule. It may be used repeatedly after that, so long as the
833    map has not changed. If the map /has/ changed, you must make sure
834    the working size is no smaller than what was allocated and re-run
835    crush_init_workspace.
836
837    If you do retain the working space between calls to crush, make it
838    thread-local. If you reinstitute the locking I've spent so much
839    time getting rid of, I will be very unhappy with you. */
840
841 void crush_init_workspace(const struct crush_map *m, void *v) {
842         /* We work by moving through the available space and setting
843            values and pointers as we go.
844
845            It's a bit like Forth's use of the 'allot' word since we
846            set the pointer first and then reserve the space for it to
847            point to by incrementing the point. */
848         struct crush_work *w = (struct crush_work *)v;
849         char *point = (char *)v;
850         __s32 b;
851         point += sizeof(struct crush_work);
852         w->work = (struct crush_work_bucket **)point;
853         point += m->max_buckets * sizeof(struct crush_work_bucket *);
854         for (b = 0; b < m->max_buckets; ++b) {
855                 if (m->buckets[b] == 0)
856                         continue;
857
858                 w->work[b] = (struct crush_work_bucket *) point;
859                 switch (m->buckets[b]->alg) {
860                 default:
861                         point += sizeof(struct crush_work_bucket);
862                         break;
863                 }
864                 w->work[b]->perm_x = 0;
865                 w->work[b]->perm_n = 0;
866                 w->work[b]->perm = (__u32 *)point;
867                 point += m->buckets[b]->size * sizeof(__u32);
868         }
869         BUG_ON((char *)point - (char *)w != m->working_size);
870 }
871
872 /**
873  * crush_do_rule - calculate a mapping with the given input and rule
874  * @map: the crush_map
875  * @ruleno: the rule id
876  * @x: hash input
877  * @result: pointer to result vector
878  * @result_max: maximum result size
879  * @weight: weight vector (for map leaves)
880  * @weight_max: size of weight vector
881  * @cwin: Pointer to at least map->working_size bytes of memory or NULL.
882  */
883 int crush_do_rule(const struct crush_map *map,
884                   int ruleno, int x, int *result, int result_max,
885                   const __u32 *weight, int weight_max,
886                   void *cwin, const struct crush_choose_arg *choose_args)
887 {
888         int result_len;
889         struct crush_work *cw = cwin;
890         int *a = (int *)((char *)cw + map->working_size);
891         int *b = a + result_max;
892         int *c = b + result_max;
893         int *w = a;
894         int *o = b;
895         int recurse_to_leaf;
896         int wsize = 0;
897         int osize;
898         int *tmp;
899         const struct crush_rule *rule;
900         __u32 step;
901         int i, j;
902         int numrep;
903         int out_size;
904         /*
905          * the original choose_total_tries value was off by one (it
906          * counted "retries" and not "tries").  add one.
907          */
908         int choose_tries = map->choose_total_tries + 1;
909         int choose_leaf_tries = 0;
910         /*
911          * the local tries values were counted as "retries", though,
912          * and need no adjustment
913          */
914         int choose_local_retries = map->choose_local_tries;
915         int choose_local_fallback_retries = map->choose_local_fallback_tries;
916
917         int vary_r = map->chooseleaf_vary_r;
918         int stable = map->chooseleaf_stable;
919
920         if ((__u32)ruleno >= map->max_rules) {
921                 dprintk(" bad ruleno %d\n", ruleno);
922                 return 0;
923         }
924
925         rule = map->rules[ruleno];
926         result_len = 0;
927
928         for (step = 0; step < rule->len; step++) {
929                 int firstn = 0;
930                 const struct crush_rule_step *curstep = &rule->steps[step];
931
932                 switch (curstep->op) {
933                 case CRUSH_RULE_TAKE:
934                         if ((curstep->arg1 >= 0 &&
935                              curstep->arg1 < map->max_devices) ||
936                             (-1-curstep->arg1 >= 0 &&
937                              -1-curstep->arg1 < map->max_buckets &&
938                              map->buckets[-1-curstep->arg1])) {
939                                 w[0] = curstep->arg1;
940                                 wsize = 1;
941                         } else {
942                                 dprintk(" bad take value %d\n", curstep->arg1);
943                         }
944                         break;
945
946                 case CRUSH_RULE_SET_CHOOSE_TRIES:
947                         if (curstep->arg1 > 0)
948                                 choose_tries = curstep->arg1;
949                         break;
950
951                 case CRUSH_RULE_SET_CHOOSELEAF_TRIES:
952                         if (curstep->arg1 > 0)
953                                 choose_leaf_tries = curstep->arg1;
954                         break;
955
956                 case CRUSH_RULE_SET_CHOOSE_LOCAL_TRIES:
957                         if (curstep->arg1 >= 0)
958                                 choose_local_retries = curstep->arg1;
959                         break;
960
961                 case CRUSH_RULE_SET_CHOOSE_LOCAL_FALLBACK_TRIES:
962                         if (curstep->arg1 >= 0)
963                                 choose_local_fallback_retries = curstep->arg1;
964                         break;
965
966                 case CRUSH_RULE_SET_CHOOSELEAF_VARY_R:
967                         if (curstep->arg1 >= 0)
968                                 vary_r = curstep->arg1;
969                         break;
970
971                 case CRUSH_RULE_SET_CHOOSELEAF_STABLE:
972                         if (curstep->arg1 >= 0)
973                                 stable = curstep->arg1;
974                         break;
975
976                 case CRUSH_RULE_CHOOSELEAF_FIRSTN:
977                 case CRUSH_RULE_CHOOSE_FIRSTN:
978                         firstn = 1;
979                         /* fall through */
980                 case CRUSH_RULE_CHOOSELEAF_INDEP:
981                 case CRUSH_RULE_CHOOSE_INDEP:
982                         if (wsize == 0)
983                                 break;
984
985                         recurse_to_leaf =
986                                 curstep->op ==
987                                  CRUSH_RULE_CHOOSELEAF_FIRSTN ||
988                                 curstep->op ==
989                                 CRUSH_RULE_CHOOSELEAF_INDEP;
990
991                         /* reset output */
992                         osize = 0;
993
994                         for (i = 0; i < wsize; i++) {
995                                 int bno;
996                                 numrep = curstep->arg1;
997                                 if (numrep <= 0) {
998                                         numrep += result_max;
999                                         if (numrep <= 0)
1000                                                 continue;
1001                                 }
1002                                 j = 0;
1003                                 /* make sure bucket id is valid */
1004                                 bno = -1 - w[i];
1005                                 if (bno < 0 || bno >= map->max_buckets) {
1006                                         // w[i] is probably CRUSH_ITEM_NONE
1007                                         dprintk("  bad w[i] %d\n", w[i]);
1008                                         continue;
1009                                 }
1010                                 if (firstn) {
1011                                         int recurse_tries;
1012                                         if (choose_leaf_tries)
1013                                                 recurse_tries =
1014                                                         choose_leaf_tries;
1015                                         else if (map->chooseleaf_descend_once)
1016                                                 recurse_tries = 1;
1017                                         else
1018                                                 recurse_tries = choose_tries;
1019                                         osize += crush_choose_firstn(
1020                                                 map,
1021                                                 cw,
1022                                                 map->buckets[bno],
1023                                                 weight, weight_max,
1024                                                 x, numrep,
1025                                                 curstep->arg2,
1026                                                 o+osize, j,
1027                                                 result_max-osize,
1028                                                 choose_tries,
1029                                                 recurse_tries,
1030                                                 choose_local_retries,
1031                                                 choose_local_fallback_retries,
1032                                                 recurse_to_leaf,
1033                                                 vary_r,
1034                                                 stable,
1035                                                 c+osize,
1036                                                 0,
1037                                                 choose_args);
1038                                 } else {
1039                                         out_size = ((numrep < (result_max-osize)) ?
1040                                                     numrep : (result_max-osize));
1041                                         crush_choose_indep(
1042                                                 map,
1043                                                 cw,
1044                                                 map->buckets[bno],
1045                                                 weight, weight_max,
1046                                                 x, out_size, numrep,
1047                                                 curstep->arg2,
1048                                                 o+osize, j,
1049                                                 choose_tries,
1050                                                 choose_leaf_tries ?
1051                                                    choose_leaf_tries : 1,
1052                                                 recurse_to_leaf,
1053                                                 c+osize,
1054                                                 0,
1055                                                 choose_args);
1056                                         osize += out_size;
1057                                 }
1058                         }
1059
1060                         if (recurse_to_leaf)
1061                                 /* copy final _leaf_ values to output set */
1062                                 memcpy(o, c, osize*sizeof(*o));
1063
1064                         /* swap o and w arrays */
1065                         tmp = o;
1066                         o = w;
1067                         w = tmp;
1068                         wsize = osize;
1069                         break;
1070
1071
1072                 case CRUSH_RULE_EMIT:
1073                         for (i = 0; i < wsize && result_len < result_max; i++) {
1074                                 result[result_len] = w[i];
1075                                 result_len++;
1076                         }
1077                         wsize = 0;
1078                         break;
1079
1080                 default:
1081                         dprintk(" unknown op %d at step %d\n",
1082                                 curstep->op, step);
1083                         break;
1084                 }
1085         }
1086
1087         return result_len;
1088 }