summaryrefslogtreecommitdiffstats
path: root/src/crush/CrushWrapper.h
blob: 136ad53864995730fd746fed5cdc9a1abfa91a38 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab

#ifndef CEPH_CRUSH_WRAPPER_H
#define CEPH_CRUSH_WRAPPER_H

#include <stdlib.h>
#include <map>
#include <set>
#include <string>

#include <iosfwd>

#include "include/types.h"

extern "C" {
#include "crush.h"
#include "hash.h"
#include "mapper.h"
#include "builder.h"
}

#include "include/ceph_assert.h"
#include "include/err.h"
#include "include/encoding.h"
#include "include/mempool.h"

#include "common/Mutex.h"

namespace ceph {
  class Formatter;
}

namespace CrushTreeDumper {
  typedef mempool::osdmap::map<int64_t,string> name_map_t;
}

WRITE_RAW_ENCODER(crush_rule_mask)   // it's all u8's

inline void encode(const crush_rule_step &s, bufferlist &bl)
{
  using ceph::encode;
  encode(s.op, bl);
  encode(s.arg1, bl);
  encode(s.arg2, bl);
}
inline void decode(crush_rule_step &s, bufferlist::const_iterator &p)
{
  using ceph::decode;
  decode(s.op, p);
  decode(s.arg1, p);
  decode(s.arg2, p);
}

class CrushWrapper {
public:
  // magic value used by OSDMap for a "default" fallback choose_args, used if
  // the choose_arg_map passed to do_rule does not exist.  if this also
  // doesn't exist, fall back to canonical weights.
  enum {
    DEFAULT_CHOOSE_ARGS = -1
  };

  std::map<int32_t, string> type_map; /* bucket/device type names */
  std::map<int32_t, string> name_map; /* bucket/device names */
  std::map<int32_t, string> rule_name_map;

  std::map<int32_t, int32_t> class_map; /* item id -> class id */
  std::map<int32_t, string> class_name; /* class id -> class name */
  std::map<string, int32_t> class_rname; /* class name -> class id */
  std::map<int32_t, map<int32_t, int32_t> > class_bucket; /* bucket[id][class] == id */
  std::map<int64_t, crush_choose_arg_map> choose_args;

private:
  struct crush_map *crush = nullptr;

  bool have_uniform_rules = false;

  /* reverse maps */
  mutable bool have_rmaps = false;
  mutable std::map<string, int> type_rmap, name_rmap, rule_name_rmap;
  void build_rmaps() const {
    if (have_rmaps) return;
    build_rmap(type_map, type_rmap);
    build_rmap(name_map, name_rmap);
    build_rmap(rule_name_map, rule_name_rmap);
    have_rmaps = true;
  }
  void build_rmap(const map<int, string> &f, std::map<string, int> &r) const {
    r.clear();
    for (std::map<int, string>::const_iterator p = f.begin(); p != f.end(); ++p)
      r[p->second] = p->first;
  }

public:
  CrushWrapper(const CrushWrapper& other);
  const CrushWrapper& operator=(const CrushWrapper& other);

  CrushWrapper() {
    create();
  }
  ~CrushWrapper() {
    if (crush)
      crush_destroy(crush);
    choose_args_clear();
  }

  crush_map *get_crush_map() { return crush; }

  /* building */
  void create() {
    if (crush)
      crush_destroy(crush);
    crush = crush_create();
    choose_args_clear();
    ceph_assert(crush);
    have_rmaps = false;

    set_tunables_default();
  }

  /**
   * true if any rule has a rule id != its position in the array
   *
   * These indicate "ruleset" IDs that were created by older versions
   * of Ceph.  They are cleaned up in renumber_rules so that eventually
   * we can remove the code for handling them.
   */
  bool has_legacy_rule_ids() const;

  /**
   * fix rules whose ruleid != ruleset
   *
   * These rules were created in older versions of Ceph.  The concept
   * of a ruleset no longer exists.
   *
   * Return a map of old ID -> new ID.  Caller must update OSDMap
   * to use new IDs.
   */
  std::map<int, int> renumber_rules();

  /// true if any buckets that aren't straw2
  bool has_non_straw2_buckets() const;

  // tunables
  void set_tunables_argonaut() {
    crush->choose_local_tries = 2;
    crush->choose_local_fallback_tries = 5;
    crush->choose_total_tries = 19;
    crush->chooseleaf_descend_once = 0;
    crush->chooseleaf_vary_r = 0;
    crush->chooseleaf_stable = 0;
    crush->allowed_bucket_algs = CRUSH_LEGACY_ALLOWED_BUCKET_ALGS;
  }
  void set_tunables_bobtail() {
    crush->choose_local_tries = 0;
    crush->choose_local_fallback_tries = 0;
    crush->choose_total_tries = 50;
    crush->chooseleaf_descend_once = 1;
    crush->chooseleaf_vary_r = 0;
    crush->chooseleaf_stable = 0;
    crush->allowed_bucket_algs = CRUSH_LEGACY_ALLOWED_BUCKET_ALGS;
  }
  void set_tunables_firefly() {
    crush->choose_local_tries = 0;
    crush->choose_local_fallback_tries = 0;
    crush->choose_total_tries = 50;
    crush->chooseleaf_descend_once = 1;
    crush->chooseleaf_vary_r = 1;
    crush->chooseleaf_stable = 0;
    crush->allowed_bucket_algs = CRUSH_LEGACY_ALLOWED_BUCKET_ALGS;
  }
  void set_tunables_hammer() {
    crush->choose_local_tries = 0;
    crush->choose_local_fallback_tries = 0;
    crush->choose_total_tries = 50;
    crush->chooseleaf_descend_once = 1;
    crush->chooseleaf_vary_r = 1;
    crush->chooseleaf_stable = 0;
    crush->allowed_bucket_algs =
      (1 << CRUSH_BUCKET_UNIFORM) |
      (1 << CRUSH_BUCKET_LIST) |
      (1 << CRUSH_BUCKET_STRAW) |
      (1 << CRUSH_BUCKET_STRAW2);
  }
  void set_tunables_jewel() {
    crush->choose_local_tries = 0;
    crush->choose_local_fallback_tries = 0;
    crush->choose_total_tries = 50;
    crush->chooseleaf_descend_once = 1;
    crush->chooseleaf_vary_r = 1;
    crush->chooseleaf_stable = 1;
    crush->allowed_bucket_algs =
      (1 << CRUSH_BUCKET_UNIFORM) |
      (1 << CRUSH_BUCKET_LIST) |
      (1 << CRUSH_BUCKET_STRAW) |
      (1 << CRUSH_BUCKET_STRAW2);
  }

  void set_tunables_legacy() {
    set_tunables_argonaut();
    crush->straw_calc_version = 0;
  }
  void set_tunables_optimal() {
    set_tunables_jewel();
    crush->straw_calc_version = 1;
  }
  void set_tunables_default() {
    set_tunables_jewel();
    crush->straw_calc_version = 1;
  }

  int get_choose_local_tries() const {
    return crush->choose_local_tries;
  }
  void set_choose_local_tries(int n) {
    crush->choose_local_tries = n;
  }

  int get_choose_local_fallback_tries() const {
    return crush->choose_local_fallback_tries;
  }
  void set_choose_local_fallback_tries(int n) {
    crush->choose_local_fallback_tries = n;
  }

  int get_choose_total_tries() const {
    return crush->choose_total_tries;
  }
  void set_choose_total_tries(int n) {
    crush->choose_total_tries = n;
  }

  int get_chooseleaf_descend_once() const {
    return crush->chooseleaf_descend_once;
  }
  void set_chooseleaf_descend_once(int n) {
    crush->chooseleaf_descend_once = !!n;
  }

  int get_chooseleaf_vary_r() const {
    return crush->chooseleaf_vary_r;
  }
  void set_chooseleaf_vary_r(int n) {
    crush->chooseleaf_vary_r = n;
  }

  int get_chooseleaf_stable() const {
    return crush->chooseleaf_stable;
  }
  void set_chooseleaf_stable(int n) {
    crush->chooseleaf_stable = n;
  }

  int get_straw_calc_version() const {
    return crush->straw_calc_version;
  }
  void set_straw_calc_version(int n) {
    crush->straw_calc_version = n;
  }

  unsigned get_allowed_bucket_algs() const {
    return crush->allowed_bucket_algs;
  }
  void set_allowed_bucket_algs(unsigned n) {
    crush->allowed_bucket_algs = n;
  }

  bool has_argonaut_tunables() const {
    return
      crush->choose_local_tries == 2 &&
      crush->choose_local_fallback_tries == 5 &&
      crush->choose_total_tries == 19 &&
      crush->chooseleaf_descend_once == 0 &&
      crush->chooseleaf_vary_r == 0 &&
      crush->chooseleaf_stable == 0 &&
      crush->allowed_bucket_algs == CRUSH_LEGACY_ALLOWED_BUCKET_ALGS;
  }
  bool has_bobtail_tunables() const {
    return
      crush->choose_local_tries == 0 &&
      crush->choose_local_fallback_tries == 0 &&
      crush->choose_total_tries == 50 &&
      crush->chooseleaf_descend_once == 1 &&
      crush->chooseleaf_vary_r == 0 &&
      crush->chooseleaf_stable == 0 &&
      crush->allowed_bucket_algs == CRUSH_LEGACY_ALLOWED_BUCKET_ALGS;
  }
  bool has_firefly_tunables() const {
    return
      crush->choose_local_tries == 0 &&
      crush->choose_local_fallback_tries == 0 &&
      crush->choose_total_tries == 50 &&
      crush->chooseleaf_descend_once == 1 &&
      crush->chooseleaf_vary_r == 1 &&
      crush->chooseleaf_stable == 0 &&
      crush->allowed_bucket_algs == CRUSH_LEGACY_ALLOWED_BUCKET_ALGS;
  }
  bool has_hammer_tunables() const {
    return
      crush->choose_local_tries == 0 &&
      crush->choose_local_fallback_tries == 0 &&
      crush->choose_total_tries == 50 &&
      crush->chooseleaf_descend_once == 1 &&
      crush->chooseleaf_vary_r == 1 &&
      crush->chooseleaf_stable == 0 &&
      crush->allowed_bucket_algs == ((1 << CRUSH_BUCKET_UNIFORM) |
				      (1 << CRUSH_BUCKET_LIST) |
				      (1 << CRUSH_BUCKET_STRAW) |
				      (1 << CRUSH_BUCKET_STRAW2));
  }
  bool has_jewel_tunables() const {
    return
      crush->choose_local_tries == 0 &&
      crush->choose_local_fallback_tries == 0 &&
      crush->choose_total_tries == 50 &&
      crush->chooseleaf_descend_once == 1 &&
      crush->chooseleaf_vary_r == 1 &&
      crush->chooseleaf_stable == 1 &&
      crush->allowed_bucket_algs == ((1 << CRUSH_BUCKET_UNIFORM) |
				      (1 << CRUSH_BUCKET_LIST) |
				      (1 << CRUSH_BUCKET_STRAW) |
				      (1 << CRUSH_BUCKET_STRAW2));
  }

  bool has_optimal_tunables() const {
    return has_jewel_tunables();
  }
  bool has_legacy_tunables() const {
    return has_argonaut_tunables();
  }

  bool has_nondefault_tunables() const {
    return
      (crush->choose_local_tries != 2 ||
       crush->choose_local_fallback_tries != 5 ||
       crush->choose_total_tries != 19);
  }
  bool has_nondefault_tunables2() const {
    return
      crush->chooseleaf_descend_once != 0;
  }
  bool has_nondefault_tunables3() const {
    return
      crush->chooseleaf_vary_r != 0;
  }
  bool has_nondefault_tunables5() const {
    return
        crush->chooseleaf_stable != 0;
  }

  bool has_v2_rules() const;
  bool has_v3_rules() const;
  bool has_v4_buckets() const;
  bool has_v5_rules() const;
  bool has_choose_args() const;          // any choose_args
  bool has_incompat_choose_args() const; // choose_args that can't be made compat

  bool is_v2_rule(unsigned ruleid) const;
  bool is_v3_rule(unsigned ruleid) const;
  bool is_v5_rule(unsigned ruleid) const;

  string get_min_required_version() const {
    if (has_v5_rules() || has_nondefault_tunables5())
      return "jewel";
    else if (has_v4_buckets())
      return "hammer";
    else if (has_nondefault_tunables3())
      return "firefly";
    else if (has_nondefault_tunables2() || has_nondefault_tunables())
      return "bobtail";
    else
      return "argonaut";
  }

  // default bucket types
  unsigned get_default_bucket_alg() const {
    // in order of preference
    if (crush->allowed_bucket_algs & (1 << CRUSH_BUCKET_STRAW2))
      return CRUSH_BUCKET_STRAW2;
    if (crush->allowed_bucket_algs & (1 << CRUSH_BUCKET_STRAW))
      return CRUSH_BUCKET_STRAW;
    if (crush->allowed_bucket_algs & (1 << CRUSH_BUCKET_TREE))
      return CRUSH_BUCKET_TREE;
    if (crush->allowed_bucket_algs & (1 << CRUSH_BUCKET_LIST))
      return CRUSH_BUCKET_LIST;
    if (crush->allowed_bucket_algs & (1 << CRUSH_BUCKET_UNIFORM))
      return CRUSH_BUCKET_UNIFORM;
    return 0;
  }

  // bucket types
  int get_num_type_names() const {
    return type_map.size();
  }
  int get_max_type_id() const {
    if (type_map.empty())
      return 0;
    return type_map.rbegin()->first;
  }
  int get_type_id(const string& name) const {
    build_rmaps();
    if (type_rmap.count(name))
      return type_rmap[name];
    return -1;
  }
  const char *get_type_name(int t) const {
    std::map<int,string>::const_iterator p = type_map.find(t);
    if (p != type_map.end())
      return p->second.c_str();
    return 0;
  }
  void set_type_name(int i, const string& name) {
    type_map[i] = name;
    if (have_rmaps)
      type_rmap[name] = i;
  }

  // item/bucket names
  bool name_exists(const string& name) const {
    build_rmaps();
    return name_rmap.count(name);
  }
  bool item_exists(int i) const {
    return name_map.count(i);
  }
  int get_item_id(const string& name) const {
    build_rmaps();
    if (name_rmap.count(name))
      return name_rmap[name];
    return 0;  /* hrm */
  }
  const char *get_item_name(int t) const {
    std::map<int,string>::const_iterator p = name_map.find(t);
    if (p != name_map.end())
      return p->second.c_str();
    return 0;
  }
  int set_item_name(int i, const string& name) {
    if (!is_valid_crush_name(name))
      return -EINVAL;
    name_map[i] = name;
    if (have_rmaps)
      name_rmap[name] = i;
    return 0;
  }
  void swap_names(int a, int b) {
    string an = name_map[a];
    string bn = name_map[b];
    name_map[a] = bn;
    name_map[b] = an;
    if (have_rmaps) {
      name_rmap[an] = b;
      name_rmap[bn] = a;
    }
  }
  int split_id_class(int i, int *idout, int *classout) const;

  bool class_exists(const string& name) const {
    return class_rname.count(name);
  }
  const char *get_class_name(int i) const {
    auto p = class_name.find(i);
    if (p != class_name.end())
      return p->second.c_str();
    return 0;
  }
  int get_class_id(const string& name) const {
    auto p = class_rname.find(name);
    if (p != class_rname.end())
      return p->second;
    else
      return -EINVAL;
  }
  int remove_class_name(const string& name) {
    auto p = class_rname.find(name);
    if (p == class_rname.end())
      return -ENOENT;
    int class_id = p->second;
    auto q = class_name.find(class_id);
    if (q == class_name.end())
      return -ENOENT;
    class_rname.erase(name);
    class_name.erase(class_id);
    return 0;
  }

  int32_t _alloc_class_id() const;

  int get_or_create_class_id(const string& name) {
    int c = get_class_id(name);
    if (c < 0) {
      int i = _alloc_class_id();
      class_name[i] = name;
      class_rname[name] = i;
      return i;
    } else {
      return c;
    }
  }

  const char *get_item_class(int t) const {
    std::map<int,int>::const_iterator p = class_map.find(t);
    if (p == class_map.end())
      return 0;
    return get_class_name(p->second);
  }
  int get_item_class_id(int t) const {
    auto p = class_map.find(t);
    if (p == class_map.end())
      return -ENOENT;
    return p->second;
  }
  int set_item_class(int i, const string& name) {
    if (!is_valid_crush_name(name))
      return -EINVAL;
    class_map[i] = get_or_create_class_id(name);
    return 0;
  }
  int set_item_class(int i, int c) {
    class_map[i] = c;
    return c;
  }
  void get_devices_by_class(const string &name, set<int> *devices) const {
    ceph_assert(devices);
    devices->clear();
    if (!class_exists(name)) {
      return;
    }
    auto cid = get_class_id(name);
    for (auto& p : class_map) {
      if (p.first >= 0 && p.second == cid) {
        devices->insert(p.first);
      }
    }
  }
  void class_remove_item(int i) {
    auto it = class_map.find(i);
    if (it == class_map.end()) {
      return;
    }
    class_map.erase(it);
  }
  int can_rename_item(const string& srcname,
		      const string& dstname,
		      ostream *ss) const;
  int rename_item(const string& srcname,
		  const string& dstname,
		  ostream *ss);
  int can_rename_bucket(const string& srcname,
			const string& dstname,
			ostream *ss) const;
  int rename_bucket(const string& srcname,
		    const string& dstname,
		    ostream *ss);

  // rule names
  int rename_rule(const string& srcname,
                  const string& dstname,
                  ostream *ss);
  bool rule_exists(string name) const {
    build_rmaps();
    return rule_name_rmap.count(name);
  }
  int get_rule_id(string name) const {
    build_rmaps();
    if (rule_name_rmap.count(name))
      return rule_name_rmap[name];
    return -ENOENT;
  }
  const char *get_rule_name(int t) const {
    std::map<int,string>::const_iterator p = rule_name_map.find(t);
    if (p != rule_name_map.end())
      return p->second.c_str();
    return 0;
  }
  void set_rule_name(int i, const string& name) {
    rule_name_map[i] = name;
    if (have_rmaps)
      rule_name_rmap[name] = i;
  }
  bool is_shadow_item(int id) const {
    const char *name = get_item_name(id);
    return name && !is_valid_crush_name(name);
  }


  /**
   * find tree nodes referenced by rules by a 'take' command
   *
   * Note that these may not be parentless roots.
   */
  void find_takes(set<int> *roots) const;
  void find_takes_by_rule(int rule, set<int> *roots) const;

  /**
   * find tree roots
   *
   * These are parentless nodes in the map.
   */
  void find_roots(set<int> *roots) const;


  /**
   * find tree roots that contain shadow (device class) items only
   */
  void find_shadow_roots(set<int> *roots) const {
    set<int> all;
    find_roots(&all);
    for (auto& p: all) {
      if (is_shadow_item(p)) {
        roots->insert(p);
      }
    }
  }

  /**
   * find tree roots that are not shadow (device class) items
   *
   * These are parentless nodes in the map that are not shadow
   * items for device classes.
   */
  void find_nonshadow_roots(set<int> *roots) const {
    set<int> all;
    find_roots(&all);
    for (auto& p: all) {
      if (!is_shadow_item(p)) {
        roots->insert(p);
      }
    }
  }

  /**
   * see if an item is contained within a subtree
   *
   * @param root haystack
   * @param item needle
   * @return true if the item is located beneath the given node
   */
  bool subtree_contains(int root, int item) const;

private:
  /**
   * search for an item in any bucket
   *
   * @param i item
   * @return true if present
   */
  bool _search_item_exists(int i) const;
  bool is_parent_of(int child, int p) const;
public:

  /**
   * see if item is located where we think it is
   *
   * This verifies that the given item is located at a particular
   * location in the hierarchy.  However, that check is imprecise; we
   * are actually verifying that the most specific location key/value
   * is correct.  For example, if loc specifies that rack=foo and
   * host=bar, it will verify that host=bar is correct; any placement
   * above that level in the hierarchy is ignored.  This matches the
   * semantics for insert_item().
   *
   * @param cct cct
   * @param item item id
   * @param loc location to check (map of type to bucket names)
   * @param weight optional pointer to weight of item at that location
   * @return true if item is at specified location
   */
  bool check_item_loc(CephContext *cct, int item, const map<string,string>& loc, int *iweight);
  bool check_item_loc(CephContext *cct, int item, const map<string,string>& loc, float *weight) {
    int iweight;
    bool ret = check_item_loc(cct, item, loc, &iweight);
    if (weight)
      *weight = (float)iweight / (float)0x10000;
    return ret;
  }


  /**
   * returns the (type, name) of the parent bucket of id
   *
   * FIXME: ambiguous for items that occur multiple times in the map
   */
  pair<string,string> get_immediate_parent(int id, int *ret = NULL) const;

  int get_immediate_parent_id(int id, int *parent) const;

  /**
   * return ancestor of the given type, or 0 if none
   * can pass in a specific crush **rule** to return ancestor from that rule only 
   * (parent is always a bucket and thus <0)
   */
  int get_parent_of_type(int id, int type, int rule = -1) const;

  /**
   * get the fully qualified location of a device by successively finding
   * parents beginning at ID and ending at highest type number specified in
   * the CRUSH map which assumes that if device foo is under device bar, the
   * type_id of foo < bar where type_id is the integer specified in the CRUSH map
   *
   * returns the location in the form of (type=foo) where type is a type of bucket
   * specified in the CRUSH map and foo is a name specified in the CRUSH map
   */
  map<string, string> get_full_location(int id) const;

  /**
   * return location map for a item, by name
   */
  int get_full_location(
    const string& name,
    std::map<string,string> *ploc);

  /*
   * identical to get_full_location(int id) although it returns the type/name
   * pairs in the order they occur in the hierarchy.
   *
   * returns -ENOENT if id is not found.
   */
  int get_full_location_ordered(int id, vector<pair<string, string> >& path) const;

  /*
   * identical to get_full_location_ordered(int id, vector<pair<string, string> >& path),
   * although it returns a concatenated string with the type/name pairs in descending
   * hierarchical order with format key1=val1,key2=val2.
   *
   * returns the location in descending hierarchy as a string.
   */
  string get_full_location_ordered_string(int id) const;

  /**
   * returns (type_id, type) of all parent buckets between id and
   * default, can be used to check for anomalous CRUSH maps
   */
  map<int, string> get_parent_hierarchy(int id) const;

  /**
   * enumerate immediate children of given node
   *
   * @param id parent bucket or device id
   * @return number of items, or error
   */
  int get_children(int id, list<int> *children) const;
 /**
   * enumerate all children of given node
   *
   * @param id parent bucket or device id
   * @return number of items, or error
   */
  int get_all_children(int id, set<int> *children) const;
  void get_children_of_type(int id,
                            int type,
			    vector<int> *children,
			    bool exclude_shadow = true) const;
  /**
   * enumerate all subtrees by type
   */
  void get_subtree_of_type(int type, vector<int> *subtrees);


  /**
   * verify upmapping results.
   * return 0 on success or a negative errno on error.
   */
  int verify_upmap(CephContext *cct,
                   int rule_id,
                   int pool_size,
                   const vector<int>& up);

  /**
    * enumerate leaves(devices) of given node
    *
    * @param name parent bucket name
    * @return 0 on success or a negative errno on error.
    */
  int get_leaves(const string &name, set<int> *leaves) const;

private:
  int _get_leaves(int id, list<int> *leaves) const; // worker

public:
  /**
   * insert an item into the map at a specific position
   *
   * Add an item as a specific location of the hierarchy.
   * Specifically, we look for the most specific location constraint
   * for which a bucket already exists, and then create intervening
   * buckets beneath that in order to place the item.
   *
   * Note that any location specifiers *above* the most specific match
   * are ignored.  For example, if we specify that osd.12 goes in
   * host=foo, rack=bar, and row=baz, and rack=bar is the most
   * specific match, we will create host=foo beneath that point and
   * put osd.12 inside it.  However, we will not verify that rack=bar
   * is beneath row=baz or move it.
   *
   * In short, we will build out a hierarchy, and move leaves around,
   * but not adjust the hierarchy's internal structure.  Yet.
   *
   * If the item is already present in the map, we will return EEXIST.
   * If the location key/value pairs are nonsensical
   * (rack=nameofdevice), or location specifies that do not attach us
   * to any existing part of the hierarchy, we will return EINVAL.
   *
   * @param cct cct
   * @param id item id
   * @param weight item weight
   * @param name item name
   * @param loc location (map of type to bucket names)
   * @param init_weight_sets initialize weight-set weights to weight (vs 0)
   * @return 0 for success, negative on error
   */
  int insert_item(CephContext *cct, int id, float weight, string name,
		  const map<string,string>& loc,
		  bool init_weight_sets=true);

  /**
   * move a bucket in the hierarchy to the given location
   *
   * This has the same location and ancestor creation behavior as
   * insert_item(), but will relocate the specified existing bucket.
   *
   * @param cct cct
   * @param id bucket id
   * @param loc location (map of type to bucket names)
   * @return 0 for success, negative on error
   */
  int move_bucket(CephContext *cct, int id, const map<string,string>& loc);

  /**
   * swap bucket contents of two buckets without touching bucket ids
   *
   * @param cct cct
   * @param src bucket a
   * @param dst bucket b
   * @return 0 for success, negative on error
   */
  int swap_bucket(CephContext *cct, int src, int dst);

  /**
   * add a link to an existing bucket in the hierarchy to the new location
   *
   * This has the same location and ancestor creation behavior as
   * insert_item(), but will add a new link to the specified existing
   * bucket.
   *
   * @param cct cct
   * @param id bucket id
   * @param loc location (map of type to bucket names)
   * @return 0 for success, negative on error
   */
  int link_bucket(CephContext *cct, int id, const map<string,string>& loc);

  /**
   * add or update an item's position in the map
   *
   * This is analogous to insert_item, except we will move an item if
   * it is already present.
   *
   * @param cct cct
   * @param id item id
   * @param weight item weight
   * @param name item name
   * @param loc location (map of type to bucket names)
   * @return 0 for no change, 1 for successful change, negative on error
   */
  int update_item(CephContext *cct, int id, float weight, string name, const map<string,string>& loc);

  /**
   * create or move an item, but do not adjust its weight if it already exists
   *
   * @param cct cct
   * @param item item id
   * @param weight initial item weight (if we need to create it)
   * @param name item name
   * @param loc location (map of type to bucket names)
   * @param init_weight_sets initialize weight-set values to weight (vs 0)
   * @return 0 for no change, 1 for successful change, negative on error
   */
  int create_or_move_item(CephContext *cct, int item, float weight, string name,
			  const map<string,string>& loc,
			  bool init_weight_sets=true);

  /**
   * remove all instances of an item from the map
   *
   * @param cct cct
   * @param id item id to remove
   * @param unlink_only unlink but do not remove bucket (useful if multiple links or not empty)
   * @return 0 on success, negative on error
   */
  int remove_item(CephContext *cct, int id, bool unlink_only);

  /**
   * recursively remove buckets starting at item and stop removing
   * when a bucket is in use.
   *
   * @param item id to remove
   * @return 0 on success, negative on error
   */
  int remove_root(CephContext *cct, int item);

  /**
   * remove all instances of an item nested beneath a certain point from the map
   *
   * @param cct cct
   * @param id item id to remove
   * @param ancestor ancestor item id under which to search for id
   * @param unlink_only unlink but do not remove bucket (useful if bucket has multiple links or is not empty)
   * @return 0 on success, negative on error
   */
private:
  bool _maybe_remove_last_instance(CephContext *cct, int id, bool unlink_only);
  int _remove_item_under(CephContext *cct, int id, int ancestor, bool unlink_only);
  bool _bucket_is_in_use(int id);
public:
  int remove_item_under(CephContext *cct, int id, int ancestor, bool unlink_only);

  /**
   * calculate the locality/distance from a given id to a crush location map
   *
   * Specifically, we look for the lowest-valued type for which the
   * location of id matches that described in loc.
   *
   * @param cct cct
   * @param id the existing id in the map
   * @param loc a set of key=value pairs describing a location in the hierarchy
   */
  int get_common_ancestor_distance(CephContext *cct, int id,
				   const std::multimap<string,string>& loc) const;

  /**
   * parse a set of key/value pairs out of a string vector
   *
   * These are used to describe a location in the CRUSH hierarchy.
   *
   * @param args list of strings (each key= or key=value)
   * @param ploc pointer to a resulting location map or multimap
   */
  static int parse_loc_map(const std::vector<string>& args,
			   std::map<string,string> *ploc);
  static int parse_loc_multimap(const std::vector<string>& args,
				std::multimap<string,string> *ploc);


  /**
   * get an item's weight
   *
   * Will return the weight for the first instance it finds.
   *
   * @param id item id to check
   * @return weight of item
   */
  int get_item_weight(int id) const;
  float get_item_weightf(int id) const {
    return (float)get_item_weight(id) / (float)0x10000;
  }
  int get_item_weight_in_loc(int id, const map<string,string> &loc);
  float get_item_weightf_in_loc(int id, const map<string,string> &loc) {
    return (float)get_item_weight_in_loc(id, loc) / (float)0x10000;
  }

  int validate_weightf(float weight) {
    uint64_t iweight = weight * 0x10000;
    if (iweight > std::numeric_limits<int>::max()) {
      return -EOVERFLOW;
    }
    return 0;
  }
  int adjust_item_weight(CephContext *cct, int id, int weight,
			 bool update_weight_sets=true);
  int adjust_item_weightf(CephContext *cct, int id, float weight,
			  bool update_weight_sets=true) {
    int r = validate_weightf(weight);
    if (r < 0) {
      return r;
    }
    return adjust_item_weight(cct, id, (int)(weight * (float)0x10000),
			      update_weight_sets);
  }
  int adjust_item_weight_in_bucket(CephContext *cct, int id, int weight,
				   int bucket_id,
				   bool update_weight_sets);
  int adjust_item_weight_in_loc(CephContext *cct, int id, int weight,
				const map<string,string>& loc,
				bool update_weight_sets=true);
  int adjust_item_weightf_in_loc(CephContext *cct, int id, float weight,
				 const map<string,string>& loc,
				 bool update_weight_sets=true) {
    int r = validate_weightf(weight);
    if (r < 0) {
      return r;
    }
    return adjust_item_weight_in_loc(cct, id, (int)(weight * (float)0x10000),
				     loc, update_weight_sets);
  }
  void reweight(CephContext *cct);
  void reweight_bucket(crush_bucket *b,
		       crush_choose_arg_map& arg_map,
		       vector<uint32_t> *weightv);

  int adjust_subtree_weight(CephContext *cct, int id, int weight,
			    bool update_weight_sets=true);
  int adjust_subtree_weightf(CephContext *cct, int id, float weight,
			     bool update_weight_sets=true) {
    int r = validate_weightf(weight);
    if (r < 0) {
      return r;
    }
    return adjust_subtree_weight(cct, id, (int)(weight * (float)0x10000),
				 update_weight_sets);
  }

  /// check if item id is present in the map hierarchy
  bool check_item_present(int id) const;


  /*** devices ***/
  int get_max_devices() const {
    if (!crush) return 0;
    return crush->max_devices;
  }


  /*** rules ***/
private:
  crush_rule *get_rule(unsigned ruleno) const {
    if (!crush) return (crush_rule *)(-ENOENT);
    if (ruleno >= crush->max_rules)
      return 0;
    return crush->rules[ruleno];
  }
  crush_rule_step *get_rule_step(unsigned ruleno, unsigned step) const {
    crush_rule *n = get_rule(ruleno);
    if (IS_ERR(n)) return (crush_rule_step *)(-EINVAL);
    if (step >= n->len) return (crush_rule_step *)(-EINVAL);
    return &n->steps[step];
  }

public:
  /* accessors */
  int get_max_rules() const {
    if (!crush) return 0;
    return crush->max_rules;
  }
  bool rule_exists(unsigned ruleno) const {
    if (!crush) return false;
    if (ruleno < crush->max_rules &&
	crush->rules[ruleno] != NULL)
      return true;
    return false;
  }
  bool rule_has_take(unsigned ruleno, int take) const {
    if (!crush) return false;
    crush_rule *rule = get_rule(ruleno);
    for (unsigned i = 0; i < rule->len; ++i) {
      if (rule->steps[i].op == CRUSH_RULE_TAKE &&
	  rule->steps[i].arg1 == take) {
	return true;
      }
    }
    return false;
  }
  int get_rule_len(unsigned ruleno) const {
    crush_rule *r = get_rule(ruleno);
    if (IS_ERR(r)) return PTR_ERR(r);
    return r->len;
  }
  int get_rule_mask_ruleset(unsigned ruleno) const {
    crush_rule *r = get_rule(ruleno);
    if (IS_ERR(r)) return -1;
    return r->mask.ruleset;
  }
  int get_rule_mask_type(unsigned ruleno) const {
    crush_rule *r = get_rule(ruleno);
    if (IS_ERR(r)) return -1;
    return r->mask.type;
  }
  int get_rule_mask_min_size(unsigned ruleno) const {
    crush_rule *r = get_rule(ruleno);
    if (IS_ERR(r)) return -1;
    return r->mask.min_size;
  }
  int get_rule_mask_max_size(unsigned ruleno) const {
    crush_rule *r = get_rule(ruleno);
    if (IS_ERR(r)) return -1;
    return r->mask.max_size;
  }
  int get_rule_op(unsigned ruleno, unsigned step) const {
    crush_rule_step *s = get_rule_step(ruleno, step);
    if (IS_ERR(s)) return PTR_ERR(s);
    return s->op;
  }
  int get_rule_arg1(unsigned ruleno, unsigned step) const {
    crush_rule_step *s = get_rule_step(ruleno, step);
    if (IS_ERR(s)) return PTR_ERR(s);
    return s->arg1;
  }
  int get_rule_arg2(unsigned ruleno, unsigned step) const {
    crush_rule_step *s = get_rule_step(ruleno, step);
    if (IS_ERR(s)) return PTR_ERR(s);
    return s->arg2;
  }

private:
  float _get_take_weight_osd_map(int root, map<int,float> *pmap) const;
  void _normalize_weight_map(float sum, const map<int,float>& m,
			     map<int,float> *pmap) const;

public:
  /**
   * calculate a map of osds to weights for a given rule
   *
   * Generate a map of which OSDs get how much relative weight for a
   * given rule.
   *
   * @param ruleno [in] rule id
   * @param pmap [out] map of osd to weight
   * @return 0 for success, or negative error code
   */
  int get_rule_weight_osd_map(unsigned ruleno, map<int,float> *pmap) const;

  /**
   * calculate a map of osds to weights for a given starting root
   *
   * Generate a map of which OSDs get how much relative weight for a
   * given starting root
   *
   * @param root node
   * @param pmap [out] map of osd to weight
   * @return 0 for success, or negative error code
   */
  int get_take_weight_osd_map(int root, map<int,float> *pmap) const;

  /* modifiers */

  int add_rule(int ruleno, int len, int type, int minsize, int maxsize) {
    if (!crush) return -ENOENT;
    crush_rule *n = crush_make_rule(len, ruleno, type, minsize, maxsize);
    ceph_assert(n);
    ruleno = crush_add_rule(crush, n, ruleno);
    return ruleno;
  }
  int set_rule_mask_max_size(unsigned ruleno, int max_size) {
    crush_rule *r = get_rule(ruleno);
    if (IS_ERR(r)) return -1;
    return r->mask.max_size = max_size;
  }
  int set_rule_step(unsigned ruleno, unsigned step, int op, int arg1, int arg2) {
    if (!crush) return -ENOENT;
    crush_rule *n = get_rule(ruleno);
    if (!n) return -1;
    crush_rule_set_step(n, step, op, arg1, arg2);
    return 0;
  }
  int set_rule_step_take(unsigned ruleno, unsigned step, int val) {
    return set_rule_step(ruleno, step, CRUSH_RULE_TAKE, val, 0);
  }
  int set_rule_step_set_choose_tries(unsigned ruleno, unsigned step, int val) {
    return set_rule_step(ruleno, step, CRUSH_RULE_SET_CHOOSE_TRIES, val, 0);
  }
  int set_rule_step_set_choose_local_tries(unsigned ruleno, unsigned step, int val) {
    return set_rule_step(ruleno, step, CRUSH_RULE_SET_CHOOSE_LOCAL_TRIES, val, 0);
  }
  int set_rule_step_set_choose_local_fallback_tries(unsigned ruleno, unsigned step, int val) {
    return set_rule_step(ruleno, step, CRUSH_RULE_SET_CHOOSE_LOCAL_FALLBACK_TRIES, val, 0);
  }
  int set_rule_step_set_chooseleaf_tries(unsigned ruleno, unsigned step, int val) {
    return set_rule_step(ruleno, step, CRUSH_RULE_SET_CHOOSELEAF_TRIES, val, 0);
  }
  int set_rule_step_set_chooseleaf_vary_r(unsigned ruleno, unsigned step, int val) {
    return set_rule_step(ruleno, step, CRUSH_RULE_SET_CHOOSELEAF_VARY_R, val, 0);
  }
  int set_rule_step_set_chooseleaf_stable(unsigned ruleno, unsigned step, int val) {
    return set_rule_step(ruleno, step, CRUSH_RULE_SET_CHOOSELEAF_STABLE, val, 0);
  }
  int set_rule_step_choose_firstn(unsigned ruleno, unsigned step, int val, int type) {
    return set_rule_step(ruleno, step, CRUSH_RULE_CHOOSE_FIRSTN, val, type);
  }
  int set_rule_step_choose_indep(unsigned ruleno, unsigned step, int val, int type) {
    return set_rule_step(ruleno, step, CRUSH_RULE_CHOOSE_INDEP, val, type);
  }
  int set_rule_step_choose_leaf_firstn(unsigned ruleno, unsigned step, int val, int type) {
    return set_rule_step(ruleno, step, CRUSH_RULE_CHOOSELEAF_FIRSTN, val, type);
  }
  int set_rule_step_choose_leaf_indep(unsigned ruleno, unsigned step, int val, int type) {
    return set_rule_step(ruleno, step, CRUSH_RULE_CHOOSELEAF_INDEP, val, type);
  }
  int set_rule_step_emit(unsigned ruleno, unsigned step) {
    return set_rule_step(ruleno, step, CRUSH_RULE_EMIT, 0, 0);
  }

  int add_simple_rule(
    string name, string root_name, string failure_domain_type,
    string device_class,
    string mode, int rule_type, ostream *err = 0);

  /**
   * @param rno rule[set] id to use, -1 to pick the lowest available
   */
  int add_simple_rule_at(
    string name, string root_name,
    string failure_domain_type, string device_class, string mode,
    int rule_type, int rno, ostream *err = 0);

  int remove_rule(int ruleno);


  /** buckets **/
  const crush_bucket *get_bucket(int id) const {
    if (!crush)
      return (crush_bucket *)(-EINVAL);
    unsigned int pos = (unsigned int)(-1 - id);
    unsigned int max_buckets = crush->max_buckets;
    if (pos >= max_buckets)
      return (crush_bucket *)(-ENOENT);
    crush_bucket *ret = crush->buckets[pos];
    if (ret == NULL)
      return (crush_bucket *)(-ENOENT);
    return ret;
  }
private:
  crush_bucket *get_bucket(int id) {
    if (!crush)
      return (crush_bucket *)(-EINVAL);
    unsigned int pos = (unsigned int)(-1 - id);
    unsigned int max_buckets = crush->max_buckets;
    if (pos >= max_buckets)
      return (crush_bucket *)(-ENOENT);
    crush_bucket *ret = crush->buckets[pos];
    if (ret == NULL)
      return (crush_bucket *)(-ENOENT);
    return ret;
  }
  /**
   * detach a bucket from its parent and adjust the parent weight
   *
   * returns the weight of the detached bucket
   **/
  int detach_bucket(CephContext *cct, int item);

  int get_new_bucket_id();

public:
  int get_max_buckets() const {
    if (!crush) return -EINVAL;
    return crush->max_buckets;
  }
  int get_next_bucket_id() const {
    if (!crush) return -EINVAL;
    return crush_get_next_bucket_id(crush);
  }
  bool bucket_exists(int id) const {
    const crush_bucket *b = get_bucket(id);
    if (IS_ERR(b))
      return false;
    return true;
  }
  int get_bucket_weight(int id) const {
    const crush_bucket *b = get_bucket(id);
    if (IS_ERR(b)) return PTR_ERR(b);
    return b->weight;
  }
  float get_bucket_weightf(int id) const {
    const crush_bucket *b = get_bucket(id);
    if (IS_ERR(b)) return 0;
    return b->weight / (float)0x10000;
  }
  int get_bucket_type(int id) const {
    const crush_bucket *b = get_bucket(id);
    if (IS_ERR(b)) return PTR_ERR(b);
    return b->type;
  }
  int get_bucket_alg(int id) const {
    const crush_bucket *b = get_bucket(id);
    if (IS_ERR(b)) return PTR_ERR(b);
    return b->alg;
  }
  int get_bucket_hash(int id) const {
    const crush_bucket *b = get_bucket(id);
    if (IS_ERR(b)) return PTR_ERR(b);
    return b->hash;
  }
  int get_bucket_size(int id) const {
    const crush_bucket *b = get_bucket(id);
    if (IS_ERR(b)) return PTR_ERR(b);
    return b->size;
  }
  int get_bucket_item(int id, int pos) const {
    const crush_bucket *b = get_bucket(id);
    if (IS_ERR(b)) return PTR_ERR(b);
    if ((__u32)pos >= b->size)
      return PTR_ERR(b);
    return b->items[pos];
  }
  int get_bucket_item_weight(int id, int pos) const {
    const crush_bucket *b = get_bucket(id);
    if (IS_ERR(b)) return PTR_ERR(b);
    return crush_get_bucket_item_weight(b, pos);
  }
  float get_bucket_item_weightf(int id, int pos) const {
    const crush_bucket *b = get_bucket(id);
    if (IS_ERR(b)) return 0;
    return (float)crush_get_bucket_item_weight(b, pos) / (float)0x10000;
  }

  /* modifiers */
  int add_bucket(int bucketno, int alg, int hash, int type, int size,
		 int *items, int *weights, int *idout);
  int bucket_add_item(crush_bucket *bucket, int item, int weight);
  int bucket_remove_item(struct crush_bucket *bucket, int item);
  int bucket_adjust_item_weight(
    CephContext *cct, struct crush_bucket *bucket, int item, int weight,
    bool adjust_weight_sets);

  void finalize() {
    ceph_assert(crush);
    crush_finalize(crush);
    if (!name_map.empty() &&
	name_map.rbegin()->first >= crush->max_devices) {
      crush->max_devices = name_map.rbegin()->first + 1;
    }
    have_uniform_rules = !has_legacy_rule_ids();
    build_rmaps();
  }
  int bucket_set_alg(int id, int alg);

  int update_device_class(int id, const string& class_name, const string& name, ostream *ss);
  int remove_device_class(CephContext *cct, int id, ostream *ss);
  int device_class_clone(
    int original, int device_class,
    const std::map<int32_t, map<int32_t, int32_t>>& old_class_bucket,
    const std::set<int32_t>& used_ids,
    int *clone,
    map<int,map<int,vector<int>>> *cmap_item_weight);
  bool class_is_in_use(int class_id, ostream *ss = nullptr);
  int rename_class(const string& srcname, const string& dstname);
  int populate_classes(
    const std::map<int32_t, map<int32_t, int32_t>>& old_class_bucket);
  int get_rules_by_class(const string &class_name, set<int> *rules);
  int get_rules_by_osd(int osd, set<int> *rules);
  bool _class_is_dead(int class_id);
  void cleanup_dead_classes();
  int rebuild_roots_with_classes(CephContext *cct);
  /* remove unused roots generated for class devices */
  int trim_roots_with_class(CephContext *cct);

  int reclassify(
    CephContext *cct,
    ostream& out,
    const map<string,string>& classify_root,
    const map<string,pair<string,string>>& classify_bucket
    );

  int set_subtree_class(const string& name, const string& class_name);

  void start_choose_profile() {
    free(crush->choose_tries);
    /*
     * the original choose_total_tries value was off by one (it
     * counted "retries" and not "tries").  add one to alloc.
     */
    crush->choose_tries = (__u32 *)calloc(sizeof(*crush->choose_tries),
					  (crush->choose_total_tries + 1));
    memset(crush->choose_tries, 0,
	   sizeof(*crush->choose_tries) * (crush->choose_total_tries + 1));
  }
  void stop_choose_profile() {
    free(crush->choose_tries);
    crush->choose_tries = 0;
  }

  int get_choose_profile(__u32 **vec) {
    if (crush->choose_tries) {
      *vec = crush->choose_tries;
      return crush->choose_total_tries;
    }
    return 0;
  }


  void set_max_devices(int m) {
    crush->max_devices = m;
  }

  int find_rule(int ruleset, int type, int size) const {
    if (!crush) return -1;
    if (have_uniform_rules &&
	ruleset < (int)crush->max_rules &&
	crush->rules[ruleset] &&
	crush->rules[ruleset]->mask.type == type &&
	crush->rules[ruleset]->mask.min_size <= size &&
	crush->rules[ruleset]->mask.max_size >= size) {
      return ruleset;
    }
    return crush_find_rule(crush, ruleset, type, size);
  }

  bool ruleset_exists(const int ruleset) const {
    for (size_t i = 0; i < crush->max_rules; ++i) {
      if (rule_exists(i) && crush->rules[i]->mask.ruleset == ruleset) {
	return true;
      }
    }

    return false;
  }

  /**
   * Return the lowest numbered ruleset of type `type`
   *
   * @returns a ruleset ID, or -1 if no matching rules found.
   */
  int find_first_ruleset(int type) const {
    int result = -1;

    for (size_t i = 0; i < crush->max_rules; ++i) {
      if (crush->rules[i]
          && crush->rules[i]->mask.type == type
          && (crush->rules[i]->mask.ruleset < result || result == -1)) {
        result = crush->rules[i]->mask.ruleset;
      }
    }

    return result;
  }

  bool have_choose_args(int64_t choose_args_index) const {
    return choose_args.count(choose_args_index);
  }

  crush_choose_arg_map choose_args_get_with_fallback(
    int64_t choose_args_index) const {
    auto i = choose_args.find(choose_args_index);
    if (i == choose_args.end()) {
      i = choose_args.find(DEFAULT_CHOOSE_ARGS);
    }
    if (i == choose_args.end()) {
      crush_choose_arg_map arg_map;
      arg_map.args = NULL;
      arg_map.size = 0;
      return arg_map;
    } else {
      return i->second;
    }
  }
  crush_choose_arg_map choose_args_get(int64_t choose_args_index) const {
    auto i = choose_args.find(choose_args_index);
    if (i == choose_args.end()) {
      crush_choose_arg_map arg_map;
      arg_map.args = NULL;
      arg_map.size = 0;
      return arg_map;
    } else {
      return i->second;
    }
  }

  void destroy_choose_args(crush_choose_arg_map arg_map) {
    for (__u32 i = 0; i < arg_map.size; i++) {
      crush_choose_arg *arg = &arg_map.args[i];
      for (__u32 j = 0; j < arg->weight_set_positions; j++) {
	crush_weight_set *weight_set = &arg->weight_set[j];
	free(weight_set->weights);
      }
      if (arg->weight_set)
	free(arg->weight_set);
      if (arg->ids)
	free(arg->ids);
    }
    free(arg_map.args);
  }

  bool create_choose_args(int64_t id, int positions) {
    if (choose_args.count(id))
      return false;
    ceph_assert(positions);
    auto &cmap = choose_args[id];
    cmap.args = static_cast<crush_choose_arg*>(calloc(sizeof(crush_choose_arg),
					  crush->max_buckets));
    cmap.size = crush->max_buckets;
    for (int bidx=0; bidx < crush->max_buckets; ++bidx) {
      crush_bucket *b = crush->buckets[bidx];
      auto &carg = cmap.args[bidx];
      carg.ids = NULL;
      carg.ids_size = 0;
      if (b && b->alg == CRUSH_BUCKET_STRAW2) {
	crush_bucket_straw2 *sb = reinterpret_cast<crush_bucket_straw2*>(b);
	carg.weight_set_positions = positions;
	carg.weight_set = static_cast<crush_weight_set*>(calloc(sizeof(crush_weight_set),
						    carg.weight_set_positions));
	// initialize with canonical weights
	for (int pos = 0; pos < positions; ++pos) {
	  carg.weight_set[pos].size = b->size;
	  carg.weight_set[pos].weights = (__u32*)calloc(4, b->size);
	  for (unsigned i = 0; i < b->size; ++i) {
	    carg.weight_set[pos].weights[i] = sb->item_weights[i];
	  }
	}
      } else {
	carg.weight_set = NULL;
	carg.weight_set_positions = 0;
      }
    }
    return true;
  }

  void rm_choose_args(int64_t id) {
    auto p = choose_args.find(id);
    if (p != choose_args.end()) {
      destroy_choose_args(p->second);
      choose_args.erase(p);
    }
  }

  void choose_args_clear() {
    for (auto w : choose_args)
      destroy_choose_args(w.second);
    choose_args.clear();
  }

  // remove choose_args for buckets that no longer exist, create them for new buckets
  void update_choose_args(CephContext *cct);

  // adjust choose_args_map weight, preserving the hierarchical summation
  // property.  used by callers optimizing layouts by tweaking weights.
  int _choose_args_adjust_item_weight_in_bucket(
    CephContext *cct,
    crush_choose_arg_map cmap,
    int bucketid,
    int id,
    const vector<int>& weight,
    ostream *ss);
  int choose_args_adjust_item_weight(
    CephContext *cct,
    crush_choose_arg_map cmap,
    int id, const vector<int>& weight,
    ostream *ss);
  int choose_args_adjust_item_weightf(
    CephContext *cct,
    crush_choose_arg_map cmap,
    int id, const vector<double>& weightf,
    ostream *ss) {
    vector<int> weight(weightf.size());
    for (unsigned i = 0; i < weightf.size(); ++i) {
      weight[i] = (int)(weightf[i] * (double)0x10000);
    }
    return choose_args_adjust_item_weight(cct, cmap, id, weight, ss);
  }

  int get_choose_args_positions(crush_choose_arg_map cmap) {
    // infer positions from other buckets
    for (unsigned j = 0; j < cmap.size; ++j) {
      if (cmap.args[j].weight_set_positions) {
	return cmap.args[j].weight_set_positions;
      }
    }
    return 1;
  }

  template<typename WeightVector>
  void do_rule(int rule, int x, vector<int>& out, int maxout,
	       const WeightVector& weight,
	       uint64_t choose_args_index) const {
    int rawout[maxout];
    char work[crush_work_size(crush, maxout)];
    crush_init_workspace(crush, work);
    crush_choose_arg_map arg_map = choose_args_get_with_fallback(
      choose_args_index);
    int numrep = crush_do_rule(crush, rule, x, rawout, maxout,
			       std::data(weight), std::size(weight),
			       work, arg_map.args);
    if (numrep < 0)
      numrep = 0;
    out.resize(numrep);
    for (int i=0; i<numrep; i++)
      out[i] = rawout[i];
  }

  int _choose_type_stack(
    CephContext *cct,
    const vector<pair<int,int>>& stack,
    const set<int>& overfull,
    const vector<int>& underfull,
    const vector<int>& more_underfull,
    const vector<int>& orig,
    vector<int>::const_iterator& i,
    set<int>& used,
    vector<int> *pw,
    int root_bucket,
    int rule) const;

  int try_remap_rule(
    CephContext *cct,
    int rule,
    int maxout,
    const set<int>& overfull,
    const vector<int>& underfull,
    const vector<int>& more_underfull,
    const vector<int>& orig,
    vector<int> *out) const;

  bool check_crush_rule(int ruleset, int type, int size,  ostream& ss) {
    ceph_assert(crush);

    __u32 i;
    for (i = 0; i < crush->max_rules; i++) {
      if (crush->rules[i] &&
	  crush->rules[i]->mask.ruleset == ruleset &&
	  crush->rules[i]->mask.type == type) {

        if (crush->rules[i]->mask.min_size <= size &&
            crush->rules[i]->mask.max_size >= size) {
          return true;
        } else if (size < crush->rules[i]->mask.min_size) {
          ss << "pool size is smaller than the crush rule min size";
          return false;
        } else {
          ss << "pool size is bigger than the crush rule max size";
          return false;
        }
      }
    }

    return false;
  }

  void encode(bufferlist &bl, uint64_t features) const;
  void decode(bufferlist::const_iterator &blp);
  void decode_crush_bucket(crush_bucket** bptr, bufferlist::const_iterator &blp);
  void dump(Formatter *f) const;
  void dump_rules(Formatter *f) const;
  void dump_rule(int ruleset, Formatter *f) const;
  void dump_tunables(Formatter *f) const;
  void dump_choose_args(Formatter *f) const;
  void list_rules(Formatter *f) const;
  void list_rules(ostream *ss) const;
  void dump_tree(ostream *out,
                 Formatter *f,
		 const CrushTreeDumper::name_map_t& ws,
                 bool show_shadow = false) const;
  void dump_tree(ostream *out, Formatter *f) {
    dump_tree(out, f, CrushTreeDumper::name_map_t());
  }
  void dump_tree(Formatter *f,
		 const CrushTreeDumper::name_map_t& ws) const;
  static void generate_test_instances(list<CrushWrapper*>& o);

  int get_osd_pool_default_crush_replicated_ruleset(CephContext *cct);

  static bool is_valid_crush_name(const string& s);
  static bool is_valid_crush_loc(CephContext *cct,
				 const map<string,string>& loc);
};
WRITE_CLASS_ENCODER_FEATURES(CrushWrapper)

#endif