summaryrefslogtreecommitdiffstats
path: root/xlators/cluster/afr/src/afr-common.c
blob: ecad217d0c40ac27392d4873ae93e5244b972e94 (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
/*
  Copyright (c) 2008-2012 Red Hat, Inc. <http://www.redhat.com>
  This file is part of GlusterFS.

  This file is licensed to you under your choice of the GNU Lesser
  General Public License, version 3 or any later version (LGPLv3 or
  later), or the GNU General Public License, version 2 (GPLv2), in all
  cases as published by the Free Software Foundation.
*/

#include <libgen.h>
#include <unistd.h>
#include <fnmatch.h>
#include <sys/time.h>
#include <stdlib.h>
#include <signal.h>

#include <glusterfs/glusterfs.h>
#include "afr.h"
#include <glusterfs/dict.h>
#include <glusterfs/xlator.h>
#include <glusterfs/hashfn.h>
#include <glusterfs/logging.h>
#include <glusterfs/list.h>
#include <glusterfs/call-stub.h>
#include <glusterfs/defaults.h>
#include <glusterfs/common-utils.h>
#include <glusterfs/compat-errno.h>
#include <glusterfs/compat.h>
#include <glusterfs/byte-order.h>
#include <glusterfs/statedump.h>
#include <glusterfs/events.h>
#include <glusterfs/upcall-utils.h>

#include "afr-inode-read.h"
#include "afr-inode-write.h"
#include "afr-dir-read.h"
#include "afr-dir-write.h"
#include "afr-transaction.h"
#include "afr-self-heal.h"
#include "afr-self-heald.h"
#include "afr-messages.h"

int32_t
afr_quorum_errno(afr_private_t *priv)
{
    return ENOTCONN;
}

int
afr_fav_child_reset_sink_xattrs(void *opaque);

int
afr_fav_child_reset_sink_xattrs_cbk(int ret, call_frame_t *frame, void *opaque);

static void
afr_discover_done(call_frame_t *frame, xlator_t *this);

gf_boolean_t
afr_is_consistent_io_possible(afr_local_t *local, afr_private_t *priv,
                              int32_t *op_errno)
{
    if (priv->consistent_io && local->call_count != priv->child_count) {
        gf_msg(THIS->name, GF_LOG_INFO, 0, AFR_MSG_SUBVOLS_DOWN,
               "All subvolumes are not up");
        if (op_errno)
            *op_errno = ENOTCONN;
        return _gf_false;
    }
    return _gf_true;
}

call_frame_t *
afr_copy_frame(call_frame_t *base)
{
    afr_local_t *local = NULL;
    call_frame_t *frame = NULL;
    int op_errno = 0;

    frame = copy_frame(base);
    if (!frame)
        return NULL;
    local = AFR_FRAME_INIT(frame, op_errno);
    if (!local) {
        AFR_STACK_DESTROY(frame);
        return NULL;
    }

    return frame;
}

/* Check if an entry or inode could be undergoing a transaction. */
gf_boolean_t
afr_is_possibly_under_txn(afr_transaction_type type, afr_local_t *local,
                          xlator_t *this)
{
    int i = 0;
    int tmp = 0;
    afr_private_t *priv = NULL;
    GF_UNUSED char *key = NULL;
    int keylen = 0;

    priv = this->private;

    if (type == AFR_ENTRY_TRANSACTION) {
        key = GLUSTERFS_PARENT_ENTRYLK;
        keylen = SLEN(GLUSTERFS_PARENT_ENTRYLK);
    } else if (type == AFR_DATA_TRANSACTION) {
        /*FIXME: Use GLUSTERFS_INODELK_DOM_COUNT etc. once
         * pl_inodelk_xattr_fill supports separate keys for different
         * domains.*/
        key = GLUSTERFS_INODELK_COUNT;
        keylen = SLEN(GLUSTERFS_INODELK_COUNT);
    }
    for (i = 0; i < priv->child_count; i++) {
        if (!local->replies[i].xdata)
            continue;
        if (dict_get_int32n(local->replies[i].xdata, key, keylen, &tmp) == 0)
            if (tmp)
                return _gf_true;
    }

    return _gf_false;
}

static void
afr_inode_ctx_destroy(afr_inode_ctx_t *ctx)
{
    int i = 0;

    if (!ctx)
        return;

    for (i = 0; i < AFR_NUM_CHANGE_LOGS; i++) {
        GF_FREE(ctx->pre_op_done[i]);
    }

    GF_FREE(ctx);
}

int
__afr_inode_ctx_get(xlator_t *this, inode_t *inode, afr_inode_ctx_t **ctx)
{
    uint64_t ctx_int = 0;
    int ret = -1;
    int i = -1;
    int num_locks = -1;
    afr_inode_ctx_t *ictx = NULL;
    afr_lock_t *lock = NULL;
    afr_private_t *priv = this->private;

    ret = __inode_ctx_get(inode, this, &ctx_int);
    if (ret == 0) {
        *ctx = (afr_inode_ctx_t *)(uintptr_t)ctx_int;
        return 0;
    }

    ictx = GF_CALLOC(1, sizeof(afr_inode_ctx_t), gf_afr_mt_inode_ctx_t);
    if (!ictx)
        goto out;

    for (i = 0; i < AFR_NUM_CHANGE_LOGS; i++) {
        ictx->pre_op_done[i] = GF_CALLOC(sizeof *ictx->pre_op_done[i],
                                         priv->child_count, gf_afr_mt_int32_t);
        if (!ictx->pre_op_done[i]) {
            ret = -ENOMEM;
            goto out;
        }
    }

    num_locks = sizeof(ictx->lock) / sizeof(afr_lock_t);
    for (i = 0; i < num_locks; i++) {
        lock = &ictx->lock[i];
        INIT_LIST_HEAD(&lock->post_op);
        INIT_LIST_HEAD(&lock->frozen);
        INIT_LIST_HEAD(&lock->waiting);
        INIT_LIST_HEAD(&lock->owners);
    }

    ctx_int = (uint64_t)(uintptr_t)ictx;
    ret = __inode_ctx_set(inode, this, &ctx_int);
    if (ret) {
        goto out;
    }

    ictx->spb_choice = -1;
    ictx->read_subvol = 0;
    ictx->write_subvol = 0;
    ictx->lock_count = 0;
    ret = 0;
    *ctx = ictx;
out:
    if (ret) {
        afr_inode_ctx_destroy(ictx);
    }
    return ret;
}

/*
 * INODE CTX 64-bit VALUE FORMAT FOR SMALL (<= 16) SUBVOL COUNTS:
 *
 * |<----------   64bit   ------------>|
 *  63           32 31    16 15       0
 * |   EVENT_GEN   |  DATA  | METADATA |
 *
 *
 *  METADATA (bit-0 .. bit-15): bitmap representing subvolumes from which
 *                              metadata can be attempted to be read.
 *
 *                              bit-0 => priv->subvolumes[0]
 *                              bit-1 => priv->subvolumes[1]
 *                              ... etc. till bit-15
 *
 *  DATA (bit-16 .. bit-31): bitmap representing subvolumes from which data
 *                           can be attempted to be read.
 *
 *                           bit-16 => priv->subvolumes[0]
 *                           bit-17 => priv->subvolumes[1]
 *                           ... etc. till bit-31
 *
 *  EVENT_GEN (bit-32 .. bit-63): event generation (i.e priv->event_generation)
 *                                when DATA and METADATA was last updated.
 *
 *                                If EVENT_GEN is < priv->event_generation,
 *                                or is 0, it means afr_inode_refresh() needs
 *                                to be called to recalculate the bitmaps.
 */

int
__afr_set_in_flight_sb_status(xlator_t *this, afr_local_t *local,
                              inode_t *inode)
{
    int i = 0;
    int txn_type = 0;
    int count = 0;
    int index = -1;
    uint16_t datamap_old = 0;
    uint16_t metadatamap_old = 0;
    uint16_t datamap = 0;
    uint16_t metadatamap = 0;
    uint16_t tmp_map = 0;
    uint16_t mask = 0;
    uint32_t event = 0;
    uint64_t val = 0;
    afr_private_t *priv = NULL;

    priv = this->private;
    txn_type = local->transaction.type;

    if (txn_type == AFR_DATA_TRANSACTION)
        val = local->inode_ctx->write_subvol;
    else
        val = local->inode_ctx->read_subvol;

    metadatamap_old = metadatamap = (val & 0x000000000000ffff);
    datamap_old = datamap = (val & 0x00000000ffff0000) >> 16;
    event = (val & 0xffffffff00000000) >> 32;

    if (txn_type == AFR_DATA_TRANSACTION)
        tmp_map = datamap;
    else if (txn_type == AFR_METADATA_TRANSACTION)
        tmp_map = metadatamap;

    count = gf_bits_count(tmp_map);

    for (i = 0; i < priv->child_count; i++) {
        if (!local->transaction.failed_subvols[i])
            continue;

        mask = 1 << i;
        if (txn_type == AFR_METADATA_TRANSACTION)
            metadatamap &= ~mask;
        else if (txn_type == AFR_DATA_TRANSACTION)
            datamap &= ~mask;
    }

    switch (txn_type) {
        case AFR_METADATA_TRANSACTION:
            if ((metadatamap_old != 0) && (metadatamap == 0) && (count == 1)) {
                index = gf_bits_index(tmp_map);
                local->transaction.in_flight_sb_errno = local->replies[index]
                                                            .op_errno;
                local->transaction.in_flight_sb = _gf_true;
                metadatamap |= (1 << index);
            }
            if (metadatamap_old != metadatamap) {
                event = 0;
            }
            break;

        case AFR_DATA_TRANSACTION:
            if ((datamap_old != 0) && (datamap == 0) && (count == 1)) {
                index = gf_bits_index(tmp_map);
                local->transaction.in_flight_sb_errno = local->replies[index]
                                                            .op_errno;
                local->transaction.in_flight_sb = _gf_true;
                datamap |= (1 << index);
            }
            if (datamap_old != datamap)
                event = 0;
            break;

        default:
            break;
    }

    val = ((uint64_t)metadatamap) | (((uint64_t)datamap) << 16) |
          (((uint64_t)event) << 32);

    if (txn_type == AFR_DATA_TRANSACTION)
        local->inode_ctx->write_subvol = val;
    local->inode_ctx->read_subvol = val;

    return 0;
}

gf_boolean_t
afr_is_symmetric_error(call_frame_t *frame, xlator_t *this)
{
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;
    int op_errno = 0;
    int i_errno = 0;
    gf_boolean_t matching_errors = _gf_true;
    int i = 0;

    priv = this->private;
    local = frame->local;

    for (i = 0; i < priv->child_count; i++) {
        if (!local->replies[i].valid)
            continue;
        if (local->replies[i].op_ret != -1) {
            /* Operation succeeded on at least one subvol,
               so it is not a failed-everywhere situation.
            */
            matching_errors = _gf_false;
            break;
        }
        i_errno = local->replies[i].op_errno;

        if (i_errno == ENOTCONN) {
            /* ENOTCONN is not a symmetric error. We do not
               know if the operation was performed on the
               backend or not.
            */
            matching_errors = _gf_false;
            break;
        }

        if (!op_errno) {
            op_errno = i_errno;
        } else if (op_errno != i_errno) {
            /* Mismatching op_errno's */
            matching_errors = _gf_false;
            break;
        }
    }

    return matching_errors;
}

int
afr_set_in_flight_sb_status(xlator_t *this, call_frame_t *frame, inode_t *inode)
{
    int ret = -1;
    afr_private_t *priv = NULL;
    afr_local_t *local = NULL;

    priv = this->private;
    local = frame->local;

    /* If this transaction saw no failures, then exit. */
    if (AFR_COUNT(local->transaction.failed_subvols, priv->child_count) == 0)
        return 0;

    if (afr_is_symmetric_error(frame, this))
        return 0;

    LOCK(&inode->lock);
    {
        ret = __afr_set_in_flight_sb_status(this, local, inode);
    }
    UNLOCK(&inode->lock);

    return ret;
}

int
__afr_inode_read_subvol_get_small(inode_t *inode, xlator_t *this,
                                  unsigned char *data, unsigned char *metadata,
                                  int *event_p)
{
    afr_private_t *priv = NULL;
    int ret = -1;
    uint16_t datamap = 0;
    uint16_t metadatamap = 0;
    uint32_t event = 0;
    uint64_t val = 0;
    int i = 0;
    afr_inode_ctx_t *ctx = NULL;

    priv = this->private;

    ret = __afr_inode_ctx_get(this, inode, &ctx);
    if (ret < 0)
        return ret;

    val = ctx->read_subvol;

    metadatamap = (val & 0x000000000000ffff);
    datamap = (val & 0x00000000ffff0000) >> 16;
    event = (val & 0xffffffff00000000) >> 32;

    for (i = 0; i < priv->child_count; i++) {
        if (metadata)
            metadata[i] = (metadatamap >> i) & 1;
        if (data)
            data[i] = (datamap >> i) & 1;
    }

    if (event_p)
        *event_p = event;
    return ret;
}

int
__afr_inode_read_subvol_set_small(inode_t *inode, xlator_t *this,
                                  unsigned char *data, unsigned char *metadata,
                                  int event)
{
    afr_private_t *priv = NULL;
    uint16_t datamap = 0;
    uint16_t metadatamap = 0;
    uint64_t val = 0;
    int i = 0;
    int ret = -1;
    afr_inode_ctx_t *ctx = NULL;

    priv = this->private;

    ret = __afr_inode_ctx_get(this, inode, &ctx);
    if (ret)
        goto out;

    for (i = 0; i < priv->child_count; i++) {
        if (data[i])
            datamap |= (1 << i);
        if (metadata[i])
            metadatamap |= (1 << i);
    }

    val = ((uint64_t)metadatamap) | (((uint64_t)datamap) << 16) |
          (((uint64_t)event) << 32);

    ctx->read_subvol = val;

    ret = 0;
out:
    return ret;
}

int
__afr_inode_event_gen_reset_small(inode_t *inode, xlator_t *this)
{
    int ret = -1;
    uint16_t datamap = 0;
    uint16_t metadatamap = 0;
    uint32_t event = 0;
    uint64_t val = 0;
    afr_inode_ctx_t *ctx = NULL;

    ret = __afr_inode_ctx_get(this, inode, &ctx);
    if (ret)
        return ret;

    val = ctx->read_subvol;

    metadatamap = (val & 0x000000000000ffff) >> 0;
    datamap = (val & 0x00000000ffff0000) >> 16;
    event = 0;

    val = ((uint64_t)metadatamap) | (((uint64_t)datamap) << 16) |
          (((uint64_t)event) << 32);

    ctx->read_subvol = val;

    return ret;
}

int
__afr_inode_read_subvol_get(inode_t *inode, xlator_t *this, unsigned char *data,
                            unsigned char *metadata, int *event_p)
{
    afr_private_t *priv = NULL;
    int ret = -1;

    priv = this->private;

    if (priv->child_count <= 16)
        ret = __afr_inode_read_subvol_get_small(inode, this, data, metadata,
                                                event_p);
    else
        /* TBD: allocate structure with array and read from it */
        ret = -1;

    return ret;
}

int
__afr_inode_split_brain_choice_get(inode_t *inode, xlator_t *this,
                                   int *spb_choice)
{
    afr_inode_ctx_t *ctx = NULL;
    int ret = -1;

    ret = __afr_inode_ctx_get(this, inode, &ctx);
    if (ret < 0)
        return ret;

    *spb_choice = ctx->spb_choice;
    return 0;
}

int
__afr_inode_read_subvol_set(inode_t *inode, xlator_t *this, unsigned char *data,
                            unsigned char *metadata, int event)
{
    afr_private_t *priv = NULL;
    int ret = -1;

    priv = this->private;

    if (priv->child_count <= 16)
        ret = __afr_inode_read_subvol_set_small(inode, this, data, metadata,
                                                event);
    else
        ret = -1;

    return ret;
}

int
__afr_inode_split_brain_choice_set(inode_t *inode, xlator_t *this,
                                   int spb_choice)
{
    afr_inode_ctx_t *ctx = NULL;
    int ret = -1;

    ret = __afr_inode_ctx_get(this, inode, &ctx);
    if (ret)
        goto out;

    ctx->spb_choice = spb_choice;

    ret = 0;
out:
    return ret;
}

int
__afr_inode_event_gen_reset(inode_t *inode, xlator_t *this)
{
    afr_private_t *priv = NULL;
    int ret = -1;

    priv = this->private;

    if (priv->child_count <= 16)
        ret = __afr_inode_event_gen_reset_small(inode, this);
    else
        ret = -1;

    return ret;
}

int
afr_inode_read_subvol_get(inode_t *inode, xlator_t *this, unsigned char *data,
                          unsigned char *metadata, int *event_p)
{
    int ret = -1;

    GF_VALIDATE_OR_GOTO(this->name, inode, out);

    LOCK(&inode->lock);
    {
        ret = __afr_inode_read_subvol_get(inode, this, data, metadata, event_p);
    }
    UNLOCK(&inode->lock);
out:
    return ret;
}

int
afr_inode_get_readable(call_frame_t *frame, inode_t *inode, xlator_t *this,
                       unsigned char *readable, int *event_p, int type)
{
    afr_private_t *priv = this->private;
    afr_local_t *local = frame->local;
    unsigned char *data = alloca0(priv->child_count);
    unsigned char *metadata = alloca0(priv->child_count);
    int data_count = 0;
    int metadata_count = 0;
    int event_generation = 0;
    int ret = 0;

    ret = afr_inode_read_subvol_get(inode, this, data, metadata,
                                    &event_generation);
    if (ret == -1)
        return -EIO;

    data_count = AFR_COUNT(data, priv->child_count);
    metadata_count = AFR_COUNT(metadata, priv->child_count);

    if (inode->ia_type == IA_IFDIR) {
        /* For directories, allow even if it is in data split-brain. */
        if (type == AFR_METADATA_TRANSACTION || local->op == GF_FOP_STAT ||
            local->op == GF_FOP_FSTAT) {
            if (!metadata_count)
                return -EIO;
        }
    } else {
        /* For files, abort in case of data/metadata split-brain. */
        if (!data_count || !metadata_count) {
            return -EIO;
        }
    }

    if (type == AFR_METADATA_TRANSACTION && readable)
        memcpy(readable, metadata, priv->child_count * sizeof *metadata);
    if (type == AFR_DATA_TRANSACTION && readable) {
        if (!data_count)
            memcpy(readable, local->child_up,
                   priv->child_count * sizeof *readable);
        else
            memcpy(readable, data, priv->child_count * sizeof *data);
    }
    if (event_p)
        *event_p = event_generation;
    return 0;
}

int
afr_inode_split_brain_choice_get(inode_t *inode, xlator_t *this,
                                 int *spb_choice)
{
    int ret = -1;

    GF_VALIDATE_OR_GOTO(this->name, inode, out);

    LOCK(&inode->lock);
    {
        ret = __afr_inode_split_brain_choice_get(inode, this, spb_choice);
    }
    UNLOCK(&inode->lock);
out:
    return ret;
}

int
afr_inode_read_subvol_set(inode_t *inode, xlator_t *this, unsigned char *data,
                          unsigned char *metadata, int event)
{
    int ret = -1;

    GF_VALIDATE_OR_GOTO(this->name, inode, out);

    LOCK(&inode->lock);
    {
        ret = __afr_inode_read_subvol_set(inode, this, data, metadata, event);
    }
    UNLOCK(&inode->lock);
out:
    return ret;
}

int
afr_inode_split_brain_choice_set(inode_t *inode, xlator_t *this, int spb_choice)
{
    int ret = -1;

    GF_VALIDATE_OR_GOTO(this->name, inode, out);

    LOCK(&inode->lock);
    {
        ret = __afr_inode_split_brain_choice_set(inode, this, spb_choice);
    }
    UNLOCK(&inode->lock);
out:
    return ret;
}

/* The caller of this should perform afr_inode_refresh, if this function
 * returns _gf_true
 */
gf_boolean_t
afr_is_inode_refresh_reqd(inode_t *inode, xlator_t *this, int event_gen1,
                          int event_gen2)
{
    gf_boolean_t need_refresh = _gf_false;
    afr_inode_ctx_t *ctx = NULL;
    int ret = -1;

    GF_VALIDATE_OR_GOTO(this->name, inode, out);

    LOCK(&inode->lock);
    {
        ret = __afr_inode_ctx_get(this, inode, &ctx);
        if (ret)
            goto unlock;

        need_refresh = ctx->need_refresh;
        /* Hoping that the caller will do inode_refresh followed by
         * this, hence setting the need_refresh to false */
        ctx->need_refresh = _gf_false;
    }
unlock:
    UNLOCK(&inode->lock);

    if (event_gen1 != event_gen2)
        need_refresh = _gf_true;
out:
    return need_refresh;
}

static int
afr_inode_need_refresh_set(inode_t *inode, xlator_t *this)
{
    int ret = -1;
    afr_inode_ctx_t *ctx = NULL;

    GF_VALIDATE_OR_GOTO(this->name, inode, out);

    LOCK(&inode->lock);
    {
        ret = __afr_inode_ctx_get(this, inode, &ctx);
        if (ret)
            goto unlock;

        ctx->need_refresh = _gf_true;
    }
unlock:
    UNLOCK(&inode->lock);
out:
    return ret;
}

int
afr_inode_event_gen_reset(inode_t *inode, xlator_t *this)
{
    int ret = -1;

    GF_VALIDATE_OR_GOTO(this->name, inode, out);

    LOCK(&inode->lock);
    {
        ret = __afr_inode_event_gen_reset(inode, this);
    }
    UNLOCK(&inode->lock);
out:
    return ret;
}

int
afr_spb_choice_timeout_cancel(xlator_t *this, inode_t *inode)
{
    afr_inode_ctx_t *ctx = NULL;
    int ret = -1;

    if (!inode)
        return ret;

    LOCK(&inode->lock);
    {
        ret = __afr_inode_ctx_get(this, inode, &ctx);
        if (ret < 0 || !ctx) {
            UNLOCK(&inode->lock);
            gf_msg(this->name, GF_LOG_WARNING, 0,
                   AFR_MSG_SPLIT_BRAIN_CHOICE_ERROR,
                   "Failed to cancel split-brain choice timer.");
            goto out;
        }
        ctx->spb_choice = -1;
        if (ctx->timer) {
            gf_timer_call_cancel(this->ctx, ctx->timer);
            ctx->timer = NULL;
        }
        ret = 0;
    }
    UNLOCK(&inode->lock);
out:
    return ret;
}

void
afr_set_split_brain_choice_cbk(void *data)
{
    inode_t *inode = data;
    xlator_t *this = THIS;

    afr_spb_choice_timeout_cancel(this, inode);
    inode_invalidate(inode);
    inode_unref(inode);
    return;
}

int
afr_set_split_brain_choice(int ret, call_frame_t *frame, void *opaque)
{
    int op_errno = ENOMEM;
    afr_private_t *priv = NULL;
    afr_inode_ctx_t *ctx = NULL;
    inode_t *inode = NULL;
    loc_t *loc = NULL;
    xlator_t *this = NULL;
    afr_spbc_timeout_t *data = opaque;
    struct timespec delta = {
        0,
    };
    gf_boolean_t timer_set = _gf_false;
    gf_boolean_t timer_cancelled = _gf_false;
    gf_boolean_t timer_reset = _gf_false;
    gf_boolean_t need_invalidate = _gf_true;
    int old_spb_choice = -1;

    frame = data->frame;
    loc = data->loc;
    this = frame->this;
    priv = this->private;

    if (ret) {
        op_errno = -ret;
        ret = -1;
        goto out;
    }

    delta.tv_sec = priv->spb_choice_timeout;
    delta.tv_nsec = 0;

    if (!loc->inode) {
        ret = -1;
        op_errno = EINVAL;
        goto out;
    }

    if (!(data->d_spb || data->m_spb)) {
        gf_msg(this->name, GF_LOG_WARNING, 0, AFR_MSG_SPLIT_BRAIN_CHOICE_ERROR,
               "Cannot set "
               "replica.split-brain-choice on %s. File is"
               " not in data/metadata split-brain.",
               uuid_utoa(loc->gfid));
        ret = -1;
        op_errno = EINVAL;
        goto out;
    }

    /*
     * we're ref'ing the inode before LOCK like it is done elsewhere in the
     * code. If we ref after LOCK, coverity complains of possible deadlocks.
     */
    inode = inode_ref(loc->inode);

    LOCK(&inode->lock);
    {
        ret = __afr_inode_ctx_get(this, inode, &ctx);
        if (ret) {
            UNLOCK(&inode->lock);
            gf_msg(this->name, GF_LOG_ERROR, 0,
                   AFR_MSG_SPLIT_BRAIN_CHOICE_ERROR,
                   "Failed to get inode_ctx for %s", loc->name);
            goto post_unlock;
        }

        old_spb_choice = ctx->spb_choice;
        ctx->spb_choice = data->spb_child_index;

        /* Possible changes in spb-choice :
         *         valid to -1    : cancel timer and unref
         *         valid to valid : cancel timer and inject new one
         *         -1    to -1    : unref and do not do anything
         *         -1 to valid    : inject timer
         */

        /* ctx->timer is NULL iff previous value of
         * ctx->spb_choice is -1
         */
        if (ctx->timer) {
            if (ctx->spb_choice == -1) {
                if (!gf_timer_call_cancel(this->ctx, ctx->timer)) {
                    ctx->timer = NULL;
                    timer_cancelled = _gf_true;
                }
                /* If timer cancel failed here it means that the
                 *  previous cbk will be executed which will set
                 *  spb_choice to -1. So we can consider the
                 *  'valid to -1' case to be a success
                 *  (i.e. ret = 0) and goto unlock.
                 */
                goto unlock;
            }
            goto reset_timer;
        } else {
            if (ctx->spb_choice == -1)
                goto unlock;
            goto set_timer;
        }

    reset_timer:
        ret = gf_timer_call_cancel(this->ctx, ctx->timer);
        if (ret != 0) {
            /* We need to bail out now instead of launching a new
             * timer. Otherwise the cbk of the previous timer event
             * will cancel the new ctx->timer.
             */
            ctx->spb_choice = old_spb_choice;
            ret = -1;
            op_errno = EAGAIN;
            goto unlock;
        }
        ctx->timer = NULL;
        timer_reset = _gf_true;

    set_timer:
        ctx->timer = gf_timer_call_after(this->ctx, delta,
                                         afr_set_split_brain_choice_cbk, inode);
        if (!ctx->timer) {
            ctx->spb_choice = old_spb_choice;
            ret = -1;
            op_errno = ENOMEM;
        }
        if (!timer_reset && ctx->timer)
            timer_set = _gf_true;
        if (timer_reset && !ctx->timer)
            timer_cancelled = _gf_true;
        need_invalidate = _gf_false;
    }
unlock:
    UNLOCK(&inode->lock);
post_unlock:
    if (!timer_set)
        inode_unref(inode);
    if (timer_cancelled)
        inode_unref(inode);
    /*
     * We need to invalidate the inode to prevent the kernel from serving
     * reads from an older cached value despite a change in spb_choice to
     * a new value.
     */
    if (need_invalidate)
        inode_invalidate(inode);
out:
    GF_FREE(data);
    AFR_STACK_UNWIND(setxattr, frame, ret, op_errno, NULL);
    return 0;
}

int
afr_accused_fill(xlator_t *this, dict_t *xdata, unsigned char *accused,
                 afr_transaction_type type)
{
    afr_private_t *priv = NULL;
    int i = 0;
    int idx = afr_index_for_transaction_type(type);
    void *pending_raw = NULL;
    int pending[3];
    int ret = 0;

    priv = this->private;

    for (i = 0; i < priv->child_count; i++) {
        ret = dict_get_ptr(xdata, priv->pending_key[i], &pending_raw);
        if (ret) /* no pending flags */
            continue;
        memcpy(pending, pending_raw, sizeof(pending));

        if (ntoh32(pending[idx]))
            accused[i] = 1;
    }

    return 0;
}

int
afr_accuse_smallfiles(xlator_t *this, struct afr_reply *replies,
                      unsigned char *data_accused)
{
    int i = 0;
    afr_private_t *priv = NULL;
    uint64_t maxsize = 0;

    priv = this->private;

    for (i = 0; i < priv->child_count; i++) {
        if (replies[i].valid && replies[i].xdata &&
            dict_get_sizen(replies[i].xdata, GLUSTERFS_BAD_INODE))
            continue;
        if (data_accused[i])
            continue;
        if (replies[i].poststat.ia_size > maxsize)
            maxsize = replies[i].poststat.ia_size;
    }

    for (i = 0; i < priv->child_count; i++) {
        if (data_accused[i])
            continue;
        if (AFR_IS_ARBITER_BRICK(priv, i))
            continue;
        if (replies[i].poststat.ia_size < maxsize)
            data_accused[i] = 1;
    }

    return 0;
}

int
afr_readables_fill(call_frame_t *frame, xlator_t *this, inode_t *inode,
                   unsigned char *data_accused, unsigned char *metadata_accused,
                   unsigned char *data_readable,
                   unsigned char *metadata_readable, struct afr_reply *replies)
{
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;
    dict_t *xdata = NULL;
    int i = 0;
    int ret = 0;
    ia_type_t ia_type = IA_INVAL;

    local = frame->local;
    priv = this->private;

    for (i = 0; i < priv->child_count; i++) {
        data_readable[i] = 1;
        metadata_readable[i] = 1;
    }
    if (AFR_IS_ARBITER_BRICK(priv, ARBITER_BRICK_INDEX)) {
        data_readable[ARBITER_BRICK_INDEX] = 0;
        metadata_readable[ARBITER_BRICK_INDEX] = 0;
    }

    for (i = 0; i < priv->child_count; i++) {
        if (replies) { /* Lookup */
            if (!replies[i].valid || replies[i].op_ret == -1 ||
                (replies[i].xdata &&
                 dict_get_sizen(replies[i].xdata, GLUSTERFS_BAD_INODE))) {
                data_readable[i] = 0;
                metadata_readable[i] = 0;
                continue;
            }

            xdata = replies[i].xdata;
            ia_type = replies[i].poststat.ia_type;
        } else { /* pre-op xattrop */
            xdata = local->transaction.changelog_xdata[i];
            ia_type = inode->ia_type;
        }

        afr_accused_fill(this, xdata, data_accused,
                         (ia_type == IA_IFDIR) ? AFR_ENTRY_TRANSACTION
                                               : AFR_DATA_TRANSACTION);

        afr_accused_fill(this, xdata, metadata_accused,
                         AFR_METADATA_TRANSACTION);
    }

    if (replies && ia_type != IA_INVAL && ia_type != IA_IFDIR &&
        /* We want to accuse small files only when we know for
         * sure that there is no IO happening. Otherwise, the
         * ia_sizes obtained in post-refresh replies may
         * mismatch due to a race between inode-refresh and
         * ongoing writes, causing spurious heal launches*/
        !afr_is_possibly_under_txn(AFR_DATA_TRANSACTION, local, this)) {
        afr_accuse_smallfiles(this, replies, data_accused);
    }

    for (i = 0; i < priv->child_count; i++) {
        if (data_accused[i]) {
            data_readable[i] = 0;
            ret = 1;
        }
        if (metadata_accused[i]) {
            metadata_readable[i] = 0;
            ret = 1;
        }
    }
    return ret;
}

int
afr_replies_interpret(call_frame_t *frame, xlator_t *this, inode_t *inode,
                      gf_boolean_t *start_heal)
{
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;
    struct afr_reply *replies = NULL;
    int event_generation = 0;
    int i = 0;
    unsigned char *data_accused = NULL;
    unsigned char *metadata_accused = NULL;
    unsigned char *data_readable = NULL;
    unsigned char *metadata_readable = NULL;
    int ret = 0;

    local = frame->local;
    priv = this->private;
    replies = local->replies;
    event_generation = local->event_generation;

    data_accused = alloca0(priv->child_count);
    data_readable = alloca0(priv->child_count);
    metadata_accused = alloca0(priv->child_count);
    metadata_readable = alloca0(priv->child_count);

    ret = afr_readables_fill(frame, this, inode, data_accused, metadata_accused,
                             data_readable, metadata_readable, replies);

    for (i = 0; i < priv->child_count; i++) {
        if (start_heal && priv->child_up[i] &&
            (data_accused[i] || metadata_accused[i])) {
            *start_heal = _gf_true;
            break;
        }
    }
    afr_inode_read_subvol_set(inode, this, data_readable, metadata_readable,
                              event_generation);
    return ret;
}

int
afr_refresh_selfheal_done(int ret, call_frame_t *heal, void *opaque)
{
    if (heal)
        AFR_STACK_DESTROY(heal);
    return 0;
}

int
afr_inode_refresh_err(call_frame_t *frame, xlator_t *this)
{
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;
    int i = 0;
    int err = 0;

    local = frame->local;
    priv = this->private;

    for (i = 0; i < priv->child_count; i++) {
        if (local->replies[i].valid && !local->replies[i].op_ret) {
            err = 0;
            goto ret;
        }
    }

    err = afr_final_errno(local, priv);
ret:
    return err;
}

gf_boolean_t
afr_selfheal_enabled(const xlator_t *this)
{
    const afr_private_t *priv = this->private;

    return priv->data_self_heal || priv->metadata_self_heal ||
           priv->entry_self_heal;
}

int
afr_txn_refresh_done(call_frame_t *frame, xlator_t *this, int err)
{
    call_frame_t *heal_frame = NULL;
    afr_local_t *heal_local = NULL;
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;
    inode_t *inode = NULL;
    int event_generation = 0;
    int read_subvol = -1;
    int op_errno = ENOMEM;
    int ret = 0;

    local = frame->local;
    inode = local->inode;
    priv = this->private;

    if (err)
        goto refresh_done;

    if (local->op == GF_FOP_LOOKUP)
        goto refresh_done;

    ret = afr_inode_get_readable(frame, inode, this, local->readable,
                                 &event_generation, local->transaction.type);

    if (ret == -EIO || (local->is_read_txn && !event_generation)) {
        /* No readable subvolume even after refresh ==> splitbrain.*/
        if (!priv->fav_child_policy) {
            err = EIO;
            goto refresh_done;
        }
        read_subvol = afr_sh_get_fav_by_policy(this, local->replies, inode,
                                               NULL);
        if (read_subvol == -1) {
            err = EIO;
            goto refresh_done;
        }

        heal_frame = copy_frame(frame);
        if (!heal_frame) {
            err = EIO;
            goto refresh_done;
        }
        heal_frame->root->pid = GF_CLIENT_PID_SELF_HEALD;
        heal_local = AFR_FRAME_INIT(heal_frame, op_errno);
        if (!heal_local) {
            err = EIO;
            AFR_STACK_DESTROY(heal_frame);
            goto refresh_done;
        }
        heal_local->xdata_req = dict_new();
        if (!heal_local->xdata_req) {
            err = EIO;
            AFR_STACK_DESTROY(heal_frame);
            goto refresh_done;
        }
        heal_local->heal_frame = frame;
        ret = synctask_new(this->ctx->env, afr_fav_child_reset_sink_xattrs,
                           afr_fav_child_reset_sink_xattrs_cbk, heal_frame,
                           heal_frame);
        return 0;
    }

refresh_done:
    afr_local_replies_wipe(local, this->private);
    local->refreshfn(frame, this, err);

    return 0;
}

void
afr_fill_success_replies(afr_local_t *local, afr_private_t *priv,
                         unsigned char *replies)
{
    int i = 0;

    for (i = 0; i < priv->child_count; i++) {
        if (local->replies[i].valid && local->replies[i].op_ret == 0)
            replies[i] = 1;
    }
}

int
afr_inode_refresh_done(call_frame_t *frame, xlator_t *this, int error)
{
    call_frame_t *heal_frame = NULL;
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;
    gf_boolean_t start_heal = _gf_false;
    afr_local_t *heal_local = NULL;
    unsigned char *success_replies = NULL;
    int op_errno = ENOMEM;
    int ret = 0;

    if (error != 0) {
        goto refresh_done;
    }

    local = frame->local;
    priv = this->private;
    success_replies = alloca0(priv->child_count);
    afr_fill_success_replies(local, priv, success_replies);

    if (priv->thin_arbiter_count && local->is_read_txn &&
        AFR_COUNT(success_replies, priv->child_count) != priv->child_count) {
        /* We need to query the good bricks and/or thin-arbiter.*/
        if (success_replies[0]) {
            local->read_txn_query_child = AFR_CHILD_ZERO;
        } else if (success_replies[1]) {
            local->read_txn_query_child = AFR_CHILD_ONE;
        }
        error = EINVAL;
        goto refresh_done;
    }

    if (!afr_has_quorum(success_replies, this, frame)) {
        error = afr_final_errno(frame->local, this->private);
        if (!error)
            error = afr_quorum_errno(priv);
        goto refresh_done;
    }

    ret = afr_replies_interpret(frame, this, local->refreshinode, &start_heal);

    if (ret && afr_selfheal_enabled(this) && start_heal) {
        heal_frame = copy_frame(frame);
        if (!heal_frame)
            goto refresh_done;
        heal_frame->root->pid = GF_CLIENT_PID_SELF_HEALD;
        heal_local = AFR_FRAME_INIT(heal_frame, op_errno);
        if (!heal_local) {
            AFR_STACK_DESTROY(heal_frame);
            goto refresh_done;
        }
        heal_local->refreshinode = inode_ref(local->refreshinode);
        heal_local->heal_frame = heal_frame;
        if (!afr_throttled_selfheal(heal_frame, this)) {
            AFR_STACK_DESTROY(heal_frame);
            goto refresh_done;
        }
    }

refresh_done:
    afr_txn_refresh_done(frame, this, error);

    return 0;
}

void
afr_inode_refresh_subvol_cbk(call_frame_t *frame, void *cookie, xlator_t *this,
                             int op_ret, int op_errno, struct iatt *buf,
                             dict_t *xdata, struct iatt *par)
{
    afr_local_t *local = NULL;
    int call_child = (long)cookie;
    int8_t need_heal = 1;
    int call_count = 0;
    int ret = 0;

    local = frame->local;
    local->replies[call_child].valid = 1;
    local->replies[call_child].op_ret = op_ret;
    local->replies[call_child].op_errno = op_errno;
    if (op_ret != -1) {
        local->replies[call_child].poststat = *buf;
        if (par)
            local->replies[call_child].postparent = *par;
        if (xdata)
            local->replies[call_child].xdata = dict_ref(xdata);
    }
    if (xdata) {
        ret = dict_get_int8(xdata, "link-count", &need_heal);
        local->replies[call_child].need_heal = need_heal;
    } else {
        local->replies[call_child].need_heal = need_heal;
    }

    call_count = afr_frame_return(frame);
    if (call_count == 0) {
        afr_set_need_heal(this, local);
        ret = afr_inode_refresh_err(frame, this);
        afr_inode_refresh_done(frame, this, ret);
    }
}

int
afr_inode_refresh_subvol_with_lookup_cbk(call_frame_t *frame, void *cookie,
                                         xlator_t *this, int op_ret,
                                         int op_errno, inode_t *inode,
                                         struct iatt *buf, dict_t *xdata,
                                         struct iatt *par)
{
    afr_inode_refresh_subvol_cbk(frame, cookie, this, op_ret, op_errno, buf,
                                 xdata, par);
    return 0;
}

int
afr_inode_refresh_subvol_with_lookup(call_frame_t *frame, xlator_t *this, int i,
                                     inode_t *inode, uuid_t gfid, dict_t *xdata)
{
    loc_t loc = {
        0,
    };
    afr_private_t *priv = NULL;

    priv = this->private;

    loc.inode = inode;
    if (gf_uuid_is_null(inode->gfid) && gfid) {
        /* To handle setattr/setxattr on yet to be linked inode from
         * dht */
        gf_uuid_copy(loc.gfid, gfid);
    } else {
        gf_uuid_copy(loc.gfid, inode->gfid);
    }

    STACK_WIND_COOKIE(frame, afr_inode_refresh_subvol_with_lookup_cbk,
                      (void *)(long)i, priv->children[i],
                      priv->children[i]->fops->lookup, &loc, xdata);
    return 0;
}

int
afr_inode_refresh_subvol_with_fstat_cbk(call_frame_t *frame, void *cookie,
                                        xlator_t *this, int32_t op_ret,
                                        int32_t op_errno, struct iatt *buf,
                                        dict_t *xdata)
{
    afr_inode_refresh_subvol_cbk(frame, cookie, this, op_ret, op_errno, buf,
                                 xdata, NULL);
    return 0;
}

int
afr_inode_refresh_subvol_with_fstat(call_frame_t *frame, xlator_t *this, int i,
                                    dict_t *xdata)
{
    afr_private_t *priv = NULL;
    afr_local_t *local = NULL;

    priv = this->private;
    local = frame->local;

    STACK_WIND_COOKIE(frame, afr_inode_refresh_subvol_with_fstat_cbk,
                      (void *)(long)i, priv->children[i],
                      priv->children[i]->fops->fstat, local->fd, xdata);
    return 0;
}

int
afr_inode_refresh_do(call_frame_t *frame, xlator_t *this)
{
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;
    int call_count = 0;
    int i = 0;
    int ret = 0;
    dict_t *xdata = NULL;
    afr_fd_ctx_t *fd_ctx = NULL;
    unsigned char *wind_subvols = NULL;

    priv = this->private;
    local = frame->local;
    wind_subvols = alloca0(priv->child_count);

    afr_local_replies_wipe(local, priv);

    if (local->fd) {
        fd_ctx = afr_fd_ctx_get(local->fd, this);
        if (!fd_ctx) {
            afr_inode_refresh_done(frame, this, EINVAL);
            return 0;
        }
    }

    xdata = dict_new();
    if (!xdata) {
        afr_inode_refresh_done(frame, this, ENOMEM);
        return 0;
    }

    ret = afr_xattr_req_prepare(this, xdata);
    if (ret != 0) {
        dict_unref(xdata);
        afr_inode_refresh_done(frame, this, -ret);
        return 0;
    }

    ret = dict_set_sizen_str_sizen(xdata, "link-count", GF_XATTROP_INDEX_COUNT);
    if (ret) {
        gf_msg_debug(this->name, -ret, "Unable to set link-count in dict ");
    }

    ret = dict_set_str_sizen(xdata, GLUSTERFS_INODELK_DOM_COUNT, this->name);
    if (ret) {
        gf_msg_debug(this->name, -ret,
                     "Unable to set inodelk-dom-count in dict ");
    }

    if (local->fd) {
        for (i = 0; i < priv->child_count; i++) {
            if (local->child_up[i] && fd_ctx->opened_on[i] == AFR_FD_OPENED)
                wind_subvols[i] = 1;
        }
    } else {
        memcpy(wind_subvols, local->child_up,
               sizeof(*local->child_up) * priv->child_count);
    }

    local->call_count = AFR_COUNT(wind_subvols, priv->child_count);

    call_count = local->call_count;
    if (!call_count) {
        dict_unref(xdata);
        if (local->fd && AFR_COUNT(local->child_up, priv->child_count))
            afr_inode_refresh_done(frame, this, EBADFD);
        else
            afr_inode_refresh_done(frame, this, ENOTCONN);
        return 0;
    }
    for (i = 0; i < priv->child_count; i++) {
        if (!wind_subvols[i])
            continue;

        if (local->fd)
            afr_inode_refresh_subvol_with_fstat(frame, this, i, xdata);
        else
            afr_inode_refresh_subvol_with_lookup(
                frame, this, i, local->refreshinode, local->refreshgfid, xdata);

        if (!--call_count)
            break;
    }

    dict_unref(xdata);

    return 0;
}

int
afr_inode_refresh(call_frame_t *frame, xlator_t *this, inode_t *inode,
                  uuid_t gfid, afr_inode_refresh_cbk_t refreshfn)
{
    afr_local_t *local = NULL;

    local = frame->local;

    local->refreshfn = refreshfn;

    if (local->refreshinode) {
        inode_unref(local->refreshinode);
        local->refreshinode = NULL;
    }

    local->refreshinode = inode_ref(inode);

    if (gfid)
        gf_uuid_copy(local->refreshgfid, gfid);
    else
        gf_uuid_clear(local->refreshgfid);

    afr_inode_refresh_do(frame, this);

    return 0;
}

int
afr_xattr_req_prepare(xlator_t *this, dict_t *xattr_req)
{
    int i = 0;
    afr_private_t *priv = NULL;
    int ret = 0;

    priv = this->private;

    for (i = 0; i < priv->child_count; i++) {
        ret = dict_set_uint64(xattr_req, priv->pending_key[i],
                              AFR_NUM_CHANGE_LOGS * sizeof(int));
        if (ret < 0)
            gf_msg(this->name, GF_LOG_WARNING, -ret, AFR_MSG_DICT_SET_FAILED,
                   "Unable to set dict value for %s", priv->pending_key[i]);
        /* 3 = data+metadata+entry */
    }
    ret = dict_set_uint64(xattr_req, AFR_DIRTY,
                          AFR_NUM_CHANGE_LOGS * sizeof(int));
    if (ret) {
        gf_msg_debug(this->name, -ret,
                     "failed to set dirty "
                     "query flag");
    }

    ret = dict_set_int32_sizen(xattr_req, "list-xattr", 1);
    if (ret) {
        gf_msg_debug(this->name, -ret, "Unable to set list-xattr in dict ");
    }

    return ret;
}

int
afr_lookup_xattr_req_prepare(afr_local_t *local, xlator_t *this,
                             dict_t *xattr_req, loc_t *loc)
{
    int ret = -ENOMEM;

    if (!local->xattr_req)
        local->xattr_req = dict_new();

    if (!local->xattr_req)
        goto out;

    if (xattr_req && (xattr_req != local->xattr_req))
        dict_copy(xattr_req, local->xattr_req);

    ret = afr_xattr_req_prepare(this, local->xattr_req);

    ret = dict_set_uint64(local->xattr_req, GLUSTERFS_INODELK_COUNT, 0);
    if (ret < 0) {
        gf_msg(this->name, GF_LOG_WARNING, -ret, AFR_MSG_DICT_SET_FAILED,
               "%s: Unable to set dict value for %s", loc->path,
               GLUSTERFS_INODELK_COUNT);
    }
    ret = dict_set_uint64(local->xattr_req, GLUSTERFS_ENTRYLK_COUNT, 0);
    if (ret < 0) {
        gf_msg(this->name, GF_LOG_WARNING, -ret, AFR_MSG_DICT_SET_FAILED,
               "%s: Unable to set dict value for %s", loc->path,
               GLUSTERFS_ENTRYLK_COUNT);
    }

    ret = dict_set_uint32(local->xattr_req, GLUSTERFS_PARENT_ENTRYLK, 0);
    if (ret < 0) {
        gf_msg(this->name, GF_LOG_WARNING, -ret, AFR_MSG_DICT_SET_FAILED,
               "%s: Unable to set dict value for %s", loc->path,
               GLUSTERFS_PARENT_ENTRYLK);
    }

    ret = dict_set_sizen_str_sizen(local->xattr_req, "link-count",
                                   GF_XATTROP_INDEX_COUNT);
    if (ret) {
        gf_msg_debug(this->name, -ret, "Unable to set link-count in dict ");
    }

    ret = 0;
out:
    return ret;
}

int
afr_least_pending_reads_child(afr_private_t *priv)
{
    int i = 0;
    int child = 0;
    int64_t read_iter = -1;
    int64_t pending_read = -1;

    pending_read = GF_ATOMIC_GET(priv->pending_reads[0]);
    for (i = 1; i < priv->child_count; i++) {
        if (AFR_IS_ARBITER_BRICK(priv, i))
            continue;
        read_iter = GF_ATOMIC_GET(priv->pending_reads[i]);
        if (read_iter < pending_read) {
            pending_read = read_iter;
            child = i;
        }
    }

    return child;
}

int
afr_hash_child(afr_read_subvol_args_t *args, afr_private_t *priv)
{
    uuid_t gfid_copy = {
        0,
    };
    pid_t pid;
    int child = -1;

    switch (priv->hash_mode) {
        case 0:
            break;
        case 1:
            gf_uuid_copy(gfid_copy, args->gfid);
            child = SuperFastHash((char *)gfid_copy, sizeof(gfid_copy)) %
                    priv->child_count;
            break;
        case 2:
            if (args->ia_type != IA_IFDIR) {
                /*
                 * Why getpid?  Because it's one of the cheapest calls
                 * available - faster than gethostname etc. - and
                 * returns a constant-length value that's sure to be
                 * shorter than a UUID. It's still very unlikely to be
                 * the same across clients, so it still provides good
                 * mixing.  We're not trying for perfection here. All we
                 * need is a low probability that multiple clients
                 * won't converge on the same subvolume.
                 */
                pid = getpid();
                memcpy(gfid_copy, &pid, sizeof(pid));
            }
            child = SuperFastHash((char *)gfid_copy, sizeof(gfid_copy)) %
                    priv->child_count;
            break;
        case 3:
            child = afr_least_pending_reads_child(priv);
            break;
    }

    return child;
}

int
afr_read_subvol_select_by_policy(inode_t *inode, xlator_t *this,
                                 unsigned char *readable,
                                 afr_read_subvol_args_t *args)
{
    int i = 0;
    int read_subvol = -1;
    afr_private_t *priv = NULL;
    afr_read_subvol_args_t local_args = {
        0,
    };

    priv = this->private;

    /* first preference - explicitly specified or local subvolume */
    if (priv->read_child >= 0 && readable[priv->read_child])
        return priv->read_child;

    if (inode_is_linked(inode)) {
        gf_uuid_copy(local_args.gfid, inode->gfid);
        local_args.ia_type = inode->ia_type;
    } else if (args) {
        local_args = *args;
    }

    /* second preference - use hashed mode */
    read_subvol = afr_hash_child(&local_args, priv);
    if (read_subvol >= 0 && readable[read_subvol])
        return read_subvol;

    for (i = 0; i < priv->child_count; i++) {
        if (readable[i])
            return i;
    }

    /* no readable subvolumes, either split brain or all subvols down */

    return -1;
}

int
afr_inode_read_subvol_type_get(inode_t *inode, xlator_t *this,
                               unsigned char *readable, int *event_p, int type)
{
    int ret = -1;

    if (type == AFR_METADATA_TRANSACTION)
        ret = afr_inode_read_subvol_get(inode, this, 0, readable, event_p);
    else
        ret = afr_inode_read_subvol_get(inode, this, readable, 0, event_p);
    return ret;
}

void
afr_readables_intersect_get(inode_t *inode, xlator_t *this, int *event,
                            unsigned char *intersection)
{
    afr_private_t *priv = NULL;
    unsigned char *data_readable = NULL;
    unsigned char *metadata_readable = NULL;
    unsigned char *intersect = NULL;

    priv = this->private;
    data_readable = alloca0(priv->child_count);
    metadata_readable = alloca0(priv->child_count);
    intersect = alloca0(priv->child_count);

    afr_inode_read_subvol_get(inode, this, data_readable, metadata_readable,
                              event);

    AFR_INTERSECT(intersect, data_readable, metadata_readable,
                  priv->child_count);
    if (intersection)
        memcpy(intersection, intersect,
               sizeof(*intersection) * priv->child_count);
}

int
afr_read_subvol_get(inode_t *inode, xlator_t *this, int *subvol_p,
                    unsigned char *readables, int *event_p,
                    afr_transaction_type type, afr_read_subvol_args_t *args)
{
    afr_private_t *priv = NULL;
    unsigned char *readable = NULL;
    unsigned char *intersection = NULL;
    int subvol = -1;
    int event = 0;

    priv = this->private;

    readable = alloca0(priv->child_count);
    intersection = alloca0(priv->child_count);

    afr_inode_read_subvol_type_get(inode, this, readable, &event, type);

    afr_readables_intersect_get(inode, this, &event, intersection);

    if (AFR_COUNT(intersection, priv->child_count) > 0)
        subvol = afr_read_subvol_select_by_policy(inode, this, intersection,
                                                  args);
    else
        subvol = afr_read_subvol_select_by_policy(inode, this, readable, args);
    if (subvol_p)
        *subvol_p = subvol;
    if (event_p)
        *event_p = event;
    if (readables)
        memcpy(readables, readable, sizeof(*readables) * priv->child_count);
    return subvol;
}

void
afr_local_transaction_cleanup(afr_local_t *local, xlator_t *this)
{
    afr_private_t *priv = NULL;
    int i = 0;

    priv = this->private;

    afr_matrix_cleanup(local->pending, priv->child_count);

    GF_FREE(local->internal_lock.lower_locked_nodes);

    afr_lockees_cleanup(&local->internal_lock);

    GF_FREE(local->transaction.pre_op);

    GF_FREE(local->transaction.pre_op_sources);
    if (local->transaction.changelog_xdata) {
        for (i = 0; i < priv->child_count; i++) {
            if (!local->transaction.changelog_xdata[i])
                continue;
            dict_unref(local->transaction.changelog_xdata[i]);
        }
        GF_FREE(local->transaction.changelog_xdata);
    }

    GF_FREE(local->transaction.failed_subvols);

    GF_FREE(local->transaction.basename);
    GF_FREE(local->transaction.new_basename);

    loc_wipe(&local->transaction.parent_loc);
    loc_wipe(&local->transaction.new_parent_loc);
}

void
afr_reply_wipe(struct afr_reply *reply)
{
    if (reply->xdata) {
        dict_unref(reply->xdata);
        reply->xdata = NULL;
    }

    if (reply->xattr) {
        dict_unref(reply->xattr);
        reply->xattr = NULL;
    }
}

void
afr_replies_wipe(struct afr_reply *replies, int count)
{
    int i = 0;

    for (i = 0; i < count; i++) {
        afr_reply_wipe(&replies[i]);
    }
}

void
afr_local_replies_wipe(afr_local_t *local, afr_private_t *priv)
{
    if (!local->replies)
        return;

    afr_replies_wipe(local->replies, priv->child_count);

    memset(local->replies, 0, sizeof(*local->replies) * priv->child_count);
}

static gf_boolean_t
afr_fop_lock_is_unlock(call_frame_t *frame)
{
    afr_local_t *local = frame->local;
    switch (local->op) {
        case GF_FOP_INODELK:
        case GF_FOP_FINODELK:
            if ((F_UNLCK == local->cont.inodelk.in_flock.l_type) &&
                (local->cont.inodelk.in_cmd == F_SETLKW ||
                 local->cont.inodelk.in_cmd == F_SETLK))
                return _gf_true;
            break;
        case GF_FOP_ENTRYLK:
        case GF_FOP_FENTRYLK:
            if (ENTRYLK_UNLOCK == local->cont.entrylk.in_cmd)
                return _gf_true;
            break;
        default:
            return _gf_false;
    }
    return _gf_false;
}

static gf_boolean_t
afr_lk_is_unlock(int32_t cmd, struct gf_flock *flock)
{
    switch (cmd) {
        case F_RESLK_UNLCK:
            return _gf_true;
            break;

#if F_SETLKW != F_SETLKW64
        case F_SETLKW64:
#endif
        case F_SETLKW:

#if F_SETLK != F_SETLK64
        case F_SETLK64:
#endif
        case F_SETLK:
            if (F_UNLCK == flock->l_type)
                return _gf_true;
            break;
        default:
            return _gf_false;
    }
    return _gf_false;
}

void
afr_handle_inconsistent_fop(call_frame_t *frame, int32_t *op_ret,
                            int32_t *op_errno)
{
    afr_private_t *priv = NULL;
    afr_local_t *local = NULL;

    if (!frame || !frame->this || !frame->local || !frame->this->private)
        return;

    if (*op_ret < 0)
        return;

    /* Failing inodelk/entrylk/lk here is not a good idea because we
     * need to cleanup the locks on the other bricks if we choose to fail
     * the fop here. The brick may go down just after unwind happens as well
     * so anyways the fop will fail when the next fop is sent so leaving
     * it like this for now.*/
    local = frame->local;
    switch (local->op) {
        case GF_FOP_LOOKUP:
        case GF_FOP_INODELK:
        case GF_FOP_FINODELK:
        case GF_FOP_ENTRYLK:
        case GF_FOP_FENTRYLK:
        case GF_FOP_LK:
            return;
        default:
            break;
    }

    priv = frame->this->private;
    if (!priv->consistent_io)
        return;

    if (local->event_generation &&
        (local->event_generation != priv->event_generation))
        goto inconsistent;

    return;
inconsistent:
    *op_ret = -1;
    *op_errno = ENOTCONN;
}

void
afr_local_cleanup(afr_local_t *local, xlator_t *this)
{
    afr_private_t *priv = NULL;

    if (!local)
        return;

    syncbarrier_destroy(&local->barrier);

    afr_local_transaction_cleanup(local, this);

    priv = this->private;

    loc_wipe(&local->loc);
    loc_wipe(&local->newloc);

    if (local->fd)
        fd_unref(local->fd);

    if (local->xattr_req)
        dict_unref(local->xattr_req);

    if (local->xattr_rsp)
        dict_unref(local->xattr_rsp);

    if (local->dict)
        dict_unref(local->dict);

    afr_local_replies_wipe(local, priv);
    GF_FREE(local->replies);

    GF_FREE(local->child_up);

    GF_FREE(local->read_attempted);

    GF_FREE(local->readable);
    GF_FREE(local->readable2);

    if (local->inode)
        inode_unref(local->inode);

    if (local->parent)
        inode_unref(local->parent);

    if (local->parent2)
        inode_unref(local->parent2);

    if (local->refreshinode)
        inode_unref(local->refreshinode);

    { /* getxattr */
        GF_FREE(local->cont.getxattr.name);
    }

    { /* lk */
        GF_FREE(local->cont.lk.locked_nodes);
    }

    { /* create */
        if (local->cont.create.fd)
            fd_unref(local->cont.create.fd);
        if (local->cont.create.params)
            dict_unref(local->cont.create.params);
    }

    { /* mknod */
        if (local->cont.mknod.params)
            dict_unref(local->cont.mknod.params);
    }

    { /* mkdir */
        if (local->cont.mkdir.params)
            dict_unref(local->cont.mkdir.params);
    }

    { /* symlink */
        if (local->cont.symlink.params)
            dict_unref(local->cont.symlink.params);
    }

    { /* writev */
        GF_FREE(local->cont.writev.vector);
        if (local->cont.writev.iobref)
            iobref_unref(local->cont.writev.iobref);
    }

    { /* setxattr */
        if (local->cont.setxattr.dict)
            dict_unref(local->cont.setxattr.dict);
    }

    { /* fsetxattr */
        if (local->cont.fsetxattr.dict)
            dict_unref(local->cont.fsetxattr.dict);
    }

    { /* removexattr */
        GF_FREE(local->cont.removexattr.name);
    }
    { /* xattrop */
        if (local->cont.xattrop.xattr)
            dict_unref(local->cont.xattrop.xattr);
    }
    { /* symlink */
        GF_FREE(local->cont.symlink.linkpath);
    }

    { /* opendir */
        GF_FREE(local->cont.opendir.checksum);
    }

    { /* open */
        if (local->cont.open.fd)
            fd_unref(local->cont.open.fd);
    }

    { /* readdirp */
        if (local->cont.readdir.dict)
            dict_unref(local->cont.readdir.dict);
    }

    { /* inodelk */
        GF_FREE(local->cont.inodelk.volume);
        if (local->cont.inodelk.xdata)
            dict_unref(local->cont.inodelk.xdata);
    }

    { /* entrylk */
        GF_FREE(local->cont.entrylk.volume);
        GF_FREE(local->cont.entrylk.basename);
        if (local->cont.entrylk.xdata)
            dict_unref(local->cont.entrylk.xdata);
    }

    if (local->xdata_req)
        dict_unref(local->xdata_req);

    if (local->xdata_rsp)
        dict_unref(local->xdata_rsp);
}

int
afr_frame_return(call_frame_t *frame)
{
    afr_local_t *local = NULL;
    int call_count = 0;

    local = frame->local;

    LOCK(&frame->lock);
    {
        call_count = --local->call_count;
    }
    UNLOCK(&frame->lock);

    return call_count;
}

static char *afr_ignore_xattrs[] = {GF_SELINUX_XATTR_KEY, QUOTA_SIZE_KEY, NULL};

gf_boolean_t
afr_is_xattr_ignorable(char *key)
{
    int i = 0;

    if (!strncmp(key, AFR_XATTR_PREFIX, SLEN(AFR_XATTR_PREFIX)))
        return _gf_true;
    for (i = 0; afr_ignore_xattrs[i]; i++) {
        if (!strcmp(key, afr_ignore_xattrs[i]))
            return _gf_true;
    }
    return _gf_false;
}

static gf_boolean_t
afr_xattr_match_needed(dict_t *this, char *key1, data_t *value1, void *data)
{
    /* Ignore all non-disk (i.e. virtual) xattrs right away. */
    if (!gf_is_valid_xattr_namespace(key1))
        return _gf_false;

    /* Ignore on-disk xattrs that AFR doesn't need to heal. */
    if (!afr_is_xattr_ignorable(key1))
        return _gf_true;

    return _gf_false;
}

gf_boolean_t
afr_xattrs_are_equal(dict_t *dict1, dict_t *dict2)
{
    return are_dicts_equal(dict1, dict2, afr_xattr_match_needed, NULL);
}

static int
afr_get_parent_read_subvol(xlator_t *this, inode_t *parent,
                           struct afr_reply *replies, unsigned char *readable)
{
    int i = 0;
    int par_read_subvol = -1;
    int par_read_subvol_iter = -1;
    afr_private_t *priv = NULL;

    priv = this->private;

    if (parent)
        par_read_subvol = afr_data_subvol_get(parent, this, NULL, NULL, NULL,
                                              NULL);

    for (i = 0; i < priv->child_count; i++) {
        if (!replies[i].valid)
            continue;

        if (replies[i].op_ret < 0)
            continue;

        if (par_read_subvol_iter == -1) {
            par_read_subvol_iter = i;
            continue;
        }

        if ((par_read_subvol_iter != par_read_subvol) && readable[i])
            par_read_subvol_iter = i;

        if (i == par_read_subvol)
            par_read_subvol_iter = i;
    }
    /* At the end of the for-loop, the only reason why @par_read_subvol_iter
     * could be -1 is when this LOOKUP has failed on all sub-volumes.
     * So it is okay to send an arbitrary subvolume (0 in this case)
     * as parent read subvol.
     */
    if (par_read_subvol_iter == -1)
        par_read_subvol_iter = 0;

    return par_read_subvol_iter;
}

int
afr_read_subvol_decide(inode_t *inode, xlator_t *this,
                       afr_read_subvol_args_t *args, unsigned char *readable)
{
    int event = 0;
    afr_private_t *priv = NULL;
    unsigned char *intersection = NULL;

    priv = this->private;
    intersection = alloca0(priv->child_count);

    afr_readables_intersect_get(inode, this, &event, intersection);

    if (AFR_COUNT(intersection, priv->child_count) <= 0) {
        /* TODO: If we have one brick with valid data_readable and
         * another with metadata_readable, try to send an iatt with
         * valid bits from both.*/
        return -1;
    }

    memcpy(readable, intersection, sizeof(*readable) * priv->child_count);

    return afr_read_subvol_select_by_policy(inode, this, intersection, args);
}

static inline int
afr_first_up_child(call_frame_t *frame, xlator_t *this)
{
    afr_private_t *priv = NULL;
    afr_local_t *local = NULL;
    int i = 0;

    local = frame->local;
    priv = this->private;

    for (i = 0; i < priv->child_count; i++)
        if (local->replies[i].valid && local->replies[i].op_ret == 0)
            return i;
    return -1;
}

static void
afr_attempt_readsubvol_set(call_frame_t *frame, xlator_t *this,
                           unsigned char *success_replies,
                           unsigned char *data_readable, int *read_subvol)
{
    afr_private_t *priv = NULL;
    afr_local_t *local = NULL;
    int spb_choice = -1;
    int child_count = -1;

    if (*read_subvol != -1)
        return;

    priv = this->private;
    local = frame->local;
    child_count = priv->child_count;

    afr_inode_split_brain_choice_get(local->inode, this, &spb_choice);
    if ((spb_choice >= 0) &&
        (AFR_COUNT(success_replies, child_count) == child_count)) {
        *read_subvol = spb_choice;
    } else if (!priv->quorum_count ||
               frame->root->pid == GF_CLIENT_PID_GLFS_HEAL) {
        *read_subvol = afr_first_up_child(frame, this);
    } else if (priv->quorum_count &&
               afr_has_quorum(data_readable, this, NULL)) {
        /* read_subvol is guaranteed to be valid if we hit this path. */
        *read_subvol = afr_first_up_child(frame, this);
    } else {
        /* If quorum is enabled and we do not have a
           readable yet, it means all good copies are down.
        */
        local->op_ret = -1;
        local->op_errno = ENOTCONN;
        gf_msg(this->name, GF_LOG_WARNING, 0, AFR_MSG_READ_SUBVOL_ERROR,
               "no read "
               "subvols for %s",
               local->loc.path);
    }
    if (*read_subvol >= 0)
        dict_del_sizen(local->replies[*read_subvol].xdata, GF_CONTENT_KEY);
}

static void
afr_lookup_done(call_frame_t *frame, xlator_t *this)
{
    afr_private_t *priv = NULL;
    afr_local_t *local = NULL;
    int i = -1;
    int op_errno = 0;
    int read_subvol = 0;
    int par_read_subvol = 0;
    int ret = -1;
    unsigned char *readable = NULL;
    unsigned char *success_replies = NULL;
    int event = 0;
    struct afr_reply *replies = NULL;
    uuid_t read_gfid = {
        0,
    };
    gf_boolean_t locked_entry = _gf_false;
    gf_boolean_t in_flight_create = _gf_false;
    gf_boolean_t can_interpret = _gf_true;
    inode_t *parent = NULL;
    ia_type_t ia_type = IA_INVAL;
    afr_read_subvol_args_t args = {
        0,
    };
    char *gfid_heal_msg = NULL;

    priv = this->private;
    local = frame->local;
    replies = local->replies;
    parent = local->loc.parent;

    locked_entry = afr_is_possibly_under_txn(AFR_ENTRY_TRANSACTION, local,
                                             this);

    readable = alloca0(priv->child_count);
    success_replies = alloca0(priv->child_count);

    afr_inode_read_subvol_get(parent, this, readable, NULL, &event);
    par_read_subvol = afr_get_parent_read_subvol(this, parent, replies,
                                                 readable);

    /* First, check if we have a gfid-change from somewhere,
       If so, propagate that so that a fresh lookup can be
       issued
    */
    if (local->cont.lookup.needs_fresh_lookup) {
        local->op_ret = -1;
        local->op_errno = ESTALE;
        goto error;
    }

    op_errno = afr_final_errno(frame->local, this->private);
    local->op_errno = op_errno;

    read_subvol = -1;
    afr_fill_success_replies(local, priv, success_replies);

    for (i = 0; i < priv->child_count; i++) {
        if (!replies[i].valid)
            continue;

        if (replies[i].op_ret == -1) {
            if (locked_entry && replies[i].op_errno == ENOENT) {
                in_flight_create = _gf_true;
            }
            continue;
        }

        if (read_subvol == -1 || !readable[read_subvol]) {
            read_subvol = i;
            gf_uuid_copy(read_gfid, replies[i].poststat.ia_gfid);
            ia_type = replies[i].poststat.ia_type;
            local->op_ret = 0;
        }
    }

    if (in_flight_create && !afr_has_quorum(success_replies, this, NULL)) {
        local->op_ret = -1;
        local->op_errno = ENOENT;
        goto error;
    }

    if (read_subvol == -1)
        goto error;
    /* We now have a read_subvol, which is readable[] (if there
       were any). Next we look for GFID mismatches. We don't
       consider a GFID mismatch as an error if read_subvol is
       readable[] but the mismatching GFID subvol is not.
    */
    for (i = 0; i < priv->child_count; i++) {
        if (!replies[i].valid || replies[i].op_ret == -1) {
            continue;
        }

        if (!gf_uuid_compare(replies[i].poststat.ia_gfid, read_gfid))
            continue;

        can_interpret = _gf_false;

        if (locked_entry)
            continue;

        /* Now GFIDs mismatch. It's OK as long as this subvol
           is not readable[] but read_subvol is */
        if (readable[read_subvol] && !readable[i])
            continue;

        /* If we were called from glfsheal and there is still a gfid
         * mismatch, succeed the lookup and let glfsheal print the
         * response via gfid-heal-msg.*/
        if (!dict_get_str_sizen(local->xattr_req, "gfid-heal-msg",
                                &gfid_heal_msg))
            goto cant_interpret;

        /* LOG ERROR */
        local->op_ret = -1;
        local->op_errno = EIO;
        goto error;
    }

    /* Forth, for the finalized GFID, pick the best subvolume
       to return stats from.
    */
    read_subvol = -1;
    memset(readable, 0, sizeof(*readable) * priv->child_count);
    if (can_interpret) {
        if (!afr_has_quorum(success_replies, this, NULL))
            goto cant_interpret;
        /* It is safe to call afr_replies_interpret() because we have
           a response from all the UP subvolumes and all of them resolved
           to the same GFID
        */
        gf_uuid_copy(args.gfid, read_gfid);
        args.ia_type = ia_type;
        ret = afr_replies_interpret(frame, this, local->inode, NULL);
        read_subvol = afr_read_subvol_decide(local->inode, this, &args,
                                             readable);
        if (read_subvol == -1)
            goto cant_interpret;
        if (ret) {
            afr_inode_event_gen_reset(local->inode, this);
            dict_del_sizen(local->replies[read_subvol].xdata, GF_CONTENT_KEY);
        }
    } else {
    cant_interpret:
        afr_attempt_readsubvol_set(frame, this, success_replies, readable,
                                   &read_subvol);
        if (read_subvol == -1) {
            goto error;
        }
    }

    afr_handle_quota_size(frame, this);

    afr_set_need_heal(this, local);
    if (AFR_IS_ARBITER_BRICK(priv, read_subvol) && local->op_ret == 0) {
        local->op_ret = -1;
        local->op_errno = ENOTCONN;
        gf_msg_debug(this->name, 0,
                     "Arbiter cannot be a read subvol "
                     "for %s",
                     local->loc.path);
        goto error;
    }

    ret = dict_get_str_sizen(local->xattr_req, "gfid-heal-msg", &gfid_heal_msg);
    if (!ret) {
        ret = dict_set_str_sizen(local->replies[read_subvol].xdata,
                                 "gfid-heal-msg", gfid_heal_msg);
        if (ret) {
            gf_msg(this->name, GF_LOG_ERROR, 0, AFR_MSG_DICT_SET_FAILED,
                   "Error setting gfid-heal-msg dict");
            local->op_ret = -1;
            local->op_errno = ENOMEM;
        }
    }

    AFR_STACK_UNWIND(lookup, frame, local->op_ret, local->op_errno,
                     local->inode, &local->replies[read_subvol].poststat,
                     local->replies[read_subvol].xdata,
                     &local->replies[par_read_subvol].postparent);
    return;

error:
    AFR_STACK_UNWIND(lookup, frame, local->op_ret, local->op_errno, NULL, NULL,
                     NULL, NULL);
}

/*
 * During a lookup, some errors are more "important" than
 * others in that they must be given higher priority while
 * returning to the user.
 *
 * The hierarchy is ENODATA > ENOENT > ESTALE > ENOSPC others
 */

int
afr_higher_errno(int32_t old_errno, int32_t new_errno)
{
    if (old_errno == ENODATA || new_errno == ENODATA)
        return ENODATA;
    if (old_errno == ENOENT || new_errno == ENOENT)
        return ENOENT;
    if (old_errno == ESTALE || new_errno == ESTALE)
        return ESTALE;
    if (old_errno == ENOSPC || new_errno == ENOSPC)
        return ENOSPC;

    return new_errno;
}

int
afr_final_errno(afr_local_t *local, afr_private_t *priv)
{
    int i = 0;
    int op_errno = 0;
    int tmp_errno = 0;

    for (i = 0; i < priv->child_count; i++) {
        if (!local->replies[i].valid)
            continue;
        if (local->replies[i].op_ret >= 0)
            continue;
        tmp_errno = local->replies[i].op_errno;
        op_errno = afr_higher_errno(op_errno, tmp_errno);
    }

    return op_errno;
}

static int32_t
afr_local_discovery_cbk(call_frame_t *frame, void *cookie, xlator_t *this,
                        int32_t op_ret, int32_t op_errno, dict_t *dict,
                        dict_t *xdata)
{
    int ret = 0;
    char *pathinfo = NULL;
    gf_boolean_t is_local = _gf_false;
    afr_private_t *priv = NULL;
    int32_t child_index = -1;

    if (op_ret != 0) {
        goto out;
    }

    priv = this->private;
    child_index = (int32_t)(long)cookie;

    ret = dict_get_str_sizen(dict, GF_XATTR_PATHINFO_KEY, &pathinfo);
    if (ret != 0) {
        goto out;
    }

    ret = glusterfs_is_local_pathinfo(pathinfo, &is_local);
    if (ret) {
        goto out;
    }

    /*
     * Note that one local subvolume will override another here.  The only
     * way to avoid that would be to retain extra information about whether
     * the previous read_child is local, and it's just not worth it.  Even
     * the slowest local subvolume is far preferable to a remote one.
     */
    if (is_local) {
        priv->local[child_index] = 1;
        /* Don't set arbiter as read child. */
        if (AFR_IS_ARBITER_BRICK(priv, child_index))
            goto out;
        gf_msg(this->name, GF_LOG_INFO, 0, AFR_MSG_LOCAL_CHILD,
               "selecting local read_child %s",
               priv->children[child_index]->name);

        priv->read_child = child_index;
    }
out:
    STACK_DESTROY(frame->root);
    return 0;
}

static void
afr_attempt_local_discovery(xlator_t *this, int32_t child_index)
{
    call_frame_t *newframe = NULL;
    loc_t tmploc = {
        0,
    };
    afr_private_t *priv = this->private;

    newframe = create_frame(this, this->ctx->pool);
    if (!newframe) {
        return;
    }

    tmploc.gfid[sizeof(tmploc.gfid) - 1] = 1;
    STACK_WIND_COOKIE(newframe, afr_local_discovery_cbk,
                      (void *)(long)child_index, priv->children[child_index],
                      priv->children[child_index]->fops->getxattr, &tmploc,
                      GF_XATTR_PATHINFO_KEY, NULL);
}

int
afr_lookup_sh_metadata_wrap(void *opaque)
{
    call_frame_t *frame = opaque;
    afr_local_t *local = NULL;
    xlator_t *this = NULL;
    inode_t *inode = NULL;
    afr_private_t *priv = NULL;
    struct afr_reply *replies = NULL;
    int i = 0, first = -1;
    int ret = -1;
    dict_t *dict = NULL;

    local = frame->local;
    this = frame->this;
    priv = this->private;
    replies = local->replies;

    for (i = 0; i < priv->child_count; i++) {
        if (!replies[i].valid || replies[i].op_ret == -1)
            continue;
        first = i;
        break;
    }
    if (first == -1)
        goto out;

    if (afr_selfheal_metadata_by_stbuf(this, &replies[first].poststat))
        goto out;

    afr_local_replies_wipe(local, this->private);

    dict = dict_new();
    if (!dict)
        goto out;
    if (local->xattr_req) {
        dict_copy(local->xattr_req, dict);
    }

    ret = dict_set_sizen_str_sizen(dict, "link-count", GF_XATTROP_INDEX_COUNT);
    if (ret) {
        gf_msg_debug(this->name, -ret, "Unable to set link-count in dict ");
    }

    if (loc_is_nameless(&local->loc)) {
        ret = afr_selfheal_unlocked_discover_on(frame, local->inode,
                                                local->loc.gfid, local->replies,
                                                local->child_up, dict);
    } else {
        inode = afr_selfheal_unlocked_lookup_on(frame, local->loc.parent,
                                                local->loc.name, local->replies,
                                                local->child_up, dict);
    }
    if (inode)
        inode_unref(inode);
out:
    if (loc_is_nameless(&local->loc))
        afr_discover_done(frame, this);
    else
        afr_lookup_done(frame, this);

    if (dict)
        dict_unref(dict);

    return 0;
}

gf_boolean_t
afr_is_pending_set(xlator_t *this, dict_t *xdata, int type)
{
    int idx = -1;
    afr_private_t *priv = NULL;
    void *pending_raw = NULL;
    int *pending_int = NULL;
    int i = 0;

    priv = this->private;
    idx = afr_index_for_transaction_type(type);

    if (dict_get_ptr(xdata, AFR_DIRTY, &pending_raw) == 0) {
        if (pending_raw) {
            pending_int = pending_raw;

            if (ntoh32(pending_int[idx]))
                return _gf_true;
        }
    }

    for (i = 0; i < priv->child_count; i++) {
        if (dict_get_ptr(xdata, priv->pending_key[i], &pending_raw))
            continue;
        if (!pending_raw)
            continue;
        pending_int = pending_raw;

        if (ntoh32(pending_int[idx]))
            return _gf_true;
    }

    return _gf_false;
}

static gf_boolean_t
afr_can_start_metadata_self_heal(call_frame_t *frame, xlator_t *this)
{
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;
    struct afr_reply *replies = NULL;
    int i = 0, first = -1;
    gf_boolean_t start = _gf_false;
    struct iatt stbuf = {
        0,
    };

    local = frame->local;
    replies = local->replies;
    priv = this->private;

    if (!priv->metadata_self_heal)
        return _gf_false;

    for (i = 0; i < priv->child_count; i++) {
        if (!replies[i].valid || replies[i].op_ret == -1)
            continue;
        if (first == -1) {
            first = i;
            stbuf = replies[i].poststat;
            continue;
        }

        if (afr_is_pending_set(this, replies[i].xdata,
                               AFR_METADATA_TRANSACTION)) {
            /* Let shd do the heal so that lookup is not blocked
             * on getting metadata lock/doing the heal */
            start = _gf_false;
            break;
        }

        if (gf_uuid_compare(stbuf.ia_gfid, replies[i].poststat.ia_gfid)) {
            start = _gf_false;
            break;
        }
        if (!IA_EQUAL(stbuf, replies[i].poststat, type)) {
            start = _gf_false;
            break;
        }

        /*Check if iattrs need heal*/
        if ((!IA_EQUAL(stbuf, replies[i].poststat, uid)) ||
            (!IA_EQUAL(stbuf, replies[i].poststat, gid)) ||
            (!IA_EQUAL(stbuf, replies[i].poststat, prot))) {
            start = _gf_true;
            continue;
        }

        /*Check if xattrs need heal*/
        if (!afr_xattrs_are_equal(replies[first].xdata, replies[i].xdata))
            start = _gf_true;
    }

    return start;
}

int
afr_lookup_metadata_heal_check(call_frame_t *frame, xlator_t *this)

{
    call_frame_t *heal = NULL;
    afr_local_t *local = NULL;
    int ret = 0;

    local = frame->local;
    if (!afr_can_start_metadata_self_heal(frame, this))
        goto out;

    heal = afr_frame_create(this, &ret);
    if (!heal) {
        ret = -ret;
        goto out;
    }

    ret = synctask_new(this->ctx->env, afr_lookup_sh_metadata_wrap,
                       afr_refresh_selfheal_done, heal, frame);
    if (ret)
        goto out;
    return ret;
out:
    if (loc_is_nameless(&local->loc))
        afr_discover_done(frame, this);
    else
        afr_lookup_done(frame, this);
    if (heal)
        AFR_STACK_DESTROY(heal);
    return ret;
}

int
afr_lookup_selfheal_wrap(void *opaque)
{
    int ret = 0;
    call_frame_t *frame = opaque;
    afr_local_t *local = NULL;
    xlator_t *this = NULL;
    inode_t *inode = NULL;
    uuid_t pargfid = {
        0,
    };

    local = frame->local;
    this = frame->this;
    loc_pargfid(&local->loc, pargfid);

    ret = afr_selfheal_name(frame->this, pargfid, local->loc.name,
                            &local->cont.lookup.gfid_req, local->xattr_req);
    if (ret == -EIO)
        goto unwind;

    afr_local_replies_wipe(local, this->private);

    inode = afr_selfheal_unlocked_lookup_on(frame, local->loc.parent,
                                            local->loc.name, local->replies,
                                            local->child_up, local->xattr_req);
    if (inode)
        inode_unref(inode);

    afr_lookup_metadata_heal_check(frame, this);
    return 0;

unwind:
    AFR_STACK_UNWIND(lookup, frame, -1, EIO, NULL, NULL, NULL, NULL);
    return 0;
}

int
afr_lookup_entry_heal(call_frame_t *frame, xlator_t *this)
{
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;
    call_frame_t *heal = NULL;
    int i = 0, first = -1;
    gf_boolean_t name_state_mismatch = _gf_false;
    struct afr_reply *replies = NULL;
    int ret = 0;
    unsigned char *par_readables = NULL;
    unsigned char *success = NULL;
    int32_t op_errno = 0;
    uuid_t gfid = {0};

    local = frame->local;
    replies = local->replies;
    priv = this->private;
    par_readables = alloca0(priv->child_count);
    success = alloca0(priv->child_count);

    ret = afr_inode_read_subvol_get(local->loc.parent, this, par_readables,
                                    NULL, NULL);
    if (ret < 0 || AFR_COUNT(par_readables, priv->child_count) == 0) {
        /* In this case set par_readables to all 1 so that name_heal
         * need checks at the end of this function will flag missing
         * entry when name state mismatches*/
        memset(par_readables, 1, priv->child_count);
    }

    for (i = 0; i < priv->child_count; i++) {
        if (!replies[i].valid)
            continue;

        if (replies[i].op_ret == 0) {
            if (gf_uuid_is_null(gfid)) {
                gf_uuid_copy(gfid, replies[i].poststat.ia_gfid);
            }
            success[i] = 1;
        } else {
            if ((replies[i].op_errno != ENOTCONN) &&
                (replies[i].op_errno != ENOENT) &&
                (replies[i].op_errno != ESTALE)) {
                op_errno = replies[i].op_errno;
            }
        }

        /*gfid is missing, needs heal*/
        if ((replies[i].op_ret == -1) && (replies[i].op_errno == ENODATA)) {
            goto name_heal;
        }

        if (first == -1) {
            first = i;
            continue;
        }

        if (replies[i].op_ret != replies[first].op_ret) {
            name_state_mismatch = _gf_true;
        }

        if (replies[i].op_ret == 0) {
            /* Rename after this lookup may succeed if we don't do
             * a name-heal and the destination may not have pending xattrs
             * to indicate which name is good and which is bad so always do
             * this heal*/
            if (gf_uuid_compare(replies[i].poststat.ia_gfid, gfid)) {
                goto name_heal;
            }
        }
    }

    if (name_state_mismatch) {
        if (!priv->quorum_count)
            goto name_heal;
        if (!afr_has_quorum(success, this, NULL))
            goto name_heal;
        if (op_errno)
            goto name_heal;
        for (i = 0; i < priv->child_count; i++) {
            if (!replies[i].valid)
                continue;
            if (par_readables[i] && replies[i].op_ret < 0 &&
                replies[i].op_errno != ENOTCONN) {
                goto name_heal;
            }
        }
    }

    goto metadata_heal;

name_heal:
    heal = afr_frame_create(this, NULL);
    if (!heal)
        goto metadata_heal;

    ret = synctask_new(this->ctx->env, afr_lookup_selfheal_wrap,
                       afr_refresh_selfheal_done, heal, frame);
    if (ret) {
        AFR_STACK_DESTROY(heal);
        goto metadata_heal;
    }
    return ret;

metadata_heal:
    ret = afr_lookup_metadata_heal_check(frame, this);

    return ret;
}

int
afr_lookup_cbk(call_frame_t *frame, void *cookie, xlator_t *this, int op_ret,
               int op_errno, inode_t *inode, struct iatt *buf, dict_t *xdata,
               struct iatt *postparent)
{
    afr_local_t *local = NULL;
    int call_count = -1;
    int child_index = -1;
    GF_UNUSED int ret = 0;
    int8_t need_heal = 1;

    child_index = (long)cookie;

    local = frame->local;

    local->replies[child_index].valid = 1;
    local->replies[child_index].op_ret = op_ret;
    local->replies[child_index].op_errno = op_errno;
    /*
     * On revalidate lookup if the gfid-changed, afr should unwind the fop
     * with ESTALE so that a fresh lookup will be sent by the top xlator.
     * So remember it.
     */
    if (xdata && dict_get_sizen(xdata, "gfid-changed"))
        local->cont.lookup.needs_fresh_lookup = _gf_true;

    if (xdata) {
        ret = dict_get_int8(xdata, "link-count", &need_heal);
        local->replies[child_index].need_heal = need_heal;
    } else {
        local->replies[child_index].need_heal = need_heal;
    }
    if (op_ret != -1) {
        local->replies[child_index].poststat = *buf;
        local->replies[child_index].postparent = *postparent;
        if (xdata)
            local->replies[child_index].xdata = dict_ref(xdata);
    }

    call_count = afr_frame_return(frame);
    if (call_count == 0) {
        afr_set_need_heal(this, local);
        afr_lookup_entry_heal(frame, this);
    }

    return 0;
}

static void
afr_discover_unwind(call_frame_t *frame, xlator_t *this)
{
    afr_private_t *priv = NULL;
    afr_local_t *local = NULL;
    int read_subvol = -1;
    unsigned char *data_readable = NULL;
    unsigned char *success_replies = NULL;

    priv = this->private;
    local = frame->local;
    data_readable = alloca0(priv->child_count);
    success_replies = alloca0(priv->child_count);

    afr_fill_success_replies(local, priv, success_replies);
    if (AFR_COUNT(success_replies, priv->child_count) > 0)
        local->op_ret = 0;

    if (local->op_ret < 0) {
        local->op_ret = -1;
        local->op_errno = afr_final_errno(frame->local, this->private);
        goto error;
    }

    if (!afr_has_quorum(success_replies, this, frame))
        goto unwind;

    afr_replies_interpret(frame, this, local->inode, NULL);

    read_subvol = afr_read_subvol_decide(local->inode, this, NULL,
                                         data_readable);

unwind:
    afr_attempt_readsubvol_set(frame, this, success_replies, data_readable,
                               &read_subvol);
    if (read_subvol == -1)
        goto error;

    if (AFR_IS_ARBITER_BRICK(priv, read_subvol) && local->op_ret == 0) {
        local->op_ret = -1;
        local->op_errno = ENOTCONN;
        gf_msg_debug(this->name, 0,
                     "Arbiter cannot be a read subvol "
                     "for %s",
                     local->loc.path);
    }

    AFR_STACK_UNWIND(lookup, frame, local->op_ret, local->op_errno,
                     local->inode, &local->replies[read_subvol].poststat,
                     local->replies[read_subvol].xdata,
                     &local->replies[read_subvol].postparent);
    return;

error:
    AFR_STACK_UNWIND(lookup, frame, local->op_ret, local->op_errno, NULL, NULL,
                     NULL, NULL);
}

static int
afr_ta_id_file_check(void *opaque)
{
    afr_private_t *priv = NULL;
    xlator_t *this = NULL;
    loc_t loc = {
        0,
    };
    struct iatt stbuf = {
        0,
    };
    dict_t *dict = NULL;
    uuid_t gfid = {
        0,
    };
    fd_t *fd = NULL;
    int ret = 0;

    this = opaque;
    priv = this->private;

    ret = afr_fill_ta_loc(this, &loc);
    if (ret) {
        gf_msg(this->name, GF_LOG_ERROR, -ret, AFR_MSG_THIN_ARB,
               "Failed to populate thin-arbiter loc for: %s.", loc.name);
        goto out;
    }

    ret = syncop_lookup(priv->children[THIN_ARBITER_BRICK_INDEX], &loc, &stbuf,
                        0, 0, 0);
    if (ret == 0) {
        goto out;
    } else if (ret == -ENOENT) {
        fd = fd_create(loc.inode, getpid());
        if (!fd)
            goto out;
        dict = dict_new();
        if (!dict)
            goto out;
        gf_uuid_generate(gfid);
        ret = dict_set_gfuuid(dict, "gfid-req", gfid, true);
        ret = syncop_create(priv->children[THIN_ARBITER_BRICK_INDEX], &loc,
                            O_RDWR, 0664, fd, &stbuf, dict, NULL);
    }

out:
    if (ret == 0) {
        gf_uuid_copy(priv->ta_gfid, stbuf.ia_gfid);
    } else {
        gf_msg(this->name, GF_LOG_ERROR, -ret, AFR_MSG_THIN_ARB,
               "Failed to lookup/create thin-arbiter id file.");
    }
    if (dict)
        dict_unref(dict);
    if (fd)
        fd_unref(fd);
    loc_wipe(&loc);

    return 0;
}

static int
afr_ta_id_file_check_cbk(int ret, call_frame_t *ta_frame, void *opaque)
{
    return 0;
}

static void
afr_discover_done(call_frame_t *frame, xlator_t *this)
{
    int ret = 0;
    afr_private_t *priv = NULL;

    priv = this->private;
    if (!priv->thin_arbiter_count)
        goto unwind;
    if (!gf_uuid_is_null(priv->ta_gfid))
        goto unwind;

    ret = synctask_new(this->ctx->env, afr_ta_id_file_check,
                       afr_ta_id_file_check_cbk, NULL, this);
    if (ret)
        goto unwind;
unwind:
    afr_discover_unwind(frame, this);
}

int
afr_discover_cbk(call_frame_t *frame, void *cookie, xlator_t *this, int op_ret,
                 int op_errno, inode_t *inode, struct iatt *buf, dict_t *xdata,
                 struct iatt *postparent)
{
    afr_local_t *local = NULL;
    int call_count = -1;
    int child_index = -1;
    GF_UNUSED int ret = 0;
    int8_t need_heal = 1;

    child_index = (long)cookie;

    local = frame->local;

    local->replies[child_index].valid = 1;
    local->replies[child_index].op_ret = op_ret;
    local->replies[child_index].op_errno = op_errno;
    if (op_ret != -1) {
        local->replies[child_index].poststat = *buf;
        local->replies[child_index].postparent = *postparent;
        if (xdata)
            local->replies[child_index].xdata = dict_ref(xdata);
    }

    if (local->do_discovery && (op_ret == 0))
        afr_attempt_local_discovery(this, child_index);

    if (xdata) {
        ret = dict_get_int8(xdata, "link-count", &need_heal);
        local->replies[child_index].need_heal = need_heal;
    } else {
        local->replies[child_index].need_heal = need_heal;
    }

    call_count = afr_frame_return(frame);
    if (call_count == 0) {
        afr_set_need_heal(this, local);
        afr_lookup_metadata_heal_check(frame, this);
    }

    return 0;
}

int
afr_discover_do(call_frame_t *frame, xlator_t *this, int err)
{
    int ret = 0;
    int i = 0;
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;
    int call_count = 0;

    local = frame->local;
    priv = this->private;

    if (err) {
        local->op_errno = err;
        goto out;
    }

    call_count = local->call_count = AFR_COUNT(local->child_up,
                                               priv->child_count);

    ret = afr_lookup_xattr_req_prepare(local, this, local->xattr_req,
                                       &local->loc);
    if (ret) {
        local->op_errno = -ret;
        goto out;
    }

    for (i = 0; i < priv->child_count; i++) {
        if (local->child_up[i]) {
            STACK_WIND_COOKIE(
                frame, afr_discover_cbk, (void *)(long)i, priv->children[i],
                priv->children[i]->fops->lookup, &local->loc, local->xattr_req);
            if (!--call_count)
                break;
        }
    }

    return 0;
out:
    AFR_STACK_UNWIND(lookup, frame, -1, local->op_errno, 0, 0, 0, 0);
    return 0;
}

int
afr_discover(call_frame_t *frame, xlator_t *this, loc_t *loc, dict_t *xattr_req)
{
    int op_errno = ENOMEM;
    afr_private_t *priv = NULL;
    afr_local_t *local = NULL;
    int event = 0;

    priv = this->private;

    local = AFR_FRAME_INIT(frame, op_errno);
    if (!local)
        goto out;

    if (!local->call_count) {
        op_errno = ENOTCONN;
        goto out;
    }

    if (__is_root_gfid(loc->inode->gfid)) {
        if (!priv->root_inode)
            priv->root_inode = inode_ref(loc->inode);

        if (priv->choose_local && !priv->did_discovery) {
            /* Logic to detect which subvolumes of AFR are
               local, in order to prefer them for reads
            */
            local->do_discovery = _gf_true;
            priv->did_discovery = _gf_true;
        }
    }

    local->op = GF_FOP_LOOKUP;

    loc_copy(&local->loc, loc);

    local->inode = inode_ref(loc->inode);

    if (xattr_req)
        /* If xattr_req was null, afr_lookup_xattr_req_prepare() will
           allocate one for us */
        local->xattr_req = dict_ref(xattr_req);

    if (gf_uuid_is_null(loc->inode->gfid)) {
        afr_discover_do(frame, this, 0);
        return 0;
    }

    afr_read_subvol_get(loc->inode, this, NULL, NULL, &event,
                        AFR_DATA_TRANSACTION, NULL);

    if (afr_is_inode_refresh_reqd(loc->inode, this, event,
                                  local->event_generation))
        afr_inode_refresh(frame, this, loc->inode, NULL, afr_discover_do);
    else
        afr_discover_do(frame, this, 0);

    return 0;
out:
    AFR_STACK_UNWIND(lookup, frame, -1, op_errno, NULL, NULL, NULL, NULL);
    return 0;
}

int
afr_lookup_do(call_frame_t *frame, xlator_t *this, int err)
{
    int ret = 0;
    int i = 0;
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;
    int call_count = 0;

    local = frame->local;
    priv = this->private;

    if (err < 0) {
        local->op_errno = err;
        goto out;
    }

    call_count = local->call_count = AFR_COUNT(local->child_up,
                                               priv->child_count);

    ret = afr_lookup_xattr_req_prepare(local, this, local->xattr_req,
                                       &local->loc);
    if (ret) {
        local->op_errno = -ret;
        goto out;
    }

    for (i = 0; i < priv->child_count; i++) {
        if (local->child_up[i]) {
            STACK_WIND_COOKIE(
                frame, afr_lookup_cbk, (void *)(long)i, priv->children[i],
                priv->children[i]->fops->lookup, &local->loc, local->xattr_req);
            if (!--call_count)
                break;
        }
    }
    return 0;
out:
    AFR_STACK_UNWIND(lookup, frame, -1, local->op_errno, 0, 0, 0, 0);
    return 0;
}

/*
 * afr_lookup()
 *
 * The goal here is to figure out what the element getting looked up is.
 * i.e what is the GFID, inode type and a conservative estimate of the
 * inode attributes are.
 *
 * As we lookup, operations may be underway on the entry name and the
 * inode. In lookup() we are primarily concerned only with the entry
 * operations. If the entry is getting unlinked or renamed, we detect
 * what operation is underway by querying for on-going transactions and
 * pending self-healing on the entry through xdata.
 *
 * If the entry is a file/dir, it may need self-heal and/or in a
 * split-brain condition. Lookup is not the place to worry about these
 * conditions. Outcast marking will naturally handle them in the read
 * paths.
 *
 * Here is a brief goal of what we are trying to achieve:
 *
 * - LOOKUP on all subvolumes concurrently, querying on-going transaction
 *   and pending self-heal info from the servers.
 *
 * - If all servers reply the same inode type and GFID, the overall call
 *   MUST be a success.
 *
 * - If inode types or GFIDs mismatch, and there IS either an on-going
 *   transaction or pending self-heal, inspect what the nature of the
 *   transaction or pending heal is, and select the appropriate subvolume's
 *   reply as the winner.
 *
 * - If inode types or GFIDs mismatch, and there are no on-going transactions
 *   or pending self-heal on the entry name on any of the servers, fail the
 *   lookup with EIO. Something has gone wrong beyond reasonable action.
 */

int
afr_lookup(call_frame_t *frame, xlator_t *this, loc_t *loc, dict_t *xattr_req)
{
    afr_local_t *local = NULL;
    int32_t op_errno = 0;
    int event = 0;
    int ret = 0;

    if (loc_is_nameless(loc)) {
        if (xattr_req)
            dict_del_sizen(xattr_req, "gfid-req");
        afr_discover(frame, this, loc, xattr_req);
        return 0;
    }

    if (__is_root_gfid(loc->parent->gfid)) {
        if (!strcmp(loc->name, GF_REPLICATE_TRASH_DIR)) {
            op_errno = EPERM;
            goto out;
        }
    }

    local = AFR_FRAME_INIT(frame, op_errno);
    if (!local)
        goto out;

    if (!local->call_count) {
        op_errno = ENOTCONN;
        goto out;
    }

    local->op = GF_FOP_LOOKUP;

    loc_copy(&local->loc, loc);

    local->inode = inode_ref(loc->inode);

    if (xattr_req) {
        /* If xattr_req was null, afr_lookup_xattr_req_prepare() will
           allocate one for us */
        local->xattr_req = dict_copy_with_ref(xattr_req, NULL);
        if (!local->xattr_req) {
            op_errno = ENOMEM;
            goto out;
        }
        ret = dict_get_gfuuid(local->xattr_req, "gfid-req",
                              &local->cont.lookup.gfid_req);
        if (ret == 0) {
            dict_del_sizen(local->xattr_req, "gfid-req");
        }
    }

    afr_read_subvol_get(loc->parent, this, NULL, NULL, &event,
                        AFR_DATA_TRANSACTION, NULL);

    if (afr_is_inode_refresh_reqd(loc->inode, this, event,
                                  local->event_generation))
        afr_inode_refresh(frame, this, loc->parent, NULL, afr_lookup_do);
    else
        afr_lookup_do(frame, this, 0);

    return 0;
out:
    AFR_STACK_UNWIND(lookup, frame, -1, op_errno, NULL, NULL, NULL, NULL);

    return 0;
}

void
_afr_cleanup_fd_ctx(afr_fd_ctx_t *fd_ctx)
{
    GF_FREE(fd_ctx->opened_on);
    GF_FREE(fd_ctx);
    return;
}

int
afr_cleanup_fd_ctx(xlator_t *this, fd_t *fd)
{
    uint64_t ctx = 0;
    afr_fd_ctx_t *fd_ctx = NULL;
    int ret = 0;

    ret = fd_ctx_get(fd, this, &ctx);
    if (ret < 0)
        goto out;

    fd_ctx = (afr_fd_ctx_t *)(long)ctx;

    if (fd_ctx) {
        _afr_cleanup_fd_ctx(fd_ctx);
    }

out:
    return 0;
}

int
afr_release(xlator_t *this, fd_t *fd)
{
    afr_cleanup_fd_ctx(this, fd);

    return 0;
}

afr_fd_ctx_t *
__afr_fd_ctx_get(fd_t *fd, xlator_t *this)
{
    uint64_t ctx = 0;
    int ret = 0;
    afr_fd_ctx_t *fd_ctx = NULL;

    ret = __fd_ctx_get(fd, this, &ctx);

    if (ret < 0) {
        ret = __afr_fd_ctx_set(this, fd);
        if (ret < 0)
            goto out;

        ret = __fd_ctx_get(fd, this, &ctx);
        if (ret < 0)
            goto out;
    }

    fd_ctx = (afr_fd_ctx_t *)(long)ctx;
out:
    return fd_ctx;
}

afr_fd_ctx_t *
afr_fd_ctx_get(fd_t *fd, xlator_t *this)
{
    afr_fd_ctx_t *fd_ctx = NULL;

    LOCK(&fd->lock);
    {
        fd_ctx = __afr_fd_ctx_get(fd, this);
    }
    UNLOCK(&fd->lock);

    return fd_ctx;
}

int
__afr_fd_ctx_set(xlator_t *this, fd_t *fd)
{
    afr_private_t *priv = NULL;
    int ret = -1;
    uint64_t ctx = 0;
    afr_fd_ctx_t *fd_ctx = NULL;
    int i = 0;

    VALIDATE_OR_GOTO(this->private, out);
    VALIDATE_OR_GOTO(fd, out);

    priv = this->private;

    ret = __fd_ctx_get(fd, this, &ctx);

    if (ret == 0)
        goto out;

    fd_ctx = GF_CALLOC(1, sizeof(afr_fd_ctx_t), gf_afr_mt_afr_fd_ctx_t);
    if (!fd_ctx) {
        ret = -ENOMEM;
        goto out;
    }

    fd_ctx->opened_on = GF_CALLOC(sizeof(*fd_ctx->opened_on), priv->child_count,
                                  gf_afr_mt_int32_t);
    if (!fd_ctx->opened_on) {
        ret = -ENOMEM;
        goto out;
    }

    for (i = 0; i < priv->child_count; i++) {
        if (fd_is_anonymous(fd))
            fd_ctx->opened_on[i] = AFR_FD_OPENED;
        else
            fd_ctx->opened_on[i] = AFR_FD_NOT_OPENED;
    }

    fd_ctx->readdir_subvol = -1;

    ret = __fd_ctx_set(fd, this, (uint64_t)(long)fd_ctx);
    if (ret)
        gf_msg_debug(this->name, 0, "failed to set fd ctx (%p)", fd);
out:
    if (ret && fd_ctx)
        _afr_cleanup_fd_ctx(fd_ctx);
    return ret;
}

/* {{{ flush */

int
afr_flush_cbk(call_frame_t *frame, void *cookie, xlator_t *this, int32_t op_ret,
              int32_t op_errno, dict_t *xdata)
{
    afr_local_t *local = NULL;
    int call_count = -1;

    local = frame->local;

    LOCK(&frame->lock);
    {
        if (op_ret != -1) {
            local->op_ret = op_ret;
            if (!local->xdata_rsp && xdata)
                local->xdata_rsp = dict_ref(xdata);
        } else {
            local->op_errno = op_errno;
        }
    }
    UNLOCK(&frame->lock);

    call_count = afr_frame_return(frame);

    if (call_count == 0)
        AFR_STACK_UNWIND(flush, frame, local->op_ret, local->op_errno,
                         local->xdata_rsp);

    return 0;
}

static int
afr_flush_wrapper(call_frame_t *frame, xlator_t *this, fd_t *fd, dict_t *xdata)
{
    int i = 0;
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;
    int call_count = -1;

    priv = this->private;
    local = frame->local;
    call_count = local->call_count;

    for (i = 0; i < priv->child_count; i++) {
        if (local->child_up[i]) {
            STACK_WIND_COOKIE(frame, afr_flush_cbk, (void *)(long)i,
                              priv->children[i], priv->children[i]->fops->flush,
                              local->fd, xdata);
            if (!--call_count)
                break;
        }
    }

    return 0;
}

afr_local_t *
afr_wakeup_same_fd_delayed_op(xlator_t *this, afr_lock_t *lock, fd_t *fd)
{
    afr_local_t *local = NULL;

    if (lock->delay_timer) {
        local = list_entry(lock->post_op.next, afr_local_t,
                           transaction.owner_list);
        if (fd == local->fd) {
            if (gf_timer_call_cancel(this->ctx, lock->delay_timer)) {
                local = NULL;
            } else {
                lock->delay_timer = NULL;
            }
        } else {
            local = NULL;
        }
    }

    return local;
}

void
afr_delayed_changelog_wake_resume(xlator_t *this, inode_t *inode,
                                  call_stub_t *stub)
{
    afr_inode_ctx_t *ctx = NULL;
    afr_lock_t *lock = NULL;
    afr_local_t *metadata_local = NULL;
    afr_local_t *data_local = NULL;
    LOCK(&inode->lock);
    {
        (void)__afr_inode_ctx_get(this, inode, &ctx);
        lock = &ctx->lock[AFR_DATA_TRANSACTION];
        data_local = afr_wakeup_same_fd_delayed_op(this, lock, stub->args.fd);
        lock = &ctx->lock[AFR_METADATA_TRANSACTION];
        metadata_local = afr_wakeup_same_fd_delayed_op(this, lock,
                                                       stub->args.fd);
    }
    UNLOCK(&inode->lock);

    if (data_local) {
        data_local->transaction.resume_stub = stub;
    } else if (metadata_local) {
        metadata_local->transaction.resume_stub = stub;
    } else {
        call_resume(stub);
    }
    if (data_local) {
        afr_delayed_changelog_wake_up_cbk(data_local);
    }
    if (metadata_local) {
        afr_delayed_changelog_wake_up_cbk(metadata_local);
    }
}

int
afr_flush(call_frame_t *frame, xlator_t *this, fd_t *fd, dict_t *xdata)
{
    afr_local_t *local = NULL;
    call_stub_t *stub = NULL;
    int op_errno = ENOMEM;

    local = AFR_FRAME_INIT(frame, op_errno);
    if (!local)
        goto out;

    local->op = GF_FOP_FLUSH;
    if (!afr_is_consistent_io_possible(local, this->private, &op_errno))
        goto out;

    local->fd = fd_ref(fd);

    stub = fop_flush_stub(frame, afr_flush_wrapper, fd, xdata);
    if (!stub)
        goto out;

    afr_delayed_changelog_wake_resume(this, fd->inode, stub);

    return 0;
out:
    AFR_STACK_UNWIND(flush, frame, -1, op_errno, NULL);
    return 0;
}

int
afr_fsyncdir_cbk(call_frame_t *frame, void *cookie, xlator_t *this,
                 int32_t op_ret, int32_t op_errno, dict_t *xdata)
{
    afr_local_t *local = NULL;
    int call_count = -1;

    local = frame->local;

    LOCK(&frame->lock);
    {
        if (op_ret == 0) {
            local->op_ret = 0;
            if (!local->xdata_rsp && xdata)
                local->xdata_rsp = dict_ref(xdata);
        } else {
            local->op_errno = op_errno;
        }
    }
    UNLOCK(&frame->lock);

    call_count = afr_frame_return(frame);

    if (call_count == 0)
        AFR_STACK_UNWIND(fsyncdir, frame, local->op_ret, local->op_errno,
                         local->xdata_rsp);

    return 0;
}

int
afr_fsyncdir(call_frame_t *frame, xlator_t *this, fd_t *fd, int32_t datasync,
             dict_t *xdata)
{
    afr_private_t *priv = NULL;
    afr_local_t *local = NULL;
    int i = 0;
    int32_t call_count = 0;
    int32_t op_errno = ENOMEM;

    priv = this->private;

    local = AFR_FRAME_INIT(frame, op_errno);
    if (!local)
        goto out;

    local->op = GF_FOP_FSYNCDIR;
    if (!afr_is_consistent_io_possible(local, priv, &op_errno))
        goto out;

    call_count = local->call_count;
    for (i = 0; i < priv->child_count; i++) {
        if (local->child_up[i]) {
            STACK_WIND(frame, afr_fsyncdir_cbk, priv->children[i],
                       priv->children[i]->fops->fsyncdir, fd, datasync, xdata);
            if (!--call_count)
                break;
        }
    }

    return 0;
out:
    AFR_STACK_UNWIND(fsyncdir, frame, -1, op_errno, NULL);

    return 0;
}

/* }}} */

static int
afr_serialized_lock_wind(call_frame_t *frame, xlator_t *this);

static gf_boolean_t
afr_is_conflicting_lock_present(int32_t op_ret, int32_t op_errno)
{
    if (op_ret == -1 && op_errno == EAGAIN)
        return _gf_true;
    return _gf_false;
}

static void
afr_fop_lock_unwind(call_frame_t *frame, glusterfs_fop_t op, int32_t op_ret,
                    int32_t op_errno, dict_t *xdata)
{
    switch (op) {
        case GF_FOP_INODELK:
            AFR_STACK_UNWIND(inodelk, frame, op_ret, op_errno, xdata);
            break;
        case GF_FOP_FINODELK:
            AFR_STACK_UNWIND(finodelk, frame, op_ret, op_errno, xdata);
            break;
        case GF_FOP_ENTRYLK:
            AFR_STACK_UNWIND(entrylk, frame, op_ret, op_errno, xdata);
            break;
        case GF_FOP_FENTRYLK:
            AFR_STACK_UNWIND(fentrylk, frame, op_ret, op_errno, xdata);
            break;
        default:
            break;
    }
}

static void
afr_fop_lock_wind(call_frame_t *frame, xlator_t *this, int child_index,
                  int32_t (*lock_cbk)(call_frame_t *, void *, xlator_t *,
                                      int32_t, int32_t, dict_t *))
{
    afr_local_t *local = frame->local;
    afr_private_t *priv = this->private;
    int i = child_index;

    switch (local->op) {
        case GF_FOP_INODELK:
            STACK_WIND_COOKIE(
                frame, lock_cbk, (void *)(long)i, priv->children[i],
                priv->children[i]->fops->inodelk,
                (const char *)local->cont.inodelk.volume, &local->loc,
                local->cont.inodelk.cmd, &local->cont.inodelk.flock,
                local->cont.inodelk.xdata);
            break;
        case GF_FOP_FINODELK:
            STACK_WIND_COOKIE(
                frame, lock_cbk, (void *)(long)i, priv->children[i],
                priv->children[i]->fops->finodelk,
                (const char *)local->cont.inodelk.volume, local->fd,
                local->cont.inodelk.cmd, &local->cont.inodelk.flock,
                local->cont.inodelk.xdata);
            break;
        case GF_FOP_ENTRYLK:
            STACK_WIND_COOKIE(
                frame, lock_cbk, (void *)(long)i, priv->children[i],
                priv->children[i]->fops->entrylk, local->cont.entrylk.volume,
                &local->loc, local->cont.entrylk.basename,
                local->cont.entrylk.cmd, local->cont.entrylk.type,
                local->cont.entrylk.xdata);
            break;
        case GF_FOP_FENTRYLK:
            STACK_WIND_COOKIE(
                frame, lock_cbk, (void *)(long)i, priv->children[i],
                priv->children[i]->fops->fentrylk, local->cont.entrylk.volume,
                local->fd, local->cont.entrylk.basename,
                local->cont.entrylk.cmd, local->cont.entrylk.type,
                local->cont.entrylk.xdata);
            break;
        default:
            break;
    }
}

void
afr_fop_lock_proceed(call_frame_t *frame)
{
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;

    local = frame->local;
    priv = frame->this->private;

    if (local->fop_lock_state != AFR_FOP_LOCK_PARALLEL) {
        afr_fop_lock_unwind(frame, local->op, local->op_ret, local->op_errno,
                            local->xdata_rsp);
        return;
    }
    /* At least one child is up */
    /*
     * Non-blocking locks also need to be serialized.  Otherwise there is
     * a chance that both the mounts which issued same non-blocking inodelk
     * may endup not acquiring the lock on any-brick.
     * Ex: Mount1 and Mount2
     * request for full length lock on file f1.  Mount1 afr may acquire the
     * partial lock on brick-1 and may not acquire the lock on brick-2
     * because Mount2 already got the lock on brick-2, vice versa.  Since
     * both the mounts only got partial locks, afr treats them as failure in
     * gaining the locks and unwinds with EAGAIN errno.
     */
    local->op_ret = -1;
    local->op_errno = EUCLEAN;
    local->fop_lock_state = AFR_FOP_LOCK_SERIAL;
    afr_local_replies_wipe(local, priv);
    if (local->xdata_rsp)
        dict_unref(local->xdata_rsp);
    local->xdata_rsp = NULL;
    switch (local->op) {
        case GF_FOP_INODELK:
        case GF_FOP_FINODELK:
            local->cont.inodelk.cmd = local->cont.inodelk.in_cmd;
            local->cont.inodelk.flock = local->cont.inodelk.in_flock;
            if (local->cont.inodelk.xdata)
                dict_unref(local->cont.inodelk.xdata);
            local->cont.inodelk.xdata = NULL;
            if (local->xdata_req)
                local->cont.inodelk.xdata = dict_ref(local->xdata_req);
            break;
        case GF_FOP_ENTRYLK:
        case GF_FOP_FENTRYLK:
            local->cont.entrylk.cmd = local->cont.entrylk.in_cmd;
            if (local->cont.entrylk.xdata)
                dict_unref(local->cont.entrylk.xdata);
            local->cont.entrylk.xdata = NULL;
            if (local->xdata_req)
                local->cont.entrylk.xdata = dict_ref(local->xdata_req);
            break;
        default:
            break;
    }
    afr_serialized_lock_wind(frame, frame->this);
}

static int32_t
afr_unlock_partial_lock_cbk(call_frame_t *frame, void *cookie, xlator_t *this,
                            int32_t op_ret, int32_t op_errno, dict_t *xdata)

{
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;
    int call_count = -1;
    int child_index = (long)cookie;
    uuid_t gfid = {0};

    local = frame->local;
    priv = this->private;

    if (op_ret < 0 && op_errno != ENOTCONN) {
        if (local->fd)
            gf_uuid_copy(gfid, local->fd->inode->gfid);
        else
            loc_gfid(&local->loc, gfid);
        gf_msg(this->name, GF_LOG_ERROR, op_errno, AFR_MSG_UNLOCK_FAIL,
               "%s: Failed to unlock %s on %s "
               "with lk_owner: %s",
               uuid_utoa(gfid), gf_fop_list[local->op],
               priv->children[child_index]->name,
               lkowner_utoa(&frame->root->lk_owner));
    }

    call_count = afr_frame_return(frame);
    if (call_count == 0)
        afr_fop_lock_proceed(frame);

    return 0;
}

static int32_t
afr_unlock_locks_and_proceed(call_frame_t *frame, xlator_t *this,
                             int call_count)
{
    int i = 0;
    afr_private_t *priv = NULL;
    afr_local_t *local = NULL;

    if (call_count == 0) {
        afr_fop_lock_proceed(frame);
        goto out;
    }

    local = frame->local;
    priv = this->private;
    local->call_count = call_count;
    switch (local->op) {
        case GF_FOP_INODELK:
        case GF_FOP_FINODELK:
            local->cont.inodelk.flock.l_type = F_UNLCK;
            local->cont.inodelk.cmd = F_SETLK;
            if (local->cont.inodelk.xdata)
                dict_unref(local->cont.inodelk.xdata);
            local->cont.inodelk.xdata = NULL;
            break;
        case GF_FOP_ENTRYLK:
        case GF_FOP_FENTRYLK:
            local->cont.entrylk.cmd = ENTRYLK_UNLOCK;
            if (local->cont.entrylk.xdata)
                dict_unref(local->cont.entrylk.xdata);
            local->cont.entrylk.xdata = NULL;
            break;
        default:
            break;
    }

    for (i = 0; i < priv->child_count; i++) {
        if (!local->replies[i].valid)
            continue;

        if (local->replies[i].op_ret == -1)
            continue;

        afr_fop_lock_wind(frame, this, i, afr_unlock_partial_lock_cbk);

        if (!--call_count)
            break;
    }

out:
    return 0;
}

int32_t
afr_fop_lock_done(call_frame_t *frame, xlator_t *this)
{
    int i = 0;
    int lock_count = 0;
    unsigned char *success = NULL;

    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;

    local = frame->local;
    priv = this->private;
    success = alloca0(priv->child_count);

    for (i = 0; i < priv->child_count; i++) {
        if (!local->replies[i].valid)
            continue;

        if (local->replies[i].op_ret == 0) {
            lock_count++;
            success[i] = 1;
        }

        if (local->op_ret == -1 && local->op_errno == EAGAIN)
            continue;

        if ((local->replies[i].op_ret == -1) &&
            (local->replies[i].op_errno == EAGAIN)) {
            local->op_ret = -1;
            local->op_errno = EAGAIN;
            continue;
        }

        if (local->replies[i].op_ret == 0)
            local->op_ret = 0;

        local->op_errno = local->replies[i].op_errno;
    }

    if (afr_fop_lock_is_unlock(frame))
        goto unwind;

    if (afr_is_conflicting_lock_present(local->op_ret, local->op_errno)) {
        afr_unlock_locks_and_proceed(frame, this, lock_count);
    } else if (priv->quorum_count && !afr_has_quorum(success, this, NULL)) {
        local->fop_lock_state = AFR_FOP_LOCK_QUORUM_FAILED;
        local->op_ret = -1;
        local->op_errno = afr_final_errno(local, priv);
        if (local->op_errno == 0)
            local->op_errno = afr_quorum_errno(priv);
        afr_unlock_locks_and_proceed(frame, this, lock_count);
    } else {
        goto unwind;
    }

    return 0;
unwind:
    afr_fop_lock_unwind(frame, local->op, local->op_ret, local->op_errno,
                        local->xdata_rsp);
    return 0;
}

static int
afr_common_lock_cbk(call_frame_t *frame, void *cookie, xlator_t *this,
                    int32_t op_ret, int32_t op_errno, dict_t *xdata)
{
    afr_local_t *local = NULL;
    int child_index = (long)cookie;

    local = frame->local;

    local->replies[child_index].valid = 1;
    local->replies[child_index].op_ret = op_ret;
    local->replies[child_index].op_errno = op_errno;
    if (op_ret == 0 && xdata) {
        local->replies[child_index].xdata = dict_ref(xdata);
        LOCK(&frame->lock);
        {
            if (!local->xdata_rsp)
                local->xdata_rsp = dict_ref(xdata);
        }
        UNLOCK(&frame->lock);
    }
    return 0;
}

static int32_t
afr_serialized_lock_cbk(call_frame_t *frame, void *cookie, xlator_t *this,
                        int32_t op_ret, int32_t op_errno, dict_t *xdata)

{
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;
    int child_index = (long)cookie;
    int next_child = 0;

    local = frame->local;
    priv = this->private;

    afr_common_lock_cbk(frame, cookie, this, op_ret, op_errno, xdata);

    for (next_child = child_index + 1; next_child < priv->child_count;
         next_child++) {
        if (local->child_up[next_child])
            break;
    }

    if (afr_is_conflicting_lock_present(op_ret, op_errno) ||
        (next_child == priv->child_count)) {
        afr_fop_lock_done(frame, this);
    } else {
        afr_fop_lock_wind(frame, this, next_child, afr_serialized_lock_cbk);
    }

    return 0;
}

static int
afr_serialized_lock_wind(call_frame_t *frame, xlator_t *this)
{
    afr_private_t *priv = NULL;
    afr_local_t *local = NULL;
    int i = 0;

    priv = this->private;
    local = frame->local;

    for (i = 0; i < priv->child_count; i++) {
        if (local->child_up[i]) {
            afr_fop_lock_wind(frame, this, i, afr_serialized_lock_cbk);
            break;
        }
    }
    return 0;
}

static int32_t
afr_parallel_lock_cbk(call_frame_t *frame, void *cookie, xlator_t *this,
                      int32_t op_ret, int32_t op_errno, dict_t *xdata)

{
    int call_count = 0;

    afr_common_lock_cbk(frame, cookie, this, op_ret, op_errno, xdata);

    call_count = afr_frame_return(frame);
    if (call_count == 0)
        afr_fop_lock_done(frame, this);

    return 0;
}

static int
afr_parallel_lock_wind(call_frame_t *frame, xlator_t *this)
{
    afr_private_t *priv = NULL;
    afr_local_t *local = NULL;
    int call_count = 0;
    int i = 0;

    priv = this->private;
    local = frame->local;
    call_count = local->call_count;

    for (i = 0; i < priv->child_count; i++) {
        if (!local->child_up[i])
            continue;
        afr_fop_lock_wind(frame, this, i, afr_parallel_lock_cbk);
        if (!--call_count)
            break;
    }
    return 0;
}

static int
afr_fop_handle_lock(call_frame_t *frame, xlator_t *this)
{
    afr_local_t *local = frame->local;
    int op_errno = 0;

    if (!afr_fop_lock_is_unlock(frame)) {
        if (!afr_is_consistent_io_possible(local, this->private, &op_errno))
            goto out;

        switch (local->op) {
            case GF_FOP_INODELK:
            case GF_FOP_FINODELK:
                local->cont.inodelk.cmd = F_SETLK;
                break;
            case GF_FOP_ENTRYLK:
            case GF_FOP_FENTRYLK:
                local->cont.entrylk.cmd = ENTRYLK_LOCK_NB;
                break;
            default:
                break;
        }
    }

    if (local->xdata_req) {
        switch (local->op) {
            case GF_FOP_INODELK:
            case GF_FOP_FINODELK:
                local->cont.inodelk.xdata = dict_ref(local->xdata_req);
                break;
            case GF_FOP_ENTRYLK:
            case GF_FOP_FENTRYLK:
                local->cont.entrylk.xdata = dict_ref(local->xdata_req);
                break;
            default:
                break;
        }
    }

    local->fop_lock_state = AFR_FOP_LOCK_PARALLEL;
    afr_parallel_lock_wind(frame, this);
out:
    return -op_errno;
}

static int32_t
afr_handle_inodelk(call_frame_t *frame, glusterfs_fop_t fop, const char *volume,
                   loc_t *loc, fd_t *fd, int32_t cmd, struct gf_flock *flock,
                   dict_t *xdata)
{
    afr_local_t *local = NULL;
    int32_t op_errno = ENOMEM;

    local = AFR_FRAME_INIT(frame, op_errno);
    if (!local)
        goto out;

    local->op = fop;
    if (loc)
        loc_copy(&local->loc, loc);
    if (fd)
        local->fd = fd_ref(fd);

    local->cont.inodelk.volume = gf_strdup(volume);
    if (!local->cont.inodelk.volume) {
        op_errno = ENOMEM;
        goto out;
    }

    local->cont.inodelk.in_cmd = cmd;
    local->cont.inodelk.cmd = cmd;
    local->cont.inodelk.in_flock = *flock;
    local->cont.inodelk.flock = *flock;
    if (xdata)
        local->xdata_req = dict_ref(xdata);

    op_errno = -afr_fop_handle_lock(frame, frame->this);
    if (op_errno)
        goto out;
    return 0;
out:
    afr_fop_lock_unwind(frame, fop, -1, op_errno, NULL);

    return 0;
}

int32_t
afr_inodelk(call_frame_t *frame, xlator_t *this, const char *volume, loc_t *loc,
            int32_t cmd, struct gf_flock *flock, dict_t *xdata)
{
    afr_handle_inodelk(frame, GF_FOP_INODELK, volume, loc, NULL, cmd, flock,
                       xdata);
    return 0;
}

int32_t
afr_finodelk(call_frame_t *frame, xlator_t *this, const char *volume, fd_t *fd,
             int32_t cmd, struct gf_flock *flock, dict_t *xdata)
{
    afr_handle_inodelk(frame, GF_FOP_FINODELK, volume, NULL, fd, cmd, flock,
                       xdata);
    return 0;
}

static int
afr_handle_entrylk(call_frame_t *frame, glusterfs_fop_t fop, const char *volume,
                   loc_t *loc, fd_t *fd, const char *basename, entrylk_cmd cmd,
                   entrylk_type type, dict_t *xdata)
{
    afr_local_t *local = NULL;
    int32_t op_errno = ENOMEM;

    local = AFR_FRAME_INIT(frame, op_errno);
    if (!local)
        goto out;

    local->op = fop;
    if (loc)
        loc_copy(&local->loc, loc);
    if (fd)
        local->fd = fd_ref(fd);
    local->cont.entrylk.cmd = cmd;
    local->cont.entrylk.in_cmd = cmd;
    local->cont.entrylk.type = type;
    local->cont.entrylk.volume = gf_strdup(volume);
    local->cont.entrylk.basename = gf_strdup(basename);
    if (!local->cont.entrylk.volume || !local->cont.entrylk.basename) {
        op_errno = ENOMEM;
        goto out;
    }
    if (xdata)
        local->xdata_req = dict_ref(xdata);
    op_errno = -afr_fop_handle_lock(frame, frame->this);
    if (op_errno)
        goto out;

    return 0;
out:
    afr_fop_lock_unwind(frame, fop, -1, op_errno, NULL);
    return 0;
}

int
afr_entrylk(call_frame_t *frame, xlator_t *this, const char *volume, loc_t *loc,
            const char *basename, entrylk_cmd cmd, entrylk_type type,
            dict_t *xdata)
{
    afr_handle_entrylk(frame, GF_FOP_ENTRYLK, volume, loc, NULL, basename, cmd,
                       type, xdata);
    return 0;
}

int
afr_fentrylk(call_frame_t *frame, xlator_t *this, const char *volume, fd_t *fd,
             const char *basename, entrylk_cmd cmd, entrylk_type type,
             dict_t *xdata)
{
    afr_handle_entrylk(frame, GF_FOP_FENTRYLK, volume, NULL, fd, basename, cmd,
                       type, xdata);
    return 0;
}

int
afr_statfs_cbk(call_frame_t *frame, void *cookie, xlator_t *this, int op_ret,
               int op_errno, struct statvfs *statvfs, dict_t *xdata)
{
    afr_local_t *local = NULL;
    int call_count = 0;
    struct statvfs *buf = NULL;

    LOCK(&frame->lock);
    {
        local = frame->local;

        if (op_ret != 0) {
            local->op_errno = op_errno;
            goto unlock;
        }

        local->op_ret = op_ret;

        buf = &local->cont.statfs.buf;
        if (local->cont.statfs.buf_set) {
            if (statvfs->f_bavail < buf->f_bavail) {
                *buf = *statvfs;
                if (xdata) {
                    if (local->xdata_rsp)
                        dict_unref(local->xdata_rsp);
                    local->xdata_rsp = dict_ref(xdata);
                }
            }
        } else {
            *buf = *statvfs;
            local->cont.statfs.buf_set = 1;
            if (xdata)
                local->xdata_rsp = dict_ref(xdata);
        }
    }
unlock:
    UNLOCK(&frame->lock);

    call_count = afr_frame_return(frame);

    if (call_count == 0)
        AFR_STACK_UNWIND(statfs, frame, local->op_ret, local->op_errno,
                         &local->cont.statfs.buf, local->xdata_rsp);

    return 0;
}

int
afr_statfs(call_frame_t *frame, xlator_t *this, loc_t *loc, dict_t *xdata)
{
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;
    int i = 0;
    int call_count = 0;
    int32_t op_errno = ENOMEM;

    priv = this->private;

    local = AFR_FRAME_INIT(frame, op_errno);
    if (!local)
        goto out;

    local->op = GF_FOP_STATFS;
    if (!afr_is_consistent_io_possible(local, priv, &op_errno))
        goto out;

    if (priv->arbiter_count == 1 && local->child_up[ARBITER_BRICK_INDEX])
        local->call_count--;
    call_count = local->call_count;
    if (!call_count) {
        op_errno = ENOTCONN;
        goto out;
    }

    for (i = 0; i < priv->child_count; i++) {
        if (local->child_up[i]) {
            if (AFR_IS_ARBITER_BRICK(priv, i))
                continue;
            STACK_WIND(frame, afr_statfs_cbk, priv->children[i],
                       priv->children[i]->fops->statfs, loc, xdata);
            if (!--call_count)
                break;
        }
    }

    return 0;
out:
    AFR_STACK_UNWIND(statfs, frame, -1, op_errno, NULL, NULL);

    return 0;
}

int32_t
afr_lk_unlock_cbk(call_frame_t *frame, void *cookie, xlator_t *this,
                  int32_t op_ret, int32_t op_errno, struct gf_flock *lock,
                  dict_t *xdata)
{
    afr_local_t *local = NULL;
    afr_private_t *priv = this->private;
    int call_count = -1;
    int child_index = (long)cookie;

    local = frame->local;

    if (op_ret < 0 && op_errno != ENOTCONN && op_errno != EBADFD) {
        gf_msg(this->name, GF_LOG_ERROR, op_errno, AFR_MSG_UNLOCK_FAIL,
               "gfid=%s: unlock failed on subvolume %s "
               "with lock owner %s",
               uuid_utoa(local->fd->inode->gfid),
               priv->children[child_index]->name,
               lkowner_utoa(&frame->root->lk_owner));
    }

    call_count = afr_frame_return(frame);
    if (call_count == 0)
        AFR_STACK_UNWIND(lk, frame, local->op_ret, local->op_errno, NULL,
                         local->xdata_rsp);

    return 0;
}

int32_t
afr_lk_unlock(call_frame_t *frame, xlator_t *this)
{
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;
    int i = 0;
    int call_count = 0;

    local = frame->local;
    priv = this->private;

    call_count = afr_locked_nodes_count(local->cont.lk.locked_nodes,
                                        priv->child_count);

    if (call_count == 0) {
        AFR_STACK_UNWIND(lk, frame, local->op_ret, local->op_errno, NULL,
                         local->xdata_rsp);
        return 0;
    }

    local->call_count = call_count;

    local->cont.lk.user_flock.l_type = F_UNLCK;

    for (i = 0; i < priv->child_count; i++) {
        if (local->cont.lk.locked_nodes[i]) {
            STACK_WIND_COOKIE(frame, afr_lk_unlock_cbk, (void *)(long)i,
                              priv->children[i], priv->children[i]->fops->lk,
                              local->fd, F_SETLK, &local->cont.lk.user_flock,
                              NULL);

            if (!--call_count)
                break;
        }
    }

    return 0;
}

int32_t
afr_lk_cbk(call_frame_t *frame, void *cookie, xlator_t *this, int32_t op_ret,
           int32_t op_errno, struct gf_flock *lock, dict_t *xdata)
{
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;
    int child_index = -1;

    local = frame->local;
    priv = this->private;

    child_index = (long)cookie;

    afr_common_lock_cbk(frame, cookie, this, op_ret, op_errno, xdata);
    if (op_ret < 0 && op_errno == EAGAIN) {
        local->op_ret = -1;
        local->op_errno = EAGAIN;

        afr_lk_unlock(frame, this);
        return 0;
    }

    if (op_ret == 0) {
        local->op_ret = 0;
        local->op_errno = 0;
        local->cont.lk.locked_nodes[child_index] = 1;
        local->cont.lk.ret_flock = *lock;
    }

    child_index++;

    if (child_index < priv->child_count) {
        STACK_WIND_COOKIE(frame, afr_lk_cbk, (void *)(long)child_index,
                          priv->children[child_index],
                          priv->children[child_index]->fops->lk, local->fd,
                          local->cont.lk.cmd, &local->cont.lk.user_flock,
                          local->xdata_req);
    } else if (priv->quorum_count &&
               !afr_has_quorum(local->cont.lk.locked_nodes, this, NULL)) {
        local->op_ret = -1;
        local->op_errno = afr_final_errno(local, priv);

        afr_lk_unlock(frame, this);
    } else {
        if (local->op_ret < 0)
            local->op_errno = afr_final_errno(local, priv);

        AFR_STACK_UNWIND(lk, frame, local->op_ret, local->op_errno,
                         &local->cont.lk.ret_flock, local->xdata_rsp);
    }

    return 0;
}

int
afr_lk(call_frame_t *frame, xlator_t *this, fd_t *fd, int32_t cmd,
       struct gf_flock *flock, dict_t *xdata)
{
    afr_private_t *priv = NULL;
    afr_local_t *local = NULL;
    int i = 0;
    int32_t op_errno = ENOMEM;

    priv = this->private;

    local = AFR_FRAME_INIT(frame, op_errno);
    if (!local)
        goto out;

    local->op = GF_FOP_LK;
    if (!afr_lk_is_unlock(cmd, flock) &&
        !afr_is_consistent_io_possible(local, priv, &op_errno))
        goto out;

    local->cont.lk.locked_nodes = GF_CALLOC(
        priv->child_count, sizeof(*local->cont.lk.locked_nodes),
        gf_afr_mt_char);

    if (!local->cont.lk.locked_nodes) {
        op_errno = ENOMEM;
        goto out;
    }

    local->fd = fd_ref(fd);
    local->cont.lk.cmd = cmd;
    local->cont.lk.user_flock = *flock;
    local->cont.lk.ret_flock = *flock;
    if (xdata)
        local->xdata_req = dict_ref(xdata);

    STACK_WIND_COOKIE(frame, afr_lk_cbk, (void *)(long)0, priv->children[i],
                      priv->children[i]->fops->lk, fd, cmd, flock,
                      local->xdata_req);

    return 0;
out:
    AFR_STACK_UNWIND(lk, frame, -1, op_errno, NULL, NULL);

    return 0;
}

int32_t
afr_lease_unlock_cbk(call_frame_t *frame, void *cookie, xlator_t *this,
                     int32_t op_ret, int32_t op_errno, struct gf_lease *lease,
                     dict_t *xdata)
{
    afr_local_t *local = NULL;
    int call_count = -1;

    local = frame->local;
    call_count = afr_frame_return(frame);

    if (call_count == 0)
        AFR_STACK_UNWIND(lease, frame, local->op_ret, local->op_errno, lease,
                         xdata);

    return 0;
}

int32_t
afr_lease_unlock(call_frame_t *frame, xlator_t *this)
{
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;
    int i = 0;
    int call_count = 0;

    local = frame->local;
    priv = this->private;

    call_count = afr_locked_nodes_count(local->cont.lease.locked_nodes,
                                        priv->child_count);

    if (call_count == 0) {
        AFR_STACK_UNWIND(lease, frame, local->op_ret, local->op_errno,
                         &local->cont.lease.ret_lease, NULL);
        return 0;
    }

    local->call_count = call_count;

    local->cont.lease.user_lease.cmd = GF_UNLK_LEASE;

    for (i = 0; i < priv->child_count; i++) {
        if (local->cont.lease.locked_nodes[i]) {
            STACK_WIND(frame, afr_lease_unlock_cbk, priv->children[i],
                       priv->children[i]->fops->lease, &local->loc,
                       &local->cont.lease.user_lease, NULL);

            if (!--call_count)
                break;
        }
    }

    return 0;
}

int32_t
afr_lease_cbk(call_frame_t *frame, void *cookie, xlator_t *this, int32_t op_ret,
              int32_t op_errno, struct gf_lease *lease, dict_t *xdata)
{
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;
    int child_index = -1;

    local = frame->local;
    priv = this->private;

    child_index = (long)cookie;

    afr_common_lock_cbk(frame, cookie, this, op_ret, op_errno, xdata);
    if (op_ret < 0 && op_errno == EAGAIN) {
        local->op_ret = -1;
        local->op_errno = EAGAIN;

        afr_lease_unlock(frame, this);
        return 0;
    }

    if (op_ret == 0) {
        local->op_ret = 0;
        local->op_errno = 0;
        local->cont.lease.locked_nodes[child_index] = 1;
        local->cont.lease.ret_lease = *lease;
    }

    child_index++;
    if (child_index < priv->child_count) {
        STACK_WIND_COOKIE(frame, afr_lease_cbk, (void *)(long)child_index,
                          priv->children[child_index],
                          priv->children[child_index]->fops->lease, &local->loc,
                          &local->cont.lease.user_lease, xdata);
    } else if (priv->quorum_count &&
               !afr_has_quorum(local->cont.lease.locked_nodes, this, NULL)) {
        local->op_ret = -1;
        local->op_errno = afr_final_errno(local, priv);

        afr_lease_unlock(frame, this);
    } else {
        if (local->op_ret < 0)
            local->op_errno = afr_final_errno(local, priv);
        AFR_STACK_UNWIND(lease, frame, local->op_ret, local->op_errno,
                         &local->cont.lease.ret_lease, NULL);
    }

    return 0;
}

int
afr_lease(call_frame_t *frame, xlator_t *this, loc_t *loc,
          struct gf_lease *lease, dict_t *xdata)
{
    afr_private_t *priv = NULL;
    afr_local_t *local = NULL;
    int32_t op_errno = ENOMEM;

    priv = this->private;

    local = AFR_FRAME_INIT(frame, op_errno);
    if (!local)
        goto out;

    local->op = GF_FOP_LEASE;
    local->cont.lease.locked_nodes = GF_CALLOC(
        priv->child_count, sizeof(*local->cont.lease.locked_nodes),
        gf_afr_mt_char);

    if (!local->cont.lease.locked_nodes) {
        op_errno = ENOMEM;
        goto out;
    }

    loc_copy(&local->loc, loc);
    local->cont.lease.user_lease = *lease;
    local->cont.lease.ret_lease = *lease;

    STACK_WIND_COOKIE(frame, afr_lease_cbk, (void *)(long)0, priv->children[0],
                      priv->children[0]->fops->lease, loc, lease, xdata);

    return 0;
out:
    AFR_STACK_UNWIND(lease, frame, -1, op_errno, NULL, NULL);

    return 0;
}

int
afr_ipc_cbk(call_frame_t *frame, void *cookie, xlator_t *this, int32_t op_ret,
            int32_t op_errno, dict_t *xdata)
{
    afr_local_t *local = NULL;
    int child_index = (long)cookie;
    int call_count = 0;
    gf_boolean_t failed = _gf_false;
    gf_boolean_t succeeded = _gf_false;
    int i = 0;
    afr_private_t *priv = NULL;

    local = frame->local;
    priv = this->private;

    local->replies[child_index].valid = 1;
    local->replies[child_index].op_ret = op_ret;
    local->replies[child_index].op_errno = op_errno;
    if (xdata)
        local->replies[child_index].xdata = dict_ref(xdata);

    call_count = afr_frame_return(frame);
    if (call_count)
        goto out;
    /* If any of the subvolumes failed with other than ENOTCONN
     * return error else return success unless all the subvolumes
     * failed.
     * TODO: In case of failure, we need to unregister the xattrs
     * from the other subvolumes where it succeeded (once upcall
     * fixes the Bz-1371622)*/
    for (i = 0; i < priv->child_count; i++) {
        if (!local->replies[i].valid)
            continue;
        if (local->replies[i].op_ret < 0 &&
            local->replies[i].op_errno != ENOTCONN) {
            local->op_ret = local->replies[i].op_ret;
            local->op_errno = local->replies[i].op_errno;
            if (local->xdata_rsp)
                dict_unref(local->xdata_rsp);
            local->xdata_rsp = NULL;
            if (local->replies[i].xdata) {
                local->xdata_rsp = dict_ref(local->replies[i].xdata);
            }
            failed = _gf_true;
            break;
        }
        if (local->replies[i].op_ret == 0) {
            succeeded = _gf_true;
            local->op_ret = 0;
            local->op_errno = 0;
            if (!local->xdata_rsp && local->replies[i].xdata) {
                local->xdata_rsp = dict_ref(local->replies[i].xdata);
            }
        }
    }

    if (!succeeded && !failed) {
        local->op_ret = -1;
        local->op_errno = ENOTCONN;
    }

    AFR_STACK_UNWIND(ipc, frame, local->op_ret, local->op_errno,
                     local->xdata_rsp);

out:
    return 0;
}

int
afr_ipc(call_frame_t *frame, xlator_t *this, int32_t op, dict_t *xdata)
{
    afr_local_t *local = NULL;
    int32_t op_errno = -1;
    afr_private_t *priv = NULL;
    int i = 0;
    int call_cnt = -1;

    VALIDATE_OR_GOTO(frame, err);
    VALIDATE_OR_GOTO(this, err);

    if (op != GF_IPC_TARGET_UPCALL)
        goto wind_default;

    VALIDATE_OR_GOTO(this->private, err);
    priv = this->private;

    local = AFR_FRAME_INIT(frame, op_errno);
    if (!local)
        goto err;

    call_cnt = local->call_count;

    if (xdata) {
        for (i = 0; i < priv->child_count; i++) {
            if (dict_set_int8(xdata, priv->pending_key[i], 0) < 0)
                goto err;
        }
    }

    for (i = 0; i < priv->child_count; i++) {
        if (!local->child_up[i])
            continue;

        STACK_WIND_COOKIE(frame, afr_ipc_cbk, (void *)(long)i,
                          priv->children[i], priv->children[i]->fops->ipc, op,
                          xdata);
        if (!--call_cnt)
            break;
    }
    return 0;

err:
    if (op_errno == -1)
        op_errno = errno;
    AFR_STACK_UNWIND(ipc, frame, -1, op_errno, NULL);

    return 0;

wind_default:
    STACK_WIND(frame, default_ipc_cbk, FIRST_CHILD(this),
               FIRST_CHILD(this)->fops->ipc, op, xdata);
    return 0;
}

int
afr_forget(xlator_t *this, inode_t *inode)
{
    uint64_t ctx_int = 0;
    afr_inode_ctx_t *ctx = NULL;

    afr_spb_choice_timeout_cancel(this, inode);
    inode_ctx_del(inode, this, &ctx_int);
    if (!ctx_int)
        return 0;

    ctx = (afr_inode_ctx_t *)(uintptr_t)ctx_int;
    afr_inode_ctx_destroy(ctx);
    return 0;
}

int
afr_priv_dump(xlator_t *this)
{
    afr_private_t *priv = NULL;
    char key_prefix[GF_DUMP_MAX_BUF_LEN];
    char key[GF_DUMP_MAX_BUF_LEN];
    int i = 0;

    GF_ASSERT(this);
    priv = this->private;

    GF_ASSERT(priv);
    snprintf(key_prefix, GF_DUMP_MAX_BUF_LEN, "%s.%s", this->type, this->name);
    gf_proc_dump_add_section("%s", key_prefix);
    gf_proc_dump_write("child_count", "%u", priv->child_count);
    for (i = 0; i < priv->child_count; i++) {
        sprintf(key, "child_up[%d]", i);
        gf_proc_dump_write(key, "%d", priv->child_up[i]);
        sprintf(key, "pending_key[%d]", i);
        gf_proc_dump_write(key, "%s", priv->pending_key[i]);
        sprintf(key, "pending_reads[%d]", i);
        gf_proc_dump_write(key, "%" PRId64,
                           GF_ATOMIC_GET(priv->pending_reads[i]));
        sprintf(key, "child_latency[%d]", i);
        gf_proc_dump_write(key, "%" PRId64, priv->child_latency[i]);
    }
    gf_proc_dump_write("data_self_heal", "%d", priv->data_self_heal);
    gf_proc_dump_write("metadata_self_heal", "%d", priv->metadata_self_heal);
    gf_proc_dump_write("entry_self_heal", "%d", priv->entry_self_heal);
    gf_proc_dump_write("read_child", "%d", priv->read_child);
    gf_proc_dump_write("wait_count", "%u", priv->wait_count);
    gf_proc_dump_write("heal-wait-queue-length", "%d", priv->heal_wait_qlen);
    gf_proc_dump_write("heal-waiters", "%d", priv->heal_waiters);
    gf_proc_dump_write("background-self-heal-count", "%d",
                       priv->background_self_heal_count);
    gf_proc_dump_write("healers", "%d", priv->healers);
    gf_proc_dump_write("read-hash-mode", "%d", priv->hash_mode);
    if (priv->quorum_count == AFR_QUORUM_AUTO) {
        gf_proc_dump_write("quorum-type", "auto");
    } else if (priv->quorum_count == 0) {
        gf_proc_dump_write("quorum-type", "none");
    } else {
        gf_proc_dump_write("quorum-type", "fixed");
        gf_proc_dump_write("quorum-count", "%d", priv->quorum_count);
    }
    gf_proc_dump_write("up", "%u", afr_has_quorum(priv->child_up, this, NULL));
    if (priv->thin_arbiter_count) {
        gf_proc_dump_write("ta_child_up", "%d", priv->ta_child_up);
        gf_proc_dump_write("ta_bad_child_index", "%d",
                           priv->ta_bad_child_index);
        gf_proc_dump_write("ta_notify_dom_lock_offset", "%" PRId64,
                           priv->ta_notify_dom_lock_offset);
    }

    return 0;
}

/**
 * find_child_index - find the child's index in the array of subvolumes
 * @this: AFR
 * @child: child
 */

static int
afr_find_child_index(xlator_t *this, xlator_t *child)
{
    afr_private_t *priv = NULL;
    int child_count = -1;
    int i = -1;

    priv = this->private;
    child_count = priv->child_count;
    if (priv->thin_arbiter_count) {
        child_count++;
    }

    for (i = 0; i < child_count; i++) {
        if ((xlator_t *)child == priv->children[i])
            break;
    }

    return i;
}

int
__afr_get_up_children_count(afr_private_t *priv)
{
    int up_children = 0;
    int i = 0;

    for (i = 0; i < priv->child_count; i++)
        if (priv->child_up[i] == 1)
            up_children++;

    return up_children;
}

static int
__get_heard_from_all_status(xlator_t *this)
{
    afr_private_t *priv = this->private;
    int i;

    for (i = 0; i < priv->child_count; i++) {
        if (!priv->last_event[i]) {
            return 0;
        }
    }
    if (priv->thin_arbiter_count && !priv->ta_child_up) {
        return 0;
    }
    return 1;
}

glusterfs_event_t
__afr_transform_event_from_state(xlator_t *this)
{
    int i = 0;
    int up_children = 0;
    afr_private_t *priv = this->private;

    if (__get_heard_from_all_status(this))
        /* have_heard_from_all. Let afr_notify() do the propagation. */
        return GF_EVENT_MAXVAL;

    up_children = __afr_get_up_children_count(priv);
    /* Treat the children with pending notification, as having sent a
     * GF_EVENT_CHILD_DOWN. i.e. set the event as GF_EVENT_SOME_DESCENDENT_DOWN,
     * as done in afr_notify() */
    for (i = 0; i < priv->child_count; i++) {
        if (priv->last_event[i])
            continue;
        priv->last_event[i] = GF_EVENT_SOME_DESCENDENT_DOWN;
        priv->child_up[i] = 0;
    }

    if (up_children)
        /* We received at least one child up */
        return GF_EVENT_CHILD_UP;
    else
        return GF_EVENT_CHILD_DOWN;

    return GF_EVENT_MAXVAL;
}

static void
afr_notify_cbk(void *data)
{
    xlator_t *this = data;
    afr_private_t *priv = this->private;
    glusterfs_event_t event = GF_EVENT_MAXVAL;
    gf_boolean_t propagate = _gf_false;

    LOCK(&priv->lock);
    {
        if (!priv->timer) {
            /*
             * Either child_up/child_down is already sent to parent.
             * This is a spurious wake up.
             */
            goto unlock;
        }
        priv->timer = NULL;
        event = __afr_transform_event_from_state(this);
        if (event != GF_EVENT_MAXVAL)
            propagate = _gf_true;
    }
unlock:
    UNLOCK(&priv->lock);
    if (propagate)
        default_notify(this, event, NULL);
}

static void
__afr_launch_notify_timer(xlator_t *this, afr_private_t *priv)
{
    struct timespec delay = {
        0,
    };

    gf_msg_debug(this->name, 0, "Initiating child-down timer");
    delay.tv_sec = 10;
    delay.tv_nsec = 0;
    priv->timer = gf_timer_call_after(this->ctx, delay, afr_notify_cbk, this);
    if (priv->timer == NULL) {
        gf_msg(this->name, GF_LOG_ERROR, 0, AFR_MSG_TIMER_CREATE_FAIL,
               "Cannot create timer for delayed initialization");
    }
}

static int
find_best_down_child(xlator_t *this)
{
    afr_private_t *priv = NULL;
    int i = -1;
    int32_t best_child = -1;
    int64_t best_latency = INT64_MAX;

    priv = this->private;

    for (i = 0; i < priv->child_count; i++) {
        if (priv->child_up[i] && priv->child_latency[i] >= 0 &&
            priv->child_latency[i] < best_latency) {
            best_child = i;
            best_latency = priv->child_latency[i];
        }
    }
    if (best_child >= 0) {
        gf_msg_debug(this->name, 0,
                     "Found best down child (%d) @ %" PRId64 " ms latency",
                     best_child, best_latency);
    }
    return best_child;
}

int
find_worst_up_child(xlator_t *this)
{
    afr_private_t *priv = NULL;
    int i = -1;
    int32_t worst_child = -1;
    int64_t worst_latency = INT64_MIN;

    priv = this->private;

    for (i = 0; i < priv->child_count; i++) {
        if (priv->child_up[i] && priv->child_latency[i] >= 0 &&
            priv->child_latency[i] > worst_latency) {
            worst_child = i;
            worst_latency = priv->child_latency[i];
        }
    }
    if (worst_child >= 0) {
        gf_msg_debug(this->name, 0,
                     "Found worst up child (%d) @ %" PRId64 " ms latency",
                     worst_child, worst_latency);
    }
    return worst_child;
}

void
__afr_handle_ping_event(xlator_t *this, xlator_t *child_xlator, const int idx,
                        int64_t halo_max_latency_msec, int32_t *event,
                        int64_t child_latency_msec)
{
    afr_private_t *priv = NULL;
    int up_children = 0;

    priv = this->private;

    priv->child_latency[idx] = child_latency_msec;
    gf_msg_debug(child_xlator->name, 0, "Client ping @ %" PRId64 " ms",
                 child_latency_msec);
    if (priv->shd.iamshd)
        return;

    up_children = __afr_get_up_children_count(priv);

    if (child_latency_msec > halo_max_latency_msec &&
        priv->child_up[idx] == 1 && up_children > priv->halo_min_replicas) {
        if ((up_children - 1) < priv->halo_min_replicas) {
            gf_log(child_xlator->name, GF_LOG_INFO,
                   "Overriding halo threshold, "
                   "min replicas: %d",
                   priv->halo_min_replicas);
        } else {
            gf_log(child_xlator->name, GF_LOG_INFO,
                   "Child latency (%" PRId64
                   " ms) "
                   "exceeds halo threshold (%" PRId64
                   "), "
                   "marking child down.",
                   child_latency_msec, halo_max_latency_msec);
            *event = GF_EVENT_CHILD_DOWN;
        }
    } else if (child_latency_msec < halo_max_latency_msec &&
               priv->child_up[idx] == 0) {
        if (up_children < priv->halo_max_replicas) {
            gf_log(child_xlator->name, GF_LOG_INFO,
                   "Child latency (%" PRId64
                   " ms) "
                   "below halo threshold (%" PRId64
                   "), "
                   "marking child up.",
                   child_latency_msec, halo_max_latency_msec);
            *event = GF_EVENT_CHILD_UP;
        } else {
            gf_log(child_xlator->name, GF_LOG_INFO,
                   "Not marking child %d up, "
                   "max replicas (%d) reached.",
                   idx, priv->halo_max_replicas);
        }
    }
}

static int64_t
afr_get_halo_latency(xlator_t *this)
{
    afr_private_t *priv = NULL;
    int64_t halo_max_latency_msec = 0;

    priv = this->private;

    if (priv->shd.iamshd) {
        halo_max_latency_msec = priv->shd.halo_max_latency_msec;
    } else if (priv->nfsd.iamnfsd) {
        halo_max_latency_msec = priv->nfsd.halo_max_latency_msec;
    } else {
        halo_max_latency_msec = priv->halo_max_latency_msec;
    }
    gf_msg_debug(this->name, 0, "Using halo latency %" PRId64,
                 halo_max_latency_msec);
    return halo_max_latency_msec;
}

void
__afr_handle_child_up_event(xlator_t *this, xlator_t *child_xlator,
                            const int idx, int64_t child_latency_msec,
                            int32_t *event, int32_t *call_psh,
                            int32_t *up_child)
{
    afr_private_t *priv = NULL;
    int up_children = 0;
    int worst_up_child = -1;
    int64_t halo_max_latency_msec = afr_get_halo_latency(this);

    priv = this->private;

    /*
     * This only really counts if the child was never up
     * (value = -1) or had been down (value = 0).  See
     * comment at GF_EVENT_CHILD_DOWN for a more detailed
     * explanation.
     */
    if (priv->child_up[idx] != 1) {
        priv->event_generation++;
    }
    priv->child_up[idx] = 1;

    *call_psh = 1;
    *up_child = idx;
    up_children = __afr_get_up_children_count(priv);
    /*
     * If this is an _actual_ CHILD_UP event, we
     * want to set the child_latency to MAX to indicate
     * the child needs ping data to be available before doing child-up
     */
    if (child_latency_msec < 0 && priv->halo_enabled) {
        /*set to INT64_MAX-1 so that it is found for best_down_child*/
        priv->child_latency[idx] = AFR_HALO_MAX_LATENCY;
    }

    /*
     * Handle the edge case where we exceed
     * halo_min_replicas and we've got a child which is
     * marked up as it was helping to satisfy the
     * halo_min_replicas even though it's latency exceeds
     * halo_max_latency_msec.
     */
    if (up_children > priv->halo_min_replicas) {
        worst_up_child = find_worst_up_child(this);
        if (worst_up_child >= 0 &&
            priv->child_latency[worst_up_child] > halo_max_latency_msec) {
            gf_msg_debug(this->name, 0,
                         "Marking child %d down, "
                         "doesn't meet halo threshold (%" PRId64
                         "), and > "
                         "halo_min_replicas (%d)",
                         worst_up_child, halo_max_latency_msec,
                         priv->halo_min_replicas);
            priv->child_up[worst_up_child] = 0;
            up_children--;
        }
    }

    if (up_children > priv->halo_max_replicas && !priv->shd.iamshd) {
        worst_up_child = find_worst_up_child(this);
        if (worst_up_child < 0) {
            worst_up_child = idx;
        }
        priv->child_up[worst_up_child] = 0;
        up_children--;
        gf_msg_debug(this->name, 0,
                     "Marking child %d down, "
                     "up_children (%d) > halo_max_replicas (%d)",
                     worst_up_child, up_children, priv->halo_max_replicas);
    }

    if (up_children == 1) {
        gf_msg(this->name, GF_LOG_INFO, 0, AFR_MSG_SUBVOL_UP,
               "Subvolume '%s' came back up; "
               "going online.",
               child_xlator->name);
        gf_event(EVENT_AFR_SUBVOL_UP, "client-pid=%d; subvol=%s",
                 this->ctx->cmd_args.client_pid, this->name);
    } else {
        *event = GF_EVENT_SOME_DESCENDENT_UP;
    }

    priv->last_event[idx] = *event;
}

void
__afr_handle_child_down_event(xlator_t *this, xlator_t *child_xlator, int idx,
                              int64_t child_latency_msec, int32_t *event,
                              int32_t *call_psh, int32_t *up_child)
{
    afr_private_t *priv = NULL;
    int i = 0;
    int up_children = 0;
    int down_children = 0;
    int best_down_child = -1;

    priv = this->private;

    /*
     * If a brick is down when we start, we'll get a
     * CHILD_DOWN to indicate its initial state.  There
     * was never a CHILD_UP in this case, so if we
     * increment "down_count" the difference between than
     * and "up_count" will no longer be the number of
     * children that are currently up.  This has serious
     * implications e.g. for quorum enforcement, so we
     * don't increment these values unless the event
     * represents an actual state transition between "up"
     * (value = 1) and anything else.
     */
    if (priv->child_up[idx] == 1) {
        priv->event_generation++;
    }

    /*
     * If this is an _actual_ CHILD_DOWN event, we
     * want to set the child_latency to < 0 to indicate
     * the child is really disconnected.
     */
    if (child_latency_msec < 0) {
        priv->child_latency[idx] = child_latency_msec;
    }
    priv->child_up[idx] = 0;

    up_children = __afr_get_up_children_count(priv);
    /*
     * Handle the edge case where we need to find the
     * next best child (to mark up) as marking this child
     * down would cause us to fall below halo_min_replicas.
     * We will also force the SHD to heal this child _now_
     * as we want it to be up to date if we are going to
     * begin using it synchronously.
     */
    if (up_children < priv->halo_min_replicas) {
        best_down_child = find_best_down_child(this);
        if (best_down_child >= 0) {
            gf_msg_debug(this->name, 0,
                         "Swapping out child %d for "
                         "child %d to satisfy halo_min_replicas (%d).",
                         idx, best_down_child, priv->halo_min_replicas);
            priv->child_up[best_down_child] = 1;
            *call_psh = 1;
            *up_child = best_down_child;
        }
    }

    for (i = 0; i < priv->child_count; i++)
        if (priv->child_up[i] == 0)
            down_children++;
    if (down_children == priv->child_count) {
        gf_msg(this->name, GF_LOG_ERROR, 0, AFR_MSG_SUBVOLS_DOWN,
               "All subvolumes are down. Going "
               "offline until at least one of them "
               "comes back up.");
        gf_event(EVENT_AFR_SUBVOLS_DOWN, "client-pid=%d; subvol=%s",
                 this->ctx->cmd_args.client_pid, this->name);
    } else {
        *event = GF_EVENT_SOME_DESCENDENT_DOWN;
    }
    priv->last_event[idx] = *event;
}

void
afr_ta_lock_release_synctask(xlator_t *this)
{
    call_frame_t *ta_frame = NULL;
    int ret = 0;

    ta_frame = afr_ta_frame_create(this);
    if (!ta_frame) {
        gf_msg(this->name, GF_LOG_ERROR, ENOMEM, AFR_MSG_THIN_ARB,
               "Failed to create ta_frame");
        return;
    }

    ret = synctask_new(this->ctx->env, afr_release_notify_lock_for_ta,
                       afr_ta_lock_release_done, ta_frame, this);
    if (ret) {
        STACK_DESTROY(ta_frame->root);
        gf_msg(this->name, GF_LOG_ERROR, ENOMEM, AFR_MSG_THIN_ARB,
               "Failed to release "
               "AFR_TA_DOM_NOTIFY lock.");
    }
}

static void
afr_handle_inodelk_contention(xlator_t *this, struct gf_upcall *upcall)
{
    struct gf_upcall_inodelk_contention *lc = NULL;
    unsigned int inmem_count = 0;
    unsigned int onwire_count = 0;
    afr_private_t *priv = this->private;

    lc = upcall->data;

    if (strcmp(lc->domain, AFR_TA_DOM_NOTIFY) != 0)
        return;

    if (priv->shd.iamshd) {
        /* shd should ignore AFR_TA_DOM_NOTIFY release requests. */
        return;
    }
    LOCK(&priv->lock);
    {
        if (priv->release_ta_notify_dom_lock == _gf_true) {
            /* Ignore multiple release requests from shds.*/
            UNLOCK(&priv->lock);
            return;
        }
        priv->release_ta_notify_dom_lock = _gf_true;
        inmem_count = priv->ta_in_mem_txn_count;
        onwire_count = priv->ta_on_wire_txn_count;
    }
    UNLOCK(&priv->lock);
    if (inmem_count || onwire_count)
        /* lock release will happen in txn code path after
         * in-memory or on-wire txns are over.*/
        return;

    afr_ta_lock_release_synctask(this);
}

static void
afr_handle_upcall_event(xlator_t *this, struct gf_upcall *upcall)
{
    struct gf_upcall_cache_invalidation *up_ci = NULL;
    afr_private_t *priv = this->private;
    inode_t *inode = NULL;
    inode_table_t *itable = NULL;
    int i = 0;

    switch (upcall->event_type) {
        case GF_UPCALL_INODELK_CONTENTION:
            afr_handle_inodelk_contention(this, upcall);
            break;
        case GF_UPCALL_CACHE_INVALIDATION:
            up_ci = (struct gf_upcall_cache_invalidation *)upcall->data;

            /* Since md-cache will be aggressively filtering
             * lookups, the stale read issue will be more
             * pronounced. Hence when a pending xattr is set notify
             * all the md-cache clients to invalidate the existing
             * stat cache and send the lookup next time */
            if (!up_ci->dict)
                break;
            for (i = 0; i < priv->child_count; i++) {
                if (!dict_get(up_ci->dict, priv->pending_key[i]))
                    continue;
                up_ci->flags |= UP_INVAL_ATTR;
                itable = ((xlator_t *)this->graph->top)->itable;
                /*Internal processes may not have itable for
                 *top xlator*/
                if (itable)
                    inode = inode_find(itable, upcall->gfid);
                if (inode)
                    afr_inode_need_refresh_set(inode, this);
                break;
            }
            break;
        default:
            break;
    }
}

int32_t
afr_notify(xlator_t *this, int32_t event, void *data, void *data2)
{
    afr_private_t *priv = NULL;
    xlator_t *child_xlator = NULL;
    int i = -1;
    int propagate = 0;
    int had_heard_from_all = 0;
    int have_heard_from_all = 0;
    int idx = -1;
    int ret = -1;
    int call_psh = 0;
    int up_child = -1;
    dict_t *input = NULL;
    dict_t *output = NULL;
    gf_boolean_t had_quorum = _gf_false;
    gf_boolean_t has_quorum = _gf_false;
    int64_t halo_max_latency_msec = 0;
    int64_t child_latency_msec = -1;

    child_xlator = (xlator_t *)data;

    priv = this->private;

    if (!priv)
        return 0;

    /*
     * We need to reset this in case children come up in "staggered"
     * fashion, so that we discover a late-arriving local subvolume.  Note
     * that we could end up issuing N lookups to the first subvolume, and
     * O(N^2) overall, but N is small for AFR so it shouldn't be an issue.
     */
    priv->did_discovery = _gf_false;

    /* parent xlators don't need to know about every child_up, child_down
     * because of afr ha. If all subvolumes go down, child_down has
     * to be triggered. In that state when 1 subvolume comes up child_up
     * needs to be triggered. dht optimizes revalidate lookup by sending
     * it only to one of its subvolumes. When child up/down happens
     * for afr's subvolumes dht should be notified by child_modified. The
     * subsequent revalidate lookup happens on all the dht's subvolumes
     * which triggers afr self-heals if any.
     */
    idx = afr_find_child_index(this, child_xlator);
    if (idx < 0) {
        gf_msg(this->name, GF_LOG_ERROR, 0, AFR_MSG_INVALID_CHILD_UP,
               "Received child_up from invalid subvolume");
        goto out;
    }

    had_quorum = priv->quorum_count &&
                 afr_has_quorum(priv->child_up, this, NULL);
    if (priv->halo_enabled) {
        halo_max_latency_msec = afr_get_halo_latency(this);

        if (event == GF_EVENT_CHILD_PING) {
            /* Calculates the child latency and sets event
             */
            child_latency_msec = (int64_t)(uintptr_t)data2;
            LOCK(&priv->lock);
            {
                __afr_handle_ping_event(this, child_xlator, idx,
                                        halo_max_latency_msec, &event,
                                        child_latency_msec);
            }
            UNLOCK(&priv->lock);
        }
    }

    if (event == GF_EVENT_CHILD_PING) {
        /* This is the only xlator that handles PING, no reason to
         * propagate.
         */
        goto out;
    }

    if (event == GF_EVENT_TRANSLATOR_OP) {
        LOCK(&priv->lock);
        {
            had_heard_from_all = __get_heard_from_all_status(this);
        }
        UNLOCK(&priv->lock);

        if (!had_heard_from_all) {
            ret = -1;
        } else {
            input = data;
            output = data2;
            ret = afr_xl_op(this, input, output);
        }
        goto out;
    }

    if (event == GF_EVENT_UPCALL) {
        afr_handle_upcall_event(this, data);
    }

    LOCK(&priv->lock);
    {
        had_heard_from_all = __get_heard_from_all_status(this);
        switch (event) {
            case GF_EVENT_PARENT_UP:
                __afr_launch_notify_timer(this, priv);
                propagate = 1;
                break;
            case GF_EVENT_CHILD_UP:
                if (priv->thin_arbiter_count &&
                    (idx == AFR_CHILD_THIN_ARBITER)) {
                    priv->ta_child_up = 1;
                    priv->ta_event_gen++;
                    break;
                }
                __afr_handle_child_up_event(this, child_xlator, idx,
                                            child_latency_msec, &event,
                                            &call_psh, &up_child);
                break;

            case GF_EVENT_CHILD_DOWN:
                if (priv->thin_arbiter_count &&
                    (idx == AFR_CHILD_THIN_ARBITER)) {
                    priv->ta_child_up = 0;
                    priv->ta_event_gen++;
                    afr_ta_locked_priv_invalidate(priv);
                    break;
                }
                __afr_handle_child_down_event(this, child_xlator, idx,
                                              child_latency_msec, &event,
                                              &call_psh, &up_child);
                break;

            case GF_EVENT_CHILD_CONNECTING:
                priv->last_event[idx] = event;

                break;

            case GF_EVENT_SOME_DESCENDENT_DOWN:
                priv->last_event[idx] = event;
                break;
            default:
                propagate = 1;
                break;
        }
        have_heard_from_all = __get_heard_from_all_status(this);
        if (!had_heard_from_all && have_heard_from_all) {
            if (priv->timer) {
                gf_timer_call_cancel(this->ctx, priv->timer);
                priv->timer = NULL;
            }
            /* This is the first event which completes aggregation
               of events from all subvolumes. If at least one subvol
               had come up, propagate CHILD_UP, but only this time
            */
            event = GF_EVENT_CHILD_DOWN;
            for (i = 0; i < priv->child_count; i++) {
                if (priv->last_event[i] == GF_EVENT_CHILD_UP) {
                    event = GF_EVENT_CHILD_UP;
                    break;
                }

                if (priv->last_event[i] == GF_EVENT_CHILD_CONNECTING) {
                    event = GF_EVENT_CHILD_CONNECTING;
                    /* continue to check other events for CHILD_UP */
                }
            }
        }
    }
    UNLOCK(&priv->lock);

    if (priv->quorum_count) {
        has_quorum = afr_has_quorum(priv->child_up, this, NULL);
        if (!had_quorum && has_quorum) {
            gf_msg(this->name, GF_LOG_INFO, 0, AFR_MSG_QUORUM_MET,
                   "Client-quorum is met");
            gf_event(EVENT_AFR_QUORUM_MET, "client-pid=%d; subvol=%s",
                     this->ctx->cmd_args.client_pid, this->name);
        }
        if (had_quorum && !has_quorum) {
            gf_msg(this->name, GF_LOG_WARNING, 0, AFR_MSG_QUORUM_FAIL,
                   "Client-quorum is not met");
            gf_event(EVENT_AFR_QUORUM_FAIL, "client-pid=%d; subvol=%s",
                     this->ctx->cmd_args.client_pid, this->name);
        }
    }

    /* if all subvols have reported status, no need to hide anything
       or wait for anything else. Just propagate blindly */
    if (have_heard_from_all)
        propagate = 1;

    ret = 0;
    if (propagate)
        ret = default_notify(this, event, data);

    if ((!had_heard_from_all) || call_psh) {
        /* Launch self-heal on all local subvolumes if:
         * a) We have_heard_from_all for the first time
         * b) Already heard from everyone, but we now got a child-up
         *    event.
         */
        if (have_heard_from_all) {
            afr_selfheal_childup(this, priv);
        }
    }
out:
    return ret;
}

int
afr_local_init(afr_local_t *local, afr_private_t *priv, int32_t *op_errno)
{
    int __ret = -1;
    local->op_ret = -1;
    local->op_errno = EUCLEAN;

    __ret = syncbarrier_init(&local->barrier);
    if (__ret) {
        if (op_errno)
            *op_errno = __ret;
        goto out;
    }

    local->child_up = GF_CALLOC(priv->child_count, sizeof(*local->child_up),
                                gf_afr_mt_char);
    if (!local->child_up) {
        if (op_errno)
            *op_errno = ENOMEM;
        goto out;
    }

    memcpy(local->child_up, priv->child_up,
           sizeof(*local->child_up) * priv->child_count);
    local->call_count = AFR_COUNT(local->child_up, priv->child_count);
    if (local->call_count == 0) {
        gf_msg(THIS->name, GF_LOG_INFO, 0, AFR_MSG_SUBVOLS_DOWN,
               "no subvolumes up");
        if (op_errno)
            *op_errno = ENOTCONN;
        goto out;
    }

    local->event_generation = priv->event_generation;

    local->read_attempted = GF_CALLOC(priv->child_count, sizeof(char),
                                      gf_afr_mt_char);
    if (!local->read_attempted) {
        if (op_errno)
            *op_errno = ENOMEM;
        goto out;
    }

    local->readable = GF_CALLOC(priv->child_count, sizeof(char),
                                gf_afr_mt_char);
    if (!local->readable) {
        if (op_errno)
            *op_errno = ENOMEM;
        goto out;
    }

    local->readable2 = GF_CALLOC(priv->child_count, sizeof(char),
                                 gf_afr_mt_char);
    if (!local->readable2) {
        if (op_errno)
            *op_errno = ENOMEM;
        goto out;
    }

    local->read_subvol = -1;

    local->replies = GF_CALLOC(priv->child_count, sizeof(*local->replies),
                               gf_afr_mt_reply_t);
    if (!local->replies) {
        if (op_errno)
            *op_errno = ENOMEM;
        goto out;
    }

    local->need_full_crawl = _gf_false;
    if (priv->thin_arbiter_count) {
        local->ta_child_up = priv->ta_child_up;
        local->ta_failed_subvol = AFR_CHILD_UNKNOWN;
        local->read_txn_query_child = AFR_CHILD_UNKNOWN;
        local->ta_event_gen = priv->ta_event_gen;
        local->fop_state = TA_SUCCESS;
    }
    local->is_new_entry = _gf_false;

    INIT_LIST_HEAD(&local->healer);
    return 0;
out:
    return -1;
}

int
afr_internal_lock_init(afr_internal_lock_t *lk, size_t child_count)
{
    int ret = -ENOMEM;

    lk->lower_locked_nodes = GF_CALLOC(sizeof(*lk->lower_locked_nodes),
                                       child_count, gf_afr_mt_char);
    if (NULL == lk->lower_locked_nodes)
        goto out;

    lk->lock_op_ret = -1;
    lk->lock_op_errno = EUCLEAN;

    ret = 0;
out:
    return ret;
}

void
afr_matrix_cleanup(int32_t **matrix, unsigned int m)
{
    int i = 0;

    if (!matrix)
        goto out;
    for (i = 0; i < m; i++) {
        GF_FREE(matrix[i]);
    }

    GF_FREE(matrix);
out:
    return;
}

int32_t **
afr_matrix_create(unsigned int m, unsigned int n)
{
    int32_t **matrix = NULL;
    int i = 0;

    matrix = GF_CALLOC(sizeof(*matrix), m, gf_afr_mt_int32_t);
    if (!matrix)
        goto out;

    for (i = 0; i < m; i++) {
        matrix[i] = GF_CALLOC(sizeof(*matrix[i]), n, gf_afr_mt_int32_t);
        if (!matrix[i])
            goto out;
    }
    return matrix;
out:
    afr_matrix_cleanup(matrix, m);
    return NULL;
}

int
afr_transaction_local_init(afr_local_t *local, xlator_t *this)
{
    int ret = -ENOMEM;
    afr_private_t *priv = NULL;

    priv = this->private;
    INIT_LIST_HEAD(&local->transaction.wait_list);
    INIT_LIST_HEAD(&local->transaction.owner_list);
    INIT_LIST_HEAD(&local->ta_waitq);
    INIT_LIST_HEAD(&local->ta_onwireq);
    ret = afr_internal_lock_init(&local->internal_lock, priv->child_count);
    if (ret < 0)
        goto out;

    ret = -ENOMEM;
    local->pre_op_compat = priv->pre_op_compat;

    local->transaction.pre_op = GF_CALLOC(sizeof(*local->transaction.pre_op),
                                          priv->child_count, gf_afr_mt_char);
    if (!local->transaction.pre_op)
        goto out;

    local->transaction.changelog_xdata = GF_CALLOC(
        sizeof(*local->transaction.changelog_xdata), priv->child_count,
        gf_afr_mt_dict_t);
    if (!local->transaction.changelog_xdata)
        goto out;

    if (priv->arbiter_count == 1) {
        local->transaction.pre_op_sources = GF_CALLOC(
            sizeof(*local->transaction.pre_op_sources), priv->child_count,
            gf_afr_mt_char);
        if (!local->transaction.pre_op_sources)
            goto out;
    }

    local->transaction.failed_subvols = GF_CALLOC(
        sizeof(*local->transaction.failed_subvols), priv->child_count,
        gf_afr_mt_char);
    if (!local->transaction.failed_subvols)
        goto out;

    local->pending = afr_matrix_create(priv->child_count, AFR_NUM_CHANGE_LOGS);
    if (!local->pending)
        goto out;

    ret = 0;
out:
    return ret;
}

void
afr_set_low_priority(call_frame_t *frame)
{
    frame->root->pid = LOW_PRIO_PROC_PID;
}

void
afr_priv_destroy(afr_private_t *priv)
{
    int i = 0;
    int child_count = -1;

    if (!priv)
        goto out;
    GF_FREE(priv->last_event);

    child_count = priv->child_count;
    if (priv->thin_arbiter_count) {
        child_count++;
    }
    if (priv->pending_key) {
        for (i = 0; i < child_count; i++)
            GF_FREE(priv->pending_key[i]);
    }

    GF_FREE(priv->pending_reads);
    GF_FREE(priv->local);
    GF_FREE(priv->pending_key);
    GF_FREE(priv->children);
    GF_FREE(priv->child_up);
    GF_FREE(priv->child_latency);
    LOCK_DESTROY(&priv->lock);

    GF_FREE(priv);
out:
    return;
}

int **
afr_mark_pending_changelog(afr_private_t *priv, unsigned char *pending,
                           dict_t *xattr, ia_type_t iat)
{
    int i = 0;
    int **changelog = NULL;
    int idx = -1;
    int m_idx = 0;
    int d_idx = 0;
    int ret = 0;

    m_idx = afr_index_for_transaction_type(AFR_METADATA_TRANSACTION);
    d_idx = afr_index_for_transaction_type(AFR_DATA_TRANSACTION);

    idx = afr_index_from_ia_type(iat);

    changelog = afr_matrix_create(priv->child_count, AFR_NUM_CHANGE_LOGS);
    if (!changelog)
        goto out;

    for (i = 0; i < priv->child_count; i++) {
        if (!pending[i])
            continue;

        changelog[i][m_idx] = hton32(1);
        if (idx != -1)
            changelog[i][idx] = hton32(1);
        /* If the newentry marking is on a newly created directory,
         * then mark it with the full-heal indicator.
         */
        if ((IA_ISDIR(iat)) && (priv->esh_granular))
            changelog[i][d_idx] = hton32(1);
    }
    ret = afr_set_pending_dict(priv, xattr, changelog);
    if (ret < 0) {
        afr_matrix_cleanup(changelog, priv->child_count);
        return NULL;
    }
out:
    return changelog;
}

gf_boolean_t
afr_decide_heal_info(afr_private_t *priv, unsigned char *sources, int source)
{
    int sources_count = 0;

    if (source < 0)
        goto out;

    sources_count = AFR_COUNT(sources, priv->child_count);
    if (sources_count == priv->child_count)
        return _gf_false;
out:
    return _gf_true;
}

int
afr_selfheal_locked_metadata_inspect(call_frame_t *frame, xlator_t *this,
                                     inode_t *inode, gf_boolean_t *msh,
                                     unsigned char *pending)
{
    int ret = -1;
    unsigned char *locked_on = NULL;
    unsigned char *sources = NULL;
    unsigned char *sinks = NULL;
    unsigned char *healed_sinks = NULL;
    unsigned char *undid_pending = NULL;
    struct afr_reply *locked_replies = NULL;

    afr_private_t *priv = this->private;

    locked_on = alloca0(priv->child_count);
    sources = alloca0(priv->child_count);
    sinks = alloca0(priv->child_count);
    healed_sinks = alloca0(priv->child_count);
    undid_pending = alloca0(priv->child_count);

    locked_replies = alloca0(sizeof(*locked_replies) * priv->child_count);

    ret = afr_selfheal_inodelk(frame, this, inode, this->name, LLONG_MAX - 1, 0,
                               locked_on);
    {
        if (ret == 0) {
            /* Not a single lock */
            ret = -afr_final_errno(frame->local, priv);
            if (ret == 0)
                ret = -ENOTCONN; /* all invalid responses */
            goto out;
        }
        ret = __afr_selfheal_metadata_prepare(
            frame, this, inode, locked_on, sources, sinks, healed_sinks,
            undid_pending, locked_replies, pending);
        *msh = afr_decide_heal_info(priv, sources, ret);
    }
    afr_selfheal_uninodelk(frame, this, inode, this->name, LLONG_MAX - 1, 0,
                           locked_on);
out:
    if (locked_replies)
        afr_replies_wipe(locked_replies, priv->child_count);
    return ret;
}

int
afr_selfheal_locked_data_inspect(call_frame_t *frame, xlator_t *this, fd_t *fd,
                                 gf_boolean_t *dsh, unsigned char *pflag)
{
    int ret = -1;
    unsigned char *data_lock = NULL;
    unsigned char *sources = NULL;
    unsigned char *sinks = NULL;
    unsigned char *healed_sinks = NULL;
    unsigned char *undid_pending = NULL;
    afr_private_t *priv = NULL;
    struct afr_reply *locked_replies = NULL;
    inode_t *inode = fd->inode;

    priv = this->private;
    data_lock = alloca0(priv->child_count);
    sources = alloca0(priv->child_count);
    sinks = alloca0(priv->child_count);
    healed_sinks = alloca0(priv->child_count);
    undid_pending = alloca0(priv->child_count);

    locked_replies = alloca0(sizeof(*locked_replies) * priv->child_count);

    ret = afr_selfheal_inodelk(frame, this, inode, this->name, 0, 0, data_lock);
    {
        if (ret == 0) {
            ret = -afr_final_errno(frame->local, priv);
            if (ret == 0)
                ret = -ENOTCONN; /* all invalid responses */
            goto out;
        }
        ret = __afr_selfheal_data_prepare(frame, this, inode, data_lock,
                                          sources, sinks, healed_sinks,
                                          undid_pending, locked_replies, pflag);
        *dsh = afr_decide_heal_info(priv, sources, ret);
    }
    afr_selfheal_uninodelk(frame, this, inode, this->name, 0, 0, data_lock);
out:
    if (locked_replies)
        afr_replies_wipe(locked_replies, priv->child_count);
    return ret;
}

int
afr_selfheal_locked_entry_inspect(call_frame_t *frame, xlator_t *this,
                                  inode_t *inode, gf_boolean_t *esh,
                                  unsigned char *pflag)
{
    int ret = -1;
    int source = -1;
    afr_private_t *priv = NULL;
    unsigned char *locked_on = NULL;
    unsigned char *data_lock = NULL;
    unsigned char *sources = NULL;
    unsigned char *sinks = NULL;
    unsigned char *healed_sinks = NULL;
    struct afr_reply *locked_replies = NULL;
    gf_boolean_t granular_locks = _gf_false;

    priv = this->private;
    granular_locks = priv->granular_locks; /*Assign to local variable so that
                                             reconfigure doesn't change this
                                             value between locking and unlocking
                                             below*/
    locked_on = alloca0(priv->child_count);
    data_lock = alloca0(priv->child_count);
    sources = alloca0(priv->child_count);
    sinks = alloca0(priv->child_count);
    healed_sinks = alloca0(priv->child_count);

    locked_replies = alloca0(sizeof(*locked_replies) * priv->child_count);

    if (!granular_locks) {
        ret = afr_selfheal_tryentrylk(frame, this, inode, priv->sh_domain, NULL,
                                      locked_on);
    }
    {
        if (!granular_locks && ret == 0) {
            ret = -afr_final_errno(frame->local, priv);
            if (ret == 0)
                ret = -ENOTCONN; /* all invalid responses */
            goto out;
        }

        ret = afr_selfheal_entrylk(frame, this, inode, this->name, NULL,
                                   data_lock);
        {
            if (ret == 0) {
                ret = -afr_final_errno(frame->local, priv);
                if (ret == 0)
                    ret = -ENOTCONN;
                /* all invalid responses */
                goto unlock;
            }
            ret = __afr_selfheal_entry_prepare(frame, this, inode, data_lock,
                                               sources, sinks, healed_sinks,
                                               locked_replies, &source, pflag);
            if ((ret == 0) && (*pflag & PFLAG_SBRAIN))
                ret = -EIO;
            *esh = afr_decide_heal_info(priv, sources, ret);
        }
        afr_selfheal_unentrylk(frame, this, inode, this->name, NULL, data_lock,
                               NULL);
    }
unlock:
    if (!granular_locks)
        afr_selfheal_unentrylk(frame, this, inode, priv->sh_domain, NULL,
                               locked_on, NULL);
out:
    if (locked_replies)
        afr_replies_wipe(locked_replies, priv->child_count);
    return ret;
}

int
afr_selfheal_locked_inspect(call_frame_t *frame, xlator_t *this, uuid_t gfid,
                            inode_t **inode, gf_boolean_t *entry_selfheal,
                            gf_boolean_t *data_selfheal,
                            gf_boolean_t *metadata_selfheal,
                            unsigned char *pending)

{
    int ret = -1;
    fd_t *fd = NULL;
    gf_boolean_t dsh = _gf_false;
    gf_boolean_t msh = _gf_false;
    gf_boolean_t esh = _gf_false;

    ret = afr_selfheal_unlocked_inspect(frame, this, gfid, inode, &dsh, &msh,
                                        &esh);
    if (ret)
        goto out;

    /* For every heal type hold locks and check if it indeed needs heal */

    /* Heal-info does an open() on the file being examined so that the
     * current eager-lock holding client, if present, at some point sees
     * open-fd count being > 1 and releases the eager-lock so that heal-info
     * doesn't remain blocked forever until IO completes.
     */
    if ((*inode)->ia_type == IA_IFREG) {
        ret = afr_selfheal_data_open(this, *inode, &fd);
        if (ret < 0) {
            gf_msg_debug(this->name, -ret, "%s: Failed to open",
                         uuid_utoa((*inode)->gfid));
            goto out;
        }
    }

    if (msh) {
        ret = afr_selfheal_locked_metadata_inspect(frame, this, *inode, &msh,
                                                   pending);
        if (ret == -EIO)
            goto out;
    }

    if (dsh) {
        ret = afr_selfheal_locked_data_inspect(frame, this, fd, &dsh, pending);
        if (ret == -EIO || (ret == -EAGAIN))
            goto out;
    }

    if (esh) {
        ret = afr_selfheal_locked_entry_inspect(frame, this, *inode, &esh,
                                                pending);
    }

out:
    *data_selfheal = dsh;
    *entry_selfheal = esh;
    *metadata_selfheal = msh;
    if (fd)
        fd_unref(fd);
    return ret;
}

static dict_t *
afr_set_heal_info(char *status)
{
    dict_t *dict = NULL;
    int ret = -1;

    dict = dict_new();
    if (!dict) {
        ret = -ENOMEM;
        goto out;
    }

    ret = dict_set_dynstr_sizen(dict, "heal-info", status);
    if (ret)
        gf_msg("", GF_LOG_WARNING, -ret, AFR_MSG_DICT_SET_FAILED,
               "Failed to set heal-info key to "
               "%s",
               status);
out:
    /* Any error other than EINVAL, dict_set_dynstr frees status */
    if (ret == -ENOMEM || ret == -EINVAL) {
        GF_FREE(status);
    }

    if (ret && dict) {
        dict_unref(dict);
        dict = NULL;
    }
    return dict;
}

int
afr_get_heal_info(call_frame_t *frame, xlator_t *this, loc_t *loc)
{
    gf_boolean_t data_selfheal = _gf_false;
    gf_boolean_t metadata_selfheal = _gf_false;
    gf_boolean_t entry_selfheal = _gf_false;
    unsigned char pending = 0;
    dict_t *dict = NULL;
    int ret = -1;
    int op_errno = ENOMEM;
    inode_t *inode = NULL;
    char *substr = NULL;
    char *status = NULL;

    ret = afr_selfheal_locked_inspect(frame, this, loc->gfid, &inode,
                                      &entry_selfheal, &data_selfheal,
                                      &metadata_selfheal, &pending);

    if (ret == -ENOMEM) {
        ret = -1;
        goto out;
    }

    if (pending & PFLAG_PENDING) {
        gf_asprintf(&substr, "-pending");
        if (!substr)
            goto out;
    }

    if (ret == -EIO) {
        ret = gf_asprintf(&status, "split-brain%s", substr ? substr : "");
        if (ret < 0) {
            goto out;
        }
        dict = afr_set_heal_info(status);
        if (!dict) {
            ret = -1;
            goto out;
        }
    } else if (ret == -EAGAIN) {
        ret = gf_asprintf(&status, "possibly-healing%s", substr ? substr : "");
        if (ret < 0) {
            goto out;
        }
        dict = afr_set_heal_info(status);
        if (!dict) {
            ret = -1;
            goto out;
        }
    } else if (ret >= 0) {
        /* value of ret = source index
         * so ret >= 0 and at least one of the 3 booleans set to
         * true means a source is identified; heal is required.
         */
        if (!data_selfheal && !entry_selfheal && !metadata_selfheal) {
            status = gf_strdup("no-heal");
            if (!status) {
                ret = -1;
                goto out;
            }
            dict = afr_set_heal_info(status);
            if (!dict) {
                ret = -1;
                goto out;
            }
        } else {
            ret = gf_asprintf(&status, "heal%s", substr ? substr : "");
            if (ret < 0) {
                goto out;
            }
            dict = afr_set_heal_info(status);
            if (!dict) {
                ret = -1;
                goto out;
            }
        }
    } else if (ret < 0) {
        /* Apart from above checked -ve ret values, there are
         * other possible ret values like ENOTCONN
         * (returned when number of valid replies received are
         * less than 2)
         * in which case heal is required when one of the
         * selfheal booleans is set.
         */
        if (data_selfheal || entry_selfheal || metadata_selfheal) {
            ret = gf_asprintf(&status, "heal%s", substr ? substr : "");
            if (ret < 0) {
                goto out;
            }
            dict = afr_set_heal_info(status);
            if (!dict) {
                ret = -1;
                goto out;
            }
        }
    }

    ret = 0;
    op_errno = 0;

out:
    AFR_STACK_UNWIND(getxattr, frame, ret, op_errno, dict, NULL);
    if (dict)
        dict_unref(dict);
    if (inode)
        inode_unref(inode);
    GF_FREE(substr);
    return ret;
}

int
_afr_is_split_brain(call_frame_t *frame, xlator_t *this,
                    struct afr_reply *replies, afr_transaction_type type,
                    gf_boolean_t *spb)
{
    afr_private_t *priv = NULL;
    uint64_t *witness = NULL;
    unsigned char *sources = NULL;
    unsigned char *sinks = NULL;
    int sources_count = 0;
    int ret = 0;

    priv = this->private;

    sources = alloca0(priv->child_count);
    sinks = alloca0(priv->child_count);
    witness = alloca0(priv->child_count * sizeof(*witness));

    ret = afr_selfheal_find_direction(frame, this, replies, type,
                                      priv->child_up, sources, sinks, witness,
                                      NULL);
    if (ret)
        return ret;

    sources_count = AFR_COUNT(sources, priv->child_count);
    if (!sources_count)
        *spb = _gf_true;

    return ret;
}

int
afr_is_split_brain(call_frame_t *frame, xlator_t *this, inode_t *inode,
                   uuid_t gfid, gf_boolean_t *d_spb, gf_boolean_t *m_spb)
{
    int ret = -1;
    afr_private_t *priv = NULL;
    struct afr_reply *replies = NULL;

    priv = this->private;

    replies = alloca0(sizeof(*replies) * priv->child_count);

    ret = afr_selfheal_unlocked_discover(frame, inode, gfid, replies);
    if (ret)
        goto out;

    if (!afr_can_decide_split_brain_source_sinks(replies, priv->child_count)) {
        ret = -EAGAIN;
        goto out;
    }

    ret = _afr_is_split_brain(frame, this, replies, AFR_DATA_TRANSACTION,
                              d_spb);
    if (ret)
        goto out;

    ret = _afr_is_split_brain(frame, this, replies, AFR_METADATA_TRANSACTION,
                              m_spb);
out:
    if (replies) {
        afr_replies_wipe(replies, priv->child_count);
        replies = NULL;
    }
    return ret;
}

int
afr_get_split_brain_status_cbk(int ret, call_frame_t *frame, void *opaque)
{
    GF_FREE(opaque);
    return 0;
}

int
afr_get_split_brain_status(void *opaque)
{
    gf_boolean_t d_spb = _gf_false;
    gf_boolean_t m_spb = _gf_false;
    int ret = -1;
    int op_errno = 0;
    int i = 0;
    char *choices = NULL;
    char *status = NULL;
    dict_t *dict = NULL;
    inode_t *inode = NULL;
    afr_private_t *priv = NULL;
    xlator_t **children = NULL;
    call_frame_t *frame = NULL;
    xlator_t *this = NULL;
    loc_t *loc = NULL;
    afr_spb_status_t *data = NULL;

    data = opaque;
    frame = data->frame;
    this = frame->this;
    loc = data->loc;
    priv = this->private;
    children = priv->children;

    inode = afr_inode_find(this, loc->gfid);
    if (!inode)
        goto out;

    dict = dict_new();
    if (!dict) {
        op_errno = ENOMEM;
        ret = -1;
        goto out;
    }

    /* Calculation for string length :
     * (child_count X length of child-name) + SLEN("    Choices :")
     * child-name consists of :
     * a) 251 = max characters for volname according to GD_VOLUME_NAME_MAX
     * b) strlen("-client-00,") assuming 16 replicas
     */
    choices = alloca0(priv->child_count * (256 + SLEN("-client-00,")) +
                      SLEN("    Choices:"));

    ret = afr_is_split_brain(frame, this, inode, loc->gfid, &d_spb, &m_spb);
    if (ret) {
        op_errno = -ret;
        if (ret == -EAGAIN) {
            ret = dict_set_sizen_str_sizen(dict, GF_AFR_SBRAIN_STATUS,
                                           SBRAIN_HEAL_NO_GO_MSG);
            if (ret) {
                gf_msg(this->name, GF_LOG_WARNING, -ret,
                       AFR_MSG_DICT_SET_FAILED,
                       "Failed to set GF_AFR_SBRAIN_STATUS in dict");
            }
        }
        ret = -1;
        goto out;
    }

    if (d_spb || m_spb) {
        sprintf(choices, "    Choices:");
        for (i = 0; i < priv->child_count; i++) {
            strcat(choices, children[i]->name);
            strcat(choices, ",");
        }
        choices[strlen(choices) - 1] = '\0';

        ret = gf_asprintf(&status,
                          "data-split-brain:%s    "
                          "metadata-split-brain:%s%s",
                          (d_spb) ? "yes" : "no", (m_spb) ? "yes" : "no",
                          choices);

        if (-1 == ret) {
            op_errno = ENOMEM;
            goto out;
        }
        ret = dict_set_dynstr_sizen(dict, GF_AFR_SBRAIN_STATUS, status);
        if (ret) {
            op_errno = -ret;
            ret = -1;
            goto out;
        }
    } else {
        ret = dict_set_sizen_str_sizen(dict, GF_AFR_SBRAIN_STATUS,
                                       SFILE_NOT_UNDER_DATA);
        if (ret) {
            op_errno = -ret;
            ret = -1;
            goto out;
        }
    }

    ret = 0;
out:
    AFR_STACK_UNWIND(getxattr, frame, ret, op_errno, dict, NULL);
    if (dict)
        dict_unref(dict);
    if (inode)
        inode_unref(inode);
    return ret;
}

int32_t
afr_heal_splitbrain_file(call_frame_t *frame, xlator_t *this, loc_t *loc)
{
    int ret = 0;
    int op_errno = 0;
    dict_t *dict = NULL;
    afr_local_t *local = NULL;

    local = frame->local;
    dict = dict_new();
    if (!dict) {
        op_errno = ENOMEM;
        ret = -1;
        goto out;
    }

    ret = afr_selfheal_do(frame, this, loc->gfid);

    if (ret == 1 || ret == 2) {
        ret = dict_set_sizen_str_sizen(dict, "sh-fail-msg",
                                       SFILE_NOT_IN_SPLIT_BRAIN);
        if (ret)
            gf_msg(this->name, GF_LOG_WARNING, -ret, AFR_MSG_DICT_SET_FAILED,
                   "Failed to set sh-fail-msg in dict");
        ret = 0;
        goto out;
    } else {
        if (local->xdata_rsp) {
            /* 'sh-fail-msg' has been set in the dict during self-heal.*/
            dict_copy(local->xdata_rsp, dict);
            ret = 0;
        } else if (ret < 0) {
            op_errno = -ret;
            ret = -1;
        }
    }

out:
    if (local->op == GF_FOP_GETXATTR)
        AFR_STACK_UNWIND(getxattr, frame, ret, op_errno, dict, NULL);
    else if (local->op == GF_FOP_SETXATTR)
        AFR_STACK_UNWIND(setxattr, frame, ret, op_errno, NULL);
    if (dict)
        dict_unref(dict);
    return ret;
}

int
afr_get_child_index_from_name(xlator_t *this, char *name)
{
    afr_private_t *priv = this->private;
    int index = -1;

    for (index = 0; index < priv->child_count; index++) {
        if (!strcmp(priv->children[index]->name, name))
            goto out;
    }
    index = -1;
out:
    return index;
}

void
afr_priv_need_heal_set(afr_private_t *priv, gf_boolean_t need_heal)
{
    LOCK(&priv->lock);
    {
        priv->need_heal = need_heal;
    }
    UNLOCK(&priv->lock);
}

void
afr_set_need_heal(xlator_t *this, afr_local_t *local)
{
    int i = 0;
    afr_private_t *priv = this->private;
    gf_boolean_t need_heal = _gf_false;

    for (i = 0; i < priv->child_count; i++) {
        if (local->replies[i].valid && local->replies[i].need_heal) {
            need_heal = _gf_true;
            break;
        }
    }
    afr_priv_need_heal_set(priv, need_heal);
    return;
}

gf_boolean_t
afr_get_need_heal(xlator_t *this)
{
    afr_private_t *priv = this->private;
    gf_boolean_t need_heal = _gf_true;

    LOCK(&priv->lock);
    {
        need_heal = priv->need_heal;
    }
    UNLOCK(&priv->lock);
    return need_heal;
}

int
afr_get_msg_id(char *op_type)
{
    if (!strcmp(op_type, GF_AFR_REPLACE_BRICK))
        return AFR_MSG_REPLACE_BRICK_STATUS;
    else if (!strcmp(op_type, GF_AFR_ADD_BRICK))
        return AFR_MSG_ADD_BRICK_STATUS;
    return -1;
}

int
afr_fav_child_reset_sink_xattrs_cbk(int ret, call_frame_t *heal_frame,
                                    void *opaque)
{
    call_frame_t *txn_frame = NULL;
    afr_local_t *local = NULL;
    afr_local_t *heal_local = NULL;
    xlator_t *this = NULL;

    heal_local = heal_frame->local;
    txn_frame = heal_local->heal_frame;
    local = txn_frame->local;
    this = txn_frame->this;

    /* Refresh the inode agan and proceed with the transaction.*/
    afr_inode_refresh(txn_frame, this, local->inode, NULL, local->refreshfn);

    AFR_STACK_DESTROY(heal_frame);

    return 0;
}

int
afr_fav_child_reset_sink_xattrs(void *opaque)
{
    call_frame_t *heal_frame = NULL;
    call_frame_t *txn_frame = NULL;
    xlator_t *this = NULL;
    gf_boolean_t d_spb = _gf_false;
    gf_boolean_t m_spb = _gf_false;
    afr_local_t *heal_local = NULL;
    afr_local_t *txn_local = NULL;
    afr_private_t *priv = NULL;
    inode_t *inode = NULL;
    unsigned char *locked_on = NULL;
    unsigned char *sources = NULL;
    unsigned char *sinks = NULL;
    unsigned char *healed_sinks = NULL;
    unsigned char *undid_pending = NULL;
    struct afr_reply *locked_replies = NULL;
    int ret = 0;

    heal_frame = (call_frame_t *)opaque;
    heal_local = heal_frame->local;
    txn_frame = heal_local->heal_frame;
    txn_local = txn_frame->local;
    this = txn_frame->this;
    inode = txn_local->inode;
    priv = this->private;
    locked_on = alloca0(priv->child_count);
    sources = alloca0(priv->child_count);
    sinks = alloca0(priv->child_count);
    healed_sinks = alloca0(priv->child_count);
    undid_pending = alloca0(priv->child_count);
    locked_replies = alloca0(sizeof(*locked_replies) * priv->child_count);

    ret = _afr_is_split_brain(txn_frame, this, txn_local->replies,
                              AFR_DATA_TRANSACTION, &d_spb);

    ret = _afr_is_split_brain(txn_frame, this, txn_local->replies,
                              AFR_METADATA_TRANSACTION, &m_spb);

    /* Take appropriate locks and reset sink xattrs. */
    if (d_spb) {
        ret = afr_selfheal_inodelk(heal_frame, this, inode, this->name, 0, 0,
                                   locked_on);
        {
            if (ret < priv->child_count)
                goto data_unlock;
            ret = __afr_selfheal_data_prepare(
                heal_frame, this, inode, locked_on, sources, sinks,
                healed_sinks, undid_pending, locked_replies, NULL);
        }
    data_unlock:
        afr_selfheal_uninodelk(heal_frame, this, inode, this->name, 0, 0,
                               locked_on);
    }

    if (m_spb) {
        memset(locked_on, 0, sizeof(*locked_on) * priv->child_count);
        memset(undid_pending, 0, sizeof(*undid_pending) * priv->child_count);
        ret = afr_selfheal_inodelk(heal_frame, this, inode, this->name,
                                   LLONG_MAX - 1, 0, locked_on);
        {
            if (ret < priv->child_count)
                goto mdata_unlock;
            ret = __afr_selfheal_metadata_prepare(
                heal_frame, this, inode, locked_on, sources, sinks,
                healed_sinks, undid_pending, locked_replies, NULL);
        }
    mdata_unlock:
        afr_selfheal_uninodelk(heal_frame, this, inode, this->name,
                               LLONG_MAX - 1, 0, locked_on);
    }

    return ret;
}

/*
 * Concatenates the xattrs in local->replies separated by a delimiter.
 */
int
afr_serialize_xattrs_with_delimiter(call_frame_t *frame, xlator_t *this,
                                    char *buf, const char *default_str,
                                    int32_t *serz_len, char delimiter)
{
    afr_private_t *priv = NULL;
    afr_local_t *local = NULL;
    char *xattr = NULL;
    int i = 0;
    int len = 0;
    int keylen = 0;
    size_t str_len = 0;
    int ret = -1;

    priv = this->private;
    local = frame->local;

    keylen = strlen(local->cont.getxattr.name);
    for (i = 0; i < priv->child_count; i++) {
        if (!local->replies[i].valid || local->replies[i].op_ret) {
            str_len = strlen(default_str);
            buf = strncat(buf, default_str, str_len);
            len += str_len;
            buf[len++] = delimiter;
            buf[len] = '\0';
        } else {
            ret = dict_get_strn(local->replies[i].xattr,
                                local->cont.getxattr.name, keylen, &xattr);
            if (ret) {
                gf_msg("TEST", GF_LOG_ERROR, -ret, AFR_MSG_DICT_GET_FAILED,
                       "Failed to get the node_uuid of brick "
                       "%d",
                       i);
                goto out;
            }
            str_len = strlen(xattr);
            buf = strncat(buf, xattr, str_len);
            len += str_len;
            buf[len++] = delimiter;
            buf[len] = '\0';
        }
    }
    buf[--len] = '\0'; /*remove the last delimiter*/
    if (serz_len)
        *serz_len = ++len;
    ret = 0;

out:
    return ret;
}

uint64_t
afr_write_subvol_get(call_frame_t *frame, xlator_t *this)
{
    afr_local_t *local = NULL;
    uint64_t write_subvol = 0;

    local = frame->local;
    LOCK(&local->inode->lock);
    write_subvol = local->inode_ctx->write_subvol;
    UNLOCK(&local->inode->lock);

    return write_subvol;
}

int
afr_write_subvol_set(call_frame_t *frame, xlator_t *this)
{
    afr_local_t *local = NULL;
    afr_private_t *priv = NULL;
    unsigned char *data_accused = NULL;
    unsigned char *metadata_accused = NULL;
    unsigned char *data_readable = NULL;
    unsigned char *metadata_readable = NULL;
    uint16_t datamap = 0;
    uint16_t metadatamap = 0;
    uint64_t val = 0;
    int event = 0;
    int i = 0;

    local = frame->local;
    priv = this->private;
    data_accused = alloca0(priv->child_count);
    metadata_accused = alloca0(priv->child_count);
    data_readable = alloca0(priv->child_count);
    metadata_readable = alloca0(priv->child_count);
    event = local->event_generation;

    afr_readables_fill(frame, this, local->inode, data_accused,
                       metadata_accused, data_readable, metadata_readable,
                       NULL);

    for (i = 0; i < priv->child_count; i++) {
        if (data_readable[i])
            datamap |= (1 << i);
        if (metadata_readable[i])
            metadatamap |= (1 << i);
    }

    val = ((uint64_t)metadatamap) | (((uint64_t)datamap) << 16) |
          (((uint64_t)event) << 32);

    LOCK(&local->inode->lock);
    {
        if (local->inode_ctx->write_subvol == 0 &&
            local->transaction.type == AFR_DATA_TRANSACTION) {
            local->inode_ctx->write_subvol = val;
        }
    }
    UNLOCK(&local->inode->lock);

    return 0;
}

int
afr_write_subvol_reset(call_frame_t *frame, xlator_t *this)
{
    afr_local_t *local = NULL;

    local = frame->local;
    LOCK(&local->inode->lock);
    {
        GF_ASSERT(local->inode_ctx->lock_count > 0);
        local->inode_ctx->lock_count--;

        if (!local->inode_ctx->lock_count)
            local->inode_ctx->write_subvol = 0;
    }
    UNLOCK(&local->inode->lock);

    return 0;
}

int
afr_set_inode_local(xlator_t *this, afr_local_t *local, inode_t *inode)
{
    int ret = 0;

    local->inode = inode_ref(inode);
    LOCK(&local->inode->lock);
    {
        ret = __afr_inode_ctx_get(this, local->inode, &local->inode_ctx);
    }
    UNLOCK(&local->inode->lock);
    if (ret < 0) {
        gf_msg_callingfn(
            this->name, GF_LOG_ERROR, ENOMEM, AFR_MSG_INODE_CTX_GET_FAILED,
            "Error getting inode ctx %s", uuid_utoa(local->inode->gfid));
    }
    return ret;
}

gf_boolean_t
afr_ta_is_fop_called_from_synctask(xlator_t *this)
{
    struct synctask *task = NULL;
    gf_lkowner_t tmp_owner = {
        0,
    };

    task = synctask_get();
    if (!task)
        return _gf_false;

    set_lk_owner_from_ptr(&tmp_owner, (void *)this);

    if (!is_same_lkowner(&tmp_owner, &task->frame->root->lk_owner))
        return _gf_false;

    return _gf_true;
}

int
afr_ta_post_op_lock(xlator_t *this, loc_t *loc)
{
    int ret = 0;
    uuid_t gfid = {
        0,
    };
    afr_private_t *priv = this->private;
    gf_boolean_t locked = _gf_false;
    struct gf_flock flock1 = {
        0,
    };
    struct gf_flock flock2 = {
        0,
    };
    int32_t cmd = 0;

    /* Clients must take AFR_TA_DOM_NOTIFY lock only when the previous lock
     * has been released in afr_notify due to upcall notification from shd.
     */
    GF_ASSERT(priv->ta_notify_dom_lock_offset == 0);

    if (!priv->shd.iamshd)
        GF_ASSERT(afr_ta_is_fop_called_from_synctask(this));
    flock1.l_type = F_WRLCK;

    while (!locked) {
        if (priv->shd.iamshd) {
            cmd = F_SETLKW;
            flock1.l_start = 0;
            flock1.l_len = 0;
        } else {
            cmd = F_SETLK;
            gf_uuid_generate(gfid);
            flock1.l_start = gfid_to_ino(gfid);
            if (flock1.l_start < 0)
                flock1.l_start = -flock1.l_start;
            flock1.l_len = 1;
        }
        ret = syncop_inodelk(priv->children[THIN_ARBITER_BRICK_INDEX],
                             AFR_TA_DOM_NOTIFY, loc, cmd, &flock1, NULL, NULL);
        if (!ret) {
            locked = _gf_true;
            priv->ta_notify_dom_lock_offset = flock1.l_start;
        } else if (ret == -EAGAIN) {
            continue;
        } else {
            gf_msg(this->name, GF_LOG_ERROR, -ret, AFR_MSG_THIN_ARB,
                   "Failed to get "
                   "AFR_TA_DOM_NOTIFY lock on %s.",
                   loc->name);
            goto out;
        }
    }

    flock2.l_type = F_WRLCK;
    flock2.l_start = 0;
    flock2.l_len = 0;
    ret = syncop_inodelk(priv->children[THIN_ARBITER_BRICK_INDEX],
                         AFR_TA_DOM_MODIFY, loc, F_SETLKW, &flock2, NULL, NULL);
    if (ret) {
        gf_msg(this->name, GF_LOG_ERROR, -ret, AFR_MSG_THIN_ARB,
               "Failed to get AFR_TA_DOM_MODIFY lock on %s.", loc->name);
        flock1.l_type = F_UNLCK;
        ret = syncop_inodelk(priv->children[THIN_ARBITER_BRICK_INDEX],
                             AFR_TA_DOM_NOTIFY, loc, F_SETLK, &flock1, NULL,
                             NULL);
    }
out:
    return ret;
}

int
afr_ta_post_op_unlock(xlator_t *this, loc_t *loc)
{
    afr_private_t *priv = this->private;
    struct gf_flock flock = {
        0,
    };
    int ret = 0;

    if (!priv->shd.iamshd)
        GF_ASSERT(afr_ta_is_fop_called_from_synctask(this));
    flock.l_type = F_UNLCK;
    flock.l_start = 0;
    flock.l_len = 0;

    ret = syncop_inodelk(priv->children[THIN_ARBITER_BRICK_INDEX],
                         AFR_TA_DOM_MODIFY, loc, F_SETLK, &flock, NULL, NULL);
    if (ret) {
        gf_msg(this->name, GF_LOG_ERROR, -ret, AFR_MSG_THIN_ARB,
               "Failed to unlock AFR_TA_DOM_MODIFY lock.");
        goto out;
    }

    if (!priv->shd.iamshd)
        /* Mounts (clients) will not release the AFR_TA_DOM_NOTIFY lock
         * in post-op as they use it as a notification mechanism. When
         * shd sends a lock request on TA during heal, the clients will
         * receive a lock-contention upcall notification upon which they
         * will release the AFR_TA_DOM_NOTIFY lock after completing the
         * in flight I/O.*/
        goto out;

    ret = syncop_inodelk(priv->children[THIN_ARBITER_BRICK_INDEX],
                         AFR_TA_DOM_NOTIFY, loc, F_SETLK, &flock, NULL, NULL);
    if (ret) {
        gf_msg(this->name, GF_LOG_ERROR, -ret, AFR_MSG_THIN_ARB,
               "Failed to unlock AFR_TA_DOM_NOTIFY lock.");
    }
out:
    return ret;
}

call_frame_t *
afr_ta_frame_create(xlator_t *this)
{
    call_frame_t *frame = NULL;
    void *lk_owner = NULL;

    frame = create_frame(this, this->ctx->pool);
    if (!frame)
        return NULL;
    lk_owner = (void *)this;
    afr_set_lk_owner(frame, this, lk_owner);
    return frame;
}

gf_boolean_t
afr_ta_has_quorum(afr_private_t *priv, afr_local_t *local)
{
    int data_count = 0;

    data_count = AFR_COUNT(local->child_up, priv->child_count);
    if (data_count == 2) {
        return _gf_true;
    } else if (data_count == 1 && local->ta_child_up) {
        return _gf_true;
    }

    return _gf_false;
}

gf_boolean_t
afr_is_add_replica_mount_lookup_on_root(call_frame_t *frame)
{
    afr_local_t *local = NULL;

    local = frame->local;

    if (frame->root->pid != GF_CLIENT_PID_ADD_REPLICA_MOUNT)
        return _gf_false;

    if (local->op != GF_FOP_LOOKUP)
        /* TODO:If the replica count is being increased on a plain distribute
         * volume that was never mounted, we need to allow setxattr on '/' with
         * GF_CLIENT_PID_NO_ROOT_SQUASH to accomodate for DHT layout setting */
        return _gf_false;

    if (local->inode == NULL)
        return _gf_false;

    if (!__is_root_gfid(local->inode->gfid))
        return _gf_false;

    return _gf_true;
}

gf_boolean_t
afr_lookup_has_quorum(call_frame_t *frame, xlator_t *this,
                      unsigned char *subvols)
{
    afr_private_t *priv = this->private;

    if (frame && afr_is_add_replica_mount_lookup_on_root(frame)) {
        if (AFR_COUNT(subvols, priv->child_count) > 0)
            return _gf_true;
    }

    return _gf_false;
}