summaryrefslogtreecommitdiffstats
path: root/libglusterfs/src/common-utils.c
blob: b2d5a279dc860580e2c543b3dab18c946075630d (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
/*
  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.
*/

#ifdef HAVE_BACKTRACE
#include <execinfo.h>
#else
#include "execinfo_compat.h"
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <unistd.h>
#include <time.h>
#include <locale.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <assert.h>
#include <libgen.h> /* for dirname() */

#if defined(GF_BSD_HOST_OS) || defined(GF_DARWIN_HOST_OS)
#include <sys/sysctl.h>
#endif
#include <libgen.h>

#include "glusterfs-acl.h"
#include "compat-errno.h"
#include "logging.h"
#include "common-utils.h"
#include "revision.h"
#include "glusterfs.h"
#include "stack.h"
#include "globals.h"
#include "lkowner.h"
#include "syscall.h"
#include <ifaddrs.h>
#include "libglusterfs-messages.h"

#ifndef AI_ADDRCONFIG
#define AI_ADDRCONFIG 0
#endif /* AI_ADDRCONFIG */

typedef int32_t (*rw_op_t)(int32_t fd, char *buf, int32_t size);
typedef int32_t (*rwv_op_t)(int32_t fd, const struct iovec *buf, int32_t size);

void
md5_wrapper(const unsigned char *data, size_t len, char *md5)
{
        unsigned short i = 0;
        unsigned short lim = MD5_DIGEST_LENGTH*2+1;
        unsigned char scratch[MD5_DIGEST_LENGTH] = {0,};
        MD5(data, len, scratch);
        for (; i < MD5_DIGEST_LENGTH; i++)
                snprintf(md5 + i * 2, lim-i*2, "%02x", scratch[i]);
}

/* works similar to mkdir(1) -p.
 */
int
mkdir_p (char *path, mode_t mode, gf_boolean_t allow_symlinks)
{
        int             i               = 0;
        int             ret             = -1;
        char            dir[PATH_MAX]   = {0,};
        struct stat     stbuf           = {0,};

        strncpy (dir, path, (PATH_MAX - 1));
        dir[PATH_MAX - 1] = '\0';

        i = (dir[0] == '/')? 1: 0;
        do {
                if (path[i] != '/' && path[i] != '\0')
                        continue;

                dir[i] = '\0';
                ret = sys_mkdir (dir, mode);
                if (ret && errno != EEXIST) {
                        gf_msg ("", GF_LOG_ERROR, errno, LG_MSG_DIR_OP_FAILED,
                                "Failed due to reason");
                        goto out;
                }

                if (ret && errno == EEXIST && !allow_symlinks) {
                        ret = sys_lstat (dir, &stbuf);
                        if (ret)
                                goto out;

                        if (S_ISLNK (stbuf.st_mode)) {
                                ret = -1;
                                gf_msg ("", GF_LOG_ERROR, 0,
                                        LG_MSG_DIR_IS_SYMLINK, "%s is a "
                                        "symlink", dir);
                                goto out;
                        }
                }
                dir[i] = '/';

        } while (path[i++] != '\0');

        ret = sys_stat (dir, &stbuf);
        if (ret || !S_ISDIR (stbuf.st_mode)) {
                if (ret == 0)
                        errno = 0;
                ret = -1;
                gf_msg ("", GF_LOG_ERROR, errno, LG_MSG_DIR_OP_FAILED, "Failed"
                        " to create directory, possibly some of the components"
                        " were not directories");
                goto out;
        }

        ret = 0;
out:

        return ret;
}

int
gf_lstat_dir (const char *path, struct stat *stbuf_in)
{
        int ret           = -1;
        struct stat stbuf = {0,};

        if (path == NULL) {
                errno = EINVAL;
                goto out;
        }

        ret = sys_lstat (path, &stbuf);
        if (ret)
                goto out;

        if (!S_ISDIR (stbuf.st_mode)) {
                errno = ENOTDIR;
                ret = -1;
                goto out;
        }
        ret = 0;

out:
        if (!ret && stbuf_in)
                *stbuf_in = stbuf;

        return ret;
}

int
log_base2 (unsigned long x)
{
        int val = 0;

        while (x > 1) {
                x /= 2;
                val++;
        }

        return val;
}

/**
 * gf_rev_dns_lookup -- Perform a reverse DNS lookup on the IP address.
 *
 * @ip: The IP address to perform a reverse lookup on
 *
 * @return: success: Allocated string containing the hostname
 *          failure: NULL
 */
char *
gf_rev_dns_lookup (const char *ip)
{
        char               *fqdn = NULL;
        int                ret  = 0;
        struct sockaddr_in sa   = {0};
        char               host_addr[256] = {0, };

        GF_VALIDATE_OR_GOTO ("resolver", ip, out);

        sa.sin_family = AF_INET;
        inet_pton (AF_INET, ip, &sa.sin_addr);
        ret = getnameinfo ((struct sockaddr *)&sa, sizeof (sa), host_addr,
                          sizeof (host_addr), NULL, 0, 0);

        if (ret != 0) {
                gf_msg ("resolver", GF_LOG_INFO, errno,
                        LG_MSG_RESOLVE_HOSTNAME_FAILED, "could not resolve "
                        "hostname for %s", ip);
                goto out;
        }

        /* Get the FQDN */
        fqdn = gf_strdup (host_addr);

out:
       return fqdn;
}

/**
 * gf_resolve_path_parent -- Given a path, returns an allocated string
 *                           containing the parent's path.
 * @path: Path to parse
 * @return: The parent path if found, NULL otherwise
 */
char *
gf_resolve_path_parent (const char *path)
{
        char    *parent = NULL;
        char    *tmp    = NULL;
        char    *pathc  = NULL;

        GF_VALIDATE_OR_GOTO (THIS->name, path, out);

        if (strlen (path) <= 0) {
                gf_msg_callingfn (THIS->name, GF_LOG_DEBUG, 0,
                                  LG_MSG_INVALID_STRING,
                                  "invalid string for 'path'");
                goto out;
        }

        /* dup the parameter, we don't want to modify it */
        pathc = strdupa (path);
        if (!pathc) {
                goto out;
        }

        /* Get the parent directory */
        tmp = dirname (pathc);
        if (strcmp (tmp, "/") == 0)
                goto out;

        parent = gf_strdup (tmp);
out:
        return parent;
}

int32_t
gf_resolve_ip6 (const char *hostname,
                uint16_t port,
                int family,
                void **dnscache,
                struct addrinfo **addr_info)
{
        int32_t ret = 0;
        struct addrinfo hints;
        struct dnscache6 *cache = NULL;
        char service[NI_MAXSERV], host[NI_MAXHOST];

        if (!hostname) {
                gf_msg_callingfn ("resolver", GF_LOG_WARNING, 0,
                                  LG_MSG_HOSTNAME_NULL, "hostname is NULL");
                return -1;
        }

        if (!*dnscache) {
                *dnscache = GF_CALLOC (1, sizeof (struct dnscache6),
                                       gf_common_mt_dnscache6);
                if (!*dnscache)
                        return -1;
        }

        cache = *dnscache;
        if (cache->first && !cache->next) {
                freeaddrinfo(cache->first);
                cache->first = cache->next = NULL;
                gf_msg_trace ("resolver", 0, "flushing DNS cache");
        }

        if (!cache->first) {
                char *port_str = NULL;
                gf_msg_trace ("resolver", 0, "DNS cache not present, freshly "
                              "probing hostname: %s", hostname);

                memset(&hints, 0, sizeof(hints));
                hints.ai_family   = family;
                hints.ai_socktype = SOCK_STREAM;

                ret = gf_asprintf (&port_str, "%d", port);
                if (-1 == ret) {
                        return -1;
                }
                if ((ret = getaddrinfo(hostname, port_str, &hints, &cache->first)) != 0) {
                        gf_msg ("resolver", GF_LOG_ERROR, 0,
                                LG_MSG_GETADDRINFO_FAILED, "getaddrinfo failed"
                                " (%s)", gai_strerror (ret));

                        GF_FREE (*dnscache);
                        *dnscache = NULL;
                        GF_FREE (port_str);
                        return -1;
                }
                GF_FREE (port_str);

                cache->next = cache->first;
        }

        if (cache->next) {
                ret = getnameinfo((struct sockaddr *)cache->next->ai_addr,
                                  cache->next->ai_addrlen,
                                  host, sizeof (host),
                                  service, sizeof (service),
                                  NI_NUMERICHOST);
                if (ret != 0) {
                        gf_msg ("resolver", GF_LOG_ERROR, 0,
                                LG_MSG_GETNAMEINFO_FAILED, "getnameinfo failed"
                                " (%s)", gai_strerror (ret));
                        goto err;
                }

                gf_msg_debug ("resolver", 0, "returning ip-%s (port-%s) for "
                              "hostname: %s and port: %d", host, service,
                              hostname, port);

                *addr_info = cache->next;
        }

        if (cache->next)
                cache->next = cache->next->ai_next;
        if (cache->next) {
                ret = getnameinfo((struct sockaddr *)cache->next->ai_addr,
                                  cache->next->ai_addrlen,
                                  host, sizeof (host),
                                  service, sizeof (service),
                                  NI_NUMERICHOST);
                if (ret != 0) {
                        gf_msg ("resolver", GF_LOG_ERROR, 0,
                                LG_MSG_GETNAMEINFO_FAILED, "getnameinfo failed"
                                " (%s)", gai_strerror (ret));
                        goto err;
                }

                gf_msg_debug ("resolver", 0, "next DNS query will return: "
                              "ip-%s port-%s", host, service);
        }

        return 0;

err:
        freeaddrinfo (cache->first);
        cache->first = cache->next = NULL;
        GF_FREE (cache);
        *dnscache = NULL;
        return -1;
}

/**
 * gf_dnscache_init -- Initializes a dnscache struct and sets the ttl
 *                     to the specified value in the parameter.
 *
 * @ttl: the TTL in seconds
 * @return: SUCCESS: Pointer to an allocated dnscache struct
 *          FAILURE: NULL
 */
struct dnscache *
gf_dnscache_init (time_t ttl)
{
        struct dnscache *cache = GF_MALLOC (sizeof (*cache),
                                            gf_common_mt_dnscache);
        cache->cache_dict = NULL;
        cache->ttl = ttl;
        return cache;
}

/**
 * gf_dnscache_entry_init -- Initialize a dnscache entry
 *
 * @return: SUCCESS: Pointer to an allocated dnscache entry struct
 *          FAILURE: NULL
 */
struct dnscache_entry *
gf_dnscache_entry_init ()
{
        struct dnscache_entry *entry = GF_CALLOC (1, sizeof (*entry),
                                                 gf_common_mt_dnscache_entry);
        return entry;
}

/**
 * gf_dnscache_entry_deinit -- Free memory used by a dnscache entry
 *
 * @entry: Pointer to deallocate
 */
void
gf_dnscache_entry_deinit (struct dnscache_entry *entry)
{
        GF_FREE (entry->ip);
        GF_FREE (entry->fqdn);
        GF_FREE (entry);
}

/**
 * gf_rev_dns_lookup -- Perform a reverse DNS lookup on the IP address.
 *
 * @ip: The IP address to perform a reverse lookup on
 *
 * @return: success: Allocated string containing the hostname
 *          failure: NULL
 */
char *
gf_rev_dns_lookup_cached (const char *ip, struct dnscache *dnscache)
{
        char               *fqdn = NULL;
        int                ret  = 0;
        dict_t             *cache = NULL;
        data_t             *entrydata = NULL;
        struct dnscache_entry *dnsentry = NULL;
        gf_boolean_t        from_cache = _gf_false;

        if (!dnscache)
                goto out;

        if (!dnscache->cache_dict) {
                dnscache->cache_dict = dict_new ();
                if (!dnscache->cache_dict) {
                        goto out;
                }
        }
        cache = dnscache->cache_dict;

        /* Quick cache lookup to see if we already hold it */
        entrydata = dict_get (cache, (char *)ip);
        if (entrydata) {
                dnsentry = (struct dnscache_entry *)entrydata->data;
                /* First check the TTL & timestamp */
                if (time (NULL) - dnsentry->timestamp > dnscache->ttl) {
                        gf_dnscache_entry_deinit (dnsentry);
                        entrydata->data = NULL; /* Mark this as 'null' so
                                                 * dict_del () doesn't try free
                                                 * this after we've already
                                                 * freed it.
                                                 */

                        dict_del (cache, (char *)ip); /* Remove this entry */
                } else {
                        /* Cache entry is valid, get the FQDN and return */
                        fqdn = dnsentry->fqdn;
                        from_cache = _gf_true; /* Mark this as from cache */
                        goto out;
                }
        }

        /* Get the FQDN */
        ret =  gf_get_hostname_from_ip ((char *)ip, &fqdn);
        if (ret != 0)
                goto out;

        if (!fqdn) {
                gf_log_callingfn ("resolver", GF_LOG_CRITICAL,
                                  "Allocation failed for the host address");
                goto out;
        }

        from_cache = _gf_false;
out:
        /* Insert into the cache */
        if (fqdn && !from_cache) {
                struct dnscache_entry *entry = gf_dnscache_entry_init ();

                if (!entry) {
                        goto out;
                }
                entry->fqdn = fqdn;
                entry->ip = gf_strdup (ip);
                if (!ip) {
                        gf_dnscache_entry_deinit (entry);
                        goto out;
                }
                entry->timestamp = time (NULL);

                entrydata = bin_to_data (entry, sizeof (*entry));
                dict_set (cache, (char *)ip, entrydata);
        }
        return fqdn;
}

struct xldump {
	int lineno;
};

/* to catch any format discrepencies that may arise in code */
static int nprintf (struct xldump *dump, const char *fmt, ...)
                    __attribute__ ((__format__ (__printf__, 2, 3)));
static int
nprintf (struct xldump *dump, const char *fmt, ...)
{
        va_list  ap;
        char    *msg = NULL;
        char     header[32];
        int      ret = 0;

        ret = snprintf (header, 32, "%3d:", ++dump->lineno);
        if (ret < 0)
                goto out;

        va_start (ap, fmt);
        ret = vasprintf (&msg, fmt, ap);
        va_end (ap);
        if (-1 == ret)
                goto out;

        /* NOTE: No ret value from gf_msg_plain, so unable to compute printed
         * characters. The return value from nprintf is not used, so for now
         * living with it */
        gf_msg_plain (GF_LOG_WARNING, "%s %s", header, msg);

out:
        FREE (msg);
        return 0;
}


static int
xldump_options (dict_t *this, char *key, data_t *value,	void *d)
{
	nprintf (d, "    option %s %s", key, value->data);
	return 0;
}


static void
xldump_subvolumes (xlator_t *this, void *d)
{
	xlator_list_t *subv = NULL;
	int len = 0;
	char *subvstr = NULL;

	subv = this->children;
	if (!this->children)
		return;

	for (subv = this->children; subv; subv = subv->next)
		len += (strlen (subv->xlator->name) + 1);

	subvstr = GF_CALLOC (1, len, gf_common_mt_strdup);

	len = 0;
	for (subv = this->children; subv; subv= subv->next)
		len += sprintf (subvstr + len, "%s%s", subv->xlator->name,
				subv->next ? " " : "");

	nprintf (d, "    subvolumes %s", subvstr);

	GF_FREE (subvstr);
}


static void
xldump (xlator_t *each, void *d)
{
	nprintf (d, "volume %s", each->name);
	nprintf (d, "    type %s", each->type);
	dict_foreach (each->options, xldump_options, d);

	xldump_subvolumes (each, d);

	nprintf (d, "end-volume");
	nprintf (d, " ");
}


void
gf_log_dump_graph (FILE *specfp, glusterfs_graph_t *graph)
{
	struct xldump xld = {0, };

        gf_msg_plain (GF_LOG_WARNING, "Final graph:");
        gf_msg_plain (GF_LOG_WARNING,
                      "+---------------------------------------"
                      "---------------------------------------+");

	xlator_foreach_depth_first (graph->top, xldump, &xld);

        gf_msg_plain (GF_LOG_WARNING,
                      "+---------------------------------------"
                      "---------------------------------------+");
}

static void
gf_dump_config_flags ()
{
        gf_msg_plain_nomem (GF_LOG_ALERT, "configuration details:");

/* have argp */
#ifdef HAVE_ARGP
        gf_msg_plain_nomem (GF_LOG_ALERT, "argp 1");
#endif

/* ifdef if found backtrace */
#ifdef HAVE_BACKTRACE
        gf_msg_plain_nomem (GF_LOG_ALERT, "backtrace 1");
#endif

/* Berkeley-DB version has cursor->get() */
#ifdef HAVE_BDB_CURSOR_GET
        gf_msg_plain_nomem (GF_LOG_ALERT, "bdb->cursor->get 1");
#endif

/* Define to 1 if you have the <db.h> header file. */
#ifdef HAVE_DB_H
        gf_msg_plain_nomem (GF_LOG_ALERT, "db.h 1");
#endif

/* Define to 1 if you have the <dlfcn.h> header file. */
#ifdef HAVE_DLFCN_H
        gf_msg_plain_nomem (GF_LOG_ALERT, "dlfcn 1");
#endif

/* define if fdatasync exists */
#ifdef HAVE_FDATASYNC
        gf_msg_plain_nomem (GF_LOG_ALERT, "fdatasync 1");
#endif

/* Define to 1 if you have the `pthread' library (-lpthread). */
#ifdef HAVE_LIBPTHREAD
        gf_msg_plain_nomem (GF_LOG_ALERT, "libpthread 1");
#endif

/* define if llistxattr exists */
#ifdef HAVE_LLISTXATTR
        gf_msg_plain_nomem (GF_LOG_ALERT, "llistxattr 1");
#endif

/* define if found setfsuid setfsgid */
#ifdef HAVE_SET_FSID
        gf_msg_plain_nomem (GF_LOG_ALERT, "setfsid 1");
#endif

/* define if found spinlock */
#ifdef HAVE_SPINLOCK
        gf_msg_plain_nomem (GF_LOG_ALERT, "spinlock 1");
#endif

/* Define to 1 if you have the <sys/epoll.h> header file. */
#ifdef HAVE_SYS_EPOLL_H
        gf_msg_plain_nomem (GF_LOG_ALERT, "epoll.h 1");
#endif

/* Define to 1 if you have the <sys/extattr.h> header file. */
#ifdef HAVE_SYS_EXTATTR_H
        gf_msg_plain_nomem (GF_LOG_ALERT, "extattr.h 1");
#endif

/* Define to 1 if you have the <sys/xattr.h> header file. */
#ifdef HAVE_SYS_XATTR_H
        gf_msg_plain_nomem (GF_LOG_ALERT, "xattr.h 1");
#endif

/* define if found st_atim.tv_nsec */
#ifdef HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC
        gf_msg_plain_nomem (GF_LOG_ALERT, "st_atim.tv_nsec 1");
#endif

/* define if found st_atimespec.tv_nsec */
#ifdef HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC
        gf_msg_plain_nomem (GF_LOG_ALERT, "st_atimespec.tv_nsec 1");
#endif

/* Define to the full name and version of this package. */
#ifdef PACKAGE_STRING
        {
                char msg[128];
                sprintf (msg, "package-string: %s", PACKAGE_STRING);
                gf_msg_plain_nomem (GF_LOG_ALERT, msg);
        }
#endif

        return;
}

/* Obtain a backtrace and print it to the log */
void
gf_print_trace (int32_t signum, glusterfs_ctx_t *ctx)
{
        char         msg[1024] = {0,};
        char         timestr[64] = {0,};
        call_stack_t *stack = NULL;

        /* Now every gf_log call will just write to a buffer and when the
         * buffer becomes full, its written to the log-file. Suppose the process
         * crashes and prints the backtrace in the log-file, then the previous
         * log information will still be in the buffer itself. So flush the
         * contents of the buffer to the log file before printing the backtrace
         * which helps in debugging.
         */
        gf_log_flush();

        gf_log_disable_suppression_before_exit (ctx);

        /* Pending frames, (if any), list them in order */
        gf_msg_plain_nomem (GF_LOG_ALERT, "pending frames:");
        {
                /* FIXME: traversing stacks outside pool->lock */
                list_for_each_entry (stack, &ctx->pool->all_frames,
                                     all_frames) {
                        if (stack->type == GF_OP_TYPE_FOP)
                                sprintf (msg,"frame : type(%d) op(%s)",
                                         stack->type,
                                         gf_fop_list[stack->op]);
                        else
                                sprintf (msg,"frame : type(%d) op(%d)",
                                         stack->type,
                                         stack->op);

                        gf_msg_plain_nomem (GF_LOG_ALERT, msg);
                }
        }

        sprintf (msg, "patchset: %s", GLUSTERFS_REPOSITORY_REVISION);
        gf_msg_plain_nomem (GF_LOG_ALERT, msg);

        sprintf (msg, "signal received: %d", signum);
        gf_msg_plain_nomem (GF_LOG_ALERT, msg);
        {
                /* Dump the timestamp of the crash too, so the previous logs
                   can be related */
                gf_time_fmt (timestr, sizeof timestr, time (NULL),
                             gf_timefmt_FT);
                gf_msg_plain_nomem (GF_LOG_ALERT, "time of crash: ");
                gf_msg_plain_nomem (GF_LOG_ALERT, timestr);
        }

        gf_dump_config_flags ();
        gf_msg_backtrace_nomem (GF_LOG_ALERT, 200);
        sprintf (msg, "---------");
        gf_msg_plain_nomem (GF_LOG_ALERT, msg);

        /* Send a signal to terminate the process */
        signal (signum, SIG_DFL);
        raise (signum);
}

void
trap (void)
{

}

char *
gf_trim (char *string)
{
        register char *s, *t;

        if (string == NULL) {
                return NULL;
        }

        for (s = string; isspace (*s); s++)
                ;

        if (*s == 0)
                return s;

        t = s + strlen (s) - 1;
        while (t > s && isspace (*t))
                t--;
        *++t = '\0';

        return s;
}

int
gf_strsplit (const char *str, const char *delim,
             char ***tokens, int *token_count)
{
        char *_running = NULL;
        char *running = NULL;
        char *token = NULL;
        char **token_list = NULL;
        int count = 0;
        int i = 0;
        int j = 0;

        if (str == NULL || delim == NULL || tokens == NULL || token_count == NULL) {
                gf_msg_callingfn (THIS->name, GF_LOG_WARNING, EINVAL,
                                  LG_MSG_INVALID_ARG, "argument invalid");
                return -1;
        }

        _running = gf_strdup (str);
        if (_running == NULL)
                return -1;

        running = _running;

        while ((token = strsep (&running, delim)) != NULL) {
                if (token[0] != '\0')
                        count++;
        }
        GF_FREE (_running);

        _running = gf_strdup (str);
        if (_running == NULL)
                return -1;

        running = _running;

        if ((token_list = GF_CALLOC (count, sizeof (char *),
                                     gf_common_mt_char)) == NULL) {
                GF_FREE (_running);
                return -1;
        }

        while ((token = strsep (&running, delim)) != NULL) {
                if (token[0] == '\0')
                        continue;

                token_list[i] = gf_strdup (token);
                if (token_list[i] == NULL)
                        goto free_exit;
                i++;
        }

        GF_FREE (_running);

        *tokens = token_list;
        *token_count = count;
        return 0;

free_exit:
        GF_FREE (_running);
        for (j = 0; j < i; j++)
                GF_FREE (token_list[j]);

        GF_FREE (token_list);
        return -1;
}

int
gf_strstr (const char *str, const char *delim, const char *match)
{
        char *tmp      = NULL;
        char *save_ptr = NULL;
        char *tmp_str  = NULL;

        int  ret       = 0;

        tmp_str = strdup (str);

        if (str == NULL || delim == NULL || match == NULL || tmp_str == NULL) {
                gf_msg_callingfn (THIS->name, GF_LOG_WARNING, EINVAL,
                                  LG_MSG_INVALID_ARG, "argument invalid");
                ret = -1;
                goto out;
        }


        tmp = strtok_r (tmp_str, delim, &save_ptr);

        while (tmp) {
                ret = strcmp (tmp, match);

                if (ret == 0)
                        break;

                tmp = strtok_r (NULL, delim, &save_ptr);
        }

out:
        free (tmp_str);

        return ret;

}

int
gf_volume_name_validate (const char *volume_name)
{
        const char *vname = NULL;

        if (volume_name == NULL) {
                gf_msg_callingfn (THIS->name, GF_LOG_WARNING, EINVAL,
                                  LG_MSG_INVALID_ARG, "argument invalid");
                return -1;
        }

        if (!isalpha (volume_name[0]))
                return 1;

        for (vname = &volume_name[1]; *vname != '\0'; vname++) {
                if (!(isalnum (*vname) || *vname == '_'))
                        return 1;
        }

        return 0;
}


int
gf_string2time (const char *str, uint32_t *n)
{
        unsigned long value = 0;
        char *tail = NULL;
        int old_errno = 0;
        const char *s = NULL;

        if (str == NULL || n == NULL) {
                gf_msg_callingfn (THIS->name, GF_LOG_WARNING, EINVAL,
                                  LG_MSG_INVALID_ARG, "argument invalid");
                errno = EINVAL;
                return -1;
        }

        for (s = str; *s != '\0'; s++) {
                if (isspace (*s))
                        continue;
                if (*s == '-')
                        return -1;
                break;
        }

        old_errno = errno;
        errno = 0;
        value = strtol (str, &tail, 0);
        if (str == tail)
                errno = EINVAL;

        if (errno == ERANGE || errno == EINVAL)
                return -1;

        if (errno == 0)
                errno = old_errno;

        if (((tail[0] == '\0') ||
              ((tail[0] == 's') && (tail[1] == '\0')) ||
              ((tail[0] == 's') && (tail[1] == 'e') &&
	       (tail[2] == 'c') && (tail[3] == '\0'))))
               goto out;

        else if (((tail[0] == 'm') && (tail[1] == '\0')) ||
                 ((tail[0] == 'm') && (tail[1] == 'i') &&
                  (tail[2] == 'n') && (tail[3] == '\0'))) {
                value = value * GF_MINUTE_IN_SECONDS;
                goto out;
        }

        else if (((tail[0] == 'h') && (tail[1] == '\0')) ||
                 ((tail[0] == 'h') && (tail[1] == 'r') &&
	         (tail[2] == '\0'))) {
                value = value * GF_HOUR_IN_SECONDS;
                goto out;
        }

        else if (((tail[0] == 'd') && (tail[1] == '\0')) ||
                 ((tail[0] == 'd') && (tail[1] == 'a') &&
	         (tail[2] == 'y') && (tail[3] == 's') &&
                 (tail[4] == '\0'))) {
                value = value * GF_DAY_IN_SECONDS;
                goto out;
        }

        else if (((tail[0] == 'w') && (tail[1] == '\0')) ||
                 ((tail[0] == 'w') && (tail[1] == 'k') &&
	         (tail[2] == '\0'))) {
                value = value * GF_WEEK_IN_SECONDS;
                goto out;
        } else {
                return -1;
        }

out:
        *n = value;

        return 0;
}

int
gf_string2percent (const char *str, double *n)
{
        double value = 0;
        char *tail = NULL;
        int old_errno = 0;
        const char *s = NULL;

        if (str == NULL || n == NULL) {
                gf_msg_callingfn (THIS->name, GF_LOG_WARNING, EINVAL,
                                  LG_MSG_INVALID_ARG, "argument invalid");
                errno = EINVAL;
                return -1;
        }

        for (s = str; *s != '\0'; s++) {
                if (isspace (*s))
                        continue;
                if (*s == '-')
                        return -1;
                break;
        }

        old_errno = errno;
        errno = 0;
        value = strtod (str, &tail);
        if (str == tail)
                errno = EINVAL;

        if (errno == ERANGE || errno == EINVAL)
                return -1;

        if (errno == 0)
                errno = old_errno;

        if (!((tail[0] == '\0') ||
              ((tail[0] == '%') && (tail[1] == '\0'))))
                return -1;

        *n = value;

        return 0;
}


static int
_gf_string2long (const char *str, long *n, int base)
{
        long value = 0;
        char *tail = NULL;
        int old_errno = 0;

        if (str == NULL || n == NULL) {
                gf_msg_callingfn (THIS->name, GF_LOG_WARNING, EINVAL,
                                  LG_MSG_INVALID_ARG, "argument invalid");
                errno = EINVAL;
                return -1;
        }

        old_errno = errno;
        errno = 0;
        value = strtol (str, &tail, base);
        if (str == tail)
                errno = EINVAL;

        if (errno == ERANGE || errno == EINVAL)
                return -1;

        if (errno == 0)
                errno = old_errno;

        if (tail[0] != '\0')
                return -1;

        *n = value;

        return 0;
}

static int
_gf_string2ulong (const char *str, unsigned long *n, int base)
{
        unsigned long value = 0;
        char *tail = NULL;
        int old_errno = 0;
        const char *s = NULL;

        if (str == NULL || n == NULL) {
                gf_msg_callingfn (THIS->name, GF_LOG_WARNING, EINVAL,
                                  LG_MSG_INVALID_ARG, "argument invalid");
                errno = EINVAL;
                return -1;
        }

        for (s = str; *s != '\0'; s++) {
                if (isspace (*s))
                        continue;
                if (*s == '-')
                        return -1;
                break;
        }

        old_errno = errno;
        errno = 0;
        value = strtoul (str, &tail, base);
        if (str == tail)
                errno = EINVAL;

        if (errno == ERANGE || errno == EINVAL)
                return -1;

        if (errno == 0)
                errno = old_errno;

        if (tail[0] != '\0')
                return -1;

        *n = value;

        return 0;
}

static int
_gf_string2uint (const char *str, unsigned int *n, int base)
{
        unsigned long value = 0;
        char *tail = NULL;
        int old_errno = 0;
        const char *s = NULL;

        if (str == NULL || n == NULL) {
                gf_msg_callingfn (THIS->name, GF_LOG_WARNING, EINVAL,
                                  LG_MSG_INVALID_ARG, "argument invalid");
                errno = EINVAL;
                return -1;
        }

        for (s = str; *s != '\0'; s++) {
                if (isspace (*s))
                        continue;
                if (*s == '-')
                        return -1;
                break;
        }

        old_errno = errno;
        errno = 0;
        value = strtoul (str, &tail, base);
        if (str == tail)
                errno = EINVAL;

        if (errno == ERANGE || errno == EINVAL)
                return -1;

        if (errno == 0)
                errno = old_errno;

        if (tail[0] != '\0')
                return -1;

        *n = (unsigned int)value;

        return 0;
}

static int
_gf_string2double (const char *str, double *n)
{
        double value     = 0.0;
        char   *tail     = NULL;
        int    old_errno = 0;

        if (str == NULL || n == NULL) {
                gf_msg_callingfn (THIS->name, GF_LOG_WARNING, EINVAL,
                                  LG_MSG_INVALID_ARG, "argument invalid");
                errno = EINVAL;
                return -1;
        }

        old_errno = errno;
        errno = 0;
        value = strtod (str, &tail);
        if (str == tail)
                errno = EINVAL;

        if (errno == ERANGE || errno == EINVAL)
                return -1;

        if (errno == 0)
                errno = old_errno;

        if (tail[0] != '\0')
                return -1;

        *n = value;

        return 0;
}

static int
_gf_string2longlong (const char *str, long long *n, int base)
{
        long long value = 0;
        char *tail = NULL;
        int old_errno = 0;

        if (str == NULL || n == NULL) {
                gf_msg_callingfn (THIS->name, GF_LOG_WARNING, EINVAL,
                                  LG_MSG_INVALID_ARG, "argument invalid");
                errno = EINVAL;
                return -1;
        }

        old_errno = errno;
        errno = 0;
        value = strtoll (str, &tail, base);
        if (str == tail)
                errno = EINVAL;

        if (errno == ERANGE || errno == EINVAL)
                return -1;

        if (errno == 0)
                errno = old_errno;

        if (tail[0] != '\0')
                return -1;

        *n = value;

        return 0;
}

static int
_gf_string2ulonglong (const char *str, unsigned long long *n, int base)
{
        unsigned long long value = 0;
        char *tail = NULL;
        int old_errno = 0;
        const char *s = NULL;

        if (str == NULL || n == NULL) {
                gf_msg_callingfn (THIS->name, GF_LOG_WARNING, EINVAL,
                                  LG_MSG_INVALID_ARG, "argument invalid");
                errno = EINVAL;
                return -1;
        }

        for (s = str; *s != '\0'; s++) {
                if (isspace (*s))
                        continue;
                if (*s == '-')
                        return -1;
                break;
        }

        old_errno = errno;
        errno = 0;
        value = strtoull (str, &tail, base);
        if (str == tail)
                errno = EINVAL;

        if (errno == ERANGE || errno == EINVAL)
                return -1;

        if (errno == 0)
                errno = old_errno;

        if (tail[0] != '\0')
                return -1;

        *n = value;

        return 0;
}

int
gf_string2long (const char *str, long *n)
{
        return _gf_string2long (str, n, 0);
}

int
gf_string2ulong (const char *str, unsigned long *n)
{
        return _gf_string2ulong (str, n, 0);
}

int
gf_string2int (const char *str, int *n)
{
        long l = 0;
        int  ret = 0;

        ret = _gf_string2long (str, &l, 0);

        *n = l;
        return ret;
}

int
gf_string2uint (const char *str, unsigned int *n)
{
        return _gf_string2uint (str, n, 0);
}

int
gf_string2double (const char *str, double *n)
{
        return _gf_string2double (str, n);
}

int
gf_string2longlong (const char *str, long long *n)
{
        return _gf_string2longlong (str, n, 0);
}

int
gf_string2ulonglong (const char *str, unsigned long long *n)
{
        return _gf_string2ulonglong (str, n, 0);
}

int
gf_string2int8 (const char *str, int8_t *n)
{
        long l = 0L;
        int rv = 0;

        rv = _gf_string2long (str, &l, 0);
        if (rv != 0)
                return rv;

        if ((l >= INT8_MIN) && (l <= INT8_MAX)) {
                *n = (int8_t) l;
                return 0;
        }

        errno = ERANGE;
        return -1;
}

int
gf_string2int16 (const char *str, int16_t *n)
{
        long l = 0L;
        int rv = 0;

        rv = _gf_string2long (str, &l, 0);
        if (rv != 0)
                return rv;

        if ((l >= INT16_MIN) && (l <= INT16_MAX)) {
                *n = (int16_t) l;
                return 0;
        }

        errno = ERANGE;
        return -1;
}

int
gf_string2int32 (const char *str, int32_t *n)
{
        long l = 0L;
        int rv = 0;

        rv = _gf_string2long (str, &l, 0);
        if (rv != 0)
                return rv;

        if ((l >= INT32_MIN) && (l <= INT32_MAX)) {
                *n = (int32_t) l;
                return 0;
        }

        errno = ERANGE;
        return -1;
}

int
gf_string2int64 (const char *str, int64_t *n)
{
        long long l = 0LL;
        int rv = 0;

        rv = _gf_string2longlong (str, &l, 0);
        if (rv != 0)
                return rv;

        if (l <= INT64_MAX) {
                *n = (int64_t) l;
                return 0;
        }

        errno = ERANGE;
        return -1;
}

int
gf_string2uint8 (const char *str, uint8_t *n)
{
        unsigned long l = 0L;
        int rv = 0;

        rv = _gf_string2ulong (str, &l, 0);
        if (rv != 0)
                return rv;

        if (l <= UINT8_MAX) {
                *n = (uint8_t) l;
                return 0;
        }

        errno = ERANGE;
        return -1;
}

int
gf_string2uint16 (const char *str, uint16_t *n)
{
        unsigned long l = 0L;
        int rv = 0;

        rv = _gf_string2ulong (str, &l, 0);
        if (rv != 0)
                return rv;

        if (l <= UINT16_MAX) {
                *n = (uint16_t) l;
                return 0;
        }

        errno = ERANGE;
        return -1;
}

int
gf_string2uint32 (const char *str, uint32_t *n)
{
        unsigned long l = 0L;
        int rv = 0;

        rv = _gf_string2ulong (str, &l, 0);
        if (rv != 0)
                return rv;

	if (l <= UINT32_MAX) {
                *n = (uint32_t) l;
                return 0;
        }

        errno = ERANGE;
        return -1;
}

int
gf_string2uint64 (const char *str, uint64_t *n)
{
        unsigned long long l = 0ULL;
        int rv = 0;

        rv = _gf_string2ulonglong (str, &l, 0);
        if (rv != 0)
                return rv;

        if (l <= UINT64_MAX) {
                *n = (uint64_t) l;
                return 0;
        }

        errno = ERANGE;
        return -1;
}

int
gf_string2ulong_base10 (const char *str, unsigned long *n)
{
        return _gf_string2ulong (str, n, 10);
}

int
gf_string2uint_base10 (const char *str, unsigned int *n)
{
        return _gf_string2uint (str,  n, 10);
}

int
gf_string2uint8_base10 (const char *str, uint8_t *n)
{
        unsigned long l = 0L;
        int rv = 0;

        rv = _gf_string2ulong (str, &l, 10);
        if (rv != 0)
                return rv;

        if (l <= UINT8_MAX) {
                *n = (uint8_t) l;
                return 0;
        }

        errno = ERANGE;
        return -1;
}

int
gf_string2uint16_base10 (const char *str, uint16_t *n)
{
        unsigned long l = 0L;
        int rv = 0;

        rv = _gf_string2ulong (str, &l, 10);
        if (rv != 0)
                return rv;

        if (l <= UINT16_MAX) {
                *n = (uint16_t) l;
                return 0;
        }

        errno = ERANGE;
        return -1;
}

int
gf_string2uint32_base10 (const char *str, uint32_t *n)
{
        unsigned long l = 0L;
        int rv = 0;

        rv = _gf_string2ulong (str, &l, 10);
        if (rv != 0)
                return rv;

        if (l <= UINT32_MAX) {
                *n = (uint32_t) l;
                return 0;
        }

        errno = ERANGE;
        return -1;
}

int
gf_string2uint64_base10 (const char *str, uint64_t *n)
{
        unsigned long long l = 0ULL;
        int rv = 0;

        rv = _gf_string2ulonglong (str, &l, 10);
        if (rv != 0)
                return rv;

        if (l <= UINT64_MAX) {
                *n = (uint64_t) l;
                return 0;
        }

        errno = ERANGE;
        return -1;
}

char *
gf_uint64_2human_readable (uint64_t n)
{
        int   ret = 0;
        char *str = NULL;

        if (n >= GF_UNIT_PB) {
                ret = gf_asprintf (&str, "%.1lfPB", ((double) n)/GF_UNIT_PB);
                if (ret < 0)
                        goto err;
        } else if (n >= GF_UNIT_TB) {
                ret = gf_asprintf (&str, "%.1lfTB", ((double) n)/GF_UNIT_TB);
                if (ret < 0)
                        goto err;
        } else if (n >= GF_UNIT_GB) {
                ret = gf_asprintf (&str, "%.1lfGB", ((double) n)/GF_UNIT_GB);
                if (ret < 0)
                        goto err;
        } else if (n >= GF_UNIT_MB) {
                ret = gf_asprintf (&str, "%.1lfMB", ((double) n)/GF_UNIT_MB);
                if (ret < 0)
                        goto err;
        } else if (n >= GF_UNIT_KB) {
                ret = gf_asprintf (&str, "%.1lfKB", ((double) n)/GF_UNIT_KB);
                if (ret < 0)
                        goto err;
        } else {
                ret = gf_asprintf (&str, "%luBytes", n);
                if (ret < 0)
                        goto err;
        }
        return str;
err:
        return NULL;
}

int
gf_string2bytesize_range (const char *str, uint64_t *n, uint64_t umax)
{
        double        value      = 0.0;
        int64_t       int_value  = 0;
        uint64_t      unit       = 0;
        int64_t       max        = 0;
        char         *tail       = NULL;
        int           old_errno  = 0;
        const char   *s          = NULL;
        gf_boolean_t  fraction   = _gf_false;

        if (str == NULL || n == NULL) {
                gf_msg_callingfn (THIS->name, GF_LOG_WARNING, EINVAL,
                                  LG_MSG_INVALID_ARG, "argument invalid");
                errno = EINVAL;
                return -1;
        }

        max = umax & 0x7fffffffffffffffLL;

        for (s = str; *s != '\0'; s++) {
                if (isspace (*s))
                        continue;
                if (*s == '-')
                        return -1;
                break;
        }

        if (strrchr (str, '.'))
                fraction = _gf_true;

        old_errno = errno;
        errno = 0;
        if (fraction)
                value = strtod (str, &tail);
        else
                int_value = strtoll (str, &tail, 10);

        if (str == tail)
                errno = EINVAL;

        if (errno == ERANGE || errno == EINVAL)
                return -1;

        if (errno == 0)
                errno = old_errno;

        if (tail[0] != '\0')
        {
                if (strcasecmp (tail, GF_UNIT_KB_STRING) == 0)
                        unit = GF_UNIT_KB;
                else if (strcasecmp (tail, GF_UNIT_MB_STRING) == 0)
                        unit = GF_UNIT_MB;
                else if (strcasecmp (tail, GF_UNIT_GB_STRING) == 0)
                        unit = GF_UNIT_GB;
                else if (strcasecmp (tail, GF_UNIT_TB_STRING) == 0)
                        unit = GF_UNIT_TB;
                else if (strcasecmp (tail, GF_UNIT_PB_STRING) == 0)
                        unit = GF_UNIT_PB;
                else if (strcasecmp (tail, GF_UNIT_B_STRING) != 0)
                        return -1;

                if (unit > 0) {
                        if (fraction)
                                value *= unit;
                        else
                                int_value *= unit;
                }
        }

        if (fraction) {
                if ((max - value) < 0) {
                        errno = ERANGE;
                        return -1;
                }
                *n = (uint64_t) value;
        } else {
                if ((max - int_value) < 0) {
                        errno = ERANGE;
                        return -1;
                }
                *n = int_value;
        }

        return 0;
}

int
gf_string2bytesize_size (const char *str, size_t *n)
{
        uint64_t u64;
        size_t max = (size_t) - 1;
        int val = gf_string2bytesize_range (str, &u64, max);
        *n = (size_t) u64;
        return val;
}

int
gf_string2bytesize (const char *str, uint64_t *n)
{
        return gf_string2bytesize_range(str, n, UINT64_MAX);
}

int
gf_string2bytesize_uint64 (const char *str, uint64_t *n)
{
        return gf_string2bytesize_range(str, n, UINT64_MAX);
}

int
gf_string2bytesize_int64 (const char *str, int64_t *n)
{
        uint64_t u64 = 0;
        int      ret = 0;

        ret = gf_string2bytesize_range(str, &u64, INT64_MAX);
        *n = (int64_t) u64;
        return ret;
}

int
gf_string2percent_or_bytesize (const char *str, double *n,
			       gf_boolean_t *is_percent)
{
        double value = 0ULL;
        char *tail = NULL;
        int old_errno = 0;
        const char *s = NULL;

        if (str == NULL || n == NULL) {
                gf_msg_callingfn (THIS->name, GF_LOG_WARNING, EINVAL,
                                  LG_MSG_INVALID_ARG, "argument invalid");
                errno = EINVAL;
                return -1;
        }

        for (s = str; *s != '\0'; s++) {
                if (isspace (*s))
                        continue;
                if (*s == '-')
                        return -1;
                break;
        }

        old_errno = errno;
        errno = 0;
        value = strtod (str, &tail);
        if (str == tail)
                errno = EINVAL;

        if (errno == ERANGE || errno == EINVAL)
                return -1;

        if (errno == 0)
                errno = old_errno;

        /*Maximum accepted value for 64 bit OS will be (2^14 -1)PB*/
        if (tail[0] != '\0') {
                if (strcasecmp (tail, GF_UNIT_KB_STRING) == 0)
                        value *= GF_UNIT_KB;
                else if (strcasecmp (tail, GF_UNIT_MB_STRING) == 0)
                        value *= GF_UNIT_MB;
                else if (strcasecmp (tail, GF_UNIT_GB_STRING) == 0)
                        value *= GF_UNIT_GB;
                else if (strcasecmp (tail, GF_UNIT_TB_STRING) == 0)
                        value *= GF_UNIT_TB;
                else if (strcasecmp (tail, GF_UNIT_PB_STRING) == 0)
                        value *= GF_UNIT_PB;
		else if (strcasecmp (tail, GF_UNIT_PERCENT_STRING) == 0)
			*is_percent = _gf_true;
                else
                        return -1;
        }

        /* Error out if we cannot store the value in uint64 */
        if ((UINT64_MAX - value) < 0) {
                errno = ERANGE;
                return -1;
        }

        *n = value;

        return 0;
}

int64_t
gf_str_to_long_long (const char *number)
{
        int64_t unit = 1;
        int64_t ret = 0;
        char *endptr = NULL ;
        if (!number)
                return 0;

        ret = strtoll (number, &endptr, 0);

        if (endptr) {
                switch (*endptr) {
                case 'G':
                case 'g':
                        if ((* (endptr + 1) == 'B') ||(* (endptr + 1) == 'b'))
                                unit = 1024 * 1024 * 1024;
                        break;
                case 'M':
                case 'm':
                        if ((* (endptr + 1) == 'B') ||(* (endptr + 1) == 'b'))
                                unit = 1024 * 1024;
                        break;
                case 'K':
                case 'k':
                        if ((* (endptr + 1) == 'B') ||(* (endptr + 1) == 'b'))
                                unit = 1024;
                        break;
                case '%':
                        unit = 1;
                        break;
                default:
                        unit = 1;
                        break;
                }
        }
        return ret * unit;
}

int
gf_string2boolean (const char *str, gf_boolean_t *b)
{
        if (str == NULL) {
                gf_msg_callingfn (THIS->name, GF_LOG_WARNING, EINVAL,
                                  LG_MSG_INVALID_ARG, "argument invalid");
                return -1;
        }

        if ((strcasecmp (str, "1") == 0) ||
            (strcasecmp (str, "on") == 0) ||
            (strcasecmp (str, "yes") == 0) ||
            (strcasecmp (str, "true") == 0) ||
            (strcasecmp (str, "enable") == 0)) {
                *b = _gf_true;
                return 0;
        }

        if ((strcasecmp (str, "0") == 0) ||
            (strcasecmp (str, "off") == 0) ||
            (strcasecmp (str, "no") == 0) ||
            (strcasecmp (str, "false") == 0) ||
            (strcasecmp (str, "disable") == 0)) {
                *b = _gf_false;
                return 0;
        }

        return -1;
}


int
gf_lockfd (int fd)
{
        struct gf_flock fl;

        fl.l_type = F_WRLCK;
        fl.l_whence = SEEK_SET;
        fl.l_start = 0;
        fl.l_len = 0;

        return fcntl (fd, F_SETLK, &fl);
}


int
gf_unlockfd (int fd)
{
        struct gf_flock fl;

        fl.l_type = F_UNLCK;
        fl.l_whence = SEEK_SET;
        fl.l_start = 0;
        fl.l_len = 0;

        return fcntl (fd, F_SETLK, &fl);
}

static void
compute_checksum (char *buf, size_t size, uint32_t *checksum)
{
        int  ret = -1;
        char *checksum_buf = NULL;

        checksum_buf = (char *)(checksum);

        if (!(*checksum)) {
                checksum_buf [0] = 0xba;
                checksum_buf [1] = 0xbe;
                checksum_buf [2] = 0xb0;
                checksum_buf [3] = 0x0b;
        }

        for (ret = 0; ret < (size - 4); ret += 4) {
                checksum_buf[0] ^= (buf[ret]);
                checksum_buf[1] ^= (buf[ret + 1] << 1) ;
                checksum_buf[2] ^= (buf[ret + 2] << 2);
                checksum_buf[3] ^= (buf[ret + 3] << 3);
        }

        for (ret = 0; ret <= (size % 4); ret++) {
                checksum_buf[ret] ^= (buf[(size - 4) + ret] << ret);
        }

        return;
}

#define GF_CHECKSUM_BUF_SIZE 1024

int
get_checksum_for_file (int fd, uint32_t *checksum)
{
        int ret = -1;
        char buf[GF_CHECKSUM_BUF_SIZE] = {0,};

        /* goto first place */
        sys_lseek (fd, 0L, SEEK_SET);
        do {
                ret = sys_read (fd, &buf, GF_CHECKSUM_BUF_SIZE);
                if (ret > 0)
                        compute_checksum (buf, GF_CHECKSUM_BUF_SIZE,
                                          checksum);
        } while (ret > 0);

        /* set it back */
        sys_lseek (fd, 0L, SEEK_SET);

        return ret;
}


int
get_checksum_for_path (char *path, uint32_t *checksum)
{
        int     ret = -1;
        int     fd = -1;

        GF_ASSERT (path);
        GF_ASSERT (checksum);

        fd = open (path, O_RDWR);

        if (fd == -1) {
                gf_msg (THIS->name, GF_LOG_ERROR, errno, LG_MSG_PATH_ERROR,
                        "Unable to open %s", path);
                goto out;
        }

        ret = get_checksum_for_file (fd, checksum);

out:
        if (fd != -1)
                sys_close (fd);

        return ret;
}

/**
 * get_file_mtime -- Given a path, get the mtime for the file
 *
 * @path: The filepath to check the mtime on
 * @stamp: The parameter to set after we get the mtime
 *
 * @returns: success: 0
 *           errors : Errors returned by the stat () call
 */
int
get_file_mtime (const char *path, time_t *stamp)
{
        struct stat     f_stat  = {0};
        int             ret     = -EINVAL;

        GF_VALIDATE_OR_GOTO (THIS->name, path, out);
        GF_VALIDATE_OR_GOTO (THIS->name, stamp, out);

        ret = sys_stat (path, &f_stat);
        if (ret < 0) {
                gf_msg (THIS->name, GF_LOG_ERROR, errno,
                        LG_MSG_FILE_STAT_FAILED, "failed to stat %s",
                        path);
                goto out;
        }

        /* Set the mtime */
        *stamp = f_stat.st_mtime;
out:
        return ret;
}

/**
 * gf_is_ip_in_net -- Checks if an IP Address is in a network.
 *                    A network should be specified by something like
 *                    '10.5.153.0/24' (in CIDR notation).
 *
 * @result : Sets to true if the IP is in the network
 * @ip_str : The IP to check
 * @network: The network to check the IP against.
 *
 * @return: success: 0
 *          failure: -EINVAL for bad args, retval of inet_pton otherwise
 */
gf_boolean_t
gf_is_ip_in_net (const char *network, const char *ip_str)
{
        unsigned long ip_buf       = 0;
        unsigned long net_ip_buf   = 0;
        unsigned long subnet_mask  = 0;
        int           ret          = -EINVAL;
        char          *slash       = NULL;
        char          *net_ip      = NULL;
        char          *subnet      = NULL;
        char          *net_str     = NULL;
        int           family       = AF_INET;
        gf_boolean_t  result       = _gf_false;

        GF_ASSERT (network);
        GF_ASSERT (ip_str);

        if (strchr (network, ':'))
                family = AF_INET6;
        else if (strchr (network, '.'))
                family = AF_INET;
        else {
                family = -1;
                goto out;
        }

        net_str = strdupa (network);
        slash = strchr (net_str, '/');
        if (!slash)
                goto out;
        *slash = '\0';

        subnet = slash + 1;
        net_ip = net_str;

        /* Convert IP address to a long */
        ret = inet_pton (family, ip_str, &ip_buf);
        if (ret < 0)
                gf_msg ("common-utils", GF_LOG_ERROR, errno,
                        LG_MSG_INET_PTON_FAILED, "inet_pton() failed");

        /* Convert network IP address to a long */
        ret = inet_pton (family, net_ip, &net_ip_buf);
        if (ret < 0) {
                gf_msg ("common-utils", GF_LOG_ERROR, errno,
                        LG_MSG_INET_PTON_FAILED, "inet_pton() failed");
                goto out;
        }

        /* Converts /x into a mask */
        subnet_mask = (1 << atoi (subnet)) - 1;

        result = ((ip_buf & subnet_mask) == (net_ip_buf & subnet_mask));
out:
        return result;
}

char *
strtail (char *str, const char *pattern)
{
        int i = 0;

        for (i = 0; str[i] == pattern[i] && str[i]; i++);

        if (pattern[i] == '\0')
                return str + i;

        return NULL;
}

void
skipwhite (char **s)
{
        while (isspace (**s))
                (*s)++;
}

char *
nwstrtail (char *str, char *pattern)
{
        for (;;) {
                skipwhite (&str);
                skipwhite (&pattern);

                if (*str != *pattern || !*str)
                        break;

                str++;
                pattern++;
        }

        return *pattern ? NULL : str;
}

void
skipword (char **s)
{
        if (!*s)
                return;

        skipwhite (s);

        while (!isspace(**s))
                (*s)++;
}

char *
get_nth_word (const char *str, int n)
{
        char           buf[4096] = {0};
        char          *start     = NULL;
        char          *word      = NULL;
        int            i         = 0;
        int            word_len  = 0;
        const char    *end       = NULL;

        if (!str)
                goto out;

        snprintf (buf, sizeof (buf), "%s", str);
        start = buf;

        for (i = 0; i < n-1; i++)
                skipword (&start);

        skipwhite (&start);
        end = strpbrk ((const char *)start, " \t\n\0");

        if (!end)
                goto out;

        word_len = labs (end - start);

        word = GF_CALLOC (1, word_len + 1, gf_common_mt_strdup);
        if (!word)
                goto out;

        strncpy (word, start, word_len);
        *(word + word_len) = '\0';
 out:
        return word;
}

/* Syntax formed according to RFC 1912 (RFC 1123 & 952 are more restrictive)  *
   <hname> ::= <gen-name>*["."<gen-name>]                                     *
   <gen-name> ::= <let-or-digit> <[*[<let-or-digit-or-hyphen>]<let-or-digit>] */
char
valid_host_name (char *address, int length)
{
        int             i = 0;
        int             str_len = 0;
        char            ret = 1;
        char            *dup_addr = NULL;
        char            *temp_str = NULL;
        char            *save_ptr = NULL;

        if ((length > _POSIX_HOST_NAME_MAX) || (length < 1)) {
                ret = 0;
                goto out;
        }

        dup_addr = gf_strdup (address);
        if (!dup_addr) {
                ret = 0;
                goto out;
        }

        if (!isalnum (dup_addr[length - 1]) && (dup_addr[length - 1] != '*')) {
                ret = 0;
                goto out;
        }

        /* Check for consecutive dots, which is invalid in a hostname and is
         * ignored by strtok()
         */
        if (strstr (dup_addr, "..")) {
                ret = 0;
                goto out;
        }

        /* gen-name */
        temp_str = strtok_r (dup_addr, ".", &save_ptr);
        do {
                str_len = strlen (temp_str);

                if (!isalnum (temp_str[0]) ||
                    !isalnum (temp_str[str_len-1])) {
                        ret = 0;
                        goto out;
                }
                for (i = 1; i < str_len; i++) {
                        if (!isalnum (temp_str[i]) && (temp_str[i] != '-')) {
                                ret = 0;
                                goto out;
                        }
                }
        } while ((temp_str = strtok_r (NULL, ".", &save_ptr)));

out:
        GF_FREE (dup_addr);
        return ret;
}

/*  Matches all ipv4 address, if wildcard_acc is true  '*' wildcard pattern for*
  subnets is considered as valid strings as well                               */
char
valid_ipv4_address (char *address, int length, gf_boolean_t wildcard_acc)
{
        int octets = 0;
        int value = 0;
        char *tmp = NULL, *ptr = NULL, *prev = NULL, *endptr = NULL;
        char ret = 1;
        int is_wildcard = 0;

        tmp = gf_strdup (address);

        /*
         * To prevent cases where last character is '.' and which have
         * consecutive dots like ".." as strtok ignore consecutive
         * delimeters.
         */
        if (length <= 0 ||
            (strstr (address, "..")) ||
            (!isdigit (tmp[length - 1]) && (tmp[length - 1] != '*'))) {
                ret = 0;
                goto out;
        }

        prev = tmp;
        prev = strtok_r (tmp, ".", &ptr);

        while (prev != NULL) {
                octets++;
                if (wildcard_acc && !strcmp (prev, "*")) {
                        is_wildcard = 1;
                } else {
                        value = strtol (prev, &endptr, 10);
                        if ((value > 255) || (value < 0) ||
                            (endptr != NULL && *endptr != '\0')) {
                                ret = 0;
                                goto out;
                        }
                }
                prev = strtok_r (NULL, ".", &ptr);
        }

        if ((octets > 4) || (octets < 4 && !is_wildcard)) {
                ret = 0;
        }

out:
        GF_FREE (tmp);
        return ret;
}

/**
 * valid_ipv4_subnetwork() takes the pattern and checks if it contains
 * a valid ipv4 subnetwork pattern i.e. xx.xx.xx.xx/n. IPv4 address
 * part (xx.xx.xx.xx) and mask bits lengh part (n). The mask bits lengh
 * must be in 0-32 range (ipv4 addr is 32 bit). The pattern must be
 * in this format.
 *
 * Returns _gf_true if both IP addr and mask bits len are valid
 *         _gf_false otherwise.
 */
gf_boolean_t
valid_ipv4_subnetwork (const char *address)
{
        char         *slash     = NULL;
        char         *paddr     = NULL;
        char         *endptr    = NULL;
        long         prefixlen  = -1;
        gf_boolean_t retv       = _gf_true;

        if (address == NULL) {
                gf_msg_callingfn (THIS->name, GF_LOG_WARNING, EINVAL,
                                  LG_MSG_INVALID_ARG, "argument invalid");
                return _gf_false;
        }

        paddr = gf_strdup (address);
        if (paddr == NULL) /* ENOMEM */
                return _gf_false;

        /*
         * INVALID: If '/' is not present OR
         *          Nothing specified after '/'
         */
        slash = strchr(paddr, '/');
        if ((slash == NULL) || (slash[1] == '\0')) {
                gf_msg_callingfn (THIS->name, GF_LOG_WARNING, 0,
                                  LG_MSG_INVALID_IPV4_FORMAT, "Invalid IPv4 "
                                  "subnetwork format");
                retv = _gf_false;
                goto out;
        }

        *slash = '\0';
        retv = valid_ipv4_address (paddr, strlen(paddr), _gf_false);
        if (retv == _gf_false) {
                gf_msg_callingfn (THIS->name, GF_LOG_WARNING, 0,
                                  LG_MSG_INVALID_IPV4_FORMAT,
                                  "Invalid IPv4 subnetwork address");
                goto out;
        }

        prefixlen = strtol (slash + 1, &endptr, 10);
        if ((errno != 0) || (*endptr != '\0') ||
            (prefixlen < 0) || (prefixlen > IPv4_ADDR_SIZE)) {
                gf_msg_callingfn (THIS->name, GF_LOG_WARNING, 0,
                                  LG_MSG_INVALID_IPV4_FORMAT,
                                  "Invalid IPv4 subnetwork mask");
                retv = _gf_false;
                goto out;
        }

        retv = _gf_true;
out:
        GF_FREE (paddr);
        return retv;
}

char
valid_ipv6_address (char *address, int length, gf_boolean_t wildcard_acc)
{
        int hex_numbers = 0;
        int value = 0;
        int i = 0;
        char *tmp = NULL, *ptr = NULL, *prev = NULL, *endptr = NULL;
        char ret = 1;
        int is_wildcard = 0;
        int is_compressed = 0;

        tmp = gf_strdup (address);

        /* Check for '%' for link local addresses */
        endptr = strchr(tmp, '%');
        if (endptr) {
                *endptr = '\0';
                length = strlen(tmp);
                endptr = NULL;
        }

        /* Check for compressed form */
        if (length <= 0 || tmp[length - 1] == ':') {
                ret = 0;
                goto out;
        }
        for (i = 0; i < (length - 1) ; i++) {
                if (tmp[i] == ':' && tmp[i + 1] == ':') {
                        if (is_compressed == 0)
                                is_compressed = 1;
                        else {
                                ret = 0;
                                goto out;
                        }
                }
        }

        prev = strtok_r (tmp, ":", &ptr);

        while (prev != NULL) {
                hex_numbers++;
                if (wildcard_acc && !strcmp (prev, "*")) {
                        is_wildcard = 1;
                } else {
                        value = strtol (prev, &endptr, 16);
                        if ((value > 0xffff) || (value < 0)
                        || (endptr != NULL && *endptr != '\0')) {
                                ret = 0;
                                goto out;
                        }
                }
                prev = strtok_r (NULL, ":", &ptr);
        }

        if ((hex_numbers > 8) || (hex_numbers < 8 && !is_wildcard
            && !is_compressed)) {
                ret = 0;
        }

out:
        GF_FREE (tmp);
        return ret;
}

char
valid_internet_address (char *address, gf_boolean_t wildcard_acc)
{
        char ret = 0;
        int length = 0;

        if (address == NULL) {
                gf_msg_callingfn (THIS->name, GF_LOG_WARNING, EINVAL,
                                  LG_MSG_INVALID_ARG, "argument invalid");
                goto out;
        }

        length = strlen (address);
        if (length == 0)
                goto out;

        if (valid_ipv4_address (address, length, wildcard_acc)
            || valid_ipv6_address (address, length, wildcard_acc)
            || valid_host_name (address, length))
                ret = 1;

out:
        return ret;
}

/**
 * valid_mount_auth_address - Validate the rpc-auth.addr.allow/reject pattern
 *
 * @param address - Pattern to be validated
 *
 * @return _gf_true if "address" is "*" (anonymous) 'OR'
 *                  if "address" is valid FQDN or valid IPv4/6 address 'OR'
 *                  if "address" contains wildcard chars e.g. "'*' or '?' or '['"
 *                  if "address" is valid ipv4 subnet pattern (xx.xx.xx.xx/n)
 *         _gf_false otherwise
 *
 *
 * NB: If the user/admin set for wildcard pattern, then it does not have
 *     to be validated. Make it similar to the way exportfs (kNFS) works.
 */
gf_boolean_t
valid_mount_auth_address (char *address)
{
        int    length = 0;
        char   *cp    = NULL;

        /* 1. Check for "NULL and empty string */
        if ((address == NULL) || (address[0] == '\0')){
                gf_msg_callingfn (THIS->name, GF_LOG_WARNING, EINVAL,
                                  LG_MSG_INVALID_ARG, "argument invalid");
                return _gf_false;
        }

        /* 2. Check for Anonymous */
        if (strcmp(address, "*") == 0)
                return _gf_true;

        for (cp = address; *cp; cp++) {
                /* 3. Check for wildcard pattern */
                if (*cp == '*' || *cp == '?' || *cp == '[') {
                        return _gf_true;
                }

                /*
                 * 4. check for IPv4 subnetwork i.e. xx.xx.xx.xx/n
                 * TODO: check for IPv6 subnetwork
                 * NB: Wildcard must not be mixed with subnetwork.
                 */
                if (*cp == '/') {
                        return valid_ipv4_subnetwork (address);
                }
        }

        /* 5. Check for v4/v6 IP addr and FQDN/hostname */
        length = strlen (address);
        if ((valid_ipv4_address (address, length, _gf_false)) ||
            (valid_ipv6_address (address, length, _gf_false)) ||
            (valid_host_name (address, length))) {
                return _gf_true;
        }

        return _gf_false;
}

/**
 * gf_sock_union_equal_addr - check if two given gf_sock_unions have same addr
 *
 * @param a - first sock union
 * @param b - second sock union
 * @return _gf_true if a and b have same ipv{4,6} addr, _gf_false otherwise
 */
gf_boolean_t
gf_sock_union_equal_addr (union gf_sock_union *a,
                          union gf_sock_union *b)
{
        if (!a || !b) {
                gf_msg ("common-utils", GF_LOG_ERROR, 0, LG_MSG_INVALID_ENTRY,
                        "Invalid arguments to gf_sock_union_equal_addr");
                return _gf_false;
        }

        if (a->storage.ss_family != b->storage.ss_family)
                return _gf_false;

        switch (a->storage.ss_family) {
        case AF_INET:
                if (a->sin.sin_addr.s_addr == b->sin.sin_addr.s_addr)
                        return _gf_true;
                else
                        return _gf_false;

        case AF_INET6:
                if (memcmp ((void *)(&a->sin6.sin6_addr),
                            (void *)(&b->sin6.sin6_addr),
                            sizeof (a->sin6.sin6_addr)))
                        return _gf_false;
                else
                        return _gf_true;

        default:
                gf_msg_debug ("common-utils", 0, "Unsupported/invalid address "
                              "family");
                break;
        }

        return _gf_false;
}

/*
 * Check if both have same network address.
 * Extract the network address from the sockaddr(s) addr by applying the
 * network mask. If they match, return boolean _gf_true, _gf_false otherwise.
 *
 * (x == y) <=> (x ^ y == 0)
 * (x & y) ^ (x & z) <=> x & (y ^ z)
 *
 * ((ip1 & mask) == (ip2 & mask)) <=> ((mask & (ip1 ^ ip2)) == 0)
 */
gf_boolean_t
mask_match(const uint32_t a, const uint32_t b, const uint32_t m)
{
        return (((a ^ b) & m) == 0);
}


/*Thread safe conversion function*/
char *
uuid_utoa (uuid_t uuid)
{
        char *uuid_buffer = glusterfs_uuid_buf_get ();
        gf_uuid_unparse (uuid, uuid_buffer);
        return uuid_buffer;
}

/*Re-entrant conversion function*/
char *
uuid_utoa_r (uuid_t uuid, char *dst)
{
        if(!dst)
                return NULL;
        gf_uuid_unparse (uuid, dst);
        return dst;
}

/*Thread safe conversion function*/
char *
lkowner_utoa (gf_lkowner_t *lkowner)
{
        char *lkowner_buffer = glusterfs_lkowner_buf_get ();
        lkowner_unparse (lkowner, lkowner_buffer, GF_LKOWNER_BUF_SIZE);
        return lkowner_buffer;
}

/*Re-entrant conversion function*/
char *
lkowner_utoa_r (gf_lkowner_t *lkowner, char *dst, int len)
{
        if(!dst)
                return NULL;
        lkowner_unparse (lkowner, dst, len);
        return dst;
}

gf_boolean_t
is_valid_lease_id (const char *lease_id)
{
        int i = 0;
        gf_boolean_t valid = _gf_false;

        for (i = 0; i < LEASE_ID_SIZE; i++) {
                if (lease_id[i] != 0) {
                        valid = _gf_true;
                        goto out;
                }
        }
out:
        return valid;
}

/* Lease_id can be a either in printable or non printable binary
 * format. This function can be used to print any lease_id.
 *
 * This function returns a pointer to a buf, containing the ascii
 * representation of the value in lease_id, in the following format:
 * 4hexnum-4hexnum-4hexnum-4hexnum-4hexnum-4hexnum-4hexnum-4hexnum
 *
 * Eg: If lease_id = "lid1-clnt1" the printable string would be:
 * 6c69-6431-2d63-6c6e-7431-0000-0000-0000
 *
 * Note: The pointer returned should not be stored for further use, as any
 * subsequent call to this function will override the same buffer.
 */
char *
leaseid_utoa (const char *lease_id)
{
        char *buf = NULL;
        int   i   = 0;
        int   j   = 0;

        buf = glusterfs_leaseid_buf_get ();
        if (!buf)
                goto out;

        for (i = 0; i < LEASE_ID_SIZE; i++) {
                if (i && !(i % 2)) {
                        buf[j] = '-';
                        j++;
                }
                sprintf (&buf[j], "%02hhx", lease_id[i]);
                j += 2;
                if (j == GF_LEASE_ID_BUF_SIZE)
                        break;
        }
        buf[GF_LEASE_ID_BUF_SIZE - 1] = '\0';
out:
        return buf;
}

void* gf_array_elem (void *a, int index, size_t elem_size)
{
        uint8_t* ptr = a;
        return (void*)(ptr + index * elem_size);
}

void
gf_elem_swap (void *x, void *y, size_t l) {
        uint8_t *a = x, *b = y, c;
        while(l--) {
                c = *a;
                *a++ = *b;
                *b++ = c;
        }
}

void
gf_array_insertionsort (void *A, int l, int r, size_t elem_size,
                        gf_cmp cmp)
{
        int  i = l;
        int  N = r+1;
        void *Temp = NULL;
        int  j = 0;

        for(i = l; i < N; i++) {
                Temp = gf_array_elem (A, i, elem_size);
                j = i - 1;
                while (j >= 0 && (cmp (Temp, gf_array_elem (A, j, elem_size))
                      < 0)) {
                        gf_elem_swap (Temp, gf_array_elem (A, j, elem_size),
                                      elem_size);
                        Temp = gf_array_elem (A, j, elem_size);
                        j = j-1;
                }
        }
}

int
gf_is_str_int (const char *value)
{
        int     flag = 0;
        char   *str  = NULL;
        char   *fptr = NULL;

        GF_VALIDATE_OR_GOTO (THIS->name, value, out);

        str = gf_strdup (value);
        if (!str)
                goto out;

        fptr = str;

        while (*str) {
                if (!isdigit(*str)) {
                        flag = 1;
                        goto out;
                }
                str++;
        }

out:
        GF_FREE (fptr);

        return flag;
}
/*
 * rounds up nr to power of two. If nr is already a power of two, just returns
 * nr
 */

int32_t
gf_roundup_power_of_two (int32_t nr)
{
        int32_t result = 1;

        if (nr < 0) {
                gf_msg ("common-utils", GF_LOG_WARNING, 0,
                        LG_MSG_NEGATIVE_NUM_PASSED, "negative number passed");
                result = -1;
                goto out;
        }

        while (result < nr)
                result *= 2;

out:
        return result;
}

/*
 * rounds up nr to next power of two. If nr is already a power of two, next
 * power of two is returned.
 */

int32_t
gf_roundup_next_power_of_two (int32_t nr)
{
        int32_t result = 1;

        if (nr < 0) {
                gf_msg ("common-utils", GF_LOG_WARNING, 0,
                        LG_MSG_NEGATIVE_NUM_PASSED, "negative number passed");
                result = -1;
                goto out;
        }

        while (result <= nr)
                result *= 2;

out:
        return result;
}

int
validate_brick_name (char *brick)
{
        char *delimiter = NULL;
        int  ret = 0;
        delimiter = strrchr (brick, ':');
        if (!delimiter || delimiter == brick
            || *(delimiter+1) != '/')
                ret = -1;

        return ret;
}

char *
get_host_name (char *word, char **host)
{
        char *delimiter = NULL;
        delimiter = strrchr (word, ':');
        if (delimiter)
                *delimiter = '\0';
        else
                return NULL;
        *host = word;
        return *host;
}


char *
get_path_name (char *word, char **path)
{
        char *delimiter = NULL;
        delimiter = strchr (word, '/');
        if (!delimiter)
                return NULL;
        *path = delimiter;
        return *path;
}

void
gf_path_strip_trailing_slashes (char *path)
{
        int i = 0;
        int len = 0;

        if (!path)
                return;

        len = strlen (path);
        for (i = len - 1; i > 0; i--) {
                if (path[i] != '/')
                        break;
	}

        if (i < (len -1))
                path [i+1] = '\0';

        return;
}

uint64_t
get_mem_size ()
{
        uint64_t memsize = -1;

#if defined GF_LINUX_HOST_OS || defined GF_SOLARIS_HOST_OS

	uint64_t page_size = 0;
	uint64_t num_pages = 0;

	page_size = sysconf (_SC_PAGESIZE);
	num_pages = sysconf (_SC_PHYS_PAGES);

	memsize = page_size * num_pages;
#endif

#if defined GF_BSD_HOST_OS || defined GF_DARWIN_HOST_OS

	size_t len = sizeof(memsize);
	int name [] = { CTL_HW, HW_PHYSMEM };

	sysctl (name, 2, &memsize, &len, NULL, 0);
#endif
	return memsize;
}

/* Strips all whitespace characters in a string and returns length of new string
 * on success
 */
int
gf_strip_whitespace (char *str, int len)
{
        int     i = 0;
        int     new_len = 0;
        char    *new_str = NULL;

        GF_ASSERT (str);

        new_str = GF_CALLOC (1, len + 1, gf_common_mt_char);
        if (new_str == NULL)
                return -1;

        for (i = 0; i < len; i++) {
                if (!isspace (str[i]))
                        new_str[new_len++] = str[i];
        }
        new_str[new_len] = '\0';

        if (new_len != len) {
                memset (str, 0, len);
                strncpy (str, new_str, new_len);
        }

        GF_FREE (new_str);
        return new_len;
}

int
gf_canonicalize_path (char *path)
{
        int             ret                  = -1;
        int             path_len             = 0;
        int             dir_path_len         = 0;
        char           *tmppath              = NULL;
        char           *dir                  = NULL;
        char           *tmpstr               = NULL;

        if (!path || *path != '/')
                goto out;

        if (!strcmp (path, "/"))
                return 0;

        tmppath = gf_strdup (path);
        if (!tmppath)
                goto out;

        /* Strip the extra slashes and return */
        bzero (path, strlen(path));
        path[0] = '/';
        dir = strtok_r(tmppath, "/", &tmpstr);

        while (dir) {
                dir_path_len = strlen(dir);
                strncpy ((path + path_len + 1), dir, dir_path_len);
                path_len += dir_path_len + 1;
                dir = strtok_r (NULL, "/", &tmpstr);
                if (dir)
                        strncpy ((path + path_len), "/", 1);
        }
        path[path_len] = '\0';
        ret = 0;

 out:
        if (ret)
                gf_msg ("common-utils", GF_LOG_ERROR, 0, LG_MSG_PATH_ERROR,
                        "Path manipulation failed");

        GF_FREE(tmppath);

        return ret;
}

static const char *__gf_timefmts[] = {
        "%F %T",
        "%Y/%m/%d-%T",
        "%b %d %T",
        "%F %H%M%S",
	"%Y-%m-%d-%T",
        "%s",
};

static const char *__gf_zerotimes[] = {
        "0000-00-00 00:00:00",
        "0000/00/00-00:00:00",
        "xxx 00 00:00:00",
        "0000-00-00 000000",
	"0000-00-00-00:00:00",
        "0",
};

void
_gf_timestuff (gf_timefmts *fmt, const char ***fmts, const char ***zeros)
{
        *fmt = gf_timefmt_last;
        *fmts = __gf_timefmts;
        *zeros = __gf_zerotimes;
}


char *
generate_glusterfs_ctx_id (void)
{
        char           tmp_str[1024] = {0,};
        char           hostname[256] = {0,};
        struct timeval tv = {0,};
        char           now_str[32];

        if (gettimeofday (&tv, NULL) == -1) {
                gf_msg ("glusterfsd", GF_LOG_ERROR, errno,
                        LG_MSG_GETTIMEOFDAY_FAILED, "gettimeofday: "
                        "failed");
        }

        if (gethostname (hostname, 256) == -1) {
                gf_msg ("glusterfsd", GF_LOG_ERROR, errno,
                        LG_MSG_GETHOSTNAME_FAILED, "gethostname: failed");
        }

        gf_time_fmt (now_str, sizeof now_str, tv.tv_sec, gf_timefmt_Ymd_T);
        snprintf (tmp_str, sizeof tmp_str, "%s-%d-%s:%"
#ifdef GF_DARWIN_HOST_OS
                  PRId32,
#else
                  "ld",
#endif
                  hostname, getpid(), now_str, tv.tv_usec);

        return gf_strdup (tmp_str);
}

char *
gf_get_reserved_ports ()
{
        char    *ports_info  = NULL;
#if defined GF_LINUX_HOST_OS
        int     proc_fd      = -1;
        char    *proc_file   = "/proc/sys/net/ipv4/ip_local_reserved_ports";
        char    buffer[4096] = {0,};
        int32_t ret          = -1;

        proc_fd = open (proc_file, O_RDONLY);
        if (proc_fd == -1) {
                /* What should be done in this case? error out from here
                 * and thus stop the glusterfs process from starting or
                 * continue with older method of using any of the available
                 * port? For now 2nd option is considered.
                 */
                gf_msg ("glusterfs", GF_LOG_WARNING, errno,
                        LG_MSG_FILE_OP_FAILED, "could not open the file "
                        "/proc/sys/net/ipv4/ip_local_reserved_ports for "
                        "getting reserved ports info");
                goto out;
        }

        ret = sys_read (proc_fd, buffer, sizeof (buffer));
        if (ret < 0) {
                gf_msg ("glusterfs", GF_LOG_WARNING, errno,
                        LG_MSG_FILE_OP_FAILED, "could not read the file %s for"
                        " getting reserved ports info", proc_file);
                goto out;
        }
        ports_info = gf_strdup (buffer);

out:
        if (proc_fd != -1)
                sys_close (proc_fd);
#endif /* GF_LINUX_HOST_OS */
        return ports_info;
}

int
gf_process_reserved_ports (gf_boolean_t *ports, uint32_t ceiling)
{
        int      ret         = -1;
        int      i           = 0;

        for (i = 0; i < GF_PORT_MAX; i++) {
                *(ports + i) = _gf_false;
        }

#if defined GF_LINUX_HOST_OS
        char    *ports_info  = NULL;
        char    *tmp         = NULL;
        char    *blocked_port = NULL;

        ports_info = gf_get_reserved_ports ();
        if (!ports_info) {
                gf_msg ("glusterfs", GF_LOG_WARNING, 0,
                        LG_MSG_RESERVED_PORTS_ERROR, "Not able to get reserved"
                        " ports, hence there is a possibility that glusterfs "
                        "may consume reserved port");
                goto out;
        }

        blocked_port = strtok_r (ports_info, ",\n",&tmp);

        while (blocked_port) {
                gf_ports_reserved (blocked_port, ports, ceiling);
                blocked_port = strtok_r (NULL, ",\n", &tmp);
        }

        ret = 0;

out:
        GF_FREE (ports_info);

#else  /* FIXME: Non Linux Host */
        ret = 0;
#endif /* GF_LINUX_HOST_OS */

        return ret;
}

gf_boolean_t
gf_ports_reserved (char *blocked_port, gf_boolean_t *ports, uint32_t ceiling)
{
        gf_boolean_t    result      = _gf_false;
        char            *range_port = NULL;
        int16_t         tmp_port1   = -1;
        int16_t         tmp_port2   = -1;

        if (strstr (blocked_port, "-") == NULL) {
                /* get rid of the new line character*/
                if (blocked_port[strlen(blocked_port) -1] == '\n')
                        blocked_port[strlen(blocked_port) -1] = '\0';
                if (gf_string2int16 (blocked_port, &tmp_port1) == 0) {
                        if (tmp_port1 > ceiling
                            || tmp_port1 < 0) {
                                gf_msg ("glusterfs-socket", GF_LOG_WARNING, 0,
                                        LG_MSG_INVALID_PORT, "invalid port %d",
                                        tmp_port1);
                                result = _gf_true;
                                goto out;
                        } else {
                                gf_msg_debug ("glusterfs", 0, "blocking port "
                                              "%d", tmp_port1);
                                ports[tmp_port1] = _gf_true;
                        }
                } else {
                        gf_msg ("glusterfs-socket", GF_LOG_WARNING, 0,
                                LG_MSG_INVALID_PORT, "%s is not a valid port "
                                "identifier", blocked_port);
                        result = _gf_true;
                        goto out;
                }
        } else {
                range_port = strtok (blocked_port, "-");
                if (!range_port){
                        result = _gf_true;
                        goto out;
                }
                if (gf_string2int16 (range_port, &tmp_port1) == 0) {
                        if (tmp_port1 > ceiling)
                                tmp_port1 = ceiling;
                        if (tmp_port1 < 0)
                                tmp_port1 = 0;
                }
                range_port = strtok (NULL, "-");
                if (!range_port) {
                        result = _gf_true;
                        goto out;
                }
                /* get rid of the new line character*/
                if (range_port[strlen(range_port) -1] == '\n')
                        range_port[strlen(range_port) - 1] = '\0';
                if (gf_string2int16 (range_port, &tmp_port2) == 0) {
                        if (tmp_port2 > ceiling)
                                tmp_port2 = ceiling;
                        if (tmp_port2 < 0)
                                tmp_port2 = 0;
                }
                gf_msg_debug ("glusterfs", 0, "lower: %d, higher: %d",
                              tmp_port1, tmp_port2);
                for (; tmp_port1 <= tmp_port2; tmp_port1++)
                        ports[tmp_port1] = _gf_true;
        }

out:
        return result;
}

/* Takes in client ip{v4,v6} and returns associated hostname, if any
 * Also, allocates memory for the hostname.
 * Returns: 0 for success, -1 for failure
 */
int
gf_get_hostname_from_ip (char *client_ip, char **hostname)
{
        int                      ret                          = -1;
        struct sockaddr         *client_sockaddr              = NULL;
        struct sockaddr_in       client_sock_in               = {0};
        struct sockaddr_in6      client_sock_in6              = {0};
        char                     client_hostname[NI_MAXHOST]  = {0};
        char                    *client_ip_copy               = NULL;
        char                    *tmp                          = NULL;
        char                    *ip                           = NULL;

        /* if ipv4, reverse lookup the hostname to
         * allow FQDN based rpc authentication
         */
        if (valid_ipv4_address (client_ip, strlen (client_ip), 0) == _gf_false) {
                /* most times, we get a.b.c.d:port form, so check that */
                client_ip_copy = gf_strdup (client_ip);
                if (!client_ip_copy)
                        goto out;

                ip = strtok_r (client_ip_copy, ":", &tmp);
        } else {
                ip = client_ip;
        }

        if (valid_ipv4_address (ip, strlen (ip), 0) == _gf_true) {
                client_sockaddr = (struct sockaddr *)&client_sock_in;
                client_sock_in.sin_family = AF_INET;
                ret = inet_pton (AF_INET, ip,
                                 (void *)&client_sock_in.sin_addr.s_addr);

        } else if (valid_ipv6_address (ip, strlen (ip), 0) == _gf_true) {
                client_sockaddr = (struct sockaddr *) &client_sock_in6;

                client_sock_in6.sin6_family = AF_INET6;
                ret = inet_pton (AF_INET6, ip,
                                 (void *)&client_sock_in6.sin6_addr);
        } else {
                goto out;
        }

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

        ret = getnameinfo (client_sockaddr,
                           sizeof (*client_sockaddr),
                           client_hostname, sizeof (client_hostname),
                           NULL, 0, 0);
        if (ret) {
                gf_msg ("common-utils", GF_LOG_ERROR, 0,
                        LG_MSG_GETNAMEINFO_FAILED, "Could not lookup hostname "
                        "of %s : %s", client_ip, gai_strerror (ret));
                ret = -1;
                goto out;
        }

        *hostname = gf_strdup ((char *)client_hostname);
 out:
        if (client_ip_copy)
                GF_FREE (client_ip_copy);

        return ret;
}

gf_boolean_t
gf_interface_search (char *ip)
{
        int32_t         ret = -1;
        gf_boolean_t    found = _gf_false;
        struct          ifaddrs *ifaddr, *ifa;
        int             family;
        char            host[NI_MAXHOST];
        xlator_t        *this = NULL;
        char            *pct = NULL;

        this = THIS;

        ret = getifaddrs (&ifaddr);

        if (ret != 0) {
                gf_msg (this->name, GF_LOG_ERROR, 0, LG_MSG_GETIFADDRS_FAILED,
                        "getifaddrs() failed: %s\n", gai_strerror(ret));
                goto out;
        }

        for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
                if (!ifa->ifa_addr) {
                        /*
                         * This seemingly happens if an interface hasn't
                         * been bound to a particular protocol (seen with
                         * TUN devices).
                         */
                        continue;
                }
                family = ifa->ifa_addr->sa_family;

                if (family != AF_INET && family != AF_INET6)
                        continue;

                ret = getnameinfo (ifa->ifa_addr,
                        (family == AF_INET) ? sizeof(struct sockaddr_in) :
                                              sizeof(struct sockaddr_in6),
                        host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);

                if (ret != 0) {
                        gf_msg (this->name, GF_LOG_ERROR, 0,
                                LG_MSG_GETNAMEINFO_FAILED, "getnameinfo() "
                                "failed: %s\n", gai_strerror(ret));
                        goto out;
                }

                /*
                 * Sometimes the address comes back as addr%eth0 or
                 * similar.  Since % is an invalid character, we can
                 * strip it out with confidence that doing so won't
                 * harm anything.
                 */
                pct = index(host,'%');
                if (pct) {
                        *pct = '\0';
                }

                if (strncmp (ip, host, NI_MAXHOST) == 0) {
                        gf_msg_debug (this->name, 0, "%s is local address at "
                                      "interface %s", ip, ifa->ifa_name);
                        found = _gf_true;
                        goto out;
                }
        }
out:
        if(ifaddr)
                freeifaddrs (ifaddr);
        return found;
}

char *
get_ip_from_addrinfo (struct addrinfo *addr, char **ip)
{
        char buf[64];
        void *in_addr = NULL;
        struct sockaddr_in *s4 = NULL;
        struct sockaddr_in6 *s6 = NULL;

        switch (addr->ai_family)
        {
                case AF_INET:
                        s4 = (struct sockaddr_in *)addr->ai_addr;
                        in_addr = &s4->sin_addr;
                        break;

                case AF_INET6:
                        s6 = (struct sockaddr_in6 *)addr->ai_addr;
                        in_addr = &s6->sin6_addr;
                        break;

                default:
                        gf_msg ("glusterd", GF_LOG_ERROR, 0,
                                LG_MSG_INVALID_FAMILY, "Invalid family");
                        return NULL;
        }

        if (!inet_ntop(addr->ai_family, in_addr, buf, sizeof(buf))) {
                gf_msg ("glusterd", GF_LOG_ERROR, 0, LG_MSG_CONVERSION_FAILED,
                        "String conversion failed");
                return NULL;
        }

        *ip = gf_strdup (buf);
        return *ip;
}

gf_boolean_t
gf_is_loopback_localhost (const struct sockaddr *sa, char *hostname)
{
        GF_ASSERT (sa);

        gf_boolean_t is_local = _gf_false;
        const struct in_addr *addr4 = NULL;
        const struct in6_addr *addr6 = NULL;
        uint8_t      *ap   = NULL;
        struct in6_addr loopbackaddr6 = IN6ADDR_LOOPBACK_INIT;

        switch (sa->sa_family) {
                case AF_INET:
                        addr4 = &(((struct sockaddr_in *)sa)->sin_addr);
                        ap = (uint8_t*)&addr4->s_addr;
                        if (ap[0] == 127)
                                is_local = _gf_true;
                        break;

                case AF_INET6:
                        addr6 = &(((struct sockaddr_in6 *)sa)->sin6_addr);
                        if (memcmp (addr6, &loopbackaddr6,
                                    sizeof (loopbackaddr6)) == 0)
                                is_local = _gf_true;
                        break;

                default:
                        if (hostname)
                                gf_msg ("glusterd", GF_LOG_ERROR, 0,
                                        LG_MSG_INVALID_FAMILY, "unknown "
                                        "address family %d for %s",
                                        sa->sa_family, hostname);
                        break;
        }

        return is_local;
}

gf_boolean_t
gf_is_local_addr (char *hostname)
{
        int32_t         ret = -1;
        struct          addrinfo *result = NULL;
        struct          addrinfo *res = NULL;
        gf_boolean_t    found = _gf_false;
        char            *ip = NULL;
        xlator_t        *this = NULL;
        struct          addrinfo hints;

        this = THIS;

        memset (&hints, 0, sizeof (hints));
        /*
         * Removing AI_ADDRCONFIG from default_hints
         * for being able to use link local ipv6 addresses
         */
        hints.ai_family = AF_UNSPEC;

        ret = getaddrinfo (hostname, NULL, &hints, &result);

        if (ret != 0) {
                gf_msg (this->name, GF_LOG_ERROR, 0, LG_MSG_GETADDRINFO_FAILED,
                        "error in getaddrinfo: %s\n", gai_strerror(ret));
                goto out;
        }

        for (res = result; res != NULL; res = res->ai_next) {
                gf_msg_debug (this->name, 0, "%s ",
                              get_ip_from_addrinfo (res, &ip));

                found = gf_is_loopback_localhost (res->ai_addr, hostname)
                        || gf_interface_search (ip);
                if (found) {
                        GF_FREE (ip);
                        goto out;
                }
                GF_FREE (ip);
        }

out:
        if (result)
                freeaddrinfo (result);

        if (!found)
                gf_msg_debug (this->name, 0, "%s is not local", hostname);

        return found;
}

gf_boolean_t
gf_is_same_address (char *name1, char *name2)
{
        struct addrinfo         *addr1 = NULL;
        struct addrinfo         *addr2 = NULL;
        struct addrinfo         *p = NULL;
        struct addrinfo         *q = NULL;
        gf_boolean_t            ret = _gf_false;
        int                     gai_err = 0;
        struct                  addrinfo hints;

        memset (&hints, 0, sizeof (hints));
        hints.ai_family = AF_UNSPEC;

        gai_err = getaddrinfo(name1, NULL, &hints, &addr1);
        if (gai_err != 0) {
                gf_msg (name1, GF_LOG_WARNING, 0, LG_MSG_GETADDRINFO_FAILED,
                        "error in getaddrinfo: %s\n", gai_strerror(gai_err));
                goto out;
        }

        gai_err = getaddrinfo(name2, NULL, &hints, &addr2);
        if (gai_err != 0) {
                gf_msg (name2, GF_LOG_WARNING, 0, LG_MSG_GETADDRINFO_FAILED,
                        "error in getaddrinfo: %s\n", gai_strerror(gai_err));
                goto out;
        }

        for (p = addr1; p; p = p->ai_next) {
                for (q = addr2; q; q = q->ai_next) {
                        if (p->ai_addrlen != q->ai_addrlen) {
                                continue;
                        }
                        if (memcmp(p->ai_addr,q->ai_addr,p->ai_addrlen)) {
                                continue;
                        }
                        ret = _gf_true;
                        goto out;
                }
        }

out:
        if (addr1) {
                freeaddrinfo(addr1);
        }
        if (addr2) {
                freeaddrinfo(addr2);
        }
        return ret;

}

/* Sets log file path from user provided arguments */
int
gf_set_log_file_path (cmd_args_t *cmd_args, glusterfs_ctx_t *ctx)
{
        int   i = 0;
        int   j = 0;
        int   ret = 0;
        char  tmp_str[1024] = {0,};

        if (!cmd_args)
                goto done;

        if (cmd_args->mount_point) {
                j = 0;
                i = 0;
                if (cmd_args->mount_point[0] == '/')
                        i = 1;
                for (; i < strlen (cmd_args->mount_point); i++,j++) {
                        tmp_str[j] = cmd_args->mount_point[i];
                        if (cmd_args->mount_point[i] == '/')
                                tmp_str[j] = '-';
                }

                ret = gf_asprintf (&cmd_args->log_file,
                                   DEFAULT_LOG_FILE_DIRECTORY "/%s.log",
                                   tmp_str);
                if (ret > 0)
                        ret = 0;
                goto done;
        }

        if (ctx && GF_GLUSTERD_PROCESS == ctx->process_mode) {
                ret = gf_asprintf (&cmd_args->log_file,
                                   DEFAULT_LOG_FILE_DIRECTORY "/%s.log",
                                   GLUSTERD_NAME);
                if (ret > 0)
                        ret = 0;

                goto done;
        }

        if (cmd_args->volfile) {
                j = 0;
                i = 0;
                if (cmd_args->volfile[0] == '/')
                        i = 1;
                for (; i < strlen (cmd_args->volfile); i++,j++) {
                        tmp_str[j] = cmd_args->volfile[i];
                        if (cmd_args->volfile[i] == '/')
                                tmp_str[j] = '-';
                }
                ret = gf_asprintf (&cmd_args->log_file,
                                   DEFAULT_LOG_FILE_DIRECTORY "/%s.log",
                                   tmp_str);
                if (ret > 0)
                        ret = 0;
                goto done;
        }

        if (cmd_args->volfile_server) {

                ret = gf_asprintf (&cmd_args->log_file,
                                   DEFAULT_LOG_FILE_DIRECTORY "/%s-%s-%d.log",
                                   cmd_args->volfile_server,
                                   cmd_args->volfile_id, getpid());
                if (ret > 0)
                        ret = 0;
        }
done:
        return ret;
}

int
gf_set_log_ident (cmd_args_t *cmd_args)
{
        int              ret = 0;
        char            *ptr = NULL;

        if (cmd_args->log_file == NULL) {
                /* no ident source */
                return 0;
        }

        /* TODO: Some idents would look like, etc-glusterfs-glusterd.vol, which
         * seems ugly and can be bettered? */
        /* just get the filename as the ident */
        if (NULL != (ptr = strrchr (cmd_args->log_file, '/'))) {
                ret = gf_asprintf (&cmd_args->log_ident, "%s", ptr + 1);
        } else {
                ret = gf_asprintf (&cmd_args->log_ident, "%s",
                                   cmd_args->log_file);
        }

        if (ret > 0)
                ret = 0;
        else
                return ret;

        /* remove .log suffix */
        if (NULL != (ptr = strrchr (cmd_args->log_ident, '.'))) {
                if (strcmp (ptr, ".log") == 0) {
                        ptr[0] = '\0';
                }
        }

        return ret;
}

int
gf_thread_cleanup_xint (pthread_t thread)
{
        int ret = 0;
        void *res = NULL;

        ret = pthread_cancel (thread);
        if (ret != 0)
                goto error_return;

        ret = pthread_join (thread, &res);
        if (ret != 0)
                goto error_return;

        if (res != PTHREAD_CANCELED)
                goto error_return;

        ret = 0;

 error_return:
        return ret;
}

int
gf_thread_create (pthread_t *thread, const pthread_attr_t *attr,
                  void *(*start_routine)(void *), void *arg)
{
        sigset_t set, old;
        int ret;

        sigemptyset (&set);

        sigfillset (&set);
        sigdelset (&set, SIGSEGV);
        sigdelset (&set, SIGBUS);
        sigdelset (&set, SIGILL);
        sigdelset (&set, SIGSYS);
        sigdelset (&set, SIGFPE);
        sigdelset (&set, SIGABRT);

        pthread_sigmask (SIG_BLOCK, &set, &old);

        ret = pthread_create (thread, attr, start_routine, arg);

        pthread_sigmask (SIG_SETMASK, &old, NULL);

        return ret;
}

int
gf_thread_create_detached (pthread_t *thread,
                         void *(*start_routine)(void *), void *arg)
{
        pthread_attr_t attr;
        int ret = -1;

        ret = pthread_attr_init (&attr);
        if (ret) {
                gf_msg (THIS->name, GF_LOG_ERROR, ret,
                        LG_MSG_PTHREAD_ATTR_INIT_FAILED,
                        "Thread attribute initialization failed");
                return -1;
        }

        pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);

        ret = gf_thread_create (thread, &attr, start_routine, arg);
        if (ret) {
                gf_msg (THIS->name, GF_LOG_ERROR, ret,
                        LG_MSG_PTHREAD_FAILED,
                        "Thread creation failed");
                ret = -1;
        }

        pthread_attr_destroy (&attr);

        return ret;
}

int
gf_skip_header_section (int fd, int header_len)
{
        int  ret           = -1;

        ret = sys_lseek (fd, header_len, SEEK_SET);
        if (ret == (off_t) -1) {
                gf_msg ("", GF_LOG_ERROR, 0, LG_MSG_SKIP_HEADER_FAILED,
                        "Failed to skip header section");
        } else {
                ret = 0;
        }

        return ret;
}

gf_boolean_t
gf_is_service_running (char *pidfile, int *pid)
{
        FILE            *file = NULL;
        gf_boolean_t    running = _gf_false;
        int             ret = 0;
        int             fno = 0;

        file = fopen (pidfile, "r+");
        if (!file)
                goto out;

        fno = fileno (file);
        ret = lockf (fno, F_TEST, 0);
        if (ret == -1)
                running = _gf_true;
        if (!pid)
                goto out;

        ret = fscanf (file, "%d", pid);
        if (ret <= 0) {
                gf_msg ("", GF_LOG_ERROR, errno, LG_MSG_FILE_OP_FAILED,
                        "Unable to read pidfile: %s", pidfile);
                *pid = -1;
        }

out:
        if (file)
                fclose (file);
        return running;
}

static int
dht_is_linkfile_key (dict_t *this, char *key, data_t *value, void *data)
{
        gf_boolean_t *linkfile_key_found = NULL;

        if (!data)
                goto out;

        linkfile_key_found = data;

        *linkfile_key_found = _gf_true;
out:
        return 0;
}


gf_boolean_t
dht_is_linkfile (struct iatt *buf, dict_t *dict)
{
        gf_boolean_t linkfile_key_found = _gf_false;

        if (!IS_DHT_LINKFILE_MODE (buf))
                return _gf_false;

        dict_foreach_fnmatch (dict, "*."DHT_LINKFILE_STR, dht_is_linkfile_key,
                              &linkfile_key_found);

        return linkfile_key_found;
}

int
gf_check_log_format (const char *value)
{
        int log_format = -1;

        if (!strcasecmp (value, GF_LOG_FORMAT_NO_MSG_ID))
                log_format = gf_logformat_traditional;
        else if (!strcasecmp (value, GF_LOG_FORMAT_WITH_MSG_ID))
                log_format = gf_logformat_withmsgid;

        if (log_format == -1)
                gf_msg (THIS->name, GF_LOG_ERROR, 0, LG_MSG_INVALID_LOG,
                        "Invalid log-format. possible values are "
                        GF_LOG_FORMAT_NO_MSG_ID "|" GF_LOG_FORMAT_WITH_MSG_ID);

        return log_format;
}

int
gf_check_logger (const char *value)
{
        int logger = -1;

        if (!strcasecmp (value, GF_LOGGER_GLUSTER_LOG))
                logger = gf_logger_glusterlog;
        else if (!strcasecmp (value, GF_LOGGER_SYSLOG))
                logger = gf_logger_syslog;

        if (logger == -1)
                gf_msg (THIS->name, GF_LOG_ERROR, 0, LG_MSG_INVALID_LOG,
                        "Invalid logger. possible values are "
                        GF_LOGGER_GLUSTER_LOG "|" GF_LOGGER_SYSLOG);

        return logger;
}

/* gf_compare_sockaddr compares the given addresses @addr1 and @addr2 for
 * equality, ie. if they both refer to the same address.
 *
 * This was inspired by sock_addr_cmp_addr() from
 * https://www.opensource.apple.com/source/postfix/postfix-197/postfix/src/util/sock_addr.c
 */
gf_boolean_t
gf_compare_sockaddr (const struct sockaddr *addr1,
                     const struct sockaddr *addr2)
{
        GF_ASSERT (addr1 != NULL);
        GF_ASSERT (addr2 != NULL);

        /* Obviously, the addresses don't match if their families are different
         */
        if (addr1->sa_family != addr2->sa_family)
                return _gf_false;


        if (AF_INET == addr1->sa_family) {
                if (((struct sockaddr_in *)addr1)->sin_addr.s_addr ==
                       ((struct sockaddr_in *)addr2)->sin_addr.s_addr)
                        return _gf_true;

        } else if (AF_INET6 == addr1->sa_family) {
                if (memcmp ((char *)&((struct sockaddr_in6 *)addr1)->sin6_addr,
                            (char *)&((struct sockaddr_in6 *)addr2)->sin6_addr,
                            sizeof (struct in6_addr)) == 0)
                        return _gf_true;
        }
        return _gf_false;
}

/*
 * gf_set_timestamp:
 *      It sets the mtime and atime of 'dest' file as of 'src'.
 */

int
gf_set_timestamp  (const char *src, const char* dest)
{
        struct stat    sb             = {0, };
        struct timeval new_time[2]    = {{0, },{0,}};
        int            ret            = 0;
        xlator_t       *this          = NULL;

        this = THIS;
        GF_ASSERT (this);
        GF_ASSERT (src);
        GF_ASSERT (dest);

        ret = sys_stat (src, &sb);
        if (ret) {
                gf_msg (this->name, GF_LOG_ERROR, errno,
                        LG_MSG_FILE_STAT_FAILED, "stat on %s", src);
                goto out;
        }
        new_time[0].tv_sec = sb.st_atime;
        new_time[0].tv_usec = ST_ATIM_NSEC (&sb)/1000;

        new_time[1].tv_sec = sb.st_mtime;
        new_time[1].tv_usec = ST_MTIM_NSEC (&sb)/1000;

        /* The granularity is micro seconds as per the current
         * requiremnt. Hence using 'utimes'. This can be updated
         * to 'utimensat' if we need timestamp in nanoseconds.
         */
        ret = sys_utimes (dest, new_time);
        if (ret) {
                gf_msg (this->name, GF_LOG_ERROR, errno, LG_MSG_UTIMES_FAILED,
                        "utimes on %s", dest);
        }
out:
        return ret;
}

static void
gf_backtrace_end (char *buf, size_t frames)
{
        size_t pos = 0;

        if (!buf)
                return;

        pos = strlen (buf);

        frames = min(frames, GF_BACKTRACE_LEN - pos -1);

        if (frames <= 0)
                return;

        memset (buf+pos, ')', frames);
        buf[pos+frames] = '\0';
}

/*Returns bytes written*/
static int
gf_backtrace_append (char *buf, size_t pos, char *framestr)
{
        if (pos >= GF_BACKTRACE_LEN)
                return -1;
        return snprintf (buf+pos, GF_BACKTRACE_LEN-pos, "(--> %s ", framestr);
}

static int
gf_backtrace_fillframes (char *buf)
{
        void    *array[GF_BACKTRACE_FRAME_COUNT];
        size_t  frames                  = 0;
        FILE    *fp                     = NULL;
        char    callingfn[GF_BACKTRACE_FRAME_COUNT-2][1024] = {{0},};
        int     ret                     = -1;
        int     fd                      = -1;
        size_t  idx                     = 0;
        size_t  pos                     = 0;
        size_t  inc                     = 0;
        char    tmpl[32]                = "/tmp/btXXXXXX";

        frames = backtrace (array, GF_BACKTRACE_FRAME_COUNT);
        if (!frames)
                return -1;

        fd = gf_mkostemp (tmpl, 0, O_RDWR);
        if (fd == -1)
                return -1;

        /*The most recent two frames are the calling function and
         * gf_backtrace_save, which we can infer.*/

        backtrace_symbols_fd (&array[2], frames-2, fd);

        fp = fdopen (fd, "r");
        if (!fp) {
                sys_close (fd);
                ret = -1;
                goto out;
        }

        ret = fseek (fp, 0L, SEEK_SET);
        if (ret)
                goto out;

        pos = 0;
        for (idx = 0; idx < frames - 2; idx++) {
                ret = fscanf (fp, "%s", callingfn[idx]);
                if (ret == EOF)
                        break;
                inc = gf_backtrace_append (buf, pos, callingfn[idx]);
                if (inc == -1)
                        break;
                pos += inc;
        }
        gf_backtrace_end (buf, idx);

out:
        if (fp)
                fclose (fp);

        sys_unlink (tmpl);

        return (idx > 0)? 0: -1;

}

/* Optionally takes @buf to save backtrace.  If @buf is NULL, uses the
 * pre-allocated ctx->btbuf to avoid allocating memory while printing
 * backtrace.
 * TODO: This API doesn't provide flexibility in terms of no. of frames
 * of the backtrace is being saved in the buffer. Deferring fixing it
 * when there is a real-use for that.*/

char *
gf_backtrace_save (char *buf)
{
        char *bt = NULL;

        if (!buf) {
                bt = THIS->ctx->btbuf;
                GF_ASSERT (bt);

        } else {
                bt = buf;

        }

        if ((0 == gf_backtrace_fillframes (bt)))
                return bt;

        gf_msg (THIS->name, GF_LOG_WARNING, 0, LG_MSG_BACKTRACE_SAVE_FAILED,
                "Failed to save the backtrace.");
        return NULL;
}

gf_loglevel_t
fop_log_level (glusterfs_fop_t fop, int op_errno)
{
        /* if gfid doesn't exist ESTALE comes */
        if (op_errno == ENOENT || op_errno == ESTALE)
                return GF_LOG_DEBUG;

        if ((fop == GF_FOP_ENTRYLK) ||
            (fop == GF_FOP_FENTRYLK) ||
            (fop == GF_FOP_FINODELK) ||
            (fop == GF_FOP_INODELK) ||
            (fop == GF_FOP_LK)) {
                /*
                 * if non-blocking lock fails EAGAIN comes
                 * if locks xlator is not loaded ENOSYS comes
                 */
                if (op_errno == EAGAIN || op_errno == ENOSYS)
                        return GF_LOG_DEBUG;
        }

        if ((fop == GF_FOP_GETXATTR) ||
            (fop == GF_FOP_FGETXATTR)) {
                if (op_errno == ENOTSUP || op_errno == ENODATA)
                        return GF_LOG_DEBUG;
        }

        if ((fop == GF_FOP_SETXATTR) ||
            (fop == GF_FOP_FSETXATTR) ||
            (fop == GF_FOP_REMOVEXATTR) ||
            (fop == GF_FOP_FREMOVEXATTR)) {
                if (op_errno == ENOTSUP)
                        return GF_LOG_DEBUG;
        }

        if (fop == GF_FOP_MKNOD || fop == GF_FOP_MKDIR)
                if (op_errno == EEXIST)
                        return GF_LOG_DEBUG;

        return GF_LOG_ERROR;
}

/* This function will build absolute path of file/directory from the
 * current location and relative path given from the current location
 * For example consider our current path is /a/b/c/ and relative path
 * from current location is ./../x/y/z .After parsing through this
 * function the absolute path becomes /a/b/x/y/z/.
 *
 * The function gives a pointer to absolute path if it is successful
 * and also returns zero.
 * Otherwise function gives NULL pointer with returning an err value.
 *
 * So the user need to free memory allocated for path.
 *
 */

int32_t
gf_build_absolute_path (char *current_path, char *relative_path, char **path)
{
        char                    *absolute_path          = NULL;
        char                    *token                  = NULL;
        char                    *component              = NULL;
        char                    *saveptr                = NULL;
        char                    *end                    = NULL;
        int                     ret                     = 0;
        size_t                  relativepath_len        = 0;
        size_t                  currentpath_len         = 0;
        size_t                  max_absolutepath_len    = 0;

        GF_ASSERT (current_path);
        GF_ASSERT (relative_path);
        GF_ASSERT (path);

        if (!path || !current_path || !relative_path) {
                ret = -EFAULT;
                goto err;
        }
        /* Check for current and relative path
         * current path should be absolute one and  start from '/'
         * relative path should not start from '/'
         */
        currentpath_len = strlen (current_path);
        if (current_path[0] != '/' || (currentpath_len > PATH_MAX)) {
                gf_msg (THIS->name, GF_LOG_ERROR, 0, LG_MSG_INVALID_ENTRY,
                        "Wrong value for current path %s", current_path);
                ret = -EINVAL;
                goto err;
        }

        relativepath_len = strlen (relative_path);
        if (relative_path[0] == '/' || (relativepath_len > PATH_MAX)) {
                gf_msg (THIS->name, GF_LOG_ERROR, 0, LG_MSG_INVALID_ENTRY,
                        "Wrong value for relative path %s", relative_path);
                ret = -EINVAL;
                goto err;
        }

        /* It is maximum possible value for absolute path */
        max_absolutepath_len = currentpath_len + relativepath_len + 2;

        absolute_path = GF_CALLOC (1, max_absolutepath_len, gf_common_mt_char);
        if (!absolute_path) {
                ret = -ENOMEM;
                goto err;
        }
        absolute_path[0] = '\0';

        /* If current path is root i.e contains only "/", we do not
         * need to copy it
         */
        if (strcmp (current_path, "/") != 0) {
                strcpy (absolute_path, current_path);

                /* We trim '/' at the end for easier string manipulation */
                gf_path_strip_trailing_slashes (absolute_path);
        }

        /* Used to spilt relative path based on '/' */
        component = gf_strdup (relative_path);
        if (!component) {
                ret = -ENOMEM;
                goto err;
        }

        /* In the relative path, we want to consider ".." and "."
         * if token is ".." , we just need to reduce one level hierarchy
         * if token is "." , we just ignore it
         * if token is NULL , end of relative path
         * if absolute path becomes '\0' and still "..", then it is a bad
         * relative path,  it points to out of boundary area and stop
         * building the absolute path
         * All other cases we just concatenate token to the absolute path
         */
        for (token = strtok_r (component,  "/", &saveptr),
             end = strchr (absolute_path, '\0'); token;
             token = strtok_r (NULL, "/", &saveptr)) {
                if (strcmp (token, ".") == 0)
                        continue;

                else if (strcmp (token, "..") == 0) {

                        if (absolute_path[0] == '\0') {
                                ret = -EACCES;
                                goto err;
                         }

                         end = strrchr (absolute_path, '/');
                         *end = '\0';
                } else {
                        ret = snprintf (end, max_absolutepath_len -
                                        strlen (absolute_path), "/%s", token);
                        end = strchr (absolute_path , '\0');
                }
        }

        if (strlen (absolute_path) > PATH_MAX) {
                ret = -EINVAL;
                goto err;
        }
        *path = gf_strdup (absolute_path);

err:
        if (component)
                GF_FREE (component);
        if (absolute_path)
                GF_FREE (absolute_path);
        return ret;
}

/* This is an utility function which will recursively delete
 * a folder and its contents.
 *
 * @param delete_path folder to be deleted.
 *
 * @return 0 on success and -1 on failure.
 */
int
recursive_rmdir (const char *delete_path)
{
        int             ret             = -1;
        char            path[PATH_MAX]  = {0,};
        struct stat     st              = {0,};
        DIR            *dir             = NULL;
        struct dirent  *entry           = NULL;
        xlator_t       *this            = NULL;

        this = THIS;
        GF_ASSERT (this);
        GF_VALIDATE_OR_GOTO (this->name, delete_path, out);

        dir = sys_opendir (delete_path);
        if (!dir) {
                gf_msg_debug (this->name, 0, "Failed to open directory %s. "
                              "Reason : %s", delete_path, strerror (errno));
                ret = 0;
                goto out;
        }

        GF_FOR_EACH_ENTRY_IN_DIR (entry, dir);
        while (entry) {
                snprintf (path, PATH_MAX, "%s/%s", delete_path, entry->d_name);
                ret = sys_lstat (path, &st);
                if (ret == -1) {
                        gf_msg_debug (this->name, 0, "Failed to stat entry %s :"
                                      " %s", path, strerror (errno));
                        goto out;
                }

                if (S_ISDIR (st.st_mode))
                        ret = recursive_rmdir (path);
                else
                        ret = sys_unlink (path);

                if (ret) {
                        gf_msg_debug (this->name, 0, " Failed to remove %s. "
                                      "Reason : %s", path, strerror (errno));
                }

                gf_msg_debug (this->name, 0, "%s %s", ret ?
                              "Failed to remove" : "Removed", entry->d_name);

                GF_FOR_EACH_ENTRY_IN_DIR (entry, dir);
        }

        ret = sys_closedir (dir);
        if (ret) {
                gf_msg_debug (this->name, 0, "Failed to close dir %s. Reason :"
                              " %s", delete_path, strerror (errno));
        }

        ret = sys_rmdir (delete_path);
        if (ret) {
                gf_msg_debug (this->name, 0, "Failed to rmdir: %s,err: %s",
                              delete_path, strerror (errno));
        }

out:
        return ret;
}
/*
 * Input: Array of strings 'array' terminating in NULL
 *        string 'elem' to be searched in the array
 *
 * Output: Index of the element in the array if found, '-1' otherwise
 */
int
gf_get_index_by_elem (char **array, char *elem)
{
        int     i = 0;

        for (i = 0; array[i]; i++) {
                if (strcmp (elem, array[i]) == 0)
                        return i;
        }

        return -1;
}

static int
get_pathinfo_host (char *pathinfo, char *hostname, size_t size)
{
        char    *start = NULL;
        char    *end = NULL;
        int     ret  = -1;
        int     i    = 0;

        if (!pathinfo)
                goto out;

        start = strchr (pathinfo, ':');
        if (!start)
                goto out;

        end = strrchr (pathinfo, ':');
        if (start == end)
                goto out;

        memset (hostname, 0, size);
        i = 0;
        while (++start != end)
                hostname[i++] = *start;
        ret = 0;
out:
        return ret;
}

/*Note: 'pathinfo' should be gathered only from one brick*/
int
glusterfs_is_local_pathinfo (char *pathinfo, gf_boolean_t *is_local)
{
        int             ret   = 0;
        char            pathinfohost[1024] = {0};
        char            localhost[1024] = {0};

        *is_local = _gf_false;
        ret = get_pathinfo_host (pathinfo, pathinfohost, sizeof (pathinfohost));
        if (ret)
                goto out;

        ret = gethostname (localhost, sizeof (localhost));
        if (ret)
                goto out;

        if (!strcmp (localhost, pathinfohost))
                *is_local = _gf_true;
out:
        return ret;
}

ssize_t
gf_nread (int fd, void *buf, size_t count)
{
        ssize_t  ret           = 0;
        ssize_t  read_bytes    = 0;

        for (read_bytes = 0; read_bytes < count; read_bytes += ret) {
                ret = sys_read (fd, buf + read_bytes, count - read_bytes);
                if (ret == 0) {
                        break;
                } else if (ret < 0) {
                        if (errno == EINTR)
                                ret = 0;
                        else
                                goto out;
                }
        }

        ret = read_bytes;
out:
        return ret;
}

ssize_t
gf_nwrite (int fd, const void *buf, size_t count)
{
        ssize_t  ret        = 0;
        ssize_t  written    = 0;

        for (written = 0; written != count; written += ret) {
                ret = sys_write (fd, buf + written, count - written);
                if (ret < 0) {
                        if (errno == EINTR)
                                ret = 0;
                        else
                                goto out;
                }
        }

        ret = written;
out:
        return ret;
}

void
gf_free_mig_locks (lock_migration_info_t *locks)
{
        lock_migration_info_t    *current       = NULL;
        lock_migration_info_t    *temp          = NULL;

        if (!locks)
                return;

        if (list_empty (&locks->list))
                return;

        list_for_each_entry_safe (current, temp, &locks->list, list) {
                list_del_init (&current->list);
                GF_FREE (current->client_uid);
                GF_FREE (current);
        }
}

void
_mask_cancellation (void)
{
        (void) pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, NULL);
}

void
_unmask_cancellation (void)
{
        (void) pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, NULL);
}

/* This is a wrapper function to add a pointer to a list,
 * which doesn't contain list member
 */
struct list_node*
_list_node_add (void *ptr, struct list_head *list,
               int (*compare)(struct list_head *, struct list_head *))
{
        struct list_node  *node = NULL;

        if (ptr == NULL || list == NULL)
                goto out;

        node = GF_CALLOC (1, sizeof (struct list_node), gf_common_list_node);

        if (node == NULL)
                goto out;

        node->ptr = ptr;
        if (compare)
                list_add_order (&node->list, list, compare);
        else
                list_add_tail (&node->list, list);
out:
        return node;
}

struct list_node*
list_node_add (void *ptr, struct list_head *list)
{
        return _list_node_add (ptr, list, NULL);
}

struct list_node*
list_node_add_order (void *ptr, struct list_head *list,
                     int (*compare)(struct list_head *, struct list_head *))
{
        return _list_node_add (ptr, list, compare);
}

void
list_node_del (struct list_node *node)
{
        if (node == NULL)
                return;

        list_del_init (&node->list);
        GF_FREE (node);
}

const char *
fop_enum_to_pri_string (glusterfs_fop_t fop)
{
        switch (fop) {
        case GF_FOP_OPEN:
        case GF_FOP_STAT:
        case GF_FOP_FSTAT:
        case GF_FOP_LOOKUP:
        case GF_FOP_ACCESS:
        case GF_FOP_READLINK:
        case GF_FOP_OPENDIR:
        case GF_FOP_STATFS:
        case GF_FOP_READDIR:
        case GF_FOP_READDIRP:
        case GF_FOP_GETACTIVELK:
        case GF_FOP_SETACTIVELK:
                return "HIGH";

        case GF_FOP_CREATE:
        case GF_FOP_FLUSH:
        case GF_FOP_LK:
        case GF_FOP_INODELK:
        case GF_FOP_FINODELK:
        case GF_FOP_ENTRYLK:
        case GF_FOP_FENTRYLK:
        case GF_FOP_UNLINK:
        case GF_FOP_SETATTR:
        case GF_FOP_FSETATTR:
        case GF_FOP_MKNOD:
        case GF_FOP_MKDIR:
        case GF_FOP_RMDIR:
        case GF_FOP_SYMLINK:
        case GF_FOP_RENAME:
        case GF_FOP_LINK:
        case GF_FOP_SETXATTR:
        case GF_FOP_GETXATTR:
        case GF_FOP_FGETXATTR:
        case GF_FOP_FSETXATTR:
        case GF_FOP_REMOVEXATTR:
        case GF_FOP_FREMOVEXATTR:
        case GF_FOP_IPC:
        case GF_FOP_LEASE:
                return "NORMAL";

        case GF_FOP_READ:
        case GF_FOP_WRITE:
        case GF_FOP_FSYNC:
        case GF_FOP_TRUNCATE:
        case GF_FOP_FTRUNCATE:
        case GF_FOP_FSYNCDIR:
        case GF_FOP_XATTROP:
        case GF_FOP_FXATTROP:
        case GF_FOP_RCHECKSUM:
        case GF_FOP_ZEROFILL:
        case GF_FOP_FALLOCATE:
        case GF_FOP_SEEK:
                return "LOW";

        case GF_FOP_NULL:
        case GF_FOP_FORGET:
        case GF_FOP_RELEASE:
        case GF_FOP_RELEASEDIR:
        case GF_FOP_GETSPEC:
        case GF_FOP_MAXVALUE:
        case GF_FOP_DISCARD:
                return "LEAST";
        default:
                return "UNKNOWN";
        }
}

const char *
fop_enum_to_string (glusterfs_fop_t fop)
{
        static const char *const str_map[] = {
                "NULL",
                "STAT",
                "READLINK",
                "MKNOD",
                "MKDIR",
                "UNLINK",
                "RMDIR",
                "SYMLINK",
                "RENAME",
                "LINK",
                "TRUNCATE",
                "OPEN",
                "READ",
                "WRITE",
                "STATFS",
                "FLUSH",
                "FSYNC",
                "SETXATTR",
                "GETXATTR",
                "REMOVEXATTR",
                "OPENDIR",
                "FSYNCDIR",
                "ACCESS",
                "CREATE",
                "FTRUNCATE",
                "FSTAT",
                "LK",
                "LOOKUP",
                "READDIR",
                "INODELK",
                "FINODELK",
                "ENTRYLK",
                "FENTRYLK",
                "XATTROP",
                "FXATTROP",
                "FGETXATTR",
                "FSETXATTR",
                "RCHECKSUM",
                "SETATTR",
                "FSETATTR",
                "READDIRP",
                "FORGET",
                "RELEASE",
                "RELEASEDIR",
                "GETSPEC",
                "FREMOVEXATTR",
                "FALLOCATE",
                "DISCARD",
                "ZEROFILL",
                "IPC",
                "SEEK",
                "COMPOUND",
                "MAXVALUE"};
        if (fop <= GF_FOP_MAXVALUE)
                return str_map[fop];

        return "UNKNOWNFOP";
}

const char *
gf_inode_type_to_str (ia_type_t type)
{
        static const char *const str_ia_type[] = {
                "UNKNOWN",
                "REGULAR FILE",
                "DIRECTORY",
                "LINK",
                "BLOCK DEVICE",
                "CHARACTER DEVICE",
                "PIPE",
                "SOCKET"};
        return str_ia_type[type];
}

gf_boolean_t
gf_is_zero_filled_stat (struct iatt *buf)
{
        if (!buf)
                return 1;

        /* Do not use st_dev because it is transformed to store the xlator id
         * in place of the device number. Do not use st_ino because by this time
         * we've already mapped the root ino to 1 so it is not guaranteed to be
         * 0.
         */
        if ((buf->ia_nlink == 0) && (buf->ia_ctime == 0))
                return 1;

        return 0;
}

void
gf_zero_fill_stat (struct iatt *buf)
{
        buf->ia_nlink = 0;
        buf->ia_ctime = 0;
}

/* This function checks if the input key is a virtual or on disk xattr.
 * Its not simple to identify a virtual xattr as there is no common
 * format used to identify virtual xattrs. One way is to list each of the
 * xattrs in different categories and compare the input against every xattr
 * in the list, this is very inefficient as there are 100s of xattrs.
 *
 * Currently the only consumer of this function is upcall and md-cache,
 * hence tailoring this function to their needs; in their case its allowed
 * to consider disk xattrs as virtual xattrs, but not vice versa, i.e.
 * virtual xattrs should not be considered as on disk xattr. Hence, being
 * conservative, we consider anything that starts from user.*, security.*,
 * system.* as on disk xattrs. trusted.* and glusterfs.* cannot be considered
 * as virtual xattrs as there are some on disk xattrs which start from
 * glusterfs.* and trusted.*
 *
 * Hence, this function could return an on disk xattr as virtual xattr but
 * never a virtual xattr as on disk xattr.
 */
gf_boolean_t
is_virtual_xattr (const char *k)
{
        gf_boolean_t ret = _gf_true;

        if ((strncmp (k, "user.", strlen ("user.")) == 0) ||
            (strncmp (k, "security.", strlen ("security.")) == 0) ||
            (strncmp (k, "system.", strlen ("system.")) == 0) ||
            (GF_POSIX_ACL_REQUEST (k))) {
                ret = _gf_false;
        }

        return ret;
}

ino_t
gfid_to_ino (uuid_t gfid)
{
        ino_t ino = 0;
        int32_t i;

        for (i = 8; i < 16; i++) {
                ino <<= 8;
                ino += (uint8_t)gfid[i];
        }

        return ino;
}