summaryrefslogtreecommitdiffstats
path: root/src/mon/OSDMonitor.cc
blob: 414c269312329ae56aa61dcbe068bf82694d41c1 (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
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
 * Copyright (C) 2013,2014 Cloudwatt <libre.licensing@cloudwatt.com>
 * Copyright (C) 2014 Red Hat <contact@redhat.com>
 *
 * Author: Loic Dachary <loic@dachary.org>
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */

#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <experimental/iterator>
#include <locale>
#include <sstream>

#include "mon/OSDMonitor.h"
#include "mon/Monitor.h"
#include "mon/MDSMonitor.h"
#include "mon/MgrStatMonitor.h"
#include "mon/AuthMonitor.h"
#include "mon/ConfigKeyService.h"

#include "mon/MonitorDBStore.h"
#include "mon/Session.h"

#include "crush/CrushWrapper.h"
#include "crush/CrushTester.h"
#include "crush/CrushTreeDumper.h"

#include "messages/MOSDBeacon.h"
#include "messages/MOSDFailure.h"
#include "messages/MOSDMarkMeDown.h"
#include "messages/MOSDFull.h"
#include "messages/MOSDMap.h"
#include "messages/MMonGetOSDMap.h"
#include "messages/MOSDBoot.h"
#include "messages/MOSDAlive.h"
#include "messages/MPoolOp.h"
#include "messages/MPoolOpReply.h"
#include "messages/MOSDPGCreate.h"
#include "messages/MOSDPGCreate2.h"
#include "messages/MOSDPGCreated.h"
#include "messages/MOSDPGTemp.h"
#include "messages/MOSDPGReadyToMerge.h"
#include "messages/MMonCommand.h"
#include "messages/MRemoveSnaps.h"
#include "messages/MOSDScrub.h"
#include "messages/MRoute.h"

#include "common/TextTable.h"
#include "common/Timer.h"
#include "common/ceph_argparse.h"
#include "common/perf_counters.h"
#include "common/PriorityCache.h"
#include "common/strtol.h"
#include "common/numa.h"

#include "common/config.h"
#include "common/errno.h"

#include "erasure-code/ErasureCodePlugin.h"
#include "compressor/Compressor.h"
#include "common/Checksummer.h"

#include "include/compat.h"
#include "include/ceph_assert.h"
#include "include/stringify.h"
#include "include/util.h"
#include "common/cmdparse.h"
#include "include/str_list.h"
#include "include/str_map.h"
#include "include/scope_guard.h"
#include "perfglue/heap_profiler.h"

#include "auth/cephx/CephxKeyServer.h"
#include "osd/OSDCap.h"

#include "json_spirit/json_spirit_reader.h"

#include <boost/algorithm/string/predicate.hpp>

#define dout_subsys ceph_subsys_mon
static const string OSD_PG_CREATING_PREFIX("osd_pg_creating");
static const string OSD_METADATA_PREFIX("osd_metadata");
static const string OSD_SNAP_PREFIX("osd_snap");

namespace {

struct OSDMemCache : public PriorityCache::PriCache {
  OSDMonitor *osdmon;
  int64_t cache_bytes[PriorityCache::Priority::LAST+1] = {0};
  int64_t committed_bytes = 0;
  double cache_ratio = 0;

  OSDMemCache(OSDMonitor *m) : osdmon(m) {};

  virtual uint64_t _get_used_bytes() const = 0;

  virtual int64_t request_cache_bytes(
      PriorityCache::Priority pri, uint64_t total_cache) const {
    int64_t assigned = get_cache_bytes(pri);

    switch (pri) {
    // All cache items are currently set to have PRI1 priority
    case PriorityCache::Priority::PRI1:
      {
        int64_t request = _get_used_bytes();
        return (request > assigned) ? request - assigned : 0;
      }
    default:
      break;
    }
    return -EOPNOTSUPP;
  }

  virtual int64_t get_cache_bytes(PriorityCache::Priority pri) const {
      return cache_bytes[pri];
  }

  virtual int64_t get_cache_bytes() const {
    int64_t total = 0;

    for (int i = 0; i < PriorityCache::Priority::LAST + 1; i++) {
      PriorityCache::Priority pri = static_cast<PriorityCache::Priority>(i);
      total += get_cache_bytes(pri);
    }
    return total;
  }

  virtual void set_cache_bytes(PriorityCache::Priority pri, int64_t bytes) {
    cache_bytes[pri] = bytes;
  }
  virtual void add_cache_bytes(PriorityCache::Priority pri, int64_t bytes) {
    cache_bytes[pri] += bytes;
  }
  virtual int64_t commit_cache_size(uint64_t total_cache) {
    committed_bytes = PriorityCache::get_chunk(
        get_cache_bytes(), total_cache);
    return committed_bytes;
  }
  virtual int64_t get_committed_size() const {
    return committed_bytes;
  }
  virtual double get_cache_ratio() const {
    return cache_ratio;
  }
  virtual void set_cache_ratio(double ratio) {
    cache_ratio = ratio;
  }
  virtual string get_cache_name() const = 0;
};

struct IncCache : public OSDMemCache {
  IncCache(OSDMonitor *m) : OSDMemCache(m) {};

  virtual uint64_t _get_used_bytes() const {
    return osdmon->inc_osd_cache.get_bytes();
  }

  virtual string get_cache_name() const {
    return "OSDMap Inc Cache";
  }

  uint64_t _get_num_osdmaps() const {
    return osdmon->inc_osd_cache.get_size();
  }
};

struct FullCache : public OSDMemCache {
  FullCache(OSDMonitor *m) : OSDMemCache(m) {};

  virtual uint64_t _get_used_bytes() const {
    return osdmon->full_osd_cache.get_bytes();
  }

  virtual string get_cache_name() const {
    return "OSDMap Full Cache";
  }

  uint64_t _get_num_osdmaps() const {
    return osdmon->full_osd_cache.get_size();
  }
};

std::shared_ptr<IncCache> inc_cache;
std::shared_ptr<FullCache> full_cache;

const uint32_t MAX_POOL_APPLICATIONS = 4;
const uint32_t MAX_POOL_APPLICATION_KEYS = 64;
const uint32_t MAX_POOL_APPLICATION_LENGTH = 128;

bool is_osd_writable(const OSDCapGrant& grant, const std::string* pool_name) {
  // Note: this doesn't include support for the application tag match
  if ((grant.spec.allow & OSD_CAP_W) != 0) {
    auto& match = grant.match;
    if (match.is_match_all()) {
      return true;
    } else if (pool_name != nullptr &&
               !match.pool_namespace.pool_name.empty() &&
               match.pool_namespace.pool_name == *pool_name) {
      return true;
    }
  }
  return false;
}

bool is_unmanaged_snap_op_permitted(CephContext* cct,
                                    const KeyServer& key_server,
                                    const EntityName& entity_name,
                                    const MonCap& mon_caps,
				    const entity_addr_t& peer_socket_addr,
                                    const std::string* pool_name)
{
  typedef std::map<std::string, std::string> CommandArgs;

  if (mon_caps.is_capable(
	cct, entity_name, "osd",
	"osd pool op unmanaged-snap",
	(pool_name == nullptr ?
	 CommandArgs{} /* pool DNE, require unrestricted cap */ :
	 CommandArgs{{"poolname", *pool_name}}),
	false, true, false,
	peer_socket_addr)) {
    return true;
  }

  AuthCapsInfo caps_info;
  if (!key_server.get_service_caps(entity_name, CEPH_ENTITY_TYPE_OSD,
                                   caps_info)) {
    dout(10) << "unable to locate OSD cap data for " << entity_name
             << " in auth db" << dendl;
    return false;
  }

  string caps_str;
  if (caps_info.caps.length() > 0) {
    auto p = caps_info.caps.cbegin();
    try {
      decode(caps_str, p);
    } catch (const buffer::error &err) {
      derr << "corrupt OSD cap data for " << entity_name << " in auth db"
           << dendl;
      return false;
    }
  }

  OSDCap osd_cap;
  if (!osd_cap.parse(caps_str, nullptr)) {
    dout(10) << "unable to parse OSD cap data for " << entity_name
             << " in auth db" << dendl;
    return false;
  }

  // if the entity has write permissions in one or all pools, permit
  // usage of unmanaged-snapshots
  if (osd_cap.allow_all()) {
    return true;
  }

  for (auto& grant : osd_cap.grants) {
    if (grant.profile.is_valid()) {
      for (auto& profile_grant : grant.profile_grants) {
        if (is_osd_writable(profile_grant, pool_name)) {
          return true;
        }
      }
    } else if (is_osd_writable(grant, pool_name)) {
      return true;
    }
  }

  return false;
}

} // anonymous namespace

void LastEpochClean::Lec::report(ps_t ps, epoch_t last_epoch_clean)
{
  if (epoch_by_pg.size() <= ps) {
    epoch_by_pg.resize(ps + 1, 0);
  }
  const auto old_lec = epoch_by_pg[ps];
  if (old_lec >= last_epoch_clean) {
    // stale lec
    return;
  }
  epoch_by_pg[ps] = last_epoch_clean;
  if (last_epoch_clean < floor) {
    floor = last_epoch_clean;
  } else if (last_epoch_clean > floor) {
    if (old_lec == floor) {
      // probably should increase floor?
      auto new_floor = std::min_element(std::begin(epoch_by_pg),
					std::end(epoch_by_pg));
      floor = *new_floor;
    }
  }
  if (ps != next_missing) {
    return;
  }
  for (; next_missing < epoch_by_pg.size(); next_missing++) {
    if (epoch_by_pg[next_missing] == 0) {
      break;
    }
  }
}

void LastEpochClean::remove_pool(uint64_t pool)
{
  report_by_pool.erase(pool);
}

void LastEpochClean::report(const pg_t& pg, epoch_t last_epoch_clean)
{
  auto& lec = report_by_pool[pg.pool()];
  return lec.report(pg.ps(), last_epoch_clean);
}

epoch_t LastEpochClean::get_lower_bound(const OSDMap& latest) const
{
  auto floor = latest.get_epoch();
  for (auto& pool : latest.get_pools()) {
    auto reported = report_by_pool.find(pool.first);
    if (reported == report_by_pool.end()) {
      return 0;
    }
    if (reported->second.next_missing < pool.second.get_pg_num()) {
      return 0;
    }
    if (reported->second.floor < floor) {
      floor = reported->second.floor;
    }
  }
  return floor;
}

void LastEpochClean::dump(Formatter *f) const
{
  f->open_array_section("per_pool");

  for (auto& it : report_by_pool) {
    f->open_object_section("pool");
    f->dump_unsigned("poolid", it.first);
    f->dump_unsigned("floor", it.second.floor);
    f->close_section();
  }

  f->close_section();
}

class C_UpdateCreatingPGs : public Context {
public:
  OSDMonitor *osdmon;
  utime_t start;
  epoch_t epoch;
  C_UpdateCreatingPGs(OSDMonitor *osdmon, epoch_t e) :
    osdmon(osdmon), start(ceph_clock_now()), epoch(e) {}
  void finish(int r) override {
    if (r >= 0) {
      utime_t end = ceph_clock_now();
      dout(10) << "osdmap epoch " << epoch << " mapping took "
	       << (end - start) << " seconds" << dendl;
      osdmon->update_creating_pgs();
      osdmon->check_pg_creates_subs();
    }
  }
};

#undef dout_prefix
#define dout_prefix _prefix(_dout, mon, osdmap)
static ostream& _prefix(std::ostream *_dout, Monitor *mon, const OSDMap& osdmap) {
  return *_dout << "mon." << mon->name << "@" << mon->rank
		<< "(" << mon->get_state_name()
		<< ").osd e" << osdmap.get_epoch() << " ";
}

OSDMonitor::OSDMonitor(
  CephContext *cct,
  Monitor *mn,
  Paxos *p,
  const string& service_name)
 : PaxosService(mn, p, service_name),
   cct(cct),
   inc_osd_cache(g_conf()->mon_osd_cache_size),
   full_osd_cache(g_conf()->mon_osd_cache_size),
   has_osdmap_manifest(false),
   mapper(mn->cct, &mn->cpu_tp)
{
  inc_cache = std::make_shared<IncCache>(this);
  full_cache = std::make_shared<FullCache>(this);
  cct->_conf.add_observer(this);
  int r = _set_cache_sizes();
  if (r < 0) {
    derr << __func__ << " using default osd cache size - mon_osd_cache_size ("
         << g_conf()->mon_osd_cache_size
         << ") without priority cache management"
         << dendl;
  }
}

const char **OSDMonitor::get_tracked_conf_keys() const
{
  static const char* KEYS[] = {
    "mon_memory_target",
    "mon_memory_autotune",
    "rocksdb_cache_size",
    NULL
  };
  return KEYS;
}

void OSDMonitor::handle_conf_change(const ConfigProxy& conf,
                                    const std::set<std::string> &changed)
{
  dout(10) << __func__ << " " << changed << dendl;

  if (changed.count("mon_memory_autotune")) {
    _set_cache_autotuning();
  }
  if (changed.count("mon_memory_target") ||
      changed.count("rocksdb_cache_size")) {
    int r = _update_mon_cache_settings();
    if (r < 0) {
      derr << __func__ << " mon_memory_target:"
           << g_conf()->mon_memory_target
           << " rocksdb_cache_size:"
           << g_conf()->rocksdb_cache_size
           << ". Unable to update cache size."
           << dendl;
    }
  }
}

void OSDMonitor::_set_cache_autotuning()
{
  if (!g_conf()->mon_memory_autotune && pcm != nullptr) {
    // Disable cache autotuning
    std::lock_guard l(balancer_lock);
    pcm = nullptr;
  }

  if (g_conf()->mon_memory_autotune && pcm == nullptr) {
    int r = register_cache_with_pcm();
    if (r < 0) {
      dout(10) << __func__
               << " Error while registering osdmon caches with pcm."
               << " Cache auto tuning not enabled."
               << dendl;
      mon_memory_autotune = false;
    } else {
      mon_memory_autotune = true;
    }
  }
}

int OSDMonitor::_update_mon_cache_settings()
{
  if (g_conf()->mon_memory_target <= 0 ||
      g_conf()->mon_memory_target < mon_memory_min ||
      g_conf()->rocksdb_cache_size <= 0) {
    return -EINVAL;
  }

  if (pcm == nullptr && rocksdb_binned_kv_cache == nullptr) {
    derr << __func__ << " not using pcm and rocksdb" << dendl;
    return -EINVAL;
  }

  uint64_t old_mon_memory_target = mon_memory_target;
  uint64_t old_rocksdb_cache_size = rocksdb_cache_size;

  // Set the new pcm memory cache sizes
  mon_memory_target = g_conf()->mon_memory_target;
  rocksdb_cache_size = g_conf()->rocksdb_cache_size;

  uint64_t base = mon_memory_base;
  double fragmentation = mon_memory_fragmentation;
  uint64_t target = mon_memory_target;
  uint64_t min = mon_memory_min;
  uint64_t max = min;

  uint64_t ltarget = (1.0 - fragmentation) * target;
  if (ltarget > base + min) {
    max = ltarget - base;
  }

  int r = _set_cache_ratios();
  if (r < 0) {
    derr << __func__ << " Cache ratios for pcm could not be set."
         << " Review the kv (rocksdb) and mon_memory_target sizes."
         << dendl;
    mon_memory_target = old_mon_memory_target;
    rocksdb_cache_size = old_rocksdb_cache_size;
    return -EINVAL;
  }

  if (mon_memory_autotune && pcm != nullptr) {
    std::lock_guard l(balancer_lock);
    // set pcm cache levels
    pcm->set_target_memory(target);
    pcm->set_min_memory(min);
    pcm->set_max_memory(max);
    // tune memory based on new values
    pcm->tune_memory();
    pcm->balance();
    _set_new_cache_sizes();
    dout(1) << __func__ << " Updated mon cache setting."
             << " target: " << target
             << " min: " << min
             << " max: " << max
             << dendl;
  }
  return 0;
}

int OSDMonitor::_set_cache_sizes()
{
  if (g_conf()->mon_memory_autotune) {
    // set the new osdmon cache targets to be managed by pcm
    mon_osd_cache_size = g_conf()->mon_osd_cache_size;
    rocksdb_cache_size = g_conf()->rocksdb_cache_size;
    mon_memory_base = cct->_conf.get_val<Option::size_t>("osd_memory_base");
    mon_memory_fragmentation = cct->_conf.get_val<double>("osd_memory_expected_fragmentation");
    mon_memory_target = g_conf()->mon_memory_target;
    mon_memory_min = g_conf()->mon_osd_cache_size_min;
    if (mon_memory_target <= 0 || mon_memory_min <= 0) {
      derr << __func__ << " mon_memory_target:" << mon_memory_target
           << " mon_memory_min:" << mon_memory_min
           << ". Invalid size option(s) provided."
           << dendl;
      return -EINVAL;
    }
    // Set the initial inc and full LRU cache sizes
    inc_osd_cache.set_bytes(mon_memory_min);
    full_osd_cache.set_bytes(mon_memory_min);
    mon_memory_autotune = g_conf()->mon_memory_autotune;
  }
  return 0;
}

bool OSDMonitor::_have_pending_crush()
{
  return pending_inc.crush.length() > 0;
}

CrushWrapper &OSDMonitor::_get_stable_crush()
{
  return *osdmap.crush;
}

void OSDMonitor::_get_pending_crush(CrushWrapper& newcrush)
{
  bufferlist bl;
  if (pending_inc.crush.length())
    bl = pending_inc.crush;
  else
    osdmap.crush->encode(bl, CEPH_FEATURES_SUPPORTED_DEFAULT);

  auto p = bl.cbegin();
  newcrush.decode(p);
}

void OSDMonitor::create_initial()
{
  dout(10) << "create_initial for " << mon->monmap->fsid << dendl;

  OSDMap newmap;

  bufferlist bl;
  mon->store->get("mkfs", "osdmap", bl);

  if (bl.length()) {
    newmap.decode(bl);
    newmap.set_fsid(mon->monmap->fsid);
  } else {
    newmap.build_simple(cct, 0, mon->monmap->fsid, 0);
  }
  newmap.set_epoch(1);
  newmap.created = newmap.modified = ceph_clock_now();

  // new clusters should sort bitwise by default.
  newmap.set_flag(CEPH_OSDMAP_SORTBITWISE);

  newmap.flags |=
    CEPH_OSDMAP_RECOVERY_DELETES |
    CEPH_OSDMAP_PURGED_SNAPDIRS |
    CEPH_OSDMAP_PGLOG_HARDLIMIT;
  newmap.full_ratio = g_conf()->mon_osd_full_ratio;
  if (newmap.full_ratio > 1.0) newmap.full_ratio /= 100;
  newmap.backfillfull_ratio = g_conf()->mon_osd_backfillfull_ratio;
  if (newmap.backfillfull_ratio > 1.0) newmap.backfillfull_ratio /= 100;
  newmap.nearfull_ratio = g_conf()->mon_osd_nearfull_ratio;
  if (newmap.nearfull_ratio > 1.0) newmap.nearfull_ratio /= 100;

  // new cluster should require latest by default
  if (g_conf().get_val<bool>("mon_debug_no_require_nautilus")) {
    if (g_conf()->mon_debug_no_require_mimic) {
      derr << __func__ << " mon_debug_no_require_mimic=true and nautilus=true" << dendl;
      newmap.require_osd_release = CEPH_RELEASE_LUMINOUS;
    } else {
      derr << __func__ << " mon_debug_no_require_nautilus=true" << dendl;
      newmap.require_osd_release = CEPH_RELEASE_MIMIC;
    }
  } else {
    newmap.require_osd_release = CEPH_RELEASE_NAUTILUS;
    int r = ceph_release_from_name(
      g_conf()->mon_osd_initial_require_min_compat_client.c_str());
    if (r <= 0) {
      ceph_abort_msg("mon_osd_initial_require_min_compat_client is not valid");
    }
    newmap.require_min_compat_client = r;
  }

  // encode into pending incremental
  uint64_t features = newmap.get_encoding_features();
  newmap.encode(pending_inc.fullmap,
                features | CEPH_FEATURE_RESERVED);
  pending_inc.full_crc = newmap.get_crc();
  dout(20) << " full crc " << pending_inc.full_crc << dendl;
}

void OSDMonitor::get_store_prefixes(std::set<string>& s) const
{
  s.insert(service_name);
  s.insert(OSD_PG_CREATING_PREFIX);
  s.insert(OSD_METADATA_PREFIX);
  s.insert(OSD_SNAP_PREFIX);
}

void OSDMonitor::update_from_paxos(bool *need_bootstrap)
{
  // we really don't care if the version has been updated, because we may
  // have trimmed without having increased the last committed; yet, we may
  // need to update the in-memory manifest.
  load_osdmap_manifest();

  version_t version = get_last_committed();
  if (version == osdmap.epoch)
    return;
  ceph_assert(version > osdmap.epoch);

  dout(15) << "update_from_paxos paxos e " << version
	   << ", my e " << osdmap.epoch << dendl;

  if (mapping_job) {
    if (!mapping_job->is_done()) {
      dout(1) << __func__ << " mapping job "
	      << mapping_job.get() << " did not complete, "
	      << mapping_job->shards << " left, canceling" << dendl;
      mapping_job->abort();
    }
    mapping_job.reset();
  }

  load_health();

  /*
   * We will possibly have a stashed latest that *we* wrote, and we will
   * always be sure to have the oldest full map in the first..last range
   * due to encode_trim_extra(), which includes the oldest full map in the trim
   * transaction.
   *
   * encode_trim_extra() does not however write the full map's
   * version to 'full_latest'.  This is only done when we are building the
   * full maps from the incremental versions.  But don't panic!  We make sure
   * that the following conditions find whichever full map version is newer.
   */
  version_t latest_full = get_version_latest_full();
  if (latest_full == 0 && get_first_committed() > 1)
    latest_full = get_first_committed();

  if (get_first_committed() > 1 &&
      latest_full < get_first_committed()) {
    // the monitor could be just sync'ed with its peer, and the latest_full key
    // is not encoded in the paxos commits in encode_pending(), so we need to
    // make sure we get it pointing to a proper version.
    version_t lc = get_last_committed();
    version_t fc = get_first_committed();

    dout(10) << __func__ << " looking for valid full map in interval"
	     << " [" << fc << ", " << lc << "]" << dendl;

    latest_full = 0;
    for (version_t v = lc; v >= fc; v--) {
      string full_key = "full_" + stringify(v);
      if (mon->store->exists(get_service_name(), full_key)) {
        dout(10) << __func__ << " found latest full map v " << v << dendl;
        latest_full = v;
        break;
      }
    }

    ceph_assert(latest_full > 0);
    auto t(std::make_shared<MonitorDBStore::Transaction>());
    put_version_latest_full(t, latest_full);
    mon->store->apply_transaction(t);
    dout(10) << __func__ << " updated the on-disk full map version to "
             << latest_full << dendl;
  }

  if ((latest_full > 0) && (latest_full > osdmap.epoch)) {
    bufferlist latest_bl;
    get_version_full(latest_full, latest_bl);
    ceph_assert(latest_bl.length() != 0);
    dout(7) << __func__ << " loading latest full map e" << latest_full << dendl;
    osdmap = OSDMap();
    osdmap.decode(latest_bl);
  }

  bufferlist bl;
  if (!mon->store->get(OSD_PG_CREATING_PREFIX, "creating", bl)) {
    auto p = bl.cbegin();
    std::lock_guard<std::mutex> l(creating_pgs_lock);
    creating_pgs.decode(p);
    dout(7) << __func__ << " loading creating_pgs last_scan_epoch "
	    << creating_pgs.last_scan_epoch
	    << " with " << creating_pgs.pgs.size() << " pgs" << dendl;
  } else {
    dout(1) << __func__ << " missing creating pgs; upgrade from post-kraken?"
	    << dendl;
  }

  // walk through incrementals
  MonitorDBStore::TransactionRef t;
  size_t tx_size = 0;
  while (version > osdmap.epoch) {
    bufferlist inc_bl;
    int err = get_version(osdmap.epoch+1, inc_bl);
    ceph_assert(err == 0);
    ceph_assert(inc_bl.length());
    // set priority cache manager levels if the osdmap is
    // being populated for the first time.
    if (mon_memory_autotune && pcm == nullptr) {
      int r = register_cache_with_pcm();
      if (r < 0) {
        dout(10) << __func__
                 << " Error while registering osdmon caches with pcm."
                 << " Proceeding without cache auto tuning."
                 << dendl;
      }
    }

    dout(7) << "update_from_paxos  applying incremental " << osdmap.epoch+1
	    << dendl;
    OSDMap::Incremental inc(inc_bl);
    err = osdmap.apply_incremental(inc);
    ceph_assert(err == 0);

    if (!t)
      t.reset(new MonitorDBStore::Transaction);

    // Write out the full map for all past epochs.  Encode the full
    // map with the same features as the incremental.  If we don't
    // know, use the quorum features.  If we don't know those either,
    // encode with all features.
    uint64_t f = inc.encode_features;
    if (!f)
      f = mon->get_quorum_con_features();
    if (!f)
      f = -1;
    bufferlist full_bl;
    osdmap.encode(full_bl, f | CEPH_FEATURE_RESERVED);
    tx_size += full_bl.length();

    bufferlist orig_full_bl;
    get_version_full(osdmap.epoch, orig_full_bl);
    if (orig_full_bl.length()) {
      // the primary provided the full map
      ceph_assert(inc.have_crc);
      if (inc.full_crc != osdmap.crc) {
	// This will happen if the mons were running mixed versions in
	// the past or some other circumstance made the full encoded
	// maps divergent.  Reloading here will bring us back into
	// sync with the primary for this and all future maps.  OSDs
	// will also be brought back into sync when they discover the
	// crc mismatch and request a full map from a mon.
	derr << __func__ << " full map CRC mismatch, resetting to canonical"
	     << dendl;

	dout(20) << __func__ << " my (bad) full osdmap:\n";
	JSONFormatter jf(true);
	jf.dump_object("osdmap", osdmap);
	jf.flush(*_dout);
	*_dout << "\nhexdump:\n";
	full_bl.hexdump(*_dout);
	*_dout << dendl;

	osdmap = OSDMap();
	osdmap.decode(orig_full_bl);

	dout(20) << __func__ << " canonical full osdmap:\n";
	JSONFormatter jf(true);
	jf.dump_object("osdmap", osdmap);
	jf.flush(*_dout);
	*_dout << "\nhexdump:\n";
	orig_full_bl.hexdump(*_dout);
	*_dout << dendl;
      }
    } else {
      ceph_assert(!inc.have_crc);
      put_version_full(t, osdmap.epoch, full_bl);
    }
    put_version_latest_full(t, osdmap.epoch);

    // share
    dout(1) << osdmap << dendl;

    if (osdmap.epoch == 1) {
      t->erase("mkfs", "osdmap");
    }

    if (tx_size > g_conf()->mon_sync_max_payload_size*2) {
      mon->store->apply_transaction(t);
      t = MonitorDBStore::TransactionRef();
      tx_size = 0;
    }
    for (const auto &osd_state : inc.new_state) {
      if (osd_state.second & CEPH_OSD_UP) {
	// could be marked up *or* down, but we're too lazy to check which
	last_osd_report.erase(osd_state.first);
      }
      if (osd_state.second & CEPH_OSD_EXISTS) {
	// could be created *or* destroyed, but we can safely drop it
	osd_epochs.erase(osd_state.first);
      }
    }
  }

  if (t) {
    mon->store->apply_transaction(t);
  }

  for (int o = 0; o < osdmap.get_max_osd(); o++) {
    if (osdmap.is_out(o))
      continue;
    auto found = down_pending_out.find(o);
    if (osdmap.is_down(o)) {
      // populate down -> out map
      if (found == down_pending_out.end()) {
        dout(10) << " adding osd." << o << " to down_pending_out map" << dendl;
        down_pending_out[o] = ceph_clock_now();
      }
    } else {
      if (found != down_pending_out.end()) {
        dout(10) << " removing osd." << o << " from down_pending_out map" << dendl;
        down_pending_out.erase(found);
      }
    }
  }
  // XXX: need to trim MonSession connected with a osd whose id > max_osd?

  check_osdmap_subs();
  check_pg_creates_subs();

  share_map_with_random_osd();
  update_logger();
  process_failures();

  // make sure our feature bits reflect the latest map
  update_msgr_features();

  if (!mon->is_leader()) {
    // will be called by on_active() on the leader, avoid doing so twice
    start_mapping();
  }
}

int OSDMonitor::register_cache_with_pcm()
{
  if (mon_memory_target <= 0 || mon_memory_min <= 0) {
    derr << __func__ << " Invalid memory size specified for mon caches."
         << " Caches will not be auto-tuned."
         << dendl;
    return -EINVAL;
  }
  uint64_t base = mon_memory_base;
  double fragmentation = mon_memory_fragmentation;
  // For calculating total target memory, consider rocksdb cache size.
  uint64_t target = mon_memory_target;
  uint64_t min = mon_memory_min;
  uint64_t max = min;

  // Apply the same logic as in bluestore to set the max amount
  // of memory to use for cache. Assume base memory for OSDMaps
  // and then add in some overhead for fragmentation.
  uint64_t ltarget = (1.0 - fragmentation) * target;
  if (ltarget > base + min) {
    max = ltarget - base;
  }

  rocksdb_binned_kv_cache = mon->store->get_priority_cache();
  if (!rocksdb_binned_kv_cache) {
    derr << __func__ << " not using rocksdb" << dendl;
    return -EINVAL;
  }

  int r = _set_cache_ratios();
  if (r < 0) {
    derr << __func__ << " Cache ratios for pcm could not be set."
         << " Review the kv (rocksdb) and mon_memory_target sizes."
         << dendl;
    return -EINVAL;
  }

  pcm = std::make_shared<PriorityCache::Manager>(
      cct, min, max, target, true);
  pcm->insert("kv", rocksdb_binned_kv_cache, true);
  pcm->insert("inc", inc_cache, true);
  pcm->insert("full", full_cache, true);
  dout(1) << __func__ << " pcm target: " << target
           << " pcm max: " << max
           << " pcm min: " << min
           << " inc_osd_cache size: " << inc_osd_cache.get_size()
           << dendl;
  return 0;
}

int OSDMonitor::_set_cache_ratios()
{
  double old_cache_kv_ratio = cache_kv_ratio;

  // Set the cache ratios for kv(rocksdb), inc and full caches
  cache_kv_ratio = (double)rocksdb_cache_size / (double)mon_memory_target;
  if (cache_kv_ratio >= 1.0) {
    derr << __func__ << " Cache kv ratio (" << cache_kv_ratio
         << ") must be in range [0,<1.0]."
         << dendl;
    cache_kv_ratio = old_cache_kv_ratio;
    return -EINVAL;
  }
  rocksdb_binned_kv_cache->set_cache_ratio(cache_kv_ratio);
  cache_inc_ratio = cache_full_ratio = (1.0 - cache_kv_ratio) / 2;
  inc_cache->set_cache_ratio(cache_inc_ratio);
  full_cache->set_cache_ratio(cache_full_ratio);

  dout(1) << __func__ << " kv ratio " << cache_kv_ratio
           << " inc ratio " << cache_inc_ratio
           << " full ratio " << cache_full_ratio
           << dendl;
  return 0;
}

void OSDMonitor::start_mapping()
{
  // initiate mapping job
  if (mapping_job) {
    dout(10) << __func__ << " canceling previous mapping_job " << mapping_job.get()
	     << dendl;
    mapping_job->abort();
  }
  if (!osdmap.get_pools().empty()) {
    auto fin = new C_UpdateCreatingPGs(this, osdmap.get_epoch());
    mapping_job = mapping.start_update(osdmap, mapper,
				       g_conf()->mon_osd_mapping_pgs_per_chunk);
    dout(10) << __func__ << " started mapping job " << mapping_job.get()
	     << " at " << fin->start << dendl;
    mapping_job->set_finish_event(fin);
  } else {
    dout(10) << __func__ << " no pools, no mapping job" << dendl;
    mapping_job = nullptr;
  }
}

void OSDMonitor::update_msgr_features()
{
  set<int> types;
  types.insert((int)entity_name_t::TYPE_OSD);
  types.insert((int)entity_name_t::TYPE_CLIENT);
  types.insert((int)entity_name_t::TYPE_MDS);
  types.insert((int)entity_name_t::TYPE_MON);
  for (set<int>::iterator q = types.begin(); q != types.end(); ++q) {
    uint64_t mask;
    uint64_t features = osdmap.get_features(*q, &mask);
    if ((mon->messenger->get_policy(*q).features_required & mask) != features) {
      dout(0) << "crush map has features " << features << ", adjusting msgr requires" << dendl;
      ceph::net::Policy p = mon->messenger->get_policy(*q);
      p.features_required = (p.features_required & ~mask) | features;
      mon->messenger->set_policy(*q, p);
    }
  }
}

void OSDMonitor::on_active()
{
  update_logger();

  if (mon->is_leader()) {
    mon->clog->debug() << "osdmap " << osdmap;
    if (!priority_convert) {
      // Only do this once at start-up
      convert_pool_priorities();
      priority_convert = true;
    }
  } else {
    list<MonOpRequestRef> ls;
    take_all_failures(ls);
    while (!ls.empty()) {
      MonOpRequestRef op = ls.front();
      op->mark_osdmon_event(__func__);
      dispatch(op);
      ls.pop_front();
    }
  }
  start_mapping();
}

void OSDMonitor::on_restart()
{
  last_osd_report.clear();
}

void OSDMonitor::on_shutdown()
{
  dout(10) << __func__ << dendl;
  if (mapping_job) {
    dout(10) << __func__ << " canceling previous mapping_job " << mapping_job.get()
	     << dendl;
    mapping_job->abort();
  }

  // discard failure info, waiters
  list<MonOpRequestRef> ls;
  take_all_failures(ls);
  ls.clear();
}

void OSDMonitor::update_logger()
{
  dout(10) << "update_logger" << dendl;

  mon->cluster_logger->set(l_cluster_num_osd, osdmap.get_num_osds());
  mon->cluster_logger->set(l_cluster_num_osd_up, osdmap.get_num_up_osds());
  mon->cluster_logger->set(l_cluster_num_osd_in, osdmap.get_num_in_osds());
  mon->cluster_logger->set(l_cluster_osd_epoch, osdmap.get_epoch());
}

void OSDMonitor::create_pending()
{
  pending_inc = OSDMap::Incremental(osdmap.epoch+1);
  pending_inc.fsid = mon->monmap->fsid;
  pending_metadata.clear();
  pending_metadata_rm.clear();

  dout(10) << "create_pending e " << pending_inc.epoch << dendl;

  // safety checks (this shouldn't really happen)
  {
    if (osdmap.backfillfull_ratio <= 0) {
      pending_inc.new_backfillfull_ratio = g_conf()->mon_osd_backfillfull_ratio;
      if (pending_inc.new_backfillfull_ratio > 1.0)
	pending_inc.new_backfillfull_ratio /= 100;
      dout(1) << __func__ << " setting backfillfull_ratio = "
	      << pending_inc.new_backfillfull_ratio << dendl;
    }
    if (osdmap.full_ratio <= 0) {
      pending_inc.new_full_ratio = g_conf()->mon_osd_full_ratio;
      if (pending_inc.new_full_ratio > 1.0)
        pending_inc.new_full_ratio /= 100;
      dout(1) << __func__ << " setting full_ratio = "
	      << pending_inc.new_full_ratio << dendl;
    }
    if (osdmap.nearfull_ratio <= 0) {
      pending_inc.new_nearfull_ratio = g_conf()->mon_osd_nearfull_ratio;
      if (pending_inc.new_nearfull_ratio > 1.0)
        pending_inc.new_nearfull_ratio /= 100;
      dout(1) << __func__ << " setting nearfull_ratio = "
	      << pending_inc.new_nearfull_ratio << dendl;
    }
  }

  // Rewrite CRUSH rule IDs if they are using legacy "ruleset"
  // structure.
  if (osdmap.crush->has_legacy_rule_ids()) {
    CrushWrapper newcrush;
    _get_pending_crush(newcrush);

    // First, for all pools, work out which rule they really used
    // by resolving ruleset to rule.
    for (const auto &i : osdmap.get_pools()) {
      const auto pool_id = i.first;
      const auto &pool = i.second;
      int new_rule_id = newcrush.find_rule(pool.crush_rule,
					   pool.type, pool.size);

      dout(1) << __func__ << " rewriting pool "
	      << osdmap.get_pool_name(pool_id) << " crush ruleset "
	      << pool.crush_rule << " -> rule id " << new_rule_id << dendl;
      if (pending_inc.new_pools.count(pool_id) == 0) {
	pending_inc.new_pools[pool_id] = pool;
      }
      pending_inc.new_pools[pool_id].crush_rule = new_rule_id;
    }

    // Now, go ahead and renumber all the rules so that their
    // rule_id field corresponds to their position in the array
    auto old_to_new = newcrush.renumber_rules();
    dout(1) << __func__ << " Rewrote " << old_to_new << " crush IDs:" << dendl;
    for (const auto &i : old_to_new) {
      dout(1) << __func__ << " " << i.first << " -> " << i.second << dendl;
    }
    pending_inc.crush.clear();
    newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
  }
}

creating_pgs_t
OSDMonitor::update_pending_pgs(const OSDMap::Incremental& inc,
			       const OSDMap& nextmap)
{
  dout(10) << __func__ << dendl;
  creating_pgs_t pending_creatings;
  {
    std::lock_guard<std::mutex> l(creating_pgs_lock);
    pending_creatings = creating_pgs;
  }
  // check for new or old pools
  if (pending_creatings.last_scan_epoch < inc.epoch) {
    unsigned queued = 0;
    queued += scan_for_creating_pgs(osdmap.get_pools(),
				    inc.old_pools,
				    inc.modified,
				    &pending_creatings);
    queued += scan_for_creating_pgs(inc.new_pools,
				    inc.old_pools,
				    inc.modified,
				    &pending_creatings);
    dout(10) << __func__ << " " << queued << " pools queued" << dendl;
    for (auto deleted_pool : inc.old_pools) {
      auto removed = pending_creatings.remove_pool(deleted_pool);
      dout(10) << __func__ << " " << removed
               << " pg removed because containing pool deleted: "
               << deleted_pool << dendl;
      last_epoch_clean.remove_pool(deleted_pool);
    }
    // pgmon updates its creating_pgs in check_osd_map() which is called by
    // on_active() and check_osd_map() could be delayed if lease expires, so its
    // creating_pgs could be stale in comparison with the one of osdmon. let's
    // trim them here. otherwise, they will be added back after being erased.
    unsigned removed = 0;
    for (auto& pg : pending_created_pgs) {
      dout(20) << __func__ << " noting created pg " << pg << dendl;
      pending_creatings.created_pools.insert(pg.pool());
      removed += pending_creatings.pgs.erase(pg);
    }
    pending_created_pgs.clear();
    dout(10) << __func__ << " " << removed
	     << " pgs removed because they're created" << dendl;
    pending_creatings.last_scan_epoch = osdmap.get_epoch();
  }

  // filter out any pgs that shouldn't exist.
  {
    auto i = pending_creatings.pgs.begin();
    while (i != pending_creatings.pgs.end()) {
      if (!nextmap.pg_exists(i->first)) {
	dout(10) << __func__ << " removing pg " << i->first
		 << " which should not exist" << dendl;
	i = pending_creatings.pgs.erase(i);
      } else {
	++i;
      }
    }
  }

  // process queue
  unsigned max = std::max<int64_t>(1, g_conf()->mon_osd_max_creating_pgs);
  const auto total = pending_creatings.pgs.size();
  while (pending_creatings.pgs.size() < max &&
	 !pending_creatings.queue.empty()) {
    auto p = pending_creatings.queue.begin();
    int64_t poolid = p->first;
    dout(10) << __func__ << " pool " << poolid
	     << " created " << p->second.created
	     << " modified " << p->second.modified
	     << " [" << p->second.start << "-" << p->second.end << ")"
	     << dendl;
    int64_t n = std::min<int64_t>(max - pending_creatings.pgs.size(),
				  p->second.end - p->second.start);
    ps_t first = p->second.start;
    ps_t end = first + n;
    for (ps_t ps = first; ps < end; ++ps) {
      const pg_t pgid{ps, static_cast<uint64_t>(poolid)};
      // NOTE: use the *current* epoch as the PG creation epoch so that the
      // OSD does not have to generate a long set of PastIntervals.
      pending_creatings.pgs.emplace(pgid, make_pair(inc.epoch,
						    p->second.modified));
      dout(10) << __func__ << " adding " << pgid << dendl;
    }
    p->second.start = end;
    if (p->second.done()) {
      dout(10) << __func__ << " done with queue for " << poolid << dendl;
      pending_creatings.queue.erase(p);
    } else {
      dout(10) << __func__ << " pool " << poolid
	       << " now [" << p->second.start << "-" << p->second.end << ")"
	       << dendl;
    }
  }
  dout(10) << __func__ << " queue remaining: " << pending_creatings.queue.size()
	   << " pools" << dendl;
  dout(10) << __func__
	   << " " << (pending_creatings.pgs.size() - total)
	   << "/" << pending_creatings.pgs.size()
	   << " pgs added from queued pools" << dendl;
  return pending_creatings;
}

void OSDMonitor::maybe_prime_pg_temp()
{
  bool all = false;
  if (pending_inc.crush.length()) {
    dout(10) << __func__ << " new crush map, all" << dendl;
    all = true;
  }

  if (!pending_inc.new_up_client.empty()) {
    dout(10) << __func__ << " new up osds, all" << dendl;
    all = true;
  }

  // check for interesting OSDs
  set<int> osds;
  for (auto p = pending_inc.new_state.begin();
       !all && p != pending_inc.new_state.end();
       ++p) {
    if ((p->second & CEPH_OSD_UP) &&
	osdmap.is_up(p->first)) {
      osds.insert(p->first);
    }
  }
  for (map<int32_t,uint32_t>::iterator p = pending_inc.new_weight.begin();
       !all && p != pending_inc.new_weight.end();
       ++p) {
    if (p->second < osdmap.get_weight(p->first)) {
      // weight reduction
      osds.insert(p->first);
    } else {
      dout(10) << __func__ << " osd." << p->first << " weight increase, all"
	       << dendl;
      all = true;
    }
  }

  if (!all && osds.empty())
    return;

  if (!all) {
    unsigned estimate =
      mapping.get_osd_acting_pgs(*osds.begin()).size() * osds.size();
    if (estimate > mapping.get_num_pgs() *
	g_conf()->mon_osd_prime_pg_temp_max_estimate) {
      dout(10) << __func__ << " estimate " << estimate << " pgs on "
	       << osds.size() << " osds >= "
	       << g_conf()->mon_osd_prime_pg_temp_max_estimate << " of total "
	       << mapping.get_num_pgs() << " pgs, all"
	       << dendl;
      all = true;
    } else {
      dout(10) << __func__ << " estimate " << estimate << " pgs on "
	       << osds.size() << " osds" << dendl;
    }
  }

  OSDMap next;
  next.deepish_copy_from(osdmap);
  next.apply_incremental(pending_inc);

  if (next.get_pools().empty()) {
    dout(10) << __func__ << " no pools, no pg_temp priming" << dendl;
  } else if (all) {
    PrimeTempJob job(next, this);
    mapper.queue(&job, g_conf()->mon_osd_mapping_pgs_per_chunk, {});
    if (job.wait_for(g_conf()->mon_osd_prime_pg_temp_max_time)) {
      dout(10) << __func__ << " done in " << job.get_duration() << dendl;
    } else {
      dout(10) << __func__ << " did not finish in "
	       << g_conf()->mon_osd_prime_pg_temp_max_time
	       << ", stopping" << dendl;
      job.abort();
    }
  } else {
    dout(10) << __func__ << " " << osds.size() << " interesting osds" << dendl;
    utime_t stop = ceph_clock_now();
    stop += g_conf()->mon_osd_prime_pg_temp_max_time;
    const int chunk = 1000;
    int n = chunk;
    std::unordered_set<pg_t> did_pgs;
    for (auto osd : osds) {
      auto& pgs = mapping.get_osd_acting_pgs(osd);
      dout(20) << __func__ << " osd." << osd << " " << pgs << dendl;
      for (auto pgid : pgs) {
	if (!did_pgs.insert(pgid).second) {
	  continue;
	}
	prime_pg_temp(next, pgid);
	if (--n <= 0) {
	  n = chunk;
	  if (ceph_clock_now() > stop) {
	    dout(10) << __func__ << " consumed more than "
		     << g_conf()->mon_osd_prime_pg_temp_max_time
		     << " seconds, stopping"
		     << dendl;
	    return;
	  }
	}
      }
    }
  }
}

void OSDMonitor::prime_pg_temp(
  const OSDMap& next,
  pg_t pgid)
{
  // TODO: remove this creating_pgs direct access?
  if (creating_pgs.pgs.count(pgid)) {
    return;
  }
  if (!osdmap.pg_exists(pgid)) {
    return;
  }

  vector<int> up, acting;
  mapping.get(pgid, &up, nullptr, &acting, nullptr);

  vector<int> next_up, next_acting;
  int next_up_primary, next_acting_primary;
  next.pg_to_up_acting_osds(pgid, &next_up, &next_up_primary,
			    &next_acting, &next_acting_primary);
  if (acting == next_acting &&
      !(up != acting && next_up == next_acting))
    return;  // no change since last epoch

  if (acting.empty())
    return;  // if previously empty now we can be no worse off
  const pg_pool_t *pool = next.get_pg_pool(pgid.pool());
  if (pool && acting.size() < pool->min_size)
    return;  // can be no worse off than before

  if (next_up == next_acting) {
    acting.clear();
    dout(20) << __func__ << " next_up == next_acting now, clear pg_temp"
	     << dendl;
  }

  dout(20) << __func__ << " " << pgid << " " << up << "/" << acting
	   << " -> " << next_up << "/" << next_acting
	   << ", priming " << acting
	   << dendl;
  {
    std::lock_guard l(prime_pg_temp_lock);
    // do not touch a mapping if a change is pending
    pending_inc.new_pg_temp.emplace(
      pgid,
      mempool::osdmap::vector<int>(acting.begin(), acting.end()));
  }
}

/**
 * @note receiving a transaction in this function gives a fair amount of
 * freedom to the service implementation if it does need it. It shouldn't.
 */
void OSDMonitor::encode_pending(MonitorDBStore::TransactionRef t)
{
  dout(10) << "encode_pending e " << pending_inc.epoch
	   << dendl;

  if (do_prune(t)) {
    dout(1) << __func__ << " osdmap full prune encoded e"
            << pending_inc.epoch << dendl;
  }

  // finalize up pending_inc
  pending_inc.modified = ceph_clock_now();

  int r = pending_inc.propagate_snaps_to_tiers(cct, osdmap);
  ceph_assert(r == 0);

  if (mapping_job) {
    if (!mapping_job->is_done()) {
      dout(1) << __func__ << " skipping prime_pg_temp; mapping job "
	      << mapping_job.get() << " did not complete, "
	      << mapping_job->shards << " left" << dendl;
      mapping_job->abort();
    } else if (mapping.get_epoch() < osdmap.get_epoch()) {
      dout(1) << __func__ << " skipping prime_pg_temp; mapping job "
	      << mapping_job.get() << " is prior epoch "
	      << mapping.get_epoch() << dendl;
    } else {
      if (g_conf()->mon_osd_prime_pg_temp) {
	maybe_prime_pg_temp();
      }
    } 
  } else if (g_conf()->mon_osd_prime_pg_temp) {
    dout(1) << __func__ << " skipping prime_pg_temp; mapping job did not start"
	    << dendl;
  }
  mapping_job.reset();

  // ensure we don't have blank new_state updates.  these are interrpeted as
  // CEPH_OSD_UP (and almost certainly not what we want!).
  auto p = pending_inc.new_state.begin();
  while (p != pending_inc.new_state.end()) {
    if (p->second == 0) {
      dout(10) << "new_state for osd." << p->first << " is 0, removing" << dendl;
      p = pending_inc.new_state.erase(p);
    } else {
      if (p->second & CEPH_OSD_UP) {
	pending_inc.new_last_up_change = pending_inc.modified;
      }
      ++p;
    }
  }
  if (!pending_inc.new_up_client.empty()) {
    pending_inc.new_last_up_change = pending_inc.modified;
  }
  for (auto& i : pending_inc.new_weight) {
    if (i.first > osdmap.max_osd) {
      if (i.second) {
	// new osd is already marked in
	pending_inc.new_last_in_change = pending_inc.modified;
      }
    } else if (!!i.second != !!osdmap.osd_weight[i.first]) {
      // existing osd marked in or out
      pending_inc.new_last_in_change = pending_inc.modified;
    }
  }

  {
    OSDMap tmp;
    tmp.deepish_copy_from(osdmap);
    tmp.apply_incremental(pending_inc);

    // clean pg_temp mappings
    OSDMap::clean_temps(cct, osdmap, tmp, &pending_inc);

    // clean inappropriate pg_upmap/pg_upmap_items (if any)
    {
      // check every upmapped pg for now
      // until we could reliably identify certain cases to ignore,
      // which is obviously the hard part TBD..
      vector<pg_t> pgs_to_check;
      tmp.get_upmap_pgs(&pgs_to_check);
      if (pgs_to_check.size() < g_conf()->mon_clean_pg_upmaps_per_chunk * 2) {
        // not enough pgs, do it inline
        tmp.clean_pg_upmaps(cct, &pending_inc);
      } else {
        CleanUpmapJob job(cct, tmp, pending_inc);
        mapper.queue(&job, g_conf()->mon_clean_pg_upmaps_per_chunk, pgs_to_check);
        job.wait();
      }
    }

    // update creating pgs first so that we can remove the created pgid and
    // process the pool flag removal below in the same osdmap epoch.
    auto pending_creatings = update_pending_pgs(pending_inc, tmp);
    bufferlist creatings_bl;
    encode(pending_creatings, creatings_bl);
    t->put(OSD_PG_CREATING_PREFIX, "creating", creatings_bl);

    // remove any old (or incompat) POOL_CREATING flags
    for (auto& i : tmp.get_pools()) {
      if (tmp.require_osd_release < CEPH_RELEASE_NAUTILUS) {
	// pre-nautilus OSDMaps shouldn't get this flag.
	if (pending_inc.new_pools.count(i.first)) {
	  pending_inc.new_pools[i.first].flags &= ~pg_pool_t::FLAG_CREATING;
	}
      }
      if (i.second.has_flag(pg_pool_t::FLAG_CREATING) &&
	  !pending_creatings.still_creating_pool(i.first)) {
	dout(10) << __func__ << " done creating pool " << i.first
		 << ", clearing CREATING flag" << dendl;
	if (pending_inc.new_pools.count(i.first) == 0) {
	  pending_inc.new_pools[i.first] = i.second;
	}
	pending_inc.new_pools[i.first].flags &= ~pg_pool_t::FLAG_CREATING;
      }
    }

    // remove any legacy osdmap nearfull/full flags
    {
      if (tmp.test_flag(CEPH_OSDMAP_FULL | CEPH_OSDMAP_NEARFULL)) {
	dout(10) << __func__ << " clearing legacy osdmap nearfull/full flag"
		 << dendl;
	remove_flag(CEPH_OSDMAP_NEARFULL);
	remove_flag(CEPH_OSDMAP_FULL);
      }
    }
    // collect which pools are currently affected by
    // the near/backfill/full osd(s),
    // and set per-pool near/backfill/full flag instead
    set<int64_t> full_pool_ids;
    set<int64_t> backfillfull_pool_ids;
    set<int64_t> nearfull_pool_ids;
    tmp.get_full_pools(cct,
		       &full_pool_ids,
		       &backfillfull_pool_ids,
                         &nearfull_pool_ids);
    if (full_pool_ids.empty() ||
	backfillfull_pool_ids.empty() ||
	nearfull_pool_ids.empty()) {
      // normal case - no nearfull, backfillfull or full osds
        // try cancel any improper nearfull/backfillfull/full pool
        // flags first
      for (auto &pool: tmp.get_pools()) {
	auto p = pool.first;
	if (tmp.get_pg_pool(p)->has_flag(pg_pool_t::FLAG_NEARFULL) &&
	    nearfull_pool_ids.empty()) {
	  dout(10) << __func__ << " clearing pool '" << tmp.pool_name[p]
		   << "'s nearfull flag" << dendl;
	  if (pending_inc.new_pools.count(p) == 0) {
	    // load original pool info first!
	    pending_inc.new_pools[p] = pool.second;
	  }
	  pending_inc.new_pools[p].flags &= ~pg_pool_t::FLAG_NEARFULL;
	}
	if (tmp.get_pg_pool(p)->has_flag(pg_pool_t::FLAG_BACKFILLFULL) &&
	    backfillfull_pool_ids.empty()) {
	  dout(10) << __func__ << " clearing pool '" << tmp.pool_name[p]
		   << "'s backfillfull flag" << dendl;
	  if (pending_inc.new_pools.count(p) == 0) {
	    pending_inc.new_pools[p] = pool.second;
	  }
	  pending_inc.new_pools[p].flags &= ~pg_pool_t::FLAG_BACKFILLFULL;
	}
	if (tmp.get_pg_pool(p)->has_flag(pg_pool_t::FLAG_FULL) &&
	    full_pool_ids.empty()) {
	  if (tmp.get_pg_pool(p)->has_flag(pg_pool_t::FLAG_FULL_QUOTA)) {
	    // set by EQUOTA, skipping
	    continue;
	  }
	  dout(10) << __func__ << " clearing pool '" << tmp.pool_name[p]
		   << "'s full flag" << dendl;
	  if (pending_inc.new_pools.count(p) == 0) {
	    pending_inc.new_pools[p] = pool.second;
	  }
	  pending_inc.new_pools[p].flags &= ~pg_pool_t::FLAG_FULL;
	}
      }
    }
    if (!full_pool_ids.empty()) {
      dout(10) << __func__ << " marking pool(s) " << full_pool_ids
	       << " as full" << dendl;
      for (auto &p: full_pool_ids) {
	if (tmp.get_pg_pool(p)->has_flag(pg_pool_t::FLAG_FULL)) {
	  continue;
	}
	if (pending_inc.new_pools.count(p) == 0) {
	  pending_inc.new_pools[p] = tmp.pools[p];
	}
	pending_inc.new_pools[p].flags |= pg_pool_t::FLAG_FULL;
	pending_inc.new_pools[p].flags &= ~pg_pool_t::FLAG_BACKFILLFULL;
	pending_inc.new_pools[p].flags &= ~pg_pool_t::FLAG_NEARFULL;
      }
      // cancel FLAG_FULL for pools which are no longer full too
      for (auto &pool: tmp.get_pools()) {
	auto p = pool.first;
	if (full_pool_ids.count(p)) {
	  // skip pools we have just marked as full above
	  continue;
	}
	if (!tmp.get_pg_pool(p)->has_flag(pg_pool_t::FLAG_FULL) ||
	    tmp.get_pg_pool(p)->has_flag(pg_pool_t::FLAG_FULL_QUOTA)) {
	  // don't touch if currently is not full
	  // or is running out of quota (and hence considered as full)
	  continue;
	}
	dout(10) << __func__ << " clearing pool '" << tmp.pool_name[p]
		 << "'s full flag" << dendl;
	if (pending_inc.new_pools.count(p) == 0) {
	  pending_inc.new_pools[p] = pool.second;
	}
	pending_inc.new_pools[p].flags &= ~pg_pool_t::FLAG_FULL;
      }
    }
    if (!backfillfull_pool_ids.empty()) {
      for (auto &p: backfillfull_pool_ids) {
	if (full_pool_ids.count(p)) {
	  // skip pools we have already considered as full above
	  continue;
	}
	if (tmp.get_pg_pool(p)->has_flag(pg_pool_t::FLAG_FULL_QUOTA)) {
	  // make sure FLAG_FULL is truly set, so we are safe not
	  // to set a extra (redundant) FLAG_BACKFILLFULL flag
	  ceph_assert(tmp.get_pg_pool(p)->has_flag(pg_pool_t::FLAG_FULL));
	  continue;
	}
	if (tmp.get_pg_pool(p)->has_flag(pg_pool_t::FLAG_BACKFILLFULL)) {
	  // don't bother if pool is already marked as backfillfull
	  continue;
	}
	dout(10) << __func__ << " marking pool '" << tmp.pool_name[p]
		 << "'s as backfillfull" << dendl;
	if (pending_inc.new_pools.count(p) == 0) {
	  pending_inc.new_pools[p] = tmp.pools[p];
	}
	pending_inc.new_pools[p].flags |= pg_pool_t::FLAG_BACKFILLFULL;
	pending_inc.new_pools[p].flags &= ~pg_pool_t::FLAG_NEARFULL;
      }
      // cancel FLAG_BACKFILLFULL for pools
      // which are no longer backfillfull too
      for (auto &pool: tmp.get_pools()) {
	auto p = pool.first;
	if (full_pool_ids.count(p) || backfillfull_pool_ids.count(p)) {
	  // skip pools we have just marked as backfillfull/full above
	  continue;
	}
	if (!tmp.get_pg_pool(p)->has_flag(pg_pool_t::FLAG_BACKFILLFULL)) {
	  // and don't touch if currently is not backfillfull
	  continue;
	}
	dout(10) << __func__ << " clearing pool '" << tmp.pool_name[p]
		 << "'s backfillfull flag" << dendl;
	if (pending_inc.new_pools.count(p) == 0) {
	  pending_inc.new_pools[p] = pool.second;
	}
	pending_inc.new_pools[p].flags &= ~pg_pool_t::FLAG_BACKFILLFULL;
      }
    }
    if (!nearfull_pool_ids.empty()) {
      for (auto &p: nearfull_pool_ids) {
	if (full_pool_ids.count(p) || backfillfull_pool_ids.count(p)) {
	  continue;
	}
	if (tmp.get_pg_pool(p)->has_flag(pg_pool_t::FLAG_FULL_QUOTA)) {
	  // make sure FLAG_FULL is truly set, so we are safe not
	  // to set a extra (redundant) FLAG_NEARFULL flag
	  ceph_assert(tmp.get_pg_pool(p)->has_flag(pg_pool_t::FLAG_FULL));
	  continue;
	}
	if (tmp.get_pg_pool(p)->has_flag(pg_pool_t::FLAG_NEARFULL)) {
	  // don't bother if pool is already marked as nearfull
	  continue;
	}
	dout(10) << __func__ << " marking pool '" << tmp.pool_name[p]
		 << "'s as nearfull" << dendl;
	if (pending_inc.new_pools.count(p) == 0) {
	  pending_inc.new_pools[p] = tmp.pools[p];
	}
	pending_inc.new_pools[p].flags |= pg_pool_t::FLAG_NEARFULL;
      }
      // cancel FLAG_NEARFULL for pools
      // which are no longer nearfull too
      for (auto &pool: tmp.get_pools()) {
	auto p = pool.first;
	if (full_pool_ids.count(p) ||
	    backfillfull_pool_ids.count(p) ||
	    nearfull_pool_ids.count(p)) {
	  // skip pools we have just marked as
	  // nearfull/backfillfull/full above
	  continue;
	}
	if (!tmp.get_pg_pool(p)->has_flag(pg_pool_t::FLAG_NEARFULL)) {
	  // and don't touch if currently is not nearfull
	  continue;
	}
	dout(10) << __func__ << " clearing pool '" << tmp.pool_name[p]
		 << "'s nearfull flag" << dendl;
	if (pending_inc.new_pools.count(p) == 0) {
	  pending_inc.new_pools[p] = pool.second;
	}
	pending_inc.new_pools[p].flags &= ~pg_pool_t::FLAG_NEARFULL;
      }
    }

    // min_compat_client?
    if (tmp.require_min_compat_client == 0) {
      auto mv = tmp.get_min_compat_client();
      dout(1) << __func__ << " setting require_min_compat_client to currently "
	      << "required " << ceph_release_name(mv) << dendl;
      mon->clog->info() << "setting require_min_compat_client to currently "
			<< "required " << ceph_release_name(mv);
      pending_inc.new_require_min_compat_client = mv;
    }

    // upgrade to mimic?
    if (osdmap.require_osd_release < CEPH_RELEASE_MIMIC &&
	tmp.require_osd_release >= CEPH_RELEASE_MIMIC) {
      dout(10) << __func__ << " first mimic+ epoch" << dendl;
      // record this epoch as the deletion for all legacy removed_snaps
      for (auto& p : tmp.get_pools()) {
	// update every pool
	if (pending_inc.new_pools.count(p.first) == 0) {
	  pending_inc.new_pools[p.first] = p.second;
	}
	auto& pi = pending_inc.new_pools[p.first];
	if (pi.snap_seq == 0) {
	  // no snaps on this pool
	  continue;
	}
	if ((pi.flags & (pg_pool_t::FLAG_SELFMANAGED_SNAPS |
			 pg_pool_t::FLAG_POOL_SNAPS)) == 0) {
	  if (!pi.removed_snaps.empty()) {
	    pi.flags |= pg_pool_t::FLAG_SELFMANAGED_SNAPS;
	  } else {
	    pi.flags |= pg_pool_t::FLAG_POOL_SNAPS;
	  }
	}

	// Make all previously removed snaps appear to be removed in this
	// epoch.  this populates removed_snaps_queue.  The OSD will subtract
	// off its purged_snaps, as before, and this set will shrink over the
	// following epochs as the purged snaps are reported back through the
	// mgr.
	OSDMap::snap_interval_set_t removed;
	if (!p.second.removed_snaps.empty()) {
	  // different flavor of interval_set :(
	  for (auto q = p.second.removed_snaps.begin();
	       q != p.second.removed_snaps.end();
	       ++q) {
	    removed.insert(q.get_start(), q.get_len());
	  }
	} else {
	  for (snapid_t s = 1; s <= pi.get_snap_seq(); s = s + 1) {
	    if (pi.snaps.count(s) == 0) {
	      removed.insert(s);
	    }
	  }
	}
	pending_inc.new_removed_snaps[p.first].union_of(removed);

	dout(10) << __func__ << " converting pool " << p.first
		 << " with " << p.second.removed_snaps.size()
		 << " legacy removed_snaps" << dendl;
	string k = make_snap_epoch_key(p.first, pending_inc.epoch);
	bufferlist v;
	encode(p.second.removed_snaps, v);
	t->put(OSD_SNAP_PREFIX, k, v);
	for (auto q = p.second.removed_snaps.begin();
	     q != p.second.removed_snaps.end();
	     ++q) {
	  bufferlist v;
	  string k = make_snap_key_value(p.first, q.get_start(),
					 q.get_len(), pending_inc.epoch, &v);
	  t->put(OSD_SNAP_PREFIX, k, v);
	}
      }
    }
    if (osdmap.require_osd_release < CEPH_RELEASE_NAUTILUS &&
	tmp.require_osd_release >= CEPH_RELEASE_NAUTILUS) {
      dout(10) << __func__ << " first nautilus+ epoch" << dendl;
      // add creating flags?
      for (auto& i : tmp.get_pools()) {
	if (pending_creatings.still_creating_pool(i.first)) {
	  dout(10) << __func__ << " adding CREATING flag to pool " << i.first
		   << dendl;
	  if (pending_inc.new_pools.count(i.first) == 0) {
	    pending_inc.new_pools[i.first] = i.second;
	  }
	  pending_inc.new_pools[i.first].flags |= pg_pool_t::FLAG_CREATING;
	}
      }
      // adjust blacklist items to all be TYPE_ANY
      for (auto& i : tmp.blacklist) {
	auto a = i.first;
	a.set_type(entity_addr_t::TYPE_ANY);
	pending_inc.new_blacklist[a] = i.second;
	pending_inc.old_blacklist.push_back(i.first);
      }
    }
  }

  // tell me about it
  for (auto i = pending_inc.new_state.begin();
       i != pending_inc.new_state.end();
       ++i) {
    int s = i->second ? i->second : CEPH_OSD_UP;
    if (s & CEPH_OSD_UP) {
      dout(2) << " osd." << i->first << " DOWN" << dendl;
      // Reset laggy parameters if failure interval exceeds a threshold.
      const osd_xinfo_t& xi = osdmap.get_xinfo(i->first);
      if ((xi.laggy_probability || xi.laggy_interval) && xi.down_stamp.sec()) {
        int last_failure_interval = pending_inc.modified.sec() - xi.down_stamp.sec();
        if (grace_interval_threshold_exceeded(last_failure_interval)) {
          set_default_laggy_params(i->first);
        }
      }
    }
    if (s & CEPH_OSD_EXISTS)
      dout(2) << " osd." << i->first << " DNE" << dendl;
  }
  for (auto i = pending_inc.new_up_client.begin();
       i != pending_inc.new_up_client.end();
       ++i) {
    //FIXME: insert cluster addresses too
    dout(2) << " osd." << i->first << " UP " << i->second << dendl;
  }
  for (map<int32_t,uint32_t>::iterator i = pending_inc.new_weight.begin();
       i != pending_inc.new_weight.end();
       ++i) {
    if (i->second == CEPH_OSD_OUT) {
      dout(2) << " osd." << i->first << " OUT" << dendl;
    } else if (i->second == CEPH_OSD_IN) {
      dout(2) << " osd." << i->first << " IN" << dendl;
    } else {
      dout(2) << " osd." << i->first << " WEIGHT " << hex << i->second << dec << dendl;
    }
  }

  // features for osdmap and its incremental
  uint64_t features;

  // encode full map and determine its crc
  OSDMap tmp;
  {
    tmp.deepish_copy_from(osdmap);
    tmp.apply_incremental(pending_inc);

    // determine appropriate features
    features = tmp.get_encoding_features();
    dout(10) << __func__ << " encoding full map with "
	     << ceph_release_name(tmp.require_osd_release)
	     << " features " << features << dendl;

    // the features should be a subset of the mon quorum's features!
    ceph_assert((features & ~mon->get_quorum_con_features()) == 0);

    bufferlist fullbl;
    encode(tmp, fullbl, features | CEPH_FEATURE_RESERVED);
    pending_inc.full_crc = tmp.get_crc();

    // include full map in the txn.  note that old monitors will
    // overwrite this.  new ones will now skip the local full map
    // encode and reload from this.
    put_version_full(t, pending_inc.epoch, fullbl);
  }

  // encode
  ceph_assert(get_last_committed() + 1 == pending_inc.epoch);
  bufferlist bl;
  encode(pending_inc, bl, features | CEPH_FEATURE_RESERVED);

  dout(20) << " full_crc " << tmp.get_crc()
	   << " inc_crc " << pending_inc.inc_crc << dendl;

  /* put everything in the transaction */
  put_version(t, pending_inc.epoch, bl);
  put_last_committed(t, pending_inc.epoch);

  // metadata, too!
  for (map<int,bufferlist>::iterator p = pending_metadata.begin();
       p != pending_metadata.end();
       ++p)
    t->put(OSD_METADATA_PREFIX, stringify(p->first), p->second);
  for (set<int>::iterator p = pending_metadata_rm.begin();
       p != pending_metadata_rm.end();
       ++p)
    t->erase(OSD_METADATA_PREFIX, stringify(*p));
  pending_metadata.clear();
  pending_metadata_rm.clear();

  // removed_snaps
  if (tmp.require_osd_release >= CEPH_RELEASE_MIMIC) {
    for (auto& i : pending_inc.new_removed_snaps) {
      {
	// all snaps removed this epoch
	string k = make_snap_epoch_key(i.first, pending_inc.epoch);
	bufferlist v;
	encode(i.second, v);
	t->put(OSD_SNAP_PREFIX, k, v);
      }
      for (auto q = i.second.begin();
	   q != i.second.end();
	   ++q) {
	bufferlist v;
	string k = make_snap_key_value(i.first, q.get_start(),
				       q.get_len(), pending_inc.epoch, &v);
	t->put(OSD_SNAP_PREFIX, k, v);
      }
    }
    for (auto& i : pending_inc.new_purged_snaps) {
      for (auto q = i.second.begin();
	   q != i.second.end();
	   ++q) {
	bufferlist v;
	string k = make_snap_purged_key_value(i.first, q.get_start(),
					      q.get_len(), pending_inc.epoch,
					      &v);
	t->put(OSD_SNAP_PREFIX, k, v);
      }
    }
  }

  // health
  health_check_map_t next;
  tmp.check_health(cct, &next);
  encode_health(next, t);
}

int OSDMonitor::load_metadata(int osd, map<string, string>& m, ostream *err)
{
  bufferlist bl;
  int r = mon->store->get(OSD_METADATA_PREFIX, stringify(osd), bl);
  if (r < 0)
    return r;
  try {
    auto p = bl.cbegin();
    decode(m, p);
  }
  catch (buffer::error& e) {
    if (err)
      *err << "osd." << osd << " metadata is corrupt";
    return -EIO;
  }
  return 0;
}

void OSDMonitor::count_metadata(const string& field, map<string,int> *out)
{
  for (int osd = 0; osd < osdmap.get_max_osd(); ++osd) {
    if (osdmap.is_up(osd)) {
      map<string,string> meta;
      load_metadata(osd, meta, nullptr);
      auto p = meta.find(field);
      if (p == meta.end()) {
	(*out)["unknown"]++;
      } else {
	(*out)[p->second]++;
      }
    }
  }
}

void OSDMonitor::count_metadata(const string& field, Formatter *f)
{
  map<string,int> by_val;
  count_metadata(field, &by_val);
  f->open_object_section(field.c_str());
  for (auto& p : by_val) {
    f->dump_int(p.first.c_str(), p.second);
  }
  f->close_section();
}

int OSDMonitor::get_osd_objectstore_type(int osd, string *type)
{
  map<string, string> metadata;
  int r = load_metadata(osd, metadata, nullptr);
  if (r < 0)
    return r;

  auto it = metadata.find("osd_objectstore");
  if (it == metadata.end())
    return -ENOENT;
  *type = it->second;
  return 0;
}

bool OSDMonitor::is_pool_currently_all_bluestore(int64_t pool_id,
						 const pg_pool_t &pool,
						 ostream *err)
{
  // just check a few pgs for efficiency - this can't give a guarantee anyway,
  // since filestore osds could always join the pool later
  set<int> checked_osds;
  for (unsigned ps = 0; ps < std::min(8u, pool.get_pg_num()); ++ps) {
    vector<int> up, acting;
    pg_t pgid(ps, pool_id);
    osdmap.pg_to_up_acting_osds(pgid, up, acting);
    for (int osd : up) {
      if (checked_osds.find(osd) != checked_osds.end())
	continue;
      string objectstore_type;
      int r = get_osd_objectstore_type(osd, &objectstore_type);
      // allow with missing metadata, e.g. due to an osd never booting yet
      if (r < 0 || objectstore_type == "bluestore") {
	checked_osds.insert(osd);
	continue;
      }
      *err << "osd." << osd << " uses " << objectstore_type;
      return false;
    }
  }
  return true;
}

int OSDMonitor::dump_osd_metadata(int osd, Formatter *f, ostream *err)
{
  map<string,string> m;
  if (int r = load_metadata(osd, m, err))
    return r;
  for (map<string,string>::iterator p = m.begin(); p != m.end(); ++p)
    f->dump_string(p->first.c_str(), p->second);
  return 0;
}

void OSDMonitor::print_nodes(Formatter *f)
{
  // group OSDs by their hosts
  map<string, list<int> > osds; // hostname => osd
  for (int osd = 0; osd < osdmap.get_max_osd(); osd++) {
    map<string, string> m;
    if (load_metadata(osd, m, NULL)) {
      continue;
    }
    map<string, string>::iterator hostname = m.find("hostname");
    if (hostname == m.end()) {
      // not likely though
      continue;
    }
    osds[hostname->second].push_back(osd);
  }

  dump_services(f, osds, "osd");
}

void OSDMonitor::share_map_with_random_osd()
{
  if (osdmap.get_num_up_osds() == 0) {
    dout(10) << __func__ << " no up osds, don't share with anyone" << dendl;
    return;
  }

  MonSession *s = mon->session_map.get_random_osd_session(&osdmap);
  if (!s) {
    dout(10) << __func__ << " no up osd on our session map" << dendl;
    return;
  }

  dout(10) << "committed, telling random " << s->name
	   << " all about it" << dendl;

  // get feature of the peer
  // use quorum_con_features, if it's an anonymous connection.
  uint64_t features = s->con_features ? s->con_features :
                                        mon->get_quorum_con_features();
  // whatev, they'll request more if they need it
  MOSDMap *m = build_incremental(osdmap.get_epoch() - 1, osdmap.get_epoch(), features);
  s->con->send_message(m);
  // NOTE: do *not* record osd has up to this epoch (as we do
  // elsewhere) as they may still need to request older values.
}

version_t OSDMonitor::get_trim_to() const
{
  if (mon->get_quorum().empty()) {
    dout(10) << __func__ << ": quorum not formed" << dendl;
    return 0;
  }

  {
    std::lock_guard<std::mutex> l(creating_pgs_lock);
    if (!creating_pgs.pgs.empty()) {
      return 0;
    }
  }

  if (g_conf().get_val<bool>("mon_debug_block_osdmap_trim")) {
    dout(0) << __func__
            << " blocking osdmap trim"
               " ('mon_debug_block_osdmap_trim' set to 'true')"
            << dendl;
    return 0;
  }

  {
    epoch_t floor = get_min_last_epoch_clean();
    dout(10) << " min_last_epoch_clean " << floor << dendl;
    if (g_conf()->mon_osd_force_trim_to > 0 &&
	g_conf()->mon_osd_force_trim_to < (int)get_last_committed()) {
      floor = g_conf()->mon_osd_force_trim_to;
      dout(10) << " explicit mon_osd_force_trim_to = " << floor << dendl;
    }
    unsigned min = g_conf()->mon_min_osdmap_epochs;
    if (floor + min > get_last_committed()) {
      if (min < get_last_committed())
	floor = get_last_committed() - min;
      else
	floor = 0;
    }
    if (floor > get_first_committed())
      return floor;
  }
  return 0;
}

epoch_t OSDMonitor::get_min_last_epoch_clean() const
{
  auto floor = last_epoch_clean.get_lower_bound(osdmap);
  // also scan osd epochs
  // don't trim past the oldest reported osd epoch
  for (auto& osd_epoch : osd_epochs) {
    if (osd_epoch.second < floor &&
        osdmap.is_in(osd_epoch.first)) {
      floor = osd_epoch.second;
    }
  }
  return floor;
}

void OSDMonitor::encode_trim_extra(MonitorDBStore::TransactionRef tx,
				   version_t first)
{
  dout(10) << __func__ << " including full map for e " << first << dendl;
  bufferlist bl;
  get_version_full(first, bl);
  put_version_full(tx, first, bl);

  if (has_osdmap_manifest &&
      first > osdmap_manifest.get_first_pinned()) {
    _prune_update_trimmed(tx, first);
  }
}


/* full osdmap prune
 *
 * for more information, please refer to doc/dev/mon-osdmap-prune.rst
 */

void OSDMonitor::load_osdmap_manifest()
{
  bool store_has_manifest =
    mon->store->exists(get_service_name(), "osdmap_manifest");

  if (!store_has_manifest) {
    if (!has_osdmap_manifest) {
      return;
    }

    dout(20) << __func__
             << " dropping osdmap manifest from memory." << dendl;
    osdmap_manifest = osdmap_manifest_t();
    has_osdmap_manifest = false;
    return;
  }

  dout(20) << __func__
           << " osdmap manifest detected in store; reload." << dendl;

  bufferlist manifest_bl;
  int r = get_value("osdmap_manifest", manifest_bl);
  if (r < 0) {
    derr << __func__ << " unable to read osdmap version manifest" << dendl;
    ceph_abort_msg("error reading manifest");
  }
  osdmap_manifest.decode(manifest_bl);
  has_osdmap_manifest = true;

  dout(10) << __func__ << " store osdmap manifest pinned ("
           << osdmap_manifest.get_first_pinned()
           << " .. "
           << osdmap_manifest.get_last_pinned()
           << ")"
           << dendl;
}

bool OSDMonitor::should_prune() const
{
  version_t first = get_first_committed();
  version_t last = get_last_committed();
  version_t min_osdmap_epochs =
    g_conf().get_val<int64_t>("mon_min_osdmap_epochs");
  version_t prune_min =
    g_conf().get_val<uint64_t>("mon_osdmap_full_prune_min");
  version_t prune_interval =
    g_conf().get_val<uint64_t>("mon_osdmap_full_prune_interval");
  version_t last_pinned = osdmap_manifest.get_last_pinned();
  version_t last_to_pin = last - min_osdmap_epochs;

  // Make it or break it constraints.
  //
  // If any of these conditions fails, we will not prune, regardless of
  // whether we have an on-disk manifest with an on-going pruning state.
  //
  if ((last - first) <= min_osdmap_epochs) {
    // between the first and last committed epochs, we don't have
    // enough epochs to trim, much less to prune.
    dout(10) << __func__
             << " currently holding only " << (last - first)
             << " epochs (min osdmap epochs: " << min_osdmap_epochs
             << "); do not prune."
             << dendl;
    return false;

  } else if ((last_to_pin - first) < prune_min) {
    // between the first committed epoch and the last epoch we would prune,
    // we simply don't have enough versions over the minimum to prune maps.
    dout(10) << __func__
             << " could only prune " << (last_to_pin - first)
             << " epochs (" << first << ".." << last_to_pin << "), which"
                " is less than the required minimum (" << prune_min << ")"
             << dendl;
    return false;

  } else if (has_osdmap_manifest && last_pinned >= last_to_pin) {
    dout(10) << __func__
             << " we have pruned as far as we can; do not prune."
             << dendl;
    return false;

  } else if (last_pinned + prune_interval > last_to_pin) {
    dout(10) << __func__
             << " not enough epochs to form an interval (last pinned: "
             << last_pinned << ", last to pin: "
             << last_to_pin << ", interval: " << prune_interval << ")"
             << dendl;
    return false;
  }

  dout(15) << __func__
           << " should prune (" << last_pinned << ".." << last_to_pin << ")"
           << " lc (" << first << ".." << last << ")"
           << dendl;
  return true;
}

void OSDMonitor::_prune_update_trimmed(
    MonitorDBStore::TransactionRef tx,
    version_t first)
{
  dout(10) << __func__
           << " first " << first
           << " last_pinned " << osdmap_manifest.get_last_pinned()
           << " last_pinned " << osdmap_manifest.get_last_pinned()
           << dendl;

  osdmap_manifest_t manifest = osdmap_manifest;

  if (!manifest.is_pinned(first)) {
    manifest.pin(first);
  }

  set<version_t>::iterator p_end = manifest.pinned.find(first);
  set<version_t>::iterator p = manifest.pinned.begin();
  manifest.pinned.erase(p, p_end);
  ceph_assert(manifest.get_first_pinned() == first);

  if (manifest.get_last_pinned() == first+1 ||
      manifest.pinned.size() == 1) {
    // we reached the end of the line, as pinned maps go; clean up our
    // manifest, and let `should_prune()` decide whether we should prune
    // again.
    tx->erase(get_service_name(), "osdmap_manifest");
    return;
  }

  bufferlist bl;
  manifest.encode(bl);
  tx->put(get_service_name(), "osdmap_manifest", bl);
}

void OSDMonitor::prune_init(osdmap_manifest_t& manifest)
{
  dout(1) << __func__ << dendl;

  version_t pin_first;

  // verify constrainsts on stable in-memory state
  if (!has_osdmap_manifest) {
    // we must have never pruned, OR if we pruned the state must no longer
    // be relevant (i.e., the state must have been removed alongside with
    // the trim that *must* have removed past the last pinned map in a
    // previous prune).
    ceph_assert(osdmap_manifest.pinned.empty());
    ceph_assert(!mon->store->exists(get_service_name(), "osdmap_manifest"));
    pin_first = get_first_committed();

  } else {
    // we must have pruned in the past AND its state is still relevant
    // (i.e., even if we trimmed, we still hold pinned maps in the manifest,
    // and thus we still hold a manifest in the store).
    ceph_assert(!osdmap_manifest.pinned.empty());
    ceph_assert(osdmap_manifest.get_first_pinned() == get_first_committed());
    ceph_assert(osdmap_manifest.get_last_pinned() < get_last_committed());

    dout(10) << __func__
             << " first_pinned " << osdmap_manifest.get_first_pinned()
             << " last_pinned " << osdmap_manifest.get_last_pinned()
             << dendl;

    pin_first = osdmap_manifest.get_last_pinned();
  }

  manifest.pin(pin_first);
}

bool OSDMonitor::_prune_sanitize_options() const
{
  uint64_t prune_interval =
    g_conf().get_val<uint64_t>("mon_osdmap_full_prune_interval");
  uint64_t prune_min =
    g_conf().get_val<uint64_t>("mon_osdmap_full_prune_min");
  uint64_t txsize =
    g_conf().get_val<uint64_t>("mon_osdmap_full_prune_txsize");

  bool r = true;

  if (prune_interval == 0) {
    derr << __func__
         << " prune is enabled BUT prune interval is zero; abort."
         << dendl;
    r = false;
  } else if (prune_interval == 1) {
    derr << __func__
         << " prune interval is equal to one, which essentially means"
            " no pruning; abort."
         << dendl;
    r = false;
  }
  if (prune_min == 0) {
    derr << __func__
         << " prune is enabled BUT prune min is zero; abort."
         << dendl;
    r = false;
  }
  if (prune_interval > prune_min) {
    derr << __func__
         << " impossible to ascertain proper prune interval because"
         << " it is greater than the minimum prune epochs"
         << " (min: " << prune_min << ", interval: " << prune_interval << ")"
         << dendl;
    r = false;
  }

  if (txsize < prune_interval - 1) {
    derr << __func__
         << "'mon_osdmap_full_prune_txsize' (" << txsize
         << ") < 'mon_osdmap_full_prune_interval-1' (" << prune_interval - 1
         << "); abort." << dendl;
    r = false;
  }
  return r;
}

bool OSDMonitor::is_prune_enabled() const {
  return g_conf().get_val<bool>("mon_osdmap_full_prune_enabled");
}

bool OSDMonitor::is_prune_supported() const {
  return mon->get_required_mon_features().contains_any(
      ceph::features::mon::FEATURE_OSDMAP_PRUNE);
}

/** do_prune
 *
 * @returns true if has side-effects; false otherwise.
 */
bool OSDMonitor::do_prune(MonitorDBStore::TransactionRef tx)
{
  bool enabled = is_prune_enabled();

  dout(1) << __func__ << " osdmap full prune "
          << ( enabled ? "enabled" : "disabled")
          << dendl;

  if (!enabled || !_prune_sanitize_options() || !should_prune()) {
    return false;
  }

  // we are beyond the minimum prune versions, we need to remove maps because
  // otherwise the store will grow unbounded and we may end up having issues
  // with available disk space or store hangs.

  // we will not pin all versions. We will leave a buffer number of versions.
  // this allows us the monitor to trim maps without caring too much about
  // pinned maps, and then allow us to use another ceph-mon without these
  // capabilities, without having to repair the store.

  osdmap_manifest_t manifest = osdmap_manifest;

  version_t first = get_first_committed();
  version_t last = get_last_committed();

  version_t last_to_pin = last - g_conf()->mon_min_osdmap_epochs;
  version_t last_pinned = manifest.get_last_pinned();
  uint64_t prune_interval =
    g_conf().get_val<uint64_t>("mon_osdmap_full_prune_interval");
  uint64_t txsize =
    g_conf().get_val<uint64_t>("mon_osdmap_full_prune_txsize");

  prune_init(manifest);

  // we need to get rid of some osdmaps

  dout(5) << __func__
          << " lc (" << first << " .. " << last << ")"
          << " last_pinned " << last_pinned
          << " interval " << prune_interval
          << " last_to_pin " << last_to_pin
          << dendl;

  // We will be erasing maps as we go.
  //
  // We will erase all maps between `last_pinned` and the `next_to_pin`.
  //
  // If `next_to_pin` happens to be greater than `last_to_pin`, then
  // we stop pruning. We could prune the maps between `next_to_pin` and
  // `last_to_pin`, but by not doing it we end up with neater pruned
  // intervals, aligned with `prune_interval`. Besides, this should not be a
  // problem as long as `prune_interval` is set to a sane value, instead of
  // hundreds or thousands of maps.

  auto map_exists = [this](version_t v) {
    string k = mon->store->combine_strings("full", v);
    return mon->store->exists(get_service_name(), k);
  };

  // 'interval' represents the number of maps from the last pinned
  // i.e., if we pinned version 1 and have an interval of 10, we're pinning
  // version 11 next; all intermediate versions will be removed.
  //
  // 'txsize' represents the maximum number of versions we'll be removing in
  // this iteration. If 'txsize' is large enough to perform multiple passes
  // pinning and removing maps, we will do so; if not, we'll do at least one
  // pass. We are quite relaxed about honouring 'txsize', but we'll always
  // ensure that we never go *over* the maximum.

  // e.g., if we pin 1 and 11, we're removing versions [2..10]; i.e., 9 maps.
  uint64_t removal_interval = prune_interval - 1;

  if (txsize < removal_interval) {
    dout(5) << __func__
	    << " setting txsize to removal interval size ("
	    << removal_interval << " versions"
	    << dendl;
    txsize = removal_interval;
  }
  ceph_assert(removal_interval > 0);

  uint64_t num_pruned = 0;
  while (num_pruned + removal_interval <= txsize) { 
    last_pinned = manifest.get_last_pinned();

    if (last_pinned + prune_interval > last_to_pin) {
      break;
    }
    ceph_assert(last_pinned < last_to_pin);

    version_t next_pinned = last_pinned + prune_interval;
    ceph_assert(next_pinned <= last_to_pin);
    manifest.pin(next_pinned);

    dout(20) << __func__
	     << " last_pinned " << last_pinned
	     << " next_pinned " << next_pinned
	     << " num_pruned " << num_pruned
	     << " removal interval (" << (last_pinned+1)
	     << ".." << (next_pinned-1) << ")"
	     << " txsize " << txsize << dendl;

    ceph_assert(map_exists(last_pinned));
    ceph_assert(map_exists(next_pinned));

    for (version_t v = last_pinned+1; v < next_pinned; ++v) {
      ceph_assert(!manifest.is_pinned(v));

      dout(20) << __func__ << "   pruning full osdmap e" << v << dendl;
      string full_key = mon->store->combine_strings("full", v);
      tx->erase(get_service_name(), full_key);
      ++num_pruned;
    }
  }

  ceph_assert(num_pruned > 0);

  bufferlist bl;
  manifest.encode(bl);
  tx->put(get_service_name(), "osdmap_manifest", bl);

  return true;
}


// -------------

bool OSDMonitor::preprocess_query(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  Message *m = op->get_req();
  dout(10) << "preprocess_query " << *m << " from " << m->get_orig_source_inst() << dendl;

  switch (m->get_type()) {
    // READs
  case MSG_MON_COMMAND:
    try {
      return preprocess_command(op);
    } catch (const bad_cmd_get& e) {
      bufferlist bl;
      mon->reply_command(op, -EINVAL, e.what(), bl, get_last_committed());
      return true;
    }
  case CEPH_MSG_MON_GET_OSDMAP:
    return preprocess_get_osdmap(op);

    // damp updates
  case MSG_OSD_MARK_ME_DOWN:
    return preprocess_mark_me_down(op);
  case MSG_OSD_FULL:
    return preprocess_full(op);
  case MSG_OSD_FAILURE:
    return preprocess_failure(op);
  case MSG_OSD_BOOT:
    return preprocess_boot(op);
  case MSG_OSD_ALIVE:
    return preprocess_alive(op);
  case MSG_OSD_PG_CREATED:
    return preprocess_pg_created(op);
  case MSG_OSD_PG_READY_TO_MERGE:
    return preprocess_pg_ready_to_merge(op);
  case MSG_OSD_PGTEMP:
    return preprocess_pgtemp(op);
  case MSG_OSD_BEACON:
    return preprocess_beacon(op);

  case CEPH_MSG_POOLOP:
    return preprocess_pool_op(op);

  case MSG_REMOVE_SNAPS:
    return preprocess_remove_snaps(op);

  default:
    ceph_abort();
    return true;
  }
}

bool OSDMonitor::prepare_update(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  Message *m = op->get_req();
  dout(7) << "prepare_update " << *m << " from " << m->get_orig_source_inst() << dendl;

  switch (m->get_type()) {
    // damp updates
  case MSG_OSD_MARK_ME_DOWN:
    return prepare_mark_me_down(op);
  case MSG_OSD_FULL:
    return prepare_full(op);
  case MSG_OSD_FAILURE:
    return prepare_failure(op);
  case MSG_OSD_BOOT:
    return prepare_boot(op);
  case MSG_OSD_ALIVE:
    return prepare_alive(op);
  case MSG_OSD_PG_CREATED:
    return prepare_pg_created(op);
  case MSG_OSD_PGTEMP:
    return prepare_pgtemp(op);
  case MSG_OSD_PG_READY_TO_MERGE:
    return prepare_pg_ready_to_merge(op);
  case MSG_OSD_BEACON:
    return prepare_beacon(op);

  case MSG_MON_COMMAND:
    try {
      return prepare_command(op);
    } catch (const bad_cmd_get& e) {
      bufferlist bl;
      mon->reply_command(op, -EINVAL, e.what(), bl, get_last_committed());
      return true;
    }

  case CEPH_MSG_POOLOP:
    return prepare_pool_op(op);

  case MSG_REMOVE_SNAPS:
    return prepare_remove_snaps(op);


  default:
    ceph_abort();
  }

  return false;
}

bool OSDMonitor::should_propose(double& delay)
{
  dout(10) << "should_propose" << dendl;

  // if full map, propose immediately!  any subsequent changes will be clobbered.
  if (pending_inc.fullmap.length())
    return true;

  // adjust osd weights?
  if (!osd_weight.empty() &&
      osd_weight.size() == (unsigned)osdmap.get_max_osd()) {
    dout(0) << " adjusting osd weights based on " << osd_weight << dendl;
    osdmap.adjust_osd_weights(osd_weight, pending_inc);
    delay = 0.0;
    osd_weight.clear();
    return true;
  }

  return PaxosService::should_propose(delay);
}



// ---------------------------
// READs

bool OSDMonitor::preprocess_get_osdmap(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  MMonGetOSDMap *m = static_cast<MMonGetOSDMap*>(op->get_req());

  uint64_t features = mon->get_quorum_con_features();
  if (op->get_session() && op->get_session()->con_features)
    features = op->get_session()->con_features;

  dout(10) << __func__ << " " << *m << dendl;
  MOSDMap *reply = new MOSDMap(mon->monmap->fsid, features);
  epoch_t first = get_first_committed();
  epoch_t last = osdmap.get_epoch();
  int max = g_conf()->osd_map_message_max;
  ssize_t max_bytes = g_conf()->osd_map_message_max_bytes;
  for (epoch_t e = std::max(first, m->get_full_first());
       e <= std::min(last, m->get_full_last()) && max > 0 && max_bytes > 0;
       ++e, --max) {
    bufferlist& bl = reply->maps[e];
    int r = get_version_full(e, features, bl);
    ceph_assert(r >= 0);
    max_bytes -= bl.length();
  }
  for (epoch_t e = std::max(first, m->get_inc_first());
       e <= std::min(last, m->get_inc_last()) && max > 0 && max_bytes > 0;
       ++e, --max) {
    bufferlist& bl = reply->incremental_maps[e];
    int r = get_version(e, features, bl);
    ceph_assert(r >= 0);
    max_bytes -= bl.length();
  }
  reply->oldest_map = first;
  reply->newest_map = last;
  mon->send_reply(op, reply);
  return true;
}


// ---------------------------
// UPDATEs

// failure --

bool OSDMonitor::check_source(MonOpRequestRef op, uuid_d fsid) {
  // check permissions
  MonSession *session = op->get_session();
  if (!session)
    return true;
  if (!session->is_capable("osd", MON_CAP_X)) {
    dout(0) << "got MOSDFailure from entity with insufficient caps "
	    << session->caps << dendl;
    return true;
  }
  if (fsid != mon->monmap->fsid) {
    dout(0) << "check_source: on fsid " << fsid
	    << " != " << mon->monmap->fsid << dendl;
    return true;
  }
  return false;
}


bool OSDMonitor::preprocess_failure(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  MOSDFailure *m = static_cast<MOSDFailure*>(op->get_req());
  // who is target_osd
  int badboy = m->get_target_osd();

  // check permissions
  if (check_source(op, m->fsid))
    goto didit;

  // first, verify the reporting host is valid
  if (m->get_orig_source().is_osd()) {
    int from = m->get_orig_source().num();
    if (!osdmap.exists(from) ||
	!osdmap.get_addrs(from).legacy_equals(m->get_orig_source_addrs()) ||
	(osdmap.is_down(from) && m->if_osd_failed())) {
      dout(5) << "preprocess_failure from dead osd." << from
	      << ", ignoring" << dendl;
      send_incremental(op, m->get_epoch()+1);
      goto didit;
    }
  }


  // weird?
  if (osdmap.is_down(badboy)) {
    dout(5) << "preprocess_failure dne(/dup?): osd." << m->get_target_osd()
	    << " " << m->get_target_addrs()
	    << ", from " << m->get_orig_source() << dendl;
    if (m->get_epoch() < osdmap.get_epoch())
      send_incremental(op, m->get_epoch()+1);
    goto didit;
  }
  if (osdmap.get_addrs(badboy) != m->get_target_addrs()) {
    dout(5) << "preprocess_failure wrong osd: report osd." << m->get_target_osd()
	    << " " << m->get_target_addrs()
	    << " != map's " << osdmap.get_addrs(badboy)
	    << ", from " << m->get_orig_source() << dendl;
    if (m->get_epoch() < osdmap.get_epoch())
      send_incremental(op, m->get_epoch()+1);
    goto didit;
  }

  // already reported?
  if (osdmap.is_down(badboy) ||
      osdmap.get_up_from(badboy) > m->get_epoch()) {
    dout(5) << "preprocess_failure dup/old: osd." << m->get_target_osd()
	    << " " << m->get_target_addrs()
	    << ", from " << m->get_orig_source() << dendl;
    if (m->get_epoch() < osdmap.get_epoch())
      send_incremental(op, m->get_epoch()+1);
    goto didit;
  }

  if (!can_mark_down(badboy)) {
    dout(5) << "preprocess_failure ignoring report of osd."
	    << m->get_target_osd() << " " << m->get_target_addrs()
	    << " from " << m->get_orig_source() << dendl;
    goto didit;
  }

  dout(10) << "preprocess_failure new: osd." << m->get_target_osd()
	   << " " << m->get_target_addrs()
	   << ", from " << m->get_orig_source() << dendl;
  return false;

 didit:
  mon->no_reply(op);
  return true;
}

class C_AckMarkedDown : public C_MonOp {
  OSDMonitor *osdmon;
public:
  C_AckMarkedDown(
    OSDMonitor *osdmon,
    MonOpRequestRef op)
    : C_MonOp(op), osdmon(osdmon) {}

  void _finish(int r) override {
    if (r == 0) {
      MOSDMarkMeDown *m = static_cast<MOSDMarkMeDown*>(op->get_req());
      osdmon->mon->send_reply(
        op,
        new MOSDMarkMeDown(
          m->fsid,
          m->target_osd,
          m->target_addrs,
          m->get_epoch(),
          false));   // ACK itself does not request an ack
    } else if (r == -EAGAIN) {
        osdmon->dispatch(op);
    } else {
        ceph_abort_msgf("C_AckMarkedDown: unknown result %d", r);
    }
  }
  ~C_AckMarkedDown() override {
  }
};

bool OSDMonitor::preprocess_mark_me_down(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  MOSDMarkMeDown *m = static_cast<MOSDMarkMeDown*>(op->get_req());
  int from = m->target_osd;

  // check permissions
  if (check_source(op, m->fsid))
    goto reply;

  // first, verify the reporting host is valid
  if (!m->get_orig_source().is_osd())
    goto reply;

  if (!osdmap.exists(from) ||
      osdmap.is_down(from) ||
      osdmap.get_addrs(from) != m->target_addrs) {
    dout(5) << "preprocess_mark_me_down from dead osd."
	    << from << ", ignoring" << dendl;
    send_incremental(op, m->get_epoch()+1);
    goto reply;
  }

  // no down might be set
  if (!can_mark_down(from))
    goto reply;

  dout(10) << "MOSDMarkMeDown for: " << m->get_orig_source()
	   << " " << m->target_addrs << dendl;
  return false;

 reply:
  if (m->request_ack) {
    Context *c(new C_AckMarkedDown(this, op));
    c->complete(0);
  }
  return true;
}

bool OSDMonitor::prepare_mark_me_down(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  MOSDMarkMeDown *m = static_cast<MOSDMarkMeDown*>(op->get_req());
  int target_osd = m->target_osd;

  ceph_assert(osdmap.is_up(target_osd));
  ceph_assert(osdmap.get_addrs(target_osd) == m->target_addrs);

  mon->clog->info() << "osd." << target_osd << " marked itself down";
  pending_inc.new_state[target_osd] = CEPH_OSD_UP;
  if (m->request_ack)
    wait_for_finished_proposal(op, new C_AckMarkedDown(this, op));
  return true;
}

bool OSDMonitor::can_mark_down(int i)
{
  if (osdmap.is_nodown(i)) {
    dout(5) << __func__ << " osd." << i << " is marked as nodown, "
            << "will not mark it down" << dendl;
    return false;
  }

  int num_osds = osdmap.get_num_osds();
  if (num_osds == 0) {
    dout(5) << __func__ << " no osds" << dendl;
    return false;
  }
  int up = osdmap.get_num_up_osds() - pending_inc.get_net_marked_down(&osdmap);
  float up_ratio = (float)up / (float)num_osds;
  if (up_ratio < g_conf()->mon_osd_min_up_ratio) {
    dout(2) << __func__ << " current up_ratio " << up_ratio << " < min "
	    << g_conf()->mon_osd_min_up_ratio
	    << ", will not mark osd." << i << " down" << dendl;
    return false;
  }
  return true;
}

bool OSDMonitor::can_mark_up(int i)
{
  if (osdmap.is_noup(i)) {
    dout(5) << __func__ << " osd." << i << " is marked as noup, "
            << "will not mark it up" << dendl;
    return false;
  }

  return true;
}

/**
 * @note the parameter @p i apparently only exists here so we can output the
 *	 osd's id on messages.
 */
bool OSDMonitor::can_mark_out(int i)
{
  if (osdmap.is_noout(i)) {
    dout(5) << __func__ << " osd." << i << " is marked as noout, "
            << "will not mark it out" << dendl;
    return false;
  }

  int num_osds = osdmap.get_num_osds();
  if (num_osds == 0) {
    dout(5) << __func__ << " no osds" << dendl;
    return false;
  }
  int in = osdmap.get_num_in_osds() - pending_inc.get_net_marked_out(&osdmap);
  float in_ratio = (float)in / (float)num_osds;
  if (in_ratio < g_conf()->mon_osd_min_in_ratio) {
    if (i >= 0)
      dout(5) << __func__ << " current in_ratio " << in_ratio << " < min "
	      << g_conf()->mon_osd_min_in_ratio
	      << ", will not mark osd." << i << " out" << dendl;
    else
      dout(5) << __func__ << " current in_ratio " << in_ratio << " < min "
	      << g_conf()->mon_osd_min_in_ratio
	      << ", will not mark osds out" << dendl;
    return false;
  }

  return true;
}

bool OSDMonitor::can_mark_in(int i)
{
  if (osdmap.is_noin(i)) {
    dout(5) << __func__ << " osd." << i << " is marked as noin, "
            << "will not mark it in" << dendl;
    return false;
  }

  return true;
}

bool OSDMonitor::check_failures(utime_t now)
{
  bool found_failure = false;
  for (map<int,failure_info_t>::iterator p = failure_info.begin();
       p != failure_info.end();
       ++p) {
    if (can_mark_down(p->first)) {
      found_failure |= check_failure(now, p->first, p->second);
    }
  }
  return found_failure;
}

bool OSDMonitor::check_failure(utime_t now, int target_osd, failure_info_t& fi)
{
  // already pending failure?
  if (pending_inc.new_state.count(target_osd) &&
      pending_inc.new_state[target_osd] & CEPH_OSD_UP) {
    dout(10) << " already pending failure" << dendl;
    return true;
  }

  set<string> reporters_by_subtree;
  auto reporter_subtree_level = g_conf().get_val<string>("mon_osd_reporter_subtree_level");
  utime_t orig_grace(g_conf()->osd_heartbeat_grace, 0);
  utime_t max_failed_since = fi.get_failed_since();
  utime_t failed_for = now - max_failed_since;

  utime_t grace = orig_grace;
  double my_grace = 0, peer_grace = 0;
  double decay_k = 0;
  if (g_conf()->mon_osd_adjust_heartbeat_grace) {
    double halflife = (double)g_conf()->mon_osd_laggy_halflife;
    decay_k = ::log(.5) / halflife;

    // scale grace period based on historical probability of 'lagginess'
    // (false positive failures due to slowness).
    const osd_xinfo_t& xi = osdmap.get_xinfo(target_osd);
    double decay = exp((double)failed_for * decay_k);
    dout(20) << " halflife " << halflife << " decay_k " << decay_k
	     << " failed_for " << failed_for << " decay " << decay << dendl;
    my_grace = decay * (double)xi.laggy_interval * xi.laggy_probability;
    grace += my_grace;
  }

  // consider the peers reporting a failure a proxy for a potential
  // 'subcluster' over the overall cluster that is similarly
  // laggy.  this is clearly not true in all cases, but will sometimes
  // help us localize the grace correction to a subset of the system
  // (say, a rack with a bad switch) that is unhappy.
  ceph_assert(fi.reporters.size());
  for (auto p = fi.reporters.begin(); p != fi.reporters.end();) {
    // get the parent bucket whose type matches with "reporter_subtree_level".
    // fall back to OSD if the level doesn't exist.
    if (osdmap.exists(p->first)) {
      auto reporter_loc = osdmap.crush->get_full_location(p->first);
      if (auto iter = reporter_loc.find(reporter_subtree_level);
          iter == reporter_loc.end()) {
        reporters_by_subtree.insert("osd." + to_string(p->first));
      } else {
        reporters_by_subtree.insert(iter->second);
      }
      if (g_conf()->mon_osd_adjust_heartbeat_grace) {
        const osd_xinfo_t& xi = osdmap.get_xinfo(p->first);
        utime_t elapsed = now - xi.down_stamp;
        double decay = exp((double)elapsed * decay_k);
        peer_grace += decay * (double)xi.laggy_interval * xi.laggy_probability;
      }
      ++p;
    } else {
      fi.cancel_report(p->first);;
      p = fi.reporters.erase(p);
    }
  }
  
  if (g_conf()->mon_osd_adjust_heartbeat_grace) {
    peer_grace /= (double)fi.reporters.size();
    grace += peer_grace;
  }

  dout(10) << " osd." << target_osd << " has "
	   << fi.reporters.size() << " reporters, "
	   << grace << " grace (" << orig_grace << " + " << my_grace
	   << " + " << peer_grace << "), max_failed_since " << max_failed_since
	   << dendl;

  if (failed_for >= grace &&
      reporters_by_subtree.size() >= g_conf().get_val<uint64_t>("mon_osd_min_down_reporters")) {
    dout(1) << " we have enough reporters to mark osd." << target_osd
	    << " down" << dendl;
    pending_inc.new_state[target_osd] = CEPH_OSD_UP;

    mon->clog->info() << "osd." << target_osd << " failed ("
		      << osdmap.crush->get_full_location_ordered_string(
			target_osd)
		      << ") ("
		      << (int)reporters_by_subtree.size()
		      << " reporters from different "
		      << reporter_subtree_level << " after "
		      << failed_for << " >= grace " << grace << ")";
    return true;
  }
  return false;
}

void OSDMonitor::force_failure(int target_osd, int by)
{
  // already pending failure?
  if (pending_inc.new_state.count(target_osd) &&
      pending_inc.new_state[target_osd] & CEPH_OSD_UP) {
    dout(10) << " already pending failure" << dendl;
    return;
  }

  dout(1) << " we're forcing failure of osd." << target_osd << dendl;
  pending_inc.new_state[target_osd] = CEPH_OSD_UP;

  mon->clog->info() << "osd." << target_osd << " failed ("
		    << osdmap.crush->get_full_location_ordered_string(target_osd)
		    << ") (connection refused reported by osd." << by << ")";
  return;
}

bool OSDMonitor::prepare_failure(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  MOSDFailure *m = static_cast<MOSDFailure*>(op->get_req());
  dout(1) << "prepare_failure osd." << m->get_target_osd()
	  << " " << m->get_target_addrs()
	  << " from " << m->get_orig_source()
          << " is reporting failure:" << m->if_osd_failed() << dendl;

  int target_osd = m->get_target_osd();
  int reporter = m->get_orig_source().num();
  ceph_assert(osdmap.is_up(target_osd));
  ceph_assert(osdmap.get_addrs(target_osd) == m->get_target_addrs());

  mon->no_reply(op);

  if (m->if_osd_failed()) {
    // calculate failure time
    utime_t now = ceph_clock_now();
    utime_t failed_since =
      m->get_recv_stamp() - utime_t(m->failed_for, 0);

    // add a report
    if (m->is_immediate()) {
      mon->clog->debug() << "osd." << m->get_target_osd()
			 << " reported immediately failed by "
			 << m->get_orig_source();
      force_failure(target_osd, reporter);
      return true;
    }
    mon->clog->debug() << "osd." << m->get_target_osd() << " reported failed by "
		      << m->get_orig_source();

    failure_info_t& fi = failure_info[target_osd];
    MonOpRequestRef old_op = fi.add_report(reporter, failed_since, op);
    if (old_op) {
      mon->no_reply(old_op);
    }

    return check_failure(now, target_osd, fi);
  } else {
    // remove the report
    mon->clog->debug() << "osd." << m->get_target_osd()
		       << " failure report canceled by "
		       << m->get_orig_source();
    if (failure_info.count(target_osd)) {
      failure_info_t& fi = failure_info[target_osd];
      MonOpRequestRef report_op = fi.cancel_report(reporter);
      if (report_op) {
        mon->no_reply(report_op);
      }
      if (fi.reporters.empty()) {
	dout(10) << " removing last failure_info for osd." << target_osd
		 << dendl;
	failure_info.erase(target_osd);
      } else {
	dout(10) << " failure_info for osd." << target_osd << " now "
		 << fi.reporters.size() << " reporters" << dendl;
      }
    } else {
      dout(10) << " no failure_info for osd." << target_osd << dendl;
    }
  }

  return false;
}

void OSDMonitor::process_failures()
{
  map<int,failure_info_t>::iterator p = failure_info.begin();
  while (p != failure_info.end()) {
    if (osdmap.is_up(p->first)) {
      ++p;
    } else {
      dout(10) << "process_failures osd." << p->first << dendl;
      list<MonOpRequestRef> ls;
      p->second.take_report_messages(ls);
      failure_info.erase(p++);

      while (!ls.empty()) {
        MonOpRequestRef o = ls.front();
        if (o) {
          o->mark_event(__func__);
          MOSDFailure *m = o->get_req<MOSDFailure>();
          send_latest(o, m->get_epoch());
	  mon->no_reply(o);
        }
	ls.pop_front();
      }
    }
  }
}

void OSDMonitor::take_all_failures(list<MonOpRequestRef>& ls)
{
  dout(10) << __func__ << " on " << failure_info.size() << " osds" << dendl;

  for (map<int,failure_info_t>::iterator p = failure_info.begin();
       p != failure_info.end();
       ++p) {
    p->second.take_report_messages(ls);
  }
  failure_info.clear();
}

int OSDMonitor::get_grace_interval_threshold()
{
  int halflife = g_conf()->mon_osd_laggy_halflife;
  // Scale the halflife period (default: 1_hr) by
  // a factor (48) to calculate the threshold.
  int grace_threshold_factor = 48;
  return halflife * grace_threshold_factor;
}

bool OSDMonitor::grace_interval_threshold_exceeded(int last_failed_interval)
{
  int grace_interval_threshold_secs = get_grace_interval_threshold();
  if (last_failed_interval > grace_interval_threshold_secs) {
    dout(1) << " last_failed_interval " << last_failed_interval
            << " > grace_interval_threshold_secs " << grace_interval_threshold_secs
            << dendl;
    return true;
  }
  return false;
}

void OSDMonitor::set_default_laggy_params(int target_osd)
{
  if (pending_inc.new_xinfo.count(target_osd) == 0) {
    pending_inc.new_xinfo[target_osd] = osdmap.osd_xinfo[target_osd];
  }
  osd_xinfo_t& xi = pending_inc.new_xinfo[target_osd];
  xi.down_stamp = pending_inc.modified;
  xi.laggy_probability = 0.0;
  xi.laggy_interval = 0;
  dout(20) << __func__ << " reset laggy, now xi " << xi << dendl;
}


// boot --

bool OSDMonitor::preprocess_boot(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  MOSDBoot *m = static_cast<MOSDBoot*>(op->get_req());
  int from = m->get_orig_source_inst().name.num();

  // check permissions, ignore if failed (no response expected)
  MonSession *session = op->get_session();
  if (!session)
    goto ignore;
  if (!session->is_capable("osd", MON_CAP_X)) {
    dout(0) << "got preprocess_boot message from entity with insufficient caps"
	    << session->caps << dendl;
    goto ignore;
  }

  if (m->sb.cluster_fsid != mon->monmap->fsid) {
    dout(0) << "preprocess_boot on fsid " << m->sb.cluster_fsid
	    << " != " << mon->monmap->fsid << dendl;
    goto ignore;
  }

  if (m->get_orig_source_inst().addr.is_blank_ip()) {
    dout(0) << "preprocess_boot got blank addr for " << m->get_orig_source_inst() << dendl;
    goto ignore;
  }

  ceph_assert(m->get_orig_source_inst().name.is_osd());

  // force all osds to have gone through luminous prior to upgrade to nautilus
  {
    vector<string> missing;
    if (!HAVE_FEATURE(m->osd_features, SERVER_LUMINOUS)) {
      missing.push_back("CEPH_FEATURE_SERVER_LUMINOUS");
    }
    if (!HAVE_FEATURE(m->osd_features, SERVER_JEWEL)) {
      missing.push_back("CEPH_FEATURE_SERVER_JEWEL");
    }
    if (!HAVE_FEATURE(m->osd_features, SERVER_KRAKEN)) {
      missing.push_back("CEPH_FEATURE_SERVER_KRAKEN");
    }
    if (!HAVE_FEATURE(m->osd_features, OSD_RECOVERY_DELETES)) {
      missing.push_back("CEPH_FEATURE_OSD_RECOVERY_DELETES");
    }

    if (!missing.empty()) {
      using std::experimental::make_ostream_joiner;

      stringstream ss;
      copy(begin(missing), end(missing), make_ostream_joiner(ss, ";"));

      mon->clog->info() << "disallowing boot of OSD "
			<< m->get_orig_source_inst()
			<< " because the osd lacks " << ss.str();
      goto ignore;
    }
  }

  // make sure upgrades stop at nautilus
  if (HAVE_FEATURE(m->osd_features, SERVER_O) &&
      osdmap.require_osd_release < CEPH_RELEASE_NAUTILUS) {
    mon->clog->info() << "disallowing boot of post-nautilus OSD "
		      << m->get_orig_source_inst()
		      << " because require_osd_release < nautilus";
    goto ignore;
  }

  // The release check here is required because for OSD_PGLOG_HARDLIMIT,
  // we are reusing a jewel feature bit that was retired in luminous.
  if (osdmap.require_osd_release >= CEPH_RELEASE_LUMINOUS &&
      osdmap.test_flag(CEPH_OSDMAP_PGLOG_HARDLIMIT) &&
      !(m->osd_features & CEPH_FEATURE_OSD_PGLOG_HARDLIMIT)) {
    mon->clog->info() << "disallowing boot of OSD "
		      << m->get_orig_source_inst()
		      << " because 'pglog_hardlimit' osdmap flag is set and OSD lacks the OSD_PGLOG_HARDLIMIT feature";
    goto ignore;
  }

  // already booted?
  if (osdmap.is_up(from) &&
      osdmap.get_addrs(from).legacy_equals(m->get_orig_source_addrs()) &&
      osdmap.get_cluster_addrs(from).legacy_equals(m->cluster_addrs)) {
    // yup.
    dout(7) << "preprocess_boot dup from " << m->get_orig_source()
	    << " " << m->get_orig_source_addrs()
	    << " =~ " << osdmap.get_addrs(from) << dendl;
    _booted(op, false);
    return true;
  }

  if (osdmap.exists(from) &&
      !osdmap.get_uuid(from).is_zero() &&
      osdmap.get_uuid(from) != m->sb.osd_fsid) {
    dout(7) << __func__ << " from " << m->get_orig_source_inst()
            << " clashes with existing osd: different fsid"
            << " (ours: " << osdmap.get_uuid(from)
            << " ; theirs: " << m->sb.osd_fsid << ")" << dendl;
    goto ignore;
  }

  if (osdmap.exists(from) &&
      osdmap.get_info(from).up_from > m->version &&
      osdmap.get_most_recent_addrs(from).legacy_equals(
	m->get_orig_source_addrs())) {
    dout(7) << "prepare_boot msg from before last up_from, ignoring" << dendl;
    send_latest(op, m->sb.current_epoch+1);
    return true;
  }

  // noup?
  if (!can_mark_up(from)) {
    dout(7) << "preprocess_boot ignoring boot from " << m->get_orig_source_inst() << dendl;
    send_latest(op, m->sb.current_epoch+1);
    return true;
  }

  dout(10) << "preprocess_boot from " << m->get_orig_source_inst() << dendl;
  return false;

 ignore:
  return true;
}

bool OSDMonitor::prepare_boot(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  MOSDBoot *m = static_cast<MOSDBoot*>(op->get_req());
  dout(7) << __func__ << " from " << m->get_source()
	  << " sb " << m->sb
	  << " client_addrs" << m->get_connection()->get_peer_addrs()
	  << " cluster_addrs " << m->cluster_addrs
	  << " hb_back_addrs " << m->hb_back_addrs
	  << " hb_front_addrs " << m->hb_front_addrs
	  << dendl;

  ceph_assert(m->get_orig_source().is_osd());
  int from = m->get_orig_source().num();

  // does this osd exist?
  if (from >= osdmap.get_max_osd()) {
    dout(1) << "boot from osd." << from << " >= max_osd "
	    << osdmap.get_max_osd() << dendl;
    return false;
  }

  int oldstate = osdmap.exists(from) ? osdmap.get_state(from) : CEPH_OSD_NEW;
  if (pending_inc.new_state.count(from))
    oldstate ^= pending_inc.new_state[from];

  // already up?  mark down first?
  if (osdmap.is_up(from)) {
    dout(7) << __func__ << " was up, first marking down osd." << from << " "
	    << osdmap.get_addrs(from) << dendl;
    // preprocess should have caught these;  if not, assert.
    ceph_assert(!osdmap.get_addrs(from).legacy_equals(
		  m->get_orig_source_addrs()) ||
		!osdmap.get_cluster_addrs(from).legacy_equals(m->cluster_addrs));
    ceph_assert(osdmap.get_uuid(from) == m->sb.osd_fsid);

    if (pending_inc.new_state.count(from) == 0 ||
	(pending_inc.new_state[from] & CEPH_OSD_UP) == 0) {
      // mark previous guy down
      pending_inc.new_state[from] = CEPH_OSD_UP;
    }
    wait_for_finished_proposal(op, new C_RetryMessage(this, op));
  } else if (pending_inc.new_up_client.count(from)) {
    // already prepared, just wait
    dout(7) << __func__ << " already prepared, waiting on "
	    << m->get_orig_source_addr() << dendl;
    wait_for_finished_proposal(op, new C_RetryMessage(this, op));
  } else {
    // mark new guy up.
    pending_inc.new_up_client[from] = m->get_orig_source_addrs();
    pending_inc.new_up_cluster[from] = m->cluster_addrs;
    pending_inc.new_hb_back_up[from] = m->hb_back_addrs;
    pending_inc.new_hb_front_up[from] = m->hb_front_addrs;

    down_pending_out.erase(from);  // if any

    if (m->sb.weight)
      osd_weight[from] = m->sb.weight;

    // set uuid?
    dout(10) << " setting osd." << from << " uuid to " << m->sb.osd_fsid
	     << dendl;
    if (!osdmap.exists(from) || osdmap.get_uuid(from) != m->sb.osd_fsid) {
      // preprocess should have caught this;  if not, assert.
      ceph_assert(!osdmap.exists(from) || osdmap.get_uuid(from).is_zero());
      pending_inc.new_uuid[from] = m->sb.osd_fsid;
    }

    // fresh osd?
    if (m->sb.newest_map == 0 && osdmap.exists(from)) {
      const osd_info_t& i = osdmap.get_info(from);
      if (i.up_from > i.lost_at) {
	dout(10) << " fresh osd; marking lost_at too" << dendl;
	pending_inc.new_lost[from] = osdmap.get_epoch();
      }
    }

    // metadata
    bufferlist osd_metadata;
    encode(m->metadata, osd_metadata);
    pending_metadata[from] = osd_metadata;
    pending_metadata_rm.erase(from);

    // adjust last clean unmount epoch?
    const osd_info_t& info = osdmap.get_info(from);
    dout(10) << " old osd_info: " << info << dendl;
    if (m->sb.mounted > info.last_clean_begin ||
	(m->sb.mounted == info.last_clean_begin &&
	 m->sb.clean_thru > info.last_clean_end)) {
      epoch_t begin = m->sb.mounted;
      epoch_t end = m->sb.clean_thru;

      dout(10) << __func__ << " osd." << from << " last_clean_interval "
	       << "[" << info.last_clean_begin << "," << info.last_clean_end
	       << ") -> [" << begin << "-" << end << ")"
	       << dendl;
      pending_inc.new_last_clean_interval[from] =
	pair<epoch_t,epoch_t>(begin, end);
    }

    osd_xinfo_t xi = osdmap.get_xinfo(from);
    if (m->boot_epoch == 0) {
      xi.laggy_probability *= (1.0 - g_conf()->mon_osd_laggy_weight);
      xi.laggy_interval *= (1.0 - g_conf()->mon_osd_laggy_weight);
      dout(10) << " not laggy, new xi " << xi << dendl;
    } else {
      if (xi.down_stamp.sec()) {
        int interval = ceph_clock_now().sec() -
	  xi.down_stamp.sec();
        if (g_conf()->mon_osd_laggy_max_interval &&
	    (interval > g_conf()->mon_osd_laggy_max_interval)) {
          interval =  g_conf()->mon_osd_laggy_max_interval;
        }
        xi.laggy_interval =
	  interval * g_conf()->mon_osd_laggy_weight +
	  xi.laggy_interval * (1.0 - g_conf()->mon_osd_laggy_weight);
      }
      xi.laggy_probability =
	g_conf()->mon_osd_laggy_weight +
	xi.laggy_probability * (1.0 - g_conf()->mon_osd_laggy_weight);
      dout(10) << " laggy, now xi " << xi << dendl;
    }

    // set features shared by the osd
    if (m->osd_features)
      xi.features = m->osd_features;
    else
      xi.features = m->get_connection()->get_features();

    // mark in?
    if ((g_conf()->mon_osd_auto_mark_auto_out_in &&
	 (oldstate & CEPH_OSD_AUTOOUT)) ||
	(g_conf()->mon_osd_auto_mark_new_in && (oldstate & CEPH_OSD_NEW)) ||
	(g_conf()->mon_osd_auto_mark_in)) {
      if (can_mark_in(from)) {
	if (osdmap.osd_xinfo[from].old_weight > 0) {
	  pending_inc.new_weight[from] = osdmap.osd_xinfo[from].old_weight;
	  xi.old_weight = 0;
	} else {
	  pending_inc.new_weight[from] = CEPH_OSD_IN;
	}
      } else {
	dout(7) << __func__ << " NOIN set, will not mark in "
		<< m->get_orig_source_addr() << dendl;
      }
    }

    pending_inc.new_xinfo[from] = xi;

    // wait
    wait_for_finished_proposal(op, new C_Booted(this, op));
  }
  return true;
}

void OSDMonitor::_booted(MonOpRequestRef op, bool logit)
{
  op->mark_osdmon_event(__func__);
  MOSDBoot *m = static_cast<MOSDBoot*>(op->get_req());
  dout(7) << "_booted " << m->get_orig_source_inst() 
	  << " w " << m->sb.weight << " from " << m->sb.current_epoch << dendl;

  if (logit) {
    mon->clog->info() << m->get_source() << " " << m->get_orig_source_addrs()
		      << " boot";
  }

  send_latest(op, m->sb.current_epoch+1);
}


// -------------
// full

bool OSDMonitor::preprocess_full(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  MOSDFull *m = static_cast<MOSDFull*>(op->get_req());
  int from = m->get_orig_source().num();
  set<string> state;
  unsigned mask = CEPH_OSD_NEARFULL | CEPH_OSD_BACKFILLFULL | CEPH_OSD_FULL;

  // check permissions, ignore if failed
  MonSession *session = op->get_session();
  if (!session)
    goto ignore;
  if (!session->is_capable("osd", MON_CAP_X)) {
    dout(0) << "MOSDFull from entity with insufficient privileges:"
	    << session->caps << dendl;
    goto ignore;
  }

  // ignore a full message from the osd instance that already went down
  if (!osdmap.exists(from)) {
    dout(7) << __func__ << " ignoring full message from nonexistent "
	    << m->get_orig_source_inst() << dendl;
    goto ignore;
  }
  if ((!osdmap.is_up(from) &&
       osdmap.get_most_recent_addrs(from).legacy_equals(
	 m->get_orig_source_addrs())) ||
      (osdmap.is_up(from) &&
       !osdmap.get_addrs(from).legacy_equals(m->get_orig_source_addrs()))) {
    dout(7) << __func__ << " ignoring full message from down "
	    << m->get_orig_source_inst() << dendl;
    goto ignore;
  }

  OSDMap::calc_state_set(osdmap.get_state(from), state);

  if ((osdmap.get_state(from) & mask) == m->state) {
    dout(7) << __func__ << " state already " << state << " for osd." << from
	    << " " << m->get_orig_source_inst() << dendl;
    _reply_map(op, m->version);
    goto ignore;
  }

  dout(10) << __func__ << " want state " << state << " for osd." << from
	   << " " << m->get_orig_source_inst() << dendl;
  return false;

 ignore:
  return true;
}

bool OSDMonitor::prepare_full(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  const MOSDFull *m = static_cast<MOSDFull*>(op->get_req());
  const int from = m->get_orig_source().num();

  const unsigned mask = CEPH_OSD_NEARFULL | CEPH_OSD_BACKFILLFULL | CEPH_OSD_FULL;
  const unsigned want_state = m->state & mask;  // safety first

  unsigned cur_state = osdmap.get_state(from);
  auto p = pending_inc.new_state.find(from);
  if (p != pending_inc.new_state.end()) {
    cur_state ^= p->second;
  }
  cur_state &= mask;

  set<string> want_state_set, cur_state_set;
  OSDMap::calc_state_set(want_state, want_state_set);
  OSDMap::calc_state_set(cur_state, cur_state_set);

  if (cur_state != want_state) {
    if (p != pending_inc.new_state.end()) {
      p->second &= ~mask;
    } else {
      pending_inc.new_state[from] = 0;
    }
    pending_inc.new_state[from] |= (osdmap.get_state(from) & mask) ^ want_state;
    dout(7) << __func__ << " osd." << from << " " << cur_state_set
	    << " -> " << want_state_set << dendl;
  } else {
    dout(7) << __func__ << " osd." << from << " " << cur_state_set
	    << " = wanted " << want_state_set << ", just waiting" << dendl;
  }

  wait_for_finished_proposal(op, new C_ReplyMap(this, op, m->version));
  return true;
}

// -------------
// alive

bool OSDMonitor::preprocess_alive(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  MOSDAlive *m = static_cast<MOSDAlive*>(op->get_req());
  int from = m->get_orig_source().num();

  // check permissions, ignore if failed
  MonSession *session = op->get_session();
  if (!session)
    goto ignore;
  if (!session->is_capable("osd", MON_CAP_X)) {
    dout(0) << "attempt to send MOSDAlive from entity with insufficient privileges:"
	    << session->caps << dendl;
    goto ignore;
  }

  if (!osdmap.is_up(from) ||
      !osdmap.get_addrs(from).legacy_equals(m->get_orig_source_addrs())) {
    dout(7) << "preprocess_alive ignoring alive message from down "
	    << m->get_orig_source() << " " << m->get_orig_source_addrs()
	    << dendl;
    goto ignore;
  }

  if (osdmap.get_up_thru(from) >= m->want) {
    // yup.
    dout(7) << "preprocess_alive want up_thru " << m->want << " dup from " << m->get_orig_source_inst() << dendl;
    _reply_map(op, m->version);
    return true;
  }

  dout(10) << "preprocess_alive want up_thru " << m->want
	   << " from " << m->get_orig_source_inst() << dendl;
  return false;

 ignore:
  return true;
}

bool OSDMonitor::prepare_alive(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  MOSDAlive *m = static_cast<MOSDAlive*>(op->get_req());
  int from = m->get_orig_source().num();

  if (0) {  // we probably don't care much about these
    mon->clog->debug() << m->get_orig_source_inst() << " alive";
  }

  dout(7) << "prepare_alive want up_thru " << m->want << " have " << m->version
	  << " from " << m->get_orig_source_inst() << dendl;

  update_up_thru(from, m->version); // set to the latest map the OSD has
  wait_for_finished_proposal(op, new C_ReplyMap(this, op, m->version));
  return true;
}

void OSDMonitor::_reply_map(MonOpRequestRef op, epoch_t e)
{
  op->mark_osdmon_event(__func__);
  dout(7) << "_reply_map " << e
	  << " from " << op->get_req()->get_orig_source_inst()
	  << dendl;
  send_latest(op, e);
}

// pg_created
bool OSDMonitor::preprocess_pg_created(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  auto m = static_cast<MOSDPGCreated*>(op->get_req());
  dout(10) << __func__ << " " << *m << dendl;
  auto session = op->get_session();
  mon->no_reply(op);
  if (!session) {
    dout(10) << __func__ << ": no monitor session!" << dendl;
    return true;
  }
  if (!session->is_capable("osd", MON_CAP_X)) {
    derr << __func__ << " received from entity "
         << "with insufficient privileges " << session->caps << dendl;
    return true;
  }
  // always forward the "created!" to the leader
  return false;
}

bool OSDMonitor::prepare_pg_created(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  auto m = static_cast<MOSDPGCreated*>(op->get_req());
  dout(10) << __func__ << " " << *m << dendl;
  auto src = m->get_orig_source();
  auto from = src.num();
  if (!src.is_osd() ||
      !mon->osdmon()->osdmap.is_up(from) ||
      !mon->osdmon()->osdmap.get_addrs(from).legacy_equals(
	m->get_orig_source_addrs())) {
    dout(1) << __func__ << " ignoring stats from non-active osd." << dendl;
    return false;
  }
  pending_created_pgs.push_back(m->pgid);
  return true;
}

bool OSDMonitor::preprocess_pg_ready_to_merge(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  auto m = static_cast<MOSDPGReadyToMerge*>(op->get_req());
  dout(10) << __func__ << " " << *m << dendl;
  const pg_pool_t *pi;
  auto session = op->get_session();
  if (!session) {
    dout(10) << __func__ << ": no monitor session!" << dendl;
    goto ignore;
  }
  if (!session->is_capable("osd", MON_CAP_X)) {
    derr << __func__ << " received from entity "
         << "with insufficient privileges " << session->caps << dendl;
    goto ignore;
  }
  pi = osdmap.get_pg_pool(m->pgid.pool());
  if (!pi) {
    derr << __func__ << " pool for " << m->pgid << " dne" << dendl;
    goto ignore;
  }
  if (pi->get_pg_num() <= m->pgid.ps()) {
    dout(20) << " pg_num " << pi->get_pg_num() << " already < " << m->pgid << dendl;
    goto ignore;
  }
  if (pi->get_pg_num() != m->pgid.ps() + 1) {
    derr << " OSD trying to merge wrong pgid " << m->pgid << dendl;
    goto ignore;
  }
  if (pi->get_pg_num_pending() > m->pgid.ps()) {
    dout(20) << " pg_num_pending " << pi->get_pg_num_pending() << " > " << m->pgid << dendl;
    goto ignore;
  }
  return false;

 ignore:
  mon->no_reply(op);
  return true;
}

bool OSDMonitor::prepare_pg_ready_to_merge(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  auto m = static_cast<MOSDPGReadyToMerge*>(op->get_req());
  dout(10) << __func__ << " " << *m << dendl;
  pg_pool_t p;
  if (pending_inc.new_pools.count(m->pgid.pool()))
    p = pending_inc.new_pools[m->pgid.pool()];
  else
    p = *osdmap.get_pg_pool(m->pgid.pool());
  if (p.get_pg_num() != m->pgid.ps() + 1 ||
      p.get_pg_num_pending() > m->pgid.ps()) {
    dout(10) << __func__
	     << " race with concurrent pg_num[_pending] update, will retry"
	     << dendl;
    wait_for_finished_proposal(op, new C_RetryMessage(this, op));
    return true;
  }

  if (m->ready) {
    p.dec_pg_num(m->pgid,
		 pending_inc.epoch,
		 m->source_version,
		 m->target_version,
		 m->last_epoch_started,
		 m->last_epoch_clean);
    p.last_change = pending_inc.epoch;
  } else {
    // back off the merge attempt!
    p.set_pg_num_pending(p.get_pg_num());
  }

  // force pre-nautilus clients to resend their ops, since they
  // don't understand pg_num_pending changes form a new interval
  p.last_force_op_resend_prenautilus = pending_inc.epoch;

  pending_inc.new_pools[m->pgid.pool()] = p;

  auto prob = g_conf().get_val<double>("mon_inject_pg_merge_bounce_probability");
  if (m->ready &&
      prob > 0 &&
      prob > (double)(rand() % 1000)/1000.0) {
    derr << __func__ << " injecting pg merge pg_num bounce" << dendl;
    auto n = new MMonCommand(mon->monmap->get_fsid());
    n->set_connection(m->get_connection());
    n->cmd = { "{\"prefix\":\"osd pool set\", \"pool\": \"" +
	       osdmap.get_pool_name(m->pgid.pool()) +
	       "\", \"var\": \"pg_num_actual\", \"val\": \"" +
	       stringify(m->pgid.ps() + 1) + "\"}" };
    MonOpRequestRef nop = mon->op_tracker.create_request<MonOpRequest>(n);
    nop->set_type_service();
    wait_for_finished_proposal(op, new C_RetryMessage(this, nop));
  } else {
    wait_for_finished_proposal(op, new C_ReplyMap(this, op, m->version));
  }
  return true;
}


// -------------
// pg_temp changes

bool OSDMonitor::preprocess_pgtemp(MonOpRequestRef op)
{
  MOSDPGTemp *m = static_cast<MOSDPGTemp*>(op->get_req());
  dout(10) << "preprocess_pgtemp " << *m << dendl;
  mempool::osdmap::vector<int> empty;
  int from = m->get_orig_source().num();
  size_t ignore_cnt = 0;

  // check caps
  MonSession *session = op->get_session();
  if (!session)
    goto ignore;
  if (!session->is_capable("osd", MON_CAP_X)) {
    dout(0) << "attempt to send MOSDPGTemp from entity with insufficient caps "
	    << session->caps << dendl;
    goto ignore;
  }

  if (!osdmap.is_up(from) ||
      !osdmap.get_addrs(from).legacy_equals(m->get_orig_source_addrs())) {
    dout(7) << "ignoring pgtemp message from down "
	    << m->get_orig_source() << " " << m->get_orig_source_addrs()
	    << dendl;
    goto ignore;
  }

  if (m->forced) {
    return false;
  }

  for (auto p = m->pg_temp.begin(); p != m->pg_temp.end(); ++p) {
    dout(20) << " " << p->first
	     << (osdmap.pg_temp->count(p->first) ? osdmap.pg_temp->get(p->first) : empty)
             << " -> " << p->second << dendl;

    // does the pool exist?
    if (!osdmap.have_pg_pool(p->first.pool())) {
      /*
       * 1. If the osdmap does not have the pool, it means the pool has been
       *    removed in-between the osd sending this message and us handling it.
       * 2. If osdmap doesn't have the pool, it is safe to assume the pool does
       *    not exist in the pending either, as the osds would not send a
       *    message about a pool they know nothing about (yet).
       * 3. However, if the pool does exist in the pending, then it must be a
       *    new pool, and not relevant to this message (see 1).
       */
      dout(10) << __func__ << " ignore " << p->first << " -> " << p->second
               << ": pool has been removed" << dendl;
      ignore_cnt++;
      continue;
    }

    int acting_primary = -1;
    osdmap.pg_to_up_acting_osds(
      p->first, nullptr, nullptr, nullptr, &acting_primary);
    if (acting_primary != from) {
      /* If the source isn't the primary based on the current osdmap, we know
       * that the interval changed and that we can discard this message.
       * Indeed, we must do so to avoid 16127 since we can't otherwise determine
       * which of two pg temp mappings on the same pg is more recent.
       */
      dout(10) << __func__ << " ignore " << p->first << " -> " << p->second
	       << ": primary has changed" << dendl;
      ignore_cnt++;
      continue;
    }

    // removal?
    if (p->second.empty() && (osdmap.pg_temp->count(p->first) ||
			      osdmap.primary_temp->count(p->first)))
      return false;
    // change?
    //  NOTE: we assume that this will clear pg_primary, so consider
    //        an existing pg_primary field to imply a change
    if (p->second.size() &&
	(osdmap.pg_temp->count(p->first) == 0 ||
	 osdmap.pg_temp->get(p->first) != p->second ||
	 osdmap.primary_temp->count(p->first)))
      return false;
  }

  // should we ignore all the pgs?
  if (ignore_cnt == m->pg_temp.size())
    goto ignore;

  dout(7) << "preprocess_pgtemp e" << m->map_epoch << " no changes from " << m->get_orig_source_inst() << dendl;
  _reply_map(op, m->map_epoch);
  return true;

 ignore:
  mon->no_reply(op);
  return true;
}

void OSDMonitor::update_up_thru(int from, epoch_t up_thru)
{
  epoch_t old_up_thru = osdmap.get_up_thru(from);
  auto ut = pending_inc.new_up_thru.find(from);
  if (ut != pending_inc.new_up_thru.end()) {
    old_up_thru = ut->second;
  }
  if (up_thru > old_up_thru) {
    // set up_thru too, so the osd doesn't have to ask again
    pending_inc.new_up_thru[from] = up_thru;
  }
}

bool OSDMonitor::prepare_pgtemp(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  MOSDPGTemp *m = static_cast<MOSDPGTemp*>(op->get_req());
  int from = m->get_orig_source().num();
  dout(7) << "prepare_pgtemp e" << m->map_epoch << " from " << m->get_orig_source_inst() << dendl;
  for (map<pg_t,vector<int32_t> >::iterator p = m->pg_temp.begin(); p != m->pg_temp.end(); ++p) {
    uint64_t pool = p->first.pool();
    if (pending_inc.old_pools.count(pool)) {
      dout(10) << __func__ << " ignore " << p->first << " -> " << p->second
               << ": pool pending removal" << dendl;
      continue;
    }
    if (!osdmap.have_pg_pool(pool)) {
      dout(10) << __func__ << " ignore " << p->first << " -> " << p->second
               << ": pool has been removed" << dendl;
      continue;
    }
    pending_inc.new_pg_temp[p->first] =
      mempool::osdmap::vector<int>(p->second.begin(), p->second.end());

    // unconditionally clear pg_primary (until this message can encode
    // a change for that, too.. at which point we need to also fix
    // preprocess_pg_temp)
    if (osdmap.primary_temp->count(p->first) ||
	pending_inc.new_primary_temp.count(p->first))
      pending_inc.new_primary_temp[p->first] = -1;
  }

  // set up_thru too, so the osd doesn't have to ask again
  update_up_thru(from, m->map_epoch);

  wait_for_finished_proposal(op, new C_ReplyMap(this, op, m->map_epoch));
  return true;
}


// ---

bool OSDMonitor::preprocess_remove_snaps(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  MRemoveSnaps *m = static_cast<MRemoveSnaps*>(op->get_req());
  dout(7) << "preprocess_remove_snaps " << *m << dendl;

  // check privilege, ignore if failed
  MonSession *session = op->get_session();
  mon->no_reply(op);
  if (!session)
    goto ignore;
  if (!session->caps.is_capable(
	cct,
	session->entity_name,
        "osd", "osd pool rmsnap", {}, true, true, false,
	session->get_peer_socket_addr())) {
    dout(0) << "got preprocess_remove_snaps from entity with insufficient caps "
	    << session->caps << dendl;
    goto ignore;
  }

  for (map<int, vector<snapid_t> >::iterator q = m->snaps.begin();
       q != m->snaps.end();
       ++q) {
    if (!osdmap.have_pg_pool(q->first)) {
      dout(10) << " ignoring removed_snaps " << q->second << " on non-existent pool " << q->first << dendl;
      continue;
    }
    const pg_pool_t *pi = osdmap.get_pg_pool(q->first);
    for (vector<snapid_t>::iterator p = q->second.begin();
	 p != q->second.end();
	 ++p) {
      if (*p > pi->get_snap_seq() ||
	  !pi->removed_snaps.contains(*p))
	return false;
    }
  }

 ignore:
  return true;
}

bool OSDMonitor::prepare_remove_snaps(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  MRemoveSnaps *m = static_cast<MRemoveSnaps*>(op->get_req());
  dout(7) << "prepare_remove_snaps " << *m << dendl;

  for (map<int, vector<snapid_t> >::iterator p = m->snaps.begin();
       p != m->snaps.end();
       ++p) {

    if (!osdmap.have_pg_pool(p->first)) {
      dout(10) << " ignoring removed_snaps " << p->second << " on non-existent pool " << p->first << dendl;
      continue;
    }

    pg_pool_t& pi = osdmap.pools[p->first];
    for (vector<snapid_t>::iterator q = p->second.begin();
	 q != p->second.end();
	 ++q) {
      if (!pi.removed_snaps.contains(*q) &&
	  (!pending_inc.new_pools.count(p->first) ||
	   !pending_inc.new_pools[p->first].removed_snaps.contains(*q))) {
	pg_pool_t *newpi = pending_inc.get_new_pool(p->first, &pi);
	newpi->removed_snaps.insert(*q);
	newpi->flags |= pg_pool_t::FLAG_SELFMANAGED_SNAPS;
	dout(10) << " pool " << p->first << " removed_snaps added " << *q
		 << " (now " << newpi->removed_snaps << ")" << dendl;
	if (*q > newpi->get_snap_seq()) {
	  dout(10) << " pool " << p->first << " snap_seq "
		   << newpi->get_snap_seq() << " -> " << *q << dendl;
	  newpi->set_snap_seq(*q);
	}
	newpi->set_snap_epoch(pending_inc.epoch);
	pending_inc.new_removed_snaps[p->first].insert(*q);
      }
    }
  }
  return true;
}

// osd beacon
bool OSDMonitor::preprocess_beacon(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  // check caps
  auto session = op->get_session();
  mon->no_reply(op);
  if (!session) {
    dout(10) << __func__ << " no monitor session!" << dendl;
    return true;
  }
  if (!session->is_capable("osd", MON_CAP_X)) {
    derr << __func__ << " received from entity "
         << "with insufficient privileges " << session->caps << dendl;
    return true;
  }
  // Always forward the beacon to the leader, even if they are the same as
  // the old one. The leader will mark as down osds that haven't sent
  // beacon for a few minutes.
  return false;
}

bool OSDMonitor::prepare_beacon(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  const auto beacon = static_cast<MOSDBeacon*>(op->get_req());
  const auto src = beacon->get_orig_source();
  dout(10) << __func__ << " " << *beacon
	   << " from " << src << dendl;
  int from = src.num();

  if (!src.is_osd() ||
      !osdmap.is_up(from) ||
      !osdmap.get_addrs(from).legacy_equals(beacon->get_orig_source_addrs())) {
    if (src.is_osd() && !osdmap.is_up(from)) {
      // share some new maps with this guy in case it may not be
      // aware of its own deadness...
      send_latest(op, beacon->version+1);
    }
    dout(1) << " ignoring beacon from non-active osd." << from << dendl;
    return false;
  }

  last_osd_report[from] = ceph_clock_now();
  osd_epochs[from] = beacon->version;

  for (const auto& pg : beacon->pgs) {
    last_epoch_clean.report(pg, beacon->min_last_epoch_clean);
  }
  return false;
}

// ---------------
// map helpers

void OSDMonitor::send_latest(MonOpRequestRef op, epoch_t start)
{
  op->mark_osdmon_event(__func__);
  dout(5) << "send_latest to " << op->get_req()->get_orig_source_inst()
	  << " start " << start << dendl;
  if (start == 0)
    send_full(op);
  else
    send_incremental(op, start);
}


MOSDMap *OSDMonitor::build_latest_full(uint64_t features)
{
  MOSDMap *r = new MOSDMap(mon->monmap->fsid, features);
  get_version_full(osdmap.get_epoch(), features, r->maps[osdmap.get_epoch()]);
  r->oldest_map = get_first_committed();
  r->newest_map = osdmap.get_epoch();
  return r;
}

MOSDMap *OSDMonitor::build_incremental(epoch_t from, epoch_t to, uint64_t features)
{
  dout(10) << "build_incremental [" << from << ".." << to << "] with features "
	   << std::hex << features << std::dec << dendl;
  MOSDMap *m = new MOSDMap(mon->monmap->fsid, features);
  m->oldest_map = get_first_committed();
  m->newest_map = osdmap.get_epoch();

  for (epoch_t e = to; e >= from && e > 0; e--) {
    bufferlist bl;
    int err = get_version(e, features, bl);
    if (err == 0) {
      ceph_assert(bl.length());
      // if (get_version(e, bl) > 0) {
      dout(20) << "build_incremental    inc " << e << " "
	       << bl.length() << " bytes" << dendl;
      m->incremental_maps[e] = bl;
    } else {
      ceph_assert(err == -ENOENT);
      ceph_assert(!bl.length());
      get_version_full(e, features, bl);
      if (bl.length() > 0) {
      //else if (get_version("full", e, bl) > 0) {
      dout(20) << "build_incremental   full " << e << " "
	       << bl.length() << " bytes" << dendl;
      m->maps[e] = bl;
      } else {
	ceph_abort();  // we should have all maps.
      }
    }
  }
  return m;
}

void OSDMonitor::send_full(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  dout(5) << "send_full to " << op->get_req()->get_orig_source_inst() << dendl;
  mon->send_reply(op, build_latest_full(op->get_session()->con_features));
}

void OSDMonitor::send_incremental(MonOpRequestRef op, epoch_t first)
{
  op->mark_osdmon_event(__func__);

  MonSession *s = op->get_session();
  ceph_assert(s);

  if (s->proxy_con) {
    // oh, we can tell the other mon to do it
    dout(10) << __func__ << " asking proxying mon to send_incremental from "
	     << first << dendl;
    MRoute *r = new MRoute(s->proxy_tid, NULL);
    r->send_osdmap_first = first;
    s->proxy_con->send_message(r);
    op->mark_event("reply: send routed send_osdmap_first reply");
  } else {
    // do it ourselves
    send_incremental(first, s, false, op);
  }
}

void OSDMonitor::send_incremental(epoch_t first,
				  MonSession *session,
				  bool onetime,
				  MonOpRequestRef req)
{
  dout(5) << "send_incremental [" << first << ".." << osdmap.get_epoch() << "]"
	  << " to " << session->name << dendl;

  // get feature of the peer
  // use quorum_con_features, if it's an anonymous connection.
  uint64_t features = session->con_features ? session->con_features :
    mon->get_quorum_con_features();

  if (first <= session->osd_epoch) {
    dout(10) << __func__ << " " << session->name << " should already have epoch "
	     << session->osd_epoch << dendl;
    first = session->osd_epoch + 1;
  }

  if (first < get_first_committed()) {
    MOSDMap *m = new MOSDMap(osdmap.get_fsid(), features);
    m->oldest_map = get_first_committed();
    m->newest_map = osdmap.get_epoch();

    // share removed snaps during the gap
    get_removed_snaps_range(first, m->oldest_map, &m->gap_removed_snaps);

    first = get_first_committed();
    bufferlist bl;
    int err = get_version_full(first, features, bl);
    ceph_assert(err == 0);
    ceph_assert(bl.length());
    dout(20) << "send_incremental starting with base full "
	     << first << " " << bl.length() << " bytes" << dendl;
    m->maps[first] = bl;

    if (req) {
      mon->send_reply(req, m);
      session->osd_epoch = first;
      return;
    } else {
      session->con->send_message(m);
      session->osd_epoch = first;
    }
    first++;
  }

  while (first <= osdmap.get_epoch()) {
    epoch_t last = std::min<epoch_t>(first + g_conf()->osd_map_message_max - 1,
				     osdmap.get_epoch());
    MOSDMap *m = build_incremental(first, last, features);

    if (req) {
      // send some maps.  it may not be all of them, but it will get them
      // started.
      mon->send_reply(req, m);
    } else {
      session->con->send_message(m);
      first = last + 1;
    }
    session->osd_epoch = last;
    if (onetime || req)
      break;
  }
}

void OSDMonitor::get_removed_snaps_range(
  epoch_t start, epoch_t end,
  mempool::osdmap::map<int64_t,OSDMap::snap_interval_set_t> *gap_removed_snaps)
{
  // we only care about pools that exist now.
  for (auto& p : osdmap.get_pools()) {
    auto& t = (*gap_removed_snaps)[p.first];
    for (epoch_t epoch = start; epoch < end; ++epoch) {
      string k = make_snap_epoch_key(p.first, epoch);
      bufferlist v;
      mon->store->get(OSD_SNAP_PREFIX, k, v);
      if (v.length()) {
	auto q = v.cbegin();
	OSDMap::snap_interval_set_t snaps;
	decode(snaps, q);
	t.union_of(snaps);
      }
    }
    dout(10) << __func__ << " " << p.first << " " << t << dendl;
  }
}

int OSDMonitor::get_version(version_t ver, bufferlist& bl)
{
  return get_version(ver, mon->get_quorum_con_features(), bl);
}

void OSDMonitor::reencode_incremental_map(bufferlist& bl, uint64_t features)
{
  OSDMap::Incremental inc;
  auto q = bl.cbegin();
  inc.decode(q);
  // always encode with subset of osdmap's canonical features
  uint64_t f = features & inc.encode_features;
  dout(20) << __func__ << " " << inc.epoch << " with features " << f
	   << dendl;
  bl.clear();
  if (inc.fullmap.length()) {
    // embedded full map?
    OSDMap m;
    m.decode(inc.fullmap);
    inc.fullmap.clear();
    m.encode(inc.fullmap, f | CEPH_FEATURE_RESERVED);
  }
  if (inc.crush.length()) {
    // embedded crush map
    CrushWrapper c;
    auto p = inc.crush.cbegin();
    c.decode(p);
    inc.crush.clear();
    c.encode(inc.crush, f);
  }
  inc.encode(bl, f | CEPH_FEATURE_RESERVED);
}

void OSDMonitor::reencode_full_map(bufferlist& bl, uint64_t features)
{
  OSDMap m;
  auto q = bl.cbegin();
  m.decode(q);
  // always encode with subset of osdmap's canonical features
  uint64_t f = features & m.get_encoding_features();
  dout(20) << __func__ << " " << m.get_epoch() << " with features " << f
	   << dendl;
  bl.clear();
  m.encode(bl, f | CEPH_FEATURE_RESERVED);
}

int OSDMonitor::get_version(version_t ver, uint64_t features, bufferlist& bl)
{
  uint64_t significant_features = OSDMap::get_significant_features(features);
  if (inc_osd_cache.lookup({ver, significant_features}, &bl)) {
    return 0;
  }
  int ret = PaxosService::get_version(ver, bl);
  if (ret < 0) {
    return ret;
  }
  // NOTE: this check is imprecise; the OSDMap encoding features may
  // be a subset of the latest mon quorum features, but worst case we
  // reencode once and then cache the (identical) result under both
  // feature masks.
  if (significant_features !=
      OSDMap::get_significant_features(mon->get_quorum_con_features())) {
    reencode_incremental_map(bl, features);
  }
  inc_osd_cache.add_bytes({ver, significant_features}, bl);
  return 0;
}

int OSDMonitor::get_inc(version_t ver, OSDMap::Incremental& inc)
{
  bufferlist inc_bl;
  int err = get_version(ver, inc_bl);
  ceph_assert(err == 0);
  ceph_assert(inc_bl.length());

  auto p = inc_bl.cbegin();
  inc.decode(p);
  dout(10) << __func__ << "     "
           << " epoch " << inc.epoch
           << " inc_crc " << inc.inc_crc
           << " full_crc " << inc.full_crc
           << " encode_features " << inc.encode_features << dendl;
  return 0;
}

int OSDMonitor::get_full_from_pinned_map(version_t ver, bufferlist& bl)
{
  dout(10) << __func__ << " ver " << ver << dendl;

  version_t closest_pinned = osdmap_manifest.get_lower_closest_pinned(ver);
  if (closest_pinned == 0) {
    return -ENOENT;
  }
  if (closest_pinned > ver) {
    dout(0) << __func__ << " pinned: " << osdmap_manifest.pinned << dendl;
  }
  ceph_assert(closest_pinned <= ver);

  dout(10) << __func__ << " closest pinned ver " << closest_pinned << dendl;

  // get osdmap incremental maps and apply on top of this one.
  bufferlist osdm_bl;
  bool has_cached_osdmap = false;
  for (version_t v = ver-1; v >= closest_pinned; --v) {
    if (full_osd_cache.lookup({v, mon->get_quorum_con_features()},
                                &osdm_bl)) {
      dout(10) << __func__ << " found map in cache ver " << v << dendl;
      closest_pinned = v;
      has_cached_osdmap = true;
      break;
    }
  }

  if (!has_cached_osdmap) {
    int err = PaxosService::get_version_full(closest_pinned, osdm_bl);
    if (err != 0) {
      derr << __func__ << " closest pinned map ver " << closest_pinned
           << " not available! error: " << cpp_strerror(err) << dendl;
    }
    ceph_assert(err == 0);
  }

  ceph_assert(osdm_bl.length());

  OSDMap osdm;
  osdm.decode(osdm_bl);

  dout(10) << __func__ << " loaded osdmap epoch " << closest_pinned
           << " e" << osdm.epoch
           << " crc " << osdm.get_crc()
           << " -- applying incremental maps." << dendl;

  uint64_t encode_features = 0;
  for (version_t v = closest_pinned + 1; v <= ver; ++v) {
    dout(20) << __func__ << "    applying inc epoch " << v << dendl;

    OSDMap::Incremental inc;
    int err = get_inc(v, inc);
    ceph_assert(err == 0);

    encode_features = inc.encode_features;

    err = osdm.apply_incremental(inc);
    ceph_assert(err == 0);

    // this block performs paranoid checks on map retrieval
    if (g_conf().get_val<bool>("mon_debug_extra_checks") &&
        inc.full_crc != 0) {

      uint64_t f = encode_features;
      if (!f) {
        f = (mon->quorum_con_features ? mon->quorum_con_features : -1);
      }

      // encode osdmap to force calculating crcs
      bufferlist tbl;
      osdm.encode(tbl, f | CEPH_FEATURE_RESERVED);
      // decode osdmap to compare crcs with what's expected by incremental
      OSDMap tosdm;
      tosdm.decode(tbl);

      if (tosdm.get_crc() != inc.full_crc) {
        derr << __func__
             << "    osdmap crc mismatch! (osdmap crc " << tosdm.get_crc()
             << ", expected " << inc.full_crc << ")" << dendl;
        ceph_abort_msg("osdmap crc mismatch");
      }
    }

    // note: we cannot add the recently computed map to the cache, as is,
    // because we have not encoded the map into a bl.
  }

  if (!encode_features) {
    dout(10) << __func__
             << " last incremental map didn't have features;"
             << " defaulting to quorum's or all" << dendl;
    encode_features =
      (mon->quorum_con_features ? mon->quorum_con_features : -1);
  }
  osdm.encode(bl, encode_features | CEPH_FEATURE_RESERVED);

  return 0;
}

int OSDMonitor::get_version_full(version_t ver, bufferlist& bl)
{
  return get_version_full(ver, mon->get_quorum_con_features(), bl);
}

int OSDMonitor::get_version_full(version_t ver, uint64_t features,
				 bufferlist& bl)
{
  uint64_t significant_features = OSDMap::get_significant_features(features);
  if (full_osd_cache.lookup({ver, significant_features}, &bl)) {
    return 0;
  }
  int ret = PaxosService::get_version_full(ver, bl);
  if (ret == -ENOENT) {
    // build map?
    ret = get_full_from_pinned_map(ver, bl);
  }
  if (ret < 0) {
    return ret;
  }
  // NOTE: this check is imprecise; the OSDMap encoding features may
  // be a subset of the latest mon quorum features, but worst case we
  // reencode once and then cache the (identical) result under both
  // feature masks.
  if (significant_features !=
      OSDMap::get_significant_features(mon->get_quorum_con_features())) {
    reencode_full_map(bl, features);
  }
  full_osd_cache.add_bytes({ver, significant_features}, bl);
  return 0;
}

epoch_t OSDMonitor::blacklist(const entity_addrvec_t& av, utime_t until)
{
  dout(10) << "blacklist " << av << " until " << until << dendl;
  for (auto a : av.v) {
    if (osdmap.require_osd_release >= CEPH_RELEASE_NAUTILUS) {
      a.set_type(entity_addr_t::TYPE_ANY);
    } else {
      a.set_type(entity_addr_t::TYPE_LEGACY);
    }
    pending_inc.new_blacklist[a] = until;
  }
  return pending_inc.epoch;
}

epoch_t OSDMonitor::blacklist(entity_addr_t a, utime_t until)
{
  if (osdmap.require_osd_release >= CEPH_RELEASE_NAUTILUS) {
    a.set_type(entity_addr_t::TYPE_ANY);
  } else {
    a.set_type(entity_addr_t::TYPE_LEGACY);
  }
  dout(10) << "blacklist " << a << " until " << until << dendl;
  pending_inc.new_blacklist[a] = until;
  return pending_inc.epoch;
}


void OSDMonitor::check_osdmap_subs()
{
  dout(10) << __func__ << dendl;
  if (!osdmap.get_epoch()) {
    return;
  }
  auto osdmap_subs = mon->session_map.subs.find("osdmap");
  if (osdmap_subs == mon->session_map.subs.end()) {
    return;
  }
  auto p = osdmap_subs->second->begin();
  while (!p.end()) {
    auto sub = *p;
    ++p;
    check_osdmap_sub(sub);
  }
}

void OSDMonitor::check_osdmap_sub(Subscription *sub)
{
  dout(10) << __func__ << " " << sub << " next " << sub->next
	   << (sub->onetime ? " (onetime)":" (ongoing)") << dendl;
  if (sub->next <= osdmap.get_epoch()) {
    if (sub->next >= 1)
      send_incremental(sub->next, sub->session, sub->incremental_onetime);
    else
      sub->session->con->send_message(build_latest_full(sub->session->con_features));
    if (sub->onetime)
      mon->session_map.remove_sub(sub);
    else
      sub->next = osdmap.get_epoch() + 1;
  }
}

void OSDMonitor::check_pg_creates_subs()
{
  if (!osdmap.get_num_up_osds()) {
    return;
  }
  ceph_assert(osdmap.get_up_osd_features() & CEPH_FEATURE_MON_STATEFUL_SUB);
  mon->with_session_map([this](const MonSessionMap& session_map) {
      auto pg_creates_subs = session_map.subs.find("osd_pg_creates");
      if (pg_creates_subs == session_map.subs.end()) {
	return;
      }
      for (auto sub : *pg_creates_subs->second) {
	check_pg_creates_sub(sub);
      }
    });
}

void OSDMonitor::check_pg_creates_sub(Subscription *sub)
{
  dout(20) << __func__ << " .. " << sub->session->name << dendl;
  ceph_assert(sub->type == "osd_pg_creates");
  // only send these if the OSD is up.  we will check_subs() when they do
  // come up so they will get the creates then.
  if (sub->session->name.is_osd() &&
      mon->osdmon()->osdmap.is_up(sub->session->name.num())) {
    sub->next = send_pg_creates(sub->session->name.num(),
				sub->session->con.get(),
				sub->next);
  }
}

void OSDMonitor::do_application_enable(int64_t pool_id,
                                       const std::string &app_name,
				       const std::string &app_key,
				       const std::string &app_value,
				       bool force)
{
  ceph_assert(paxos->is_plugged() && is_writeable());

  dout(20) << __func__ << ": pool_id=" << pool_id << ", app_name=" << app_name
           << dendl;

  ceph_assert(osdmap.require_osd_release >= CEPH_RELEASE_LUMINOUS);

  auto pp = osdmap.get_pg_pool(pool_id);
  ceph_assert(pp != nullptr);

  pg_pool_t p = *pp;
  if (pending_inc.new_pools.count(pool_id)) {
    p = pending_inc.new_pools[pool_id];
  }

  if (app_key.empty()) {
    p.application_metadata.insert({app_name, {}});
  } else {
    if (force) {
      p.application_metadata[app_name][app_key] = app_value;
    } else {
      p.application_metadata.insert({app_name, {{app_key, app_value}}});
    }
  }
  p.last_change = pending_inc.epoch;
  pending_inc.new_pools[pool_id] = p;
}

void OSDMonitor::do_set_pool_opt(int64_t pool_id,
				 pool_opts_t::key_t opt,
				 pool_opts_t::value_t val)
{
  auto p = pending_inc.new_pools.try_emplace(
    pool_id, *osdmap.get_pg_pool(pool_id));
  p.first->second.opts.set(opt, val);
}

unsigned OSDMonitor::scan_for_creating_pgs(
  const mempool::osdmap::map<int64_t,pg_pool_t>& pools,
  const mempool::osdmap::set<int64_t>& removed_pools,
  utime_t modified,
  creating_pgs_t* creating_pgs) const
{
  unsigned queued = 0;
  for (auto& p : pools) {
    int64_t poolid = p.first;
    if (creating_pgs->created_pools.count(poolid)) {
      dout(10) << __func__ << " already created " << poolid << dendl;
      continue;
    }
    const pg_pool_t& pool = p.second;
    int ruleno = osdmap.crush->find_rule(pool.get_crush_rule(),
					 pool.get_type(), pool.get_size());
    if (ruleno < 0 || !osdmap.crush->rule_exists(ruleno))
      continue;

    const auto last_scan_epoch = creating_pgs->last_scan_epoch;
    const auto created = pool.get_last_change();
    if (last_scan_epoch && created <= last_scan_epoch) {
      dout(10) << __func__ << " no change in pool " << poolid
	       << " " << pool << dendl;
      continue;
    }
    if (removed_pools.count(poolid)) {
      dout(10) << __func__ << " pool is being removed: " << poolid
	       << " " << pool << dendl;
      continue;
    }
    dout(10) << __func__ << " queueing pool create for " << poolid
	     << " " << pool << dendl;
    creating_pgs->create_pool(poolid, pool.get_pg_num(),
			      created, modified);
    queued++;
  }
  return queued;
}

void OSDMonitor::update_creating_pgs()
{
  dout(10) << __func__ << " " << creating_pgs.pgs.size() << " pgs creating, "
	   << creating_pgs.queue.size() << " pools in queue" << dendl;
  decltype(creating_pgs_by_osd_epoch) new_pgs_by_osd_epoch;
  std::lock_guard<std::mutex> l(creating_pgs_lock);
  for (const auto& pg : creating_pgs.pgs) {
    int acting_primary = -1;
    auto pgid = pg.first;
    if (!osdmap.pg_exists(pgid)) {
      dout(20) << __func__ << " ignoring " << pgid << " which should not exist"
	       << dendl;
      continue;
    }
    auto mapped = pg.second.first;
    dout(20) << __func__ << " looking up " << pgid << "@" << mapped << dendl;
    spg_t spgid(pgid);
    mapping.get_primary_and_shard(pgid, &acting_primary, &spgid);
    // check the previous creating_pgs, look for the target to whom the pg was
    // previously mapped
    for (const auto& pgs_by_epoch : creating_pgs_by_osd_epoch) {
      const auto last_acting_primary = pgs_by_epoch.first;
      for (auto& pgs: pgs_by_epoch.second) {
	if (pgs.second.count(spgid)) {
	  if (last_acting_primary == acting_primary) {
	    mapped = pgs.first;
	  } else {
	    dout(20) << __func__ << " " << pgid << " "
		     << " acting_primary:" << last_acting_primary
		     << " -> " << acting_primary << dendl;
	    // note epoch if the target of the create message changed.
	    mapped = mapping.get_epoch();
          }
          break;
        } else {
	  // newly creating
	  mapped = mapping.get_epoch();
	}
      }
    }
    dout(10) << __func__ << " will instruct osd." << acting_primary
	     << " to create " << pgid << "@" << mapped << dendl;
    new_pgs_by_osd_epoch[acting_primary][mapped].insert(spgid);
  }
  creating_pgs_by_osd_epoch = std::move(new_pgs_by_osd_epoch);
  creating_pgs_epoch = mapping.get_epoch();
}

epoch_t OSDMonitor::send_pg_creates(int osd, Connection *con, epoch_t next) const
{
  dout(30) << __func__ << " osd." << osd << " next=" << next
	   << " " << creating_pgs_by_osd_epoch << dendl;
  std::lock_guard<std::mutex> l(creating_pgs_lock);
  if (creating_pgs_epoch <= creating_pgs.last_scan_epoch) {
    dout(20) << __func__
	     << " not using stale creating_pgs@" << creating_pgs_epoch << dendl;
    // the subscribers will be updated when the mapping is completed anyway
    return next;
  }
  auto creating_pgs_by_epoch = creating_pgs_by_osd_epoch.find(osd);
  if (creating_pgs_by_epoch == creating_pgs_by_osd_epoch.end())
    return next;
  ceph_assert(!creating_pgs_by_epoch->second.empty());

  MOSDPGCreate *oldm = nullptr; // for pre-mimic OSD compat
  MOSDPGCreate2 *m = nullptr;

  bool old = osdmap.require_osd_release < CEPH_RELEASE_NAUTILUS;

  epoch_t last = 0;
  for (auto epoch_pgs = creating_pgs_by_epoch->second.lower_bound(next);
       epoch_pgs != creating_pgs_by_epoch->second.end(); ++epoch_pgs) {
    auto epoch = epoch_pgs->first;
    auto& pgs = epoch_pgs->second;
    dout(20) << __func__ << " osd." << osd << " from " << next
             << " : epoch " << epoch << " " << pgs.size() << " pgs" << dendl;
    last = epoch;
    for (auto& pg : pgs) {
      // Need the create time from the monitor using its clock to set
      // last_scrub_stamp upon pg creation.
      auto create = creating_pgs.pgs.find(pg.pgid);
      ceph_assert(create != creating_pgs.pgs.end());
      if (old) {
	if (!oldm) {
	  oldm = new MOSDPGCreate(creating_pgs_epoch);
	}
	oldm->mkpg.emplace(pg.pgid,
			   pg_create_t{create->second.first, pg.pgid, 0});
	oldm->ctimes.emplace(pg.pgid, create->second.second);
      } else {
	if (!m) {
	  m = new MOSDPGCreate2(creating_pgs_epoch);
	}
	m->pgs.emplace(pg, create->second);
      }
      dout(20) << __func__ << " will create " << pg
	       << " at " << create->second.first << dendl;
    }
  }
  if (m) {
    con->send_message(m);
  } else if (oldm) {
    con->send_message(oldm);
  } else {
    dout(20) << __func__ << " osd." << osd << " from " << next
             << " has nothing to send" << dendl;
    return next;
  }

  // sub is current through last + 1
  return last + 1;
}

// TICK


void OSDMonitor::tick()
{
  if (!is_active()) return;

  dout(10) << osdmap << dendl;

  // always update osdmap manifest, regardless of being the leader.
  load_osdmap_manifest();

  // always tune priority cache manager memory on leader and peons
  if (ceph_using_tcmalloc() && mon_memory_autotune) {
    std::lock_guard l(balancer_lock);
    if (pcm != nullptr) {
      pcm->tune_memory();
      pcm->balance();
      _set_new_cache_sizes();
      dout(10) << "tick balancer "
               << " inc cache_bytes: " << inc_cache->get_cache_bytes()
               << " inc comtd_bytes: " << inc_cache->get_committed_size()
               << " inc used_bytes: " << inc_cache->_get_used_bytes()
               << " inc num_osdmaps: " << inc_cache->_get_num_osdmaps()
               << dendl;
      dout(10) << "tick balancer "
               << " full cache_bytes: " << full_cache->get_cache_bytes()
               << " full comtd_bytes: " << full_cache->get_committed_size()
               << " full used_bytes: " << full_cache->_get_used_bytes()
               << " full num_osdmaps: " << full_cache->_get_num_osdmaps()
               << dendl;
    }
  }

  if (!mon->is_leader()) return;

  bool do_propose = false;
  utime_t now = ceph_clock_now();

  if (handle_osd_timeouts(now, last_osd_report)) {
    do_propose = true;
  }

  // mark osds down?
  if (check_failures(now)) {
    do_propose = true;
  }

  // Force a proposal if we need to prune; pruning is performed on
  // ``encode_pending()``, hence why we need to regularly trigger a proposal
  // even if there's nothing going on.
  if (is_prune_enabled() && should_prune()) {
    do_propose = true;
  }

  // mark down osds out?

  /* can_mark_out() checks if we can mark osds as being out. The -1 has no
   * influence at all. The decision is made based on the ratio of "in" osds,
   * and the function returns false if this ratio is lower that the minimum
   * ratio set by g_conf()->mon_osd_min_in_ratio. So it's not really up to us.
   */
  if (can_mark_out(-1)) {
    string down_out_subtree_limit = g_conf().get_val<string>(
      "mon_osd_down_out_subtree_limit");
    set<int> down_cache;  // quick cache of down subtrees

    map<int,utime_t>::iterator i = down_pending_out.begin();
    while (i != down_pending_out.end()) {
      int o = i->first;
      utime_t down = now;
      down -= i->second;
      ++i;

      if (osdmap.is_down(o) &&
	  osdmap.is_in(o) &&
	  can_mark_out(o)) {
	utime_t orig_grace(g_conf()->mon_osd_down_out_interval, 0);
	utime_t grace = orig_grace;
	double my_grace = 0.0;

	if (g_conf()->mon_osd_adjust_down_out_interval) {
	  // scale grace period the same way we do the heartbeat grace.
	  const osd_xinfo_t& xi = osdmap.get_xinfo(o);
	  double halflife = (double)g_conf()->mon_osd_laggy_halflife;
	  double decay_k = ::log(.5) / halflife;
	  double decay = exp((double)down * decay_k);
	  dout(20) << "osd." << o << " laggy halflife " << halflife << " decay_k " << decay_k
		   << " down for " << down << " decay " << decay << dendl;
	  my_grace = decay * (double)xi.laggy_interval * xi.laggy_probability;
	  grace += my_grace;
	}

	// is this an entire large subtree down?
	if (down_out_subtree_limit.length()) {
	  int type = osdmap.crush->get_type_id(down_out_subtree_limit);
	  if (type > 0) {
	    if (osdmap.containing_subtree_is_down(cct, o, type, &down_cache)) {
	      dout(10) << "tick entire containing " << down_out_subtree_limit
		       << " subtree for osd." << o
		       << " is down; resetting timer" << dendl;
	      // reset timer, too.
	      down_pending_out[o] = now;
	      continue;
	    }
	  }
	}

        bool down_out = !osdmap.is_destroyed(o) &&
          g_conf()->mon_osd_down_out_interval > 0 && down.sec() >= grace;
        bool destroyed_out = osdmap.is_destroyed(o) &&
          g_conf()->mon_osd_destroyed_out_interval > 0 &&
        // this is not precise enough as we did not make a note when this osd
        // was marked as destroyed, but let's not bother with that
        // complexity for now.
          down.sec() >= g_conf()->mon_osd_destroyed_out_interval;
        if (down_out || destroyed_out) {
	  dout(10) << "tick marking osd." << o << " OUT after " << down
		   << " sec (target " << grace << " = " << orig_grace << " + " << my_grace << ")" << dendl;
	  pending_inc.new_weight[o] = CEPH_OSD_OUT;

	  // set the AUTOOUT bit.
	  if (pending_inc.new_state.count(o) == 0)
	    pending_inc.new_state[o] = 0;
	  pending_inc.new_state[o] |= CEPH_OSD_AUTOOUT;

	  // remember previous weight
	  if (pending_inc.new_xinfo.count(o) == 0)
	    pending_inc.new_xinfo[o] = osdmap.osd_xinfo[o];
	  pending_inc.new_xinfo[o].old_weight = osdmap.osd_weight[o];

	  do_propose = true;

	  mon->clog->info() << "Marking osd." << o << " out (has been down for "
                            << int(down.sec()) << " seconds)";
	} else
	  continue;
      }

      down_pending_out.erase(o);
    }
  } else {
    dout(10) << "tick NOOUT flag set, not checking down osds" << dendl;
  }

  // expire blacklisted items?
  for (ceph::unordered_map<entity_addr_t,utime_t>::iterator p = osdmap.blacklist.begin();
       p != osdmap.blacklist.end();
       ++p) {
    if (p->second < now) {
      dout(10) << "expiring blacklist item " << p->first << " expired " << p->second << " < now " << now << dendl;
      pending_inc.old_blacklist.push_back(p->first);
      do_propose = true;
    }
  }

  if (try_prune_purged_snaps()) {
    do_propose = true;
  }

  if (update_pools_status())
    do_propose = true;

  if (do_propose ||
      !pending_inc.new_pg_temp.empty())  // also propose if we adjusted pg_temp
    propose_pending();
}

void OSDMonitor::_set_new_cache_sizes()
{
  uint64_t cache_size = 0;
  int64_t inc_alloc = 0;
  int64_t full_alloc = 0;
  int64_t kv_alloc = 0;

  if (pcm != nullptr && rocksdb_binned_kv_cache != nullptr) {
    cache_size = pcm->get_tuned_mem();
    inc_alloc = inc_cache->get_committed_size();
    full_alloc = full_cache->get_committed_size();
    kv_alloc = rocksdb_binned_kv_cache->get_committed_size();
  }

  inc_osd_cache.set_bytes(inc_alloc);
  full_osd_cache.set_bytes(full_alloc);

  dout(1) << __func__ << " cache_size:" << cache_size
           << " inc_alloc: " << inc_alloc
           << " full_alloc: " << full_alloc
           << " kv_alloc: " << kv_alloc
           << dendl;
}

bool OSDMonitor::handle_osd_timeouts(const utime_t &now,
				     std::map<int,utime_t> &last_osd_report)
{
  utime_t timeo(g_conf()->mon_osd_report_timeout, 0);
  if (now - mon->get_leader_since() < timeo) {
    // We haven't been the leader for long enough to consider OSD timeouts
    return false;
  }

  int max_osd = osdmap.get_max_osd();
  bool new_down = false;

  for (int i=0; i < max_osd; ++i) {
    dout(30) << __func__ << ": checking up on osd " << i << dendl;
    if (!osdmap.exists(i)) {
      last_osd_report.erase(i); // if any
      continue;
    }
    if (!osdmap.is_up(i))
      continue;
    const std::map<int,utime_t>::const_iterator t = last_osd_report.find(i);
    if (t == last_osd_report.end()) {
      // it wasn't in the map; start the timer.
      last_osd_report[i] = now;
    } else if (can_mark_down(i)) {
      utime_t diff = now - t->second;
      if (diff > timeo) {
	mon->clog->info() << "osd." << i << " marked down after no beacon for "
			  << diff << " seconds";
	derr << "no beacon from osd." << i << " since " << t->second
	     << ", " << diff << " seconds ago.  marking down" << dendl;
	pending_inc.new_state[i] = CEPH_OSD_UP;
	new_down = true;
      }
    }
  }
  return new_down;
}

static void dump_cpu_list(Formatter *f, const char *name,
			  const string& strlist)
{
  cpu_set_t cpu_set;
  size_t cpu_set_size;
  if (parse_cpu_set_list(strlist.c_str(), &cpu_set_size, &cpu_set) < 0) {
    return;
  }
  set<int> cpus = cpu_set_to_set(cpu_set_size, &cpu_set);
  f->open_array_section(name);
  for (auto cpu : cpus) {
    f->dump_int("cpu", cpu);
  }
  f->close_section();
}

void OSDMonitor::dump_info(Formatter *f)
{
  f->open_object_section("osdmap");
  osdmap.dump(f);
  f->close_section();

  f->open_array_section("osd_metadata");
  for (int i=0; i<osdmap.get_max_osd(); ++i) {
    if (osdmap.exists(i)) {
      f->open_object_section("osd");
      f->dump_unsigned("id", i);
      dump_osd_metadata(i, f, NULL);
      f->close_section();
    }
  }
  f->close_section();

  f->open_object_section("osdmap_clean_epochs");
  f->dump_unsigned("min_last_epoch_clean", get_min_last_epoch_clean());

  f->open_object_section("last_epoch_clean");
  last_epoch_clean.dump(f);
  f->close_section();

  f->open_array_section("osd_epochs");
  for (auto& osd_epoch : osd_epochs) {
    f->open_object_section("osd");
    f->dump_unsigned("id", osd_epoch.first);
    f->dump_unsigned("epoch", osd_epoch.second);
    f->close_section();
  }
  f->close_section(); // osd_epochs

  f->close_section(); // osd_clean_epochs

  f->dump_unsigned("osdmap_first_committed", get_first_committed());
  f->dump_unsigned("osdmap_last_committed", get_last_committed());

  f->open_object_section("crushmap");
  osdmap.crush->dump(f);
  f->close_section();

  if (has_osdmap_manifest) {
    f->open_object_section("osdmap_manifest");
    osdmap_manifest.dump(f);
    f->close_section();
  }
}

namespace {
  enum osd_pool_get_choices {
    SIZE, MIN_SIZE,
    PG_NUM, PGP_NUM, CRUSH_RULE, HASHPSPOOL, EC_OVERWRITES,
    NODELETE, NOPGCHANGE, NOSIZECHANGE,
    WRITE_FADVISE_DONTNEED, NOSCRUB, NODEEP_SCRUB,
    HIT_SET_TYPE, HIT_SET_PERIOD, HIT_SET_COUNT, HIT_SET_FPP,
    USE_GMT_HITSET, TARGET_MAX_OBJECTS, TARGET_MAX_BYTES,
    CACHE_TARGET_DIRTY_RATIO, CACHE_TARGET_DIRTY_HIGH_RATIO,
    CACHE_TARGET_FULL_RATIO,
    CACHE_MIN_FLUSH_AGE, CACHE_MIN_EVICT_AGE,
    ERASURE_CODE_PROFILE, MIN_READ_RECENCY_FOR_PROMOTE,
    MIN_WRITE_RECENCY_FOR_PROMOTE, FAST_READ,
    HIT_SET_GRADE_DECAY_RATE, HIT_SET_SEARCH_LAST_N,
    SCRUB_MIN_INTERVAL, SCRUB_MAX_INTERVAL, DEEP_SCRUB_INTERVAL,
    RECOVERY_PRIORITY, RECOVERY_OP_PRIORITY, SCRUB_PRIORITY,
    COMPRESSION_MODE, COMPRESSION_ALGORITHM, COMPRESSION_REQUIRED_RATIO,
    COMPRESSION_MAX_BLOB_SIZE, COMPRESSION_MIN_BLOB_SIZE,
    CSUM_TYPE, CSUM_MAX_BLOCK, CSUM_MIN_BLOCK, FINGERPRINT_ALGORITHM,
    PG_AUTOSCALE_MODE, PG_NUM_MIN, TARGET_SIZE_BYTES, TARGET_SIZE_RATIO,
    PG_AUTOSCALE_BIAS };

  std::set<osd_pool_get_choices>
    subtract_second_from_first(const std::set<osd_pool_get_choices>& first,
				const std::set<osd_pool_get_choices>& second)
    {
      std::set<osd_pool_get_choices> result;
      std::set_difference(first.begin(), first.end(),
			  second.begin(), second.end(),
			  std::inserter(result, result.end()));
      return result;
    }
}


bool OSDMonitor::preprocess_command(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  MMonCommand *m = static_cast<MMonCommand*>(op->get_req());
  int r = 0;
  bufferlist rdata;
  stringstream ss, ds;

  cmdmap_t cmdmap;
  if (!cmdmap_from_json(m->cmd, &cmdmap, ss)) {
    string rs = ss.str();
    mon->reply_command(op, -EINVAL, rs, get_last_committed());
    return true;
  }

  MonSession *session = op->get_session();
  if (!session) {
    derr << __func__ << " no session" << dendl;
    mon->reply_command(op, -EACCES, "access denied", get_last_committed());
    return true;
  }

  string prefix;
  cmd_getval(cct, cmdmap, "prefix", prefix);

  string format;
  cmd_getval(cct, cmdmap, "format", format, string("plain"));
  boost::scoped_ptr<Formatter> f(Formatter::create(format));

  if (prefix == "osd stat") {
    if (f) {
      f->open_object_section("osdmap");
      osdmap.print_summary(f.get(), ds, "", true);
      f->close_section();
      f->flush(rdata);
    } else {
      osdmap.print_summary(nullptr, ds, "", true);
      rdata.append(ds);
    }
  }
  else if (prefix == "osd dump" ||
	   prefix == "osd tree" ||
	   prefix == "osd tree-from" ||
	   prefix == "osd ls" ||
	   prefix == "osd getmap" ||
	   prefix == "osd getcrushmap" ||
	   prefix == "osd ls-tree") {
    string val;

    epoch_t epoch = 0;
    int64_t epochnum;
    cmd_getval(cct, cmdmap, "epoch", epochnum, (int64_t)osdmap.get_epoch());
    epoch = epochnum;
    
    bufferlist osdmap_bl;
    int err = get_version_full(epoch, osdmap_bl);
    if (err == -ENOENT) {
      r = -ENOENT;
      ss << "there is no map for epoch " << epoch;
      goto reply;
    }
    ceph_assert(err == 0);
    ceph_assert(osdmap_bl.length());

    OSDMap *p;
    if (epoch == osdmap.get_epoch()) {
      p = &osdmap;
    } else {
      p = new OSDMap;
      p->decode(osdmap_bl);
    }

    auto sg = make_scope_guard([&] {
      if (p != &osdmap) {
        delete p;
      }
    });

    if (prefix == "osd dump") {
      stringstream ds;
      if (f) {
	f->open_object_section("osdmap");
	p->dump(f.get());
	f->close_section();
	f->flush(ds);
      } else {
	p->print(ds);
      }
      rdata.append(ds);
      if (!f)
	ds << " ";
    } else if (prefix == "osd ls") {
      if (f) {
	f->open_array_section("osds");
	for (int i = 0; i < osdmap.get_max_osd(); i++) {
	  if (osdmap.exists(i)) {
	    f->dump_int("osd", i);
	  }
	}
	f->close_section();
	f->flush(ds);
      } else {
	bool first = true;
	for (int i = 0; i < osdmap.get_max_osd(); i++) {
	  if (osdmap.exists(i)) {
	    if (!first)
	      ds << "\n";
	    first = false;
	    ds << i;
	  }
	}
      }
      rdata.append(ds);
    } else if (prefix == "osd tree" || prefix == "osd tree-from") {
      string bucket;
      if (prefix == "osd tree-from") {
        cmd_getval(cct, cmdmap, "bucket", bucket);
        if (!osdmap.crush->name_exists(bucket)) {
          ss << "bucket '" << bucket << "' does not exist";
          r = -ENOENT;
          goto reply;
        }
        int id = osdmap.crush->get_item_id(bucket);
        if (id >= 0) {
          ss << "\"" << bucket << "\" is not a bucket";
          r = -EINVAL;
          goto reply;
        }
      }

      vector<string> states;
      cmd_getval(cct, cmdmap, "states", states);
      unsigned filter = 0;
      for (auto& s : states) {
	if (s == "up") {
	  filter |= OSDMap::DUMP_UP;
	} else if (s == "down") {
	  filter |= OSDMap::DUMP_DOWN;
	} else if (s == "in") {
	  filter |= OSDMap::DUMP_IN;
	} else if (s == "out") {
	  filter |= OSDMap::DUMP_OUT;
	} else if (s == "destroyed") {
	  filter |= OSDMap::DUMP_DESTROYED;
	} else {
	  ss << "unrecognized state '" << s << "'";
	  r = -EINVAL;
	  goto reply;
	}
      }
      if ((filter & (OSDMap::DUMP_IN|OSDMap::DUMP_OUT)) ==
	  (OSDMap::DUMP_IN|OSDMap::DUMP_OUT)) {
        ss << "cannot specify both 'in' and 'out'";
        r = -EINVAL;
        goto reply;
      }
      if (((filter & (OSDMap::DUMP_UP|OSDMap::DUMP_DOWN)) ==
	   (OSDMap::DUMP_UP|OSDMap::DUMP_DOWN)) ||
           ((filter & (OSDMap::DUMP_UP|OSDMap::DUMP_DESTROYED)) ==
           (OSDMap::DUMP_UP|OSDMap::DUMP_DESTROYED)) ||
           ((filter & (OSDMap::DUMP_DOWN|OSDMap::DUMP_DESTROYED)) ==
           (OSDMap::DUMP_DOWN|OSDMap::DUMP_DESTROYED))) {
	ss << "can specify only one of 'up', 'down' and 'destroyed'";
	r = -EINVAL;
	goto reply;
      }
      if (f) {
	f->open_object_section("tree");
	p->print_tree(f.get(), NULL, filter, bucket);
	f->close_section();
	f->flush(ds);
      } else {
	p->print_tree(NULL, &ds, filter, bucket);
      }
      rdata.append(ds);
    } else if (prefix == "osd getmap") {
      rdata.append(osdmap_bl);
      ss << "got osdmap epoch " << p->get_epoch();
    } else if (prefix == "osd getcrushmap") {
      p->crush->encode(rdata, mon->get_quorum_con_features());
      ss << p->get_crush_version();
    } else if (prefix == "osd ls-tree") {
      string bucket_name;
      cmd_getval(cct, cmdmap, "name", bucket_name);
      set<int> osds;
      r = p->get_osds_by_bucket_name(bucket_name, &osds);
      if (r == -ENOENT) {
        ss << "\"" << bucket_name << "\" does not exist";
        goto reply;
      } else if (r < 0) {
        ss << "can not parse bucket name:\"" << bucket_name << "\"";
        goto reply;
      }

      if (f) {
        f->open_array_section("osds");
        for (auto &i : osds) {
          if (osdmap.exists(i)) {
            f->dump_int("osd", i);
          }
        }
        f->close_section();
        f->flush(ds);
      } else {
        bool first = true;
        for (auto &i : osds) {
          if (osdmap.exists(i)) {
            if (!first)
              ds << "\n";
            first = false;
            ds << i;
          }
        }
      }

      rdata.append(ds);
    }
  } else if (prefix == "osd getmaxosd") {
    if (f) {
      f->open_object_section("getmaxosd");
      f->dump_unsigned("epoch", osdmap.get_epoch());
      f->dump_int("max_osd", osdmap.get_max_osd());
      f->close_section();
      f->flush(rdata);
    } else {
      ds << "max_osd = " << osdmap.get_max_osd() << " in epoch " << osdmap.get_epoch();
      rdata.append(ds);
    }
  } else if (prefix == "osd utilization") {
    string out;
    osdmap.summarize_mapping_stats(NULL, NULL, &out, f.get());
    if (f)
      f->flush(rdata);
    else
      rdata.append(out);
    r = 0;
    goto reply;
  } else if (prefix  == "osd find") {
    int64_t osd;
    if (!cmd_getval(cct, cmdmap, "id", osd)) {
      ss << "unable to parse osd id value '"
         << cmd_vartype_stringify(cmdmap["id"]) << "'";
      r = -EINVAL;
      goto reply;
    }
    if (!osdmap.exists(osd)) {
      ss << "osd." << osd << " does not exist";
      r = -ENOENT;
      goto reply;
    }
    string format;
    cmd_getval(cct, cmdmap, "format", format);
    boost::scoped_ptr<Formatter> f(Formatter::create(format, "json-pretty", "json-pretty"));
    f->open_object_section("osd_location");
    f->dump_int("osd", osd);
    f->dump_object("addrs", osdmap.get_addrs(osd));
    f->dump_stream("osd_fsid") << osdmap.get_uuid(osd);

    // try to identify host, pod/container name, etc.
    map<string,string> m;
    load_metadata(osd, m, nullptr);
    if (auto p = m.find("hostname"); p != m.end()) {
      f->dump_string("host", p->second);
    }
    for (auto& k : {
	"pod_name", "pod_namespace", // set by rook
	"container_name"             // set by ceph-ansible
	}) {
      if (auto p = m.find(k); p != m.end()) {
	f->dump_string(k, p->second);
      }
    }

    // crush is helpful too
    f->open_object_section("crush_location");
    map<string,string> loc = osdmap.crush->get_full_location(osd);
    for (map<string,string>::iterator p = loc.begin(); p != loc.end(); ++p)
      f->dump_string(p->first.c_str(), p->second);
    f->close_section();
    f->close_section();
    f->flush(rdata);
  } else if (prefix == "osd metadata") {
    int64_t osd = -1;
    if (cmd_vartype_stringify(cmdmap["id"]).size() &&
        !cmd_getval(cct, cmdmap, "id", osd)) {
      ss << "unable to parse osd id value '"
         << cmd_vartype_stringify(cmdmap["id"]) << "'";
      r = -EINVAL;
      goto reply;
    }
    if (osd >= 0 && !osdmap.exists(osd)) {
      ss << "osd." << osd << " does not exist";
      r = -ENOENT;
      goto reply;
    }
    string format;
    cmd_getval(cct, cmdmap, "format", format);
    boost::scoped_ptr<Formatter> f(Formatter::create(format, "json-pretty", "json-pretty"));
    if (osd >= 0) {
      f->open_object_section("osd_metadata");
      f->dump_unsigned("id", osd);
      r = dump_osd_metadata(osd, f.get(), &ss);
      if (r < 0)
        goto reply;
      f->close_section();
    } else {
      r = 0;
      f->open_array_section("osd_metadata");
      for (int i=0; i<osdmap.get_max_osd(); ++i) {
        if (osdmap.exists(i)) {
          f->open_object_section("osd");
          f->dump_unsigned("id", i);
          r = dump_osd_metadata(i, f.get(), NULL);
          if (r == -EINVAL || r == -ENOENT) {
            // Drop error, continue to get other daemons' metadata
            dout(4) << "No metadata for osd." << i << dendl;
            r = 0;
          } else if (r < 0) {
            // Unexpected error
            goto reply;
          }
          f->close_section();
        }
      }
      f->close_section();
    }
    f->flush(rdata);
  } else if (prefix == "osd versions") {
    if (!f)
      f.reset(Formatter::create("json-pretty"));
    count_metadata("ceph_version", f.get());
    f->flush(rdata);
    r = 0;
  } else if (prefix == "osd count-metadata") {
    if (!f)
      f.reset(Formatter::create("json-pretty"));
    string field;
    cmd_getval(cct, cmdmap, "property", field);
    count_metadata(field, f.get());
    f->flush(rdata);
    r = 0;
  } else if (prefix == "osd numa-status") {
    TextTable tbl;
    if (f) {
      f->open_array_section("osds");
    } else {
      tbl.define_column("OSD", TextTable::LEFT, TextTable::RIGHT);
      tbl.define_column("HOST", TextTable::LEFT, TextTable::LEFT);
      tbl.define_column("NETWORK", TextTable::RIGHT, TextTable::RIGHT);
      tbl.define_column("STORAGE", TextTable::RIGHT, TextTable::RIGHT);
      tbl.define_column("AFFINITY", TextTable::RIGHT, TextTable::RIGHT);
      tbl.define_column("CPUS", TextTable::LEFT, TextTable::LEFT);
    }
    for (int i=0; i<osdmap.get_max_osd(); ++i) {
      if (osdmap.exists(i)) {
	map<string,string> m;
	ostringstream err;
	if (load_metadata(i, m, &err) < 0) {
	  continue;
	}
	string host;
	auto p = m.find("hostname");
	if (p != m.end()) {
	  host = p->second;
	}
	if (f) {
	  f->open_object_section("osd");
	  f->dump_int("osd", i);
	  f->dump_string("host", host);
	  for (auto n : { "network_numa_node", "objectstore_numa_node",
		"numa_node" }) {
	    p = m.find(n);
	    if (p != m.end()) {
	      f->dump_int(n, atoi(p->second.c_str()));
	    }
	  }
	  for (auto n : { "network_numa_nodes", "objectstore_numa_nodes" }) {
	    p = m.find(n);
	    if (p != m.end()) {
	      list<string> ls = get_str_list(p->second, ",");
	      f->open_array_section(n);
	      for (auto node : ls) {
		f->dump_int("node", atoi(node.c_str()));
	      }
	      f->close_section();
	    }
	  }
	  for (auto n : { "numa_node_cpus" }) {
	    p = m.find(n);
	    if (p != m.end()) {
	      dump_cpu_list(f.get(), n, p->second);
	    }
	  }
	  f->close_section();
	} else {
	  tbl << i;
	  tbl << host;
	  p = m.find("network_numa_nodes");
	  if (p != m.end()) {
	    tbl << p->second;
	  } else {
	    tbl << "-";
	  }
	  p = m.find("objectstore_numa_nodes");
	  if (p != m.end()) {
	    tbl << p->second;
	  } else {
	    tbl << "-";
	  }
	  p = m.find("numa_node");
	  auto q = m.find("numa_node_cpus");
	  if (p != m.end() && q != m.end()) {
	    tbl << p->second;
	    tbl << q->second;
	  } else {
	    tbl << "-";
	    tbl << "-";
	  }
	  tbl << TextTable::endrow;
	}
      }
    }
    if (f) {
      f->close_section();
      f->flush(rdata);
    } else {
      rdata.append(stringify(tbl));
    }
  } else if (prefix == "osd map") {
    string poolstr, objstr, namespacestr;
    cmd_getval(cct, cmdmap, "pool", poolstr);
    cmd_getval(cct, cmdmap, "object", objstr);
    cmd_getval(cct, cmdmap, "nspace", namespacestr);

    int64_t pool = osdmap.lookup_pg_pool_name(poolstr.c_str());
    if (pool < 0) {
      ss << "pool " << poolstr << " does not exist";
      r = -ENOENT;
      goto reply;
    }
    object_locator_t oloc(pool, namespacestr);
    object_t oid(objstr);
    pg_t pgid = osdmap.object_locator_to_pg(oid, oloc);
    pg_t mpgid = osdmap.raw_pg_to_pg(pgid);
    vector<int> up, acting;
    int up_p, acting_p;
    osdmap.pg_to_up_acting_osds(mpgid, &up, &up_p, &acting, &acting_p);

    string fullobjname;
    if (!namespacestr.empty())
      fullobjname = namespacestr + string("/") + oid.name;
    else
      fullobjname = oid.name;
    if (f) {
      f->open_object_section("osd_map");
      f->dump_unsigned("epoch", osdmap.get_epoch());
      f->dump_string("pool", poolstr);
      f->dump_int("pool_id", pool);
      f->dump_stream("objname") << fullobjname;
      f->dump_stream("raw_pgid") << pgid;
      f->dump_stream("pgid") << mpgid;
      f->open_array_section("up");
      for (vector<int>::iterator p = up.begin(); p != up.end(); ++p)
        f->dump_int("osd", *p);
      f->close_section();
      f->dump_int("up_primary", up_p);
      f->open_array_section("acting");
      for (vector<int>::iterator p = acting.begin(); p != acting.end(); ++p)
        f->dump_int("osd", *p);
      f->close_section();
      f->dump_int("acting_primary", acting_p);
      f->close_section(); // osd_map
      f->flush(rdata);
    } else {
      ds << "osdmap e" << osdmap.get_epoch()
        << " pool '" << poolstr << "' (" << pool << ")"
        << " object '" << fullobjname << "' ->"
        << " pg " << pgid << " (" << mpgid << ")"
        << " -> up (" << pg_vector_string(up) << ", p" << up_p << ") acting ("
        << pg_vector_string(acting) << ", p" << acting_p << ")";
      rdata.append(ds);
    }

  } else if (prefix == "pg map") {
    pg_t pgid;
    string pgidstr;
    cmd_getval(cct, cmdmap, "pgid", pgidstr);
    if (!pgid.parse(pgidstr.c_str())) {
      ss << "invalid pgid '" << pgidstr << "'";
      r = -EINVAL;
      goto reply;
    }
    vector<int> up, acting;
    if (!osdmap.have_pg_pool(pgid.pool())) {
      ss << "pg '" << pgidstr << "' does not exist";
      r = -ENOENT;
      goto reply;
    }
    pg_t mpgid = osdmap.raw_pg_to_pg(pgid);
    osdmap.pg_to_up_acting_osds(pgid, up, acting);
    if (f) {
      f->open_object_section("pg_map");
      f->dump_unsigned("epoch", osdmap.get_epoch());
      f->dump_stream("raw_pgid") << pgid;
      f->dump_stream("pgid") << mpgid;
      f->open_array_section("up");
      for (auto osd : up) {
	f->dump_int("up_osd", osd);
      }
      f->close_section();
      f->open_array_section("acting");
      for (auto osd : acting) {
	f->dump_int("acting_osd", osd);
      }
      f->close_section();
      f->close_section();
      f->flush(rdata);
    } else {
      ds << "osdmap e" << osdmap.get_epoch()
         << " pg " << pgid << " (" << mpgid << ")"
         << " -> up " << up << " acting " << acting;
      rdata.append(ds);
    }
    goto reply;

  } else if (prefix == "osd lspools") {
    if (f)
      f->open_array_section("pools");
    for (map<int64_t, pg_pool_t>::iterator p = osdmap.pools.begin();
	 p != osdmap.pools.end();
	 ++p) {
      if (f) {
	f->open_object_section("pool");
	f->dump_int("poolnum", p->first);
	f->dump_string("poolname", osdmap.pool_name[p->first]);
	f->close_section();
      } else {
	ds << p->first << ' ' << osdmap.pool_name[p->first];
	if (next(p) != osdmap.pools.end()) {
	  ds << '\n';
	}
      }
    }
    if (f) {
      f->close_section();
      f->flush(ds);
    }
    rdata.append(ds);
  } else if (prefix == "osd blacklist ls") {
    if (f)
      f->open_array_section("blacklist");

    for (ceph::unordered_map<entity_addr_t,utime_t>::iterator p = osdmap.blacklist.begin();
	 p != osdmap.blacklist.end();
	 ++p) {
      if (f) {
	f->open_object_section("entry");
	f->dump_string("addr", p->first.get_legacy_str());
	f->dump_stream("until") << p->second;
	f->close_section();
      } else {
	stringstream ss;
	string s;
	ss << p->first << " " << p->second;
	getline(ss, s);
	s += "\n";
	rdata.append(s);
      }
    }
    if (f) {
      f->close_section();
      f->flush(rdata);
    }
    ss << "listed " << osdmap.blacklist.size() << " entries";

  } else if (prefix == "osd pool ls") {
    string detail;
    cmd_getval(cct, cmdmap, "detail", detail);
    if (!f && detail == "detail") {
      ostringstream ss;
      osdmap.print_pools(ss);
      rdata.append(ss.str());
    } else {
      if (f)
	f->open_array_section("pools");
      for (map<int64_t,pg_pool_t>::const_iterator it = osdmap.get_pools().begin();
	   it != osdmap.get_pools().end();
	   ++it) {
	if (f) {
	  if (detail == "detail") {
	    f->open_object_section("pool");
	    f->dump_int("pool_id", it->first);
	    f->dump_string("pool_name", osdmap.get_pool_name(it->first));
	    it->second.dump(f.get());
	    f->close_section();
	  } else {
	    f->dump_string("pool_name", osdmap.get_pool_name(it->first));
	  }
	} else {
	  rdata.append(osdmap.get_pool_name(it->first) + "\n");
	}
      }
      if (f) {
	f->close_section();
	f->flush(rdata);
      }
    }

  } else if (prefix == "osd crush get-tunable") {
    string tunable;
    cmd_getval(cct, cmdmap, "tunable", tunable);
    ostringstream rss;
    if (f)
      f->open_object_section("tunable");
    if (tunable == "straw_calc_version") {
      if (f)
	f->dump_int(tunable.c_str(), osdmap.crush->get_straw_calc_version());
      else
	rss << osdmap.crush->get_straw_calc_version() << "\n";
    } else {
      r = -EINVAL;
      goto reply;
    }
    if (f) {
      f->close_section();
      f->flush(rdata);
    } else {
      rdata.append(rss.str());
    }
    r = 0;

  } else if (prefix == "osd pool get") {
    string poolstr;
    cmd_getval(cct, cmdmap, "pool", poolstr);
    int64_t pool = osdmap.lookup_pg_pool_name(poolstr.c_str());
    if (pool < 0) {
      ss << "unrecognized pool '" << poolstr << "'";
      r = -ENOENT;
      goto reply;
    }

    const pg_pool_t *p = osdmap.get_pg_pool(pool);
    string var;
    cmd_getval(cct, cmdmap, "var", var);

    typedef std::map<std::string, osd_pool_get_choices> choices_map_t;
    const choices_map_t ALL_CHOICES = {
      {"size", SIZE},
      {"min_size", MIN_SIZE},
      {"pg_num", PG_NUM}, {"pgp_num", PGP_NUM},
      {"crush_rule", CRUSH_RULE}, {"hashpspool", HASHPSPOOL},
      {"allow_ec_overwrites", EC_OVERWRITES}, {"nodelete", NODELETE},
      {"nopgchange", NOPGCHANGE}, {"nosizechange", NOSIZECHANGE},
      {"noscrub", NOSCRUB}, {"nodeep-scrub", NODEEP_SCRUB},
      {"write_fadvise_dontneed", WRITE_FADVISE_DONTNEED},
      {"hit_set_type", HIT_SET_TYPE}, {"hit_set_period", HIT_SET_PERIOD},
      {"hit_set_count", HIT_SET_COUNT}, {"hit_set_fpp", HIT_SET_FPP},
      {"use_gmt_hitset", USE_GMT_HITSET},
      {"target_max_objects", TARGET_MAX_OBJECTS},
      {"target_max_bytes", TARGET_MAX_BYTES},
      {"cache_target_dirty_ratio", CACHE_TARGET_DIRTY_RATIO},
      {"cache_target_dirty_high_ratio", CACHE_TARGET_DIRTY_HIGH_RATIO},
      {"cache_target_full_ratio", CACHE_TARGET_FULL_RATIO},
      {"cache_min_flush_age", CACHE_MIN_FLUSH_AGE},
      {"cache_min_evict_age", CACHE_MIN_EVICT_AGE},
      {"erasure_code_profile", ERASURE_CODE_PROFILE},
      {"min_read_recency_for_promote", MIN_READ_RECENCY_FOR_PROMOTE},
      {"min_write_recency_for_promote", MIN_WRITE_RECENCY_FOR_PROMOTE},
      {"fast_read", FAST_READ},
      {"hit_set_grade_decay_rate", HIT_SET_GRADE_DECAY_RATE},
      {"hit_set_search_last_n", HIT_SET_SEARCH_LAST_N},
      {"scrub_min_interval", SCRUB_MIN_INTERVAL},
      {"scrub_max_interval", SCRUB_MAX_INTERVAL},
      {"deep_scrub_interval", DEEP_SCRUB_INTERVAL},
      {"recovery_priority", RECOVERY_PRIORITY},
      {"recovery_op_priority", RECOVERY_OP_PRIORITY},
      {"scrub_priority", SCRUB_PRIORITY},
      {"compression_mode", COMPRESSION_MODE},
      {"compression_algorithm", COMPRESSION_ALGORITHM},
      {"compression_required_ratio", COMPRESSION_REQUIRED_RATIO},
      {"compression_max_blob_size", COMPRESSION_MAX_BLOB_SIZE},
      {"compression_min_blob_size", COMPRESSION_MIN_BLOB_SIZE},
      {"csum_type", CSUM_TYPE},
      {"csum_max_block", CSUM_MAX_BLOCK},
      {"csum_min_block", CSUM_MIN_BLOCK},
      {"fingerprint_algorithm", FINGERPRINT_ALGORITHM},
      {"pg_autoscale_mode", PG_AUTOSCALE_MODE},
      {"pg_num_min", PG_NUM_MIN},
      {"target_size_bytes", TARGET_SIZE_BYTES},
      {"target_size_ratio", TARGET_SIZE_RATIO},
      {"pg_autoscale_bias", PG_AUTOSCALE_BIAS},
    };

    typedef std::set<osd_pool_get_choices> choices_set_t;

    const choices_set_t ONLY_TIER_CHOICES = {
      HIT_SET_TYPE, HIT_SET_PERIOD, HIT_SET_COUNT, HIT_SET_FPP,
      TARGET_MAX_OBJECTS, TARGET_MAX_BYTES, CACHE_TARGET_FULL_RATIO,
      CACHE_TARGET_DIRTY_RATIO, CACHE_TARGET_DIRTY_HIGH_RATIO,
      CACHE_MIN_FLUSH_AGE, CACHE_MIN_EVICT_AGE,
      MIN_READ_RECENCY_FOR_PROMOTE,
      MIN_WRITE_RECENCY_FOR_PROMOTE,
      HIT_SET_GRADE_DECAY_RATE, HIT_SET_SEARCH_LAST_N
    };
    const choices_set_t ONLY_ERASURE_CHOICES = {
      EC_OVERWRITES, ERASURE_CODE_PROFILE
    };

    choices_set_t selected_choices;
    if (var == "all") {
      for(choices_map_t::const_iterator it = ALL_CHOICES.begin();
	  it != ALL_CHOICES.end(); ++it) {
	selected_choices.insert(it->second);
      }

      if(!p->is_tier()) {
	selected_choices = subtract_second_from_first(selected_choices,
						      ONLY_TIER_CHOICES);
      }

      if(!p->is_erasure()) {
	selected_choices = subtract_second_from_first(selected_choices,
						      ONLY_ERASURE_CHOICES);
      }
    } else /* var != "all" */  {
      choices_map_t::const_iterator found = ALL_CHOICES.find(var);
      osd_pool_get_choices selected = found->second;

      if (!p->is_tier() &&
	  ONLY_TIER_CHOICES.find(selected) != ONLY_TIER_CHOICES.end()) {
	ss << "pool '" << poolstr
	   << "' is not a tier pool: variable not applicable";
	r = -EACCES;
	goto reply;
      }

      if (!p->is_erasure() &&
	  ONLY_ERASURE_CHOICES.find(selected)
	  != ONLY_ERASURE_CHOICES.end()) {
	ss << "pool '" << poolstr
	   << "' is not a erasure pool: variable not applicable";
	r = -EACCES;
	goto reply;
      }

      if (pool_opts_t::is_opt_name(var) &&
	  !p->opts.is_set(pool_opts_t::get_opt_desc(var).key)) {
	ss << "option '" << var << "' is not set on pool '" << poolstr << "'";
	r = -ENOENT;
	goto reply;
      }

      selected_choices.insert(selected);
    }

    if (f) {
      f->open_object_section("pool");
      f->dump_string("pool", poolstr);
      f->dump_int("pool_id", pool);
      for(choices_set_t::const_iterator it = selected_choices.begin();
	  it != selected_choices.end(); ++it) {
	choices_map_t::const_iterator i;
        for (i = ALL_CHOICES.begin(); i != ALL_CHOICES.end(); ++i) {
          if (i->second == *it) {
            break;
          }
        }
        ceph_assert(i != ALL_CHOICES.end());
	switch(*it) {
	  case PG_NUM:
	    f->dump_int("pg_num", p->get_pg_num());
	    break;
	  case PGP_NUM:
	    f->dump_int("pgp_num", p->get_pgp_num());
	    break;
	  case SIZE:
	    f->dump_int("size", p->get_size());
	    break;
	  case MIN_SIZE:
	    f->dump_int("min_size", p->get_min_size());
	    break;
	  case CRUSH_RULE:
	    if (osdmap.crush->rule_exists(p->get_crush_rule())) {
	      f->dump_string("crush_rule", osdmap.crush->get_rule_name(
			       p->get_crush_rule()));
	    } else {
	      f->dump_string("crush_rule", stringify(p->get_crush_rule()));
	    }
	    break;
	  case EC_OVERWRITES:
	    f->dump_bool("allow_ec_overwrites",
                         p->has_flag(pg_pool_t::FLAG_EC_OVERWRITES));
	    break;
	  case PG_AUTOSCALE_MODE:
	    f->dump_string("pg_autoscale_mode",
			   pg_pool_t::get_pg_autoscale_mode_name(
			     p->pg_autoscale_mode));
	    break;
	  case HASHPSPOOL:
	  case NODELETE:
	  case NOPGCHANGE:
	  case NOSIZECHANGE:
	  case WRITE_FADVISE_DONTNEED:
	  case NOSCRUB:
	  case NODEEP_SCRUB:
	    f->dump_bool(i->first.c_str(),
			   p->has_flag(pg_pool_t::get_flag_by_name(i->first)));
	    break;
	  case HIT_SET_PERIOD:
	    f->dump_int("hit_set_period", p->hit_set_period);
	    break;
	  case HIT_SET_COUNT:
	    f->dump_int("hit_set_count", p->hit_set_count);
	    break;
	  case HIT_SET_TYPE:
	    f->dump_string("hit_set_type",
			   HitSet::get_type_name(p->hit_set_params.get_type()));
	    break;
	  case HIT_SET_FPP:
	    {
	      if (p->hit_set_params.get_type() == HitSet::TYPE_BLOOM) {
		BloomHitSet::Params *bloomp =
		  static_cast<BloomHitSet::Params*>(p->hit_set_params.impl.get());
		f->dump_float("hit_set_fpp", bloomp->get_fpp());
	      } else if(var != "all") {
		f->close_section();
		ss << "hit set is not of type Bloom; " <<
		  "invalid to get a false positive rate!";
		r = -EINVAL;
		goto reply;
	      }
	    }
	    break;
	  case USE_GMT_HITSET:
	    f->dump_bool("use_gmt_hitset", p->use_gmt_hitset);
	    break;
	  case TARGET_MAX_OBJECTS:
	    f->dump_unsigned("target_max_objects", p->target_max_objects);
	    break;
	  case TARGET_MAX_BYTES:
	    f->dump_unsigned("target_max_bytes", p->target_max_bytes);
	    break;
	  case CACHE_TARGET_DIRTY_RATIO:
	    f->dump_unsigned("cache_target_dirty_ratio_micro",
			     p->cache_target_dirty_ratio_micro);
	    f->dump_float("cache_target_dirty_ratio",
			  ((float)p->cache_target_dirty_ratio_micro/1000000));
	    break;
	  case CACHE_TARGET_DIRTY_HIGH_RATIO:
	    f->dump_unsigned("cache_target_dirty_high_ratio_micro",
			     p->cache_target_dirty_high_ratio_micro);
	    f->dump_float("cache_target_dirty_high_ratio",
			  ((float)p->cache_target_dirty_high_ratio_micro/1000000));
	    break;
	  case CACHE_TARGET_FULL_RATIO:
	    f->dump_unsigned("cache_target_full_ratio_micro",
			     p->cache_target_full_ratio_micro);
	    f->dump_float("cache_target_full_ratio",
			  ((float)p->cache_target_full_ratio_micro/1000000));
	    break;
	  case CACHE_MIN_FLUSH_AGE:
	    f->dump_unsigned("cache_min_flush_age", p->cache_min_flush_age);
	    break;
	  case CACHE_MIN_EVICT_AGE:
	    f->dump_unsigned("cache_min_evict_age", p->cache_min_evict_age);
	    break;
	  case ERASURE_CODE_PROFILE:
	    f->dump_string("erasure_code_profile", p->erasure_code_profile);
	    break;
	  case MIN_READ_RECENCY_FOR_PROMOTE:
	    f->dump_int("min_read_recency_for_promote",
			p->min_read_recency_for_promote);
	    break;
	  case MIN_WRITE_RECENCY_FOR_PROMOTE:
	    f->dump_int("min_write_recency_for_promote",
			p->min_write_recency_for_promote);
	    break;
          case FAST_READ:
            f->dump_int("fast_read", p->fast_read);
            break;
	  case HIT_SET_GRADE_DECAY_RATE:
	    f->dump_int("hit_set_grade_decay_rate",
			p->hit_set_grade_decay_rate);
	    break;
	  case HIT_SET_SEARCH_LAST_N:
	    f->dump_int("hit_set_search_last_n",
			p->hit_set_search_last_n);
	    break;
	  case SCRUB_MIN_INTERVAL:
	  case SCRUB_MAX_INTERVAL:
	  case DEEP_SCRUB_INTERVAL:
          case RECOVERY_PRIORITY:
          case RECOVERY_OP_PRIORITY:
          case SCRUB_PRIORITY:
	  case COMPRESSION_MODE:
	  case COMPRESSION_ALGORITHM:
	  case COMPRESSION_REQUIRED_RATIO:
	  case COMPRESSION_MAX_BLOB_SIZE:
	  case COMPRESSION_MIN_BLOB_SIZE:
	  case CSUM_TYPE:
	  case CSUM_MAX_BLOCK:
	  case CSUM_MIN_BLOCK:
	  case FINGERPRINT_ALGORITHM:
	  case PG_NUM_MIN:
	  case TARGET_SIZE_BYTES:
	  case TARGET_SIZE_RATIO:
	  case PG_AUTOSCALE_BIAS:
            pool_opts_t::key_t key = pool_opts_t::get_opt_desc(i->first).key;
            if (p->opts.is_set(key)) {
              if(*it == CSUM_TYPE) {
                int64_t val;
                p->opts.get(pool_opts_t::CSUM_TYPE, &val);
                f->dump_string(i->first.c_str(), Checksummer::get_csum_type_string(val));
              } else {
                p->opts.dump(i->first, f.get());
              }
	    }
            break;
	}
      }
      f->close_section();
      f->flush(rdata);
    } else /* !f */ {
      for(choices_set_t::const_iterator it = selected_choices.begin();
	  it != selected_choices.end(); ++it) {
	choices_map_t::const_iterator i;
	switch(*it) {
	  case PG_NUM:
	    ss << "pg_num: " << p->get_pg_num() << "\n";
	    break;
	  case PGP_NUM:
	    ss << "pgp_num: " << p->get_pgp_num() << "\n";
	    break;
	  case SIZE:
	    ss << "size: " << p->get_size() << "\n";
	    break;
	  case MIN_SIZE:
	    ss << "min_size: " << p->get_min_size() << "\n";
	    break;
	  case CRUSH_RULE:
	    if (osdmap.crush->rule_exists(p->get_crush_rule())) {
	      ss << "crush_rule: " << osdmap.crush->get_rule_name(
		p->get_crush_rule()) << "\n";
	    } else {
	      ss << "crush_rule: " << p->get_crush_rule() << "\n";
	    }
	    break;
	  case PG_AUTOSCALE_MODE:
	    ss << "pg_autoscale_mode: " << pg_pool_t::get_pg_autoscale_mode_name(
	      p->pg_autoscale_mode) <<"\n";
	    break;
	  case HIT_SET_PERIOD:
	    ss << "hit_set_period: " << p->hit_set_period << "\n";
	    break;
	  case HIT_SET_COUNT:
	    ss << "hit_set_count: " << p->hit_set_count << "\n";
	    break;
	  case HIT_SET_TYPE:
	    ss << "hit_set_type: " <<
	      HitSet::get_type_name(p->hit_set_params.get_type()) << "\n";
	    break;
	  case HIT_SET_FPP:
	    {
	      if (p->hit_set_params.get_type() == HitSet::TYPE_BLOOM) {
		BloomHitSet::Params *bloomp =
		  static_cast<BloomHitSet::Params*>(p->hit_set_params.impl.get());
		ss << "hit_set_fpp: " << bloomp->get_fpp() << "\n";
	      } else if(var != "all") {
		ss << "hit set is not of type Bloom; " <<
		  "invalid to get a false positive rate!";
		r = -EINVAL;
		goto reply;
	      }
	    }
	    break;
	  case USE_GMT_HITSET:
	    ss << "use_gmt_hitset: " << p->use_gmt_hitset << "\n";
	    break;
	  case TARGET_MAX_OBJECTS:
	    ss << "target_max_objects: " << p->target_max_objects << "\n";
	    break;
	  case TARGET_MAX_BYTES:
	    ss << "target_max_bytes: " << p->target_max_bytes << "\n";
	    break;
	  case CACHE_TARGET_DIRTY_RATIO:
	    ss << "cache_target_dirty_ratio: "
	       << ((float)p->cache_target_dirty_ratio_micro/1000000) << "\n";
	    break;
	  case CACHE_TARGET_DIRTY_HIGH_RATIO:
	    ss << "cache_target_dirty_high_ratio: "
	       << ((float)p->cache_target_dirty_high_ratio_micro/1000000) << "\n";
	    break;
	  case CACHE_TARGET_FULL_RATIO:
	    ss << "cache_target_full_ratio: "
	       << ((float)p->cache_target_full_ratio_micro/1000000) << "\n";
	    break;
	  case CACHE_MIN_FLUSH_AGE:
	    ss << "cache_min_flush_age: " << p->cache_min_flush_age << "\n";
	    break;
	  case CACHE_MIN_EVICT_AGE:
	    ss << "cache_min_evict_age: " << p->cache_min_evict_age << "\n";
	    break;
	  case ERASURE_CODE_PROFILE:
	    ss << "erasure_code_profile: " << p->erasure_code_profile << "\n";
	    break;
	  case MIN_READ_RECENCY_FOR_PROMOTE:
	    ss << "min_read_recency_for_promote: " <<
	      p->min_read_recency_for_promote << "\n";
	    break;
	  case HIT_SET_GRADE_DECAY_RATE:
	    ss << "hit_set_grade_decay_rate: " <<
	      p->hit_set_grade_decay_rate << "\n";
	    break;
	  case HIT_SET_SEARCH_LAST_N:
	    ss << "hit_set_search_last_n: " <<
	      p->hit_set_search_last_n << "\n";
	    break;
	  case EC_OVERWRITES:
	    ss << "allow_ec_overwrites: " <<
	      (p->has_flag(pg_pool_t::FLAG_EC_OVERWRITES) ? "true" : "false") <<
	      "\n";
	    break;
	  case HASHPSPOOL:
	  case NODELETE:
	  case NOPGCHANGE:
	  case NOSIZECHANGE:
	  case WRITE_FADVISE_DONTNEED:
	  case NOSCRUB:
	  case NODEEP_SCRUB:
	    for (i = ALL_CHOICES.begin(); i != ALL_CHOICES.end(); ++i) {
	      if (i->second == *it)
		break;
	    }
	    ceph_assert(i != ALL_CHOICES.end());
	    ss << i->first << ": " <<
	      (p->has_flag(pg_pool_t::get_flag_by_name(i->first)) ?
	       "true" : "false") << "\n";
	    break;
	  case MIN_WRITE_RECENCY_FOR_PROMOTE:
	    ss << "min_write_recency_for_promote: " <<
	      p->min_write_recency_for_promote << "\n";
	    break;
          case FAST_READ:
            ss << "fast_read: " << p->fast_read << "\n";
            break;
	  case SCRUB_MIN_INTERVAL:
	  case SCRUB_MAX_INTERVAL:
	  case DEEP_SCRUB_INTERVAL:
          case RECOVERY_PRIORITY:
          case RECOVERY_OP_PRIORITY:
          case SCRUB_PRIORITY:
	  case COMPRESSION_MODE:
	  case COMPRESSION_ALGORITHM:
	  case COMPRESSION_REQUIRED_RATIO:
	  case COMPRESSION_MAX_BLOB_SIZE:
	  case COMPRESSION_MIN_BLOB_SIZE:
	  case CSUM_TYPE:
	  case CSUM_MAX_BLOCK:
	  case CSUM_MIN_BLOCK:
	  case FINGERPRINT_ALGORITHM:
	  case PG_NUM_MIN:
	  case TARGET_SIZE_BYTES:
	  case TARGET_SIZE_RATIO:
	  case PG_AUTOSCALE_BIAS:
	    for (i = ALL_CHOICES.begin(); i != ALL_CHOICES.end(); ++i) {
	      if (i->second == *it)
		break;
	    }
	    ceph_assert(i != ALL_CHOICES.end());
	    {
	      pool_opts_t::key_t key = pool_opts_t::get_opt_desc(i->first).key;
	      if (p->opts.is_set(key)) {
                if(key == pool_opts_t::CSUM_TYPE) {
                  int64_t val;
                  p->opts.get(key, &val);
  		  ss << i->first << ": " << Checksummer::get_csum_type_string(val) << "\n";
                } else {
  		  ss << i->first << ": " << p->opts.get(key) << "\n";
                }
	      }
	    }
	    break;
	}
	rdata.append(ss.str());
	ss.str("");
      }
    }
    r = 0;
  } else if (prefix == "osd pool get-quota") {
    string pool_name;
    cmd_getval(cct, cmdmap, "pool", pool_name);

    int64_t poolid = osdmap.lookup_pg_pool_name(pool_name);
    if (poolid < 0) {
      ceph_assert(poolid == -ENOENT);
      ss << "unrecognized pool '" << pool_name << "'";
      r = -ENOENT;
      goto reply;
    }
    const pg_pool_t *p = osdmap.get_pg_pool(poolid);

    if (f) {
      f->open_object_section("pool_quotas");
      f->dump_string("pool_name", pool_name);
      f->dump_unsigned("pool_id", poolid);
      f->dump_unsigned("quota_max_objects", p->quota_max_objects);
      f->dump_unsigned("quota_max_bytes", p->quota_max_bytes);
      f->close_section();
      f->flush(rdata);
    } else {
      stringstream rs;
      rs << "quotas for pool '" << pool_name << "':\n"
         << "  max objects: ";
      if (p->quota_max_objects == 0)
        rs << "N/A";
      else
        rs << si_u_t(p->quota_max_objects) << " objects";
      rs << "\n"
         << "  max bytes  : ";
      if (p->quota_max_bytes == 0)
        rs << "N/A";
      else
        rs << byte_u_t(p->quota_max_bytes);
      rdata.append(rs.str());
    }
    rdata.append("\n");
    r = 0;
  } else if (prefix == "osd crush rule list" ||
	     prefix == "osd crush rule ls") {
    if (f) {
      f->open_array_section("rules");
      osdmap.crush->list_rules(f.get());
      f->close_section();
      f->flush(rdata);
    } else {
      ostringstream ss;
      osdmap.crush->list_rules(&ss);
      rdata.append(ss.str());
    }
  } else if (prefix == "osd crush rule ls-by-class") {
    string class_name;
    cmd_getval(cct, cmdmap, "class", class_name);
    if (class_name.empty()) {
      ss << "no class specified";
      r = -EINVAL;
      goto reply;
    }
    set<int> rules;
    r = osdmap.crush->get_rules_by_class(class_name, &rules);
    if (r < 0) {
      ss << "failed to get rules by class '" << class_name << "'";
      goto reply;
    }
    if (f) {
      f->open_array_section("rules");
      for (auto &rule: rules) {
        f->dump_string("name", osdmap.crush->get_rule_name(rule));
      }
      f->close_section();
      f->flush(rdata);
    } else {
      ostringstream rs;
      for (auto &rule: rules) {
        rs << osdmap.crush->get_rule_name(rule) << "\n";
      }
      rdata.append(rs.str());
    }
  } else if (prefix == "osd crush rule dump") {
    string name;
    cmd_getval(cct, cmdmap, "name", name);
    string format;
    cmd_getval(cct, cmdmap, "format", format);
    boost::scoped_ptr<Formatter> f(Formatter::create(format, "json-pretty", "json-pretty"));
    if (name == "") {
      f->open_array_section("rules");
      osdmap.crush->dump_rules(f.get());
      f->close_section();
    } else {
      int ruleno = osdmap.crush->get_rule_id(name);
      if (ruleno < 0) {
	ss << "unknown crush rule '" << name << "'";
	r = ruleno;
	goto reply;
      }
      osdmap.crush->dump_rule(ruleno, f.get());
    }
    ostringstream rs;
    f->flush(rs);
    rs << "\n";
    rdata.append(rs.str());
  } else if (prefix == "osd crush dump") {
    string format;
    cmd_getval(cct, cmdmap, "format", format);
    boost::scoped_ptr<Formatter> f(Formatter::create(format, "json-pretty", "json-pretty"));
    f->open_object_section("crush_map");
    osdmap.crush->dump(f.get());
    f->close_section();
    ostringstream rs;
    f->flush(rs);
    rs << "\n";
    rdata.append(rs.str());
  } else if (prefix == "osd crush show-tunables") {
    string format;
    cmd_getval(cct, cmdmap, "format", format);
    boost::scoped_ptr<Formatter> f(Formatter::create(format, "json-pretty", "json-pretty"));
    f->open_object_section("crush_map_tunables");
    osdmap.crush->dump_tunables(f.get());
    f->close_section();
    ostringstream rs;
    f->flush(rs);
    rs << "\n";
    rdata.append(rs.str());
  } else if (prefix == "osd crush tree") {
    string shadow;
    cmd_getval(cct, cmdmap, "shadow", shadow);
    bool show_shadow = shadow == "--show-shadow";
    boost::scoped_ptr<Formatter> f(Formatter::create(format));
    if (f) {
      f->open_object_section("crush_tree");
      osdmap.crush->dump_tree(nullptr,
                              f.get(),
                              osdmap.get_pool_names(),
                              show_shadow);
      f->close_section();
      f->flush(rdata);
    } else {
      ostringstream ss;
      osdmap.crush->dump_tree(&ss,
                              nullptr,
                              osdmap.get_pool_names(),
                              show_shadow);
      rdata.append(ss.str());
    }
  } else if (prefix == "osd crush ls") {
    string name;
    if (!cmd_getval(cct, cmdmap, "node", name)) {
      ss << "no node specified";
      r = -EINVAL;
      goto reply;
    }
    if (!osdmap.crush->name_exists(name)) {
      ss << "node '" << name << "' does not exist";
      r = -ENOENT;
      goto reply;
    }
    int id = osdmap.crush->get_item_id(name);
    list<int> result;
    if (id >= 0) {
      result.push_back(id);
    } else {
      int num = osdmap.crush->get_bucket_size(id);
      for (int i = 0; i < num; ++i) {
	result.push_back(osdmap.crush->get_bucket_item(id, i));
      }
    }
    if (f) {
      f->open_array_section("items");
      for (auto i : result) {
	f->dump_string("item", osdmap.crush->get_item_name(i));
      }
      f->close_section();
      f->flush(rdata);
    } else {
      ostringstream ss;
      for (auto i : result) {
	ss << osdmap.crush->get_item_name(i) << "\n";
      }
      rdata.append(ss.str());
    }
    r = 0;
  } else if (prefix == "osd crush class ls") {
    boost::scoped_ptr<Formatter> f(Formatter::create(format, "json-pretty", "json-pretty"));
    f->open_array_section("crush_classes");
    for (auto i : osdmap.crush->class_name)
      f->dump_string("class", i.second);
    f->close_section();
    f->flush(rdata);
  } else if (prefix == "osd crush class ls-osd") {
    string name;
    cmd_getval(cct, cmdmap, "class", name);
    set<int> osds;
    osdmap.crush->get_devices_by_class(name, &osds);
    if (f) {
      f->open_array_section("osds");
      for (auto &osd: osds)
        f->dump_int("osd", osd);
      f->close_section();
      f->flush(rdata);
    } else {
      bool first = true;
      for (auto &osd : osds) {
        if (!first)
          ds << "\n";
        first = false;
        ds << osd;
      }
      rdata.append(ds);
    }
  } else if (prefix == "osd crush get-device-class") {
    vector<string> idvec;
    cmd_getval(cct, cmdmap, "ids", idvec);
    map<int, string> class_by_osd;
    for (auto& id : idvec) {
      ostringstream ts;
      long osd = parse_osd_id(id.c_str(), &ts);
      if (osd < 0) {
        ss << "unable to parse osd id:'" << id << "'";
        r = -EINVAL;
        goto reply;
      }
      auto device_class = osdmap.crush->get_item_class(osd);
      if (device_class)
        class_by_osd[osd] = device_class;
      else
        class_by_osd[osd] = ""; // no class
    }
    if (f) {
      f->open_array_section("osd_device_classes");
      for (auto& i : class_by_osd) {
        f->open_object_section("osd_device_class");
        f->dump_int("osd", i.first);
        f->dump_string("device_class", i.second);
        f->close_section();
      }
      f->close_section();
      f->flush(rdata);
    } else {
      if (class_by_osd.size() == 1) {
        // for single input, make a clean output
        ds << class_by_osd.begin()->second;
      } else {
        // note that we do not group osds by class here
        for (auto it = class_by_osd.begin();
             it != class_by_osd.end();
             it++) {
          ds << "osd." << it->first << ' ' << it->second;
          if (next(it) != class_by_osd.end())
            ds << '\n';
        }
      }
      rdata.append(ds);
    }
  } else if (prefix == "osd erasure-code-profile ls") {
    const auto &profiles = osdmap.get_erasure_code_profiles();
    if (f)
      f->open_array_section("erasure-code-profiles");
    for (auto i = profiles.begin(); i != profiles.end(); ++i) {
      if (f)
        f->dump_string("profile", i->first.c_str());
      else
	rdata.append(i->first + "\n");
    }
    if (f) {
      f->close_section();
      ostringstream rs;
      f->flush(rs);
      rs << "\n";
      rdata.append(rs.str());
    }
  } else if (prefix == "osd crush weight-set ls") {
    boost::scoped_ptr<Formatter> f(Formatter::create(format));
    if (f) {
      f->open_array_section("weight_sets");
      if (osdmap.crush->have_choose_args(CrushWrapper::DEFAULT_CHOOSE_ARGS)) {
	f->dump_string("pool", "(compat)");
      }
      for (auto& i : osdmap.crush->choose_args) {
	if (i.first >= 0) {
	  f->dump_string("pool", osdmap.get_pool_name(i.first));
	}
      }
      f->close_section();
      f->flush(rdata);
    } else {
      ostringstream rs;
      if (osdmap.crush->have_choose_args(CrushWrapper::DEFAULT_CHOOSE_ARGS)) {
	rs << "(compat)\n";
      }
      for (auto& i : osdmap.crush->choose_args) {
	if (i.first >= 0) {
	  rs << osdmap.get_pool_name(i.first) << "\n";
	}
      }
      rdata.append(rs.str());
    }
  } else if (prefix == "osd crush weight-set dump") {
    boost::scoped_ptr<Formatter> f(Formatter::create(format, "json-pretty",
						     "json-pretty"));
    osdmap.crush->dump_choose_args(f.get());
    f->flush(rdata);
  } else if (prefix == "osd erasure-code-profile get") {
    string name;
    cmd_getval(cct, cmdmap, "name", name);
    if (!osdmap.has_erasure_code_profile(name)) {
      ss << "unknown erasure code profile '" << name << "'";
      r = -ENOENT;
      goto reply;
    }
    const map<string,string> &profile = osdmap.get_erasure_code_profile(name);
    if (f)
      f->open_object_section("profile");
    for (map<string,string>::const_iterator i = profile.begin();
	 i != profile.end();
	 ++i) {
      if (f)
        f->dump_string(i->first.c_str(), i->second.c_str());
      else
	rdata.append(i->first + "=" + i->second + "\n");
    }
    if (f) {
      f->close_section();
      ostringstream rs;
      f->flush(rs);
      rs << "\n";
      rdata.append(rs.str());
    }
  } else if (prefix == "osd pool application get") {
    boost::scoped_ptr<Formatter> f(Formatter::create(format, "json-pretty",
                                                     "json-pretty"));
    string pool_name;
    cmd_getval(cct, cmdmap, "pool", pool_name);
    string app;
    cmd_getval(cct, cmdmap, "app", app);
    string key;
    cmd_getval(cct, cmdmap, "key", key);

    if (pool_name.empty()) {
      // all
      f->open_object_section("pools");
      for (const auto &pool : osdmap.pools) {
        std::string name("<unknown>");
        const auto &pni = osdmap.pool_name.find(pool.first);
        if (pni != osdmap.pool_name.end())
          name = pni->second;
        f->open_object_section(name.c_str());
        for (auto &app_pair : pool.second.application_metadata) {
          f->open_object_section(app_pair.first.c_str());
          for (auto &kv_pair : app_pair.second) {
            f->dump_string(kv_pair.first.c_str(), kv_pair.second);
          }
          f->close_section();
        }
        f->close_section(); // name
      }
      f->close_section(); // pools
      f->flush(rdata);
    } else {
      int64_t pool = osdmap.lookup_pg_pool_name(pool_name.c_str());
      if (pool < 0) {
        ss << "unrecognized pool '" << pool_name << "'";
        r = -ENOENT;
        goto reply;
      }
      auto p = osdmap.get_pg_pool(pool);
      // filter by pool
      if (app.empty()) {
        f->open_object_section(pool_name.c_str());
        for (auto &app_pair : p->application_metadata) {
          f->open_object_section(app_pair.first.c_str());
          for (auto &kv_pair : app_pair.second) {
            f->dump_string(kv_pair.first.c_str(), kv_pair.second);
          }
          f->close_section(); // application
        }
        f->close_section(); // pool_name
        f->flush(rdata);
        goto reply;
      }

      auto app_it = p->application_metadata.find(app);
      if (app_it == p->application_metadata.end()) {
        ss << "pool '" << pool_name << "' has no application '" << app << "'";
        r = -ENOENT;
        goto reply;
      }
      // filter by pool + app
      if (key.empty()) {
        f->open_object_section(app_it->first.c_str());
        for (auto &kv_pair : app_it->second) {
          f->dump_string(kv_pair.first.c_str(), kv_pair.second);
        }
        f->close_section(); // application
        f->flush(rdata);
        goto reply;
      }
      // filter by pool + app + key
      auto key_it = app_it->second.find(key);
      if (key_it == app_it->second.end()) {
        ss << "application '" << app << "' on pool '" << pool_name
           << "' does not have key '" << key << "'";
        r = -ENOENT;
        goto reply;
      }
      ss << key_it->second << "\n";
      rdata.append(ss.str());
      ss.str("");
    }
  } else if (prefix == "osd get-require-min-compat-client") {
    ss << ceph_release_name(osdmap.require_min_compat_client) << std::endl;
    rdata.append(ss.str());
    ss.str("");
    goto reply;
  } else if (prefix == "osd pool application enable" ||
             prefix == "osd pool application disable" ||
             prefix == "osd pool application set" ||
             prefix == "osd pool application rm") {
    bool changed = false;
    r = preprocess_command_pool_application(prefix, cmdmap, ss, &changed);
    if (r != 0) {
      // Error, reply.
      goto reply;
    } else if (changed) {
      // Valid mutation, proceed to prepare phase
      return false;
    } else {
      // Idempotent case, reply
      goto reply;
    }
  } else {
    // try prepare update
    return false;
  }

 reply:
  string rs;
  getline(ss, rs);
  mon->reply_command(op, r, rs, rdata, get_last_committed());
  return true;
}

void OSDMonitor::set_pool_flags(int64_t pool_id, uint64_t flags)
{
  pg_pool_t *pool = pending_inc.get_new_pool(pool_id,
    osdmap.get_pg_pool(pool_id));
  ceph_assert(pool);
  pool->set_flag(flags);
}

void OSDMonitor::clear_pool_flags(int64_t pool_id, uint64_t flags)
{
  pg_pool_t *pool = pending_inc.get_new_pool(pool_id,
    osdmap.get_pg_pool(pool_id));
  ceph_assert(pool);
  pool->unset_flag(flags);
}

string OSDMonitor::make_snap_epoch_key(int64_t pool, epoch_t epoch)
{
  char k[80];
  snprintf(k, sizeof(k), "removed_epoch_%llu_%08lx",
	   (unsigned long long)pool, (unsigned long)epoch);
  return k;
}

string OSDMonitor::make_snap_key(int64_t pool, snapid_t snap)
{
  char k[80];
  snprintf(k, sizeof(k), "removed_snap_%llu_%016llx",
	   (unsigned long long)pool, (unsigned long long)snap);
  return k;
}


string OSDMonitor::make_snap_key_value(
  int64_t pool, snapid_t snap, snapid_t num,
  epoch_t epoch, bufferlist *v)
{
  // encode the *last* epoch in the key so that we can use forward
  // iteration only to search for an epoch in an interval.
  encode(snap, *v);
  encode(snap + num, *v);
  encode(epoch, *v);
  return make_snap_key(pool, snap + num - 1);
}

string OSDMonitor::make_snap_purged_key(int64_t pool, snapid_t snap)
{
  char k[80];
  snprintf(k, sizeof(k), "purged_snap_%llu_%016llx",
	   (unsigned long long)pool, (unsigned long long)snap);
  return k;
}
string OSDMonitor::make_snap_purged_key_value(
  int64_t pool, snapid_t snap, snapid_t num,
  epoch_t epoch, bufferlist *v)
{
  // encode the *last* epoch in the key so that we can use forward
  // iteration only to search for an epoch in an interval.
  encode(snap, *v);
  encode(snap + num, *v);
  encode(epoch, *v);
  return make_snap_purged_key(pool, snap + num - 1);
}

int OSDMonitor::lookup_pruned_snap(int64_t pool, snapid_t snap,
				   snapid_t *begin, snapid_t *end)
{
  string k = make_snap_key(pool, snap);
  auto it = mon->store->get_iterator(OSD_SNAP_PREFIX);
  it->lower_bound(k);
  if (!it->valid()) {
    return -ENOENT;
  }
  if (it->key().find(OSD_SNAP_PREFIX) != 0) {
    return -ENOENT;
  }
  bufferlist v = it->value();
  auto p = v.cbegin();
  decode(*begin, p);
  decode(*end, p);
  if (snap < *begin || snap >= *end) {
    return -ENOENT;
  }
  return 0;
}

bool OSDMonitor::try_prune_purged_snaps()
{
  if (!mon->mgrstatmon()->is_readable()) {
    return false;
  }
  if (osdmap.require_osd_release < CEPH_RELEASE_MIMIC) {
    return false;
  }
  if (!pending_inc.new_purged_snaps.empty()) {
    return false;  // we already pruned for this epoch
  }

  unsigned max_prune = cct->_conf.get_val<uint64_t>(
    "mon_max_snap_prune_per_epoch");
  if (!max_prune) {
    max_prune = 100000;
  }
  dout(10) << __func__ << " max_prune " << max_prune << dendl;

  unsigned actually_pruned = 0;
  auto& purged_snaps = mon->mgrstatmon()->get_digest().purged_snaps;
  for (auto& p : osdmap.get_pools()) {
    auto q = purged_snaps.find(p.first);
    if (q == purged_snaps.end()) {
      continue;
    }
    auto& purged = q->second;
    if (purged.empty()) {
      dout(20) << __func__ << " " << p.first << " nothing purged" << dendl;
      continue;
    }
    dout(20) << __func__ << " pool " << p.first << " purged " << purged << dendl;
    OSDMap::snap_interval_set_t to_prune;
    unsigned maybe_pruned = actually_pruned;
    for (auto i = purged.begin(); i != purged.end(); ++i) {
      snapid_t begin = i.get_start();
      auto end = i.get_start() + i.get_len();
      snapid_t pbegin = 0, pend = 0;
      int r = lookup_pruned_snap(p.first, begin, &pbegin, &pend);
      if (r == 0) {
	// already purged.
	// be a bit aggressive about backing off here, because the mon may
	// do a lot of work going through this set, and if we know the
	// purged set from the OSDs is at least *partly* stale we may as
	// well wait for it to be fresh.
	dout(20) << __func__ << "  we've already pruned " << pbegin
		 << "~" << (pend - pbegin) << dendl;
	break;  // next pool
      }
      if (pbegin && pbegin < end) {
	// the tail of [begin,end) is purged; shorten the range
	ceph_assert(pbegin > begin);
	end = pbegin;
      }
      to_prune.insert(begin, end - begin);
      maybe_pruned += end - begin;
      if (maybe_pruned >= max_prune) {
	break;
      }
    }
    if (!to_prune.empty()) {
      // PGs may still be reporting things as purged that we have already
      // pruned from removed_snaps_queue.
      OSDMap::snap_interval_set_t actual;
      auto r = osdmap.removed_snaps_queue.find(p.first);
      if (r != osdmap.removed_snaps_queue.end()) {
	actual.intersection_of(to_prune, r->second);
      }
      actually_pruned += actual.size();
      dout(10) << __func__ << " pool " << p.first << " reports pruned " << to_prune
	       << ", actual pruned " << actual << dendl;
      if (!actual.empty()) {
	pending_inc.new_purged_snaps[p.first].swap(actual);
      }
    }
    if (actually_pruned >= max_prune) {
      break;
    }
  }
  dout(10) << __func__ << " actually pruned " << actually_pruned << dendl;
  return !!actually_pruned;
}

bool OSDMonitor::update_pools_status()
{
  if (!mon->mgrstatmon()->is_readable())
    return false;

  bool ret = false;

  auto& pools = osdmap.get_pools();
  for (auto it = pools.begin(); it != pools.end(); ++it) {
    const pool_stat_t *pstat = mon->mgrstatmon()->get_pool_stat(it->first);
    if (!pstat)
      continue;
    const object_stat_sum_t& sum = pstat->stats.sum;
    const pg_pool_t &pool = it->second;
    const string& pool_name = osdmap.get_pool_name(it->first);

    bool pool_is_full =
      (pool.quota_max_bytes > 0 && (uint64_t)sum.num_bytes >= pool.quota_max_bytes) ||
      (pool.quota_max_objects > 0 && (uint64_t)sum.num_objects >= pool.quota_max_objects);

    if (pool.has_flag(pg_pool_t::FLAG_FULL_QUOTA)) {
      if (pool_is_full)
        continue;

      mon->clog->info() << "pool '" << pool_name
                       << "' no longer out of quota; removing NO_QUOTA flag";
      // below we cancel FLAG_FULL too, we'll set it again in
      // OSDMonitor::encode_pending if it still fails the osd-full checking.
      clear_pool_flags(it->first,
                       pg_pool_t::FLAG_FULL_QUOTA | pg_pool_t::FLAG_FULL);
      ret = true;
    } else {
      if (!pool_is_full)
	continue;

      if (pool.quota_max_bytes > 0 &&
          (uint64_t)sum.num_bytes >= pool.quota_max_bytes) {
        mon->clog->warn() << "pool '" << pool_name << "' is full"
                         << " (reached quota's max_bytes: "
                         << byte_u_t(pool.quota_max_bytes) << ")";
      }
      if (pool.quota_max_objects > 0 &&
		 (uint64_t)sum.num_objects >= pool.quota_max_objects) {
        mon->clog->warn() << "pool '" << pool_name << "' is full"
                         << " (reached quota's max_objects: "
                         << pool.quota_max_objects << ")";
      }
      // set both FLAG_FULL_QUOTA and FLAG_FULL
      // note that below we try to cancel FLAG_BACKFILLFULL/NEARFULL too
      // since FLAG_FULL should always take precedence
      set_pool_flags(it->first,
                     pg_pool_t::FLAG_FULL_QUOTA | pg_pool_t::FLAG_FULL);
      clear_pool_flags(it->first,
                       pg_pool_t::FLAG_NEARFULL |
                       pg_pool_t::FLAG_BACKFILLFULL);
      ret = true;
    }
  }
  return ret;
}

int OSDMonitor::prepare_new_pool(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  MPoolOp *m = static_cast<MPoolOp*>(op->get_req());
  dout(10) << "prepare_new_pool from " << m->get_connection() << dendl;
  MonSession *session = op->get_session();
  if (!session)
    return -EPERM;
  string erasure_code_profile;
  stringstream ss;
  string rule_name;
  int ret = 0;
  ret = prepare_new_pool(m->name, m->crush_rule, rule_name,
			 0, 0, 0, 0, 0, 0.0,
			 erasure_code_profile,
			 pg_pool_t::TYPE_REPLICATED, 0, FAST_READ_OFF, &ss);

  if (ret < 0) {
    dout(10) << __func__ << " got " << ret << " " << ss.str() << dendl;
  }
  return ret;
}

int OSDMonitor::crush_rename_bucket(const string& srcname,
				    const string& dstname,
				    ostream *ss)
{
  int ret;
  //
  // Avoid creating a pending crush if it does not already exists and
  // the rename would fail.
  //
  if (!_have_pending_crush()) {
    ret = _get_stable_crush().can_rename_bucket(srcname,
						dstname,
						ss);
    if (ret)
      return ret;
  }

  CrushWrapper newcrush;
  _get_pending_crush(newcrush);

  ret = newcrush.rename_bucket(srcname,
			       dstname,
			       ss);
  if (ret)
    return ret;

  pending_inc.crush.clear();
  newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
  *ss << "renamed bucket " << srcname << " into " << dstname;	
  return 0;
}

void OSDMonitor::check_legacy_ec_plugin(const string& plugin, const string& profile) const
{
  string replacement = "";

  if (plugin == "jerasure_generic" || 
      plugin == "jerasure_sse3" ||
      plugin == "jerasure_sse4" ||
      plugin == "jerasure_neon") {
    replacement = "jerasure";
  } else if (plugin == "shec_generic" ||
	     plugin == "shec_sse3" ||
	     plugin == "shec_sse4" ||
             plugin == "shec_neon") {
    replacement = "shec";
  }

  if (replacement != "") {
    dout(0) << "WARNING: erasure coding profile " << profile << " uses plugin "
	    << plugin << " that has been deprecated. Please use " 
	    << replacement << " instead." << dendl;
  }
}

int OSDMonitor::normalize_profile(const string& profilename,
				  ErasureCodeProfile &profile,
				  bool force,
				  ostream *ss)
{
  ErasureCodeInterfaceRef erasure_code;
  ErasureCodePluginRegistry &instance = ErasureCodePluginRegistry::instance();
  ErasureCodeProfile::const_iterator plugin = profile.find("plugin");
  check_legacy_ec_plugin(plugin->second, profilename);
  int err = instance.factory(plugin->second,
			     g_conf().get_val<std::string>("erasure_code_dir"),
			     profile, &erasure_code, ss);
  if (err) {
    return err;
  }

  err = erasure_code->init(profile, ss);
  if (err) {
    return err;
  }

  auto it = profile.find("stripe_unit");
  if (it != profile.end()) {
    string err_str;
    uint32_t stripe_unit = strict_iecstrtoll(it->second.c_str(), &err_str);
    if (!err_str.empty()) {
      *ss << "could not parse stripe_unit '" << it->second
	  << "': " << err_str << std::endl;
      return -EINVAL;
    }
    uint32_t data_chunks = erasure_code->get_data_chunk_count();
    uint32_t chunk_size = erasure_code->get_chunk_size(stripe_unit * data_chunks);
    if (chunk_size != stripe_unit) {
      *ss << "stripe_unit " << stripe_unit << " does not match ec profile "
	  << "alignment. Would be padded to " << chunk_size
	  << std::endl;
      return -EINVAL;
    }
    if ((stripe_unit % 4096) != 0 && !force) {
      *ss << "stripe_unit should be a multiple of 4096 bytes for best performance."
	  << "use --force to override this check" << std::endl;
      return -EINVAL;
    }
  }
  return 0;
}

int OSDMonitor::crush_rule_create_erasure(const string &name,
					     const string &profile,
					     int *rule,
					     ostream *ss)
{
  int ruleid = osdmap.crush->get_rule_id(name);
  if (ruleid != -ENOENT) {
    *rule = osdmap.crush->get_rule_mask_ruleset(ruleid);
    return -EEXIST;
  }

  CrushWrapper newcrush;
  _get_pending_crush(newcrush);

  ruleid = newcrush.get_rule_id(name);
  if (ruleid != -ENOENT) {
    *rule = newcrush.get_rule_mask_ruleset(ruleid);
    return -EALREADY;
  } else {
    ErasureCodeInterfaceRef erasure_code;
    int err = get_erasure_code(profile, &erasure_code, ss);
    if (err) {
      *ss << "failed to load plugin using profile " << profile << std::endl;
      return err;
    }

    err = erasure_code->create_rule(name, newcrush, ss);
    erasure_code.reset();
    if (err < 0)
      return err;
    *rule = err;
    pending_inc.crush.clear();
    newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
    return 0;
  }
}

int OSDMonitor::get_erasure_code(const string &erasure_code_profile,
				 ErasureCodeInterfaceRef *erasure_code,
				 ostream *ss) const
{
  if (pending_inc.has_erasure_code_profile(erasure_code_profile))
    return -EAGAIN;
  ErasureCodeProfile profile =
    osdmap.get_erasure_code_profile(erasure_code_profile);
  ErasureCodeProfile::const_iterator plugin =
    profile.find("plugin");
  if (plugin == profile.end()) {
    *ss << "cannot determine the erasure code plugin"
	<< " because there is no 'plugin' entry in the erasure_code_profile "
	<< profile << std::endl;
    return -EINVAL;
  }
  check_legacy_ec_plugin(plugin->second, erasure_code_profile);
  ErasureCodePluginRegistry &instance = ErasureCodePluginRegistry::instance();
  return instance.factory(plugin->second,
			  g_conf().get_val<std::string>("erasure_code_dir"),
			  profile, erasure_code, ss);
}

int OSDMonitor::check_cluster_features(uint64_t features,
				       stringstream &ss)
{
  stringstream unsupported_ss;
  int unsupported_count = 0;
  if ((mon->get_quorum_con_features() & features) != features) {
    unsupported_ss << "the monitor cluster";
    ++unsupported_count;
  }

  set<int32_t> up_osds;
  osdmap.get_up_osds(up_osds);
  for (set<int32_t>::iterator it = up_osds.begin();
       it != up_osds.end(); ++it) {
    const osd_xinfo_t &xi = osdmap.get_xinfo(*it);
    if ((xi.features & features) != features) {
      if (unsupported_count > 0)
	unsupported_ss << ", ";
      unsupported_ss << "osd." << *it;
      unsupported_count ++;
    }
  }

  if (unsupported_count > 0) {
    ss << "features " << features << " unsupported by: "
       << unsupported_ss.str();
    return -ENOTSUP;
  }

  // check pending osd state, too!
  for (map<int32_t,osd_xinfo_t>::const_iterator p =
	 pending_inc.new_xinfo.begin();
       p != pending_inc.new_xinfo.end(); ++p) {
    const osd_xinfo_t &xi = p->second;
    if ((xi.features & features) != features) {
      dout(10) << __func__ << " pending osd." << p->first
	       << " features are insufficient; retry" << dendl;
      return -EAGAIN;
    }
  }

  return 0;
}

bool OSDMonitor::validate_crush_against_features(const CrushWrapper *newcrush,
                                                 stringstream& ss)
{
  OSDMap::Incremental new_pending = pending_inc;
  encode(*newcrush, new_pending.crush, mon->get_quorum_con_features());
  OSDMap newmap;
  newmap.deepish_copy_from(osdmap);
  newmap.apply_incremental(new_pending);

  // client compat
  if (newmap.require_min_compat_client > 0) {
    auto mv = newmap.get_min_compat_client();
    if (mv > newmap.require_min_compat_client) {
      ss << "new crush map requires client version " << ceph_release_name(mv)
	 << " but require_min_compat_client is "
	 << ceph_release_name(newmap.require_min_compat_client);
      return false;
    }
  }

  // osd compat
  uint64_t features =
    newmap.get_features(CEPH_ENTITY_TYPE_MON, NULL) |
    newmap.get_features(CEPH_ENTITY_TYPE_OSD, NULL);
  stringstream features_ss;
  int r = check_cluster_features(features, features_ss);
  if (r) {
    ss << "Could not change CRUSH: " << features_ss.str();
    return false;
  }

  return true;
}

bool OSDMonitor::erasure_code_profile_in_use(
  const mempool::osdmap::map<int64_t, pg_pool_t> &pools,
  const string &profile,
  ostream *ss)
{
  bool found = false;
  for (map<int64_t, pg_pool_t>::const_iterator p = pools.begin();
       p != pools.end();
       ++p) {
    if (p->second.erasure_code_profile == profile && p->second.is_erasure()) {
      *ss << osdmap.pool_name[p->first] << " ";
      found = true;
    }
  }
  if (found) {
    *ss << "pool(s) are using the erasure code profile '" << profile << "'";
  }
  return found;
}

int OSDMonitor::parse_erasure_code_profile(const vector<string> &erasure_code_profile,
					   map<string,string> *erasure_code_profile_map,
					   ostream *ss)
{
  int r = g_conf().with_val<string>("osd_pool_default_erasure_code_profile",
				   get_json_str_map,
				   *ss,
				   erasure_code_profile_map,
				   true);
  if (r)
    return r;
  ceph_assert((*erasure_code_profile_map).count("plugin"));
  string default_plugin = (*erasure_code_profile_map)["plugin"];
  map<string,string> user_map;
  for (vector<string>::const_iterator i = erasure_code_profile.begin();
       i != erasure_code_profile.end();
       ++i) {
    size_t equal = i->find('=');
    if (equal == string::npos) {
      user_map[*i] = string();
      (*erasure_code_profile_map)[*i] = string();
    } else {
      const string key = i->substr(0, equal);
      equal++;
      const string value = i->substr(equal);
      if (key.find("ruleset-") == 0) {
	*ss << "property '" << key << "' is no longer supported; try "
	    << "'crush-" << key.substr(8) << "' instead";
	return -EINVAL;
      }
      user_map[key] = value;
      (*erasure_code_profile_map)[key] = value;
    }
  }

  if (user_map.count("plugin") && user_map["plugin"] != default_plugin)
    (*erasure_code_profile_map) = user_map;

  return 0;
}

int OSDMonitor::prepare_pool_size(const unsigned pool_type,
				  const string &erasure_code_profile,
                                  uint8_t repl_size,
				  unsigned *size, unsigned *min_size,
				  ostream *ss)
{
  int err = 0;
  switch (pool_type) {
  case pg_pool_t::TYPE_REPLICATED:
    if (repl_size == 0) {
      repl_size = g_conf().get_val<uint64_t>("osd_pool_default_size");
    }
    *size = repl_size;
    *min_size = g_conf().get_osd_pool_default_min_size(repl_size);
    break;
  case pg_pool_t::TYPE_ERASURE:
    {
      ErasureCodeInterfaceRef erasure_code;
      err = get_erasure_code(erasure_code_profile, &erasure_code, ss);
      if (err == 0) {
	*size = erasure_code->get_chunk_count();
	*min_size =
	  erasure_code->get_data_chunk_count() +
	  std::min<int>(1, erasure_code->get_coding_chunk_count() - 1);
	assert(*min_size <= *size);
	assert(*min_size >= erasure_code->get_data_chunk_count());
      }
    }
    break;
  default:
    *ss << "prepare_pool_size: " << pool_type << " is not a known pool type";
    err = -EINVAL;
    break;
  }
  return err;
}

int OSDMonitor::prepare_pool_stripe_width(const unsigned pool_type,
					  const string &erasure_code_profile,
					  uint32_t *stripe_width,
					  ostream *ss)
{
  int err = 0;
  switch (pool_type) {
  case pg_pool_t::TYPE_REPLICATED:
    // ignored
    break;
  case pg_pool_t::TYPE_ERASURE:
    {
      ErasureCodeProfile profile =
	osdmap.get_erasure_code_profile(erasure_code_profile);
      ErasureCodeInterfaceRef erasure_code;
      err = get_erasure_code(erasure_code_profile, &erasure_code, ss);
      if (err)
	break;
      uint32_t data_chunks = erasure_code->get_data_chunk_count();
      uint32_t stripe_unit = g_conf().get_val<Option::size_t>("osd_pool_erasure_code_stripe_unit");
      auto it = profile.find("stripe_unit");
      if (it != profile.end()) {
	string err_str;
	stripe_unit = strict_iecstrtoll(it->second.c_str(), &err_str);
	ceph_assert(err_str.empty());
      }
      *stripe_width = data_chunks *
	erasure_code->get_chunk_size(stripe_unit * data_chunks);
    }
    break;
  default:
    *ss << "prepare_pool_stripe_width: "
       << pool_type << " is not a known pool type";
    err = -EINVAL;
    break;
  }
  return err;
}

int OSDMonitor::prepare_pool_crush_rule(const unsigned pool_type,
					const string &erasure_code_profile,
					const string &rule_name,
					int *crush_rule,
					ostream *ss)
{

  if (*crush_rule < 0) {
    switch (pool_type) {
    case pg_pool_t::TYPE_REPLICATED:
      {
	if (rule_name == "") {
	  // Use default rule
	  *crush_rule = osdmap.crush->get_osd_pool_default_crush_replicated_ruleset(cct);
	  if (*crush_rule < 0) {
	    // Errors may happen e.g. if no valid rule is available
	    *ss << "No suitable CRUSH rule exists, check "
                << "'osd pool default crush *' config options";
	    return -ENOENT;
	  }
	} else {
	  return get_crush_rule(rule_name, crush_rule, ss);
	}
      }
      break;
    case pg_pool_t::TYPE_ERASURE:
      {
	int err = crush_rule_create_erasure(rule_name,
					       erasure_code_profile,
					       crush_rule, ss);
	switch (err) {
	case -EALREADY:
	  dout(20) << "prepare_pool_crush_rule: rule "
		   << rule_name << " try again" << dendl;
	  // fall through
	case 0:
	  // need to wait for the crush rule to be proposed before proceeding
	  err = -EAGAIN;
	  break;
	case -EEXIST:
	  err = 0;
	  break;
 	}
	return err;
      }
      break;
    default:
      *ss << "prepare_pool_crush_rule: " << pool_type
	 << " is not a known pool type";
      return -EINVAL;
      break;
    }
  } else {
    if (!osdmap.crush->ruleset_exists(*crush_rule)) {
      *ss << "CRUSH rule " << *crush_rule << " not found";
      return -ENOENT;
    }
  }

  return 0;
}

int OSDMonitor::get_crush_rule(const string &rule_name,
			       int *crush_rule,
			       ostream *ss)
{
  int ret;
  ret = osdmap.crush->get_rule_id(rule_name);
  if (ret != -ENOENT) {
    // found it, use it
    *crush_rule = ret;
  } else {
    CrushWrapper newcrush;
    _get_pending_crush(newcrush);

    ret = newcrush.get_rule_id(rule_name);
    if (ret != -ENOENT) {
      // found it, wait for it to be proposed
      dout(20) << __func__ << ": rule " << rule_name
	       << " try again" << dendl;
      return -EAGAIN;
    } else {
      // Cannot find it , return error
      *ss << "specified rule " << rule_name << " doesn't exist";
      return ret;
    }
  }
  return 0;
}

int OSDMonitor::check_pg_num(int64_t pool, int pg_num, int size, ostream *ss)
{
  auto max_pgs_per_osd = g_conf().get_val<uint64_t>("mon_max_pg_per_osd");
  auto num_osds = std::max(osdmap.get_num_in_osds(), 3u);   // assume min cluster size 3
  auto max_pgs = max_pgs_per_osd * num_osds;
  uint64_t projected = 0;
  if (pool < 0) {
    projected += pg_num * size;
  }
  for (const auto& i : osdmap.get_pools()) {
    if (i.first == pool) {
      projected += pg_num * size;
    } else {
      projected += i.second.get_pg_num_target() * i.second.get_size();
    }
  }
  if (projected > max_pgs) {
    if (pool >= 0) {
      *ss << "pool id " << pool;
    }
    *ss << " pg_num " << pg_num << " size " << size
	<< " would mean " << projected
	<< " total pgs, which exceeds max " << max_pgs
	<< " (mon_max_pg_per_osd " << max_pgs_per_osd
	<< " * num_in_osds " << num_osds << ")";
    return -ERANGE;
  }
  return 0;
}

/**
 * @param name The name of the new pool
 * @param crush_rule The crush rule to use. If <0, will use the system default
 * @param crush_rule_name The crush rule to use, if crush_rulset <0
 * @param pg_num The pg_num to use. If set to 0, will use the system default
 * @param pgp_num The pgp_num to use. If set to 0, will use the system default
 * @param repl_size Replication factor, or 0 for default
 * @param erasure_code_profile The profile name in OSDMap to be used for erasure code
 * @param pool_type TYPE_ERASURE, or TYPE_REP
 * @param expected_num_objects expected number of objects on the pool
 * @param fast_read fast read type. 
 * @param ss human readable error message, if any.
 *
 * @return 0 on success, negative errno on failure.
 */
int OSDMonitor::prepare_new_pool(string& name,
				 int crush_rule,
				 const string &crush_rule_name,
                                 unsigned pg_num, unsigned pgp_num,
				 unsigned pg_num_min,
                                 const uint64_t repl_size,
				 const uint64_t target_size_bytes,
				 const float target_size_ratio,
				 const string &erasure_code_profile,
                                 const unsigned pool_type,
                                 const uint64_t expected_num_objects,
                                 FastReadType fast_read,
				 ostream *ss)
{
  if (name.length() == 0)
    return -EINVAL;
  if (pg_num == 0)
    pg_num = g_conf().get_val<uint64_t>("osd_pool_default_pg_num");
  if (pgp_num == 0)
    pgp_num = g_conf().get_val<uint64_t>("osd_pool_default_pgp_num");
  if (!pgp_num)
    pgp_num = pg_num;
  if (pg_num > g_conf().get_val<uint64_t>("mon_max_pool_pg_num")) {
    *ss << "'pg_num' must be greater than 0 and less than or equal to "
        << g_conf().get_val<uint64_t>("mon_max_pool_pg_num")
        << " (you may adjust 'mon max pool pg num' for higher values)";
    return -ERANGE;
  }
  if (pgp_num > pg_num) {
    *ss << "'pgp_num' must be greater than 0 and lower or equal than 'pg_num'"
        << ", which in this case is " << pg_num;
    return -ERANGE;
  }
  if (pool_type == pg_pool_t::TYPE_REPLICATED && fast_read == FAST_READ_ON) {
    *ss << "'fast_read' can only apply to erasure coding pool";
    return -EINVAL;
  }
  int r;
  r = prepare_pool_crush_rule(pool_type, erasure_code_profile,
				 crush_rule_name, &crush_rule, ss);
  if (r) {
    dout(10) << "prepare_pool_crush_rule returns " << r << dendl;
    return r;
  }
  if (g_conf()->mon_osd_crush_smoke_test) {
    CrushWrapper newcrush;
    _get_pending_crush(newcrush);
    ostringstream err;
    CrushTester tester(newcrush, err);
    tester.set_min_x(0);
    tester.set_max_x(50);
    tester.set_rule(crush_rule);
    auto start = ceph::coarse_mono_clock::now();
    r = tester.test_with_fork(g_conf()->mon_lease);
    auto duration = ceph::coarse_mono_clock::now() - start;
    if (r < 0) {
      dout(10) << "tester.test_with_fork returns " << r
	       << ": " << err.str() << dendl;
      *ss << "crush test failed with " << r << ": " << err.str();
      return r;
    }
    dout(10) << __func__ << " crush smoke test duration: "
             << duration << dendl;
  }
  unsigned size, min_size;
  r = prepare_pool_size(pool_type, erasure_code_profile, repl_size,
                        &size, &min_size, ss);
  if (r) {
    dout(10) << "prepare_pool_size returns " << r << dendl;
    return r;
  }
  r = check_pg_num(-1, pg_num, size, ss);
  if (r) {
    dout(10) << "check_pg_num returns " << r << dendl;
    return r;
  }

  if (!osdmap.crush->check_crush_rule(crush_rule, pool_type, size, *ss)) {
    return -EINVAL;
  }

  uint32_t stripe_width = 0;
  r = prepare_pool_stripe_width(pool_type, erasure_code_profile, &stripe_width, ss);
  if (r) {
    dout(10) << "prepare_pool_stripe_width returns " << r << dendl;
    return r;
  }
  
  bool fread = false;
  if (pool_type == pg_pool_t::TYPE_ERASURE) {
    switch (fast_read) {
      case FAST_READ_OFF:
        fread = false;
        break;
      case FAST_READ_ON:
        fread = true;
        break;
      case FAST_READ_DEFAULT:
        fread = g_conf()->osd_pool_default_ec_fast_read;
        break;
      default:
        *ss << "invalid fast_read setting: " << fast_read;
        return -EINVAL;
    }
  }

  for (map<int64_t,string>::iterator p = pending_inc.new_pool_names.begin();
       p != pending_inc.new_pool_names.end();
       ++p) {
    if (p->second == name)
      return 0;
  }

  if (-1 == pending_inc.new_pool_max)
    pending_inc.new_pool_max = osdmap.pool_max;
  int64_t pool = ++pending_inc.new_pool_max;
  pg_pool_t empty;
  pg_pool_t *pi = pending_inc.get_new_pool(pool, &empty);
  pi->create_time = ceph_clock_now();
  pi->type = pool_type;
  pi->fast_read = fread; 
  pi->flags = g_conf()->osd_pool_default_flags;
  if (g_conf()->osd_pool_default_flag_hashpspool)
    pi->set_flag(pg_pool_t::FLAG_HASHPSPOOL);
  if (g_conf()->osd_pool_default_flag_nodelete)
    pi->set_flag(pg_pool_t::FLAG_NODELETE);
  if (g_conf()->osd_pool_default_flag_nopgchange)
    pi->set_flag(pg_pool_t::FLAG_NOPGCHANGE);
  if (g_conf()->osd_pool_default_flag_nosizechange)
    pi->set_flag(pg_pool_t::FLAG_NOSIZECHANGE);
  pi->set_flag(pg_pool_t::FLAG_CREATING);
  if (g_conf()->osd_pool_use_gmt_hitset)
    pi->use_gmt_hitset = true;
  else
    pi->use_gmt_hitset = false;

  pi->size = size;
  pi->min_size = min_size;
  pi->crush_rule = crush_rule;
  pi->expected_num_objects = expected_num_objects;
  pi->object_hash = CEPH_STR_HASH_RJENKINS;

  {
    auto m = pg_pool_t::get_pg_autoscale_mode_by_name(
      g_conf().get_val<string>("osd_pool_default_pg_autoscale_mode"));
    pi->pg_autoscale_mode = m >= 0 ? m : 0;
  }
  auto max = g_conf().get_val<int64_t>("mon_osd_max_initial_pgs");
  pi->set_pg_num(
    max > 0 ? std::min<uint64_t>(pg_num, std::max<int64_t>(1, max))
    : pg_num);
  pi->set_pg_num_pending(pi->get_pg_num());
  pi->set_pg_num_target(pg_num);
  pi->set_pgp_num(pi->get_pg_num());
  pi->set_pgp_num_target(pgp_num);
  if (osdmap.require_osd_release >= CEPH_RELEASE_NAUTILUS &&
      pg_num_min) {
    pi->opts.set(pool_opts_t::PG_NUM_MIN, static_cast<int64_t>(pg_num_min));
  }

  pi->last_change = pending_inc.epoch;
  pi->auid = 0;

  if (pool_type == pg_pool_t::TYPE_ERASURE) {
      pi->erasure_code_profile = erasure_code_profile;
  } else {
      pi->erasure_code_profile = "";
  }
  pi->stripe_width = stripe_width;

  if (osdmap.require_osd_release >= CEPH_RELEASE_NAUTILUS &&
      target_size_bytes) {
    // only store for nautilus+ because TARGET_SIZE_BYTES may be
    // larger than int32_t max.
    pi->opts.set(pool_opts_t::TARGET_SIZE_BYTES, static_cast<int64_t>(target_size_bytes));
  }
  if (target_size_ratio > 0.0 &&
    osdmap.require_osd_release >= CEPH_RELEASE_NAUTILUS) {
    // only store for nautilus+, just to be consistent and tidy.
    pi->opts.set(pool_opts_t::TARGET_SIZE_RATIO, target_size_ratio);
  }

  pi->cache_target_dirty_ratio_micro =
    g_conf()->osd_pool_default_cache_target_dirty_ratio * 1000000;
  pi->cache_target_dirty_high_ratio_micro =
    g_conf()->osd_pool_default_cache_target_dirty_high_ratio * 1000000;
  pi->cache_target_full_ratio_micro =
    g_conf()->osd_pool_default_cache_target_full_ratio * 1000000;
  pi->cache_min_flush_age = g_conf()->osd_pool_default_cache_min_flush_age;
  pi->cache_min_evict_age = g_conf()->osd_pool_default_cache_min_evict_age;

  pending_inc.new_pool_names[pool] = name;
  return 0;
}

bool OSDMonitor::prepare_set_flag(MonOpRequestRef op, int flag)
{
  op->mark_osdmon_event(__func__);
  ostringstream ss;
  if (pending_inc.new_flags < 0)
    pending_inc.new_flags = osdmap.get_flags();
  pending_inc.new_flags |= flag;
  ss << OSDMap::get_flag_string(flag) << " is set";
  wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, ss.str(),
						    get_last_committed() + 1));
  return true;
}

bool OSDMonitor::prepare_unset_flag(MonOpRequestRef op, int flag)
{
  op->mark_osdmon_event(__func__);
  ostringstream ss;
  if (pending_inc.new_flags < 0)
    pending_inc.new_flags = osdmap.get_flags();
  pending_inc.new_flags &= ~flag;
  ss << OSDMap::get_flag_string(flag) << " is unset";
  wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, ss.str(),
						    get_last_committed() + 1));
  return true;
}

int OSDMonitor::prepare_command_pool_set(const cmdmap_t& cmdmap,
                                         stringstream& ss)
{
  string poolstr;
  cmd_getval(cct, cmdmap, "pool", poolstr);
  int64_t pool = osdmap.lookup_pg_pool_name(poolstr.c_str());
  if (pool < 0) {
    ss << "unrecognized pool '" << poolstr << "'";
    return -ENOENT;
  }
  string var;
  cmd_getval(cct, cmdmap, "var", var);

  pg_pool_t p = *osdmap.get_pg_pool(pool);
  if (pending_inc.new_pools.count(pool))
    p = pending_inc.new_pools[pool];

  // accept val as a json string in the normal case (current
  // generation monitor).  parse out int or float values from the
  // string as needed.  however, if it is not a string, try to pull
  // out an int, in case an older monitor with an older json schema is
  // forwarding a request.
  string val;
  string interr, floaterr;
  int64_t n = 0;
  double f = 0;
  int64_t uf = 0;  // micro-f
  cmd_getval(cct, cmdmap, "val", val);

  // create list of properties that use SI units
  std::set<std::string> si_items = {};
  // create list of properties that use IEC units
  std::set<std::string> iec_items = {"target_size_bytes"};

  if (si_items.count(var)) {
    n = strict_si_cast<int64_t>(val.c_str(), &interr);
  } else if (iec_items.count(var)) {
    n = strict_iec_cast<int64_t>(val.c_str(), &interr);
  } else {
    // parse string as both int and float; different fields use different types.
    n = strict_strtoll(val.c_str(), 10, &interr);
    f = strict_strtod(val.c_str(), &floaterr);
    uf = llrintl(f * (double)1000000.0);
  }

  if (!p.is_tier() &&
      (var == "hit_set_type" || var == "hit_set_period" ||
       var == "hit_set_count" || var == "hit_set_fpp" ||
       var == "target_max_objects" || var == "target_max_bytes" ||
       var == "cache_target_full_ratio" || var == "cache_target_dirty_ratio" ||
       var == "cache_target_dirty_high_ratio" || var == "use_gmt_hitset" ||
       var == "cache_min_flush_age" || var == "cache_min_evict_age" ||
       var == "hit_set_grade_decay_rate" || var == "hit_set_search_last_n" ||
       var == "min_read_recency_for_promote" || var == "min_write_recency_for_promote")) {
    return -EACCES;
  }

  if (var == "size") {
    if (p.has_flag(pg_pool_t::FLAG_NOSIZECHANGE)) {
      ss << "pool size change is disabled; you must unset nosizechange flag for the pool first";
      return -EPERM;
    }
    if (p.type == pg_pool_t::TYPE_ERASURE) {
      ss << "can not change the size of an erasure-coded pool";
      return -ENOTSUP;
    }
    if (interr.length()) {
      ss << "error parsing integer value '" << val << "': " << interr;
      return -EINVAL;
    }
    if (n <= 0 || n > 10) {
      ss << "pool size must be between 1 and 10";
      return -EINVAL;
    }
    if (!osdmap.crush->check_crush_rule(p.get_crush_rule(), p.type, n, ss)) {
      return -EINVAL;
    }
    int r = check_pg_num(pool, p.get_pg_num(), n, &ss);
    if (r < 0) {
      return r;
    }
    p.size = n;
    p.min_size = g_conf().get_osd_pool_default_min_size(p.size);
  } else if (var == "min_size") {
    if (p.has_flag(pg_pool_t::FLAG_NOSIZECHANGE)) {
      ss << "pool min size change is disabled; you must unset nosizechange flag for the pool first";
      return -EPERM;
    }
    if (interr.length()) {
      ss << "error parsing integer value '" << val << "': " << interr;
      return -EINVAL;
    }

    if (p.type != pg_pool_t::TYPE_ERASURE) {
      if (n < 1 || n > p.size) {
	ss << "pool min_size must be between 1 and size, which is set to " << (int)p.size;
	return -EINVAL;
      }
    } else {
       ErasureCodeInterfaceRef erasure_code;
       int k;
       stringstream tmp;
       int err = get_erasure_code(p.erasure_code_profile, &erasure_code, &tmp);
       if (err == 0) {
	 k = erasure_code->get_data_chunk_count();
       } else {
	 ss << __func__ << " get_erasure_code failed: " << tmp.str();
	 return err;
       }

       if (n < k || n > p.size) {
	 ss << "pool min_size must be between " << k << " and size, which is set to " << (int)p.size;
	 return -EINVAL;
       }
    }
    p.min_size = n;
  } else if (var == "pg_num_actual") {
    if (interr.length()) {
      ss << "error parsing integer value '" << val << "': " << interr;
      return -EINVAL;
    }
    if (n == (int)p.get_pg_num()) {
      return 0;
    }
    if (static_cast<uint64_t>(n) > g_conf().get_val<uint64_t>("mon_max_pool_pg_num")) {
      ss << "'pg_num' must be greater than 0 and less than or equal to "
         << g_conf().get_val<uint64_t>("mon_max_pool_pg_num")
         << " (you may adjust 'mon max pool pg num' for higher values)";
      return -ERANGE;
    }
    if (p.has_flag(pg_pool_t::FLAG_CREATING)) {
      ss << "cannot adjust pg_num while initial PGs are being created";
      return -EBUSY;
    }
    if (n > (int)p.get_pg_num()) {
      if (p.get_pg_num() != p.get_pg_num_pending()) {
	// force pre-nautilus clients to resend their ops, since they
	// don't understand pg_num_pending changes form a new interval
	p.last_force_op_resend_prenautilus = pending_inc.epoch;
      }
      p.set_pg_num(n);
    } else {
      if (osdmap.require_osd_release < CEPH_RELEASE_NAUTILUS) {
	ss << "nautilus OSDs are required to adjust pg_num_pending";
	return -EPERM;
      }
      if (n < (int)p.get_pgp_num()) {
	ss << "specified pg_num " << n << " < pgp_num " << p.get_pgp_num();
	return -EINVAL;
      }
      if (n < (int)p.get_pg_num() - 1) {
	ss << "specified pg_num " << n << " < pg_num (" << p.get_pg_num()
	   << ") - 1; only single pg decrease is currently supported";
	return -EINVAL;
      }
      p.set_pg_num_pending(n);
      // force pre-nautilus clients to resend their ops, since they
      // don't understand pg_num_pending changes form a new interval
      p.last_force_op_resend_prenautilus = pending_inc.epoch;
    }
    // force pre-luminous clients to resend their ops, since they
    // don't understand that split PGs now form a new interval.
    p.last_force_op_resend_preluminous = pending_inc.epoch;
  } else if (var == "pg_num") {
    if (p.has_flag(pg_pool_t::FLAG_NOPGCHANGE)) {
      ss << "pool pg_num change is disabled; you must unset nopgchange flag for the pool first";
      return -EPERM;
    }
    if (interr.length()) {
      ss << "error parsing integer value '" << val << "': " << interr;
      return -EINVAL;
    }
    if (n == (int)p.get_pg_num_target()) {
      return 0;
    }
    if (n <= 0 || static_cast<uint64_t>(n) >
                  g_conf().get_val<uint64_t>("mon_max_pool_pg_num")) {
      ss << "'pg_num' must be greater than 0 and less than or equal to "
         << g_conf().get_val<uint64_t>("mon_max_pool_pg_num")
         << " (you may adjust 'mon max pool pg num' for higher values)";
      return -ERANGE;
    }
    if (n > (int)p.get_pg_num_target()) {
      int r = check_pg_num(pool, n, p.get_size(), &ss);
      if (r) {
	return r;
      }
      bool force = false;
      cmd_getval(cct,cmdmap, "yes_i_really_mean_it", force);
      if (p.cache_mode != pg_pool_t::CACHEMODE_NONE && !force) {
	ss << "splits in cache pools must be followed by scrubs and leave sufficient free space to avoid overfilling.  use --yes-i-really-mean-it to force.";
	return -EPERM;
      }
    } else {
      if (osdmap.require_osd_release < CEPH_RELEASE_NAUTILUS) {
	ss << "nautilus OSDs are required to decrease pg_num";
	return -EPERM;
      }
    }
    if (osdmap.require_osd_release < CEPH_RELEASE_NAUTILUS) {
      // pre-nautilus osdmap format; increase pg_num directly
      assert(n > (int)p.get_pg_num());
      // force pre-nautilus clients to resend their ops, since they
      // don't understand pg_num_target changes form a new interval
      p.last_force_op_resend_prenautilus = pending_inc.epoch;
      // force pre-luminous clients to resend their ops, since they
      // don't understand that split PGs now form a new interval.
      p.last_force_op_resend_preluminous = pending_inc.epoch;
      p.set_pg_num(n);
    } else {
      // set targets; mgr will adjust pg_num_actual and pgp_num later.
      // make pgp_num track pg_num if it already matches.  if it is set
      // differently, leave it different and let the user control it
      // manually.
      if (p.get_pg_num_target() == p.get_pgp_num_target()) {
	p.set_pgp_num_target(n);
      }
      p.set_pg_num_target(n);
    }
  } else if (var == "pgp_num_actual") {
    if (p.has_flag(pg_pool_t::FLAG_NOPGCHANGE)) {
      ss << "pool pgp_num change is disabled; you must unset nopgchange flag for the pool first";
      return -EPERM;
    }
    if (interr.length()) {
      ss << "error parsing integer value '" << val << "': " << interr;
      return -EINVAL;
    }
    if (n <= 0) {
      ss << "specified pgp_num must > 0, but you set to " << n;
      return -EINVAL;
    }
    if (n > (int)p.get_pg_num()) {
      ss << "specified pgp_num " << n << " > pg_num " << p.get_pg_num();
      return -EINVAL;
    }
    if (n > (int)p.get_pg_num_pending()) {
      ss << "specified pgp_num " << n
	 << " > pg_num_pending " << p.get_pg_num_pending();
      return -EINVAL;
    }
    p.set_pgp_num(n);
  } else if (var == "pgp_num") {
    if (p.has_flag(pg_pool_t::FLAG_NOPGCHANGE)) {
      ss << "pool pgp_num change is disabled; you must unset nopgchange flag for the pool first";
      return -EPERM;
    }
    if (interr.length()) {
      ss << "error parsing integer value '" << val << "': " << interr;
      return -EINVAL;
    }
    if (n <= 0) {
      ss << "specified pgp_num must > 0, but you set to " << n;
      return -EINVAL;
    }
    if (n > (int)p.get_pg_num_target()) {
      ss << "specified pgp_num " << n << " > pg_num " << p.get_pg_num_target();
      return -EINVAL;
    }
    if (osdmap.require_osd_release < CEPH_RELEASE_NAUTILUS) {
      // pre-nautilus osdmap format; increase pgp_num directly
      p.set_pgp_num(n);
    } else {
      p.set_pgp_num_target(n);
    }
  } else if (var == "pg_autoscale_mode") {
    n = pg_pool_t::get_pg_autoscale_mode_by_name(val);
    if (n < 0) {
      ss << "specified invalid mode " << val;
      return -EINVAL;
    }
    if (osdmap.require_osd_release < CEPH_RELEASE_NAUTILUS) {
      ss << "must set require_osd_release to nautilus or later before setting pg_autoscale_mode";
      return -EINVAL;
    }
    p.pg_autoscale_mode = n;
  } else if (var == "crush_rule") {
    int id = osdmap.crush->get_rule_id(val);
    if (id == -ENOENT) {
      ss << "crush rule " << val << " does not exist";
      return -ENOENT;
    }
    if (id < 0) {
      ss << cpp_strerror(id);
      return -ENOENT;
    }
    if (!osdmap.crush->check_crush_rule(id, p.get_type(), p.get_size(), ss)) {
      return -EINVAL;
    }
    p.crush_rule = id;
  } else if (var == "nodelete" || var == "nopgchange" ||
	     var == "nosizechange" || var == "write_fadvise_dontneed" ||
	     var == "noscrub" || var == "nodeep-scrub") {
    uint64_t flag = pg_pool_t::get_flag_by_name(var);
    // make sure we only compare against 'n' if we didn't receive a string
    if (val == "true" || (interr.empty() && n == 1)) {
      p.set_flag(flag);
    } else if (val == "false" || (interr.empty() && n == 0)) {
      p.unset_flag(flag);
    } else {
      ss << "expecting value 'true', 'false', '0', or '1'";
      return -EINVAL;
    }
  } else if (var == "hashpspool") {
    uint64_t flag = pg_pool_t::get_flag_by_name(var);
    bool force = false;
    cmd_getval(cct, cmdmap, "yes_i_really_mean_it", force);

    if (!force) {
      ss << "are you SURE?  this will remap all placement groups in this pool,"
	    " this triggers large data movement,"
	    " pass --yes-i-really-mean-it if you really do.";
      return -EPERM;
    }
    // make sure we only compare against 'n' if we didn't receive a string
    if (val == "true" || (interr.empty() && n == 1)) {
      p.set_flag(flag);
    } else if (val == "false" || (interr.empty() && n == 0)) {
      p.unset_flag(flag);
    } else {
      ss << "expecting value 'true', 'false', '0', or '1'";
      return -EINVAL;
    }
  } else if (var == "hit_set_type") {
    if (val == "none")
      p.hit_set_params = HitSet::Params();
    else {
      int err = check_cluster_features(CEPH_FEATURE_OSD_CACHEPOOL, ss);
      if (err)
	return err;
      if (val == "bloom") {
	BloomHitSet::Params *bsp = new BloomHitSet::Params;
	bsp->set_fpp(g_conf().get_val<double>("osd_pool_default_hit_set_bloom_fpp"));
	p.hit_set_params = HitSet::Params(bsp);
      } else if (val == "explicit_hash")
	p.hit_set_params = HitSet::Params(new ExplicitHashHitSet::Params);
      else if (val == "explicit_object")
	p.hit_set_params = HitSet::Params(new ExplicitObjectHitSet::Params);
      else {
	ss << "unrecognized hit_set type '" << val << "'";
	return -EINVAL;
      }
    }
  } else if (var == "hit_set_period") {
    if (interr.length()) {
      ss << "error parsing integer value '" << val << "': " << interr;
      return -EINVAL;
    } else if (n < 0) {
      ss << "hit_set_period should be non-negative";
      return -EINVAL;
    }
    p.hit_set_period = n;
  } else if (var == "hit_set_count") {
    if (interr.length()) {
      ss << "error parsing integer value '" << val << "': " << interr;
      return -EINVAL;
    } else if (n < 0) {
      ss << "hit_set_count should be non-negative";
      return -EINVAL;
    }
    p.hit_set_count = n;
  } else if (var == "hit_set_fpp") {
    if (floaterr.length()) {
      ss << "error parsing floating point value '" << val << "': " << floaterr;
      return -EINVAL;
    } else if (f < 0 || f > 1.0) {
      ss << "hit_set_fpp should be in the range 0..1";
      return -EINVAL;
    }
    if (p.hit_set_params.get_type() != HitSet::TYPE_BLOOM) {
      ss << "hit set is not of type Bloom; invalid to set a false positive rate!";
      return -EINVAL;
    }
    BloomHitSet::Params *bloomp = static_cast<BloomHitSet::Params*>(p.hit_set_params.impl.get());
    bloomp->set_fpp(f);
  } else if (var == "use_gmt_hitset") {
    if (val == "true" || (interr.empty() && n == 1)) {
      p.use_gmt_hitset = true;
    } else {
      ss << "expecting value 'true' or '1'";
      return -EINVAL;
    }
  } else if (var == "allow_ec_overwrites") {
    if (!p.is_erasure()) {
      ss << "ec overwrites can only be enabled for an erasure coded pool";
      return -EINVAL;
    }
    stringstream err;
    if (!g_conf()->mon_debug_no_require_bluestore_for_ec_overwrites &&
	!is_pool_currently_all_bluestore(pool, p, &err)) {
      ss << "pool must only be stored on bluestore for scrubbing to work: " << err.str();
      return -EINVAL;
    }
    if (val == "true" || (interr.empty() && n == 1)) {
	p.flags |= pg_pool_t::FLAG_EC_OVERWRITES;
    } else if (val == "false" || (interr.empty() && n == 0)) {
      ss << "ec overwrites cannot be disabled once enabled";
      return -EINVAL;
    } else {
      ss << "expecting value 'true', 'false', '0', or '1'";
      return -EINVAL;
    }
  } else if (var == "target_max_objects") {
    if (interr.length()) {
      ss << "error parsing int '" << val << "': " << interr;
      return -EINVAL;
    }
    p.target_max_objects = n;
  } else if (var == "target_max_bytes") {
    if (interr.length()) {
      ss << "error parsing int '" << val << "': " << interr;
      return -EINVAL;
    }
    p.target_max_bytes = n;
  } else if (var == "cache_target_dirty_ratio") {
    if (floaterr.length()) {
      ss << "error parsing float '" << val << "': " << floaterr;
      return -EINVAL;
    }
    if (f < 0 || f > 1.0) {
      ss << "value must be in the range 0..1";
      return -ERANGE;
    }
    p.cache_target_dirty_ratio_micro = uf;
  } else if (var == "cache_target_dirty_high_ratio") {
    if (floaterr.length()) {
      ss << "error parsing float '" << val << "': " << floaterr;
      return -EINVAL;
    }
    if (f < 0 || f > 1.0) {
      ss << "value must be in the range 0..1";
      return -ERANGE;
    }
    p.cache_target_dirty_high_ratio_micro = uf;
  } else if (var == "cache_target_full_ratio") {
    if (floaterr.length()) {
      ss << "error parsing float '" << val << "': " << floaterr;
      return -EINVAL;
    }
    if (f < 0 || f > 1.0) {
      ss << "value must be in the range 0..1";
      return -ERANGE;
    }
    p.cache_target_full_ratio_micro = uf;
  } else if (var == "cache_min_flush_age") {
    if (interr.length()) {
      ss << "error parsing int '" << val << "': " << interr;
      return -EINVAL;
    }
    p.cache_min_flush_age = n;
  } else if (var == "cache_min_evict_age") {
    if (interr.length()) {
      ss << "error parsing int '" << val << "': " << interr;
      return -EINVAL;
    }
    p.cache_min_evict_age = n;
  } else if (var == "min_read_recency_for_promote") {
    if (interr.length()) {
      ss << "error parsing integer value '" << val << "': " << interr;
      return -EINVAL;
    }
    p.min_read_recency_for_promote = n;
  } else if (var == "hit_set_grade_decay_rate") {
    if (interr.length()) {
      ss << "error parsing integer value '" << val << "': " << interr;
      return -EINVAL;
    }
    if (n > 100 || n < 0) {
      ss << "value out of range,valid range is 0 - 100";
      return -EINVAL;
    }
    p.hit_set_grade_decay_rate = n;
  } else if (var == "hit_set_search_last_n") {
    if (interr.length()) {
      ss << "error parsing integer value '" << val << "': " << interr;
      return -EINVAL;
    }
    if (n > p.hit_set_count || n < 0) {
      ss << "value out of range,valid range is 0 - hit_set_count";
      return -EINVAL;
    }
    p.hit_set_search_last_n = n;
  } else if (var == "min_write_recency_for_promote") {
    if (interr.length()) {
      ss << "error parsing integer value '" << val << "': " << interr;
      return -EINVAL;
    }
    p.min_write_recency_for_promote = n;
  } else if (var == "fast_read") {
    if (p.is_replicated()) {
        ss << "fast read is not supported in replication pool";
        return -EINVAL;
    }
    if (val == "true" || (interr.empty() && n == 1)) {
      p.fast_read = true;
    } else if (val == "false" || (interr.empty() && n == 0)) {
      p.fast_read = false;
    } else {
      ss << "expecting value 'true', 'false', '0', or '1'";
      return -EINVAL;
    }
  } else if (pool_opts_t::is_opt_name(var)) {
    bool unset = val == "unset";
    if (var == "compression_mode") {
      if (!unset) {
        auto cmode = Compressor::get_comp_mode_type(val);
        if (!cmode) {
	  ss << "unrecognized compression mode '" << val << "'";
	  return -EINVAL;
        }
      }
    } else if (var == "compression_algorithm") {
      if (!unset) {
        auto alg = Compressor::get_comp_alg_type(val);
        if (!alg) {
          ss << "unrecognized compression_algorithm '" << val << "'";
	  return -EINVAL;
        }
      }
    } else if (var == "compression_required_ratio") {
      if (floaterr.length()) {
        ss << "error parsing float value '" << val << "': " << floaterr;
        return -EINVAL;
      }
      if (f < 0 || f > 1) {
        ss << "compression_required_ratio is out of range (0-1): '" << val << "'";
	return -EINVAL;
      }
    } else if (var == "csum_type") {
      auto t = unset ? 0 : Checksummer::get_csum_string_type(val);
      if (t < 0 ) {
        ss << "unrecognized csum_type '" << val << "'";
	return -EINVAL;
      }
      //preserve csum_type numeric value
      n = t;
      interr.clear(); 
    } else if (var == "compression_max_blob_size" ||
               var == "compression_min_blob_size" ||
               var == "csum_max_block" ||
               var == "csum_min_block") {
      if (interr.length()) {
        ss << "error parsing int value '" << val << "': " << interr;
        return -EINVAL;
      }
    } else if (var == "fingerprint_algorithm") {
      if (!unset) {
        auto alg = pg_pool_t::get_fingerprint_from_str(val);
        if (!alg) {
          ss << "unrecognized fingerprint_algorithm '" << val << "'";
	  return -EINVAL;
        }
      }
    } else if (var == "target_size_bytes") {
      if (interr.length()) {
        ss << "error parsing unit value '" << val << "': " << interr;
        return -EINVAL;
      }
      if (osdmap.require_osd_release < CEPH_RELEASE_NAUTILUS) {
        ss << "must set require_osd_release to nautilus or "
           << "later before setting target_size_bytes";
        return -EINVAL;
      }
    } else if (var == "pg_num_min") {
      if (interr.length()) {
        ss << "error parsing int value '" << val << "': " << interr;
        return -EINVAL;
      }
      if (n > (int)p.get_pg_num_target()) {
	ss << "specified pg_num_min " << n
	   << " > pg_num " << p.get_pg_num_target();
	return -EINVAL;
      }
    } else if (var == "recovery_priority") {
      if (interr.length()) {
        ss << "error parsing int value '" << val << "': " << interr;
        return -EINVAL;
      }
      if (!g_conf()->debug_allow_any_pool_priority) {
        if (n > OSD_POOL_PRIORITY_MAX || n < OSD_POOL_PRIORITY_MIN) {
          ss << "pool recovery_priority must be between " << OSD_POOL_PRIORITY_MIN
	     << " and " << OSD_POOL_PRIORITY_MAX;
          return -EINVAL;
        }
      }
    } else if (var == "pg_autoscale_bias") {
      if (f < 0.0 || f > 1000.0) {
	ss << "pg_autoscale_bias must be between 0 and 1000";
	return -EINVAL;
      }
    }

    pool_opts_t::opt_desc_t desc = pool_opts_t::get_opt_desc(var);
    switch (desc.type) {
    case pool_opts_t::STR:
      if (unset) {
	p.opts.unset(desc.key);
      } else {
	p.opts.set(desc.key, static_cast<std::string>(val));
      }
      break;
    case pool_opts_t::INT:
      if (interr.length()) {
	ss << "error parsing integer value '" << val << "': " << interr;
	return -EINVAL;
      }
      if (n == 0) {
	p.opts.unset(desc.key);
      } else {
	p.opts.set(desc.key, static_cast<int64_t>(n));
      }
      break;
    case pool_opts_t::DOUBLE:
      if (floaterr.length()) {
	ss << "error parsing floating point value '" << val << "': " << floaterr;
	return -EINVAL;
      }
      if (f == 0) {
	p.opts.unset(desc.key);
      } else {
	p.opts.set(desc.key, static_cast<double>(f));
      }
      break;
    default:
      ceph_assert(!"unknown type");
    }
  } else {
    ss << "unrecognized variable '" << var << "'";
    return -EINVAL;
  }
  if (val != "unset") {
    ss << "set pool " << pool << " " << var << " to " << val;
  } else {
    ss << "unset pool " << pool << " " << var;
  }
  p.last_change = pending_inc.epoch;
  pending_inc.new_pools[pool] = p;
  return 0;
}

int OSDMonitor::prepare_command_pool_application(const string &prefix,
                                                 const cmdmap_t& cmdmap,
                                                 stringstream& ss)
{
  return _command_pool_application(prefix, cmdmap, ss, nullptr, true);
}

int OSDMonitor::preprocess_command_pool_application(const string &prefix,
                                                    const cmdmap_t& cmdmap,
                                                    stringstream& ss,
                                                    bool *modified)
{
  return _command_pool_application(prefix, cmdmap, ss, modified, false);
}


/**
 * Common logic for preprocess and prepare phases of pool application
 * tag commands.  In preprocess mode we're only detecting invalid
 * commands, and determining whether it was a modification or a no-op.
 * In prepare mode we're actually updating the pending state.
 */
int OSDMonitor::_command_pool_application(const string &prefix,
                                          const cmdmap_t& cmdmap,
                                          stringstream& ss,
                                          bool *modified,
                                          bool preparing)
{
  string pool_name;
  cmd_getval(cct, cmdmap, "pool", pool_name);
  int64_t pool = osdmap.lookup_pg_pool_name(pool_name.c_str());
  if (pool < 0) {
    ss << "unrecognized pool '" << pool_name << "'";
    return -ENOENT;
  }

  pg_pool_t p = *osdmap.get_pg_pool(pool);
  if (preparing) {
    if (pending_inc.new_pools.count(pool)) {
      p = pending_inc.new_pools[pool];
    }
  }

  string app;
  cmd_getval(cct, cmdmap, "app", app);
  bool app_exists = (p.application_metadata.count(app) > 0);

  string key;
  cmd_getval(cct, cmdmap, "key", key);
  if (key == "all") {
    ss << "key cannot be 'all'";
    return -EINVAL;
  }

  string value;
  cmd_getval(cct, cmdmap, "value", value);
  if (value == "all") {
    ss << "value cannot be 'all'";
    return -EINVAL;
  }

  if (boost::algorithm::ends_with(prefix, "enable")) {
    if (app.empty()) {
      ss << "application name must be provided";
      return -EINVAL;
    }

    if (p.is_tier()) {
      ss << "application must be enabled on base tier";
      return -EINVAL;
    }

    bool force = false;
    cmd_getval(cct, cmdmap, "yes_i_really_mean_it", force);

    if (!app_exists && !p.application_metadata.empty() && !force) {
      ss << "Are you SURE? Pool '" << pool_name << "' already has an enabled "
         << "application; pass --yes-i-really-mean-it to proceed anyway";
      return -EPERM;
    }

    if (!app_exists && p.application_metadata.size() >= MAX_POOL_APPLICATIONS) {
      ss << "too many enabled applications on pool '" << pool_name << "'; "
         << "max " << MAX_POOL_APPLICATIONS;
      return -EINVAL;
    }

    if (app.length() > MAX_POOL_APPLICATION_LENGTH) {
      ss << "application name '" << app << "' too long; max length "
         << MAX_POOL_APPLICATION_LENGTH;
      return -EINVAL;
    }

    if (!app_exists) {
      p.application_metadata[app] = {};
    }
    ss << "enabled application '" << app << "' on pool '" << pool_name << "'";

  } else if (boost::algorithm::ends_with(prefix, "disable")) {
    bool force = false;
    cmd_getval(cct, cmdmap, "yes_i_really_mean_it", force);

    if (!force) {
      ss << "Are you SURE? Disabling an application within a pool might result "
         << "in loss of application functionality; pass "
         << "--yes-i-really-mean-it to proceed anyway";
      return -EPERM;
    }

    if (!app_exists) {
      ss << "application '" << app << "' is not enabled on pool '" << pool_name
         << "'";
      return 0; // idempotent
    }

    p.application_metadata.erase(app);
    ss << "disable application '" << app << "' on pool '" << pool_name << "'";

  } else if (boost::algorithm::ends_with(prefix, "set")) {
    if (p.is_tier()) {
      ss << "application metadata must be set on base tier";
      return -EINVAL;
    }

    if (!app_exists) {
      ss << "application '" << app << "' is not enabled on pool '" << pool_name
         << "'";
      return -ENOENT;
    }

    string key;
    cmd_getval(cct, cmdmap, "key", key);

    if (key.empty()) {
      ss << "key must be provided";
      return -EINVAL;
    }

    auto &app_keys = p.application_metadata[app];
    if (app_keys.count(key) == 0 &&
        app_keys.size() >= MAX_POOL_APPLICATION_KEYS) {
      ss << "too many keys set for application '" << app << "' on pool '"
         << pool_name << "'; max " << MAX_POOL_APPLICATION_KEYS;
      return -EINVAL;
    }

    if (key.length() > MAX_POOL_APPLICATION_LENGTH) {
      ss << "key '" << app << "' too long; max length "
         << MAX_POOL_APPLICATION_LENGTH;
      return -EINVAL;
    }

    string value;
    cmd_getval(cct, cmdmap, "value", value);
    if (value.length() > MAX_POOL_APPLICATION_LENGTH) {
      ss << "value '" << value << "' too long; max length "
         << MAX_POOL_APPLICATION_LENGTH;
      return -EINVAL;
    }

    p.application_metadata[app][key] = value;
    ss << "set application '" << app << "' key '" << key << "' to '"
       << value << "' on pool '" << pool_name << "'";
  } else if (boost::algorithm::ends_with(prefix, "rm")) {
    if (!app_exists) {
      ss << "application '" << app << "' is not enabled on pool '" << pool_name
         << "'";
      return -ENOENT;
    }

    string key;
    cmd_getval(cct, cmdmap, "key", key);
    auto it = p.application_metadata[app].find(key);
    if (it == p.application_metadata[app].end()) {
      ss << "application '" << app << "' on pool '" << pool_name
         << "' does not have key '" << key << "'";
      return 0; // idempotent
    }

    p.application_metadata[app].erase(it);
    ss << "removed application '" << app << "' key '" << key << "' on pool '"
       << pool_name << "'";
  } else {
    ceph_abort();
  }

  if (preparing) {
    p.last_change = pending_inc.epoch;
    pending_inc.new_pools[pool] = p;
  }

  // Because we fell through this far, we didn't hit no-op cases,
  // so pool was definitely modified
  if (modified != nullptr) {
    *modified = true;
  }

  return 0;
}

int OSDMonitor::_prepare_command_osd_crush_remove(
    CrushWrapper &newcrush,
    int32_t id,
    int32_t ancestor,
    bool has_ancestor,
    bool unlink_only)
{
  int err = 0;

  if (has_ancestor) {
    err = newcrush.remove_item_under(cct, id, ancestor,
        unlink_only);
  } else {
    err = newcrush.remove_item(cct, id, unlink_only);
  }
  return err;
}

void OSDMonitor::do_osd_crush_remove(CrushWrapper& newcrush)
{
  pending_inc.crush.clear();
  newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
}

int OSDMonitor::prepare_command_osd_crush_remove(
    CrushWrapper &newcrush,
    int32_t id,
    int32_t ancestor,
    bool has_ancestor,
    bool unlink_only)
{
  int err = _prepare_command_osd_crush_remove(
      newcrush, id, ancestor,
      has_ancestor, unlink_only);

  if (err < 0)
    return err;

  ceph_assert(err == 0);
  do_osd_crush_remove(newcrush);

  return 0;
}

int OSDMonitor::prepare_command_osd_remove(int32_t id)
{
  if (osdmap.is_up(id)) {
    return -EBUSY;
  }

  pending_inc.new_state[id] = osdmap.get_state(id);
  pending_inc.new_uuid[id] = uuid_d();
  pending_metadata_rm.insert(id);
  pending_metadata.erase(id);

  return 0;
}

int32_t OSDMonitor::_allocate_osd_id(int32_t* existing_id)
{
  ceph_assert(existing_id);
  *existing_id = -1;

  for (int32_t i = 0; i < osdmap.get_max_osd(); ++i) {
    if (!osdmap.exists(i) &&
        pending_inc.new_up_client.count(i) == 0 &&
        (pending_inc.new_state.count(i) == 0 ||
         (pending_inc.new_state[i] & CEPH_OSD_EXISTS) == 0)) {
      *existing_id = i;
      return -1;
    }
  }

  if (pending_inc.new_max_osd < 0) {
    return osdmap.get_max_osd();
  }
  return pending_inc.new_max_osd;
}

void OSDMonitor::do_osd_create(
    const int32_t id,
    const uuid_d& uuid,
    const string& device_class,
    int32_t* new_id)
{
  dout(10) << __func__ << " uuid " << uuid << dendl;
  ceph_assert(new_id);

  // We presume validation has been performed prior to calling this
  // function. We assert with prejudice.

  int32_t allocated_id = -1; // declare here so we can jump
  int32_t existing_id = -1;
  if (!uuid.is_zero()) {
    existing_id = osdmap.identify_osd(uuid);
    if (existing_id >= 0) {
      ceph_assert(id < 0 || id == existing_id);
      *new_id = existing_id;
      goto out;
    } else if (id >= 0) {
      // uuid does not exist, and id has been provided, so just create
      // the new osd.id
      *new_id = id;
      goto out;
    }
  }

  // allocate a new id
  allocated_id = _allocate_osd_id(&existing_id);
  dout(10) << __func__ << " allocated id " << allocated_id
           << " existing id " << existing_id << dendl;
  if (existing_id >= 0) {
    ceph_assert(existing_id < osdmap.get_max_osd());
    ceph_assert(allocated_id < 0);
    pending_inc.new_weight[existing_id] = CEPH_OSD_OUT;
    *new_id = existing_id;
  } else if (allocated_id >= 0) {
    ceph_assert(existing_id < 0);
    // raise max_osd
    if (pending_inc.new_max_osd < 0) {
      pending_inc.new_max_osd = osdmap.get_max_osd() + 1;
    } else {
      ++pending_inc.new_max_osd;
    }
    *new_id = pending_inc.new_max_osd - 1;
    ceph_assert(*new_id == allocated_id);
  } else {
    ceph_abort_msg("unexpected condition");
  }

out:
  if (device_class.size()) {
    CrushWrapper newcrush;
    _get_pending_crush(newcrush);
    if (newcrush.get_max_devices() < *new_id + 1) {
      newcrush.set_max_devices(*new_id + 1);
    }
    string name = string("osd.") + stringify(*new_id);
    if (!newcrush.item_exists(*new_id)) {
      newcrush.set_item_name(*new_id, name);
    }
    ostringstream ss;
    int r = newcrush.update_device_class(*new_id, device_class, name, &ss);
    if (r < 0) {
      derr << __func__ << " failed to set " << name << " device_class "
	   << device_class << ": " << cpp_strerror(r) << " - " << ss.str()
	   << dendl;
      // non-fatal... this might be a replay and we want to be idempotent.
    } else {
      dout(20) << __func__ << " set " << name << " device_class " << device_class
	       << dendl;
      pending_inc.crush.clear();
      newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
    }
  } else {
    dout(20) << __func__ << " no device_class" << dendl;
  }

  dout(10) << __func__ << " using id " << *new_id << dendl;
  if (osdmap.get_max_osd() <= *new_id && pending_inc.new_max_osd <= *new_id) {
    pending_inc.new_max_osd = *new_id + 1;
  }

  pending_inc.new_state[*new_id] |= CEPH_OSD_EXISTS | CEPH_OSD_NEW;
  if (!uuid.is_zero())
    pending_inc.new_uuid[*new_id] = uuid;
}

int OSDMonitor::validate_osd_create(
    const int32_t id,
    const uuid_d& uuid,
    const bool check_osd_exists,
    int32_t* existing_id,
    stringstream& ss)
{

  dout(10) << __func__ << " id " << id << " uuid " << uuid
           << " check_osd_exists " << check_osd_exists << dendl;

  ceph_assert(existing_id);

  if (id < 0 && uuid.is_zero()) {
    // we have nothing to validate
    *existing_id = -1;
    return 0;
  } else if (uuid.is_zero()) {
    // we have an id but we will ignore it - because that's what
    // `osd create` does.
    return 0;
  }

  /*
   * This function will be used to validate whether we are able to
   * create a new osd when the `uuid` is specified.
   *
   * It will be used by both `osd create` and `osd new`, as the checks
   * are basically the same when it pertains to osd id and uuid validation.
   * However, `osd create` presumes an `uuid` is optional, for legacy
   * reasons, while `osd new` requires the `uuid` to be provided. This
   * means that `osd create` will not be idempotent if an `uuid` is not
   * provided, but we will always guarantee the idempotency of `osd new`.
   */

  ceph_assert(!uuid.is_zero());
  if (pending_inc.identify_osd(uuid) >= 0) {
    // osd is about to exist
    return -EAGAIN;
  }

  int32_t i = osdmap.identify_osd(uuid);
  if (i >= 0) {
    // osd already exists
    if (id >= 0 && i != id) {
      ss << "uuid " << uuid << " already in use for different id " << i;
      return -EEXIST;
    }
    // return a positive errno to distinguish between a blocking error
    // and an error we consider to not be a problem (i.e., this would be
    // an idempotent operation).
    *existing_id = i;
    return EEXIST;
  }
  // i < 0
  if (id >= 0) {
    if (pending_inc.new_state.count(id)) {
      // osd is about to exist
      return -EAGAIN;
    }
    // we may not care if an osd exists if we are recreating a previously
    // destroyed osd.
    if (check_osd_exists && osdmap.exists(id)) {
      ss << "id " << id << " already in use and does not match uuid "
         << uuid;
      return -EINVAL;
    }
  }
  return 0;
}

int OSDMonitor::prepare_command_osd_create(
    const int32_t id,
    const uuid_d& uuid,
    int32_t* existing_id,
    stringstream& ss)
{
  dout(10) << __func__ << " id " << id << " uuid " << uuid << dendl;
  ceph_assert(existing_id);
  if (osdmap.is_destroyed(id)) {
    ss << "ceph osd create has been deprecated. Please use ceph osd new "
          "instead.";
    return -EINVAL;
  }

  if (uuid.is_zero()) {
    dout(10) << __func__ << " no uuid; assuming legacy `osd create`" << dendl;
  }

  return validate_osd_create(id, uuid, true, existing_id, ss);
}

int OSDMonitor::prepare_command_osd_new(
    MonOpRequestRef op,
    const cmdmap_t& cmdmap,
    const map<string,string>& params,
    stringstream &ss,
    Formatter *f)
{
  uuid_d uuid;
  string uuidstr;
  int64_t id = -1;

  ceph_assert(paxos->is_plugged());

  dout(10) << __func__ << " " << op << dendl;

  /* validate command. abort now if something's wrong. */

  /* `osd new` will expect a `uuid` to be supplied; `id` is optional.
   *
   * If `id` is not specified, we will identify any existing osd based
   * on `uuid`. Operation will be idempotent iff secrets match.
   *
   * If `id` is specified, we will identify any existing osd based on
   * `uuid` and match against `id`. If they match, operation will be
   * idempotent iff secrets match.
   *
   * `-i secrets.json` will be optional. If supplied, will be used
   * to check for idempotency when `id` and `uuid` match.
   *
   * If `id` is not specified, and `uuid` does not exist, an id will
   * be found or allocated for the osd.
   *
   * If `id` is specified, and the osd has been previously marked
   * as destroyed, then the `id` will be reused.
   */
  if (!cmd_getval(cct, cmdmap, "uuid", uuidstr)) {
    ss << "requires the OSD's UUID to be specified.";
    return -EINVAL;
  } else if (!uuid.parse(uuidstr.c_str())) {
    ss << "invalid UUID value '" << uuidstr << "'.";
    return -EINVAL;
  }

  if (cmd_getval(cct, cmdmap, "id", id) &&
      (id < 0)) {
    ss << "invalid OSD id; must be greater or equal than zero.";
    return -EINVAL;
  }

  // are we running an `osd create`-like command, or recreating
  // a previously destroyed osd?

  bool is_recreate_destroyed = (id >= 0 && osdmap.is_destroyed(id));

  // we will care about `id` to assess whether osd is `destroyed`, or
  // to create a new osd.
  // we will need an `id` by the time we reach auth.

  int32_t existing_id = -1;
  int err = validate_osd_create(id, uuid, !is_recreate_destroyed,
                                &existing_id, ss);

  bool may_be_idempotent = false;
  if (err == EEXIST) {
    // this is idempotent from the osdmon's point-of-view
    may_be_idempotent = true;
    ceph_assert(existing_id >= 0);
    id = existing_id;
  } else if (err < 0) {
    return err;
  }

  if (!may_be_idempotent) {
    // idempotency is out of the window. We are either creating a new
    // osd or recreating a destroyed osd.
    //
    // We now need to figure out if we have an `id` (and if it's valid),
    // of find an `id` if we don't have one.

    // NOTE: we need to consider the case where the `id` is specified for
    // `osd create`, and we must honor it. So this means checking if
    // the `id` is destroyed, and if so assume the destroy; otherwise,
    // check if it `exists` - in which case we complain about not being
    // `destroyed`. In the end, if nothing fails, we must allow the
    // creation, so that we are compatible with `create`.
    if (id >= 0 && osdmap.exists(id) && !osdmap.is_destroyed(id)) {
      dout(10) << __func__ << " osd." << id << " isn't destroyed" << dendl;
      ss << "OSD " << id << " has not yet been destroyed";
      return -EINVAL;
    } else if (id < 0) {
      // find an `id`
      id = _allocate_osd_id(&existing_id);
      if (id < 0) {
        ceph_assert(existing_id >= 0);
        id = existing_id;
      }
      dout(10) << __func__ << " found id " << id << " to use" << dendl;
    } else if (id >= 0 && osdmap.is_destroyed(id)) {
      dout(10) << __func__ << " recreating osd." << id << dendl;
    } else {
      dout(10) << __func__ << " creating new osd." << id << dendl;
    }
  } else {
    ceph_assert(id >= 0);
    ceph_assert(osdmap.exists(id));
  }

  // we are now able to either create a brand new osd or reuse an existing
  // osd that has been previously destroyed.

  dout(10) << __func__ << " id " << id << " uuid " << uuid << dendl;

  if (may_be_idempotent && params.empty()) {
    // nothing to do, really.
    dout(10) << __func__ << " idempotent and no params -- no op." << dendl;
    ceph_assert(id >= 0);
    if (f) {
      f->open_object_section("created_osd");
      f->dump_int("osdid", id);
      f->close_section();
    } else {
      ss << id;
    }
    return EEXIST;
  }

  string device_class;
  auto p = params.find("crush_device_class");
  if (p != params.end()) {
    device_class = p->second;
    dout(20) << __func__ << " device_class will be " << device_class << dendl;
  }
  string cephx_secret, lockbox_secret, dmcrypt_key;
  bool has_lockbox = false;
  bool has_secrets = params.count("cephx_secret")
    || params.count("cephx_lockbox_secret")
    || params.count("dmcrypt_key");

  ConfigKeyService *svc = nullptr;
  AuthMonitor::auth_entity_t cephx_entity, lockbox_entity;

  if (has_secrets) {
    if (params.count("cephx_secret") == 0) {
      ss << "requires a cephx secret.";
      return -EINVAL;
    }
    cephx_secret = params.at("cephx_secret");

    bool has_lockbox_secret = (params.count("cephx_lockbox_secret") > 0);
    bool has_dmcrypt_key = (params.count("dmcrypt_key") > 0);

    dout(10) << __func__ << " has lockbox " << has_lockbox_secret
             << " dmcrypt " << has_dmcrypt_key << dendl;

    if (has_lockbox_secret && has_dmcrypt_key) {
      has_lockbox = true;
      lockbox_secret = params.at("cephx_lockbox_secret");
      dmcrypt_key = params.at("dmcrypt_key");
    } else if (!has_lockbox_secret != !has_dmcrypt_key) {
      ss << "requires both a cephx lockbox secret and a dm-crypt key.";
      return -EINVAL;
    }

    dout(10) << __func__ << " validate secrets using osd id " << id << dendl;

    err = mon->authmon()->validate_osd_new(id, uuid,
        cephx_secret,
        lockbox_secret,
        cephx_entity,
        lockbox_entity,
        ss);
    if (err < 0) {
      return err;
    } else if (may_be_idempotent && err != EEXIST) {
      // for this to be idempotent, `id` should already be >= 0; no need
      // to use validate_id.
      ceph_assert(id >= 0);
      ss << "osd." << id << " exists but secrets do not match";
      return -EEXIST;
    }

    if (has_lockbox) {
      svc = (ConfigKeyService*)mon->config_key_service;
      err = svc->validate_osd_new(uuid, dmcrypt_key, ss);
      if (err < 0) {
        return err;
      } else if (may_be_idempotent && err != EEXIST) {
        ceph_assert(id >= 0);
        ss << "osd." << id << " exists but dm-crypt key does not match.";
        return -EEXIST;
      }
    }
  }
  ceph_assert(!has_secrets || !cephx_secret.empty());
  ceph_assert(!has_lockbox || !lockbox_secret.empty());

  if (may_be_idempotent) {
    // we have nothing to do for either the osdmon or the authmon,
    // and we have no lockbox - so the config key service will not be
    // touched. This is therefore an idempotent operation, and we can
    // just return right away.
    dout(10) << __func__ << " idempotent -- no op." << dendl;
    ceph_assert(id >= 0);
    if (f) {
      f->open_object_section("created_osd");
      f->dump_int("osdid", id);
      f->close_section();
    } else {
      ss << id;
    }
    return EEXIST;
  }
  ceph_assert(!may_be_idempotent);

  // perform updates.
  if (has_secrets) {
    ceph_assert(!cephx_secret.empty());
    ceph_assert((lockbox_secret.empty() && dmcrypt_key.empty()) ||
           (!lockbox_secret.empty() && !dmcrypt_key.empty()));

    err = mon->authmon()->do_osd_new(cephx_entity,
        lockbox_entity,
        has_lockbox);
    ceph_assert(0 == err);

    if (has_lockbox) {
      ceph_assert(nullptr != svc);
      svc->do_osd_new(uuid, dmcrypt_key);
    }
  }

  if (is_recreate_destroyed) {
    ceph_assert(id >= 0);
    ceph_assert(osdmap.is_destroyed(id));
    pending_inc.new_weight[id] = CEPH_OSD_OUT;
    pending_inc.new_state[id] |= CEPH_OSD_DESTROYED;
    if ((osdmap.get_state(id) & CEPH_OSD_NEW) == 0) {
      pending_inc.new_state[id] |= CEPH_OSD_NEW;
    }
    if (osdmap.get_state(id) & CEPH_OSD_UP) {
      // due to http://tracker.ceph.com/issues/20751 some clusters may
      // have UP set for non-existent OSDs; make sure it is cleared
      // for a newly created osd.
      pending_inc.new_state[id] |= CEPH_OSD_UP;
    }
    pending_inc.new_uuid[id] = uuid;
  } else {
    ceph_assert(id >= 0);
    int32_t new_id = -1;
    do_osd_create(id, uuid, device_class, &new_id);
    ceph_assert(new_id >= 0);
    ceph_assert(id == new_id);
  }

  if (f) {
    f->open_object_section("created_osd");
    f->dump_int("osdid", id);
    f->close_section();
  } else {
    ss << id;
  }

  return 0;
}

bool OSDMonitor::prepare_command(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  MMonCommand *m = static_cast<MMonCommand*>(op->get_req());
  stringstream ss;
  cmdmap_t cmdmap;
  if (!cmdmap_from_json(m->cmd, &cmdmap, ss)) {
    string rs = ss.str();
    mon->reply_command(op, -EINVAL, rs, get_last_committed());
    return true;
  }

  MonSession *session = op->get_session();
  if (!session) {
    derr << __func__ << " no session" << dendl;
    mon->reply_command(op, -EACCES, "access denied", get_last_committed());
    return true;
  }

  return prepare_command_impl(op, cmdmap);
}

static int parse_reweights(CephContext *cct,
			   const cmdmap_t& cmdmap,
			   const OSDMap& osdmap,
			   map<int32_t, uint32_t>* weights)
{
  string weights_str;
  if (!cmd_getval(cct, cmdmap, "weights", weights_str)) {
    return -EINVAL;
  }
  std::replace(begin(weights_str), end(weights_str), '\'', '"');
  json_spirit::mValue json_value;
  if (!json_spirit::read(weights_str, json_value)) {
    return -EINVAL;
  }
  if (json_value.type() != json_spirit::obj_type) {
    return -EINVAL;
  }
  const auto obj = json_value.get_obj();
  try {
    for (auto& osd_weight : obj) {
      auto osd_id = std::stoi(osd_weight.first);
      if (!osdmap.exists(osd_id)) {
	return -ENOENT;
      }
      if (osd_weight.second.type() != json_spirit::str_type) {
	return -EINVAL;
      }
      auto weight = std::stoul(osd_weight.second.get_str());
      weights->insert({osd_id, weight});
    }
  } catch (const std::logic_error& e) {
    return -EINVAL;
  }
  return 0;
}

int OSDMonitor::prepare_command_osd_destroy(
    int32_t id,
    stringstream& ss)
{
  ceph_assert(paxos->is_plugged());

  // we check if the osd exists for the benefit of `osd purge`, which may
  // have previously removed the osd. If the osd does not exist, return
  // -ENOENT to convey this, and let the caller deal with it.
  //
  // we presume that all auth secrets and config keys were removed prior
  // to this command being called. if they exist by now, we also assume
  // they must have been created by some other command and do not pertain
  // to this non-existent osd.
  if (!osdmap.exists(id)) {
    dout(10) << __func__ << " osd." << id << " does not exist." << dendl;
    return -ENOENT;
  }

  uuid_d uuid = osdmap.get_uuid(id);
  dout(10) << __func__ << " destroying osd." << id
           << " uuid " << uuid << dendl;

  // if it has been destroyed, we assume our work here is done.
  if (osdmap.is_destroyed(id)) {
    ss << "destroyed osd." << id;
    return 0;
  }

  EntityName cephx_entity, lockbox_entity;
  bool idempotent_auth = false, idempotent_cks = false;

  int err = mon->authmon()->validate_osd_destroy(id, uuid,
                                                 cephx_entity,
                                                 lockbox_entity,
                                                 ss);
  if (err < 0) {
    if (err == -ENOENT) {
      idempotent_auth = true;
    } else {
      return err;
    }
  }

  ConfigKeyService *svc = (ConfigKeyService*)mon->config_key_service;
  err = svc->validate_osd_destroy(id, uuid);
  if (err < 0) {
    ceph_assert(err == -ENOENT);
    err = 0;
    idempotent_cks = true;
  }

  if (!idempotent_auth) {
    err = mon->authmon()->do_osd_destroy(cephx_entity, lockbox_entity);
    ceph_assert(0 == err);
  }

  if (!idempotent_cks) {
    svc->do_osd_destroy(id, uuid);
  }

  pending_inc.new_state[id] = CEPH_OSD_DESTROYED;
  pending_inc.new_uuid[id] = uuid_d();

  // we can only propose_pending() once per service, otherwise we'll be
  // defying PaxosService and all laws of nature. Therefore, as we may
  // be used during 'osd purge', let's keep the caller responsible for
  // proposing.
  ceph_assert(err == 0);
  return 0;
}

int OSDMonitor::prepare_command_osd_purge(
    int32_t id,
    stringstream& ss)
{
  ceph_assert(paxos->is_plugged());
  dout(10) << __func__ << " purging osd." << id << dendl;

  ceph_assert(!osdmap.is_up(id));

  /*
   * This may look a bit weird, but this is what's going to happen:
   *
   *  1. we make sure that removing from crush works
   *  2. we call `prepare_command_osd_destroy()`. If it returns an
   *     error, then we abort the whole operation, as no updates
   *     have been made. However, we this function will have
   *     side-effects, thus we need to make sure that all operations
   *     performed henceforth will *always* succeed.
   *  3. we call `prepare_command_osd_remove()`. Although this
   *     function can return an error, it currently only checks if the
   *     osd is up - and we have made sure that it is not so, so there
   *     is no conflict, and it is effectively an update.
   *  4. finally, we call `do_osd_crush_remove()`, which will perform
   *     the crush update we delayed from before.
   */

  CrushWrapper newcrush;
  _get_pending_crush(newcrush);

  bool may_be_idempotent = false;

  int err = _prepare_command_osd_crush_remove(newcrush, id, 0, false, false);
  if (err == -ENOENT) {
    err = 0;
    may_be_idempotent = true;
  } else if (err < 0) {
    ss << "error removing osd." << id << " from crush";
    return err;
  }

  // no point destroying the osd again if it has already been marked destroyed
  if (!osdmap.is_destroyed(id)) {
    err = prepare_command_osd_destroy(id, ss);
    if (err < 0) {
      if (err == -ENOENT) {
        err = 0;
      } else {
        return err;
      }
    } else {
      may_be_idempotent = false;
    }
  }
  ceph_assert(0 == err);

  if (may_be_idempotent && !osdmap.exists(id)) {
    dout(10) << __func__ << " osd." << id << " does not exist and "
             << "we are idempotent." << dendl;
    return -ENOENT;
  }

  err = prepare_command_osd_remove(id);
  // we should not be busy, as we should have made sure this id is not up.
  ceph_assert(0 == err);

  do_osd_crush_remove(newcrush);
  return 0;
}

bool OSDMonitor::prepare_command_impl(MonOpRequestRef op,
				      const cmdmap_t& cmdmap)
{
  op->mark_osdmon_event(__func__);
  MMonCommand *m = static_cast<MMonCommand*>(op->get_req());
  bool ret = false;
  stringstream ss;
  string rs;
  bufferlist rdata;
  int err = 0;

  string format;
  cmd_getval(cct, cmdmap, "format", format, string("plain"));
  boost::scoped_ptr<Formatter> f(Formatter::create(format));

  string prefix;
  cmd_getval(cct, cmdmap, "prefix", prefix);

  int64_t osdid;
  string osd_name;
  bool osdid_present = false;
  if (prefix != "osd pg-temp" &&
      prefix != "osd pg-upmap" &&
      prefix != "osd pg-upmap-items") {  // avoid commands with non-int id arg
    osdid_present = cmd_getval(cct, cmdmap, "id", osdid);
  }
  if (osdid_present) {
    ostringstream oss;
    oss << "osd." << osdid;
    osd_name = oss.str();
  }

  // Even if there's a pending state with changes that could affect
  // a command, considering that said state isn't yet committed, we
  // just don't care about those changes if the command currently being
  // handled acts as a no-op against the current committed state.
  // In a nutshell, we assume this command  happens *before*.
  //
  // Let me make this clearer:
  //
  //   - If we have only one client, and that client issues some
  //     operation that would conflict with this operation  but is
  //     still on the pending state, then we would be sure that said
  //     operation wouldn't have returned yet, so the client wouldn't
  //     issue this operation (unless the client didn't wait for the
  //     operation to finish, and that would be the client's own fault).
  //
  //   - If we have more than one client, each client will observe
  //     whatever is the state at the moment of the commit.  So, if we
  //     have two clients, one issuing an unlink and another issuing a
  //     link, and if the link happens while the unlink is still on the
  //     pending state, from the link's point-of-view this is a no-op.
  //     If different clients are issuing conflicting operations and
  //     they care about that, then the clients should make sure they
  //     enforce some kind of concurrency mechanism -- from our
  //     perspective that's what Douglas Adams would call an SEP.
  //
  // This should be used as a general guideline for most commands handled
  // in this function.  Adapt as you see fit, but please bear in mind that
  // this is the expected behavior.
   
 
  if (prefix == "osd setcrushmap" ||
      (prefix == "osd crush set" && !osdid_present)) {
    if (pending_inc.crush.length()) {
      dout(10) << __func__ << " waiting for pending crush update " << dendl;
      wait_for_finished_proposal(op, new C_RetryMessage(this, op));
      return true;
    }
    dout(10) << "prepare_command setting new crush map" << dendl;
    bufferlist data(m->get_data());
    CrushWrapper crush;
    try {
      auto bl = data.cbegin();
      crush.decode(bl);
    }
    catch (const std::exception &e) {
      err = -EINVAL;
      ss << "Failed to parse crushmap: " << e.what();
      goto reply;
    }
  
    int64_t prior_version = 0;
    if (cmd_getval(cct, cmdmap, "prior_version", prior_version)) {
      if (prior_version == osdmap.get_crush_version() - 1) {
	// see if we are a resend of the last update.  this is imperfect
	// (multiple racing updaters may not both get reliable success)
	// but we expect crush updaters (via this interface) to be rare-ish.
	bufferlist current, proposed;
	osdmap.crush->encode(current, mon->get_quorum_con_features());
	crush.encode(proposed, mon->get_quorum_con_features());
	if (current.contents_equal(proposed)) {
	  dout(10) << __func__
		   << " proposed matches current and version equals previous"
		   << dendl;
	  err = 0;
	  ss << osdmap.get_crush_version();
	  goto reply;
	}
      }
      if (prior_version != osdmap.get_crush_version()) {
	err = -EPERM;
	ss << "prior_version " << prior_version << " != crush version "
	   << osdmap.get_crush_version();
	goto reply;
      }
    }

    if (crush.has_legacy_rule_ids()) {
      err = -EINVAL;
      ss << "crush maps with ruleset != ruleid are no longer allowed";
      goto reply;
    }
    if (!validate_crush_against_features(&crush, ss)) {
      err = -EINVAL;
      goto reply;
    }

    err = osdmap.validate_crush_rules(&crush, &ss);
    if (err < 0) {
      goto reply;
    }

    if (g_conf()->mon_osd_crush_smoke_test) {
      // sanity check: test some inputs to make sure this map isn't
      // totally broken
      dout(10) << " testing map" << dendl;
      stringstream ess;
      CrushTester tester(crush, ess);
      tester.set_min_x(0);
      tester.set_max_x(50);
      auto start = ceph::coarse_mono_clock::now();
      int r = tester.test_with_fork(g_conf()->mon_lease);
      auto duration = ceph::coarse_mono_clock::now() - start;
      if (r < 0) {
	dout(10) << " tester.test_with_fork returns " << r
		 << ": " << ess.str() << dendl;
	ss << "crush smoke test failed with " << r << ": " << ess.str();
	err = r;
	goto reply;
      }
      dout(10) << __func__ << " crush somke test duration: "
               << duration << ", result: " << ess.str() << dendl;
    }

    pending_inc.crush = data;
    ss << osdmap.get_crush_version() + 1;
    goto update;

  } else if (prefix == "osd crush set-all-straw-buckets-to-straw2") {
    CrushWrapper newcrush;
    _get_pending_crush(newcrush);
    for (int b = 0; b < newcrush.get_max_buckets(); ++b) {
      int bid = -1 - b;
      if (newcrush.bucket_exists(bid) &&
	  newcrush.get_bucket_alg(bid) == CRUSH_BUCKET_STRAW) {
	dout(20) << " bucket " << bid << " is straw, can convert" << dendl;
	newcrush.bucket_set_alg(bid, CRUSH_BUCKET_STRAW2);
      }
    }
    if (!validate_crush_against_features(&newcrush, ss)) {
      err = -EINVAL;
      goto reply;
    }
    pending_inc.crush.clear();
    newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
					      get_last_committed() + 1));
    return true;
  } else if (prefix == "osd crush set-device-class") {
    string device_class;
    if (!cmd_getval(cct, cmdmap, "class", device_class)) {
      err = -EINVAL; // no value!
      goto reply;
    }

    bool stop = false;
    vector<string> idvec;
    cmd_getval(cct, cmdmap, "ids", idvec);
    CrushWrapper newcrush;
    _get_pending_crush(newcrush);
    set<int> updated;
    for (unsigned j = 0; j < idvec.size() && !stop; j++) {
      set<int> osds;
      // wildcard?
      if (j == 0 &&
          (idvec[0] == "any" || idvec[0] == "all" || idvec[0] == "*")) {
        osdmap.get_all_osds(osds);
        stop = true;
      } else {
        // try traditional single osd way
        long osd = parse_osd_id(idvec[j].c_str(), &ss);
        if (osd < 0) {
          // ss has reason for failure
          ss << ", unable to parse osd id:\"" << idvec[j] << "\". ";
          err = -EINVAL;
          continue;
        }
        osds.insert(osd);
      }

      for (auto &osd : osds) {
        if (!osdmap.exists(osd)) {
          ss << "osd." << osd << " does not exist. ";
          continue;
        }

        ostringstream oss;
        oss << "osd." << osd;
        string name = oss.str();

	if (newcrush.get_max_devices() < osd + 1) {
	  newcrush.set_max_devices(osd + 1);
	}
        string action;
        if (newcrush.item_exists(osd)) {
          action = "updating";
        } else {
          action = "creating";
          newcrush.set_item_name(osd, name);
        }

        dout(5) << action << " crush item id " << osd << " name '" << name
                << "' device_class '" << device_class << "'"
                << dendl;
        err = newcrush.update_device_class(osd, device_class, name, &ss);
        if (err < 0) {
          goto reply;
        }
        if (err == 0 && !_have_pending_crush()) {
          if (!stop) {
            // for single osd only, wildcard makes too much noise
            ss << "set-device-class item id " << osd << " name '" << name
               << "' device_class '" << device_class << "': no change. ";
          }
        } else {
          updated.insert(osd);
        }
      }
    }

    if (!updated.empty()) {
      pending_inc.crush.clear();
      newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
      ss << "set osd(s) " << updated << " to class '" << device_class << "'";
      getline(ss, rs);
      wait_for_finished_proposal(op,
        new Monitor::C_Command(mon,op, 0, rs, get_last_committed() + 1));
      return true;
    }

 } else if (prefix == "osd crush rm-device-class") {
    bool stop = false;
    vector<string> idvec;
    cmd_getval(cct, cmdmap, "ids", idvec);
    CrushWrapper newcrush;
    _get_pending_crush(newcrush);
    set<int> updated;

    for (unsigned j = 0; j < idvec.size() && !stop; j++) {
      set<int> osds;

      // wildcard?
      if (j == 0 &&
          (idvec[0] == "any" || idvec[0] == "all" || idvec[0] == "*")) {
        osdmap.get_all_osds(osds);
        stop = true;
      } else {
        // try traditional single osd way
        long osd = parse_osd_id(idvec[j].c_str(), &ss);
        if (osd < 0) {
          // ss has reason for failure
          ss << ", unable to parse osd id:\"" << idvec[j] << "\". ";
          err = -EINVAL;
          goto reply;
        }
        osds.insert(osd);
      }

      for (auto &osd : osds) {
        if (!osdmap.exists(osd)) {
          ss << "osd." << osd << " does not exist. ";
          continue;
        }

        auto class_name = newcrush.get_item_class(osd);
        if (!class_name) {
          ss << "osd." << osd << " belongs to no class, ";
          continue;
        }
        // note that we do not verify if class_is_in_use here
        // in case the device is misclassified and user wants
        // to overridely reset...

        err = newcrush.remove_device_class(cct, osd, &ss);
        if (err < 0) {
          // ss has reason for failure
          goto reply;
        }
        updated.insert(osd);
      }
    }

    if (!updated.empty()) {
      pending_inc.crush.clear();
      newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
      ss << "done removing class of osd(s): " << updated;
      getline(ss, rs);
      wait_for_finished_proposal(op,
        new Monitor::C_Command(mon,op, 0, rs, get_last_committed() + 1));
      return true;
    }
  } else if (prefix == "osd crush class create") {
    string device_class;
    if (!cmd_getval(g_ceph_context, cmdmap, "class", device_class)) {
      err = -EINVAL; // no value!
      goto reply;
    }
    if (osdmap.require_osd_release < CEPH_RELEASE_LUMINOUS) {
      ss << "you must complete the upgrade and 'ceph osd require-osd-release "
         << "luminous' before using crush device classes";
      err = -EPERM;
      goto reply;
    }
    if (!_have_pending_crush() &&
        _get_stable_crush().class_exists(device_class)) {
      ss << "class '" << device_class << "' already exists";
      goto reply;
    }
     CrushWrapper newcrush;
    _get_pending_crush(newcrush);
     if (newcrush.class_exists(device_class)) {
      ss << "class '" << device_class << "' already exists";
      goto update;
    }
    int class_id = newcrush.get_or_create_class_id(device_class);
    pending_inc.crush.clear();
    newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
    ss << "created class " << device_class << " with id " << class_id
       << " to crush map";
    goto update;
  } else if (prefix == "osd crush class rm") {
    string device_class;
    if (!cmd_getval(g_ceph_context, cmdmap, "class", device_class)) {
       err = -EINVAL; // no value!
       goto reply;
     }
     if (osdmap.require_osd_release < CEPH_RELEASE_LUMINOUS) {
       ss << "you must complete the upgrade and 'ceph osd require-osd-release "
         << "luminous' before using crush device classes";
       err = -EPERM;
       goto reply;
     }

     if (!osdmap.crush->class_exists(device_class)) {
       err = 0;
       goto reply;
     }

     CrushWrapper newcrush;
     _get_pending_crush(newcrush);
     if (!newcrush.class_exists(device_class)) {
       err = 0; // make command idempotent
       goto wait;
     }
     int class_id = newcrush.get_class_id(device_class);
     stringstream ts;
     if (newcrush.class_is_in_use(class_id, &ts)) {
       err = -EBUSY;
       ss << "class '" << device_class << "' " << ts.str();
       goto reply;
     }

     // check if class is used by any erasure-code-profiles
     mempool::osdmap::map<string,map<string,string>> old_ec_profiles =
       osdmap.get_erasure_code_profiles();
     auto ec_profiles = pending_inc.get_erasure_code_profiles();
#ifdef HAVE_STDLIB_MAP_SPLICING
     ec_profiles.merge(old_ec_profiles);
#else
     ec_profiles.insert(make_move_iterator(begin(old_ec_profiles)),
                        make_move_iterator(end(old_ec_profiles)));
#endif
     list<string> referenced_by;
     for (auto &i: ec_profiles) {
       for (auto &j: i.second) {
         if ("crush-device-class" == j.first && device_class == j.second) {
           referenced_by.push_back(i.first);
         }
       }
     }
     if (!referenced_by.empty()) {
       err = -EBUSY;
       ss << "class '" << device_class
          << "' is still referenced by erasure-code-profile(s): " << referenced_by;
       goto reply;
     }

     set<int> osds;
     newcrush.get_devices_by_class(device_class, &osds);
     for (auto& p: osds) {
       err = newcrush.remove_device_class(g_ceph_context, p, &ss);
       if (err < 0) {
         // ss has reason for failure
         goto reply;
       }
     }

     if (osds.empty()) {
       // empty class, remove directly
       err = newcrush.remove_class_name(device_class);
       if (err < 0) {
         ss << "class '" << device_class << "' cannot be removed '"
            << cpp_strerror(err) << "'";
         goto reply;
       }
     }

     pending_inc.crush.clear();
     newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
     ss << "removed class " << device_class << " with id " << class_id
        << " from crush map";
     goto update;
  } else if (prefix == "osd crush class rename") {
    string srcname, dstname;
    if (!cmd_getval(cct, cmdmap, "srcname", srcname)) {
      err = -EINVAL;
      goto reply;
    }
    if (!cmd_getval(cct, cmdmap, "dstname", dstname)) {
      err = -EINVAL;
      goto reply;
    }

    CrushWrapper newcrush;
    _get_pending_crush(newcrush);
    if (!newcrush.class_exists(srcname) && newcrush.class_exists(dstname)) {
      // suppose this is a replay and return success
      // so command is idempotent
      ss << "already renamed to '" << dstname << "'";
      err = 0;
      goto reply;
    }

    err = newcrush.rename_class(srcname, dstname);
    if (err < 0) {
      ss << "fail to rename '" << srcname << "' to '" << dstname << "' : "
         << cpp_strerror(err);
      goto reply;
    }

    pending_inc.crush.clear();
    newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
    ss << "rename class '" << srcname << "' to '" << dstname << "'";
    goto update;
  } else if (prefix == "osd crush add-bucket") {
    // os crush add-bucket <name> <type>
    string name, typestr;
    vector<string> argvec;
    cmd_getval(cct, cmdmap, "name", name);
    cmd_getval(cct, cmdmap, "type", typestr);
    cmd_getval(cct, cmdmap, "args", argvec);
    map<string,string> loc;
    if (!argvec.empty()) {
      CrushWrapper::parse_loc_map(argvec, &loc);
      dout(0) << "will create and move bucket '" << name
              << "' to location " << loc << dendl;
    }

    if (!_have_pending_crush() &&
	_get_stable_crush().name_exists(name)) {
      ss << "bucket '" << name << "' already exists";
      goto reply;
    }

    CrushWrapper newcrush;
    _get_pending_crush(newcrush);

    if (newcrush.name_exists(name)) {
      ss << "bucket '" << name << "' already exists";
      goto update;
    }
    int type = newcrush.get_type_id(typestr);
    if (type < 0) {
      ss << "type '" << typestr << "' does not exist";
      err = -EINVAL;
      goto reply;
    }
    if (type == 0) {
      ss << "type '" << typestr << "' is for devices, not buckets";
      err = -EINVAL;
      goto reply;
    }
    int bucketno;
    err = newcrush.add_bucket(0, 0,
			      CRUSH_HASH_DEFAULT, type, 0, NULL,
			      NULL, &bucketno);
    if (err < 0) {
      ss << "add_bucket error: '" << cpp_strerror(err) << "'";
      goto reply;
    }
    err = newcrush.set_item_name(bucketno, name);
    if (err < 0) {
      ss << "error setting bucket name to '" << name << "'";
      goto reply;
    }

    if (!loc.empty()) {
      if (!newcrush.check_item_loc(cct, bucketno, loc,
          (int *)NULL)) {
        err = newcrush.move_bucket(cct, bucketno, loc);
        if (err < 0) {
          ss << "error moving bucket '" << name << "' to location " << loc;
          goto reply;
        }
      } else {
        ss << "no need to move item id " << bucketno << " name '" << name
           << "' to location " << loc << " in crush map";
      }
    }

    pending_inc.crush.clear();
    newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
    if (loc.empty()) {
      ss << "added bucket " << name << " type " << typestr
         << " to crush map";
    } else {
      ss << "added bucket " << name << " type " << typestr
         << " to location " << loc;
    }
    goto update;
  } else if (prefix == "osd crush rename-bucket") {
    string srcname, dstname;
    cmd_getval(cct, cmdmap, "srcname", srcname);
    cmd_getval(cct, cmdmap, "dstname", dstname);

    err = crush_rename_bucket(srcname, dstname, &ss);
    if (err == -EALREADY) // equivalent to success for idempotency
      err = 0;
    if (err)
      goto reply;
    else
      goto update;
  } else if (prefix == "osd crush weight-set create" ||
	     prefix == "osd crush weight-set create-compat") {
    CrushWrapper newcrush;
    _get_pending_crush(newcrush);
    int64_t pool;
    int positions;
    if (newcrush.has_non_straw2_buckets()) {
      ss << "crush map contains one or more bucket(s) that are not straw2";
      err = -EPERM;
      goto reply;
    }
    if (prefix == "osd crush weight-set create") {
      if (osdmap.require_min_compat_client > 0 &&
	  osdmap.require_min_compat_client < CEPH_RELEASE_LUMINOUS) {
	ss << "require_min_compat_client "
	   << ceph_release_name(osdmap.require_min_compat_client)
	   << " < luminous, which is required for per-pool weight-sets. "
           << "Try 'ceph osd set-require-min-compat-client luminous' "
           << "before using the new interface";
	err = -EPERM;
	goto reply;
      }
      string poolname, mode;
      cmd_getval(cct, cmdmap, "pool", poolname);
      pool = osdmap.lookup_pg_pool_name(poolname.c_str());
      if (pool < 0) {
	ss << "pool '" << poolname << "' not found";
	err = -ENOENT;
	goto reply;
      }
      cmd_getval(cct, cmdmap, "mode", mode);
      if (mode != "flat" && mode != "positional") {
	ss << "unrecognized weight-set mode '" << mode << "'";
	err = -EINVAL;
	goto reply;
      }
      positions = mode == "flat" ? 1 : osdmap.get_pg_pool(pool)->get_size();
    } else {
      pool = CrushWrapper::DEFAULT_CHOOSE_ARGS;
      positions = 1;
    }
    if (!newcrush.create_choose_args(pool, positions)) {
      if (pool == CrushWrapper::DEFAULT_CHOOSE_ARGS) {
        ss << "compat weight-set already created";
      } else {
        ss << "weight-set for pool '" << osdmap.get_pool_name(pool)
           << "' already created";
      }
      goto reply;
    }
    pending_inc.crush.clear();
    newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
    goto update;

  } else if (prefix == "osd crush weight-set rm" ||
	     prefix == "osd crush weight-set rm-compat") {
    CrushWrapper newcrush;
    _get_pending_crush(newcrush);
    int64_t pool;
    if (prefix == "osd crush weight-set rm") {
      string poolname;
      cmd_getval(cct, cmdmap, "pool", poolname);
      pool = osdmap.lookup_pg_pool_name(poolname.c_str());
      if (pool < 0) {
	ss << "pool '" << poolname << "' not found";
	err = -ENOENT;
	goto reply;
      }
    } else {
      pool = CrushWrapper::DEFAULT_CHOOSE_ARGS;
    }
    newcrush.rm_choose_args(pool);
    pending_inc.crush.clear();
    newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
    goto update;

  } else if (prefix == "osd crush weight-set reweight" ||
	     prefix == "osd crush weight-set reweight-compat") {
    string poolname, item;
    vector<double> weight;
    cmd_getval(cct, cmdmap, "pool", poolname);
    cmd_getval(cct, cmdmap, "item", item);
    cmd_getval(cct, cmdmap, "weight", weight);
    CrushWrapper newcrush;
    _get_pending_crush(newcrush);
    int64_t pool;
    if (prefix == "osd crush weight-set reweight") {
      pool = osdmap.lookup_pg_pool_name(poolname.c_str());
      if (pool < 0) {
	ss << "pool '" << poolname << "' not found";
	err = -ENOENT;
	goto reply;
      }
      if (!newcrush.have_choose_args(pool)) {
	ss << "no weight-set for pool '" << poolname << "'";
	err = -ENOENT;
	goto reply;
      }
      auto arg_map = newcrush.choose_args_get(pool);
      int positions = newcrush.get_choose_args_positions(arg_map);
      if (weight.size() != (size_t)positions) {
         ss << "must specify exact " << positions << " weight values";
         err = -EINVAL;
         goto reply;
      }
    } else {
      pool = CrushWrapper::DEFAULT_CHOOSE_ARGS;
      if (!newcrush.have_choose_args(pool)) {
	ss << "no backward-compatible weight-set";
	err = -ENOENT;
	goto reply;
      }
    }
    if (!newcrush.name_exists(item)) {
      ss << "item '" << item << "' does not exist";
      err = -ENOENT;
      goto reply;
    }
    err = newcrush.choose_args_adjust_item_weightf(
      cct,
      newcrush.choose_args_get(pool),
      newcrush.get_item_id(item),
      weight,
      &ss);
    if (err < 0) {
      goto reply;
    }
    err = 0;
    pending_inc.crush.clear();
    newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
    goto update;
  } else if (osdid_present &&
	     (prefix == "osd crush set" || prefix == "osd crush add")) {
    // <OsdName> is 'osd.<id>' or '<id>', passed as int64_t id
    // osd crush set <OsdName> <weight> <loc1> [<loc2> ...]
    // osd crush add <OsdName> <weight> <loc1> [<loc2> ...]

    if (!osdmap.exists(osdid)) {
      err = -ENOENT;
      ss << osd_name
	 << " does not exist. Create it before updating the crush map";
      goto reply;
    }

    double weight;
    if (!cmd_getval(cct, cmdmap, "weight", weight)) {
      ss << "unable to parse weight value '"
         << cmd_vartype_stringify(cmdmap.at("weight")) << "'";
      err = -EINVAL;
      goto reply;
    }

    string args;
    vector<string> argvec;
    cmd_getval(cct, cmdmap, "args", argvec);
    map<string,string> loc;
    CrushWrapper::parse_loc_map(argvec, &loc);

    if (prefix == "osd crush set"
        && !_get_stable_crush().item_exists(osdid)) {
      err = -ENOENT;
      ss << "unable to set item id " << osdid << " name '" << osd_name
         << "' weight " << weight << " at location " << loc
         << ": does not exist";
      goto reply;
    }

    dout(5) << "adding/updating crush item id " << osdid << " name '"
      << osd_name << "' weight " << weight << " at location "
      << loc << dendl;
    CrushWrapper newcrush;
    _get_pending_crush(newcrush);

    string action;
    if (prefix == "osd crush set" ||
        newcrush.check_item_loc(cct, osdid, loc, (int *)NULL)) {
      action = "set";
      err = newcrush.update_item(cct, osdid, weight, osd_name, loc);
    } else {
      action = "add";
      err = newcrush.insert_item(cct, osdid, weight, osd_name, loc);
      if (err == 0)
        err = 1;
    }

    if (err < 0)
      goto reply;

    if (err == 0 && !_have_pending_crush()) {
      ss << action << " item id " << osdid << " name '" << osd_name
	 << "' weight " << weight << " at location " << loc << ": no change";
      goto reply;
    }

    pending_inc.crush.clear();
    newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
    ss << action << " item id " << osdid << " name '" << osd_name << "' weight "
       << weight << " at location " << loc << " to crush map";
    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
						      get_last_committed() + 1));
    return true;

  } else if (prefix == "osd crush create-or-move") {
    do {
      // osd crush create-or-move <OsdName> <initial_weight> <loc1> [<loc2> ...]
      if (!osdmap.exists(osdid)) {
	err = -ENOENT;
	ss << osd_name
	   << " does not exist.  create it before updating the crush map";
	goto reply;
      }

      double weight;
      if (!cmd_getval(cct, cmdmap, "weight", weight)) {
        ss << "unable to parse weight value '"
           << cmd_vartype_stringify(cmdmap.at("weight")) << "'";
        err = -EINVAL;
        goto reply;
      }

      string args;
      vector<string> argvec;
      cmd_getval(cct, cmdmap, "args", argvec);
      map<string,string> loc;
      CrushWrapper::parse_loc_map(argvec, &loc);

      dout(0) << "create-or-move crush item name '" << osd_name
	      << "' initial_weight " << weight << " at location " << loc
	      << dendl;

      CrushWrapper newcrush;
      _get_pending_crush(newcrush);

      err = newcrush.create_or_move_item(cct, osdid, weight, osd_name, loc,
					 g_conf()->osd_crush_update_weight_set);
      if (err == 0) {
	ss << "create-or-move updated item name '" << osd_name
	   << "' weight " << weight
	   << " at location " << loc << " to crush map";
	break;
      }
      if (err > 0) {
	pending_inc.crush.clear();
	newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
	ss << "create-or-move updating item name '" << osd_name
	   << "' weight " << weight
	   << " at location " << loc << " to crush map";
	getline(ss, rs);
	wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
						  get_last_committed() + 1));
	return true;
      }
    } while (false);

  } else if (prefix == "osd crush move") {
    do {
      // osd crush move <name> <loc1> [<loc2> ...]
      string name;
      vector<string> argvec;
      cmd_getval(cct, cmdmap, "name", name);
      cmd_getval(cct, cmdmap, "args", argvec);
      map<string,string> loc;
      CrushWrapper::parse_loc_map(argvec, &loc);

      dout(0) << "moving crush item name '" << name << "' to location " << loc << dendl;
      CrushWrapper newcrush;
      _get_pending_crush(newcrush);

      if (!newcrush.name_exists(name)) {
	err = -ENOENT;
	ss << "item " << name << " does not exist";
	break;
      }
      int id = newcrush.get_item_id(name);

      if (!newcrush.check_item_loc(cct, id, loc, (int *)NULL)) {
	if (id >= 0) {
	  err = newcrush.create_or_move_item(
	    cct, id, 0, name, loc,
	    g_conf()->osd_crush_update_weight_set);
	} else {
	  err = newcrush.move_bucket(cct, id, loc);
	}
	if (err >= 0) {
	  ss << "moved item id " << id << " name '" << name << "' to location " << loc << " in crush map";
	  pending_inc.crush.clear();
	  newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
	  getline(ss, rs);
	  wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
						   get_last_committed() + 1));
	  return true;
	}
      } else {
	ss << "no need to move item id " << id << " name '" << name << "' to location " << loc << " in crush map";
	err = 0;
      }
    } while (false);
  } else if (prefix == "osd crush swap-bucket") {
    string source, dest;
    cmd_getval(cct, cmdmap, "source", source);
    cmd_getval(cct, cmdmap, "dest", dest);

    bool force = false;
    cmd_getval(cct, cmdmap, "yes_i_really_mean_it", force);

    CrushWrapper newcrush;
    _get_pending_crush(newcrush);
    if (!newcrush.name_exists(source)) {
      ss << "source item " << source << " does not exist";
      err = -ENOENT;
      goto reply;
    }
    if (!newcrush.name_exists(dest)) {
      ss << "dest item " << dest << " does not exist";
      err = -ENOENT;
      goto reply;
    }
    int sid = newcrush.get_item_id(source);
    int did = newcrush.get_item_id(dest);
    int sparent;
    if (newcrush.get_immediate_parent_id(sid, &sparent) == 0 && !force) {
      ss << "source item " << source << " is not an orphan bucket; pass --yes-i-really-mean-it to proceed anyway";
      err = -EPERM;
      goto reply;
    }
    if (newcrush.get_bucket_alg(sid) != newcrush.get_bucket_alg(did) &&
	!force) {
      ss << "source bucket alg " << crush_alg_name(newcrush.get_bucket_alg(sid)) << " != "
	 << "dest bucket alg " << crush_alg_name(newcrush.get_bucket_alg(did))
	 << "; pass --yes-i-really-mean-it to proceed anyway";
      err = -EPERM;
      goto reply;
    }
    int r = newcrush.swap_bucket(cct, sid, did);
    if (r < 0) {
      ss << "failed to swap bucket contents: " << cpp_strerror(r);
      err = r;
      goto reply;
    }
    ss << "swapped bucket of " << source << " to " << dest;
    pending_inc.crush.clear();
    newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
    wait_for_finished_proposal(op,
			       new Monitor::C_Command(mon, op, err, ss.str(),
						      get_last_committed() + 1));
    return true;
  } else if (prefix == "osd crush link") {
    // osd crush link <name> <loc1> [<loc2> ...]
    string name;
    cmd_getval(cct, cmdmap, "name", name);
    vector<string> argvec;
    cmd_getval(cct, cmdmap, "args", argvec);
    map<string,string> loc;
    CrushWrapper::parse_loc_map(argvec, &loc);

    // Need an explicit check for name_exists because get_item_id returns
    // 0 on unfound.
    int id = osdmap.crush->get_item_id(name);
    if (!osdmap.crush->name_exists(name)) {
      err = -ENOENT;
      ss << "item " << name << " does not exist";
      goto reply;
    } else {
      dout(5) << "resolved crush name '" << name << "' to id " << id << dendl;
    }
    if (osdmap.crush->check_item_loc(cct, id, loc, (int*) NULL)) {
      ss << "no need to move item id " << id << " name '" << name
	 << "' to location " << loc << " in crush map";
      err = 0;
      goto reply;
    }

    dout(5) << "linking crush item name '" << name << "' at location " << loc << dendl;
    CrushWrapper newcrush;
    _get_pending_crush(newcrush);

    if (!newcrush.name_exists(name)) {
      err = -ENOENT;
      ss << "item " << name << " does not exist";
      goto reply;
    } else {
      int id = newcrush.get_item_id(name);
      if (!newcrush.check_item_loc(cct, id, loc, (int *)NULL)) {
	err = newcrush.link_bucket(cct, id, loc);
	if (err >= 0) {
	  ss << "linked item id " << id << " name '" << name
             << "' to location " << loc << " in crush map";
	  pending_inc.crush.clear();
	  newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
	} else {
	  ss << "cannot link item id " << id << " name '" << name
             << "' to location " << loc;
          goto reply;
	}
      } else {
	ss << "no need to move item id " << id << " name '" << name
           << "' to location " << loc << " in crush map";
	err = 0;
      }
    }
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, err, ss.str(),
					      get_last_committed() + 1));
    return true;
  } else if (prefix == "osd crush rm" ||
	     prefix == "osd crush remove" ||
	     prefix == "osd crush unlink") {
    do {
      // osd crush rm <id> [ancestor]
      CrushWrapper newcrush;
      _get_pending_crush(newcrush);

      string name;
      cmd_getval(cct, cmdmap, "name", name);

      if (!osdmap.crush->name_exists(name)) {
	err = 0;
	ss << "device '" << name << "' does not appear in the crush map";
	break;
      }
      if (!newcrush.name_exists(name)) {
	err = 0;
	ss << "device '" << name << "' does not appear in the crush map";
	getline(ss, rs);
	wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
						  get_last_committed() + 1));
	return true;
      }
      int id = newcrush.get_item_id(name);
      int ancestor = 0;

      bool unlink_only = prefix == "osd crush unlink";
      string ancestor_str;
      if (cmd_getval(cct, cmdmap, "ancestor", ancestor_str)) {
	if (!newcrush.name_exists(ancestor_str)) {
	  err = -ENOENT;
	  ss << "ancestor item '" << ancestor_str
	     << "' does not appear in the crush map";
	  break;
	}
        ancestor = newcrush.get_item_id(ancestor_str);
      }

      err = prepare_command_osd_crush_remove(
          newcrush,
          id, ancestor,
          (ancestor < 0), unlink_only);

      if (err == -ENOENT) {
	ss << "item " << id << " does not appear in that position";
	err = 0;
	break;
      }
      if (err == 0) {
        if (!unlink_only)
          pending_inc.new_crush_node_flags[id] = 0;
	ss << "removed item id " << id << " name '" << name << "' from crush map";
	getline(ss, rs);
	wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
						  get_last_committed() + 1));
	return true;
      }
    } while (false);

  } else if (prefix == "osd crush reweight-all") {
    CrushWrapper newcrush;
    _get_pending_crush(newcrush);

    newcrush.reweight(cct);
    pending_inc.crush.clear();
    newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
    ss << "reweighted crush hierarchy";
    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
						  get_last_committed() + 1));
    return true;
  } else if (prefix == "osd crush reweight") {
    // osd crush reweight <name> <weight>
    CrushWrapper newcrush;
    _get_pending_crush(newcrush);

    string name;
    cmd_getval(cct, cmdmap, "name", name);
    if (!newcrush.name_exists(name)) {
      err = -ENOENT;
      ss << "device '" << name << "' does not appear in the crush map";
      goto reply;
    }

    int id = newcrush.get_item_id(name);
    if (id < 0) {
      ss << "device '" << name << "' is not a leaf in the crush map";
      err = -EINVAL;
      goto reply;
    }
    double w;
    if (!cmd_getval(cct, cmdmap, "weight", w)) {
      ss << "unable to parse weight value '"
	 << cmd_vartype_stringify(cmdmap.at("weight")) << "'";
      err = -EINVAL;
      goto reply;
    }

    err = newcrush.adjust_item_weightf(cct, id, w,
				       g_conf()->osd_crush_update_weight_set);
    if (err < 0)
      goto reply;
    pending_inc.crush.clear();
    newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
    ss << "reweighted item id " << id << " name '" << name << "' to " << w
       << " in crush map";
    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
						  get_last_committed() + 1));
    return true;
  } else if (prefix == "osd crush reweight-subtree") {
    // osd crush reweight <name> <weight>
    CrushWrapper newcrush;
    _get_pending_crush(newcrush);

    string name;
    cmd_getval(cct, cmdmap, "name", name);
    if (!newcrush.name_exists(name)) {
      err = -ENOENT;
      ss << "device '" << name << "' does not appear in the crush map";
      goto reply;
    }

    int id = newcrush.get_item_id(name);
    if (id >= 0) {
      ss << "device '" << name << "' is not a subtree in the crush map";
      err = -EINVAL;
      goto reply;
    }
    double w;
    if (!cmd_getval(cct, cmdmap, "weight", w)) {
      ss << "unable to parse weight value '"
	 << cmd_vartype_stringify(cmdmap.at("weight")) << "'";
      err = -EINVAL;
      goto reply;
    }

    err = newcrush.adjust_subtree_weightf(cct, id, w,
					  g_conf()->osd_crush_update_weight_set);
    if (err < 0)
      goto reply;
    pending_inc.crush.clear();
    newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
    ss << "reweighted subtree id " << id << " name '" << name << "' to " << w
       << " in crush map";
    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
					      get_last_committed() + 1));
    return true;
  } else if (prefix == "osd crush tunables") {
    CrushWrapper newcrush;
    _get_pending_crush(newcrush);

    err = 0;
    string profile;
    cmd_getval(cct, cmdmap, "profile", profile);
    if (profile == "legacy" || profile == "argonaut") {
      newcrush.set_tunables_legacy();
    } else if (profile == "bobtail") {
      newcrush.set_tunables_bobtail();
    } else if (profile == "firefly") {
      newcrush.set_tunables_firefly();
    } else if (profile == "hammer") {
      newcrush.set_tunables_hammer();
    } else if (profile == "jewel") {
      newcrush.set_tunables_jewel();
    } else if (profile == "optimal") {
      newcrush.set_tunables_optimal();
    } else if (profile == "default") {
      newcrush.set_tunables_default();
    } else {
      ss << "unrecognized profile '" << profile << "'";
      err = -EINVAL;
      goto reply;
    }

    if (!validate_crush_against_features(&newcrush, ss)) {
      err = -EINVAL;
      goto reply;
    }

    pending_inc.crush.clear();
    newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
    ss << "adjusted tunables profile to " << profile;
    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
					      get_last_committed() + 1));
    return true;
  } else if (prefix == "osd crush set-tunable") {
    CrushWrapper newcrush;
    _get_pending_crush(newcrush);

    err = 0;
    string tunable;
    cmd_getval(cct, cmdmap, "tunable", tunable);

    int64_t value = -1;
    if (!cmd_getval(cct, cmdmap, "value", value)) {
      err = -EINVAL;
      ss << "failed to parse integer value "
	 << cmd_vartype_stringify(cmdmap.at("value"));
      goto reply;
    }

    if (tunable == "straw_calc_version") {
      if (value != 0 && value != 1) {
	ss << "value must be 0 or 1; got " << value;
	err = -EINVAL;
	goto reply;
      }
      newcrush.set_straw_calc_version(value);
    } else {
      ss << "unrecognized tunable '" << tunable << "'";
      err = -EINVAL;
      goto reply;
    }

    if (!validate_crush_against_features(&newcrush, ss)) {
      err = -EINVAL;
      goto reply;
    }

    pending_inc.crush.clear();
    newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
    ss << "adjusted tunable " << tunable << " to " << value;
    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
					      get_last_committed() + 1));
    return true;

  } else if (prefix == "osd crush rule create-simple") {
    string name, root, type, mode;
    cmd_getval(cct, cmdmap, "name", name);
    cmd_getval(cct, cmdmap, "root", root);
    cmd_getval(cct, cmdmap, "type", type);
    cmd_getval(cct, cmdmap, "mode", mode);
    if (mode == "")
      mode = "firstn";

    if (osdmap.crush->rule_exists(name)) {
      // The name is uniquely associated to a ruleid and the rule it contains
      // From the user point of view, the rule is more meaningfull.
      ss << "rule " << name << " already exists";
      err = 0;
      goto reply;
    }

    CrushWrapper newcrush;
    _get_pending_crush(newcrush);

    if (newcrush.rule_exists(name)) {
      // The name is uniquely associated to a ruleid and the rule it contains
      // From the user point of view, the rule is more meaningfull.
      ss << "rule " << name << " already exists";
      err = 0;
    } else {
      int ruleno = newcrush.add_simple_rule(name, root, type, "", mode,
					       pg_pool_t::TYPE_REPLICATED, &ss);
      if (ruleno < 0) {
	err = ruleno;
	goto reply;
      }

      pending_inc.crush.clear();
      newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
    }
    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
					      get_last_committed() + 1));
    return true;

  } else if (prefix == "osd crush rule create-replicated") {
    string name, root, type, device_class;
    cmd_getval(cct, cmdmap, "name", name);
    cmd_getval(cct, cmdmap, "root", root);
    cmd_getval(cct, cmdmap, "type", type);
    cmd_getval(cct, cmdmap, "class", device_class);

    if (osdmap.crush->rule_exists(name)) {
      // The name is uniquely associated to a ruleid and the rule it contains
      // From the user point of view, the rule is more meaningfull.
      ss << "rule " << name << " already exists";
      err = 0;
      goto reply;
    }

    CrushWrapper newcrush;
    _get_pending_crush(newcrush);

    if (newcrush.rule_exists(name)) {
      // The name is uniquely associated to a ruleid and the rule it contains
      // From the user point of view, the rule is more meaningfull.
      ss << "rule " << name << " already exists";
      err = 0;
    } else {
      int ruleno = newcrush.add_simple_rule(
	name, root, type, device_class,
	"firstn", pg_pool_t::TYPE_REPLICATED, &ss);
      if (ruleno < 0) {
	err = ruleno;
	goto reply;
      }

      pending_inc.crush.clear();
      newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
    }
    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
					      get_last_committed() + 1));
    return true;

  } else if (prefix == "osd erasure-code-profile rm") {
    string name;
    cmd_getval(cct, cmdmap, "name", name);

    if (erasure_code_profile_in_use(pending_inc.new_pools, name, &ss))
      goto wait;

    if (erasure_code_profile_in_use(osdmap.pools, name, &ss)) {
      err = -EBUSY;
      goto reply;
    }

    if (osdmap.has_erasure_code_profile(name) ||
	pending_inc.new_erasure_code_profiles.count(name)) {
      if (osdmap.has_erasure_code_profile(name)) {
	pending_inc.old_erasure_code_profiles.push_back(name);
      } else {
	dout(20) << "erasure code profile rm " << name << ": creation canceled" << dendl;
	pending_inc.new_erasure_code_profiles.erase(name);
      }

      getline(ss, rs);
      wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
							get_last_committed() + 1));
      return true;
    } else {
      ss << "erasure-code-profile " << name << " does not exist";
      err = 0;
      goto reply;
    }

  } else if (prefix == "osd erasure-code-profile set") {
    string name;
    cmd_getval(cct, cmdmap, "name", name);
    vector<string> profile;
    cmd_getval(cct, cmdmap, "profile", profile);

    bool force = false;
    cmd_getval(cct, cmdmap, "force", force);

    map<string,string> profile_map;
    err = parse_erasure_code_profile(profile, &profile_map, &ss);
    if (err)
      goto reply;
    if (auto found = profile_map.find("crush-failure-domain");
	found != profile_map.end()) {
      const auto& failure_domain = found->second;
      int failure_domain_type = osdmap.crush->get_type_id(failure_domain);
      if (failure_domain_type < 0) {
	ss << "erasure-code-profile " << profile_map
	  << " contains an invalid failure-domain " << std::quoted(failure_domain);
	err = -EINVAL;
	goto reply;
      }
    }

    if (profile_map.find("plugin") == profile_map.end()) {
      ss << "erasure-code-profile " << profile_map
	 << " must contain a plugin entry" << std::endl;
      err = -EINVAL;
      goto reply;
    }
    string plugin = profile_map["plugin"];

    if (pending_inc.has_erasure_code_profile(name)) {
      dout(20) << "erasure code profile " << name << " try again" << dendl;
      goto wait;
    } else {
      err = normalize_profile(name, profile_map, force, &ss);
      if (err)
	goto reply;

      if (osdmap.has_erasure_code_profile(name)) {
	ErasureCodeProfile existing_profile_map =
	  osdmap.get_erasure_code_profile(name);
	err = normalize_profile(name, existing_profile_map, force, &ss);
	if (err)
	  goto reply;

	if (existing_profile_map == profile_map) {
	  err = 0;
	  goto reply;
	}
	if (!force) {
	  err = -EPERM;
	  ss << "will not override erasure code profile " << name
	     << " because the existing profile "
	     << existing_profile_map
	     << " is different from the proposed profile "
	     << profile_map;
	  goto reply;
	}
      }

      dout(20) << "erasure code profile set " << name << "="
	       << profile_map << dendl;
      pending_inc.set_erasure_code_profile(name, profile_map);
    }

    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
                                                      get_last_committed() + 1));
    return true;

  } else if (prefix == "osd crush rule create-erasure") {
    err = check_cluster_features(CEPH_FEATURE_CRUSH_V2, ss);
    if (err == -EAGAIN)
      goto wait;
    if (err)
      goto reply;
    string name, poolstr;
    cmd_getval(cct, cmdmap, "name", name);
    string profile;
    cmd_getval(cct, cmdmap, "profile", profile);
    if (profile == "")
      profile = "default";
    if (profile == "default") {
      if (!osdmap.has_erasure_code_profile(profile)) {
	if (pending_inc.has_erasure_code_profile(profile)) {
	  dout(20) << "erasure code profile " << profile << " already pending" << dendl;
	  goto wait;
	}

	map<string,string> profile_map;
	err = osdmap.get_erasure_code_profile_default(cct,
						      profile_map,
						      &ss);
	if (err)
	  goto reply;
	err = normalize_profile(name, profile_map, true, &ss);
	if (err)
	  goto reply;
	dout(20) << "erasure code profile set " << profile << "="
		 << profile_map << dendl;
	pending_inc.set_erasure_code_profile(profile, profile_map);
	goto wait;
      }
    }

    int rule;
    err = crush_rule_create_erasure(name, profile, &rule, &ss);
    if (err < 0) {
      switch(err) {
      case -EEXIST: // return immediately
	ss << "rule " << name << " already exists";
	err = 0;
	goto reply;
	break;
      case -EALREADY: // wait for pending to be proposed
	ss << "rule " << name << " already exists";
	err = 0;
	break;
      default: // non recoverable error
 	goto reply;
	break;
      }
    } else {
      ss << "created rule " << name << " at " << rule;
    }

    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
                                                      get_last_committed() + 1));
    return true;

  } else if (prefix == "osd crush rule rm") {
    string name;
    cmd_getval(cct, cmdmap, "name", name);

    if (!osdmap.crush->rule_exists(name)) {
      ss << "rule " << name << " does not exist";
      err = 0;
      goto reply;
    }

    CrushWrapper newcrush;
    _get_pending_crush(newcrush);

    if (!newcrush.rule_exists(name)) {
      ss << "rule " << name << " does not exist";
      err = 0;
    } else {
      int ruleno = newcrush.get_rule_id(name);
      ceph_assert(ruleno >= 0);

      // make sure it is not in use.
      // FIXME: this is ok in some situations, but let's not bother with that
      // complexity now.
      int ruleset = newcrush.get_rule_mask_ruleset(ruleno);
      if (osdmap.crush_rule_in_use(ruleset)) {
	ss << "crush ruleset " << name << " " << ruleset << " is in use";
	err = -EBUSY;
	goto reply;
      }

      err = newcrush.remove_rule(ruleno);
      if (err < 0) {
	goto reply;
      }

      pending_inc.crush.clear();
      newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
    }
    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
					      get_last_committed() + 1));
    return true;

  } else if (prefix == "osd crush rule rename") {
    string srcname;
    string dstname;
    cmd_getval(cct, cmdmap, "srcname", srcname);
    cmd_getval(cct, cmdmap, "dstname", dstname);
    if (srcname.empty() || dstname.empty()) {
      ss << "must specify both source rule name and destination rule name";
      err = -EINVAL;
      goto reply;
    }
    if (srcname == dstname) {
      ss << "destination rule name is equal to source rule name";
      err = 0;
      goto reply;
    }

    CrushWrapper newcrush;
    _get_pending_crush(newcrush);
    if (!newcrush.rule_exists(srcname) && newcrush.rule_exists(dstname)) {
      // srcname does not exist and dstname already exists
      // suppose this is a replay and return success
      // (so this command is idempotent)
      ss << "already renamed to '" << dstname << "'";
      err = 0;
      goto reply;
    }

    err = newcrush.rename_rule(srcname, dstname, &ss);
    if (err < 0) {
      // ss has reason for failure
      goto reply;
    }
    pending_inc.crush.clear();
    newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
                               get_last_committed() + 1));
    return true;

  } else if (prefix == "osd setmaxosd") {
    int64_t newmax;
    if (!cmd_getval(cct, cmdmap, "newmax", newmax)) {
      ss << "unable to parse 'newmax' value '"
         << cmd_vartype_stringify(cmdmap.at("newmax")) << "'";
      err = -EINVAL;
      goto reply;
    }

    if (newmax > g_conf()->mon_max_osd) {
      err = -ERANGE;
      ss << "cannot set max_osd to " << newmax << " which is > conf.mon_max_osd ("
	 << g_conf()->mon_max_osd << ")";
      goto reply;
    }

    // Don't allow shrinking OSD number as this will cause data loss
    // and may cause kernel crashes.
    // Note: setmaxosd sets the maximum OSD number and not the number of OSDs
    if (newmax < osdmap.get_max_osd()) {
      // Check if the OSDs exist between current max and new value.
      // If there are any OSDs exist, then don't allow shrinking number
      // of OSDs.
      for (int i = newmax; i < osdmap.get_max_osd(); i++) {
        if (osdmap.exists(i)) {
          err = -EBUSY;
          ss << "cannot shrink max_osd to " << newmax
             << " because osd." << i << " (and possibly others) still in use";
          goto reply;
        }
      }
    }

    pending_inc.new_max_osd = newmax;
    ss << "set new max_osd = " << pending_inc.new_max_osd;
    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
					      get_last_committed() + 1));
    return true;

  } else if (prefix == "osd set-full-ratio" ||
	     prefix == "osd set-backfillfull-ratio" ||
             prefix == "osd set-nearfull-ratio") {
    double n;
    if (!cmd_getval(cct, cmdmap, "ratio", n)) {
      ss << "unable to parse 'ratio' value '"
         << cmd_vartype_stringify(cmdmap.at("ratio")) << "'";
      err = -EINVAL;
      goto reply;
    }
    if (prefix == "osd set-full-ratio")
      pending_inc.new_full_ratio = n;
    else if (prefix == "osd set-backfillfull-ratio")
      pending_inc.new_backfillfull_ratio = n;
    else if (prefix == "osd set-nearfull-ratio")
      pending_inc.new_nearfull_ratio = n;
    ss << prefix << " " << n;
    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
					      get_last_committed() + 1));
    return true;
  } else if (prefix == "osd set-require-min-compat-client") {
    string v;
    cmd_getval(cct, cmdmap, "version", v);
    int vno = ceph_release_from_name(v.c_str());
    if (vno <= 0) {
      ss << "version " << v << " is not recognized";
      err = -EINVAL;
      goto reply;
    }
    OSDMap newmap;
    newmap.deepish_copy_from(osdmap);
    newmap.apply_incremental(pending_inc);
    newmap.require_min_compat_client = vno;
    auto mvno = newmap.get_min_compat_client();
    if (vno < mvno) {
      ss << "osdmap current utilizes features that require "
	 << ceph_release_name(mvno)
	 << "; cannot set require_min_compat_client below that to "
	 << ceph_release_name(vno);
      err = -EPERM;
      goto reply;
    }
    bool sure = false;
    cmd_getval(cct, cmdmap, "yes_i_really_mean_it", sure);
    if (!sure) {
      FeatureMap m;
      mon->get_combined_feature_map(&m);
      uint64_t features = ceph_release_features(vno);
      bool first = true;
      bool ok = true;
      for (int type : {
	    CEPH_ENTITY_TYPE_CLIENT,
	    CEPH_ENTITY_TYPE_MDS,
	    CEPH_ENTITY_TYPE_MGR }) {
	auto p = m.m.find(type);
	if (p == m.m.end()) {
	  continue;
	}
	for (auto& q : p->second) {
	  uint64_t missing = ~q.first & features;
	  if (missing) {
	    if (first) {
	      ss << "cannot set require_min_compat_client to " << v << ": ";
	    } else {
	      ss << "; ";
	    }
	    first = false;
	    ss << q.second << " connected " << ceph_entity_type_name(type)
	       << "(s) look like " << ceph_release_name(
		 ceph_release_from_features(q.first))
	       << " (missing 0x" << std::hex << missing << std::dec << ")";
	    ok = false;
	  }
	}
      }
      if (!ok) {
	ss << "; add --yes-i-really-mean-it to do it anyway";
	err = -EPERM;
	goto reply;
      }
    }
    ss << "set require_min_compat_client to " << ceph_release_name(vno);
    pending_inc.new_require_min_compat_client = vno;
    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
							  get_last_committed() + 1));
    return true;
  } else if (prefix == "osd pause") {
    return prepare_set_flag(op, CEPH_OSDMAP_PAUSERD | CEPH_OSDMAP_PAUSEWR);

  } else if (prefix == "osd unpause") {
    return prepare_unset_flag(op, CEPH_OSDMAP_PAUSERD | CEPH_OSDMAP_PAUSEWR);

  } else if (prefix == "osd set") {
    bool sure = false;
    cmd_getval(g_ceph_context, cmdmap, "yes_i_really_mean_it", sure);

    string key;
    cmd_getval(cct, cmdmap, "key", key);
    if (key == "full")
      return prepare_set_flag(op, CEPH_OSDMAP_FULL);
    else if (key == "pause")
      return prepare_set_flag(op, CEPH_OSDMAP_PAUSERD | CEPH_OSDMAP_PAUSEWR);
    else if (key == "noup")
      return prepare_set_flag(op, CEPH_OSDMAP_NOUP);
    else if (key == "nodown")
      return prepare_set_flag(op, CEPH_OSDMAP_NODOWN);
    else if (key == "noout")
      return prepare_set_flag(op, CEPH_OSDMAP_NOOUT);
    else if (key == "noin")
      return prepare_set_flag(op, CEPH_OSDMAP_NOIN);
    else if (key == "nobackfill")
      return prepare_set_flag(op, CEPH_OSDMAP_NOBACKFILL);
    else if (key == "norebalance")
      return prepare_set_flag(op, CEPH_OSDMAP_NOREBALANCE);
    else if (key == "norecover")
      return prepare_set_flag(op, CEPH_OSDMAP_NORECOVER);
    else if (key == "noscrub")
      return prepare_set_flag(op, CEPH_OSDMAP_NOSCRUB);
    else if (key == "nodeep-scrub")
      return prepare_set_flag(op, CEPH_OSDMAP_NODEEP_SCRUB);
    else if (key == "notieragent")
      return prepare_set_flag(op, CEPH_OSDMAP_NOTIERAGENT);
    else if (key == "nosnaptrim")
      return prepare_set_flag(op, CEPH_OSDMAP_NOSNAPTRIM);
    else if (key == "pglog_hardlimit") {
      if (!osdmap.get_num_up_osds() && !sure) {
        ss << "Not advisable to continue since no OSDs are up. Pass "
           << "--yes-i-really-mean-it if you really wish to continue.";
        err = -EPERM;
        goto reply;
      }
      // The release check here is required because for OSD_PGLOG_HARDLIMIT,
      // we are reusing a jewel feature bit that was retired in luminous.
      if (osdmap.require_osd_release >= CEPH_RELEASE_LUMINOUS &&
         (HAVE_FEATURE(osdmap.get_up_osd_features(), OSD_PGLOG_HARDLIMIT)
          || sure)) {
	return prepare_set_flag(op, CEPH_OSDMAP_PGLOG_HARDLIMIT);
      } else {
	ss << "not all up OSDs have OSD_PGLOG_HARDLIMIT feature";
	err = -EPERM;
	goto reply;
      }
    } else {
      ss << "unrecognized flag '" << key << "'";
      err = -EINVAL;
    }

  } else if (prefix == "osd unset") {
    string key;
    cmd_getval(cct, cmdmap, "key", key);
    if (key == "full")
      return prepare_unset_flag(op, CEPH_OSDMAP_FULL);
    else if (key == "pause")
      return prepare_unset_flag(op, CEPH_OSDMAP_PAUSERD | CEPH_OSDMAP_PAUSEWR);
    else if (key == "noup")
      return prepare_unset_flag(op, CEPH_OSDMAP_NOUP);
    else if (key == "nodown")
      return prepare_unset_flag(op, CEPH_OSDMAP_NODOWN);
    else if (key == "noout")
      return prepare_unset_flag(op, CEPH_OSDMAP_NOOUT);
    else if (key == "noin")
      return prepare_unset_flag(op, CEPH_OSDMAP_NOIN);
    else if (key == "nobackfill")
      return prepare_unset_flag(op, CEPH_OSDMAP_NOBACKFILL);
    else if (key == "norebalance")
      return prepare_unset_flag(op, CEPH_OSDMAP_NOREBALANCE);
    else if (key == "norecover")
      return prepare_unset_flag(op, CEPH_OSDMAP_NORECOVER);
    else if (key == "noscrub")
      return prepare_unset_flag(op, CEPH_OSDMAP_NOSCRUB);
    else if (key == "nodeep-scrub")
      return prepare_unset_flag(op, CEPH_OSDMAP_NODEEP_SCRUB);
    else if (key == "notieragent")
      return prepare_unset_flag(op, CEPH_OSDMAP_NOTIERAGENT);
    else if (key == "nosnaptrim")
      return prepare_unset_flag(op, CEPH_OSDMAP_NOSNAPTRIM);
    else {
      ss << "unrecognized flag '" << key << "'";
      err = -EINVAL;
    }

  } else if (prefix == "osd require-osd-release") {
    string release;
    cmd_getval(cct, cmdmap, "release", release);
    bool sure = false;
    cmd_getval(cct, cmdmap, "yes_i_really_mean_it", sure);
    int rel = ceph_release_from_name(release.c_str());
    if (rel <= 0) {
      ss << "unrecognized release " << release;
      err = -EINVAL;
      goto reply;
    }
    if (rel == osdmap.require_osd_release) {
      // idempotent
      err = 0;
      goto reply;
    }
    ceph_assert(osdmap.require_osd_release >= CEPH_RELEASE_LUMINOUS);
    if (!osdmap.get_num_up_osds() && !sure) {
      ss << "Not advisable to continue since no OSDs are up. Pass "
	 << "--yes-i-really-mean-it if you really wish to continue.";
      err = -EPERM;
      goto reply;
    }
    if (rel == CEPH_RELEASE_MIMIC) {
      if (!mon->monmap->get_required_features().contains_all(
	    ceph::features::mon::FEATURE_MIMIC)) {
	ss << "not all mons are mimic";
	err = -EPERM;
	goto reply;
      }
      if ((!HAVE_FEATURE(osdmap.get_up_osd_features(), SERVER_MIMIC))
           && !sure) {
	ss << "not all up OSDs have CEPH_FEATURE_SERVER_MIMIC feature";
	err = -EPERM;
	goto reply;
      }
    } else if (rel == CEPH_RELEASE_NAUTILUS) {
      if (!mon->monmap->get_required_features().contains_all(
	    ceph::features::mon::FEATURE_NAUTILUS)) {
	ss << "not all mons are nautilus";
	err = -EPERM;
	goto reply;
      }
      if ((!HAVE_FEATURE(osdmap.get_up_osd_features(), SERVER_NAUTILUS))
           && !sure) {
	ss << "not all up OSDs have CEPH_FEATURE_SERVER_NAUTILUS feature";
	err = -EPERM;
	goto reply;
      }
    } else {
      ss << "not supported for this release yet";
      err = -EPERM;
      goto reply;
    }
    if (rel < osdmap.require_osd_release) {
      ss << "require_osd_release cannot be lowered once it has been set";
      err = -EPERM;
      goto reply;
    }
    pending_inc.new_require_osd_release = rel;
    goto update;
  } else if (prefix == "osd down" ||
	     prefix == "osd out" ||
	     prefix == "osd in" ||
	     prefix == "osd rm") {

    bool any = false;
    bool stop = false;
    bool verbose = true;

    vector<string> idvec;
    cmd_getval(cct, cmdmap, "ids", idvec);
    for (unsigned j = 0; j < idvec.size() && !stop; j++) {
      set<int> osds;

      // wildcard?
      if (j == 0 &&
          (idvec[0] == "any" || idvec[0] == "all" || idvec[0] == "*")) {
        if (prefix == "osd in") {
          // touch out osds only
          osdmap.get_out_existing_osds(osds);
        } else {
          osdmap.get_all_osds(osds);
        }
        stop = true;
        verbose = false; // so the output is less noisy.
      } else {
        long osd = parse_osd_id(idvec[j].c_str(), &ss);
        if (osd < 0) {
          ss << "invalid osd id" << osd;
          err = -EINVAL;
          continue;
        } else if (!osdmap.exists(osd)) {
          ss << "osd." << osd << " does not exist. ";
          continue;
        }

        osds.insert(osd);
      }

      for (auto &osd : osds) {
        if (prefix == "osd down") {
	  if (osdmap.is_down(osd)) {
            if (verbose)
	      ss << "osd." << osd << " is already down. ";
	  } else {
            pending_inc.pending_osd_state_set(osd, CEPH_OSD_UP);
	    ss << "marked down osd." << osd << ". ";
	    any = true;
	  }
        } else if (prefix == "osd out") {
	  if (osdmap.is_out(osd)) {
            if (verbose)
	      ss << "osd." << osd << " is already out. ";
	  } else {
	    pending_inc.new_weight[osd] = CEPH_OSD_OUT;
	    if (osdmap.osd_weight[osd]) {
	      if (pending_inc.new_xinfo.count(osd) == 0) {
	        pending_inc.new_xinfo[osd] = osdmap.osd_xinfo[osd];
	      }
	      pending_inc.new_xinfo[osd].old_weight = osdmap.osd_weight[osd];
	    }
	    ss << "marked out osd." << osd << ". ";
            std::ostringstream msg;
            msg << "Client " << op->get_session()->entity_name
                << " marked osd." << osd << " out";
            if (osdmap.is_up(osd)) {
              msg << ", while it was still marked up";
            } else {
              auto period = ceph_clock_now() - down_pending_out[osd];
              msg << ", after it was down for " << int(period.sec())
                  << " seconds";
            }

            mon->clog->info() << msg.str();
	    any = true;
	  }
        } else if (prefix == "osd in") {
	  if (osdmap.is_in(osd)) {
            if (verbose)
	      ss << "osd." << osd << " is already in. ";
	  } else {
	    if (osdmap.osd_xinfo[osd].old_weight > 0) {
	      pending_inc.new_weight[osd] = osdmap.osd_xinfo[osd].old_weight;
	      if (pending_inc.new_xinfo.count(osd) == 0) {
	        pending_inc.new_xinfo[osd] = osdmap.osd_xinfo[osd];
	      }
	      pending_inc.new_xinfo[osd].old_weight = 0;
	    } else {
	      pending_inc.new_weight[osd] = CEPH_OSD_IN;
	    }
	    ss << "marked in osd." << osd << ". ";
	    any = true;
	  }
        } else if (prefix == "osd rm") {
          err = prepare_command_osd_remove(osd);

          if (err == -EBUSY) {
	    if (any)
	      ss << ", ";
            ss << "osd." << osd << " is still up; must be down before removal. ";
	  } else {
            ceph_assert(err == 0);
	    if (any) {
	      ss << ", osd." << osd;
            } else {
	      ss << "removed osd." << osd;
            }
	    any = true;
	  }
        }
      }
    }
    if (any) {
      getline(ss, rs);
      wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, err, rs,
						get_last_committed() + 1));
      return true;
    }
  } else if (prefix == "osd set-group" ||
             prefix == "osd unset-group" ||
             prefix == "osd add-noup" ||
             prefix == "osd add-nodown" ||
             prefix == "osd add-noin" ||
             prefix == "osd add-noout" ||
             prefix == "osd rm-noup" ||
             prefix == "osd rm-nodown" ||
             prefix == "osd rm-noin" ||
             prefix == "osd rm-noout") {
    bool do_set = prefix == "osd set-group" ||
                  prefix.find("add") != string::npos;
    string flag_str;
    unsigned flags = 0;
    vector<string> who;
    if (prefix == "osd set-group" || prefix == "osd unset-group") {
      cmd_getval(cct, cmdmap, "flags", flag_str);
      cmd_getval(cct, cmdmap, "who", who);
      vector<string> raw_flags;
      boost::split(raw_flags, flag_str, boost::is_any_of(","));
      for (auto& f : raw_flags) {
        if (f == "noup")
          flags |= CEPH_OSD_NOUP;
        else if (f == "nodown")
          flags |= CEPH_OSD_NODOWN;
        else if (f == "noin")
          flags |= CEPH_OSD_NOIN;
        else if (f == "noout")
          flags |= CEPH_OSD_NOOUT;
        else {
          ss << "unrecognized flag '" << f << "', must be one of "
             << "{noup,nodown,noin,noout}";
          err = -EINVAL;
          goto reply;
        }
      }
    } else {
      cmd_getval(cct, cmdmap, "ids", who);
      if (prefix.find("noup") != string::npos)
        flags = CEPH_OSD_NOUP;
      else if (prefix.find("nodown") != string::npos)
        flags = CEPH_OSD_NODOWN;
      else if (prefix.find("noin") != string::npos)
        flags = CEPH_OSD_NOIN;
      else if (prefix.find("noout") != string::npos)
        flags = CEPH_OSD_NOOUT;
      else
        ceph_assert(0 == "Unreachable!");
    }
    if (flags == 0) {
      ss << "must specify flag(s) {noup,nodwon,noin,noout} to set/unset";
      err = -EINVAL;
      goto reply;
    }
    if (who.empty()) {
      ss << "must specify at least one or more targets to set/unset";
      err = -EINVAL;
      goto reply;
    }
    set<int> osds;
    set<int> crush_nodes;
    set<int> device_classes;
    for (auto& w : who) {
      if (w == "any" || w == "all" || w == "*") {
        osdmap.get_all_osds(osds);
        break;
      }
      std::stringstream ts;
      if (auto osd = parse_osd_id(w.c_str(), &ts); osd >= 0) {
        osds.insert(osd);
      } else if (osdmap.crush->name_exists(w)) {
        crush_nodes.insert(osdmap.crush->get_item_id(w));
      } else if (osdmap.crush->class_exists(w)) {
        device_classes.insert(osdmap.crush->get_class_id(w));
      } else {
        ss << "unable to parse osd id or crush node or device class: "
           << "\"" << w << "\". ";
      }
    }
    if (osds.empty() && crush_nodes.empty() && device_classes.empty()) {
      // ss has reason for failure
      err = -EINVAL;
      goto reply;
    }
    bool any = false;
    for (auto osd : osds) {
      if (!osdmap.exists(osd)) {
        ss << "osd." << osd << " does not exist. ";
        continue;
      }
      if (do_set) {
        if (flags & CEPH_OSD_NOUP) {
          any |= osdmap.is_noup_by_osd(osd) ?
            pending_inc.pending_osd_state_clear(osd, CEPH_OSD_NOUP) :
            pending_inc.pending_osd_state_set(osd, CEPH_OSD_NOUP);
        }
        if (flags & CEPH_OSD_NODOWN) {
          any |= osdmap.is_nodown_by_osd(osd) ?
            pending_inc.pending_osd_state_clear(osd, CEPH_OSD_NODOWN) :
            pending_inc.pending_osd_state_set(osd, CEPH_OSD_NODOWN);
        }
        if (flags & CEPH_OSD_NOIN) {
          any |= osdmap.is_noin_by_osd(osd) ?
            pending_inc.pending_osd_state_clear(osd, CEPH_OSD_NOIN) :
            pending_inc.pending_osd_state_set(osd, CEPH_OSD_NOIN);
        }
        if (flags & CEPH_OSD_NOOUT) {
          any |= osdmap.is_noout_by_osd(osd) ?
            pending_inc.pending_osd_state_clear(osd, CEPH_OSD_NOOUT) :
            pending_inc.pending_osd_state_set(osd, CEPH_OSD_NOOUT);
        }
      } else {
        if (flags & CEPH_OSD_NOUP) {
          any |= osdmap.is_noup_by_osd(osd) ?
            pending_inc.pending_osd_state_set(osd, CEPH_OSD_NOUP) :
            pending_inc.pending_osd_state_clear(osd, CEPH_OSD_NOUP);
        }
        if (flags & CEPH_OSD_NODOWN) {
          any |= osdmap.is_nodown_by_osd(osd) ?
            pending_inc.pending_osd_state_set(osd, CEPH_OSD_NODOWN) :
            pending_inc.pending_osd_state_clear(osd, CEPH_OSD_NODOWN);
        }
        if (flags & CEPH_OSD_NOIN) {
          any |= osdmap.is_noin_by_osd(osd) ?
            pending_inc.pending_osd_state_set(osd, CEPH_OSD_NOIN) :
            pending_inc.pending_osd_state_clear(osd, CEPH_OSD_NOIN);
        }
        if (flags & CEPH_OSD_NOOUT) {
          any |= osdmap.is_noout_by_osd(osd) ?
            pending_inc.pending_osd_state_set(osd, CEPH_OSD_NOOUT) :
            pending_inc.pending_osd_state_clear(osd, CEPH_OSD_NOOUT);
        }
      }
    }
    for (auto& id : crush_nodes) {
      auto old_flags = osdmap.get_crush_node_flags(id);
      auto& pending_flags = pending_inc.new_crush_node_flags[id];
      pending_flags |= old_flags; // adopt existing flags first!
      if (do_set) {
        pending_flags |= flags;
      } else {
        pending_flags &= ~flags;
      }
      any = true;
    }
    for (auto& id : device_classes) {
      auto old_flags = osdmap.get_device_class_flags(id);
      auto& pending_flags = pending_inc.new_device_class_flags[id];
      pending_flags |= old_flags;
      if (do_set) {
        pending_flags |= flags;
      } else {
        pending_flags &= ~flags;
      }
      any = true;
    }
    if (any) {
      getline(ss, rs);
      wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, err, rs,
                                 get_last_committed() + 1));
      return true;
    }
  } else if (prefix == "osd pg-temp") {
    string pgidstr;
    if (!cmd_getval(cct, cmdmap, "pgid", pgidstr)) {
      ss << "unable to parse 'pgid' value '"
         << cmd_vartype_stringify(cmdmap.at("pgid")) << "'";
      err = -EINVAL;
      goto reply;
    }
    pg_t pgid;
    if (!pgid.parse(pgidstr.c_str())) {
      ss << "invalid pgid '" << pgidstr << "'";
      err = -EINVAL;
      goto reply;
    }
    if (!osdmap.pg_exists(pgid)) {
      ss << "pg " << pgid << " does not exist";
      err = -ENOENT;
      goto reply;
    }
    if (pending_inc.new_pg_temp.count(pgid)) {
      dout(10) << __func__ << " waiting for pending update on " << pgid << dendl;
      wait_for_finished_proposal(op, new C_RetryMessage(this, op));
      return true;
    }

    vector<int64_t> id_vec;
    vector<int32_t> new_pg_temp;
    cmd_getval(cct, cmdmap, "id", id_vec);
    if (id_vec.empty())  {
      pending_inc.new_pg_temp[pgid] = mempool::osdmap::vector<int>();
      ss << "done cleaning up pg_temp of " << pgid;
      goto update;
    }
    for (auto osd : id_vec) {
      if (!osdmap.exists(osd)) {
        ss << "osd." << osd << " does not exist";
        err = -ENOENT;
        goto reply;
      }
      new_pg_temp.push_back(osd);
    }

    int pool_min_size = osdmap.get_pg_pool_min_size(pgid);
    if ((int)new_pg_temp.size() < pool_min_size) {
      ss << "num of osds (" << new_pg_temp.size() <<") < pool min size ("
         << pool_min_size << ")";
      err = -EINVAL;
      goto reply;
    }

    int pool_size = osdmap.get_pg_pool_size(pgid);
    if ((int)new_pg_temp.size() > pool_size) {
      ss << "num of osds (" << new_pg_temp.size() <<") > pool size ("
         << pool_size << ")";
      err = -EINVAL;
      goto reply;
    }

    pending_inc.new_pg_temp[pgid] = mempool::osdmap::vector<int>(
      new_pg_temp.begin(), new_pg_temp.end());
    ss << "set " << pgid << " pg_temp mapping to " << new_pg_temp;
    goto update;
  } else if (prefix == "osd primary-temp") {
    string pgidstr;
    if (!cmd_getval(cct, cmdmap, "pgid", pgidstr)) {
      ss << "unable to parse 'pgid' value '"
         << cmd_vartype_stringify(cmdmap.at("pgid")) << "'";
      err = -EINVAL;
      goto reply;
    }
    pg_t pgid;
    if (!pgid.parse(pgidstr.c_str())) {
      ss << "invalid pgid '" << pgidstr << "'";
      err = -EINVAL;
      goto reply;
    }
    if (!osdmap.pg_exists(pgid)) {
      ss << "pg " << pgid << " does not exist";
      err = -ENOENT;
      goto reply;
    }

    int64_t osd;
    if (!cmd_getval(cct, cmdmap, "id", osd)) {
      ss << "unable to parse 'id' value '"
         << cmd_vartype_stringify(cmdmap.at("id")) << "'";
      err = -EINVAL;
      goto reply;
    }
    if (osd != -1 && !osdmap.exists(osd)) {
      ss << "osd." << osd << " does not exist";
      err = -ENOENT;
      goto reply;
    }

    if (osdmap.require_min_compat_client > 0 &&
	osdmap.require_min_compat_client < CEPH_RELEASE_FIREFLY) {
      ss << "require_min_compat_client "
	 << ceph_release_name(osdmap.require_min_compat_client)
	 << " < firefly, which is required for primary-temp";
      err = -EPERM;
      goto reply;
    }

    pending_inc.new_primary_temp[pgid] = osd;
    ss << "set " << pgid << " primary_temp mapping to " << osd;
    goto update;
  } else if (prefix == "pg repeer") {
    pg_t pgid;
    string pgidstr;
    cmd_getval(cct, cmdmap, "pgid", pgidstr);
    if (!pgid.parse(pgidstr.c_str())) {
      ss << "invalid pgid '" << pgidstr << "'";
      err = -EINVAL;
      goto reply;
    }
    if (!osdmap.pg_exists(pgid)) {
      ss << "pg '" << pgidstr << "' does not exist";
      err = -ENOENT;
      goto reply;
    }
    vector<int> acting;
    int primary;
    osdmap.pg_to_acting_osds(pgid, &acting, &primary);
    if (primary < 0) {
      err = -EAGAIN;
      ss << "pg currently has no primary";
      goto reply;
    }
    if (acting.size() > 1) {
      // map to just primary; it will map back to what it wants
      pending_inc.new_pg_temp[pgid] = { primary };
    } else {
      // hmm, pick another arbitrary osd to induce a change.  Note
      // that this won't work if there is only one suitable OSD in the cluster.
      int i;
      bool done = false;
      for (i = 0; i < osdmap.get_max_osd(); ++i) {
	if (i == primary || !osdmap.is_up(i) || !osdmap.exists(i)) {
	  continue;
	}
	pending_inc.new_pg_temp[pgid] = { primary, i };
	done = true;
	break;
      }
      if (!done) {
	err = -EAGAIN;
	ss << "not enough up OSDs in the cluster to force repeer";
	goto reply;
      }
    }
    goto update;
  } else if (prefix == "osd pg-upmap" ||
             prefix == "osd rm-pg-upmap" ||
             prefix == "osd pg-upmap-items" ||
             prefix == "osd rm-pg-upmap-items") {
    if (osdmap.require_min_compat_client < CEPH_RELEASE_LUMINOUS) {
      ss << "min_compat_client "
	 << ceph_release_name(osdmap.require_min_compat_client)
	 << " < luminous, which is required for pg-upmap. "
         << "Try 'ceph osd set-require-min-compat-client luminous' "
         << "before using the new interface";
      err = -EPERM;
      goto reply;
    }
    err = check_cluster_features(CEPH_FEATUREMASK_OSDMAP_PG_UPMAP, ss);
    if (err == -EAGAIN)
      goto wait;
    if (err < 0)
      goto reply;
    string pgidstr;
    if (!cmd_getval(cct, cmdmap, "pgid", pgidstr)) {
      ss << "unable to parse 'pgid' value '"
         << cmd_vartype_stringify(cmdmap.at("pgid")) << "'";
      err = -EINVAL;
      goto reply;
    }
    pg_t pgid;
    if (!pgid.parse(pgidstr.c_str())) {
      ss << "invalid pgid '" << pgidstr << "'";
      err = -EINVAL;
      goto reply;
    }
    if (!osdmap.pg_exists(pgid)) {
      ss << "pg " << pgid << " does not exist";
      err = -ENOENT;
      goto reply;
    }
    if (pending_inc.old_pools.count(pgid.pool())) {
      ss << "pool of " << pgid << " is pending removal";
      err = -ENOENT;
      getline(ss, rs);
      wait_for_finished_proposal(op,
        new Monitor::C_Command(mon, op, err, rs, get_last_committed() + 1));
      return true;
    }

    enum {
      OP_PG_UPMAP,
      OP_RM_PG_UPMAP,
      OP_PG_UPMAP_ITEMS,
      OP_RM_PG_UPMAP_ITEMS,
    } option;

    if (prefix == "osd pg-upmap") {
      option = OP_PG_UPMAP;
    } else if (prefix == "osd rm-pg-upmap") {
      option = OP_RM_PG_UPMAP;
    } else if (prefix == "osd pg-upmap-items") {
      option = OP_PG_UPMAP_ITEMS;
    } else {
      option = OP_RM_PG_UPMAP_ITEMS;
    }

    // check pending upmap changes
    switch (option) {
    case OP_PG_UPMAP: // fall through
    case OP_RM_PG_UPMAP:
      if (pending_inc.new_pg_upmap.count(pgid) ||
          pending_inc.old_pg_upmap.count(pgid)) {
        dout(10) << __func__ << " waiting for pending update on "
                 << pgid << dendl;
        wait_for_finished_proposal(op, new C_RetryMessage(this, op));
        return true;
      }
      break;

    case OP_PG_UPMAP_ITEMS: // fall through
    case OP_RM_PG_UPMAP_ITEMS:
      if (pending_inc.new_pg_upmap_items.count(pgid) ||
          pending_inc.old_pg_upmap_items.count(pgid)) {
        dout(10) << __func__ << " waiting for pending update on "
                 << pgid << dendl;
        wait_for_finished_proposal(op, new C_RetryMessage(this, op));
        return true;
      }
      break;

    default:
      ceph_abort_msg("invalid option");
    }

    switch (option) {
    case OP_PG_UPMAP:
      {
        vector<int64_t> id_vec;
        if (!cmd_getval(cct, cmdmap, "id", id_vec)) {
          ss << "unable to parse 'id' value(s) '"
             << cmd_vartype_stringify(cmdmap.at("id")) << "'";
          err = -EINVAL;
          goto reply;
        }

        int pool_min_size = osdmap.get_pg_pool_min_size(pgid);
        if ((int)id_vec.size() < pool_min_size) {
          ss << "num of osds (" << id_vec.size() <<") < pool min size ("
             << pool_min_size << ")";
          err = -EINVAL;
          goto reply;
        }

        int pool_size = osdmap.get_pg_pool_size(pgid);
        if ((int)id_vec.size() > pool_size) {
          ss << "num of osds (" << id_vec.size() <<") > pool size ("
             << pool_size << ")";
          err = -EINVAL;
          goto reply;
        }

        vector<int32_t> new_pg_upmap;
        for (auto osd : id_vec) {
          if (osd != CRUSH_ITEM_NONE && !osdmap.exists(osd)) {
            ss << "osd." << osd << " does not exist";
            err = -ENOENT;
            goto reply;
          }
          auto it = std::find(new_pg_upmap.begin(), new_pg_upmap.end(), osd);
          if (it != new_pg_upmap.end()) {
            ss << "osd." << osd << " already exists, ";
            continue;
          }
          new_pg_upmap.push_back(osd);
        }

        if (new_pg_upmap.empty()) {
          ss << "no valid upmap items(pairs) is specified";
          err = -EINVAL;
          goto reply;
        }

        pending_inc.new_pg_upmap[pgid] = mempool::osdmap::vector<int32_t>(
          new_pg_upmap.begin(), new_pg_upmap.end());
        ss << "set " << pgid << " pg_upmap mapping to " << new_pg_upmap;
      }
      break;

    case OP_RM_PG_UPMAP:
      {
        pending_inc.old_pg_upmap.insert(pgid);
        ss << "clear " << pgid << " pg_upmap mapping";
      }
      break;

    case OP_PG_UPMAP_ITEMS:
      {
        vector<int64_t> id_vec;
        if (!cmd_getval(cct, cmdmap, "id", id_vec)) {
          ss << "unable to parse 'id' value(s) '"
             << cmd_vartype_stringify(cmdmap.at("id")) << "'";
          err = -EINVAL;
          goto reply;
        }

        if (id_vec.size() % 2) {
          ss << "you must specify pairs of osd ids to be remapped";
          err = -EINVAL;
          goto reply;
        }

        int pool_size = osdmap.get_pg_pool_size(pgid);
        if ((int)(id_vec.size() / 2) > pool_size) {
          ss << "num of osd pairs (" << id_vec.size() / 2 <<") > pool size ("
             << pool_size << ")";
          err = -EINVAL;
          goto reply;
        }

        vector<pair<int32_t,int32_t>> new_pg_upmap_items;
        ostringstream items;
        items << "[";
        for (auto p = id_vec.begin(); p != id_vec.end(); ++p) {
          int from = *p++;
          int to = *p;
          if (from == to) {
            ss << "from osd." << from << " == to osd." << to << ", ";
            continue;
          }
          if (!osdmap.exists(from)) {
            ss << "osd." << from << " does not exist";
            err = -ENOENT;
            goto reply;
          }
          if (to != CRUSH_ITEM_NONE && !osdmap.exists(to)) {
            ss << "osd." << to << " does not exist";
            err = -ENOENT;
            goto reply;
          }
          pair<int32_t,int32_t> entry = make_pair(from, to);
          auto it = std::find(new_pg_upmap_items.begin(),
            new_pg_upmap_items.end(), entry);
          if (it != new_pg_upmap_items.end()) {
            ss << "osd." << from << " -> osd." << to << " already exists, ";
            continue;
          }
          new_pg_upmap_items.push_back(entry);
          items << from << "->" << to << ",";
        }
        string out(items.str());
        out.resize(out.size() - 1); // drop last ','
        out += "]";

        if (new_pg_upmap_items.empty()) {
          ss << "no valid upmap items(pairs) is specified";
          err = -EINVAL;
          goto reply;
        }

        pending_inc.new_pg_upmap_items[pgid] =
          mempool::osdmap::vector<pair<int32_t,int32_t>>(
          new_pg_upmap_items.begin(), new_pg_upmap_items.end());
        ss << "set " << pgid << " pg_upmap_items mapping to " << out;
      }
      break;

    case OP_RM_PG_UPMAP_ITEMS:
      {
        pending_inc.old_pg_upmap_items.insert(pgid);
        ss << "clear " << pgid << " pg_upmap_items mapping";
      }
      break;

    default:
      ceph_abort_msg("invalid option");
    }

    goto update;
  } else if (prefix == "osd primary-affinity") {
    int64_t id;
    if (!cmd_getval(cct, cmdmap, "id", id)) {
      ss << "invalid osd id value '"
         << cmd_vartype_stringify(cmdmap.at("id")) << "'";
      err = -EINVAL;
      goto reply;
    }
    double w;
    if (!cmd_getval(cct, cmdmap, "weight", w)) {
      ss << "unable to parse 'weight' value '"
	 << cmd_vartype_stringify(cmdmap.at("weight")) << "'";
      err = -EINVAL;
      goto reply;
    }
    long ww = (int)((double)CEPH_OSD_MAX_PRIMARY_AFFINITY*w);
    if (ww < 0L) {
      ss << "weight must be >= 0";
      err = -EINVAL;
      goto reply;
    }
    if (osdmap.require_min_compat_client > 0 &&
	osdmap.require_min_compat_client < CEPH_RELEASE_FIREFLY) {
      ss << "require_min_compat_client "
	 << ceph_release_name(osdmap.require_min_compat_client)
	 << " < firefly, which is required for primary-affinity";
      err = -EPERM;
      goto reply;
    }
    if (osdmap.exists(id)) {
      pending_inc.new_primary_affinity[id] = ww;
      ss << "set osd." << id << " primary-affinity to " << w << " (" << ios::hex << ww << ios::dec << ")";
      getline(ss, rs);
      wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
                                                get_last_committed() + 1));
      return true;
    } else {
      ss << "osd." << id << " does not exist";
      err = -ENOENT;
      goto reply;
    }
  } else if (prefix == "osd reweight") {
    int64_t id;
    if (!cmd_getval(cct, cmdmap, "id", id)) {
      ss << "unable to parse osd id value '"
         << cmd_vartype_stringify(cmdmap.at("id")) << "'";
      err = -EINVAL;
      goto reply;
    }
    double w;
    if (!cmd_getval(cct, cmdmap, "weight", w)) {
      ss << "unable to parse weight value '"
         << cmd_vartype_stringify(cmdmap.at("weight")) << "'";
      err = -EINVAL;
      goto reply;
    }
    long ww = (int)((double)CEPH_OSD_IN*w);
    if (ww < 0L) {
      ss << "weight must be >= 0";
      err = -EINVAL;
      goto reply;
    }
    if (osdmap.exists(id)) {
      pending_inc.new_weight[id] = ww;
      ss << "reweighted osd." << id << " to " << w << " (" << std::hex << ww << std::dec << ")";
      getline(ss, rs);
      wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
						get_last_committed() + 1));
      return true;
    } else {
      ss << "osd." << id << " does not exist";
      err = -ENOENT;
      goto reply;
    }
  } else if (prefix == "osd reweightn") {
    map<int32_t, uint32_t> weights;
    err = parse_reweights(cct, cmdmap, osdmap, &weights);
    if (err) {
      ss << "unable to parse 'weights' value '"
         << cmd_vartype_stringify(cmdmap.at("weights")) << "'";
      goto reply;
    }
    pending_inc.new_weight.insert(weights.begin(), weights.end());
    wait_for_finished_proposal(
	op,
	new Monitor::C_Command(mon, op, 0, rs, rdata, get_last_committed() + 1));
    return true;
  } else if (prefix == "osd lost") {
    int64_t id;
    if (!cmd_getval(cct, cmdmap, "id", id)) {
      ss << "unable to parse osd id value '"
         << cmd_vartype_stringify(cmdmap.at("id")) << "'";
      err = -EINVAL;
      goto reply;
    }
    bool sure = false;
    cmd_getval(g_ceph_context, cmdmap, "yes_i_really_mean_it", sure);
    if (!sure) {
      ss << "are you SURE?  this might mean real, permanent data loss.  pass "
	    "--yes-i-really-mean-it if you really do.";
      err = -EPERM;
      goto reply;
    } else if (!osdmap.exists(id)) {
      ss << "osd." << id << " does not exist";
      err = -ENOENT;
      goto reply;
    } else if (!osdmap.is_down(id)) {
      ss << "osd." << id << " is not down";
      err = -EBUSY;
      goto reply;
    } else {
      epoch_t e = osdmap.get_info(id).down_at;
      pending_inc.new_lost[id] = e;
      ss << "marked osd lost in epoch " << e;
      getline(ss, rs);
      wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
						get_last_committed() + 1));
      return true;
    }

  } else if (prefix == "osd destroy-actual" ||
	     prefix == "osd purge-actual" ||
	     prefix == "osd purge-new") {
    /* Destroying an OSD means that we don't expect to further make use of
     * the OSDs data (which may even become unreadable after this operation),
     * and that we are okay with scrubbing all its cephx keys and config-key
     * data (which may include lockbox keys, thus rendering the osd's data
     * unreadable).
     *
     * The OSD will not be removed. Instead, we will mark it as destroyed,
     * such that a subsequent call to `create` will not reuse the osd id.
     * This will play into being able to recreate the OSD, at the same
     * crush location, with minimal data movement.
     */

    // make sure authmon is writeable.
    if (!mon->authmon()->is_writeable()) {
      dout(10) << __func__ << " waiting for auth mon to be writeable for "
               << "osd destroy" << dendl;
      mon->authmon()->wait_for_writeable(op, new C_RetryMessage(this, op));
      return false;
    }

    int64_t id;
    if (!cmd_getval(cct, cmdmap, "id", id)) {
      auto p = cmdmap.find("id");
      if (p == cmdmap.end()) {
	ss << "no osd id specified";
      } else {
	ss << "unable to parse osd id value '"
	   << cmd_vartype_stringify(cmdmap.at("id")) << "";
      }
      err = -EINVAL;
      goto reply;
    }

    bool is_destroy = (prefix == "osd destroy-actual");
    if (!is_destroy) {
      ceph_assert("osd purge-actual" == prefix ||
	     "osd purge-new" == prefix);
    }

    bool sure = false;
    cmd_getval(g_ceph_context, cmdmap, "yes_i_really_mean_it", sure);
    if (!sure) {
      ss << "Are you SURE?  Did you verify with 'ceph osd safe-to-destroy'?  "
	 << "This will mean real, permanent data loss, as well "
         << "as deletion of cephx and lockbox keys. "
	 << "Pass --yes-i-really-mean-it if you really do.";
      err = -EPERM;
      goto reply;
    } else if (!osdmap.exists(id)) {
      ss << "osd." << id << " does not exist";
      err = 0; // idempotent
      goto reply;
    } else if (osdmap.is_up(id)) {
      ss << "osd." << id << " is not `down`.";
      err = -EBUSY;
      goto reply;
    } else if (is_destroy && osdmap.is_destroyed(id)) {
      ss << "destroyed osd." << id;
      err = 0;
      goto reply;
    }

    if (prefix == "osd purge-new" &&
	(osdmap.get_state(id) & CEPH_OSD_NEW) == 0) {
      ss << "osd." << id << " is not new";
      err = -EPERM;
      goto reply;
    }

    bool goto_reply = false;

    paxos->plug();
    if (is_destroy) {
      err = prepare_command_osd_destroy(id, ss);
      // we checked above that it should exist.
      ceph_assert(err != -ENOENT);
    } else {
      err = prepare_command_osd_purge(id, ss);
      if (err == -ENOENT) {
        err = 0;
        ss << "osd." << id << " does not exist.";
        goto_reply = true;
      }
    }
    paxos->unplug();

    if (err < 0 || goto_reply) {
      goto reply;
    }

    if (is_destroy) {
      ss << "destroyed osd." << id;
    } else {
      ss << "purged osd." << id;
    }

    getline(ss, rs);
    wait_for_finished_proposal(op,
        new Monitor::C_Command(mon, op, 0, rs, get_last_committed() + 1));
    force_immediate_propose();
    return true;

  } else if (prefix == "osd new") {

    // make sure authmon is writeable.
    if (!mon->authmon()->is_writeable()) {
      dout(10) << __func__ << " waiting for auth mon to be writeable for "
               << "osd new" << dendl;
      mon->authmon()->wait_for_writeable(op, new C_RetryMessage(this, op));
      return false;
    }

    map<string,string> param_map;

    bufferlist bl = m->get_data();
    string param_json = bl.to_str();
    dout(20) << __func__ << " osd new json = " << param_json << dendl;

    err = get_json_str_map(param_json, ss, &param_map);
    if (err < 0)
      goto reply;

    dout(20) << __func__ << " osd new params " << param_map << dendl;

    paxos->plug();
    err = prepare_command_osd_new(op, cmdmap, param_map, ss, f.get());
    paxos->unplug();

    if (err < 0) {
      goto reply;
    }

    if (f) {
      f->flush(rdata);
    } else {
      rdata.append(ss);
    }

    if (err == EEXIST) {
      // idempotent operation
      err = 0;
      goto reply;
    }

    wait_for_finished_proposal(op,
        new Monitor::C_Command(mon, op, 0, rs, rdata,
                               get_last_committed() + 1));
    force_immediate_propose();
    return true;

  } else if (prefix == "osd create") {

    // optional id provided?
    int64_t id = -1, cmd_id = -1;
    if (cmd_getval(cct, cmdmap, "id", cmd_id)) {
      if (cmd_id < 0) {
	ss << "invalid osd id value '" << cmd_id << "'";
	err = -EINVAL;
	goto reply;
      }
      dout(10) << " osd create got id " << cmd_id << dendl;
    }

    uuid_d uuid;
    string uuidstr;
    if (cmd_getval(cct, cmdmap, "uuid", uuidstr)) {
      if (!uuid.parse(uuidstr.c_str())) {
        ss << "invalid uuid value '" << uuidstr << "'";
        err = -EINVAL;
        goto reply;
      }
      // we only care about the id if we also have the uuid, to
      // ensure the operation's idempotency.
      id = cmd_id;
    }

    int32_t new_id = -1;
    err = prepare_command_osd_create(id, uuid, &new_id, ss);
    if (err < 0) {
      if (err == -EAGAIN) {
        wait_for_finished_proposal(op, new C_RetryMessage(this, op));
        return true;
      }
      // a check has failed; reply to the user.
      goto reply;

    } else if (err == EEXIST) {
      // this is an idempotent operation; we can go ahead and reply.
      if (f) {
        f->open_object_section("created_osd");
        f->dump_int("osdid", new_id);
        f->close_section();
        f->flush(rdata);
      } else {
        ss << new_id;
        rdata.append(ss);
      }
      err = 0;
      goto reply;
    }

    string empty_device_class;
    do_osd_create(id, uuid, empty_device_class, &new_id);

    if (f) {
      f->open_object_section("created_osd");
      f->dump_int("osdid", new_id);
      f->close_section();
      f->flush(rdata);
    } else {
      ss << new_id;
      rdata.append(ss);
    }
    wait_for_finished_proposal(op,
        new Monitor::C_Command(mon, op, 0, rs, rdata,
                               get_last_committed() + 1));
    return true;

  } else if (prefix == "osd blacklist clear") {
    pending_inc.new_blacklist.clear();
    std::list<std::pair<entity_addr_t,utime_t > > blacklist;
    osdmap.get_blacklist(&blacklist);
    for (const auto &entry : blacklist) {
      pending_inc.old_blacklist.push_back(entry.first);
    }
    ss << " removed all blacklist entries";
    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
                                              get_last_committed() + 1));
    return true;
  } else if (prefix == "osd blacklist") {
    string addrstr;
    cmd_getval(cct, cmdmap, "addr", addrstr);
    entity_addr_t addr;
    if (!addr.parse(addrstr.c_str(), 0)) {
      ss << "unable to parse address " << addrstr;
      err = -EINVAL;
      goto reply;
    }
    else {
      if (osdmap.require_osd_release >= CEPH_RELEASE_NAUTILUS) {
	// always blacklist type ANY
	addr.set_type(entity_addr_t::TYPE_ANY);
      } else {
	addr.set_type(entity_addr_t::TYPE_LEGACY);
      }

      string blacklistop;
      cmd_getval(cct, cmdmap, "blacklistop", blacklistop);
      if (blacklistop == "add") {
	utime_t expires = ceph_clock_now();
	double d;
	// default one hour
	cmd_getval(cct, cmdmap, "expire", d,
          g_conf()->mon_osd_blacklist_default_expire);
	expires += d;

	pending_inc.new_blacklist[addr] = expires;

        {
          // cancel any pending un-blacklisting request too
          auto it = std::find(pending_inc.old_blacklist.begin(),
            pending_inc.old_blacklist.end(), addr);
          if (it != pending_inc.old_blacklist.end()) {
            pending_inc.old_blacklist.erase(it);
          }
        }

	ss << "blacklisting " << addr << " until " << expires << " (" << d << " sec)";
	getline(ss, rs);
	wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
						  get_last_committed() + 1));
	return true;
      } else if (blacklistop == "rm") {
	if (osdmap.is_blacklisted(addr) ||
	    pending_inc.new_blacklist.count(addr)) {
	  if (osdmap.is_blacklisted(addr))
	    pending_inc.old_blacklist.push_back(addr);
	  else
	    pending_inc.new_blacklist.erase(addr);
	  ss << "un-blacklisting " << addr;
	  getline(ss, rs);
	  wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
						    get_last_committed() + 1));
	  return true;
	}
	ss << addr << " isn't blacklisted";
	err = 0;
	goto reply;
      }
    }
  } else if (prefix == "osd pool mksnap") {
    string poolstr;
    cmd_getval(cct, cmdmap, "pool", poolstr);
    int64_t pool = osdmap.lookup_pg_pool_name(poolstr.c_str());
    if (pool < 0) {
      ss << "unrecognized pool '" << poolstr << "'";
      err = -ENOENT;
      goto reply;
    }
    string snapname;
    cmd_getval(cct, cmdmap, "snap", snapname);
    const pg_pool_t *p = osdmap.get_pg_pool(pool);
    if (p->is_unmanaged_snaps_mode()) {
      ss << "pool " << poolstr << " is in unmanaged snaps mode";
      err = -EINVAL;
      goto reply;
    } else if (p->snap_exists(snapname.c_str())) {
      ss << "pool " << poolstr << " snap " << snapname << " already exists";
      err = 0;
      goto reply;
    } else if (p->is_tier()) {
      ss << "pool " << poolstr << " is a cache tier";
      err = -EINVAL;
      goto reply;
    }
    pg_pool_t *pp = 0;
    if (pending_inc.new_pools.count(pool))
      pp = &pending_inc.new_pools[pool];
    if (!pp) {
      pp = &pending_inc.new_pools[pool];
      *pp = *p;
    }
    if (pp->snap_exists(snapname.c_str())) {
      ss << "pool " << poolstr << " snap " << snapname << " already exists";
    } else {
      pp->add_snap(snapname.c_str(), ceph_clock_now());
      pp->set_snap_epoch(pending_inc.epoch);
      ss << "created pool " << poolstr << " snap " << snapname;
    }
    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
					      get_last_committed() + 1));
    return true;
  } else if (prefix == "osd pool rmsnap") {
    string poolstr;
    cmd_getval(cct, cmdmap, "pool", poolstr);
    int64_t pool = osdmap.lookup_pg_pool_name(poolstr.c_str());
    if (pool < 0) {
      ss << "unrecognized pool '" << poolstr << "'";
      err = -ENOENT;
      goto reply;
    }
    string snapname;
    cmd_getval(cct, cmdmap, "snap", snapname);
    const pg_pool_t *p = osdmap.get_pg_pool(pool);
    if (p->is_unmanaged_snaps_mode()) {
      ss << "pool " << poolstr << " is in unmanaged snaps mode";
      err = -EINVAL;
      goto reply;
    } else if (!p->snap_exists(snapname.c_str())) {
      ss << "pool " << poolstr << " snap " << snapname << " does not exist";
      err = 0;
      goto reply;
    }
    pg_pool_t *pp = 0;
    if (pending_inc.new_pools.count(pool))
      pp = &pending_inc.new_pools[pool];
    if (!pp) {
      pp = &pending_inc.new_pools[pool];
      *pp = *p;
    }
    snapid_t sn = pp->snap_exists(snapname.c_str());
    if (sn) {
      pp->remove_snap(sn);
      pp->set_snap_epoch(pending_inc.epoch);
      ss << "removed pool " << poolstr << " snap " << snapname;
    } else {
      ss << "already removed pool " << poolstr << " snap " << snapname;
    }
    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
					      get_last_committed() + 1));
    return true;
  } else if (prefix == "osd pool create") {
    int64_t pg_num, pg_num_min;
    int64_t pgp_num;
    cmd_getval(cct, cmdmap, "pg_num", pg_num, int64_t(0));
    cmd_getval(cct, cmdmap, "pgp_num", pgp_num, pg_num);
    cmd_getval(cct, cmdmap, "pg_num_min", pg_num_min, int64_t(0));

    string pool_type_str;
    cmd_getval(cct, cmdmap, "pool_type", pool_type_str);
    if (pool_type_str.empty())
      pool_type_str = g_conf().get_val<string>("osd_pool_default_type");

    string poolstr;
    cmd_getval(cct, cmdmap, "pool", poolstr);
    int64_t pool_id = osdmap.lookup_pg_pool_name(poolstr);
    if (pool_id >= 0) {
      const pg_pool_t *p = osdmap.get_pg_pool(pool_id);
      if (pool_type_str != p->get_type_name()) {
	ss << "pool '" << poolstr << "' cannot change to type " << pool_type_str;
 	err = -EINVAL;
      } else {
	ss << "pool '" << poolstr << "' already exists";
	err = 0;
      }
      goto reply;
    }

    int pool_type;
    if (pool_type_str == "replicated") {
      pool_type = pg_pool_t::TYPE_REPLICATED;
    } else if (pool_type_str == "erasure") {
      pool_type = pg_pool_t::TYPE_ERASURE;
    } else {
      ss << "unknown pool type '" << pool_type_str << "'";
      err = -EINVAL;
      goto reply;
    }

    bool implicit_rule_creation = false;
    int64_t expected_num_objects = 0;
    string rule_name;
    cmd_getval(cct, cmdmap, "rule", rule_name);
    string erasure_code_profile;
    cmd_getval(cct, cmdmap, "erasure_code_profile", erasure_code_profile);

    if (pool_type == pg_pool_t::TYPE_ERASURE) {
      if (erasure_code_profile == "")
	erasure_code_profile = "default";
      //handle the erasure code profile
      if (erasure_code_profile == "default") {
	if (!osdmap.has_erasure_code_profile(erasure_code_profile)) {
	  if (pending_inc.has_erasure_code_profile(erasure_code_profile)) {
	    dout(20) << "erasure code profile " << erasure_code_profile << " already pending" << dendl;
	    goto wait;
	  }

	  map<string,string> profile_map;
	  err = osdmap.get_erasure_code_profile_default(cct,
						      profile_map,
						      &ss);
	  if (err)
	    goto reply;
	  dout(20) << "erasure code profile " << erasure_code_profile << " set" << dendl;
	  pending_inc.set_erasure_code_profile(erasure_code_profile, profile_map);
	  goto wait;
	}
      }
      if (rule_name == "") {
	implicit_rule_creation = true;
	if (erasure_code_profile == "default") {
	  rule_name = "erasure-code";
	} else {
	  dout(1) << "implicitly use rule named after the pool: "
		<< poolstr << dendl;
	  rule_name = poolstr;
	}
      }
      cmd_getval(g_ceph_context, cmdmap, "expected_num_objects",
                 expected_num_objects, int64_t(0));
    } else {
      //NOTE:for replicated pool,cmd_map will put rule_name to erasure_code_profile field
      //     and put expected_num_objects to rule field
      if (erasure_code_profile != "") { // cmd is from CLI
        if (rule_name != "") {
          string interr;
          expected_num_objects = strict_strtoll(rule_name.c_str(), 10, &interr);
          if (interr.length()) {
            ss << "error parsing integer value '" << rule_name << "': " << interr;
            err = -EINVAL;
            goto reply;
          }
        }
        rule_name = erasure_code_profile;
      } else { // cmd is well-formed
        cmd_getval(g_ceph_context, cmdmap, "expected_num_objects",
                   expected_num_objects, int64_t(0));
      }
    }

    if (!implicit_rule_creation && rule_name != "") {
      int rule;
      err = get_crush_rule(rule_name, &rule, &ss);
      if (err == -EAGAIN) {
	wait_for_finished_proposal(op, new C_RetryMessage(this, op));
	return true;
      }
      if (err)
	goto reply;
    }

    if (expected_num_objects < 0) {
      ss << "'expected_num_objects' must be non-negative";
      err = -EINVAL;
      goto reply;
    }

    set<int32_t> osds;
    osdmap.get_all_osds(osds);
    bool has_filestore_osd = std::any_of(osds.begin(), osds.end(), [this](int osd) {
      string type;
      if (!get_osd_objectstore_type(osd, &type)) {
        return type == "filestore";
      } else {
        return false;
      }
    });

    if (has_filestore_osd &&
        expected_num_objects > 0 &&
        cct->_conf->filestore_merge_threshold > 0) {
      ss << "'expected_num_objects' requires 'filestore_merge_threshold < 0'";
      err = -EINVAL;
      goto reply;
    }

    if (has_filestore_osd &&
        expected_num_objects == 0 &&
        cct->_conf->filestore_merge_threshold < 0) {
      int osds = osdmap.get_num_osds();
      bool sure = false;
      cmd_getval(cct, cmdmap, "yes_i_really_mean_it", sure);
      if (!sure && osds && (pg_num >= 1024 || pg_num / osds >= 100)) {
        ss << "For better initial performance on pools expected to store a "
           << "large number of objects, consider supplying the "
           << "expected_num_objects parameter when creating the pool."
           << " Pass --yes-i-really-mean-it to ignore it";
        err = -EPERM;
        goto reply;
      }
    }

    int64_t fast_read_param;
    cmd_getval(cct, cmdmap, "fast_read", fast_read_param, int64_t(-1));
    FastReadType fast_read = FAST_READ_DEFAULT;
    if (fast_read_param == 0)
      fast_read = FAST_READ_OFF;
    else if (fast_read_param > 0)
      fast_read = FAST_READ_ON;

    int64_t repl_size = 0;
    cmd_getval(cct, cmdmap, "size", repl_size);
    int64_t target_size_bytes = 0;
    double target_size_ratio = 0.0;
    cmd_getval(cct, cmdmap, "target_size_bytes", target_size_bytes);
    cmd_getval(cct, cmdmap, "target_size_ratio", target_size_ratio);

    err = prepare_new_pool(poolstr,
			   -1, // default crush rule
			   rule_name,
			   pg_num, pgp_num, pg_num_min,
                           repl_size, target_size_bytes, target_size_ratio,
			   erasure_code_profile, pool_type,
                           (uint64_t)expected_num_objects,
                           fast_read,
			   &ss);
    if (err < 0) {
      switch(err) {
      case -EEXIST:
	ss << "pool '" << poolstr << "' already exists";
	break;
      case -EAGAIN:
	wait_for_finished_proposal(op, new C_RetryMessage(this, op));
	return true;
      case -ERANGE:
        goto reply;
      default:
	goto reply;
	break;
      }
    } else {
      ss << "pool '" << poolstr << "' created";
    }
    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
					      get_last_committed() + 1));
    return true;

  } else if (prefix == "osd pool delete" ||
             prefix == "osd pool rm") {
    // osd pool delete/rm <poolname> <poolname again> --yes-i-really-really-mean-it
    string poolstr, poolstr2, sure;
    cmd_getval(cct, cmdmap, "pool", poolstr);
    cmd_getval(cct, cmdmap, "pool2", poolstr2);
    int64_t pool = osdmap.lookup_pg_pool_name(poolstr.c_str());
    if (pool < 0) {
      ss << "pool '" << poolstr << "' does not exist";
      err = 0;
      goto reply;
    }

    bool force_no_fake = false;
    cmd_getval(cct, cmdmap, "yes_i_really_really_mean_it", force_no_fake);
    bool force = false;
    cmd_getval(cct, cmdmap, "yes_i_really_really_mean_it_not_faking", force);
    if (poolstr2 != poolstr ||
	(!force && !force_no_fake)) {
      ss << "WARNING: this will *PERMANENTLY DESTROY* all data stored in pool " << poolstr
	 << ".  If you are *ABSOLUTELY CERTAIN* that is what you want, pass the pool name *twice*, "
	 << "followed by --yes-i-really-really-mean-it.";
      err = -EPERM;
      goto reply;
    }
    err = _prepare_remove_pool(pool, &ss, force_no_fake);
    if (err == -EAGAIN) {
      wait_for_finished_proposal(op, new C_RetryMessage(this, op));
      return true;
    }
    if (err < 0)
      goto reply;
    goto update;
  } else if (prefix == "osd pool rename") {
    string srcpoolstr, destpoolstr;
    cmd_getval(cct, cmdmap, "srcpool", srcpoolstr);
    cmd_getval(cct, cmdmap, "destpool", destpoolstr);
    int64_t pool_src = osdmap.lookup_pg_pool_name(srcpoolstr.c_str());
    int64_t pool_dst = osdmap.lookup_pg_pool_name(destpoolstr.c_str());

    if (pool_src < 0) {
      if (pool_dst >= 0) {
        // src pool doesn't exist, dst pool does exist: to ensure idempotency
        // of operations, assume this rename succeeded, as it is not changing
        // the current state.  Make sure we output something understandable
        // for whoever is issuing the command, if they are paying attention,
        // in case it was not intentional; or to avoid a "wtf?" and a bug
        // report in case it was intentional, while expecting a failure.
        ss << "pool '" << srcpoolstr << "' does not exist; pool '"
          << destpoolstr << "' does -- assuming successful rename";
        err = 0;
      } else {
        ss << "unrecognized pool '" << srcpoolstr << "'";
        err = -ENOENT;
      }
      goto reply;
    } else if (pool_dst >= 0) {
      // source pool exists and so does the destination pool
      ss << "pool '" << destpoolstr << "' already exists";
      err = -EEXIST;
      goto reply;
    }

    int ret = _prepare_rename_pool(pool_src, destpoolstr);
    if (ret == 0) {
      ss << "pool '" << srcpoolstr << "' renamed to '" << destpoolstr << "'";
    } else {
      ss << "failed to rename pool '" << srcpoolstr << "' to '" << destpoolstr << "': "
        << cpp_strerror(ret);
    }
    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, ret, rs,
					      get_last_committed() + 1));
    return true;

  } else if (prefix == "osd pool set") {
    err = prepare_command_pool_set(cmdmap, ss);
    if (err == -EAGAIN)
      goto wait;
    if (err < 0)
      goto reply;

    getline(ss, rs);
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
						   get_last_committed() + 1));
    return true;
  } else if (prefix == "osd tier add") {
    err = check_cluster_features(CEPH_FEATURE_OSD_CACHEPOOL, ss);
    if (err == -EAGAIN)
      goto wait;
    if (err)
      goto reply;
    string poolstr;
    cmd_getval(cct, cmdmap, "pool", poolstr);
    int64_t pool_id = osdmap.lookup_pg_pool_name(poolstr);
    if (pool_id < 0) {
      ss << "unrecognized pool '" << poolstr << "'";
      err = -ENOENT;
      goto reply;
    }
    string tierpoolstr;
    cmd_getval(cct, cmdmap, "tierpool", tierpoolstr);
    int64_t tierpool_id = osdmap.lookup_pg_pool_name(tierpoolstr);
    if (tierpool_id < 0) {
      ss << "unrecognized pool '" << tierpoolstr << "'";
      err = -ENOENT;
      goto reply;
    }
    const pg_pool_t *p = osdmap.get_pg_pool(pool_id);
    ceph_assert(p);
    const pg_pool_t *tp = osdmap.get_pg_pool(tierpool_id);
    ceph_assert(tp);

    if (!_check_become_tier(tierpool_id, tp, pool_id, p, &err, &ss)) {
      goto reply;
    }

    // make sure new tier is empty
    string force_nonempty;
    cmd_getval(cct, cmdmap, "force_nonempty", force_nonempty);
    const pool_stat_t *pstats = mon->mgrstatmon()->get_pool_stat(tierpool_id);
    if (pstats && pstats->stats.sum.num_objects != 0 &&
	force_nonempty != "--force-nonempty") {
      ss << "tier pool '" << tierpoolstr << "' is not empty; --force-nonempty to force";
      err = -ENOTEMPTY;
      goto reply;
    }
    if (tp->is_erasure()) {
      ss << "tier pool '" << tierpoolstr
	 << "' is an ec pool, which cannot be a tier";
      err = -ENOTSUP;
      goto reply;
    }
    if ((!tp->removed_snaps.empty() || !tp->snaps.empty()) &&
	((force_nonempty != "--force-nonempty") ||
	 (!g_conf()->mon_debug_unsafe_allow_tier_with_nonempty_snaps))) {
      ss << "tier pool '" << tierpoolstr << "' has snapshot state; it cannot be added as a tier without breaking the pool";
      err = -ENOTEMPTY;
      goto reply;
    }
    // go
    pg_pool_t *np = pending_inc.get_new_pool(pool_id, p);
    pg_pool_t *ntp = pending_inc.get_new_pool(tierpool_id, tp);
    if (np->tiers.count(tierpool_id) || ntp->is_tier()) {
      wait_for_finished_proposal(op, new C_RetryMessage(this, op));
      return true;
    }
    np->tiers.insert(tierpool_id);
    np->set_snap_epoch(pending_inc.epoch); // tier will update to our snap info
    ntp->tier_of = pool_id;
    ss << "pool '" << tierpoolstr << "' is now (or already was) a tier of '" << poolstr << "'";
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, ss.str(),
					      get_last_committed() + 1));
    return true;
  } else if (prefix == "osd tier remove" ||
             prefix == "osd tier rm") {
    string poolstr;
    cmd_getval(cct, cmdmap, "pool", poolstr);
    int64_t pool_id = osdmap.lookup_pg_pool_name(poolstr);
    if (pool_id < 0) {
      ss << "unrecognized pool '" << poolstr << "'";
      err = -ENOENT;
      goto reply;
    }
    string tierpoolstr;
    cmd_getval(cct, cmdmap, "tierpool", tierpoolstr);
    int64_t tierpool_id = osdmap.lookup_pg_pool_name(tierpoolstr);
    if (tierpool_id < 0) {
      ss << "unrecognized pool '" << tierpoolstr << "'";
      err = -ENOENT;
      goto reply;
    }
    const pg_pool_t *p = osdmap.get_pg_pool(pool_id);
    ceph_assert(p);
    const pg_pool_t *tp = osdmap.get_pg_pool(tierpool_id);
    ceph_assert(tp);

    if (!_check_remove_tier(pool_id, p, tp, &err, &ss)) {
      goto reply;
    }

    if (p->tiers.count(tierpool_id) == 0) {
      ss << "pool '" << tierpoolstr << "' is now (or already was) not a tier of '" << poolstr << "'";
      err = 0;
      goto reply;
    }
    if (tp->tier_of != pool_id) {
      ss << "tier pool '" << tierpoolstr << "' is a tier of '"
         << osdmap.get_pool_name(tp->tier_of) << "': "
         // be scary about it; this is an inconsistency and bells must go off
         << "THIS SHOULD NOT HAVE HAPPENED AT ALL";
      err = -EINVAL;
      goto reply;
    }
    if (p->read_tier == tierpool_id) {
      ss << "tier pool '" << tierpoolstr << "' is the overlay for '" << poolstr << "'; please remove-overlay first";
      err = -EBUSY;
      goto reply;
    }
    // go
    pg_pool_t *np = pending_inc.get_new_pool(pool_id, p);
    pg_pool_t *ntp = pending_inc.get_new_pool(tierpool_id, tp);
    if (np->tiers.count(tierpool_id) == 0 ||
	ntp->tier_of != pool_id ||
	np->read_tier == tierpool_id) {
      wait_for_finished_proposal(op, new C_RetryMessage(this, op));
      return true;
    }
    np->tiers.erase(tierpool_id);
    ntp->clear_tier();
    ss << "pool '" << tierpoolstr << "' is now (or already was) not a tier of '" << poolstr << "'";
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, ss.str(),
					      get_last_committed() + 1));
    return true;
  } else if (prefix == "osd tier set-overlay") {
    err = check_cluster_features(CEPH_FEATURE_OSD_CACHEPOOL, ss);
    if (err == -EAGAIN)
      goto wait;
    if (err)
      goto reply;
    string poolstr;
    cmd_getval(cct, cmdmap, "pool", poolstr);
    int64_t pool_id = osdmap.lookup_pg_pool_name(poolstr);
    if (pool_id < 0) {
      ss << "unrecognized pool '" << poolstr << "'";
      err = -ENOENT;
      goto reply;
    }
    string overlaypoolstr;
    cmd_getval(cct, cmdmap, "overlaypool", overlaypoolstr);
    int64_t overlaypool_id = osdmap.lookup_pg_pool_name(overlaypoolstr);
    if (overlaypool_id < 0) {
      ss << "unrecognized pool '" << overlaypoolstr << "'";
      err = -ENOENT;
      goto reply;
    }
    const pg_pool_t *p = osdmap.get_pg_pool(pool_id);
    ceph_assert(p);
    const pg_pool_t *overlay_p = osdmap.get_pg_pool(overlaypool_id);
    ceph_assert(overlay_p);
    if (p->tiers.count(overlaypool_id) == 0) {
      ss << "tier pool '" << overlaypoolstr << "' is not a tier of '" << poolstr << "'";
      err = -EINVAL;
      goto reply;
    }
    if (p->read_tier == overlaypool_id) {
      err = 0;
      ss << "overlay for '" << poolstr << "' is now (or already was) '" << overlaypoolstr << "'";
      goto reply;
    }
    if (p->has_read_tier()) {
      ss << "pool '" << poolstr << "' has overlay '"
	 << osdmap.get_pool_name(p->read_tier)
	 << "'; please remove-overlay first";
      err = -EINVAL;
      goto reply;
    }

    // go
    pg_pool_t *np = pending_inc.get_new_pool(pool_id, p);
    np->read_tier = overlaypool_id;
    np->write_tier = overlaypool_id;
    np->set_last_force_op_resend(pending_inc.epoch);
    pg_pool_t *noverlay_p = pending_inc.get_new_pool(overlaypool_id, overlay_p);
    noverlay_p->set_last_force_op_resend(pending_inc.epoch);
    ss << "overlay for '" << poolstr << "' is now (or already was) '" << overlaypoolstr << "'";
    if (overlay_p->cache_mode == pg_pool_t::CACHEMODE_NONE)
      ss <<" (WARNING: overlay pool cache_mode is still NONE)";
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, ss.str(),
					      get_last_committed() + 1));
    return true;
  } else if (prefix == "osd tier remove-overlay" ||
             prefix == "osd tier rm-overlay") {
    string poolstr;
    cmd_getval(cct, cmdmap, "pool", poolstr);
    int64_t pool_id = osdmap.lookup_pg_pool_name(poolstr);
    if (pool_id < 0) {
      ss << "unrecognized pool '" << poolstr << "'";
      err = -ENOENT;
      goto reply;
    }
    const pg_pool_t *p = osdmap.get_pg_pool(pool_id);
    ceph_assert(p);
    if (!p->has_read_tier()) {
      err = 0;
      ss << "there is now (or already was) no overlay for '" << poolstr << "'";
      goto reply;
    }

    if (!_check_remove_tier(pool_id, p, NULL, &err, &ss)) {
      goto reply;
    }

    // go
    pg_pool_t *np = pending_inc.get_new_pool(pool_id, p);
    if (np->has_read_tier()) {
      const pg_pool_t *op = osdmap.get_pg_pool(np->read_tier);
      pg_pool_t *nop = pending_inc.get_new_pool(np->read_tier,op);
      nop->set_last_force_op_resend(pending_inc.epoch);
    }
    if (np->has_write_tier()) {
      const pg_pool_t *op = osdmap.get_pg_pool(np->write_tier);
      pg_pool_t *nop = pending_inc.get_new_pool(np->write_tier, op);
      nop->set_last_force_op_resend(pending_inc.epoch);
    }
    np->clear_read_tier();
    np->clear_write_tier();
    np->set_last_force_op_resend(pending_inc.epoch);
    ss << "there is now (or already was) no overlay for '" << poolstr << "'";
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, ss.str(),
					      get_last_committed() + 1));
    return true;
  } else if (prefix == "osd tier cache-mode") {
    err = check_cluster_features(CEPH_FEATURE_OSD_CACHEPOOL, ss);
    if (err == -EAGAIN)
      goto wait;
    if (err)
      goto reply;
    string poolstr;
    cmd_getval(cct, cmdmap, "pool", poolstr);
    int64_t pool_id = osdmap.lookup_pg_pool_name(poolstr);
    if (pool_id < 0) {
      ss << "unrecognized pool '" << poolstr << "'";
      err = -ENOENT;
      goto reply;
    }
    const pg_pool_t *p = osdmap.get_pg_pool(pool_id);
    ceph_assert(p);
    if (!p->is_tier()) {
      ss << "pool '" << poolstr << "' is not a tier";
      err = -EINVAL;
      goto reply;
    }
    string modestr;
    cmd_getval(cct, cmdmap, "mode", modestr);
    pg_pool_t::cache_mode_t mode = pg_pool_t::get_cache_mode_from_str(modestr);
    if (mode < 0) {
      ss << "'" << modestr << "' is not a valid cache mode";
      err = -EINVAL;
      goto reply;
    }

    bool sure = false;
    cmd_getval(cct, cmdmap, "yes_i_really_mean_it", sure);

    if ((mode != pg_pool_t::CACHEMODE_WRITEBACK &&
	 mode != pg_pool_t::CACHEMODE_NONE &&
	 mode != pg_pool_t::CACHEMODE_PROXY &&
	 mode != pg_pool_t::CACHEMODE_READPROXY) &&
	 !sure) {
      ss << "'" << modestr << "' is not a well-supported cache mode and may "
	 << "corrupt your data.  pass --yes-i-really-mean-it to force.";
      err = -EPERM;
      goto reply;
    }

    // pool already has this cache-mode set and there are no pending changes
    if (p->cache_mode == mode &&
	(pending_inc.new_pools.count(pool_id) == 0 ||
	 pending_inc.new_pools[pool_id].cache_mode == p->cache_mode)) {
      ss << "set cache-mode for pool '" << poolstr << "'"
         << " to " << pg_pool_t::get_cache_mode_name(mode);
      err = 0;
      goto reply;
    }

    /* Mode description:
     *
     *  none:       No cache-mode defined
     *  forward:    Forward all reads and writes to base pool
     *  writeback:  Cache writes, promote reads from base pool
     *  readonly:   Forward writes to base pool
     *  readforward: Writes are in writeback mode, Reads are in forward mode
     *  proxy:       Proxy all reads and writes to base pool
     *  readproxy:   Writes are in writeback mode, Reads are in proxy mode
     *
     * Hence, these are the allowed transitions:
     *
     *  none -> any
     *  forward -> proxy || readforward || readproxy || writeback || any IF num_objects_dirty == 0
     *  proxy -> forward || readforward || readproxy || writeback || any IF num_objects_dirty == 0
     *  readforward -> forward || proxy || readproxy || writeback || any IF num_objects_dirty == 0
     *  readproxy -> forward || proxy || readforward || writeback || any IF num_objects_dirty == 0
     *  writeback -> readforward || readproxy || forward || proxy
     *  readonly -> any
     */

    // We check if the transition is valid against the current pool mode, as
    // it is the only committed state thus far.  We will blantly squash
    // whatever mode is on the pending state.

    if (p->cache_mode == pg_pool_t::CACHEMODE_WRITEBACK &&
        (mode != pg_pool_t::CACHEMODE_FORWARD &&
	  mode != pg_pool_t::CACHEMODE_PROXY &&
	  mode != pg_pool_t::CACHEMODE_READFORWARD &&
	  mode != pg_pool_t::CACHEMODE_READPROXY)) {
      ss << "unable to set cache-mode '" << pg_pool_t::get_cache_mode_name(mode)
         << "' on a '" << pg_pool_t::get_cache_mode_name(p->cache_mode)
         << "' pool; only '"
         << pg_pool_t::get_cache_mode_name(pg_pool_t::CACHEMODE_FORWARD)
	 << "','"
         << pg_pool_t::get_cache_mode_name(pg_pool_t::CACHEMODE_PROXY)
	 << "','"
         << pg_pool_t::get_cache_mode_name(pg_pool_t::CACHEMODE_READFORWARD)
	 << "','"
         << pg_pool_t::get_cache_mode_name(pg_pool_t::CACHEMODE_READPROXY)
        << "' allowed.";
      err = -EINVAL;
      goto reply;
    }
    if ((p->cache_mode == pg_pool_t::CACHEMODE_READFORWARD &&
        (mode != pg_pool_t::CACHEMODE_WRITEBACK &&
	  mode != pg_pool_t::CACHEMODE_FORWARD &&
	  mode != pg_pool_t::CACHEMODE_PROXY &&
	  mode != pg_pool_t::CACHEMODE_READPROXY)) ||

        (p->cache_mode == pg_pool_t::CACHEMODE_READPROXY &&
        (mode != pg_pool_t::CACHEMODE_WRITEBACK &&
	  mode != pg_pool_t::CACHEMODE_FORWARD &&
	  mode != pg_pool_t::CACHEMODE_READFORWARD &&
	  mode != pg_pool_t::CACHEMODE_PROXY)) ||

        (p->cache_mode == pg_pool_t::CACHEMODE_PROXY &&
        (mode != pg_pool_t::CACHEMODE_WRITEBACK &&
	  mode != pg_pool_t::CACHEMODE_FORWARD &&
	  mode != pg_pool_t::CACHEMODE_READFORWARD &&
	  mode != pg_pool_t::CACHEMODE_READPROXY)) ||

        (p->cache_mode == pg_pool_t::CACHEMODE_FORWARD &&
        (mode != pg_pool_t::CACHEMODE_WRITEBACK &&
	  mode != pg_pool_t::CACHEMODE_READFORWARD &&
	  mode != pg_pool_t::CACHEMODE_PROXY &&
	  mode != pg_pool_t::CACHEMODE_READPROXY))) {

      const pool_stat_t* pstats =
        mon->mgrstatmon()->get_pool_stat(pool_id);

      if (pstats && pstats->stats.sum.num_objects_dirty > 0) {
        ss << "unable to set cache-mode '"
           << pg_pool_t::get_cache_mode_name(mode) << "' on pool '" << poolstr
           << "': dirty objects found";
        err = -EBUSY;
        goto reply;
      }
    }
    // go
    pg_pool_t *np = pending_inc.get_new_pool(pool_id, p);
    np->cache_mode = mode;
    // set this both when moving to and from cache_mode NONE.  this is to
    // capture legacy pools that were set up before this flag existed.
    np->flags |= pg_pool_t::FLAG_INCOMPLETE_CLONES;
    ss << "set cache-mode for pool '" << poolstr
	<< "' to " << pg_pool_t::get_cache_mode_name(mode);
    if (mode == pg_pool_t::CACHEMODE_NONE) {
      const pg_pool_t *base_pool = osdmap.get_pg_pool(np->tier_of);
      ceph_assert(base_pool);
      if (base_pool->read_tier == pool_id ||
	  base_pool->write_tier == pool_id)
	ss <<" (WARNING: pool is still configured as read or write tier)";
    }
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, ss.str(),
					      get_last_committed() + 1));
    return true;
  } else if (prefix == "osd tier add-cache") {
    err = check_cluster_features(CEPH_FEATURE_OSD_CACHEPOOL, ss);
    if (err == -EAGAIN)
      goto wait;
    if (err)
      goto reply;
    string poolstr;
    cmd_getval(cct, cmdmap, "pool", poolstr);
    int64_t pool_id = osdmap.lookup_pg_pool_name(poolstr);
    if (pool_id < 0) {
      ss << "unrecognized pool '" << poolstr << "'";
      err = -ENOENT;
      goto reply;
    }
    string tierpoolstr;
    cmd_getval(cct, cmdmap, "tierpool", tierpoolstr);
    int64_t tierpool_id = osdmap.lookup_pg_pool_name(tierpoolstr);
    if (tierpool_id < 0) {
      ss << "unrecognized pool '" << tierpoolstr << "'";
      err = -ENOENT;
      goto reply;
    }
    const pg_pool_t *p = osdmap.get_pg_pool(pool_id);
    ceph_assert(p);
    const pg_pool_t *tp = osdmap.get_pg_pool(tierpool_id);
    ceph_assert(tp);

    if (!_check_become_tier(tierpool_id, tp, pool_id, p, &err, &ss)) {
      goto reply;
    }

    int64_t size = 0;
    if (!cmd_getval(cct, cmdmap, "size", size)) {
      ss << "unable to parse 'size' value '"
         << cmd_vartype_stringify(cmdmap.at("size")) << "'";
      err = -EINVAL;
      goto reply;
    }
    // make sure new tier is empty
    const pool_stat_t *pstats =
      mon->mgrstatmon()->get_pool_stat(tierpool_id);
    if (pstats && pstats->stats.sum.num_objects != 0) {
      ss << "tier pool '" << tierpoolstr << "' is not empty";
      err = -ENOTEMPTY;
      goto reply;
    }
    auto& modestr = g_conf().get_val<string>("osd_tier_default_cache_mode");
    pg_pool_t::cache_mode_t mode = pg_pool_t::get_cache_mode_from_str(modestr);
    if (mode < 0) {
      ss << "osd tier cache default mode '" << modestr << "' is not a valid cache mode";
      err = -EINVAL;
      goto reply;
    }
    HitSet::Params hsp;
    auto& cache_hit_set_type =
      g_conf().get_val<string>("osd_tier_default_cache_hit_set_type");
    if (cache_hit_set_type == "bloom") {
      BloomHitSet::Params *bsp = new BloomHitSet::Params;
      bsp->set_fpp(g_conf().get_val<double>("osd_pool_default_hit_set_bloom_fpp"));
      hsp = HitSet::Params(bsp);
    } else if (cache_hit_set_type == "explicit_hash") {
      hsp = HitSet::Params(new ExplicitHashHitSet::Params);
    } else if (cache_hit_set_type == "explicit_object") {
      hsp = HitSet::Params(new ExplicitObjectHitSet::Params);
    } else {
      ss << "osd tier cache default hit set type '"
	 << cache_hit_set_type << "' is not a known type";
      err = -EINVAL;
      goto reply;
    }
    // go
    pg_pool_t *np = pending_inc.get_new_pool(pool_id, p);
    pg_pool_t *ntp = pending_inc.get_new_pool(tierpool_id, tp);
    if (np->tiers.count(tierpool_id) || ntp->is_tier()) {
      wait_for_finished_proposal(op, new C_RetryMessage(this, op));
      return true;
    }
    np->tiers.insert(tierpool_id);
    np->read_tier = np->write_tier = tierpool_id;
    np->set_snap_epoch(pending_inc.epoch); // tier will update to our snap info
    np->set_last_force_op_resend(pending_inc.epoch);
    ntp->set_last_force_op_resend(pending_inc.epoch);
    ntp->tier_of = pool_id;
    ntp->cache_mode = mode;
    ntp->hit_set_count = g_conf().get_val<uint64_t>("osd_tier_default_cache_hit_set_count");
    ntp->hit_set_period = g_conf().get_val<uint64_t>("osd_tier_default_cache_hit_set_period");
    ntp->min_read_recency_for_promote = g_conf().get_val<uint64_t>("osd_tier_default_cache_min_read_recency_for_promote");
    ntp->min_write_recency_for_promote = g_conf().get_val<uint64_t>("osd_tier_default_cache_min_write_recency_for_promote");
    ntp->hit_set_grade_decay_rate = g_conf().get_val<uint64_t>("osd_tier_default_cache_hit_set_grade_decay_rate");
    ntp->hit_set_search_last_n = g_conf().get_val<uint64_t>("osd_tier_default_cache_hit_set_search_last_n");
    ntp->hit_set_params = hsp;
    ntp->target_max_bytes = size;
    ss << "pool '" << tierpoolstr << "' is now (or already was) a cache tier of '" << poolstr << "'";
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, ss.str(),
					      get_last_committed() + 1));
    return true;
  } else if (prefix == "osd pool set-quota") {
    string poolstr;
    cmd_getval(cct, cmdmap, "pool", poolstr);
    int64_t pool_id = osdmap.lookup_pg_pool_name(poolstr);
    if (pool_id < 0) {
      ss << "unrecognized pool '" << poolstr << "'";
      err = -ENOENT;
      goto reply;
    }

    string field;
    cmd_getval(cct, cmdmap, "field", field);
    if (field != "max_objects" && field != "max_bytes") {
      ss << "unrecognized field '" << field << "'; should be 'max_bytes' or 'max_objects'";
      err = -EINVAL;
      goto reply;
    }

    // val could contain unit designations, so we treat as a string
    string val;
    cmd_getval(cct, cmdmap, "val", val);
    string tss;
    int64_t value;
    if (field == "max_objects") {
      value = strict_sistrtoll(val.c_str(), &tss);
    } else if (field == "max_bytes") {
      value = strict_iecstrtoll(val.c_str(), &tss);
    } else {
      ceph_abort_msg("unrecognized option");
    }
    if (!tss.empty()) {
      ss << "error parsing value '" << val << "': " << tss;
      err = -EINVAL;
      goto reply;
    }

    pg_pool_t *pi = pending_inc.get_new_pool(pool_id, osdmap.get_pg_pool(pool_id));
    if (field == "max_objects") {
      pi->quota_max_objects = value;
    } else if (field == "max_bytes") {
      pi->quota_max_bytes = value;
    } else {
      ceph_abort_msg("unrecognized option");
    }
    ss << "set-quota " << field << " = " << value << " for pool " << poolstr;
    rs = ss.str();
    wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
					      get_last_committed() + 1));
    return true;
  } else if (prefix == "osd pool application enable" ||
             prefix == "osd pool application disable" ||
             prefix == "osd pool application set" ||
             prefix == "osd pool application rm") {
    err = prepare_command_pool_application(prefix, cmdmap, ss);
    if (err == -EAGAIN) {
      goto wait;
    } else if (err < 0) {
      goto reply;
    } else {
      goto update;
    }
  } else if (prefix == "osd force-create-pg") {
    pg_t pgid;
    string pgidstr;
    cmd_getval(cct, cmdmap, "pgid", pgidstr);
    if (!pgid.parse(pgidstr.c_str())) {
      ss << "invalid pgid '" << pgidstr << "'";
      err = -EINVAL;
      goto reply;
    }
    if (!osdmap.pg_exists(pgid)) {
      ss << "pg " << pgid << " should not exist";
      err = -ENOENT;
      goto reply;
    }
    bool sure = false;
    cmd_getval(cct, cmdmap, "yes_i_really_mean_it", sure);
    if (!sure) {
      ss << "This command will recreate a lost (as in data lost) PG with data in it, such "
	 << "that the cluster will give up ever trying to recover the lost data.  Do this "
	 << "only if you are certain that all copies of the PG are in fact lost and you are "
	 << "willing to accept that the data is permanently destroyed.  Pass "
	 << "--yes-i-really-mean-it to proceed.";
      err = -EPERM;
      goto reply;
    }
    bool creating_now;
    {
      std::lock_guard<std::mutex> l(creating_pgs_lock);
      auto emplaced = creating_pgs.pgs.emplace(pgid,
					       make_pair(osdmap.get_epoch(),
							 ceph_clock_now()));
      creating_now = emplaced.second;
    }
    if (creating_now) {
      ss << "pg " << pgidstr << " now creating, ok";
      // set the pool's CREATING flag so that (1) the osd won't ignore our
      // create message and (2) we won't propose any future pg_num changes
      // until after the PG has been instantiated.
      if (pending_inc.new_pools.count(pgid.pool()) == 0) {
	pending_inc.new_pools[pgid.pool()] = *osdmap.get_pg_pool(pgid.pool());
      }
      pending_inc.new_pools[pgid.pool()].flags |= pg_pool_t::FLAG_CREATING;
      err = 0;
      goto update;
    } else {
      ss << "pg " << pgid << " already creating";
      err = 0;
      goto reply;
    }
  } else {
    err = -EINVAL;
  }

 reply:
  getline(ss, rs);
  if (err < 0 && rs.length() == 0)
    rs = cpp_strerror(err);
  mon->reply_command(op, err, rs, rdata, get_last_committed());
  return ret;

 update:
  getline(ss, rs);
  wait_for_finished_proposal(op, new Monitor::C_Command(mon, op, 0, rs,
					    get_last_committed() + 1));
  return true;

 wait:
  wait_for_finished_proposal(op, new C_RetryMessage(this, op));
  return true;
}

bool OSDMonitor::enforce_pool_op_caps(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);

  MPoolOp *m = static_cast<MPoolOp*>(op->get_req());
  MonSession *session = op->get_session();
  if (!session) {
    _pool_op_reply(op, -EPERM, osdmap.get_epoch());
    return true;
  }

  switch (m->op) {
  case POOL_OP_CREATE_UNMANAGED_SNAP:
  case POOL_OP_DELETE_UNMANAGED_SNAP:
    {
      const std::string* pool_name = nullptr;
      const pg_pool_t *pg_pool = osdmap.get_pg_pool(m->pool);
      if (pg_pool != nullptr) {
        pool_name = &osdmap.get_pool_name(m->pool);
      }

      if (!is_unmanaged_snap_op_permitted(cct, mon->key_server,
                                          session->entity_name, session->caps,
					  session->get_peer_socket_addr(),
                                          pool_name)) {
        dout(0) << "got unmanaged-snap pool op from entity with insufficient "
                << "privileges. message: " << *m  << std::endl
                << "caps: " << session->caps << dendl;
        _pool_op_reply(op, -EPERM, osdmap.get_epoch());
        return true;
      }
    }
    break;
  default:
    if (!session->is_capable("osd", MON_CAP_W)) {
      dout(0) << "got pool op from entity with insufficient privileges. "
              << "message: " << *m  << std::endl
              << "caps: " << session->caps << dendl;
      _pool_op_reply(op, -EPERM, osdmap.get_epoch());
      return true;
    }
    break;
  }

  return false;
}

bool OSDMonitor::preprocess_pool_op(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  MPoolOp *m = static_cast<MPoolOp*>(op->get_req());

  if (enforce_pool_op_caps(op)) {
    return true;
  }

  if (m->fsid != mon->monmap->fsid) {
    dout(0) << __func__ << " drop message on fsid " << m->fsid
            << " != " << mon->monmap->fsid << " for " << *m << dendl;
    _pool_op_reply(op, -EINVAL, osdmap.get_epoch());
    return true;
  }

  if (m->op == POOL_OP_CREATE)
    return preprocess_pool_op_create(op);

  const pg_pool_t *p = osdmap.get_pg_pool(m->pool);
  if (p == nullptr) {
    dout(10) << "attempt to operate on non-existent pool id " << m->pool << dendl;
    if (m->op == POOL_OP_DELETE) {
      _pool_op_reply(op, 0, osdmap.get_epoch());
    } else {
      _pool_op_reply(op, -ENOENT, osdmap.get_epoch());
    }
    return true;
  }

  // check if the snap and snapname exist
  bool snap_exists = false;
  if (p->snap_exists(m->name.c_str()))
    snap_exists = true;

  switch (m->op) {
  case POOL_OP_CREATE_SNAP:
    if (p->is_unmanaged_snaps_mode() || p->is_tier()) {
      _pool_op_reply(op, -EINVAL, osdmap.get_epoch());
      return true;
    }
    if (snap_exists) {
      _pool_op_reply(op, 0, osdmap.get_epoch());
      return true;
    }
    return false;
  case POOL_OP_CREATE_UNMANAGED_SNAP:
    if (p->is_pool_snaps_mode()) {
      _pool_op_reply(op, -EINVAL, osdmap.get_epoch());
      return true;
    }
    return false;
  case POOL_OP_DELETE_SNAP:
    if (p->is_unmanaged_snaps_mode()) {
      _pool_op_reply(op, -EINVAL, osdmap.get_epoch());
      return true;
    }
    if (!snap_exists) {
      _pool_op_reply(op, 0, osdmap.get_epoch());
      return true;
    }
    return false;
  case POOL_OP_DELETE_UNMANAGED_SNAP:
    if (p->is_pool_snaps_mode()) {
      _pool_op_reply(op, -EINVAL, osdmap.get_epoch());
      return true;
    }
    if (p->is_removed_snap(m->snapid)) {
      _pool_op_reply(op, 0, osdmap.get_epoch());
      return true;
    }
    return false;
  case POOL_OP_DELETE:
    if (osdmap.lookup_pg_pool_name(m->name.c_str()) >= 0) {
      _pool_op_reply(op, 0, osdmap.get_epoch());
      return true;
    }
    return false;
  case POOL_OP_AUID_CHANGE:
    return false;
  default:
    ceph_abort();
    break;
  }

  return false;
}

bool OSDMonitor::preprocess_pool_op_create(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  MPoolOp *m = static_cast<MPoolOp*>(op->get_req());
  int64_t pool = osdmap.lookup_pg_pool_name(m->name.c_str());
  if (pool >= 0) {
    _pool_op_reply(op, 0, osdmap.get_epoch());
    return true;
  }

  return false;
}

bool OSDMonitor::prepare_pool_op(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  MPoolOp *m = static_cast<MPoolOp*>(op->get_req());
  dout(10) << "prepare_pool_op " << *m << dendl;
  if (m->op == POOL_OP_CREATE) {
    return prepare_pool_op_create(op);
  } else if (m->op == POOL_OP_DELETE) {
    return prepare_pool_op_delete(op);
  }

  int ret = 0;
  bool changed = false;

  if (!osdmap.have_pg_pool(m->pool)) {
    _pool_op_reply(op, -ENOENT, osdmap.get_epoch());
    return false;
  }

  const pg_pool_t *pool = osdmap.get_pg_pool(m->pool);

  switch (m->op) {
    case POOL_OP_CREATE_SNAP:
      if (pool->is_tier()) {
        ret = -EINVAL;
        _pool_op_reply(op, ret, osdmap.get_epoch());
        return false;
      }  // else, fall through
    case POOL_OP_DELETE_SNAP:
      if (!pool->is_unmanaged_snaps_mode()) {
        bool snap_exists = pool->snap_exists(m->name.c_str());
        if ((m->op == POOL_OP_CREATE_SNAP && snap_exists)
          || (m->op == POOL_OP_DELETE_SNAP && !snap_exists)) {
          ret = 0;
        } else {
          break;
        }
      } else {
        ret = -EINVAL;
      }
      _pool_op_reply(op, ret, osdmap.get_epoch());
      return false;

    case POOL_OP_DELETE_UNMANAGED_SNAP:
      // we won't allow removal of an unmanaged snapshot from a pool
      // not in unmanaged snaps mode.
      if (!pool->is_unmanaged_snaps_mode()) {
        _pool_op_reply(op, -ENOTSUP, osdmap.get_epoch());
        return false;
      }
      /* fall-thru */
    case POOL_OP_CREATE_UNMANAGED_SNAP:
      // but we will allow creating an unmanaged snapshot on any pool
      // as long as it is not in 'pool' snaps mode.
      if (pool->is_pool_snaps_mode()) {
        _pool_op_reply(op, -EINVAL, osdmap.get_epoch());
        return false;
      }
  }

  // projected pool info
  pg_pool_t pp;
  if (pending_inc.new_pools.count(m->pool))
    pp = pending_inc.new_pools[m->pool];
  else
    pp = *osdmap.get_pg_pool(m->pool);

  bufferlist reply_data;

  // pool snaps vs unmanaged snaps are mutually exclusive
  switch (m->op) {
  case POOL_OP_CREATE_SNAP:
  case POOL_OP_DELETE_SNAP:
    if (pp.is_unmanaged_snaps_mode()) {
      ret = -EINVAL;
      goto out;
    }
    break;

  case POOL_OP_CREATE_UNMANAGED_SNAP:
  case POOL_OP_DELETE_UNMANAGED_SNAP:
    if (pp.is_pool_snaps_mode()) {
      ret = -EINVAL;
      goto out;
    }
  }

  switch (m->op) {
  case POOL_OP_CREATE_SNAP:
    if (!pp.snap_exists(m->name.c_str())) {
      pp.add_snap(m->name.c_str(), ceph_clock_now());
      dout(10) << "create snap in pool " << m->pool << " " << m->name
	       << " seq " << pp.get_snap_epoch() << dendl;
      changed = true;
    }
    break;

  case POOL_OP_DELETE_SNAP:
    {
      snapid_t s = pp.snap_exists(m->name.c_str());
      if (s) {
	pp.remove_snap(s);
	pending_inc.new_removed_snaps[m->pool].insert(s);
	changed = true;
      }
    }
    break;

  case POOL_OP_CREATE_UNMANAGED_SNAP:
    {
      uint64_t snapid;
      pp.add_unmanaged_snap(snapid);
      encode(snapid, reply_data);
      changed = true;
    }
    break;

  case POOL_OP_DELETE_UNMANAGED_SNAP:
    if (!pp.is_removed_snap(m->snapid)) {
      if (m->snapid > pp.get_snap_seq()) {
        _pool_op_reply(op, -ENOENT, osdmap.get_epoch());
        return false;
      }
      pp.remove_unmanaged_snap(m->snapid);
      pending_inc.new_removed_snaps[m->pool].insert(m->snapid);
      changed = true;
    }
    break;

  case POOL_OP_AUID_CHANGE:
    _pool_op_reply(op, -EOPNOTSUPP, osdmap.get_epoch());
    return false;

  default:
    ceph_abort();
    break;
  }

  if (changed) {
    pp.set_snap_epoch(pending_inc.epoch);
    pending_inc.new_pools[m->pool] = pp;
  }

 out:
  wait_for_finished_proposal(op, new OSDMonitor::C_PoolOp(this, op, ret, pending_inc.epoch, &reply_data));
  return true;
}

bool OSDMonitor::prepare_pool_op_create(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  int err = prepare_new_pool(op);
  wait_for_finished_proposal(op, new OSDMonitor::C_PoolOp(this, op, err, pending_inc.epoch));
  return true;
}

int OSDMonitor::_check_remove_pool(int64_t pool_id, const pg_pool_t& pool,
				   ostream *ss)
{
  const string& poolstr = osdmap.get_pool_name(pool_id);

  // If the Pool is in use by CephFS, refuse to delete it
  FSMap const &pending_fsmap = mon->mdsmon()->get_pending_fsmap();
  if (pending_fsmap.pool_in_use(pool_id)) {
    *ss << "pool '" << poolstr << "' is in use by CephFS";
    return -EBUSY;
  }

  if (pool.tier_of >= 0) {
    *ss << "pool '" << poolstr << "' is a tier of '"
	<< osdmap.get_pool_name(pool.tier_of) << "'";
    return -EBUSY;
  }
  if (!pool.tiers.empty()) {
    *ss << "pool '" << poolstr << "' has tiers";
    for(auto tier : pool.tiers) {
      *ss << " " << osdmap.get_pool_name(tier);
    }
    return -EBUSY;
  }

  if (!g_conf()->mon_allow_pool_delete) {
    *ss << "pool deletion is disabled; you must first set the mon_allow_pool_delete config option to true before you can destroy a pool";
    return -EPERM;
  }

  if (pool.has_flag(pg_pool_t::FLAG_NODELETE)) {
    *ss << "pool deletion is disabled; you must unset nodelete flag for the pool first";
    return -EPERM;
  }

  *ss << "pool '" << poolstr << "' removed";
  return 0;
}

/**
 * Check if it is safe to add a tier to a base pool
 *
 * @return
 * True if the operation should proceed, false if we should abort here
 * (abort doesn't necessarily mean error, could be idempotency)
 */
bool OSDMonitor::_check_become_tier(
    const int64_t tier_pool_id, const pg_pool_t *tier_pool,
    const int64_t base_pool_id, const pg_pool_t *base_pool,
    int *err,
    ostream *ss) const
{
  const std::string &tier_pool_name = osdmap.get_pool_name(tier_pool_id);
  const std::string &base_pool_name = osdmap.get_pool_name(base_pool_id);

  const FSMap &pending_fsmap = mon->mdsmon()->get_pending_fsmap();
  if (pending_fsmap.pool_in_use(tier_pool_id)) {
    *ss << "pool '" << tier_pool_name << "' is in use by CephFS";
    *err = -EBUSY;
    return false;
  }

  if (base_pool->tiers.count(tier_pool_id)) {
    ceph_assert(tier_pool->tier_of == base_pool_id);
    *err = 0;
    *ss << "pool '" << tier_pool_name << "' is now (or already was) a tier of '"
      << base_pool_name << "'";
    return false;
  }

  if (base_pool->is_tier()) {
    *ss << "pool '" << base_pool_name << "' is already a tier of '"
      << osdmap.get_pool_name(base_pool->tier_of) << "', "
      << "multiple tiers are not yet supported.";
    *err = -EINVAL;
    return false;
  }

  if (tier_pool->has_tiers()) {
    *ss << "pool '" << tier_pool_name << "' has following tier(s) already:";
    for (set<uint64_t>::iterator it = tier_pool->tiers.begin();
         it != tier_pool->tiers.end(); ++it)
      *ss << "'" << osdmap.get_pool_name(*it) << "',";
    *ss << " multiple tiers are not yet supported.";
    *err = -EINVAL;
    return false;
  }

  if (tier_pool->is_tier()) {
    *ss << "tier pool '" << tier_pool_name << "' is already a tier of '"
       << osdmap.get_pool_name(tier_pool->tier_of) << "'";
    *err = -EINVAL;
    return false;
  }

  *err = 0;
  return true;
}


/**
 * Check if it is safe to remove a tier from this base pool
 *
 * @return
 * True if the operation should proceed, false if we should abort here
 * (abort doesn't necessarily mean error, could be idempotency)
 */
bool OSDMonitor::_check_remove_tier(
    const int64_t base_pool_id, const pg_pool_t *base_pool,
    const pg_pool_t *tier_pool,
    int *err, ostream *ss) const
{
  const std::string &base_pool_name = osdmap.get_pool_name(base_pool_id);

  // Apply CephFS-specific checks
  const FSMap &pending_fsmap = mon->mdsmon()->get_pending_fsmap();
  if (pending_fsmap.pool_in_use(base_pool_id)) {
    if (base_pool->is_erasure() && !base_pool->allows_ecoverwrites()) {
      // If the underlying pool is erasure coded and does not allow EC
      // overwrites, we can't permit the removal of the replicated tier that
      // CephFS relies on to access it
      *ss << "pool '" << base_pool_name <<
          "' does not allow EC overwrites and is in use by CephFS"
          " via its tier";
      *err = -EBUSY;
      return false;
    }

    if (tier_pool && tier_pool->cache_mode == pg_pool_t::CACHEMODE_WRITEBACK) {
      *ss << "pool '" << base_pool_name << "' is in use by CephFS, and this "
             "tier is still in use as a writeback cache.  Change the cache "
             "mode and flush the cache before removing it";
      *err = -EBUSY;
      return false;
    }
  }

  *err = 0;
  return true;
}

int OSDMonitor::_prepare_remove_pool(
  int64_t pool, ostream *ss, bool no_fake)
{
  dout(10) << __func__ << " " << pool << dendl;
  const pg_pool_t *p = osdmap.get_pg_pool(pool);
  int r = _check_remove_pool(pool, *p, ss);
  if (r < 0)
    return r;

  auto new_pool = pending_inc.new_pools.find(pool);
  if (new_pool != pending_inc.new_pools.end()) {
    // if there is a problem with the pending info, wait and retry
    // this op.
    const auto& p = new_pool->second;
    int r = _check_remove_pool(pool, p, ss);
    if (r < 0)
      return -EAGAIN;
  }

  if (pending_inc.old_pools.count(pool)) {
    dout(10) << __func__ << " " << pool << " already pending removal"
	     << dendl;
    return 0;
  }

  if (g_conf()->mon_fake_pool_delete && !no_fake) {
    string old_name = osdmap.get_pool_name(pool);
    string new_name = old_name + "." + stringify(pool) + ".DELETED";
    dout(1) << __func__ << " faking pool deletion: renaming " << pool << " "
	    << old_name << " -> " << new_name << dendl;
    pending_inc.new_pool_names[pool] = new_name;
    return 0;
  }

  // remove
  pending_inc.old_pools.insert(pool);

  // remove any pg_temp mappings for this pool
  for (auto p = osdmap.pg_temp->begin();
       p != osdmap.pg_temp->end();
       ++p) {
    if (p->first.pool() == pool) {
      dout(10) << __func__ << " " << pool << " removing obsolete pg_temp "
	       << p->first << dendl;
      pending_inc.new_pg_temp[p->first].clear();
    }
  }
  // remove any primary_temp mappings for this pool
  for (auto p = osdmap.primary_temp->begin();
      p != osdmap.primary_temp->end();
      ++p) {
    if (p->first.pool() == pool) {
      dout(10) << __func__ << " " << pool
               << " removing obsolete primary_temp" << p->first << dendl;
      pending_inc.new_primary_temp[p->first] = -1;
    }
  }
  // remove any pg_upmap mappings for this pool
  for (auto& p : osdmap.pg_upmap) {
    if (p.first.pool() == pool) {
      dout(10) << __func__ << " " << pool
               << " removing obsolete pg_upmap "
               << p.first << dendl;
      pending_inc.old_pg_upmap.insert(p.first);
    }
  }
  // remove any pending pg_upmap mappings for this pool
  {
    auto it = pending_inc.new_pg_upmap.begin();
    while (it != pending_inc.new_pg_upmap.end()) {
      if (it->first.pool() == pool) {
        dout(10) << __func__ << " " << pool
                 << " removing pending pg_upmap "
                 << it->first << dendl;
        it = pending_inc.new_pg_upmap.erase(it);
      } else {
        it++;
      }
    }
  }
  // remove any pg_upmap_items mappings for this pool
  for (auto& p : osdmap.pg_upmap_items) {
    if (p.first.pool() == pool) {
      dout(10) << __func__ << " " << pool
               << " removing obsolete pg_upmap_items " << p.first
               << dendl;
      pending_inc.old_pg_upmap_items.insert(p.first);
    }
  }
  // remove any pending pg_upmap mappings for this pool
  {
    auto it = pending_inc.new_pg_upmap_items.begin();
    while (it != pending_inc.new_pg_upmap_items.end()) {
      if (it->first.pool() == pool) {
        dout(10) << __func__ << " " << pool
                 << " removing pending pg_upmap_items "
                 << it->first << dendl;
        it = pending_inc.new_pg_upmap_items.erase(it);
      } else {
        it++;
      }
    }
  }

  // remove any choose_args for this pool
  CrushWrapper newcrush;
  _get_pending_crush(newcrush);
  if (newcrush.have_choose_args(pool)) {
    dout(10) << __func__ << " removing choose_args for pool " << pool << dendl;
    newcrush.rm_choose_args(pool);
    pending_inc.crush.clear();
    newcrush.encode(pending_inc.crush, mon->get_quorum_con_features());
  }
  return 0;
}

int OSDMonitor::_prepare_rename_pool(int64_t pool, string newname)
{
  dout(10) << "_prepare_rename_pool " << pool << dendl;
  if (pending_inc.old_pools.count(pool)) {
    dout(10) << "_prepare_rename_pool " << pool << " pending removal" << dendl;
    return -ENOENT;
  }
  for (map<int64_t,string>::iterator p = pending_inc.new_pool_names.begin();
       p != pending_inc.new_pool_names.end();
       ++p) {
    if (p->second == newname && p->first != pool) {
      return -EEXIST;
    }
  }

  pending_inc.new_pool_names[pool] = newname;
  return 0;
}

bool OSDMonitor::prepare_pool_op_delete(MonOpRequestRef op)
{
  op->mark_osdmon_event(__func__);
  MPoolOp *m = static_cast<MPoolOp*>(op->get_req());
  ostringstream ss;
  int ret = _prepare_remove_pool(m->pool, &ss, false);
  if (ret == -EAGAIN) {
    wait_for_finished_proposal(op, new C_RetryMessage(this, op));
    return true;
  }
  if (ret < 0)
    dout(10) << __func__ << " got " << ret << " " << ss.str() << dendl;
  wait_for_finished_proposal(op, new OSDMonitor::C_PoolOp(this, op, ret,
						      pending_inc.epoch));
  return true;
}

void OSDMonitor::_pool_op_reply(MonOpRequestRef op,
                                int ret, epoch_t epoch, bufferlist *blp)
{
  op->mark_osdmon_event(__func__);
  MPoolOp *m = static_cast<MPoolOp*>(op->get_req());
  dout(20) << "_pool_op_reply " << ret << dendl;
  MPoolOpReply *reply = new MPoolOpReply(m->fsid, m->get_tid(),
					 ret, epoch, get_last_committed(), blp);
  mon->send_reply(op, reply);
}

void OSDMonitor::convert_pool_priorities(void)
{
  pool_opts_t::key_t key = pool_opts_t::get_opt_desc("recovery_priority").key;
  int64_t max_prio = 0;
  int64_t min_prio = 0;
  for (const auto &i : osdmap.get_pools()) {
    const auto &pool = i.second;

    if (pool.opts.is_set(key)) {
      int64_t prio;
      pool.opts.get(key, &prio);
      if (prio > max_prio)
	max_prio = prio;
      if (prio < min_prio)
	min_prio = prio;
    }
  }
  if (max_prio <= OSD_POOL_PRIORITY_MAX && min_prio >= OSD_POOL_PRIORITY_MIN) {
    dout(20) << __func__ << " nothing to fix" << dendl;
    return;
  }
  // Current pool priorities exceeds new maximum
  for (const auto &i : osdmap.get_pools()) {
    const auto pool_id = i.first;
    pg_pool_t pool = i.second;

    int64_t prio = 0;
    pool.opts.get(key, &prio);
    int64_t n;

    if (prio > 0 && max_prio > OSD_POOL_PRIORITY_MAX) { // Likely scenario
      // Scaled priority range 0 to OSD_POOL_PRIORITY_MAX
      n = (float)prio / max_prio * OSD_POOL_PRIORITY_MAX;
    } else if (prio < 0 && min_prio < OSD_POOL_PRIORITY_MIN) {
      // Scaled  priority range OSD_POOL_PRIORITY_MIN to 0
      n = (float)prio / min_prio * OSD_POOL_PRIORITY_MIN;
    } else {
      continue;
    }
    if (n == 0) {
      pool.opts.unset(key);
    } else {
      pool.opts.set(key, static_cast<int64_t>(n));
    }
    dout(10) << __func__ << " pool " << pool_id
	     << " recovery_priority adjusted "
	     << prio << " to " << n << dendl;
    pool.last_change = pending_inc.epoch;
    pending_inc.new_pools[pool_id] = pool;
  }
}