summaryrefslogtreecommitdiffstats
path: root/scripts/kernel-doc
blob: 08a6c768459e006b4b3dedc14b4765733ba9c561 (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
#!/usr/bin/perl -w

use strict;

## Copyright (c) 1998 Michael Zucchi, All Rights Reserved        ##
## Copyright (C) 2000, 1  Tim Waugh <twaugh@redhat.com>          ##
## Copyright (C) 2001  Simon Huggins                             ##
## Copyright (C) 2005-2012  Randy Dunlap                         ##
## Copyright (C) 2012  Dan Luedtke                               ##
## 								 ##
## #define enhancements by Armin Kuster <akuster@mvista.com>	 ##
## Copyright (c) 2000 MontaVista Software, Inc.			 ##
## 								 ##
## This software falls under the GNU General Public License.     ##
## Please read the COPYING file for more information             ##

# 18/01/2001 - 	Cleanups
# 		Functions prototyped as foo(void) same as foo()
# 		Stop eval'ing where we don't need to.
# -- huggie@earth.li

# 27/06/2001 -  Allowed whitespace after initial "/**" and
#               allowed comments before function declarations.
# -- Christian Kreibich <ck@whoop.org>

# Still to do:
# 	- add perldoc documentation
# 	- Look more closely at some of the scarier bits :)

# 26/05/2001 - 	Support for separate source and object trees.
#		Return error code.
# 		Keith Owens <kaos@ocs.com.au>

# 23/09/2001 - Added support for typedefs, structs, enums and unions
#              Support for Context section; can be terminated using empty line
#              Small fixes (like spaces vs. \s in regex)
# -- Tim Jansen <tim@tjansen.de>

# 25/07/2012 - Added support for HTML5
# -- Dan Luedtke <mail@danrl.de>

#
# This will read a 'c' file and scan for embedded comments in the
# style of gnome comments (+minor extensions - see below).
#

# Note: This only supports 'c'.

# usage:
# kernel-doc [ -docbook | -html | -html5 | -text | -man | -list ]
#            [ -no-doc-sections ]
#            [ -function funcname [ -function funcname ...] ]
#            c file(s)s > outputfile
# or
#            [ -nofunction funcname [ -function funcname ...] ]
#            c file(s)s > outputfile
#
#  Set output format using one of -docbook -html -html5 -text or -man.
#  Default is man.
#  The -list format is for internal use by docproc.
#
#  -no-doc-sections
#	Do not output DOC: sections
#
#  -function funcname
#	If set, then only generate documentation for the given function(s) or
#	DOC: section titles.  All other functions and DOC: sections are ignored.
#
#  -nofunction funcname
#	If set, then only generate documentation for the other function(s)/DOC:
#	sections. Cannot be used together with -function (yes, that's a bug --
#	perl hackers can fix it 8))
#
#  c files - list of 'c' files to process
#
#  All output goes to stdout, with errors to stderr.

#
# format of comments.
# In the following table, (...)? signifies optional structure.
#                         (...)* signifies 0 or more structure elements
# /**
#  * function_name(:)? (- short description)?
# (* @parameterx: (description of parameter x)?)*
# (* a blank line)?
#  * (Description:)? (Description of function)?
#  * (section header: (section description)? )*
#  (*)?*/
#
# So .. the trivial example would be:
#
# /**
#  * my_function
#  */
#
# If the Description: header tag is omitted, then there must be a blank line
# after the last parameter specification.
# e.g.
# /**
#  * my_function - does my stuff
#  * @my_arg: its mine damnit
#  *
#  * Does my stuff explained.
#  */
#
#  or, could also use:
# /**
#  * my_function - does my stuff
#  * @my_arg: its mine damnit
#  * Description: Does my stuff explained.
#  */
# etc.
#
# Besides functions you can also write documentation for structs, unions,
# enums and typedefs. Instead of the function name you must write the name
# of the declaration;  the struct/union/enum/typedef must always precede
# the name. Nesting of declarations is not supported.
# Use the argument mechanism to document members or constants.
# e.g.
# /**
#  * struct my_struct - short description
#  * @a: first member
#  * @b: second member
#  *
#  * Longer description
#  */
# struct my_struct {
#     int a;
#     int b;
# /* private: */
#     int c;
# };
#
# All descriptions can be multiline, except the short function description.
#
# You can also add additional sections. When documenting kernel functions you
# should document the "Context:" of the function, e.g. whether the functions
# can be called form interrupts. Unlike other sections you can end it with an
# empty line.
# A non-void function should have a "Return:" section describing the return
# value(s).
# Example-sections should contain the string EXAMPLE so that they are marked
# appropriately in DocBook.
#
# Example:
# /**
#  * user_function - function that can only be called in user context
#  * @a: some argument
#  * Context: !in_interrupt()
#  *
#  * Some description
#  * Example:
#  *    user_function(22);
#  */
# ...
#
#
# All descriptive text is further processed, scanning for the following special
# patterns, which are highlighted appropriately.
#
# 'funcname()' - function
# '$ENVVAR' - environmental variable
# '&struct_name' - name of a structure (up to two words including 'struct')
# '@parameter' - name of a parameter
# '%CONST' - name of a constant.

## init lots of data

my $errors = 0;
my $warnings = 0;
my $anon_struct_union = 0;

# match expressions used to find embedded type information
my $type_constant = '\%([-_\w]+)';
my $type_func = '(\w+)\(\)';
my $type_param = '\@(\w+)';
my $type_struct = '\&((struct\s*)*[_\w]+)';
my $type_struct_xml = '\\&amp;((struct\s*)*[_\w]+)';
my $type_env = '(\$\w+)';

# Output conversion substitutions.
#  One for each output format

# these work fairly well
my %highlights_html = ( $type_constant, "<i>\$1</i>",
			$type_func, "<b>\$1</b>",
			$type_struct_xml, "<i>\$1</i>",
			$type_env, "<b><i>\$1</i></b>",
			$type_param, "<tt><b>\$1</b></tt>" );
my $local_lt = "\\\\\\\\lt:";
my $local_gt = "\\\\\\\\gt:";
my $blankline_html = $local_lt . "p" . $local_gt;	# was "<p>"

# html version 5
my %highlights_html5 = ( $type_constant, "<span class=\"const\">\$1</span>",
			$type_func, "<span class=\"func\">\$1</span>",
			$type_struct_xml, "<span class=\"struct\">\$1</span>",
			$type_env, "<span class=\"env\">\$1</span>",
			$type_param, "<span class=\"param\">\$1</span>" );
my $blankline_html5 = $local_lt . "br /" . $local_gt;

# XML, docbook format
my %highlights_xml = ( "([^=])\\\"([^\\\"<]+)\\\"", "\$1<quote>\$2</quote>",
			$type_constant, "<constant>\$1</constant>",
			$type_func, "<function>\$1</function>",
			$type_struct_xml, "<structname>\$1</structname>",
			$type_env, "<envar>\$1</envar>",
			$type_param, "<parameter>\$1</parameter>" );
my $blankline_xml = $local_lt . "/para" . $local_gt . $local_lt . "para" . $local_gt . "\n";

# gnome, docbook format
my %highlights_gnome = ( $type_constant, "<replaceable class=\"option\">\$1</replaceable>",
			 $type_func, "<function>\$1</function>",
			 $type_struct, "<structname>\$1</structname>",
			 $type_env, "<envar>\$1</envar>",
			 $type_param, "<parameter>\$1</parameter>" );
my $blankline_gnome = "</para><para>\n";

# these are pretty rough
my %highlights_man = ( $type_constant, "\$1",
		       $type_func, "\\\\fB\$1\\\\fP",
		       $type_struct, "\\\\fI\$1\\\\fP",
		       $type_param, "\\\\fI\$1\\\\fP" );
my $blankline_man = "";

# text-mode
my %highlights_text = ( $type_constant, "\$1",
			$type_func, "\$1",
			$type_struct, "\$1",
			$type_param, "\$1" );
my $blankline_text = "";

# list mode
my %highlights_list = ( $type_constant, "\$1",
			$type_func, "\$1",
			$type_struct, "\$1",
			$type_param, "\$1" );
my $blankline_list = "";

# read arguments
if ($#ARGV == -1) {
    usage();
}

my $kernelversion;
my $dohighlight = "";

my $verbose = 0;
my $output_mode = "man";
my $output_preformatted = 0;
my $no_doc_sections = 0;
my %highlights = %highlights_man;
my $blankline = $blankline_man;
my $modulename = "Bootloader API";
my $function_only = 0;
my $man_date = ('January', 'February', 'March', 'April', 'May', 'June',
		'July', 'August', 'September', 'October',
		'November', 'December')[(localtime)[4]] .
  " " . ((localtime)[5]+1900);
my $show_not_found = 0;

# Essentially these are globals.
# They probably want to be tidied up, made more localised or something.
# CAVEAT EMPTOR!  Some of the others I localised may not want to be, which
# could cause "use of undefined value" or other bugs.
my ($function, %function_table, %parametertypes, $declaration_purpose);
my ($type, $declaration_name, $return_type);
my ($newsection, $newcontents, $prototype, $brcount, %source_map);

if (defined($ENV{'KBUILD_VERBOSE'})) {
	$verbose = "$ENV{'KBUILD_VERBOSE'}";
}

# Generated docbook code is inserted in a template at a point where
# docbook v3.1 requires a non-zero sequence of RefEntry's; see:
# http://www.oasis-open.org/docbook/documentation/reference/html/refentry.html
# We keep track of number of generated entries and generate a dummy
# if needs be to ensure the expanded template can be postprocessed
# into html.
my $section_counter = 0;

my $lineprefix="";

# states
# 0 - normal code
# 1 - looking for function name
# 2 - scanning field start.
# 3 - scanning prototype.
# 4 - documentation block
my $state;
my $in_doc_sect;

#declaration types: can be
# 'function', 'struct', 'union', 'enum', 'typedef'
my $decl_type;

my $doc_special = "\@\%\$\&";

my $doc_start = '^/\*\*\s*$'; # Allow whitespace at end of comment start.
my $doc_end = '\*/';
my $doc_com = '\s*\*\s*';
my $doc_com_body = '\s*\* ?';
my $doc_decl = $doc_com . '(\w+)';
my $doc_sect = $doc_com . '([' . $doc_special . ']?[\w\s]+):(.*)';
my $doc_content = $doc_com_body . '(.*)';
my $doc_block = $doc_com . 'DOC:\s*(.*)?';

my %constants;
my %parameterdescs;
my @parameterlist;
my %sections;
my @sectionlist;
my $sectcheck;
my $struct_actual;

my $contents = "";
my $section_default = "Description";	# default section
my $section_intro = "Introduction";
my $section = $section_default;
my $section_context = "Context";
my $section_return = "Return";

my $undescribed = "-- undescribed --";

reset_state();

while ($ARGV[0] =~ m/^-(.*)/) {
    my $cmd = shift @ARGV;
    if ($cmd eq "-html") {
	$output_mode = "html";
	%highlights = %highlights_html;
	$blankline = $blankline_html;
    } elsif ($cmd eq "-html5") {
	$output_mode = "html5";
	%highlights = %highlights_html5;
	$blankline = $blankline_html5;
    } elsif ($cmd eq "-man") {
	$output_mode = "man";
	%highlights = %highlights_man;
	$blankline = $blankline_man;
    } elsif ($cmd eq "-text") {
	$output_mode = "text";
	%highlights = %highlights_text;
	$blankline = $blankline_text;
    } elsif ($cmd eq "-docbook") {
	$output_mode = "xml";
	%highlights = %highlights_xml;
	$blankline = $blankline_xml;
    } elsif ($cmd eq "-list") {
	$output_mode = "list";
	%highlights = %highlights_list;
	$blankline = $blankline_list;
    } elsif ($cmd eq "-gnome") {
	$output_mode = "gnome";
	%highlights = %highlights_gnome;
	$blankline = $blankline_gnome;
    } elsif ($cmd eq "-module") { # not needed for XML, inherits from calling document
	$modulename = shift @ARGV;
    } elsif ($cmd eq "-function") { # to only output specific functions
	$function_only = 1;
	$function = shift @ARGV;
	$function_table{$function} = 1;
    } elsif ($cmd eq "-nofunction") { # to only output specific functions
	$function_only = 2;
	$function = shift @ARGV;
	$function_table{$function} = 1;
    } elsif ($cmd eq "-v") {
	$verbose = 1;
    } elsif (($cmd eq "-h") || ($cmd eq "--help")) {
	usage();
    } elsif ($cmd eq '-no-doc-sections') {
	    $no_doc_sections = 1;
    } elsif ($cmd eq '-show-not-found') {
	$show_not_found = 1;
    }
}

# continue execution near EOF;

sub usage {
    print "Usage: $0 [ -docbook | -html | -html5 | -text | -man | -list ]\n";
    print "         [ -no-doc-sections ]\n";
    print "         [ -function funcname [ -function funcname ...] ]\n";
    print "         [ -nofunction funcname [ -nofunction funcname ...] ]\n";
    print "         [ -v ]\n";
    print "         c source file(s) > outputfile\n";
    print "         -v : verbose output, more warnings & other info listed\n";
    exit 1;
}

# get kernel version from env
sub get_kernel_version() {
    my $version = 'unknown kernel version';

    if (defined($ENV{'UBOOTVERSION'})) {
	$version = $ENV{'UBOOTVERSION'};
    }
    return $version;
}

##
# dumps section contents to arrays/hashes intended for that purpose.
#
sub dump_section {
    my $file = shift;
    my $name = shift;
    my $contents = join "\n", @_;

    if ($name =~ m/$type_constant/) {
	$name = $1;
#	print STDERR "constant section '$1' = '$contents'\n";
	$constants{$name} = $contents;
    } elsif ($name =~ m/$type_param/) {
#	print STDERR "parameter def '$1' = '$contents'\n";
	$name = $1;
	$parameterdescs{$name} = $contents;
	$sectcheck = $sectcheck . $name . " ";
    } elsif ($name eq "@\.\.\.") {
#	print STDERR "parameter def '...' = '$contents'\n";
	$name = "...";
	$parameterdescs{$name} = $contents;
	$sectcheck = $sectcheck . $name . " ";
    } else {
#	print STDERR "other section '$name' = '$contents'\n";
	if (defined($sections{$name}) && ($sections{$name} ne "")) {
		print STDERR "Error(${file}:$.): duplicate section name '$name'\n";
		++$errors;
	}
	$sections{$name} = $contents;
	push @sectionlist, $name;
    }
}

##
# dump DOC: section after checking that it should go out
#
sub dump_doc_section {
    my $file = shift;
    my $name = shift;
    my $contents = join "\n", @_;

    if ($no_doc_sections) {
        return;
    }

    if (($function_only == 0) ||
	( $function_only == 1 && defined($function_table{$name})) ||
	( $function_only == 2 && !defined($function_table{$name})))
    {
	dump_section($file, $name, $contents);
	output_blockhead({'sectionlist' => \@sectionlist,
			  'sections' => \%sections,
			  'module' => $modulename,
			  'content-only' => ($function_only != 0), });
    }
}

##
# output function
#
# parameterdescs, a hash.
#  function => "function name"
#  parameterlist => @list of parameters
#  parameterdescs => %parameter descriptions
#  sectionlist => @list of sections
#  sections => %section descriptions
#

sub output_highlight {
    my $contents = join "\n",@_;
    my $line;

#   DEBUG
#   if (!defined $contents) {
#	use Carp;
#	confess "output_highlight got called with no args?\n";
#   }

    if ($output_mode eq "html" || $output_mode eq "html5" ||
	$output_mode eq "xml") {
	$contents = local_unescape($contents);
	# convert data read & converted thru xml_escape() into &xyz; format:
	$contents =~ s/\\\\\\/\&/g;
    }
#   print STDERR "contents b4:$contents\n";
    eval $dohighlight;
    die $@ if $@;
#   print STDERR "contents af:$contents\n";

#   strip whitespaces when generating html5
    if ($output_mode eq "html5") {
	$contents =~ s/^\s+//;
	$contents =~ s/\s+$//;
    }
    foreach $line (split "\n", $contents) {
	if (! $output_preformatted) {
	    $line =~ s/^\s*//;
	}
	if ($line eq ""){
	    if (! $output_preformatted) {
		print $lineprefix, local_unescape($blankline);
	    }
	} else {
	    $line =~ s/\\\\\\/\&/g;
	    if ($output_mode eq "man" && substr($line, 0, 1) eq ".") {
		print "\\&$line";
	    } else {
		print $lineprefix, $line;
	    }
	}
	print "\n";
    }
}

# output sections in html
sub output_section_html(%) {
    my %args = %{$_[0]};
    my $section;

    foreach $section (@{$args{'sectionlist'}}) {
	print "<h3>$section</h3>\n";
	print "<blockquote>\n";
	output_highlight($args{'sections'}{$section});
	print "</blockquote>\n";
    }
}

# output enum in html
sub output_enum_html(%) {
    my %args = %{$_[0]};
    my ($parameter);
    my $count;
    print "<h2>enum " . $args{'enum'} . "</h2>\n";

    print "<b>enum " . $args{'enum'} . "</b> {<br>\n";
    $count = 0;
    foreach $parameter (@{$args{'parameterlist'}}) {
	print " <b>" . $parameter . "</b>";
	if ($count != $#{$args{'parameterlist'}}) {
	    $count++;
	    print ",\n";
	}
	print "<br>";
    }
    print "};<br>\n";

    print "<h3>Constants</h3>\n";
    print "<dl>\n";
    foreach $parameter (@{$args{'parameterlist'}}) {
	print "<dt><b>" . $parameter . "</b>\n";
	print "<dd>";
	output_highlight($args{'parameterdescs'}{$parameter});
    }
    print "</dl>\n";
    output_section_html(@_);
    print "<hr>\n";
}

# output typedef in html
sub output_typedef_html(%) {
    my %args = %{$_[0]};
    my ($parameter);
    my $count;
    print "<h2>typedef " . $args{'typedef'} . "</h2>\n";

    print "<b>typedef " . $args{'typedef'} . "</b>\n";
    output_section_html(@_);
    print "<hr>\n";
}

# output struct in html
sub output_struct_html(%) {
    my %args = %{$_[0]};
    my ($parameter);

    print "<h2>" . $args{'type'} . " " . $args{'struct'} . " - " . $args{'purpose'} . "</h2>\n";
    print "<b>" . $args{'type'} . " " . $args{'struct'} . "</b> {<br>\n";
    foreach $parameter (@{$args{'parameterlist'}}) {
	if ($parameter =~ /^#/) {
		print "$parameter<br>\n";
		next;
	}
	my $parameter_name = $parameter;
	$parameter_name =~ s/\[.*//;

	($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
	$type = $args{'parametertypes'}{$parameter};
	if ($type =~ m/([^\(]*\(\*)\s*\)\s*\(([^\)]*)\)/) {
	    # pointer-to-function
	    print "&nbsp; &nbsp; <i>$1</i><b>$parameter</b>) <i>($2)</i>;<br>\n";
	} elsif ($type =~ m/^(.*?)\s*(:.*)/) {
	    # bitfield
	    print "&nbsp; &nbsp; <i>$1</i> <b>$parameter</b>$2;<br>\n";
	} else {
	    print "&nbsp; &nbsp; <i>$type</i> <b>$parameter</b>;<br>\n";
	}
    }
    print "};<br>\n";

    print "<h3>Members</h3>\n";
    print "<dl>\n";
    foreach $parameter (@{$args{'parameterlist'}}) {
	($parameter =~ /^#/) && next;

	my $parameter_name = $parameter;
	$parameter_name =~ s/\[.*//;

	($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
	print "<dt><b>" . $parameter . "</b>\n";
	print "<dd>";
	output_highlight($args{'parameterdescs'}{$parameter_name});
    }
    print "</dl>\n";
    output_section_html(@_);
    print "<hr>\n";
}

# output function in html
sub output_function_html(%) {
    my %args = %{$_[0]};
    my ($parameter, $section);
    my $count;

    print "<h2>" . $args{'function'} . " - " . $args{'purpose'} . "</h2>\n";
    print "<i>" . $args{'functiontype'} . "</i>\n";
    print "<b>" . $args{'function'} . "</b>\n";
    print "(";
    $count = 0;
    foreach $parameter (@{$args{'parameterlist'}}) {
	$type = $args{'parametertypes'}{$parameter};
	if ($type =~ m/([^\(]*\(\*)\s*\)\s*\(([^\)]*)\)/) {
	    # pointer-to-function
	    print "<i>$1</i><b>$parameter</b>) <i>($2)</i>";
	} else {
	    print "<i>" . $type . "</i> <b>" . $parameter . "</b>";
	}
	if ($count != $#{$args{'parameterlist'}}) {
	    $count++;
	    print ",\n";
	}
    }
    print ")\n";

    print "<h3>Arguments</h3>\n";
    print "<dl>\n";
    foreach $parameter (@{$args{'parameterlist'}}) {
	my $parameter_name = $parameter;
	$parameter_name =~ s/\[.*//;

	($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
	print "<dt><b>" . $parameter . "</b>\n";
	print "<dd>";
	output_highlight($args{'parameterdescs'}{$parameter_name});
    }
    print "</dl>\n";
    output_section_html(@_);
    print "<hr>\n";
}

# output DOC: block header in html
sub output_blockhead_html(%) {
    my %args = %{$_[0]};
    my ($parameter, $section);
    my $count;

    foreach $section (@{$args{'sectionlist'}}) {
	print "<h3>$section</h3>\n";
	print "<ul>\n";
	output_highlight($args{'sections'}{$section});
	print "</ul>\n";
    }
    print "<hr>\n";
}

# output sections in html5
sub output_section_html5(%) {
    my %args = %{$_[0]};
    my $section;

    foreach $section (@{$args{'sectionlist'}}) {
	print "<section>\n";
	print "<h1>$section</h1>\n";
	print "<p>\n";
	output_highlight($args{'sections'}{$section});
	print "</p>\n";
	print "</section>\n";
    }
}

# output enum in html5
sub output_enum_html5(%) {
    my %args = %{$_[0]};
    my ($parameter);
    my $count;
    my $html5id;

    $html5id = $args{'enum'};
    $html5id =~ s/[^a-zA-Z0-9\-]+/_/g;
    print "<article class=\"enum\" id=\"enum:". $html5id . "\">";
    print "<h1>enum " . $args{'enum'} . "</h1>\n";
    print "<ol class=\"code\">\n";
    print "<li>";
    print "<span class=\"keyword\">enum</span> ";
    print "<span class=\"identifier\">" . $args{'enum'} . "</span> {";
    print "</li>\n";
    $count = 0;
    foreach $parameter (@{$args{'parameterlist'}}) {
	print "<li class=\"indent\">";
	print "<span class=\"param\">" . $parameter . "</span>";
	if ($count != $#{$args{'parameterlist'}}) {
	    $count++;
	    print ",";
	}
	print "</li>\n";
    }
    print "<li>};</li>\n";
    print "</ol>\n";

    print "<section>\n";
    print "<h1>Constants</h1>\n";
    print "<dl>\n";
    foreach $parameter (@{$args{'parameterlist'}}) {
	print "<dt>" . $parameter . "</dt>\n";
	print "<dd>";
	output_highlight($args{'parameterdescs'}{$parameter});
	print "</dd>\n";
    }
    print "</dl>\n";
    print "</section>\n";
    output_section_html5(@_);
    print "</article>\n";
}

# output typedef in html5
sub output_typedef_html5(%) {
    my %args = %{$_[0]};
    my ($parameter);
    my $count;
    my $html5id;

    $html5id = $args{'typedef'};
    $html5id =~ s/[^a-zA-Z0-9\-]+/_/g;
    print "<article class=\"typedef\" id=\"typedef:" . $html5id . "\">\n";
    print "<h1>typedef " . $args{'typedef'} . "</h1>\n";

    print "<ol class=\"code\">\n";
    print "<li>";
    print "<span class=\"keyword\">typedef</span> ";
    print "<span class=\"identifier\">" . $args{'typedef'} . "</span>";
    print "</li>\n";
    print "</ol>\n";
    output_section_html5(@_);
    print "</article>\n";
}

# output struct in html5
sub output_struct_html5(%) {
    my %args = %{$_[0]};
    my ($parameter);
    my $html5id;

    $html5id = $args{'struct'};
    $html5id =~ s/[^a-zA-Z0-9\-]+/_/g;
    print "<article class=\"struct\" id=\"struct:" . $html5id . "\">\n";
    print "<hgroup>\n";
    print "<h1>" . $args{'type'} . " " . $args{'struct'} . "</h1>";
    print "<h2>". $args{'purpose'} . "</h2>\n";
    print "</hgroup>\n";
    print "<ol class=\"code\">\n";
    print "<li>";
    print "<span class=\"type\">" . $args{'type'} . "</span> ";
    print "<span class=\"identifier\">" . $args{'struct'} . "</span> {";
    print "</li>\n";
    foreach $parameter (@{$args{'parameterlist'}}) {
	print "<li class=\"indent\">";
	if ($parameter =~ /^#/) {
		print "<span class=\"param\">" . $parameter ."</span>\n";
		print "</li>\n";
		next;
	}
	my $parameter_name = $parameter;
	$parameter_name =~ s/\[.*//;

	($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
	$type = $args{'parametertypes'}{$parameter};
	if ($type =~ m/([^\(]*\(\*)\s*\)\s*\(([^\)]*)\)/) {
	    # pointer-to-function
	    print "<span class=\"type\">$1</span> ";
	    print "<span class=\"param\">$parameter</span>";
	    print "<span class=\"type\">)</span> ";
	    print "(<span class=\"args\">$2</span>);";
	} elsif ($type =~ m/^(.*?)\s*(:.*)/) {
	    # bitfield
	    print "<span class=\"type\">$1</span> ";
	    print "<span class=\"param\">$parameter</span>";
	    print "<span class=\"bits\">$2</span>;";
	} else {
	    print "<span class=\"type\">$type</span> ";
	    print "<span class=\"param\">$parameter</span>;";
	}
	print "</li>\n";
    }
    print "<li>};</li>\n";
    print "</ol>\n";

    print "<section>\n";
    print "<h1>Members</h1>\n";
    print "<dl>\n";
    foreach $parameter (@{$args{'parameterlist'}}) {
	($parameter =~ /^#/) && next;

	my $parameter_name = $parameter;
	$parameter_name =~ s/\[.*//;

	($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
	print "<dt>" . $parameter . "</dt>\n";
	print "<dd>";
	output_highlight($args{'parameterdescs'}{$parameter_name});
	print "</dd>\n";
    }
    print "</dl>\n";
    print "</section>\n";
    output_section_html5(@_);
    print "</article>\n";
}

# output function in html5
sub output_function_html5(%) {
    my %args = %{$_[0]};
    my ($parameter, $section);
    my $count;
    my $html5id;

    $html5id = $args{'function'};
    $html5id =~ s/[^a-zA-Z0-9\-]+/_/g;
    print "<article class=\"function\" id=\"func:". $html5id . "\">\n";
    print "<hgroup>\n";
    print "<h1>" . $args{'function'} . "</h1>";
    print "<h2>" . $args{'purpose'} . "</h2>\n";
    print "</hgroup>\n";
    print "<ol class=\"code\">\n";
    print "<li>";
    print "<span class=\"type\">" . $args{'functiontype'} . "</span> ";
    print "<span class=\"identifier\">" . $args{'function'} . "</span> (";
    print "</li>";
    $count = 0;
    foreach $parameter (@{$args{'parameterlist'}}) {
	print "<li class=\"indent\">";
	$type = $args{'parametertypes'}{$parameter};
	if ($type =~ m/([^\(]*\(\*)\s*\)\s*\(([^\)]*)\)/) {
	    # pointer-to-function
	    print "<span class=\"type\">$1</span> ";
	    print "<span class=\"param\">$parameter</span>";
	    print "<span class=\"type\">)</span> ";
	    print "(<span class=\"args\">$2</span>)";
	} else {
	    print "<span class=\"type\">$type</span> ";
	    print "<span class=\"param\">$parameter</span>";
	}
	if ($count != $#{$args{'parameterlist'}}) {
	    $count++;
	    print ",";
	}
	print "</li>\n";
    }
    print "<li>)</li>\n";
    print "</ol>\n";

    print "<section>\n";
    print "<h1>Arguments</h1>\n";
    print "<p>\n";
    print "<dl>\n";
    foreach $parameter (@{$args{'parameterlist'}}) {
	my $parameter_name = $parameter;
	$parameter_name =~ s/\[.*//;

	($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
	print "<dt>" . $parameter . "</dt>\n";
	print "<dd>";
	output_highlight($args{'parameterdescs'}{$parameter_name});
	print "</dd>\n";
    }
    print "</dl>\n";
    print "</section>\n";
    output_section_html5(@_);
    print "</article>\n";
}

# output DOC: block header in html5
sub output_blockhead_html5(%) {
    my %args = %{$_[0]};
    my ($parameter, $section);
    my $count;
    my $html5id;

    foreach $section (@{$args{'sectionlist'}}) {
	$html5id = $section;
	$html5id =~ s/[^a-zA-Z0-9\-]+/_/g;
	print "<article class=\"doc\" id=\"doc:". $html5id . "\">\n";
	print "<h1>$section</h1>\n";
	print "<p>\n";
	output_highlight($args{'sections'}{$section});
	print "</p>\n";
    }
    print "</article>\n";
}

sub output_section_xml(%) {
    my %args = %{$_[0]};
    my $section;
    # print out each section
    $lineprefix="   ";
    foreach $section (@{$args{'sectionlist'}}) {
	print "<refsect1>\n";
	print "<title>$section</title>\n";
	if ($section =~ m/EXAMPLE/i) {
	    print "<informalexample><programlisting>\n";
	    $output_preformatted = 1;
	} else {
	    print "<para>\n";
	}
	output_highlight($args{'sections'}{$section});
	$output_preformatted = 0;
	if ($section =~ m/EXAMPLE/i) {
	    print "</programlisting></informalexample>\n";
	} else {
	    print "</para>\n";
	}
	print "</refsect1>\n";
    }
}

# output function in XML DocBook
sub output_function_xml(%) {
    my %args = %{$_[0]};
    my ($parameter, $section);
    my $count;
    my $id;

    $id = "API-" . $args{'function'};
    $id =~ s/[^A-Za-z0-9]/-/g;

    print "<refentry id=\"$id\">\n";
    print "<refentryinfo>\n";
    print " <title>U-BOOT</title>\n";
    print " <productname>Bootloader Hackers Manual</productname>\n";
    print " <date>$man_date</date>\n";
    print "</refentryinfo>\n";
    print "<refmeta>\n";
    print " <refentrytitle><phrase>" . $args{'function'} . "</phrase></refentrytitle>\n";
    print " <manvolnum>9</manvolnum>\n";
    print " <refmiscinfo class=\"version\">" . $kernelversion . "</refmiscinfo>\n";
    print "</refmeta>\n";
    print "<refnamediv>\n";
    print " <refname>" . $args{'function'} . "</refname>\n";
    print " <refpurpose>\n";
    print "  ";
    output_highlight ($args{'purpose'});
    print " </refpurpose>\n";
    print "</refnamediv>\n";

    print "<refsynopsisdiv>\n";
    print " <title>Synopsis</title>\n";
    print "  <funcsynopsis><funcprototype>\n";
    print "   <funcdef>" . $args{'functiontype'} . " ";
    print "<function>" . $args{'function'} . " </function></funcdef>\n";

    $count = 0;
    if ($#{$args{'parameterlist'}} >= 0) {
	foreach $parameter (@{$args{'parameterlist'}}) {
	    $type = $args{'parametertypes'}{$parameter};
	    if ($type =~ m/([^\(]*\(\*)\s*\)\s*\(([^\)]*)\)/) {
		# pointer-to-function
		print "   <paramdef>$1<parameter>$parameter</parameter>)\n";
		print "     <funcparams>$2</funcparams></paramdef>\n";
	    } else {
		print "   <paramdef>" . $type;
		print " <parameter>$parameter</parameter></paramdef>\n";
	    }
	}
    } else {
	print "  <void/>\n";
    }
    print "  </funcprototype></funcsynopsis>\n";
    print "</refsynopsisdiv>\n";

    # print parameters
    print "<refsect1>\n <title>Arguments</title>\n";
    if ($#{$args{'parameterlist'}} >= 0) {
	print " <variablelist>\n";
	foreach $parameter (@{$args{'parameterlist'}}) {
	    my $parameter_name = $parameter;
	    $parameter_name =~ s/\[.*//;

	    print "  <varlistentry>\n   <term><parameter>$parameter</parameter></term>\n";
	    print "   <listitem>\n    <para>\n";
	    $lineprefix="     ";
	    output_highlight($args{'parameterdescs'}{$parameter_name});
	    print "    </para>\n   </listitem>\n  </varlistentry>\n";
	}
	print " </variablelist>\n";
    } else {
	print " <para>\n  None\n </para>\n";
    }
    print "</refsect1>\n";

    output_section_xml(@_);
    print "</refentry>\n\n";
}

# output struct in XML DocBook
sub output_struct_xml(%) {
    my %args = %{$_[0]};
    my ($parameter, $section);
    my $id;

    $id = "API-struct-" . $args{'struct'};
    $id =~ s/[^A-Za-z0-9]/-/g;

    print "<refentry id=\"$id\">\n";
    print "<refentryinfo>\n";
    print " <title>U-BOOT</title>\n";
    print " <productname>Bootloader Hackers Manual</productname>\n";
    print " <date>$man_date</date>\n";
    print "</refentryinfo>\n";
    print "<refmeta>\n";
    print " <refentrytitle><phrase>" . $args{'type'} . " " . $args{'struct'} . "</phrase></refentrytitle>\n";
    print " <manvolnum>9</manvolnum>\n";
    print " <refmiscinfo class=\"version\">" . $kernelversion . "</refmiscinfo>\n";
    print "</refmeta>\n";
    print "<refnamediv>\n";
    print " <refname>" . $args{'type'} . " " . $args{'struct'} . "</refname>\n";
    print " <refpurpose>\n";
    print "  ";
    output_highlight ($args{'purpose'});
    print " </refpurpose>\n";
    print "</refnamediv>\n";

    print "<refsynopsisdiv>\n";
    print " <title>Synopsis</title>\n";
    print "  <programlisting>\n";
    print $args{'type'} . " " . $args{'struct'} . " {\n";
    foreach $parameter (@{$args{'parameterlist'}}) {
	if ($parameter =~ /^#/) {
	    my $prm = $parameter;
	    # convert data read & converted thru xml_escape() into &xyz; format:
	    # This allows us to have #define macros interspersed in a struct.
	    $prm =~ s/\\\\\\/\&/g;
	    print "$prm\n";
	    next;
	}

	my $parameter_name = $parameter;
	$parameter_name =~ s/\[.*//;

	defined($args{'parameterdescs'}{$parameter_name}) || next;
	($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
	$type = $args{'parametertypes'}{$parameter};
	if ($type =~ m/([^\(]*\(\*)\s*\)\s*\(([^\)]*)\)/) {
	    # pointer-to-function
	    print "  $1 $parameter) ($2);\n";
	} elsif ($type =~ m/^(.*?)\s*(:.*)/) {
	    # bitfield
	    print "  $1 $parameter$2;\n";
	} else {
	    print "  " . $type . " " . $parameter . ";\n";
	}
    }
    print "};";
    print "  </programlisting>\n";
    print "</refsynopsisdiv>\n";

    print " <refsect1>\n";
    print "  <title>Members</title>\n";

    if ($#{$args{'parameterlist'}} >= 0) {
    print "  <variablelist>\n";
    foreach $parameter (@{$args{'parameterlist'}}) {
      ($parameter =~ /^#/) && next;

      my $parameter_name = $parameter;
      $parameter_name =~ s/\[.*//;

      defined($args{'parameterdescs'}{$parameter_name}) || next;
      ($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
      print "    <varlistentry>";
      print "      <term>$parameter</term>\n";
      print "      <listitem><para>\n";
      output_highlight($args{'parameterdescs'}{$parameter_name});
      print "      </para></listitem>\n";
      print "    </varlistentry>\n";
    }
    print "  </variablelist>\n";
    } else {
	print " <para>\n  None\n </para>\n";
    }
    print " </refsect1>\n";

    output_section_xml(@_);

    print "</refentry>\n\n";
}

# output enum in XML DocBook
sub output_enum_xml(%) {
    my %args = %{$_[0]};
    my ($parameter, $section);
    my $count;
    my $id;

    $id = "API-enum-" . $args{'enum'};
    $id =~ s/[^A-Za-z0-9]/-/g;

    print "<refentry id=\"$id\">\n";
    print "<refentryinfo>\n";
    print " <title>U-BOOT</title>\n";
    print " <productname>Bootloader Hackers Manual</productname>\n";
    print " <date>$man_date</date>\n";
    print "</refentryinfo>\n";
    print "<refmeta>\n";
    print " <refentrytitle><phrase>enum " . $args{'enum'} . "</phrase></refentrytitle>\n";
    print " <manvolnum>9</manvolnum>\n";
    print " <refmiscinfo class=\"version\">" . $kernelversion . "</refmiscinfo>\n";
    print "</refmeta>\n";
    print "<refnamediv>\n";
    print " <refname>enum " . $args{'enum'} . "</refname>\n";
    print " <refpurpose>\n";
    print "  ";
    output_highlight ($args{'purpose'});
    print " </refpurpose>\n";
    print "</refnamediv>\n";

    print "<refsynopsisdiv>\n";
    print " <title>Synopsis</title>\n";
    print "  <programlisting>\n";
    print "enum " . $args{'enum'} . " {\n";
    $count = 0;
    foreach $parameter (@{$args{'parameterlist'}}) {
	print "  $parameter";
	if ($count != $#{$args{'parameterlist'}}) {
	    $count++;
	    print ",";
	}
	print "\n";
    }
    print "};";
    print "  </programlisting>\n";
    print "</refsynopsisdiv>\n";

    print "<refsect1>\n";
    print " <title>Constants</title>\n";
    print "  <variablelist>\n";
    foreach $parameter (@{$args{'parameterlist'}}) {
      my $parameter_name = $parameter;
      $parameter_name =~ s/\[.*//;

      print "    <varlistentry>";
      print "      <term>$parameter</term>\n";
      print "      <listitem><para>\n";
      output_highlight($args{'parameterdescs'}{$parameter_name});
      print "      </para></listitem>\n";
      print "    </varlistentry>\n";
    }
    print "  </variablelist>\n";
    print "</refsect1>\n";

    output_section_xml(@_);

    print "</refentry>\n\n";
}

# output typedef in XML DocBook
sub output_typedef_xml(%) {
    my %args = %{$_[0]};
    my ($parameter, $section);
    my $id;

    $id = "API-typedef-" . $args{'typedef'};
    $id =~ s/[^A-Za-z0-9]/-/g;

    print "<refentry id=\"$id\">\n";
    print "<refentryinfo>\n";
    print " <title>U-BOOT</title>\n";
    print " <productname>Bootloader Hackers Manual</productname>\n";
    print " <date>$man_date</date>\n";
    print "</refentryinfo>\n";
    print "<refmeta>\n";
    print " <refentrytitle><phrase>typedef " . $args{'typedef'} . "</phrase></refentrytitle>\n";
    print " <manvolnum>9</manvolnum>\n";
    print "</refmeta>\n";
    print "<refnamediv>\n";
    print " <refname>typedef " . $args{'typedef'} . "</refname>\n";
    print " <refpurpose>\n";
    print "  ";
    output_highlight ($args{'purpose'});
    print " </refpurpose>\n";
    print "</refnamediv>\n";

    print "<refsynopsisdiv>\n";
    print " <title>Synopsis</title>\n";
    print "  <synopsis>typedef " . $args{'typedef'} . ";</synopsis>\n";
    print "</refsynopsisdiv>\n";

    output_section_xml(@_);

    print "</refentry>\n\n";
}

# output in XML DocBook
sub output_blockhead_xml(%) {
    my %args = %{$_[0]};
    my ($parameter, $section);
    my $count;

    my $id = $args{'module'};
    $id =~ s/[^A-Za-z0-9]/-/g;

    # print out each section
    $lineprefix="   ";
    foreach $section (@{$args{'sectionlist'}}) {
	if (!$args{'content-only'}) {
		print "<refsect1>\n <title>$section</title>\n";
	}
	if ($section =~ m/EXAMPLE/i) {
	    print "<example><para>\n";
	    $output_preformatted = 1;
	} else {
	    print "<para>\n";
	}
	output_highlight($args{'sections'}{$section});
	$output_preformatted = 0;
	if ($section =~ m/EXAMPLE/i) {
	    print "</para></example>\n";
	} else {
	    print "</para>";
	}
	if (!$args{'content-only'}) {
		print "\n</refsect1>\n";
	}
    }

    print "\n\n";
}

# output in XML DocBook
sub output_function_gnome {
    my %args = %{$_[0]};
    my ($parameter, $section);
    my $count;
    my $id;

    $id = $args{'module'} . "-" . $args{'function'};
    $id =~ s/[^A-Za-z0-9]/-/g;

    print "<sect2>\n";
    print " <title id=\"$id\">" . $args{'function'} . "</title>\n";

    print "  <funcsynopsis>\n";
    print "   <funcdef>" . $args{'functiontype'} . " ";
    print "<function>" . $args{'function'} . " ";
    print "</function></funcdef>\n";

    $count = 0;
    if ($#{$args{'parameterlist'}} >= 0) {
	foreach $parameter (@{$args{'parameterlist'}}) {
	    $type = $args{'parametertypes'}{$parameter};
	    if ($type =~ m/([^\(]*\(\*)\s*\)\s*\(([^\)]*)\)/) {
		# pointer-to-function
		print "   <paramdef>$1 <parameter>$parameter</parameter>)\n";
		print "     <funcparams>$2</funcparams></paramdef>\n";
	    } else {
		print "   <paramdef>" . $type;
		print " <parameter>$parameter</parameter></paramdef>\n";
	    }
	}
    } else {
	print "  <void>\n";
    }
    print "  </funcsynopsis>\n";
    if ($#{$args{'parameterlist'}} >= 0) {
	print " <informaltable pgwide=\"1\" frame=\"none\" role=\"params\">\n";
	print "<tgroup cols=\"2\">\n";
	print "<colspec colwidth=\"2*\">\n";
	print "<colspec colwidth=\"8*\">\n";
	print "<tbody>\n";
	foreach $parameter (@{$args{'parameterlist'}}) {
	    my $parameter_name = $parameter;
	    $parameter_name =~ s/\[.*//;

	    print "  <row><entry align=\"right\"><parameter>$parameter</parameter></entry>\n";
	    print "   <entry>\n";
	    $lineprefix="     ";
	    output_highlight($args{'parameterdescs'}{$parameter_name});
	    print "    </entry></row>\n";
	}
	print " </tbody></tgroup></informaltable>\n";
    } else {
	print " <para>\n  None\n </para>\n";
    }

    # print out each section
    $lineprefix="   ";
    foreach $section (@{$args{'sectionlist'}}) {
	print "<simplesect>\n <title>$section</title>\n";
	if ($section =~ m/EXAMPLE/i) {
	    print "<example><programlisting>\n";
	    $output_preformatted = 1;
	} else {
	}
	print "<para>\n";
	output_highlight($args{'sections'}{$section});
	$output_preformatted = 0;
	print "</para>\n";
	if ($section =~ m/EXAMPLE/i) {
	    print "</programlisting></example>\n";
	} else {
	}
	print " </simplesect>\n";
    }

    print "</sect2>\n\n";
}

##
# output function in man
sub output_function_man(%) {
    my %args = %{$_[0]};
    my ($parameter, $section);
    my $count;

    print ".TH \"$args{'function'}\" 9 \"$args{'function'}\" \"$man_date\" \"Bootloader Hacker's Manual\" U-BOOT\n";

    print ".SH NAME\n";
    print $args{'function'} . " \\- " . $args{'purpose'} . "\n";

    print ".SH SYNOPSIS\n";
    if ($args{'functiontype'} ne "") {
	print ".B \"" . $args{'functiontype'} . "\" " . $args{'function'} . "\n";
    } else {
	print ".B \"" . $args{'function'} . "\n";
    }
    $count = 0;
    my $parenth = "(";
    my $post = ",";
    foreach my $parameter (@{$args{'parameterlist'}}) {
	if ($count == $#{$args{'parameterlist'}}) {
	    $post = ");";
	}
	$type = $args{'parametertypes'}{$parameter};
	if ($type =~ m/([^\(]*\(\*)\s*\)\s*\(([^\)]*)\)/) {
	    # pointer-to-function
	    print ".BI \"" . $parenth . $1 . "\" " . $parameter . " \") (" . $2 . ")" . $post . "\"\n";
	} else {
	    $type =~ s/([^\*])$/$1 /;
	    print ".BI \"" . $parenth . $type . "\" " . $parameter . " \"" . $post . "\"\n";
	}
	$count++;
	$parenth = "";
    }

    print ".SH ARGUMENTS\n";
    foreach $parameter (@{$args{'parameterlist'}}) {
	my $parameter_name = $parameter;
	$parameter_name =~ s/\[.*//;

	print ".IP \"" . $parameter . "\" 12\n";
	output_highlight($args{'parameterdescs'}{$parameter_name});
    }
    foreach $section (@{$args{'sectionlist'}}) {
	print ".SH \"", uc $section, "\"\n";
	output_highlight($args{'sections'}{$section});
    }
}

##
# output enum in man
sub output_enum_man(%) {
    my %args = %{$_[0]};
    my ($parameter, $section);
    my $count;

    print ".TH \"$args{'module'}\" 9 \"enum $args{'enum'}\" \"$man_date\" \"API Manual\" U-BOOT\n";

    print ".SH NAME\n";
    print "enum " . $args{'enum'} . " \\- " . $args{'purpose'} . "\n";

    print ".SH SYNOPSIS\n";
    print "enum " . $args{'enum'} . " {\n";
    $count = 0;
    foreach my $parameter (@{$args{'parameterlist'}}) {
	print ".br\n.BI \"    $parameter\"\n";
	if ($count == $#{$args{'parameterlist'}}) {
	    print "\n};\n";
	    last;
	}
	else {
	    print ", \n.br\n";
	}
	$count++;
    }

    print ".SH Constants\n";
    foreach $parameter (@{$args{'parameterlist'}}) {
	my $parameter_name = $parameter;
	$parameter_name =~ s/\[.*//;

	print ".IP \"" . $parameter . "\" 12\n";
	output_highlight($args{'parameterdescs'}{$parameter_name});
    }
    foreach $section (@{$args{'sectionlist'}}) {
	print ".SH \"$section\"\n";
	output_highlight($args{'sections'}{$section});
    }
}

##
# output struct in man
sub output_struct_man(%) {
    my %args = %{$_[0]};
    my ($parameter, $section);

    print ".TH \"$args{'module'}\" 9 \"" . $args{'type'} . " " . $args{'struct'} . "\" \"$man_date\" \"API Manual\" U-BOOT\n";

    print ".SH NAME\n";
    print $args{'type'} . " " . $args{'struct'} . " \\- " . $args{'purpose'} . "\n";

    print ".SH SYNOPSIS\n";
    print $args{'type'} . " " . $args{'struct'} . " {\n.br\n";

    foreach my $parameter (@{$args{'parameterlist'}}) {
	if ($parameter =~ /^#/) {
	    print ".BI \"$parameter\"\n.br\n";
	    next;
	}
	my $parameter_name = $parameter;
	$parameter_name =~ s/\[.*//;

	($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
	$type = $args{'parametertypes'}{$parameter};
	if ($type =~ m/([^\(]*\(\*)\s*\)\s*\(([^\)]*)\)/) {
	    # pointer-to-function
	    print ".BI \"    " . $1 . "\" " . $parameter . " \") (" . $2 . ")" . "\"\n;\n";
	} elsif ($type =~ m/^(.*?)\s*(:.*)/) {
	    # bitfield
	    print ".BI \"    " . $1 . "\ \" " . $parameter . $2 . " \"" . "\"\n;\n";
	} else {
	    $type =~ s/([^\*])$/$1 /;
	    print ".BI \"    " . $type . "\" " . $parameter . " \"" . "\"\n;\n";
	}
	print "\n.br\n";
    }
    print "};\n.br\n";

    print ".SH Members\n";
    foreach $parameter (@{$args{'parameterlist'}}) {
	($parameter =~ /^#/) && next;

	my $parameter_name = $parameter;
	$parameter_name =~ s/\[.*//;

	($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
	print ".IP \"" . $parameter . "\" 12\n";
	output_highlight($args{'parameterdescs'}{$parameter_name});
    }
    foreach $section (@{$args{'sectionlist'}}) {
	print ".SH \"$section\"\n";
	output_highlight($args{'sections'}{$section});
    }
}

##
# output typedef in man
sub output_typedef_man(%) {
    my %args = %{$_[0]};
    my ($parameter, $section);

    print ".TH \"$args{'module'}\" 9 \"$args{'typedef'}\" \"$man_date\" \"API Manual\" U-BOOT\n";

    print ".SH NAME\n";
    print "typedef " . $args{'typedef'} . " \\- " . $args{'purpose'} . "\n";

    foreach $section (@{$args{'sectionlist'}}) {
	print ".SH \"$section\"\n";
	output_highlight($args{'sections'}{$section});
    }
}

sub output_blockhead_man(%) {
    my %args = %{$_[0]};
    my ($parameter, $section);
    my $count;

    print ".TH \"$args{'module'}\" 9 \"$args{'module'}\" \"$man_date\" \"API Manual\" U-BOOT\n";

    foreach $section (@{$args{'sectionlist'}}) {
	print ".SH \"$section\"\n";
	output_highlight($args{'sections'}{$section});
    }
}

##
# output in text
sub output_function_text(%) {
    my %args = %{$_[0]};
    my ($parameter, $section);
    my $start;

    print "Name:\n\n";
    print $args{'function'} . " - " . $args{'purpose'} . "\n";

    print "\nSynopsis:\n\n";
    if ($args{'functiontype'} ne "") {
	$start = $args{'functiontype'} . " " . $args{'function'} . " (";
    } else {
	$start = $args{'function'} . " (";
    }
    print $start;

    my $count = 0;
    foreach my $parameter (@{$args{'parameterlist'}}) {
	$type = $args{'parametertypes'}{$parameter};
	if ($type =~ m/([^\(]*\(\*)\s*\)\s*\(([^\)]*)\)/) {
	    # pointer-to-function
	    print $1 . $parameter . ") (" . $2;
	} else {
	    print $type . " " . $parameter;
	}
	if ($count != $#{$args{'parameterlist'}}) {
	    $count++;
	    print ",\n";
	    print " " x length($start);
	} else {
	    print ");\n\n";
	}
    }

    print "Arguments:\n\n";
    foreach $parameter (@{$args{'parameterlist'}}) {
	my $parameter_name = $parameter;
	$parameter_name =~ s/\[.*//;

	print $parameter . "\n\t" . $args{'parameterdescs'}{$parameter_name} . "\n";
    }
    output_section_text(@_);
}

#output sections in text
sub output_section_text(%) {
    my %args = %{$_[0]};
    my $section;

    print "\n";
    foreach $section (@{$args{'sectionlist'}}) {
	print "$section:\n\n";
	output_highlight($args{'sections'}{$section});
    }
    print "\n\n";
}

# output enum in text
sub output_enum_text(%) {
    my %args = %{$_[0]};
    my ($parameter);
    my $count;
    print "Enum:\n\n";

    print "enum " . $args{'enum'} . " - " . $args{'purpose'} . "\n\n";
    print "enum " . $args{'enum'} . " {\n";
    $count = 0;
    foreach $parameter (@{$args{'parameterlist'}}) {
	print "\t$parameter";
	if ($count != $#{$args{'parameterlist'}}) {
	    $count++;
	    print ",";
	}
	print "\n";
    }
    print "};\n\n";

    print "Constants:\n\n";
    foreach $parameter (@{$args{'parameterlist'}}) {
	print "$parameter\n\t";
	print $args{'parameterdescs'}{$parameter} . "\n";
    }

    output_section_text(@_);
}

# output typedef in text
sub output_typedef_text(%) {
    my %args = %{$_[0]};
    my ($parameter);
    my $count;
    print "Typedef:\n\n";

    print "typedef " . $args{'typedef'} . " - " . $args{'purpose'} . "\n";
    output_section_text(@_);
}

# output struct as text
sub output_struct_text(%) {
    my %args = %{$_[0]};
    my ($parameter);

    print $args{'type'} . " " . $args{'struct'} . " - " . $args{'purpose'} . "\n\n";
    print $args{'type'} . " " . $args{'struct'} . " {\n";
    foreach $parameter (@{$args{'parameterlist'}}) {
	if ($parameter =~ /^#/) {
	    print "$parameter\n";
	    next;
	}

	my $parameter_name = $parameter;
	$parameter_name =~ s/\[.*//;

	($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
	$type = $args{'parametertypes'}{$parameter};
	if ($type =~ m/([^\(]*\(\*)\s*\)\s*\(([^\)]*)\)/) {
	    # pointer-to-function
	    print "\t$1 $parameter) ($2);\n";
	} elsif ($type =~ m/^(.*?)\s*(:.*)/) {
	    # bitfield
	    print "\t$1 $parameter$2;\n";
	} else {
	    print "\t" . $type . " " . $parameter . ";\n";
	}
    }
    print "};\n\n";

    print "Members:\n\n";
    foreach $parameter (@{$args{'parameterlist'}}) {
	($parameter =~ /^#/) && next;

	my $parameter_name = $parameter;
	$parameter_name =~ s/\[.*//;

	($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next;
	print "$parameter\n\t";
	print $args{'parameterdescs'}{$parameter_name} . "\n";
    }
    print "\n";
    output_section_text(@_);
}

sub output_blockhead_text(%) {
    my %args = %{$_[0]};
    my ($parameter, $section);

    foreach $section (@{$args{'sectionlist'}}) {
	print " $section:\n";
	print "    -> ";
	output_highlight($args{'sections'}{$section});
    }
}

## list mode output functions

sub output_function_list(%) {
    my %args = %{$_[0]};

    print $args{'function'} . "\n";
}

# output enum in list
sub output_enum_list(%) {
    my %args = %{$_[0]};
    print $args{'enum'} . "\n";
}

# output typedef in list
sub output_typedef_list(%) {
    my %args = %{$_[0]};
    print $args{'typedef'} . "\n";
}

# output struct as list
sub output_struct_list(%) {
    my %args = %{$_[0]};

    print $args{'struct'} . "\n";
}

sub output_blockhead_list(%) {
    my %args = %{$_[0]};
    my ($parameter, $section);

    foreach $section (@{$args{'sectionlist'}}) {
	print "DOC: $section\n";
    }
}

##
# generic output function for all types (function, struct/union, typedef, enum);
# calls the generated, variable output_ function name based on
# functype and output_mode
sub output_declaration {
    no strict 'refs';
    my $name = shift;
    my $functype = shift;
    my $func = "output_${functype}_$output_mode";
    if (($function_only==0) ||
	( $function_only == 1 && defined($function_table{$name})) ||
	( $function_only == 2 && !defined($function_table{$name})))
    {
	&$func(@_);
	$section_counter++;
    }
}

##
# generic output function - calls the right one based on current output mode.
sub output_blockhead {
    no strict 'refs';
    my $func = "output_blockhead_" . $output_mode;
    &$func(@_);
    $section_counter++;
}

##
# takes a declaration (struct, union, enum, typedef) and
# invokes the right handler. NOT called for functions.
sub dump_declaration($$) {
    no strict 'refs';
    my ($prototype, $file) = @_;
    my $func = "dump_" . $decl_type;
    &$func(@_);
}

sub dump_union($$) {
    dump_struct(@_);
}

sub dump_struct($$) {
    my $x = shift;
    my $file = shift;
    my $nested;

    if ($x =~ /(struct|union)\s+(\w+)\s*{(.*)}/) {
	#my $decl_type = $1;
	$declaration_name = $2;
	my $members = $3;

	# ignore embedded structs or unions
	$members =~ s/({.*})//g;
	$nested = $1;

	# ignore members marked private:
	$members =~ s/\/\*\s*private:.*?\/\*\s*public:.*?\*\///gos;
	$members =~ s/\/\*\s*private:.*//gos;
	# strip comments:
	$members =~ s/\/\*.*?\*\///gos;
	$nested =~ s/\/\*.*?\*\///gos;
	# strip kmemcheck_bitfield_{begin,end}.*;
	$members =~ s/kmemcheck_bitfield_.*?;//gos;
	# strip attributes
	$members =~ s/__aligned\s*\(.+\)//gos;

	create_parameterlist($members, ';', $file);
	check_sections($file, $declaration_name, "struct", $sectcheck, $struct_actual, $nested);

	output_declaration($declaration_name,
			   'struct',
			   {'struct' => $declaration_name,
			    'module' => $modulename,
			    'parameterlist' => \@parameterlist,
			    'parameterdescs' => \%parameterdescs,
			    'parametertypes' => \%parametertypes,
			    'sectionlist' => \@sectionlist,
			    'sections' => \%sections,
			    'purpose' => $declaration_purpose,
			    'type' => $decl_type
			   });
    }
    else {
	print STDERR "Error(${file}:$.): Cannot parse struct or union!\n";
	++$errors;
    }
}

sub dump_enum($$) {
    my $x = shift;
    my $file = shift;

    $x =~ s@/\*.*?\*/@@gos;	# strip comments.
    $x =~ s/^#\s*define\s+.*$//; # strip #define macros inside enums

    if ($x =~ /enum\s+(\w+)\s*{(.*)}/) {
	$declaration_name = $1;
	my $members = $2;

	foreach my $arg (split ',', $members) {
	    $arg =~ s/^\s*(\w+).*/$1/;
	    push @parameterlist, $arg;
	    if (!$parameterdescs{$arg}) {
		$parameterdescs{$arg} = $undescribed;
		print STDERR "Warning(${file}:$.): Enum value '$arg' ".
		    "not described in enum '$declaration_name'\n";
	    }

	}

	output_declaration($declaration_name,
			   'enum',
			   {'enum' => $declaration_name,
			    'module' => $modulename,
			    'parameterlist' => \@parameterlist,
			    'parameterdescs' => \%parameterdescs,
			    'sectionlist' => \@sectionlist,
			    'sections' => \%sections,
			    'purpose' => $declaration_purpose
			   });
    }
    else {
	print STDERR "Error(${file}:$.): Cannot parse enum!\n";
	++$errors;
    }
}

sub dump_typedef($$) {
    my $x = shift;
    my $file = shift;

    $x =~ s@/\*.*?\*/@@gos;	# strip comments.
    while (($x =~ /\(*.\)\s*;$/) || ($x =~ /\[*.\]\s*;$/)) {
	$x =~ s/\(*.\)\s*;$/;/;
	$x =~ s/\[*.\]\s*;$/;/;
    }

    if ($x =~ /typedef.*\s+(\w+)\s*;/) {
	$declaration_name = $1;

	output_declaration($declaration_name,
			   'typedef',
			   {'typedef' => $declaration_name,
			    'module' => $modulename,
			    'sectionlist' => \@sectionlist,
			    'sections' => \%sections,
			    'purpose' => $declaration_purpose
			   });
    }
    else {
	print STDERR "Error(${file}:$.): Cannot parse typedef!\n";
	++$errors;
    }
}

sub save_struct_actual($) {
    my $actual = shift;

    # strip all spaces from the actual param so that it looks like one string item
    $actual =~ s/\s*//g;
    $struct_actual = $struct_actual . $actual . " ";
}

sub create_parameterlist($$$) {
    my $args = shift;
    my $splitter = shift;
    my $file = shift;
    my $type;
    my $param;

    # temporarily replace commas inside function pointer definition
    while ($args =~ /(\([^\),]+),/) {
	$args =~ s/(\([^\),]+),/$1#/g;
    }

    foreach my $arg (split($splitter, $args)) {
	# strip comments
	$arg =~ s/\/\*.*\*\///;
	# strip leading/trailing spaces
	$arg =~ s/^\s*//;
	$arg =~ s/\s*$//;
	$arg =~ s/\s+/ /;

	if ($arg =~ /^#/) {
	    # Treat preprocessor directive as a typeless variable just to fill
	    # corresponding data structures "correctly". Catch it later in
	    # output_* subs.
	    push_parameter($arg, "", $file);
	} elsif ($arg =~ m/\(.+\)\s*\(/) {
	    # pointer-to-function
	    $arg =~ tr/#/,/;
	    $arg =~ m/[^\(]+\(\*?\s*(\w*)\s*\)/;
	    $param = $1;
	    $type = $arg;
	    $type =~ s/([^\(]+\(\*?)\s*$param/$1/;
	    save_struct_actual($param);
	    push_parameter($param, $type, $file);
	} elsif ($arg) {
	    $arg =~ s/\s*:\s*/:/g;
	    $arg =~ s/\s*\[/\[/g;

	    my @args = split('\s*,\s*', $arg);
	    if ($args[0] =~ m/\*/) {
		$args[0] =~ s/(\*+)\s*/ $1/;
	    }

	    my @first_arg;
	    if ($args[0] =~ /^(.*\s+)(.*?\[.*\].*)$/) {
		    shift @args;
		    push(@first_arg, split('\s+', $1));
		    push(@first_arg, $2);
	    } else {
		    @first_arg = split('\s+', shift @args);
	    }

	    unshift(@args, pop @first_arg);
	    $type = join " ", @first_arg;

	    foreach $param (@args) {
		if ($param =~ m/^(\*+)\s*(.*)/) {
		    save_struct_actual($2);
		    push_parameter($2, "$type $1", $file);
		}
		elsif ($param =~ m/(.*?):(\d+)/) {
		    if ($type ne "") { # skip unnamed bit-fields
			save_struct_actual($1);
			push_parameter($1, "$type:$2", $file)
		    }
		}
		else {
		    save_struct_actual($param);
		    push_parameter($param, $type, $file);
		}
	    }
	}
    }
}

sub push_parameter($$$) {
	my $param = shift;
	my $type = shift;
	my $file = shift;

	if (($anon_struct_union == 1) && ($type eq "") &&
	    ($param eq "}")) {
		return;		# ignore the ending }; from anon. struct/union
	}

	$anon_struct_union = 0;
	my $param_name = $param;
	$param_name =~ s/\[.*//;

	if ($type eq "" && $param =~ /\.\.\.$/)
	{
	    if (!defined $parameterdescs{$param} || $parameterdescs{$param} eq "") {
		$parameterdescs{$param} = "variable arguments";
	    }
	}
	elsif ($type eq "" && ($param eq "" or $param eq "void"))
	{
	    $param="void";
	    $parameterdescs{void} = "no arguments";
	}
	elsif ($type eq "" && ($param eq "struct" or $param eq "union"))
	# handle unnamed (anonymous) union or struct:
	{
		$type = $param;
		$param = "{unnamed_" . $param . "}";
		$parameterdescs{$param} = "anonymous\n";
		$anon_struct_union = 1;
	}

	# warn if parameter has no description
	# (but ignore ones starting with # as these are not parameters
	# but inline preprocessor statements);
	# also ignore unnamed structs/unions;
	if (!$anon_struct_union) {
	if (!defined $parameterdescs{$param_name} && $param_name !~ /^#/) {

	    $parameterdescs{$param_name} = $undescribed;

	    if (($type eq 'function') || ($type eq 'enum')) {
		print STDERR "Warning(${file}:$.): Function parameter ".
		    "or member '$param' not " .
		    "described in '$declaration_name'\n";
	    }
	    print STDERR "Warning(${file}:$.):" .
			 " No description found for parameter '$param'\n";
	    ++$warnings;
	}
	}

	$param = xml_escape($param);

	# strip spaces from $param so that it is one continuous string
	# on @parameterlist;
	# this fixes a problem where check_sections() cannot find
	# a parameter like "addr[6 + 2]" because it actually appears
	# as "addr[6", "+", "2]" on the parameter list;
	# but it's better to maintain the param string unchanged for output,
	# so just weaken the string compare in check_sections() to ignore
	# "[blah" in a parameter string;
	###$param =~ s/\s*//g;
	push @parameterlist, $param;
	$parametertypes{$param} = $type;
}

sub check_sections($$$$$$) {
	my ($file, $decl_name, $decl_type, $sectcheck, $prmscheck, $nested) = @_;
	my @sects = split ' ', $sectcheck;
	my @prms = split ' ', $prmscheck;
	my $err;
	my ($px, $sx);
	my $prm_clean;		# strip trailing "[array size]" and/or beginning "*"

	foreach $sx (0 .. $#sects) {
		$err = 1;
		foreach $px (0 .. $#prms) {
			$prm_clean = $prms[$px];
			$prm_clean =~ s/\[.*\]//;
			$prm_clean =~ s/__attribute__\s*\(\([a-z,_\*\s\(\)]*\)\)//i;
			# ignore array size in a parameter string;
			# however, the original param string may contain
			# spaces, e.g.:  addr[6 + 2]
			# and this appears in @prms as "addr[6" since the
			# parameter list is split at spaces;
			# hence just ignore "[..." for the sections check;
			$prm_clean =~ s/\[.*//;

			##$prm_clean =~ s/^\**//;
			if ($prm_clean eq $sects[$sx]) {
				$err = 0;
				last;
			}
		}
		if ($err) {
			if ($decl_type eq "function") {
				print STDERR "Warning(${file}:$.): " .
					"Excess function parameter " .
					"'$sects[$sx]' " .
					"description in '$decl_name'\n";
				++$warnings;
			} else {
				if ($nested !~ m/\Q$sects[$sx]\E/) {
				    print STDERR "Warning(${file}:$.): " .
					"Excess struct/union/enum/typedef member " .
					"'$sects[$sx]' " .
					"description in '$decl_name'\n";
				    ++$warnings;
				}
			}
		}
	}
}

##
# Checks the section describing the return value of a function.
sub check_return_section {
        my $file = shift;
        my $declaration_name = shift;
        my $return_type = shift;

        # Ignore an empty return type (It's a macro)
        # Ignore functions with a "void" return type. (But don't ignore "void *")
        if (($return_type eq "") || ($return_type =~ /void\s*\w*\s*$/)) {
                return;
        }

        if (!defined($sections{$section_return}) ||
            $sections{$section_return} eq "") {
                print STDERR "Warning(${file}:$.): " .
                        "No description found for return value of " .
                        "'$declaration_name'\n";
                ++$warnings;
        }
}

##
# takes a function prototype and the name of the current file being
# processed and spits out all the details stored in the global
# arrays/hashes.
sub dump_function($$) {
    my $prototype = shift;
    my $file = shift;
    my $noret = 0;

    $prototype =~ s/^static +//;
    $prototype =~ s/^extern +//;
    $prototype =~ s/^asmlinkage +//;
    $prototype =~ s/^inline +//;
    $prototype =~ s/^__inline__ +//;
    $prototype =~ s/^__inline +//;
    $prototype =~ s/^__always_inline +//;
    $prototype =~ s/^noinline +//;
    $prototype =~ s/__init +//;
    $prototype =~ s/__init_or_module +//;
    $prototype =~ s/__meminit +//;
    $prototype =~ s/__must_check +//;
    $prototype =~ s/__weak +//;
    my $define = $prototype =~ s/^#\s*define\s+//; #ak added
    $prototype =~ s/__attribute__\s*\(\([a-z,]*\)\)//;

    # Yes, this truly is vile.  We are looking for:
    # 1. Return type (may be nothing if we're looking at a macro)
    # 2. Function name
    # 3. Function parameters.
    #
    # All the while we have to watch out for function pointer parameters
    # (which IIRC is what the two sections are for), C types (these
    # regexps don't even start to express all the possibilities), and
    # so on.
    #
    # If you mess with these regexps, it's a good idea to check that
    # the following functions' documentation still comes out right:
    # - parport_register_device (function pointer parameters)
    # - atomic_set (macro)
    # - pci_match_device, __copy_to_user (long return type)

    if ($define && $prototype =~ m/^()([a-zA-Z0-9_~:]+)\s+/) {
        # This is an object-like macro, it has no return type and no parameter
        # list.
        # Function-like macros are not allowed to have spaces between
        # declaration_name and opening parenthesis (notice the \s+).
        $return_type = $1;
        $declaration_name = $2;
        $noret = 1;
    } elsif ($prototype =~ m/^()([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
	$prototype =~ m/^(\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
	$prototype =~ m/^(\w+\s*\*)\s*([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
	$prototype =~ m/^(\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
	$prototype =~ m/^(\w+\s+\w+\s*\*+)\s*([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
	$prototype =~ m/^(\w+\s+\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
	$prototype =~ m/^(\w+\s+\w+\s+\w+\s*\*)\s*([a-zA-Z0-9_~:]+)\s*\(([^\(]*)\)/ ||
	$prototype =~ m/^()([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
	$prototype =~ m/^(\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
	$prototype =~ m/^(\w+\s*\*)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
	$prototype =~ m/^(\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
	$prototype =~ m/^(\w+\s+\w+\s*\*)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
	$prototype =~ m/^(\w+\s+\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
	$prototype =~ m/^(\w+\s+\w+\s+\w+\s*\*)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
	$prototype =~ m/^(\w+\s+\w+\s+\w+\s+\w+)\s+([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
	$prototype =~ m/^(\w+\s+\w+\s+\w+\s+\w+\s*\*)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/ ||
	$prototype =~ m/^(\w+\s+\w+\s*\*\s*\w+\s*\*\s*)\s*([a-zA-Z0-9_~:]+)\s*\(([^\{]*)\)/)  {
	$return_type = $1;
	$declaration_name = $2;
	my $args = $3;

	create_parameterlist($args, ',', $file);
    } else {
	print STDERR "Warning(${file}:$.): cannot understand function prototype: '$prototype'\n";
	return;
    }

	my $prms = join " ", @parameterlist;
	check_sections($file, $declaration_name, "function", $sectcheck, $prms, "");

        # This check emits a lot of warnings at the moment, because many
        # functions don't have a 'Return' doc section. So until the number
        # of warnings goes sufficiently down, the check is only performed in
        # verbose mode.
        # TODO: always perform the check.
        if ($verbose && !$noret) {
                check_return_section($file, $declaration_name, $return_type);
        }

    output_declaration($declaration_name,
		       'function',
		       {'function' => $declaration_name,
			'module' => $modulename,
			'functiontype' => $return_type,
			'parameterlist' => \@parameterlist,
			'parameterdescs' => \%parameterdescs,
			'parametertypes' => \%parametertypes,
			'sectionlist' => \@sectionlist,
			'sections' => \%sections,
			'purpose' => $declaration_purpose
		       });
}

sub reset_state {
    $function = "";
    %constants = ();
    %parameterdescs = ();
    %parametertypes = ();
    @parameterlist = ();
    %sections = ();
    @sectionlist = ();
    $sectcheck = "";
    $struct_actual = "";
    $prototype = "";

    $state = 0;
}

sub tracepoint_munge($) {
	my $file = shift;
	my $tracepointname = 0;
	my $tracepointargs = 0;

	if ($prototype =~ m/TRACE_EVENT\((.*?),/) {
		$tracepointname = $1;
	}
	if ($prototype =~ m/DEFINE_SINGLE_EVENT\((.*?),/) {
		$tracepointname = $1;
	}
	if ($prototype =~ m/DEFINE_EVENT\((.*?),(.*?),/) {
		$tracepointname = $2;
	}
	$tracepointname =~ s/^\s+//; #strip leading whitespace
	if ($prototype =~ m/TP_PROTO\((.*?)\)/) {
		$tracepointargs = $1;
	}
	if (($tracepointname eq 0) || ($tracepointargs eq 0)) {
		print STDERR "Warning(${file}:$.): Unrecognized tracepoint format: \n".
			     "$prototype\n";
	} else {
		$prototype = "static inline void trace_$tracepointname($tracepointargs)";
	}
}

sub syscall_munge() {
	my $void = 0;

	$prototype =~ s@[\r\n\t]+@ @gos; # strip newlines/CR's/tabs
##	if ($prototype =~ m/SYSCALL_DEFINE0\s*\(\s*(a-zA-Z0-9_)*\s*\)/) {
	if ($prototype =~ m/SYSCALL_DEFINE0/) {
		$void = 1;
##		$prototype = "long sys_$1(void)";
	}

	$prototype =~ s/SYSCALL_DEFINE.*\(/long sys_/; # fix return type & func name
	if ($prototype =~ m/long (sys_.*?),/) {
		$prototype =~ s/,/\(/;
	} elsif ($void) {
		$prototype =~ s/\)/\(void\)/;
	}

	# now delete all of the odd-number commas in $prototype
	# so that arg types & arg names don't have a comma between them
	my $count = 0;
	my $len = length($prototype);
	if ($void) {
		$len = 0;	# skip the for-loop
	}
	for (my $ix = 0; $ix < $len; $ix++) {
		if (substr($prototype, $ix, 1) eq ',') {
			$count++;
			if ($count % 2 == 1) {
				substr($prototype, $ix, 1) = ' ';
			}
		}
	}
}

sub process_state3_function($$) {
    my $x = shift;
    my $file = shift;

    $x =~ s@\/\/.*$@@gos; # strip C99-style comments to end of line

    if ($x =~ m#\s*/\*\s+MACDOC\s*#io || ($x =~ /^#/ && $x !~ /^#\s*define/)) {
	# do nothing
    }
    elsif ($x =~ /([^\{]*)/) {
	$prototype .= $1;
    }

    if (($x =~ /\{/) || ($x =~ /\#\s*define/) || ($x =~ /;/)) {
	$prototype =~ s@/\*.*?\*/@@gos;	# strip comments.
	$prototype =~ s@[\r\n]+@ @gos; # strip newlines/cr's.
	$prototype =~ s@^\s+@@gos; # strip leading spaces
	if ($prototype =~ /SYSCALL_DEFINE/) {
		syscall_munge();
	}
	if ($prototype =~ /TRACE_EVENT/ || $prototype =~ /DEFINE_EVENT/ ||
	    $prototype =~ /DEFINE_SINGLE_EVENT/)
	{
		tracepoint_munge($file);
	}
	dump_function($prototype, $file);
	reset_state();
    }
}

sub process_state3_type($$) {
    my $x = shift;
    my $file = shift;

    $x =~ s@[\r\n]+@ @gos; # strip newlines/cr's.
    $x =~ s@^\s+@@gos; # strip leading spaces
    $x =~ s@\s+$@@gos; # strip trailing spaces
    $x =~ s@\/\/.*$@@gos; # strip C99-style comments to end of line

    if ($x =~ /^#/) {
	# To distinguish preprocessor directive from regular declaration later.
	$x .= ";";
    }

    while (1) {
	if ( $x =~ /([^{};]*)([{};])(.*)/ ) {
	    $prototype .= $1 . $2;
	    ($2 eq '{') && $brcount++;
	    ($2 eq '}') && $brcount--;
	    if (($2 eq ';') && ($brcount == 0)) {
		dump_declaration($prototype, $file);
		reset_state();
		last;
	    }
	    $x = $3;
	} else {
	    $prototype .= $x;
	    last;
	}
    }
}

# xml_escape: replace <, >, and & in the text stream;
#
# however, formatting controls that are generated internally/locally in the
# kernel-doc script are not escaped here; instead, they begin life like
# $blankline_html (4 of '\' followed by a mnemonic + ':'), then these strings
# are converted to their mnemonic-expected output, without the 4 * '\' & ':',
# just before actual output; (this is done by local_unescape())
sub xml_escape($) {
	my $text = shift;
	if (($output_mode eq "text") || ($output_mode eq "man")) {
		return $text;
	}
	$text =~ s/\&/\\\\\\amp;/g;
	$text =~ s/\</\\\\\\lt;/g;
	$text =~ s/\>/\\\\\\gt;/g;
	return $text;
}

# convert local escape strings to html
# local escape strings look like:  '\\\\menmonic:' (that's 4 backslashes)
sub local_unescape($) {
	my $text = shift;
	if (($output_mode eq "text") || ($output_mode eq "man")) {
		return $text;
	}
	$text =~ s/\\\\\\\\lt:/</g;
	$text =~ s/\\\\\\\\gt:/>/g;
	return $text;
}

sub process_file($) {
    my $file;
    my $identifier;
    my $func;
    my $descr;
    my $in_purpose = 0;
    my $initial_section_counter = $section_counter;

    if (defined($ENV{'SRCTREE'})) {
	$file = "$ENV{'SRCTREE'}" . "/" . "@_";
    }
    else {
	$file = "@_";
    }
    if (defined($source_map{$file})) {
	$file = $source_map{$file};
    }

    if (!open(IN,"<$file")) {
	print STDERR "Error: Cannot open file $file\n";
	++$errors;
	return;
    }

    $. = 1;

    $section_counter = 0;
    while (<IN>) {
	while (s/\\\s*$//) {
	    $_ .= <IN>;
	}
	if ($state == 0) {
	    if (/$doc_start/o) {
		$state = 1;		# next line is always the function name
		$in_doc_sect = 0;
	    }
	} elsif ($state == 1) {	# this line is the function name (always)
	    if (/$doc_block/o) {
		$state = 4;
		$contents = "";
		if ( $1 eq "" ) {
			$section = $section_intro;
		} else {
			$section = $1;
		}
	    }
	    elsif (/$doc_decl/o) {
		$identifier = $1;
		if (/\s*([\w\s]+?)\s*-/) {
		    $identifier = $1;
		}

		$state = 2;
		if (/-(.*)/) {
		    # strip leading/trailing/multiple spaces
		    $descr= $1;
		    $descr =~ s/^\s*//;
		    $descr =~ s/\s*$//;
		    $descr =~ s/\s+/ /g;
		    $declaration_purpose = xml_escape($descr);
		    $in_purpose = 1;
		} else {
		    $declaration_purpose = "";
		}

		if (($declaration_purpose eq "") && $verbose) {
			print STDERR "Warning(${file}:$.): missing initial short description on line:\n";
			print STDERR $_;
			++$warnings;
		}

		if ($identifier =~ m/^struct/) {
		    $decl_type = 'struct';
		} elsif ($identifier =~ m/^union/) {
		    $decl_type = 'union';
		} elsif ($identifier =~ m/^enum/) {
		    $decl_type = 'enum';
		} elsif ($identifier =~ m/^typedef/) {
		    $decl_type = 'typedef';
		} else {
		    $decl_type = 'function';
		}

		if ($verbose) {
		    print STDERR "Info(${file}:$.): Scanning doc for $identifier\n";
		}
	    } else {
		print STDERR "Warning(${file}:$.): Cannot understand $_ on line $.",
		" - I thought it was a doc line\n";
		++$warnings;
		$state = 0;
	    }
	} elsif ($state == 2) {	# look for head: lines, and include content
	    if (/$doc_sect/o) {
		$newsection = $1;
		$newcontents = $2;

		if (($contents ne "") && ($contents ne "\n")) {
		    if (!$in_doc_sect && $verbose) {
			print STDERR "Warning(${file}:$.): contents before sections\n";
			++$warnings;
		    }
		    dump_section($file, $section, xml_escape($contents));
		    $section = $section_default;
		}

		$in_doc_sect = 1;
		$in_purpose = 0;
		$contents = $newcontents;
		if ($contents ne "") {
		    while ((substr($contents, 0, 1) eq " ") ||
			substr($contents, 0, 1) eq "\t") {
			    $contents = substr($contents, 1);
		    }
		    $contents .= "\n";
		}
		$section = $newsection;
	    } elsif (/$doc_end/) {

		if (($contents ne "") && ($contents ne "\n")) {
		    dump_section($file, $section, xml_escape($contents));
		    $section = $section_default;
		    $contents = "";
		}
		# look for doc_com + <text> + doc_end:
		if ($_ =~ m'\s*\*\s*[a-zA-Z_0-9:\.]+\*/') {
		    print STDERR "Warning(${file}:$.): suspicious ending line: $_";
		    ++$warnings;
		}

		$prototype = "";
		$state = 3;
		$brcount = 0;
#		print STDERR "end of doc comment, looking for prototype\n";
	    } elsif (/$doc_content/) {
		# miguel-style comment kludge, look for blank lines after
		# @parameter line to signify start of description
		if ($1 eq "") {
		    if ($section =~ m/^@/ || $section eq $section_context) {
			dump_section($file, $section, xml_escape($contents));
			$section = $section_default;
			$contents = "";
		    } else {
			$contents .= "\n";
		    }
		    $in_purpose = 0;
		} elsif ($in_purpose == 1) {
		    # Continued declaration purpose
		    chomp($declaration_purpose);
		    $declaration_purpose .= " " . xml_escape($1);
		    $declaration_purpose =~ s/\s+/ /g;
		} else {
		    $contents .= $1 . "\n";
		}
	    } else {
		# i dont know - bad line?  ignore.
		print STDERR "Warning(${file}:$.): bad line: $_";
		++$warnings;
	    }
	} elsif ($state == 3) {	# scanning for function '{' (end of prototype)
	    if ($decl_type eq 'function') {
		process_state3_function($_, $file);
	    } else {
		process_state3_type($_, $file);
	    }
	} elsif ($state == 4) {
		# Documentation block
		if (/$doc_block/) {
			dump_doc_section($file, $section, xml_escape($contents));
			$contents = "";
			$function = "";
			%constants = ();
			%parameterdescs = ();
			%parametertypes = ();
			@parameterlist = ();
			%sections = ();
			@sectionlist = ();
			$prototype = "";
			if ( $1 eq "" ) {
				$section = $section_intro;
			} else {
				$section = $1;
			}
		}
		elsif (/$doc_end/)
		{
			dump_doc_section($file, $section, xml_escape($contents));
			$contents = "";
			$function = "";
			%constants = ();
			%parameterdescs = ();
			%parametertypes = ();
			@parameterlist = ();
			%sections = ();
			@sectionlist = ();
			$prototype = "";
			$state = 0;
		}
		elsif (/$doc_content/)
		{
			if ( $1 eq "" )
			{
				$contents .= $blankline;
			}
			else
			{
				$contents .= $1 . "\n";
			}
		}
	}
    }
    if ($initial_section_counter == $section_counter) {
	print STDERR "Warning(${file}): no structured comments found\n";
	if (($function_only == 1) && ($show_not_found == 1)) {
	    print STDERR "    Was looking for '$_'.\n" for keys %function_table;
	}
	if ($output_mode eq "xml") {
	    # The template wants at least one RefEntry here; make one.
	    print "<refentry>\n";
	    print " <refnamediv>\n";
	    print "  <refname>\n";
	    print "   ${file}\n";
	    print "  </refname>\n";
	    print "  <refpurpose>\n";
	    print "   Document generation inconsistency\n";
	    print "  </refpurpose>\n";
	    print " </refnamediv>\n";
	    print " <refsect1>\n";
	    print "  <title>\n";
	    print "   Oops\n";
	    print "  </title>\n";
	    print "  <warning>\n";
	    print "   <para>\n";
	    print "    The template for this document tried to insert\n";
	    print "    the structured comment from the file\n";
	    print "    <filename>${file}</filename> at this point,\n";
	    print "    but none was found.\n";
	    print "    This dummy section is inserted to allow\n";
	    print "    generation to continue.\n";
	    print "   </para>\n";
	    print "  </warning>\n";
	    print " </refsect1>\n";
	    print "</refentry>\n";
	}
    }
}


$kernelversion = get_kernel_version();

# generate a sequence of code that will splice in highlighting information
# using the s// operator.
foreach my $pattern (keys %highlights) {
#   print STDERR "scanning pattern:$pattern, highlight:($highlights{$pattern})\n";
    $dohighlight .=  "\$contents =~ s:$pattern:$highlights{$pattern}:gs;\n";
}

# Read the file that maps relative names to absolute names for
# separate source and object directories and for shadow trees.
if (open(SOURCE_MAP, "<.tmp_filelist.txt")) {
	my ($relname, $absname);
	while(<SOURCE_MAP>) {
		chop();
		($relname, $absname) = (split())[0..1];
		$relname =~ s:^/+::;
		$source_map{$relname} = $absname;
	}
	close(SOURCE_MAP);
}

foreach (@ARGV) {
    chomp;
    process_file($_);
}
if ($verbose && $errors) {
  print STDERR "$errors errors\n";
}
if ($verbose && $warnings) {
  print STDERR "$warnings warnings\n";
}

exit($errors);
> 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772
/*
  Copyright (c) 2008-2009 Z RESEARCH, Inc. <http://www.zresearch.com>
  This file is part of GlusterFS.

  GlusterFS is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published
  by the Free Software Foundation; either version 3 of the License,
  or (at your option) any later version.

  GlusterFS is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see
  <http://www.gnu.org/licenses/>.
*/

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

#include <stdio.h>
#include <errno.h>
#include <libgen.h>
#include <stddef.h>

#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef GF_SOLARIS_HOST_OS
#include <sys/statfs.h>
#endif
#include <unistd.h>
#include <xlator.h>
#include <timer.h>
#include "defaults.h"
#include <time.h>
#include <poll.h>
#include "transport.h"
#include "event.h"
#include "libglusterfsclient.h"
#include "libglusterfsclient-internals.h"
#include "compat.h"
#include "compat-errno.h"
#include <sys/vfs.h>
#include <utime.h>
#include <sys/param.h>
#include <list.h>
#include <stdarg.h>
#include <sys/statvfs.h>
#include "hashfn.h"
#include <sys/select.h>

#define LIBGF_XL_NAME "libglusterfsclient"
#define LIBGLUSTERFS_INODE_TABLE_LRU_LIMIT 1000 //14057
#define LIBGF_SENDFILE_BLOCK_SIZE 4096
#define LIBGF_READDIR_BLOCK     4096

static inline xlator_t *
libglusterfs_graph (xlator_t *graph);
int32_t libgf_client_readlink (libglusterfs_client_ctx_t *ctx, loc_t *loc,
                                        char *buf, size_t bufsize);

int
libgf_realpath_loc_fill (libglusterfs_client_ctx_t *ctx, char *link,
                         loc_t *targetloc);
static int first_init = 1;

/* The global list of virtual mount points */
struct {
        struct list_head list;
        int              entries;
}vmplist;


/* Protects the VMP list above. */
pthread_mutex_t vmplock = PTHREAD_MUTEX_INITIALIZER;

/* Ensures only one thread is ever calling glusterfs_mount.
 * Since that function internally calls routines which
 * use the yacc parser code using global vars, this process
 * needs to be syncronised.
 */
pthread_mutex_t mountlock = PTHREAD_MUTEX_INITIALIZER;

char *
libgf_vmp_virtual_path(struct vmp_entry *entry, const char *path)
{
        char    *vpath = NULL;
        char    *tmp = NULL;

        vpath = calloc (strlen (path) + 1, sizeof (char));
        tmp = ((char *)(path + (entry->vmplen-1)));
        if (tmp[0] != '/') {
                vpath[0] = '/';
                strcat (&vpath[1], tmp);
        } else
                strcpy (vpath, tmp);

        return vpath;
}

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

	if (-1 == gettimeofday(&tv, NULL)) {
		gf_log ("", GF_LOG_ERROR, 
			"gettimeofday: failed %s",
			strerror (errno));		
	}

	if (-1 == gethostname (hostname, 256)) {
		gf_log ("", GF_LOG_ERROR, 
			"gethostname: failed %s",
			strerror (errno));
	}

	localtime_r (&tv.tv_sec, &now);
	strftime (now_str, 32, "%Y/%m/%d-%H:%M:%S", &now);
	snprintf (tmp_str, 1024, "%s-%d-%s:%ld", 
		  hostname, getpid(), now_str, tv.tv_usec);
	
	return strdup (tmp_str);
}


int32_t
libgf_client_forget (xlator_t *this,
		     inode_t *inode)
{
        uint64_t ptr = 0;
	libglusterfs_client_inode_ctx_t *ctx = NULL;
	
	inode_ctx_del (inode, this, &ptr);
        ctx = (libglusterfs_client_inode_ctx_t *)(long) ptr;

	FREE (ctx);

        return 0;
}

xlator_t *
libgf_inode_to_xlator (inode_t *inode)
{
        if (!inode)
                return NULL;

        if (!inode->table)
                return NULL;

        if (!inode->table->xl)
                return NULL;

        if (!inode->table->xl->ctx)
                return NULL;

        return inode->table->xl->ctx->top;
}

libglusterfs_client_fd_ctx_t *
libgf_get_fd_ctx (fd_t *fd)
{
        uint64_t                        ctxaddr = 0;
        libglusterfs_client_fd_ctx_t    *ctx = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, fd, out);

        if (fd_ctx_get (fd, libgf_inode_to_xlator (fd->inode), &ctxaddr) == -1)
                goto out;

        ctx = (libglusterfs_client_fd_ctx_t *)(long)ctxaddr;

out:
        return ctx;
}

libglusterfs_client_fd_ctx_t *
libgf_alloc_fd_ctx (libglusterfs_client_ctx_t *ctx, fd_t *fd)
{
        libglusterfs_client_fd_ctx_t    *fdctx = NULL;
        uint64_t                        ctxaddr = 0;

        fdctx = CALLOC (1, sizeof (*fdctx));
        if (fdctx == NULL) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR,
                        "memory allocation failure");
                fdctx = NULL;
                goto out;
        }

        pthread_mutex_init (&fdctx->lock, NULL);
        fdctx->ctx = ctx;
        ctxaddr = (uint64_t) (long)fdctx;

        if (fd->inode) {
                if (S_ISDIR (fd->inode->st_mode)) {
                        fdctx->dcache = CALLOC (1, sizeof (struct direntcache));
                        if (fdctx->dcache)
                                INIT_LIST_HEAD (&fdctx->dcache->entries.list);
                        /* If the calloc fails, we can still continue
                         * working as the dcache is not required for correct
                         * operation.
                         */
                }
        }
        fd_ctx_set (fd, libgf_inode_to_xlator (fd->inode), ctxaddr);
out:
        return fdctx;
}

libglusterfs_client_fd_ctx_t *
libgf_del_fd_ctx (fd_t *fd)
{
        uint64_t                        ctxaddr = 0;
        libglusterfs_client_fd_ctx_t    *ctx = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, fd, out);

        if (fd_ctx_del (fd, libgf_inode_to_xlator (fd->inode) , &ctxaddr) == -1)
                goto out;

        ctx = (libglusterfs_client_fd_ctx_t *)(long)ctxaddr;

out:
        return ctx;
}

void
libgf_dcache_invalidate (fd_t *fd)
{
        libglusterfs_client_fd_ctx_t    *fd_ctx = NULL;

        if (!fd)
                return;

        fd_ctx = libgf_get_fd_ctx (fd);
        if (!fd_ctx) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "No fd context present");
                errno = EBADF;
                return;
        }

        if (!fd_ctx->dcache) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "No dcache present");
                return;
        }

        if (!list_empty (&fd_ctx->dcache->entries.list))
                gf_dirent_free (&fd_ctx->dcache->entries);

        INIT_LIST_HEAD (&fd_ctx->dcache->entries.list);

        fd_ctx->dcache->next = NULL;
        fd_ctx->dcache->prev_off = 0;

        return;
}

/* The first entry in the entries is always a placeholder
 * or the list head. The real entries begin from entries->next.
 */
int
libgf_dcache_update (libglusterfs_client_ctx_t *ctx, fd_t *fd,
                     gf_dirent_t *entries)
{
        libglusterfs_client_fd_ctx_t    *fd_ctx = NULL;
        int                             op_ret = -1;

        if ((!ctx) || (!fd) || (!entries)) {
                errno = EINVAL;
                goto out;
        }

        fd_ctx = libgf_get_fd_ctx (fd);
        if (!fd_ctx) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "No fd context present");
                errno = EBADF;
		goto out;
        }

        /* dcache is not enabled. */
        if (!fd_ctx->dcache) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "No dcache present");
                op_ret = 0;
                goto out;
        }

        /* If we're updating, we must begin with invalidating any previous
         * entries.
         */
        libgf_dcache_invalidate (fd);

        fd_ctx->dcache->next = entries->next;
        /* We still need to store a pointer to the head
         * so we start free'ing from the head when invalidation
         * is required.
         *
         * Need to delink the entries from the list
         * given to us by an underlying translators. Most translators will
         * free this list after this call so we must preserve the dirents in
         * order to cache them.
         */
        list_splice_init (&entries->list, &fd_ctx->dcache->entries.list);
        op_ret = 0;
out:
        return op_ret;
}

int
libgf_dcache_readdir (libglusterfs_client_ctx_t *ctx, fd_t *fd,
                      struct dirent *dirp, off_t *offset)
{
        libglusterfs_client_fd_ctx_t    *fd_ctx = NULL;
        int                             cachevalid = 0;

        if ((!ctx) || (!fd) || (!dirp) || (!offset))
                return 0;

        fd_ctx = libgf_get_fd_ctx (fd);
        if (!fd_ctx) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "No fd context present");
                errno = EBADF;
                goto out;
        }

        if (!fd_ctx->dcache) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "No dcache present");
                goto out;
        }

        /* We've either run out of entries in the cache
         * or the cache is empty.
         */
        if (!fd_ctx->dcache->next) {
                gf_log (LIBGF_XL_NAME, GF_LOG_TRACE, "No entries present");
                goto out;
        }

        /* The dirent list is created as a circular linked list
         * so this check is needed to ensure, we dont start
         * reading old entries again.
         * If we're reached this situation, the cache is exhausted
         * and we'll need to pre-fetch more entries to continue serving.
         */
        if (fd_ctx->dcache->next == &fd_ctx->dcache->entries) {
                gf_log (LIBGF_XL_NAME, GF_LOG_TRACE, "Entries exhausted");
                goto out;
        }

        /* During sequential reading we generally expect that the offset
         * requested is the same as the offset we served in the previous call
         * to readdir. But, seekdir, rewinddir and libgf_dcache_invalidate
         * require special handling because seekdir/rewinddir change the offset
         * in the fd_ctx and libgf_dcache_invalidate changes the prev_off.
         */
        if (*offset != fd_ctx->dcache->prev_off) {
                /* For all cases of the if branch above, we know that the
                 * cache is now invalid except for the case below. It handles
                 * the case where the two offset values above are different
                 * but different because the previous readdir block was
                 * exhausted, resulting in a prev_off being set to 0 in
                 * libgf_dcache_invalidate, while the requested offset is non
                 * zero because that is what we returned for the last dirent
                 * of the previous readdir block.
                 */
                if ((*offset != 0) && (fd_ctx->dcache->prev_off == 0)) {
                        gf_log (LIBGF_XL_NAME, GF_LOG_TRACE, "Entries"
                                " exhausted");
                        cachevalid = 1;
                } else
                        gf_log (LIBGF_XL_NAME, GF_LOG_TRACE, "Dcache"
                                " invalidated previously");
        } else
                cachevalid = 1;

        if (!cachevalid)
                goto out;

        dirp->d_ino = fd_ctx->dcache->next->d_ino;
        strncpy (dirp->d_name, fd_ctx->dcache->next->d_name,
                 fd_ctx->dcache->next->d_len);

        *offset = fd_ctx->dcache->next->d_off;
        dirp->d_off = *offset;
        fd_ctx->dcache->prev_off = fd_ctx->dcache->next->d_off;
        fd_ctx->dcache->next = fd_ctx->dcache->next->next;

out:
        return cachevalid;
}


int32_t
libgf_client_release (xlator_t *this,
		      fd_t *fd)
{
	libglusterfs_client_fd_ctx_t *fd_ctx = NULL;
        fd_ctx = libgf_get_fd_ctx (fd);
        if (S_ISDIR (fd->inode->st_mode)) {
                libgf_dcache_invalidate (fd);
                FREE (fd_ctx->dcache);
        }

        libgf_del_fd_ctx (fd);
        if (fd_ctx != NULL) {
                pthread_mutex_destroy (&fd_ctx->lock);
                FREE (fd_ctx);
        }

	return 0;
}

libglusterfs_client_inode_ctx_t *
libgf_get_inode_ctx (inode_t *inode)
{
        uint64_t                                ctxaddr = 0;
        libglusterfs_client_inode_ctx_t         *ictx = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, inode, out);
        if (inode_ctx_get (inode, libgf_inode_to_xlator (inode), &ctxaddr) < 0)
                goto out;

        ictx = (libglusterfs_client_inode_ctx_t *)(long)ctxaddr;

out:
        return ictx;
}

libglusterfs_client_inode_ctx_t *
libgf_del_inode_ctx (inode_t *inode)
{
        uint64_t                                ctxaddr = 0;
        libglusterfs_client_inode_ctx_t         *ictx = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, inode, out);
        if (inode_ctx_del (inode, libgf_inode_to_xlator (inode), &ctxaddr) < 0)
                goto out;

        ictx = (libglusterfs_client_inode_ctx_t *)(long)ctxaddr;

out:
        return ictx;
}

libglusterfs_client_inode_ctx_t *
libgf_alloc_inode_ctx (libglusterfs_client_ctx_t *ctx, inode_t *inode)
{
        uint64_t                                ctxaddr = 0;
        libglusterfs_client_inode_ctx_t         *ictx = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, inode, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        ictx = CALLOC (1, sizeof (*ictx));
        if (ictx == NULL) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR,
                                "memory allocation failure");
                goto out;
        }

        pthread_mutex_init (&ictx->lock, NULL);
        ctxaddr = (uint64_t) (long)ictx;
        if (inode_ctx_put (inode, libgf_inode_to_xlator (inode), ctxaddr) < 0){
                FREE (ictx);
                ictx = NULL;
        }

out:
        return ictx;
}

int
libgf_transform_devnum (libglusterfs_client_ctx_t *libctx, struct stat *buf)
{

        if ((!libctx) || (!buf))
                return -1;

        buf->st_dev = libctx->fake_fsid;
        return 0;
}

int
libgf_update_iattr_cache (inode_t *inode, int flags, struct stat *buf)
{
        libglusterfs_client_inode_ctx_t *inode_ctx = NULL;
        time_t                          current = 0;
        int                             op_ret = -1;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, inode, out);

        inode_ctx = libgf_get_inode_ctx (inode);
        if (!inode_ctx) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "No inode context"
                        " present");
                errno = EINVAL;
                op_ret = -1;
                goto out;
        }

        pthread_mutex_lock (&inode_ctx->lock);
        {
                /* Take a timestamp only after we've acquired the
                 * lock.
                 */
                current = time (NULL);
                if (flags & LIBGF_UPDATE_LOOKUP) {
                        gf_log (LIBGF_XL_NAME, GF_LOG_TRACE, "Updating lookup");
                        inode_ctx->previous_lookup_time = current;
                }

                if (flags & LIBGF_UPDATE_STAT) {
                        gf_log (LIBGF_XL_NAME, GF_LOG_TRACE, "Updating stat");

                        /* Update the cached stat struct only if a new
                         * stat buf is given.
                         */
                        if (buf != NULL) {
                                inode_ctx->previous_stat_time = current;
                                memcpy (&inode_ctx->stbuf, buf,
                                                sizeof (inode_ctx->stbuf));
                        }
                }
        }
        pthread_mutex_unlock (&inode_ctx->lock);
        op_ret = 0;

out:
        return op_ret;
}


int
libgf_invalidate_iattr_cache (inode_t *inode, int flags)
{
        libglusterfs_client_inode_ctx_t         *ictx = NULL;

        if (!inode)
                return -1;

        ictx = libgf_get_inode_ctx (inode);
        if (!ictx) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "No inode context"
                        " present");
                return -1;
        }

        pthread_mutex_lock (&ictx->lock);
        {
                if (flags & LIBGF_INVALIDATE_LOOKUP) {
                        gf_log (LIBGF_XL_NAME, GF_LOG_TRACE, "Invalidating"
                                " lookup");
                        ictx->previous_lookup_time = 0;
                }

                if (flags & LIBGF_INVALIDATE_STAT) {
                        gf_log (LIBGF_XL_NAME, GF_LOG_TRACE, "Invalidating"
                                " stat");
                        ictx->previous_stat_time = 0;
                }

        }
        pthread_mutex_unlock (&ictx->lock);

        return 0;
}


int
libgf_is_iattr_cache_valid (libglusterfs_client_ctx_t *ctx, inode_t *inode,
                            struct stat *sbuf, int flags)
{
        time_t                                  current = 0;
        time_t                                  prev = 0;
        libglusterfs_client_inode_ctx_t         *inode_ctx = NULL;
        int                                     cache_valid = 0;
        time_t                                  timeout = 0;

        if (inode == NULL)
                return 0;

        inode_ctx = libgf_get_inode_ctx (inode);
        if (!inode_ctx) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "No inode context"
                        " present\n");
                return 0;
        }

        pthread_mutex_lock (&inode_ctx->lock);
        {
                current = time (NULL);
                if (flags & LIBGF_VALIDATE_LOOKUP) {
                        gf_log (LIBGF_XL_NAME, GF_LOG_TRACE, "Checking lookup");
                        prev = inode_ctx->previous_lookup_time;
                        timeout = ctx->lookup_timeout;
                } else {
                        gf_log (LIBGF_XL_NAME, GF_LOG_TRACE, "Checking stat");
                        prev = inode_ctx->previous_stat_time;
                        timeout = ctx->stat_timeout;
                }

                /* Even if the timeout is set to -1 to cache
                 * infinitely, fops like write must invalidate the
                 * stat cache because writev_cbk cannot update
                 * the cache using the stat returned to it. This is
                 * because write-behind can return a stat bufs filled
                 * with zeroes.
                 */
                if (prev == 0) {
                        cache_valid = 0;
                        gf_log (LIBGF_XL_NAME, GF_LOG_TRACE, "Cache Invalid");
                        goto iattr_unlock_out;
                }

                /* Cache infinitely */
                if (timeout == (time_t)-1) {
                        cache_valid = 1;
                        gf_log (LIBGF_XL_NAME, GF_LOG_TRACE, "Caching On and "
                                "valid");
                        goto iattr_unlock_out;
                }

                /* Disable caching completely */
                if (timeout == 0) {
                        cache_valid = 0;
                        gf_log (LIBGF_XL_NAME, GF_LOG_TRACE, "Cache disabled");
                        goto iattr_unlock_out;
                }

                if ((prev > 0) && (timeout >= (current - prev))) {
                        gf_log (LIBGF_XL_NAME, GF_LOG_TRACE, "Cache valid");
                        cache_valid = 1;
                }

                if (flags & LIBGF_VALIDATE_LOOKUP)
                        goto iattr_unlock_out;

                if ((cache_valid) && (sbuf))
                        *sbuf = inode_ctx->stbuf;
        }
iattr_unlock_out:
        pthread_mutex_unlock (&inode_ctx->lock);

        return cache_valid;
}

int32_t
libgf_client_releasedir (xlator_t *this,
			 fd_t *fd)
{
	libglusterfs_client_fd_ctx_t *fd_ctx = NULL;
        fd_ctx = libgf_get_fd_ctx (fd);
        if (S_ISDIR (fd->inode->st_mode)) {
                libgf_dcache_invalidate (fd);
                FREE (fd_ctx->dcache);
        }

        libgf_del_fd_ctx (fd);
        if (fd_ctx != NULL) {
                pthread_mutex_destroy (&fd_ctx->lock);
                FREE (fd_ctx);
        }

	return 0;
}

void *poll_proc (void *ptr)
{
        glusterfs_ctx_t *ctx = ptr;

        event_dispatch (ctx->event_pool);

        return NULL;
}


int32_t
xlator_graph_init (xlator_t *xl)
{
        xlator_t *trav = xl;
        int32_t ret = -1;

        while (trav->prev)
                trav = trav->prev;

        while (trav) {
                if (!trav->ready) {
                        ret = xlator_tree_init (trav);
                        if (ret < 0)
                                break;
                }
                trav = trav->next;
        }

        return ret;
}


void
xlator_graph_fini (xlator_t *xl)
{
	xlator_t *trav = xl;
	while (trav->prev)
		trav = trav->prev;

	while (trav) {
		if (!trav->init_succeeded) {
			break;
		}

		xlator_tree_fini (trav);
		trav = trav->next;
	}
}

/* Returns a pointer to the @n'th char matching
 * @c in string @str, starting the search from right or
 * end-of-string, rather than starting from left, as rindex
 * function does.
 */
char *
libgf_rrindex (char *str, int c, int n)
{
        int     len = 0;
        int     occurrence = 0;

        if (str == NULL)
                return NULL;

        len = strlen (str);
        /* Point to last character of string. */
        str += (len - 1);
        while (len > 0) {
                if ((int)*str == c) {
                        ++occurrence;
                        if (occurrence == n)
                                break;
                }
                --len;
                --str;
        }

        return str;
}

char *
libgf_trim_to_prev_dir (char * path)
{
        char    *idx = NULL;
        int      len = 0;

        if (!path)
                return NULL;

        /* Check if we're already at root, if yes
         * then there is no prev dir.
         */
        len = strlen (path);
        if (len == 1)
                return path;

        if (path[len - 1] == '/') {
                path[len - 1] = '\0';
        }

        idx = libgf_rrindex (path, '/', 1);
        /* Move to the char after the / */
        ++idx;
        *idx = '\0';

        return path;
}

/* Performs a lightweight path resolution that only
 * looks for . and  .. and replaces those with the
 * proper names.
 *
 * FIXME: This is a stop-gap measure till we have full
 * fledge path resolution going in here.
 * Function returns path strdup'ed so remember to FREE the
 * string as required.
 */
char *
libgf_resolve_path_light (char *path)
{
        char            *respath = NULL;
        char            *saveptr = NULL;
        char            *tok = NULL;
        char            *mypath = NULL;
        int             len = 0;
        int             addslash = 0;

        if (!path)
                goto out;

        /* We dont as yet support relative paths anywhere in
         * the lib.
         */
        if (path[0] != '/')
                goto out;

        mypath = strdup (path);
        len = strlen (mypath);
        respath = calloc (strlen(mypath) + 1, sizeof (char));
        if (respath == NULL) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR,"Memory allocation failed");
                goto out;
        }

        /* The path only contains a / or a //, so simply add a /
         * and return.
         * This needs special handling because the loop below does
         * not allow us to do so through strtok.
         */
        if (((mypath[0] == '/') && (len == 1))
                        || (strcmp (mypath, "//") == 0)) {
                strcat (respath, "/");
                goto out;
        }

        tok = strtok_r (mypath, "/", &saveptr);
        addslash = 0;
        strcat (respath, "/");
        while (tok) {
                if (addslash) {
                        if ((strcmp (tok, ".") != 0)
                                        && (strcmp (tok, "..") != 0)) {
                                strcat (respath, "/");
                        }
                }

                if ((strcmp (tok, ".") != 0) && (strcmp (tok, "..") != 0)) {
                        strcat (respath, tok);
                        addslash = 1;
                } else if ((strcmp (tok, "..") == 0)) {
                        libgf_trim_to_prev_dir (respath);
                        addslash = 0;
                }

                tok = strtok_r (NULL, "/", &saveptr);
        }

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "Path: %s, Resolved Path: %s",
                path, respath);
out:
        if (mypath)
                free (mypath);
        return respath;
}

void 
libgf_client_loc_wipe (loc_t *loc)
{
	if (loc->path) {
		FREE (loc->path);
	}

	if (loc->parent) { 
		inode_unref (loc->parent);
		loc->parent = NULL;
	}

	if (loc->inode) {
		inode_unref (loc->inode);
		loc->inode = NULL;
	}

	loc->path = loc->name = NULL;
        loc->ino = 0;
}


int32_t
libgf_client_loc_fill (loc_t *loc,
		       libglusterfs_client_ctx_t *ctx,
		       ino_t ino,
		       ino_t par,
		       const char *name)
{
        inode_t *inode = NULL, *parent = NULL;
	int32_t ret = -1;
	char *path = NULL;

        /* resistance against multiple invocation of loc_fill not to get
           reference leaks via inode_search() */

        inode = loc->inode;
	
        if (!inode) {
                if (ino)
                        inode = inode_search (ctx->itable, ino, NULL);

                if (inode)
                        goto inode_found;

                if (par && name)
                        inode = inode_search (ctx->itable, par, name);
        }

inode_found:
        if (inode) {
                loc->ino = inode->ino;
                loc->inode = inode;
        }

        parent = loc->parent;
        if (!parent) {
                if (inode)
                        parent = inode_parent (inode, par, name);
                else
                        parent = inode_search (ctx->itable, par, NULL);
                loc->parent = parent;
        }
  
	if (!loc->path) {
		if (name && parent) {
			ret = inode_path (parent, name, &path);
			if (ret <= 0) {
				gf_log ("glusterfs-fuse", GF_LOG_ERROR,
					"inode_path failed for %"PRId64"/%s",
					parent->ino, name);
				goto fail;
			} else {
				loc->path = path;
			}
		} else 	if (inode) {
			ret = inode_path (inode, NULL, &path);
			if (ret <= 0) {
				gf_log ("glusterfs-fuse", GF_LOG_ERROR,
					"inode_path failed for %"PRId64,
					inode->ino);
				goto fail;
			} else {
				loc->path = path;
			}
		}
	}

	if (loc->path) {
		loc->name = strrchr (loc->path, '/');
		if (loc->name)
			loc->name++;
		else loc->name = "";
	}
	
	if ((ino != 1) &&
	    (parent == NULL)) {
		gf_log ("fuse-bridge", GF_LOG_ERROR,
			"failed to search parent for %"PRId64"/%s (%"PRId64")",
			(ino_t)par, name, (ino_t)ino);
		ret = -1;
		goto fail;
	}
	ret = 0;
fail:
	return ret;
}


static call_frame_t *
get_call_frame_for_req (libglusterfs_client_ctx_t *ctx, char d)
{
        call_pool_t  *pool = ctx->gf_ctx.pool;
        xlator_t     *this = ctx->gf_ctx.graph;
        call_frame_t *frame = NULL;
  

        frame = create_frame (this, pool);

        frame->root->uid = geteuid ();
        frame->root->gid = getegid ();
        frame->root->pid = ctx->pid;
        frame->root->unique = ctx->counter++;
  
        return frame;
}

void 
libgf_client_fini (xlator_t *this)
{
	FREE (this->private);
        return;
}


int32_t
libgf_client_notify (xlator_t *this, 
                     int32_t event,
                     void *data, 
                     ...)
{
        libglusterfs_client_private_t *priv = this->private;

        switch (event)
        {
        case GF_EVENT_CHILD_UP:
                pthread_mutex_lock (&priv->lock);
                {
                        priv->complete = 1;
                        pthread_cond_broadcast (&priv->init_con_established);
                }
                pthread_mutex_unlock (&priv->lock);
                break;

        default:
                default_notify (this, event, data);
        }

        return 0;
}

int32_t 
libgf_client_init (xlator_t *this)
{
        return 0;
}

glusterfs_handle_t 
glusterfs_init (glusterfs_init_params_t *init_ctx, uint32_t fakefsid)
{
        libglusterfs_client_ctx_t *ctx = NULL;
        libglusterfs_client_private_t *priv = NULL;
        FILE *specfp = NULL;
        xlator_t *graph = NULL, *trav = NULL;
        call_pool_t *pool = NULL;
        int32_t ret = 0;
        struct rlimit lim;
	uint32_t xl_count = 0;
        loc_t       new_loc = {0, };
        struct timeval tv = {0, };

        if (!init_ctx || (!init_ctx->specfile && !init_ctx->specfp)) {
                errno = EINVAL;
                return NULL;
        }

        ctx = CALLOC (1, sizeof (*ctx));
        if (!ctx) {
		fprintf (stderr, 
			 "libglusterfsclient: %s:%s():%d: out of memory\n",
			 __FILE__, __PRETTY_FUNCTION__, __LINE__);

                errno = ENOMEM;
                return NULL;
        }

        ctx->lookup_timeout = init_ctx->lookup_timeout;
        ctx->stat_timeout = init_ctx->stat_timeout;
        ctx->fake_fsid = fakefsid;
        ctx->pid = getpid ();
        pthread_mutex_init (&ctx->gf_ctx.lock, NULL);
  
        pool = ctx->gf_ctx.pool = CALLOC (1, sizeof (call_pool_t));
        if (!pool) {
                errno = ENOMEM;
                FREE (ctx);
                return NULL;
        }

        LOCK_INIT (&pool->lock);
        INIT_LIST_HEAD (&pool->all_frames);

	/* FIXME: why is count hardcoded to 16384 */
        ctx->gf_ctx.event_pool = event_pool_new (16384);
        ctx->gf_ctx.page_size  = LIBGF_IOBUF_SIZE;
        ctx->gf_ctx.iobuf_pool = iobuf_pool_new (8 * 1048576,
                                                 ctx->gf_ctx.page_size);

        lim.rlim_cur = RLIM_INFINITY;
        lim.rlim_max = RLIM_INFINITY;
        setrlimit (RLIMIT_CORE, &lim);
        setrlimit (RLIMIT_NOFILE, &lim);

        ctx->gf_ctx.cmd_args.log_level = GF_LOG_WARNING;

        if (init_ctx->logfile)
                ctx->gf_ctx.cmd_args.log_file = strdup (init_ctx->logfile);
        else
                ctx->gf_ctx.cmd_args.log_file = strdup ("/dev/stderr");

        if (init_ctx->loglevel) {
                if (!strncasecmp (init_ctx->loglevel, "DEBUG",
                                  strlen ("DEBUG"))) {
                        ctx->gf_ctx.cmd_args.log_level = GF_LOG_DEBUG;
                } else if (!strncasecmp (init_ctx->loglevel, "WARNING",
                                         strlen ("WARNING"))) {
                        ctx->gf_ctx.cmd_args.log_level = GF_LOG_WARNING;
                } else if (!strncasecmp (init_ctx->loglevel, "CRITICAL",
                                         strlen ("CRITICAL"))) {
                        ctx->gf_ctx.cmd_args.log_level = GF_LOG_CRITICAL;
                } else if (!strncasecmp (init_ctx->loglevel, "NONE",
                                         strlen ("NONE"))) {
                        ctx->gf_ctx.cmd_args.log_level = GF_LOG_NONE;
                } else if (!strncasecmp (init_ctx->loglevel, "ERROR",
                                         strlen ("ERROR"))) {
                        ctx->gf_ctx.cmd_args.log_level = GF_LOG_ERROR;
                } else if (!strncasecmp (init_ctx->loglevel, "TRACE",
                                         strlen ("TRACE"))) {
                        ctx->gf_ctx.cmd_args.log_level = GF_LOG_TRACE;
                } else {
			fprintf (stderr, 
				 "libglusterfsclient: %s:%s():%d: Unrecognized log-level \"%s\", possible values are \"DEBUG|WARNING|[ERROR]|CRITICAL|NONE|TRACE\"\n",
                                 __FILE__, __PRETTY_FUNCTION__, __LINE__,
                                 init_ctx->loglevel);
			FREE (ctx->gf_ctx.cmd_args.log_file);
                        FREE (ctx->gf_ctx.pool);
                        FREE (ctx->gf_ctx.event_pool);
                        FREE (ctx);
                        errno = EINVAL;
                        return NULL;
                }
        }

	if (first_init)
        {
                ret = gf_log_init (ctx->gf_ctx.cmd_args.log_file);
                if (ret == -1) {
			fprintf (stderr, 
				 "libglusterfsclient: %s:%s():%d: failed to open logfile \"%s\"\n", 
				 __FILE__, __PRETTY_FUNCTION__, __LINE__, 
				 ctx->gf_ctx.cmd_args.log_file);
			FREE (ctx->gf_ctx.cmd_args.log_file);
                        FREE (ctx->gf_ctx.pool);
                        FREE (ctx->gf_ctx.event_pool);
                        FREE (ctx);
                        return NULL;
                }

                gf_log_set_loglevel (ctx->gf_ctx.cmd_args.log_level);
        }

        if (init_ctx->specfp) {
                specfp = init_ctx->specfp;
                if (fseek (specfp, 0L, SEEK_SET)) {
			fprintf (stderr, 
				 "libglusterfsclient: %s:%s():%d: fseek on volume file stream failed (%s)\n",
                                 __FILE__, __PRETTY_FUNCTION__, __LINE__,
                                 strerror (errno));
			FREE (ctx->gf_ctx.cmd_args.log_file);
                        FREE (ctx->gf_ctx.pool);
                        FREE (ctx->gf_ctx.event_pool);
                        FREE (ctx);
                        return NULL;
                }
        } else if (init_ctx->specfile) { 
                specfp = fopen (init_ctx->specfile, "r");
                ctx->gf_ctx.cmd_args.volume_file = strdup (init_ctx->specfile);
        }

        if (!specfp) {
		fprintf (stderr, 
			 "libglusterfsclient: %s:%s():%d: could not open volfile: %s\n", 
			 __FILE__, __PRETTY_FUNCTION__, __LINE__,
                         strerror (errno));
		FREE (ctx->gf_ctx.cmd_args.log_file);
                FREE (ctx->gf_ctx.cmd_args.volume_file);
                FREE (ctx->gf_ctx.pool);
                FREE (ctx->gf_ctx.event_pool);
                FREE (ctx);
                return NULL;
        }

        if (init_ctx->volume_name) {
                ctx->gf_ctx.cmd_args.volume_name = strdup (init_ctx->volume_name);
        }

	graph = file_to_xlator_tree (&ctx->gf_ctx, specfp);
        if (!graph) {
		fprintf (stderr, 
			 "libglusterfsclient: %s:%s():%d: cannot create configuration graph (%s)\n",
			 __FILE__, __PRETTY_FUNCTION__, __LINE__,
                         strerror (errno));

		FREE (ctx->gf_ctx.cmd_args.log_file);
                FREE (ctx->gf_ctx.cmd_args.volume_file);
                FREE (ctx->gf_ctx.cmd_args.volume_name);
                FREE (ctx->gf_ctx.pool);
                FREE (ctx->gf_ctx.event_pool);
                FREE (ctx);
                return NULL;
        }

        if (init_ctx->volume_name) {
                trav = graph;
                while (trav) {
                        if (strcmp (trav->name, init_ctx->volume_name) == 0) {
                                graph = trav;
                                break;
                        }
                        trav = trav->next;
                }
        }

        ctx->gf_ctx.graph = libglusterfs_graph (graph);
        if (!ctx->gf_ctx.graph) {
		fprintf (stderr, 
			 "libglusterfsclient: %s:%s():%d: graph creation failed (%s)\n",
			 __FILE__, __PRETTY_FUNCTION__, __LINE__,
                         strerror (errno));

		xlator_tree_free (graph);
		FREE (ctx->gf_ctx.cmd_args.log_file);
                FREE (ctx->gf_ctx.cmd_args.volume_file);
                FREE (ctx->gf_ctx.cmd_args.volume_name);
                FREE (ctx->gf_ctx.pool);
                FREE (ctx->gf_ctx.event_pool);
                FREE (ctx);
                return NULL;
        }
        graph = ctx->gf_ctx.graph;
        ctx->gf_ctx.top = graph;

	trav = graph;
	while (trav) {
		xl_count++;  /* Getting this value right is very important */
		trav = trav->next;
	}

	ctx->gf_ctx.xl_count = xl_count + 1;

        priv = CALLOC (1, sizeof (*priv));
        if (!priv) {
		fprintf (stderr, 
			 "libglusterfsclient: %s:%s():%d: cannot allocate memory (%s)\n",
			 __FILE__, __PRETTY_FUNCTION__, __LINE__,
                         strerror (errno));

		xlator_tree_free (graph);
		FREE (ctx->gf_ctx.cmd_args.log_file);
                FREE (ctx->gf_ctx.cmd_args.volume_file);
                FREE (ctx->gf_ctx.cmd_args.volume_name);
                FREE (ctx->gf_ctx.pool);
                FREE (ctx->gf_ctx.event_pool);
                /* inode_table_destroy (ctx->itable); */
                FREE (ctx);
         
                return NULL;
        }

        pthread_cond_init (&priv->init_con_established, NULL);
        pthread_mutex_init (&priv->lock, NULL);

        graph->private = priv;
        ctx->itable = inode_table_new (LIBGLUSTERFS_INODE_TABLE_LRU_LIMIT,
                                       graph);
        if (!ctx->itable) {
		fprintf (stderr, 
			 "libglusterfsclient: %s:%s():%d: cannot create inode table\n",
			 __FILE__, __PRETTY_FUNCTION__, __LINE__);
		xlator_tree_free (graph); 
		FREE (ctx->gf_ctx.cmd_args.log_file);
                FREE (ctx->gf_ctx.cmd_args.volume_file);
                FREE (ctx->gf_ctx.cmd_args.volume_name);

                FREE (ctx->gf_ctx.pool);
                FREE (ctx->gf_ctx.event_pool);
		xlator_tree_free (graph); 
                /* TODO: destroy graph */
                /* inode_table_destroy (ctx->itable); */
                FREE (ctx);
         
                return NULL;
        }

	set_global_ctx_ptr (&ctx->gf_ctx);
	ctx->gf_ctx.process_uuid = zr_build_process_uuid ();

        if (xlator_graph_init (graph) == -1) {
		fprintf (stderr, 
			 "libglusterfsclient: %s:%s():%d: graph initialization failed\n",
			 __FILE__, __PRETTY_FUNCTION__, __LINE__);
		xlator_tree_free (graph);
		FREE (ctx->gf_ctx.cmd_args.log_file);
                FREE (ctx->gf_ctx.cmd_args.volume_file);
                FREE (ctx->gf_ctx.cmd_args.volume_name);
                FREE (ctx->gf_ctx.pool);
                FREE (ctx->gf_ctx.event_pool);
                /* TODO: destroy graph */
                /* inode_table_destroy (ctx->itable); */
                FREE (ctx);
                return NULL;
        }

	/* Send notify to all translator saying things are ready */
	graph->notify (graph, GF_EVENT_PARENT_UP, graph);

        if (gf_timer_registry_init (&ctx->gf_ctx) == NULL) {
		fprintf (stderr, 
			 "libglusterfsclient: %s:%s():%d: timer init failed (%s)\n", 
			 __FILE__, __PRETTY_FUNCTION__, __LINE__,
                         strerror (errno));

		xlator_graph_fini (graph);
		xlator_tree_free (graph);
		FREE (ctx->gf_ctx.cmd_args.log_file);
                FREE (ctx->gf_ctx.cmd_args.volume_file);
                FREE (ctx->gf_ctx.cmd_args.volume_name);

                FREE (ctx->gf_ctx.pool);
                FREE (ctx->gf_ctx.event_pool);
                /* TODO: destroy graph */
                /* inode_table_destroy (ctx->itable); */
                FREE (ctx);
                return NULL;
        }

        if ((ret = pthread_create (&ctx->reply_thread, NULL, poll_proc,
                                   (void *)&ctx->gf_ctx))) {
		fprintf (stderr, 
			 "libglusterfsclient: %s:%s():%d: reply thread creation failed\n", 
			 __FILE__, __PRETTY_FUNCTION__, __LINE__);
		xlator_graph_fini (graph);
		xlator_tree_free (graph);
		FREE (ctx->gf_ctx.cmd_args.log_file);
                FREE (ctx->gf_ctx.cmd_args.volume_file);
                FREE (ctx->gf_ctx.cmd_args.volume_name);

                FREE (ctx->gf_ctx.pool);
                FREE (ctx->gf_ctx.event_pool);
                /* TODO: destroy graph */
                /* inode_table_destroy (ctx->itable); */
                FREE (ctx);
                return NULL;
        }

        pthread_mutex_lock (&priv->lock); 
        {
                while (!priv->complete) {
                        pthread_cond_wait (&priv->init_con_established,
                                           &priv->lock);
                }
        }
        pthread_mutex_unlock (&priv->lock);

        /* 
         * wait for some time to allow initialization of all children of 
         * distribute before sending lookup on '/'
         */

        tv.tv_sec = 0;
        tv.tv_usec = (100 * 1000);
        select (0, NULL, NULL, NULL, &tv);

        /* workaround for xlators like dht which require lookup to be sent
         * on / */
        libgf_client_loc_fill (&new_loc, ctx, 1, 0, "/");
        ret = libgf_client_lookup (ctx, &new_loc, NULL, NULL, NULL);
        if (ret == -1) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR, "lookup of /"
                        " failed");
                return NULL;
        }
        libgf_client_loc_wipe (&new_loc);
        libgf_alloc_inode_ctx (ctx, ctx->itable->root);

	first_init = 0;
 
        return ctx;
}

struct vmp_entry *
libgf_init_vmpentry (char *vmp, glusterfs_handle_t *vmphandle)
{
        struct vmp_entry        *entry = NULL;
        int                     vmplen = 0;
        int                     appendslash = 0;
        int                     ret = -1;

        entry = CALLOC (1, sizeof (struct vmp_entry));
        if (!entry) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR,"Memory allocation failed");
                return NULL;
        }

        vmplen = strlen (vmp);
        if (vmp[vmplen - 1] != '/') {
                vmplen++;
                appendslash = 1;
        }

        entry->vmp = CALLOC (vmplen + 1, sizeof (char));
        if (!entry->vmp) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Memory allocation "
                        "failed");
                goto free_entry;
        }

        strcpy (entry->vmp, vmp);
        if (appendslash) {
                entry->vmp[vmplen-1] = '/';
                entry->vmp[vmplen] = '\0';
        }
 
        entry->vmplen = vmplen;
        entry->handle = vmphandle;
        INIT_LIST_HEAD (&entry->list);
        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "New VMP entry: %s", vmp);

        ret = 0;

free_entry:
        if (ret == -1) {
                if (entry->vmp)
                        FREE (entry->vmp);
                if (entry)
                        FREE (entry);
                entry = NULL;
        }
        return entry;
}

void
libgf_free_vmp_entry (struct vmp_entry *entry)
{
        FREE (entry->vmp);
        FREE (entry);
}

int
libgf_count_path_components (char *path)
{
        int     compos = 0;
        char    *pathdup = NULL;
        int     len = 0;

        if (!path)
                return -1;

        pathdup = strdup (path);
        if (!pathdup)
                return -1;

        len = strlen (pathdup);
        if (pathdup[len - 1] == '/')
                pathdup[len - 1] = '\0';

        path = pathdup;
        while ((path = strchr (path, '/'))) {
                compos++;
                ++path;
        }

        free (pathdup);
        return compos;
}

/* Returns the number of components that match between
 * the VMP and the path. Assumes string1 is vmp entry.
 * Assumes both are absolute paths.
 */
int
libgf_strmatchcount (char *string1, char *string2)
{
        int     matchcount = 0;
        char    *s1dup = NULL, *s2dup = NULL;
        char    *tok1 = NULL, *saveptr1 = NULL;
        char    *tok2 = NULL, *saveptr2 = NULL;

        if ((!string1) || (!string2))
                return 0;

        s1dup = strdup (string1);
        if (!s1dup)
                return 0;

        s2dup  = strdup (string2);
        if (!s2dup)
                goto free_s1;

        string1 = s1dup;
        string2 = s2dup;

        tok1 = strtok_r(string1, "/", &saveptr1);
        tok2 = strtok_r (string2, "/", &saveptr2);
        while (tok1) {
                if (!tok2)
                        break;

                if (strcmp (tok1, tok2) != 0)
                        break;

                matchcount++;
                tok1 = strtok_r(NULL, "/", &saveptr1);
                tok2 = strtok_r (NULL, "/", &saveptr2);
        }

        free (s2dup);
free_s1:
        free (s1dup);
        return matchcount;
}

int
libgf_vmp_entry_match (struct vmp_entry *entry, char *path)
{
        return libgf_strmatchcount (entry->vmp, path);
}

#define LIBGF_VMP_EXACT          1
#define LIBGF_VMP_LONGESTPREFIX  0
struct vmp_entry *
_libgf_vmp_search_entry (char *path, int searchtype)
{
        struct vmp_entry        *entry = NULL;
        int                     matchcount = 0;
        struct vmp_entry        *maxentry = NULL;
        int                     maxcount = 0;
        int                     vmpcompcount = 0;

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "VMP Search: path %s, type: %s",
                path, (searchtype == LIBGF_VMP_EXACT)?"Exact":"LongestPrefix");
        if (vmplist.entries == 0) {
                gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "Virtual Mount Point "
                        "list is empty.");
                goto out;
        }

        list_for_each_entry(entry, &vmplist.list, list) {
                vmpcompcount = libgf_count_path_components (entry->vmp);
                matchcount = libgf_vmp_entry_match (entry, path);
                gf_log (LIBGF_XL_NAME, GF_LOG_TRACE, "Candidate VMP:  %s,"
                        " Matchcount: %d", entry->vmp, matchcount);
                if ((matchcount > maxcount) && (matchcount == vmpcompcount)) {
                        maxcount = matchcount;
                        maxentry = entry;
                }
        }

        /* To ensure that the longest prefix matched entry is also an exact
         * match, this is used to check whether duplicate entries are present
         * in the vmplist.
         */
        vmpcompcount = 0;
        if ((searchtype == LIBGF_VMP_EXACT) && (maxentry)) {
                vmpcompcount = libgf_count_path_components (maxentry->vmp);
                matchcount = libgf_count_path_components (path);
                gf_log (LIBGF_XL_NAME, GF_LOG_TRACE, "Exact Check: VMP: %s,"
                        " CompCount: %d, Path: %s, CompCount: %d",
                        maxentry->vmp, vmpcompcount, path, matchcount);
                if (vmpcompcount != matchcount) {
                        gf_log (LIBGF_XL_NAME, GF_LOG_TRACE, "No Match");
                        maxentry = NULL;
                } else
                        gf_log (LIBGF_XL_NAME, GF_LOG_TRACE, "Matches!");
        }

out:        
        return maxentry;
} 

/* Used to search for a exactly matching VMP entry.
 */
struct vmp_entry *
libgf_vmp_search_exact_entry (char *path)
{
        struct vmp_entry        *entry = NULL;

        if (!path)
                goto out;

        pthread_mutex_lock (&vmplock);
        {
                entry = _libgf_vmp_search_entry (path, LIBGF_VMP_EXACT);
        }
        pthread_mutex_unlock (&vmplock);

out:
        if (entry)
                gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "VMP Entry found: path :%s"
                        " vmp: %s", path, entry->vmp);
        else
                gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "VMP Entry not found: path"
                        ": %s", path);

        return entry;
}


/* Used to search for a longest prefix matching VMP entry.
 */
struct vmp_entry *
libgf_vmp_search_entry (char *path)
{
        struct vmp_entry        *entry = NULL;

        if (!path)
                goto out;

        pthread_mutex_lock (&vmplock);
        {
                entry = _libgf_vmp_search_entry (path, LIBGF_VMP_LONGESTPREFIX);
        }
        pthread_mutex_unlock (&vmplock);

out:
        if (entry)
                gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "VMP Entry found: path :%s"
                        " vmp: %s", path, entry->vmp);
        else
                gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "VMP Entry not found: path"
                        ": %s", path);

        return entry;
}

int
libgf_vmp_map_ghandle (char *vmp, glusterfs_handle_t *vmphandle)
{
        int                     ret = -1;
        struct vmp_entry        *vmpentry = NULL;

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "New Entry: %s", vmp);
        vmpentry = libgf_init_vmpentry (vmp, vmphandle);
        if (!vmpentry) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Failed to create VMP"
                        " entry");
                goto out;
        }

        pthread_mutex_lock (&vmplock);
        {
                if (vmplist.entries == 0) {
                        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "Empty list");
                        INIT_LIST_HEAD (&vmplist.list);
                }

                list_add_tail (&vmpentry->list, &vmplist.list);
                ++vmplist.entries;
        }
        pthread_mutex_unlock (&vmplock);
        ret = 0;

out:
        return ret;
}

/* Path must be validated already. */
glusterfs_handle_t
libgf_vmp_get_ghandle (char * path)
{
        struct vmp_entry        *entry = NULL;

        entry = libgf_vmp_search_entry (path);

        if (entry == NULL)
                return NULL;

        return entry->handle;
}

int
glusterfs_mount (char *vmp, glusterfs_init_params_t *ipars)
{
        glusterfs_handle_t      vmphandle = NULL;
        int                     ret = -1;
        char                    *vmp_resolved = NULL;
        struct vmp_entry        *vmp_entry = NULL;
        uint32_t                vmphash = 0;
        
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, vmp, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ipars, out);

        vmp_resolved = libgf_resolve_path_light (vmp);
        if (!vmp_resolved) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

        vmphash = (dev_t)ReallySimpleHash (vmp, strlen (vmp));
        pthread_mutex_lock (&mountlock);
        {
                vmp_entry = libgf_vmp_search_exact_entry (vmp);
                if (vmp_entry) {
                        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "Entry exists");
                        ret = 0;
                        goto unlock;
                }

                vmphandle = glusterfs_init (ipars, vmphash);
                if (!vmphandle) {
                        errno = EINVAL;
                        gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "GlusterFS context"
                                " init failed");
                        goto unlock;
                }

                ret = libgf_vmp_map_ghandle (vmp_resolved, vmphandle);
                if (ret == -1) {
                        gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Failed to map new"
                                " handle: %s", vmp);
                        glusterfs_fini (vmphandle);
                }
        }
unlock:
        pthread_mutex_unlock (&mountlock);

out:
        if (vmp_resolved)
                FREE (vmp_resolved);

        return ret;
}

inline int
_libgf_umount (char *vmp)
{
        struct vmp_entry *entry= NULL;
        int               ret = -1;

        entry = _libgf_vmp_search_entry (vmp, LIBGF_VMP_EXACT);
        if (entry == NULL) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                        "path (%s) not mounted", vmp);
                goto out;
        }

        if (entry->handle == NULL) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                        "path (%s) has no corresponding glusterfs handle",
                        vmp);
                goto out;
        }

        ret = glusterfs_fini (entry->handle);
        list_del_init (&entry->list);
        libgf_free_vmp_entry (entry);

        vmplist.entries--; 

out:
        return ret;
}

inline int
libgf_umount (char *vmp)
{
        int ret = -1;

        pthread_mutex_lock (&vmplock);
        { 
                ret = _libgf_umount (vmp);
        }
        pthread_mutex_unlock (&vmplock);
        
        return ret;
}

int
glusterfs_umount (char *vmp)
{ 
        int    ret = -1; 
        char *vmp_resolved = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, vmp, out);

        vmp_resolved = libgf_resolve_path_light (vmp);
        if (!vmp_resolved) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

        ret = libgf_umount (vmp_resolved);

out:
        if (vmp_resolved)
                FREE (vmp_resolved);

        return ret;
}

int
glusterfs_umount_all (void)
{
        struct vmp_entry *entry = NULL, *tmp = NULL;

        pthread_mutex_lock (&vmplock);
        {
                if (vmplist.entries > 0) {
                        list_for_each_entry_safe (entry, tmp, &vmplist.list,
                                                  list) {
                                /* even if there are errors, continue with other
                                   mounts
                                */
                                _libgf_umount (entry->vmp);
                        }
                }
        }
        pthread_mutex_unlock (&vmplock);
        
        return 0;
}

void
glusterfs_reset (void)
{
        INIT_LIST_HEAD (&vmplist.list);
        vmplist.entries = 0;

        memset (&vmplock, 0, sizeof (vmplock));
        pthread_mutex_init (&vmplock, NULL);

	first_init = 1;
}

void 
glusterfs_log_lock (void)
{
	gf_log_lock ();
}


void glusterfs_log_unlock (void)
{
	gf_log_unlock ();
}


void
libgf_wait_for_frames_unwind (libglusterfs_client_ctx_t *ctx)
{
        call_pool_t     *pool = NULL;
        int             canreturn = 0;

        if (!ctx)
                return;

        pool = (call_pool_t *)ctx->gf_ctx.pool;
        while (1) {
                LOCK (&pool->lock);
                {
                        if (pool->cnt == 0) {
                                canreturn = 1;
                                goto unlock_out;
                        }
                }
unlock_out:
                UNLOCK (&pool->lock);

                if (canreturn)
                        break;

                gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "Waiting for call frames");
                sleep (1);
        }

        return;
}


int 
glusterfs_fini (glusterfs_handle_t handle)
{
	libglusterfs_client_ctx_t *ctx = handle;

        libgf_wait_for_frames_unwind (ctx);

	FREE (ctx->gf_ctx.cmd_args.log_file);
	FREE (ctx->gf_ctx.cmd_args.volume_file);
	FREE (ctx->gf_ctx.cmd_args.volume_name);
	FREE (ctx->gf_ctx.pool);
        FREE (ctx->gf_ctx.event_pool);
        /* iobuf_pool_destroy (ctx->gf_ctx.iobuf_pool); */
        ((gf_timer_registry_t *)ctx->gf_ctx.timer)->fin = 1;

	xlator_graph_fini (ctx->gf_ctx.graph);
	xlator_tree_free (ctx->gf_ctx.graph);
	ctx->gf_ctx.graph = NULL;
        pthread_cancel (ctx->reply_thread);

        FREE (ctx);

        return 0;
}


int32_t 
libgf_client_lookup_cbk (call_frame_t *frame,
                         void *cookie,
                         xlator_t *this,
                         int32_t op_ret,
                         int32_t op_errno,
                         inode_t *inode,
                         struct stat *buf,
                         dict_t *dict,
                         struct stat *postparent)
{
        libgf_client_local_t *local = frame->local;
        libglusterfs_client_ctx_t *ctx = frame->root->state;
	dict_t *xattr_req = NULL;

        if (op_ret == 0) {
		inode_t *parent = NULL;

		if (local->fop.lookup.loc->ino == 1) {
			buf->st_ino = 1;
		}

		parent = local->fop.lookup.loc->parent;
                libgf_transform_devnum (ctx, buf);
                inode_link (inode, parent, local->fop.lookup.loc->name, buf);
		inode_lookup (inode);
        } else {
                if ((local->fop.lookup.is_revalidate == 0) 
                    && (op_errno == ENOENT)) {
                        gf_log ("libglusterfsclient", GF_LOG_DEBUG,
                                "%"PRId64": (op_num=%d) %s => -1 (%s)",
				frame->root->unique, frame->root->op,
				local->fop.lookup.loc->path,
				strerror (op_errno));
                } else {
                        gf_log ("libglusterfsclient", GF_LOG_ERROR,
                                "%"PRId64": (op_num=%d) %s => -1 (%s)",
				frame->root->unique, frame->root->op,
				local->fop.lookup.loc->path,
				strerror (op_errno));
                }

                if (local->fop.lookup.is_revalidate == 1) {
			int32_t ret = 0;
                        inode_unref (local->fop.lookup.loc->inode);
                        local->fop.lookup.loc->inode = inode_new (ctx->itable);
                        local->fop.lookup.is_revalidate = 2;

                        if (local->fop.lookup.size > 0) {
                                xattr_req = dict_new ();
                                ret = dict_set (xattr_req, "glusterfs.content",
                                                data_from_uint64 (local->fop.lookup.size));
                                if (ret == -1) {
                                        op_ret = -1;
                                        /* TODO: set proper error code */
                                        op_errno = errno;
                                        inode = NULL;
                                        buf = NULL;
                                        dict = NULL;
                                        dict_unref (xattr_req);
                                        goto out;
                                }
                        }

                        STACK_WIND (frame, libgf_client_lookup_cbk,
                                    FIRST_CHILD (this),
                                    FIRST_CHILD (this)->fops->lookup,
                                    local->fop.lookup.loc, xattr_req);

			if (xattr_req) {
				dict_unref (xattr_req);
				xattr_req = NULL;
			}

                        return 0;
                }
        }

out:
        local->reply_stub = fop_lookup_cbk_stub (frame, NULL, op_ret, op_errno,
                                                 inode, buf, dict, postparent);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}

int32_t
libgf_client_lookup (libglusterfs_client_ctx_t *ctx,
                     loc_t *loc,
                     struct stat *stbuf,
                     dict_t **dict,
		     dict_t *xattr_req)
{
        call_stub_t  *stub = NULL;
        int32_t op_ret;
        libgf_client_local_t *local = NULL;
        inode_t *inode = NULL;
        
        local = CALLOC (1, sizeof (*local));
        if (!local) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Memory allocation"
                        " failed");
                errno = ENOMEM;
                return -1;
        }

        if (loc->inode) {
                local->fop.lookup.is_revalidate = 1;
                loc->ino = loc->inode->ino;
        }
        else
                loc->inode = inode_new (ctx->itable);

        local->fop.lookup.loc = loc;

        LIBGF_CLIENT_FOP(ctx, stub, lookup, local, loc, xattr_req);

        op_ret = stub->args.lookup_cbk.op_ret;
        errno = stub->args.lookup_cbk.op_errno;

        if (op_ret == -1)
                goto out;

        inode = stub->args.lookup_cbk.inode;
        if (!(libgf_get_inode_ctx (inode)))
                libgf_alloc_inode_ctx (ctx, inode);
        libgf_transform_devnum (ctx, &stub->args.lookup_cbk.buf);
        libgf_update_iattr_cache (inode, LIBGF_UPDATE_ALL,
                                        &stub->args.lookup_cbk.buf);
        if (stbuf)
                *stbuf = stub->args.lookup_cbk.buf;

        if (dict)
                *dict = dict_ref (stub->args.lookup_cbk.dict);
out:
	call_stub_destroy (stub);
        return op_ret;
}

int 
glusterfs_glh_get (glusterfs_handle_t handle, const char *path, void *buf,
                        size_t size, struct stat *stbuf)
{
        int32_t op_ret = -1;
        loc_t loc = {0, };
        libglusterfs_client_ctx_t *ctx = handle;
        dict_t *dict = NULL;
	dict_t *xattr_req = NULL;
	char *name = NULL, *pathname = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s, size %lu", path,
                (long unsigned)size);
        if (size < 0) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Invalid size");
                errno = EINVAL;
                goto out;
        }

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

        loc.path = libgf_resolve_path_light ((char *)path);
        if (!loc.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

	op_ret = libgf_client_path_lookup (&loc, ctx, 0);
	if (op_ret == -1) {
		gf_log ("libglusterfsclient", GF_LOG_ERROR,
			"path lookup failed for (%s)", loc.path);
		goto out;
	}

	pathname = strdup (loc.path);
	name = basename (pathname);

        op_ret = libgf_client_loc_fill (&loc, ctx, 0, loc.parent->ino, name);
        if (op_ret < 0) {
                gf_log ("libglusterfsclient",
                        GF_LOG_ERROR,
                        "libgf_client_loc_fill returned -1, returning EINVAL");
                errno = EINVAL;
                goto out;
        }

        if (size) { 
                xattr_req = dict_new ();
                op_ret = dict_set (xattr_req, "glusterfs.content",
                                   data_from_uint64 (size));
                if (op_ret < 0) {
                        gf_log ("libglusterfsclient",
                                GF_LOG_ERROR,
                                "setting requested content size dictionary failed");
                        goto out;
                }
        }

        op_ret = libgf_client_lookup (ctx, &loc, stbuf, &dict, xattr_req);
        if (!op_ret && stbuf && (stbuf->st_size <= size) && dict && buf) {
                data_t *mem_data = NULL;
                void *mem = NULL;
                
                mem_data = dict_get (dict, "glusterfs.content");
                if (mem_data) {
                        mem = data_to_ptr (mem_data);
                }
                        
                if (mem != NULL) { 
                        memcpy (buf, mem, stbuf->st_size);
                }
        }

out:
	if (xattr_req) {
		dict_unref (xattr_req);
	}
        
	if (dict) {
		dict_unref (dict);
	}

	if (pathname) {
		FREE (pathname);
	}
	libgf_client_loc_wipe (&loc);

        return op_ret;
}

int
glusterfs_get (const char *path, void *buf, size_t size, struct stat *stbuf)
{
        struct vmp_entry        *entry = NULL;
        int                     op_ret = -1;
        char                    *vpath = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, buf, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, stbuf, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s, size %lu", path,
                (long unsigned)size);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        op_ret = glusterfs_glh_get (entry->handle, vpath, buf, size, stbuf);

out:
        if (vpath)
                free (vpath);
        return op_ret;
}

int
libgf_client_lookup_async_cbk (call_frame_t *frame,
                               void *cookie,
                               xlator_t *this,
                               int32_t op_ret,
                               int32_t op_errno,
                               inode_t *inode,
                               struct stat *stbuf,
                               dict_t *dict,
                               struct stat *postparent)
{
        libglusterfs_client_async_local_t *local = frame->local;
        glusterfs_get_cbk_t lookup_cbk = local->fop.lookup_cbk.cbk;
        libglusterfs_client_ctx_t *ctx = frame->root->state;
	glusterfs_iobuf_t *iobuf = NULL;
	dict_t *xattr_req = NULL;
        inode_t *parent = NULL;

        if (op_ret == 0) {
                parent = local->fop.lookup_cbk.loc->parent;
                libgf_transform_devnum (ctx, stbuf);
                inode_link (inode, parent, local->fop.lookup_cbk.loc->name,
                            stbuf);
                
                if (!(libgf_get_inode_ctx (inode)))
                        libgf_alloc_inode_ctx (ctx, inode);
                libgf_update_iattr_cache (inode, LIBGF_UPDATE_ALL, stbuf);
                inode_lookup (inode);
        } else {
                if ((local->fop.lookup_cbk.is_revalidate == 0) 
                    && (op_errno == ENOENT)) {
                        gf_log ("libglusterfsclient", GF_LOG_DEBUG,
                                "%"PRId64": (op_num=%d) %s => -1 (%s)",
				frame->root->unique, frame->root->op,
				local->fop.lookup_cbk.loc->path,
				strerror (op_errno));
                } else {
                        gf_log ("libglusterfsclient", GF_LOG_ERROR,
                                "%"PRId64": (op_num=%d) %s => -1 (%s)",
				frame->root->unique, frame->root->op,
                                local->fop.lookup_cbk.loc->path,
				strerror (op_errno));
                }

                if (local->fop.lookup_cbk.is_revalidate == 1) {
			int32_t ret = 0;
                        inode_unref (local->fop.lookup_cbk.loc->inode);
                        local->fop.lookup_cbk.loc->inode = inode_new (ctx->itable);
                        local->fop.lookup_cbk.is_revalidate = 2;

                        if (local->fop.lookup_cbk.size > 0) {
                                xattr_req = dict_new ();
                                ret = dict_set (xattr_req, "glusterfs.content",
                                                data_from_uint64 (local->fop.lookup_cbk.size));
                                if (ret == -1) {
                                        op_ret = -1;
                                        /* TODO: set proper error code */
                                        op_errno = errno;
                                        inode = NULL;
                                        stbuf = NULL;
                                        dict = NULL;
                                        dict_unref (xattr_req);
                                        goto out;
                                }
                        }


                        STACK_WIND (frame, libgf_client_lookup_async_cbk,
                                    FIRST_CHILD (this),
                                    FIRST_CHILD (this)->fops->lookup,
                                    local->fop.lookup_cbk.loc, xattr_req);
			
			if (xattr_req) {
				dict_unref (xattr_req);
				xattr_req = NULL;
			}

                        return 0;
                }
        }

out:
        if (!op_ret && local->fop.lookup_cbk.size && dict) {
                data_t *mem_data = NULL;
                void *mem = NULL;
		struct iovec *vector = NULL;

                mem_data = dict_get (dict, "glusterfs.content");
                if (mem_data) {
                        mem = data_to_ptr (mem_data);
                }

                if (mem && stbuf->st_size <= local->fop.lookup_cbk.size) {
			iobuf = CALLOC (1, sizeof (*iobuf));
			ERR_ABORT (iobuf);

			vector = CALLOC (1, sizeof (*vector));
			ERR_ABORT (vector);
			vector->iov_base = mem;
			vector->iov_len = stbuf->st_size;  

			iobuf->vector = vector;
			iobuf->count = 1;
			iobuf->dictref = dict_ref (dict);
		}
	}
	
        lookup_cbk (op_ret, op_errno, iobuf, stbuf, local->cbk_data);

	libgf_client_loc_wipe (local->fop.lookup_cbk.loc);
        free (local->fop.lookup_cbk.loc);

        free (local);
        frame->local = NULL;
        STACK_DESTROY (frame->root);

        return 0;
}

/* TODO: implement async dentry lookup */

int
glusterfs_get_async (glusterfs_handle_t handle, 
		     const char *path,
		     size_t size, 
		     glusterfs_get_cbk_t cbk,
		     void *cbk_data)
{
        loc_t *loc = NULL;
        libglusterfs_client_ctx_t *ctx = handle;
        libglusterfs_client_async_local_t *local = NULL;
	int32_t op_ret = 0;
	dict_t *xattr_req = NULL;
	char *name = NULL, *pathname = NULL;

	if (!ctx || !path || path[0] != '/') {
		errno = EINVAL;
		op_ret = -1;
		goto out;
	}

        if (size < 0) {
                errno = EINVAL;
                op_ret = -1;
                goto out;
        }

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

        local = CALLOC (1, sizeof (*local));
        local->fop.lookup_cbk.is_revalidate = 1;

        loc = CALLOC (1, sizeof (*loc));
	loc->path = strdup (path);
	op_ret = libgf_client_path_lookup (loc, ctx, 1);
	if (op_ret == -1) {
		gf_log ("libglusterfsclient",
			GF_LOG_ERROR,
			"path lookup failed for (%s)", path);
		goto out;
	}

	pathname = strdup (path);
	name = basename (pathname);
        op_ret = libgf_client_loc_fill (loc, ctx, 0, loc->parent->ino, name);
	if (op_ret < 0) {
		gf_log ("libglusterfsclient",
			GF_LOG_ERROR,
			"libgf_client_loc_fill returned -1, returning EINVAL");
		errno = EINVAL;
		goto out;
	}

        if (!loc->inode) {
                loc->inode = inode_new (ctx->itable);
                local->fop.lookup_cbk.is_revalidate = 0;
        } 

        local->fop.lookup_cbk.cbk = cbk;
        local->fop.lookup_cbk.size = size;
        local->fop.lookup_cbk.loc = loc;
        local->cbk_data = cbk_data;

        if (size > 0) {
                xattr_req = dict_new ();
                op_ret = dict_set (xattr_req, "glusterfs.content",
                                   data_from_uint64 (size));
                if (op_ret < 0) {
                        dict_unref (xattr_req);
                        xattr_req = NULL;
                        goto out;
                }
        }

        LIBGF_CLIENT_FOP_ASYNC (ctx,
                                local,
                                libgf_client_lookup_async_cbk,
                                lookup,
                                loc,
                                xattr_req);
	if (xattr_req) {
		dict_unref (xattr_req);
		xattr_req = NULL;
	}

out:
	if (pathname) {
		FREE (pathname);
	}
 
        return op_ret;
}

int32_t
libgf_client_getxattr_cbk (call_frame_t *frame,
                           void *cookie,
                           xlator_t *this,
                           int32_t op_ret,
                           int32_t op_errno,
                           dict_t *dict)
{

        libgf_client_local_t *local = frame->local;

        local->reply_stub = fop_getxattr_cbk_stub (frame, NULL, op_ret,
                                                   op_errno, dict);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}

size_t 
libgf_client_getxattr (libglusterfs_client_ctx_t *ctx, 
                       loc_t *loc,
                       const char *name,
                       void *value,
                       size_t size)
{
        call_stub_t  *stub = NULL;
        int32_t op_ret = 0;
        libgf_client_local_t *local = NULL;

        LIBGF_CLIENT_FOP (ctx, stub, getxattr, local, loc, name);

        op_ret = stub->args.getxattr_cbk.op_ret;
        errno = stub->args.getxattr_cbk.op_errno;

        if (op_ret >= 0) {
                /*
                  gf_log ("LIBGF_CLIENT", GF_LOG_DEBUG,
                  "%"PRId64": %s => %d", frame->root->unique,
                  state->fuse_loc.loc.path, op_ret);
                */

                data_t *value_data = dict_get (stub->args.getxattr_cbk.dict,
                                               (char *)name);
    
                if (value_data) {
                        int32_t copy_len = 0;

                        /* Don't return the value for '\0' */
                        op_ret = value_data->len; 
                        copy_len = size < value_data->len ? 
                                size : value_data->len;
                        memcpy (value, value_data->data, copy_len);
                } else {
                        errno = ENODATA;
                        op_ret = -1;
                }
        }
	
	call_stub_destroy (stub);
        return op_ret;
}

#define LIBGF_DO_GETXATTR       1
#define LIBGF_DO_LGETXATTR      2

ssize_t
__glusterfs_glh_getxattr (glusterfs_handle_t handle, const char *path,
                          const char *name, void *value, size_t size,
                          int whichop)
{
        int32_t op_ret = -1;
        loc_t loc = {0, };
	dict_t *dict = NULL;
	libglusterfs_client_ctx_t *ctx = handle;
	char *file = NULL;
	dict_t *xattr_req = NULL;
        char *pathres = NULL, *tmp = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, path, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, name, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s, name %s, size %lu,"
                " op %d", path, name, (long unsigned)size, whichop);
        if (name[0] == '\0') {
		errno = EINVAL;
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Invalid argument: Name"
                        " not NULL terminated");
		goto out;
	}

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

        if (size < 0) {
                errno = EINVAL;
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Invalid argument: size is"
                        " less than zero");
                goto out;
        }

        pathres = libgf_resolve_path_light ((char *)path);
        if (!pathres) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

        loc.path = strdup (pathres);
	op_ret = libgf_client_path_lookup (&loc, ctx, 1);
	if (op_ret == -1) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
			"path lookup failed for (%s)", loc.path);
		goto out;
	}

	tmp = strdup (pathres);
	file = basename (tmp);
        op_ret = libgf_client_loc_fill (&loc, ctx, 0, loc.parent->ino, file);
	if (op_ret == -1) {
		gf_log ("libglusterfsclient",
			GF_LOG_ERROR,
			"libgf_client_loc_fill returned -1, returning EINVAL");
		errno = EINVAL;
		goto out;
	}

	xattr_req = dict_new ();
	op_ret = dict_set (xattr_req, (char *)name,
			   data_from_uint64 (size));
	if (op_ret == -1) {
		/* TODO: set proper error code */
		goto out;
	}

        if (whichop == LIBGF_DO_LGETXATTR)
                goto do_getx;

        if (!S_ISLNK (loc.inode->st_mode))
                goto do_getx;

        libgf_client_loc_wipe (&loc);
        op_ret = libgf_realpath_loc_fill (ctx, (char *)pathres, &loc);
        if (op_ret == -1) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "realpath failed");
                goto out;
        }

do_getx:
	op_ret = libgf_client_lookup (ctx, &loc, NULL, &dict, xattr_req);
	if (op_ret == 0) {
		data_t *value_data = dict_get (dict, (char *)name);
			
		if (value_data) {
			int32_t copy_len = 0;

                        /* Don't return the value for '\0' */
			op_ret = value_data->len;
				
			copy_len = size < value_data->len ? 
                                size : value_data->len;
			memcpy (value, value_data->data, copy_len);
		} else {
			errno = ENODATA;
			op_ret = -1;
		}
	}

out:
	if (tmp) {
		FREE (tmp);
	}

	if (xattr_req) {
		dict_unref (xattr_req);
	}

	if (dict) {
		dict_unref (dict);
	}

        if (pathres)
                FREE (pathres);

        libgf_client_loc_wipe (&loc);

        return op_ret;
}

ssize_t
glusterfs_glh_getxattr (glusterfs_handle_t handle, const char *path,
                        const char *name, void *value, size_t size)
{
        return __glusterfs_glh_getxattr (handle, path, name, value, size,
                                         LIBGF_DO_GETXATTR);
}

ssize_t
glusterfs_glh_lgetxattr (glusterfs_handle_t handle, const char *path,
                         const char *name, void *value, size_t size)
{
        return __glusterfs_glh_getxattr (handle, path, name, value, size,
                                         LIBGF_DO_LGETXATTR);
}

ssize_t
glusterfs_getxattr (const char *path, const char *name, void *value,
                        size_t size)
{
        int                     op_ret = -1;
        struct vmp_entry        *entry = NULL;
        char                    *vpath = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, name, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, value, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s, name %s, size %lu",
                path, name, (long unsigned)size);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        op_ret = __glusterfs_glh_getxattr (entry->handle, vpath, name, value,
                                           size, LIBGF_DO_GETXATTR);

out:
        if (vpath)
                free (vpath);
        return op_ret;
}

ssize_t
glusterfs_lgetxattr (const char *path, const char *name, void *value,
                     size_t size)
{
        int                     op_ret = -1;
        struct vmp_entry        *entry = NULL;
        char                    *vpath = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, name, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, value, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s, name %s, size %lu",
                path, name, (long unsigned)size);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        op_ret = __glusterfs_glh_getxattr (entry->handle, vpath, name, value,
                                           size, LIBGF_DO_LGETXATTR);

out:
        if (vpath)
                free (vpath);
        return op_ret;
}

static int32_t
libgf_client_open_cbk (call_frame_t *frame,
                       void *cookie,
                       xlator_t *this,
                       int32_t op_ret,
                       int32_t op_errno,
                       fd_t *fd)
{
        libgf_client_local_t *local = frame->local;

        local->reply_stub = fop_open_cbk_stub (frame, NULL, op_ret, op_errno,
                                               fd);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}


int 
libgf_client_open (libglusterfs_client_ctx_t *ctx, 
                   loc_t *loc, 
                   fd_t *fd, 
                   int flags)
{
        call_stub_t *stub = NULL;
        int32_t op_ret = 0;
        libgf_client_local_t *local = NULL;

        LIBGF_CLIENT_FOP (ctx, stub, open, local, loc, flags, fd, 0);

        op_ret = stub->args.open_cbk.op_ret;
        errno = stub->args.open_cbk.op_errno;

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "open: path %s, status: %d, errno"
                " %d", loc->path, op_ret, errno);
        if (op_ret != -1)
                fd_bind (fd);
	call_stub_destroy (stub);
        return op_ret;
}

static int32_t
libgf_client_create_cbk (call_frame_t *frame,
                         void *cookie,
                         xlator_t *this,
                         int32_t op_ret,
                         int32_t op_errno,
                         fd_t *fd,
                         inode_t *inode,
                         struct stat *buf,
                         struct stat *preparent,
                         struct stat *postparent)
{
        libgf_client_local_t *local = frame->local;

        local->reply_stub = fop_create_cbk_stub (frame, NULL, op_ret, op_errno,
                                                 fd, inode, buf, preparent,
                                                 postparent);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}

int 
libgf_client_creat (libglusterfs_client_ctx_t *ctx,
                    loc_t *loc,
                    fd_t *fd,
                    int flags,
                    mode_t mode)
{
        call_stub_t *stub = NULL;
        int32_t op_ret = 0;
        libgf_client_local_t *local = NULL;
        inode_t *libgf_inode = NULL;

        LIBGF_CLIENT_FOP (ctx, stub, create, local, loc, flags, mode, fd);
  
        op_ret = stub->args.create_cbk.op_ret;
        errno = stub->args.create_cbk.op_errno;
        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "Create: path %s, status: %d,"
                " errno: %d", loc->path, op_ret, errno);
        if (op_ret == -1)
                goto out;

	libgf_inode = stub->args.create_cbk.inode;
        libgf_transform_devnum (ctx, &stub->args.create_cbk.buf);
        inode_link (libgf_inode, loc->parent, loc->name,
                        &stub->args.create_cbk.buf);

        inode_lookup (libgf_inode);

        libgf_alloc_inode_ctx (ctx, libgf_inode);
        libgf_update_iattr_cache (libgf_inode, LIBGF_UPDATE_ALL,
                                        &stub->args.create_cbk.buf);

out:
	call_stub_destroy (stub);
        return op_ret;
}

int32_t
libgf_client_opendir_cbk (call_frame_t *frame,
                          void *cookie,
                          xlator_t *this,
                          int32_t op_ret,
                          int32_t op_errno,
                          fd_t *fd)
{
        libgf_client_local_t *local = frame->local;

        local->reply_stub = fop_opendir_cbk_stub (frame, NULL, op_ret, op_errno,
                                                  fd);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}

int 
libgf_client_opendir (libglusterfs_client_ctx_t *ctx,
                      loc_t *loc,
                      fd_t *fd)
{
        call_stub_t *stub = NULL;
        int32_t op_ret = -1;
        libgf_client_local_t *local = NULL;

        if (((fd->flags & O_ACCMODE) == O_WRONLY)
                || ((fd->flags & O_ACCMODE) == O_RDWR)) {
                errno = EISDIR;
                goto out;
        }
        LIBGF_CLIENT_FOP (ctx, stub, opendir, local, loc, fd);

        op_ret = stub->args.opendir_cbk.op_ret;
        errno = stub->args.opendir_cbk.op_errno;
        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "opendir: path %s, status %d,"
                " errno %d", loc->path, op_ret, errno);
        if (op_ret != -1)
                fd_bind (fd);

	call_stub_destroy (stub);
out:
        return op_ret;
}

glusterfs_file_t 
glusterfs_glh_open (glusterfs_handle_t handle, const char *path, int flags,...)
{
        loc_t loc = {0, };
        long op_ret = -1;
        fd_t *fd = NULL;
	int32_t ret = -1;
	libglusterfs_client_ctx_t *ctx = handle;
	char *name = NULL, *pathname = NULL;
        libglusterfs_client_inode_ctx_t *inode_ctx = NULL;
        mode_t mode = 0;
        va_list ap;
        char *pathres = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, path, out);

        pathres = libgf_resolve_path_light ((char *)path);
        if (!pathres) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

	loc.path = strdup (pathres);
	op_ret = libgf_client_path_lookup (&loc, ctx, 1);

        if ((op_ret == -1) && ((flags & O_CREAT) != O_CREAT)) {
		gf_log ("libglusterfsclient", GF_LOG_ERROR,
			"path lookup failed for (%s)", loc.path);
		goto out;
	}

        if (!op_ret && ((flags & O_CREAT) == O_CREAT) 
            && ((flags & O_EXCL) == O_EXCL)) {
                errno = EEXIST;
                op_ret = -1;
                goto out;
        }

        if ((op_ret == -1) && ((flags & O_CREAT) == O_CREAT)) {
                libgf_client_loc_wipe (&loc);
                loc.path = strdup (pathres);

                op_ret = libgf_client_path_lookup (&loc, ctx, 0);
                if (op_ret == -1) {
                        gf_log ("libglusterfsclient", GF_LOG_ERROR,
                                "path lookup failed for parent while trying to"
                                " create (%s)", pathres);
                        goto out;
                }

                loc.inode = inode_new (ctx->itable);
        }

	pathname = strdup (pathres);
	name = basename (pathname);

        ret = libgf_client_loc_fill (&loc, ctx, 0, loc.parent->ino, name);
	if (ret == -1) {
		gf_log ("libglusterfsclient",
			GF_LOG_ERROR,
			"libgf_client_loc_fill returned -1, returning EINVAL");
		errno = EINVAL;
		goto out;
	}

        fd = fd_create (loc.inode, ctx->pid);
        fd->flags = flags;

        if ((flags & O_CREAT) == O_CREAT) {
                /* If we have the st_mode for the basename, check if
                 * it is a directory here itself, rather than sending
                 * a network message through libgf_client_creat, and
                 * then receiving a EISDIR.
                 */
                if (S_ISDIR (loc.inode->st_mode)) {
                        errno = EISDIR;
                        op_ret = -1;
                        goto op_over;
                }
                va_start (ap, flags);
                mode = va_arg (ap, mode_t);
                va_end (ap);
                op_ret = libgf_client_creat (ctx, &loc, fd, flags, mode);
        } else {
                if (S_ISDIR (loc.inode->st_mode))
                        op_ret = libgf_client_opendir (ctx, &loc, fd);
                else
                        op_ret = libgf_client_open (ctx, &loc, fd, flags);
        }

op_over:
        if (op_ret == -1) {
                fd_unref (fd);
                fd = NULL;
                goto out;
        }

        if (!libgf_get_fd_ctx (fd)) {
                if (!libgf_alloc_fd_ctx (ctx, fd)) {
                        gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Failed to"
                                " allocate fd context");
                        errno = EINVAL;
                        op_ret = -1;
                        goto out;
                }
        }

        if ((flags & O_TRUNC) && (((flags & O_ACCMODE) == O_RDWR)
                        || ((flags & O_ACCMODE) == O_WRONLY))) {
                inode_ctx = libgf_get_inode_ctx (fd->inode);
                if (S_ISREG (inode_ctx->stbuf.st_mode)) {
                                inode_ctx->stbuf.st_size = 0;
                                inode_ctx->stbuf.st_blocks = 0;
                }
        }

out:
        libgf_client_loc_wipe (&loc);

	if (pathname) {
		FREE (pathname);
	}

        if (pathres)
                FREE (pathres);

        return fd;
}

glusterfs_file_t
glusterfs_open (const char *path, int flags, ...)
{
        struct vmp_entry        *entry = NULL;
        char                    *vpath = NULL;
        glusterfs_file_t        fh = NULL;
        mode_t                  mode = 0;
        va_list                 ap;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        if (flags & O_CREAT) {
                va_start (ap, flags);
                mode = va_arg (ap, mode_t);
                va_end (ap);
                fh = glusterfs_glh_open (entry->handle, vpath, flags, mode);
        } else
                fh = glusterfs_glh_open (entry->handle, vpath, flags);
out:
        if (vpath)
                free (vpath);
        return fh;
}

glusterfs_file_t 
glusterfs_glh_creat (glusterfs_handle_t handle, const char *path, mode_t mode)
{
        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
	return glusterfs_glh_open (handle, path,
			       (O_CREAT | O_WRONLY | O_TRUNC), mode);
}

glusterfs_file_t
glusterfs_creat (const char *path, mode_t mode)
{
        struct vmp_entry        *entry = NULL;
        char                    *vpath = NULL;
        glusterfs_file_t        fh = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        fh = glusterfs_glh_creat (entry->handle, vpath, mode);

out:
        if (vpath)
                free (vpath);
        return fh;
}

int32_t
libgf_client_flush_cbk (call_frame_t *frame,
                        void *cookie,
                        xlator_t *this,
                        int32_t op_ret,
                        int32_t op_errno)
{
        libgf_client_local_t *local = frame->local;
        
        local->reply_stub = fop_flush_cbk_stub (frame, NULL, op_ret, op_errno);
        
        LIBGF_REPLY_NOTIFY (local);
        return 0;
}


int 
libgf_client_flush (libglusterfs_client_ctx_t *ctx, fd_t *fd)
{
        call_stub_t *stub;
        int32_t op_ret;
        libgf_client_local_t *local = NULL;

        LIBGF_CLIENT_FOP (ctx, stub, flush, local, fd);
        
        op_ret = stub->args.flush_cbk.op_ret;
        errno = stub->args.flush_cbk.op_errno;
        
	call_stub_destroy (stub);        
        return op_ret;
}


int 
glusterfs_close (glusterfs_file_t fd)
{
        int32_t op_ret = -1;
        libglusterfs_client_ctx_t *ctx = NULL;
        libglusterfs_client_fd_ctx_t *fd_ctx = NULL;

        if (!fd) {
                errno = EINVAL;
		goto out;
        }

        fd_ctx = libgf_get_fd_ctx (fd);
        if (!fd_ctx) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "No fd context present");
                errno = EBADF;
                goto out;
        }
        ctx = fd_ctx->ctx;

        op_ret = libgf_client_flush (ctx, (fd_t *)fd);

        fd_unref ((fd_t *)fd);

out:
        return op_ret;
}

int32_t
libgf_client_setxattr_cbk (call_frame_t *frame,
                           void *cookie,
                           xlator_t *this,
                           int32_t op_ret,
                           int32_t op_errno)
{
        libgf_client_local_t *local = frame->local;

        local->reply_stub = fop_setxattr_cbk_stub (frame, NULL, op_ret,
                                                   op_errno);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}

int
libgf_client_setxattr (libglusterfs_client_ctx_t *ctx, 
                       loc_t *loc,
                       const char *name,
                       const void *value,
                       size_t size,
                       int flags)
{
        call_stub_t  *stub = NULL;
        int32_t op_ret = 0;
        dict_t *dict;
        libgf_client_local_t *local = NULL;

        dict = get_new_dict ();

        dict_set (dict, (char *)name,
                  bin_to_data ((void *)value, size));
        dict_ref (dict);


        LIBGF_CLIENT_FOP (ctx, stub, setxattr, local, loc, dict, flags);

        op_ret = stub->args.setxattr_cbk.op_ret;
        errno = stub->args.setxattr_cbk.op_errno;

        gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "path %s, name %s, status %d,"
                "errno %d", loc->path, name, op_ret, errno);
        dict_unref (dict);
	call_stub_destroy (stub);
        return op_ret;
}


#define LIBGF_DO_SETXATTR       1
#define LIBGF_DO_LSETXATTR      2

int 
__glusterfs_glh_setxattr (glusterfs_handle_t handle, const char *path,
                          const char *name, const void *value,
                          size_t size, int flags, int whichop)
{
        int32_t op_ret = -1;
        loc_t loc = {0, };
	libglusterfs_client_ctx_t *ctx = handle;
        char *tmppath = NULL;
        loc_t *realloc = NULL;
        char *pathres = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "path %s, name %s, op %d", path
                ,name, whichop);
        if (size <= 0) {
                errno = EINVAL;
                goto out;
        }

        pathres = libgf_resolve_path_light ((char *)path);
        if (!pathres) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

        loc.path = strdup (pathres);
	op_ret = libgf_client_path_lookup (&loc, ctx, 1);
	if (op_ret == -1) {
		gf_log ("libglusterfsclient", GF_LOG_ERROR,
			"path lookup failed for (%s)", pathres);
		goto out;
	}

        tmppath = strdup (pathres);

        op_ret = libgf_client_loc_fill (&loc, ctx, 0, loc.parent->ino,
                                        basename (tmppath));
        FREE (tmppath);
	if (op_ret == -1) {
		gf_log ("libglusterfsclient",
			GF_LOG_ERROR,
			"libgf_client_loc_fill returned -1, returning EINVAL");
		errno = EINVAL;
		goto out;
	}

        realloc = &loc;
        if (whichop == LIBGF_DO_LSETXATTR)
                goto do_setx;

        if (!S_ISLNK (loc.inode->st_mode))
                goto do_setx;

        libgf_client_loc_wipe (&loc);
        realloc = &loc;
        libgf_realpath_loc_fill (ctx, (char *)pathres, realloc);

do_setx:
        if (!op_ret)
                op_ret = libgf_client_setxattr (ctx, realloc, name, value,
                                                size, flags);

out:
        if (pathres)
                FREE (pathres);

        libgf_client_loc_wipe (realloc);
        return op_ret;
}

int
glusterfs_glh_setxattr (glusterfs_handle_t handle, const char *path,
                        const char *name, const void *value, size_t size,
                        int flags)
{
        return __glusterfs_glh_setxattr (handle, path, name, value, size, flags
                                         , LIBGF_DO_SETXATTR);
}

int
glusterfs_glh_lsetxattr (glusterfs_handle_t handle, const char *path,
                         const char *name, const void *value, size_t size,
                         int flags)
{
        return __glusterfs_glh_setxattr (handle, path, name, value, size, flags
                                         , LIBGF_DO_LSETXATTR);
}

int
glusterfs_setxattr (const char *path, const char *name, const void *value,
                        size_t size, int flags)
{
        struct vmp_entry        *entry = NULL;
        int                     op_ret = -1;
        char                    *vpath = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, name, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, value, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "path %s, name %s", path, name);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        op_ret = __glusterfs_glh_setxattr (entry->handle, vpath, name, value,
                                           size, flags, LIBGF_DO_SETXATTR);
out:
        if (vpath)
                free (vpath);
        return op_ret;
}

int
glusterfs_lsetxattr (glusterfs_handle_t handle, const char *path,
                     const char *name, const void *value, size_t size,
                     int flags)
{
        struct vmp_entry        *entry = NULL;
        int                     op_ret = -1;
        char                    *vpath = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, name, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, value, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "path %s, name %s", path, name);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        op_ret = __glusterfs_glh_setxattr (entry->handle, vpath, name, value,
                                           size, flags, LIBGF_DO_LSETXATTR);
out:
        if (vpath)
                free (vpath);
        return op_ret;
}

int32_t
libgf_client_fsetxattr_cbk (call_frame_t *frame,
                            void *cookie,
                            xlator_t *this,
                            int32_t op_ret,
                            int32_t op_errno)
{
        libgf_client_local_t *local = frame->local;

        local->reply_stub = fop_fsetxattr_cbk_stub (frame, NULL, op_ret,
                                                    op_errno);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}

int
libgf_client_fsetxattr (libglusterfs_client_ctx_t *ctx, 
                        fd_t *fd,
                        const char *name,
                        const void *value,
                        size_t size,
                        int flags)
{
        call_stub_t  *stub = NULL;
        int32_t op_ret = 0;
        dict_t *dict;
        libgf_client_local_t *local = NULL;

        dict = get_new_dict ();

        dict_set (dict, (char *)name,
                  bin_to_data ((void *)value, size));
        dict_ref (dict);

        LIBGF_CLIENT_FOP (ctx, stub, fsetxattr, local, fd, dict, flags);

        op_ret = stub->args.fsetxattr_cbk.op_ret;
        errno = stub->args.fsetxattr_cbk.op_errno;

        gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "name %s, status %d, errno %d",
                name, op_ret, errno);
        dict_unref (dict);
	call_stub_destroy (stub);

        return op_ret;
}

int 
glusterfs_fsetxattr (glusterfs_file_t fd, 
                     const char *name,
                     const void *value, 
                     size_t size, 
                     int flags)
{
	int32_t op_ret = 0;
        fd_t *__fd = fd;
        libglusterfs_client_fd_ctx_t *fd_ctx = NULL;
        libglusterfs_client_ctx_t *ctx = NULL;
        
        if (!fd) {
                errno = EINVAL;
                op_ret = -1;
                gf_log("libglusterfsclient",
                       GF_LOG_ERROR,
                       "invalid fd");
                goto out;
        }

        if (size <= 0) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Invalid argument: size is"
                        " less than or equal to zero");
                errno = EINVAL;
                op_ret = -1;
                goto out;
        }

        fd_ctx = libgf_get_fd_ctx (fd);
        if (!fd_ctx) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "No fd context present");
                errno = EBADF;
		op_ret = -1;
		goto out;
        }

        ctx = fd_ctx->ctx;
        op_ret = libgf_client_fsetxattr (ctx, __fd, name, value, size,
                                         flags);
        
out:
	return op_ret;
}

int32_t
libgf_client_fgetxattr_cbk (call_frame_t *frame,
                            void *cookie,
                            xlator_t *this,
                            int32_t op_ret,
                            int32_t op_errno,
                            dict_t *dict)
{

        libgf_client_local_t *local = frame->local;

        local->reply_stub = fop_fgetxattr_cbk_stub (frame, NULL, op_ret,
                                                    op_errno, dict);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}

size_t 
libgf_client_fgetxattr (libglusterfs_client_ctx_t *ctx, 
                        fd_t *fd,
                        const char *name,
                        void *value,
                        size_t size)
{
        call_stub_t  *stub = NULL;
        int32_t op_ret = 0;
        libgf_client_local_t *local = NULL;

        LIBGF_CLIENT_FOP (ctx, stub, fgetxattr, local, fd, name);

        op_ret = stub->args.fgetxattr_cbk.op_ret;
        errno = stub->args.fgetxattr_cbk.op_errno;

        if (op_ret >= 0) {
                /*
                  gf_log ("LIBGF_CLIENT", GF_LOG_DEBUG,
                  "%"PRId64": %s => %d", frame->root->unique,
                  state->fuse_loc.loc.path, op_ret);
                */

                data_t *value_data = dict_get (stub->args.fgetxattr_cbk.dict,
                                               (char *)name);
    
                if (value_data) {
                        int32_t copy_len = 0;

                        /* Don't return the value for '\0' */
                        op_ret = value_data->len; 
                        copy_len = size < value_data->len ? 
                                size : value_data->len;
                        memcpy (value, value_data->data, copy_len);
                } else {
                        errno = ENODATA;
                        op_ret = -1;
                }
        }
	
        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "name %s, status %d, errno %d",
                name, op_ret, errno);
	call_stub_destroy (stub);
        return op_ret;
}

ssize_t 
glusterfs_fgetxattr (glusterfs_file_t fd, 
                     const char *name,
                     void *value, 
                     size_t size)
{
	int32_t op_ret = 0;
        libglusterfs_client_ctx_t *ctx;
        fd_t *__fd = (fd_t *)fd;
        libglusterfs_client_fd_ctx_t *fd_ctx = NULL;

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "name %s", name);
        if (size < 0) {
                errno = EINVAL;
                op_ret = -1;
                goto out;
        }

        if (size == 0)
                goto out;

        fd_ctx = libgf_get_fd_ctx (fd);
        if (!fd_ctx) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "No fd context present");
                errno = EBADF;
		op_ret = -1;
		goto out;
        }

        ctx = fd_ctx->ctx;
        op_ret = libgf_client_fgetxattr (ctx, __fd, name, value, size);
out:
	return op_ret;
}

ssize_t 
glusterfs_listxattr (glusterfs_handle_t handle,
                     const char *path, 
                     char *list,
                     size_t size)
{
        return ENOSYS;
}

ssize_t 
glusterfs_llistxattr (glusterfs_handle_t handle,
                      const char *path, 
                      char *list,
                      size_t size)
{
        return ENOSYS;
}

ssize_t 
glusterfs_flistxattr (glusterfs_file_t fd, 
                      char *list,
                      size_t size)
{
        return ENOSYS;
}

int 
glusterfs_removexattr (glusterfs_handle_t handle, 
                       const char *path, 
                       const char *name)
{
        return ENOSYS;
}

int 
glusterfs_lremovexattr (glusterfs_handle_t handle, 
                        const char *path, 
                        const char *name)
{
        return ENOSYS;
}

int 
glusterfs_fremovexattr (glusterfs_file_t fd, 
                        const char *name)
{
        return ENOSYS;
}

int32_t
libgf_client_readv_cbk (call_frame_t *frame,
                        void *cookie,
                        xlator_t *this,
                        int32_t op_ret,
                        int32_t op_errno,
                        struct iovec *vector,
                        int32_t count,
                        struct stat *stbuf,
                        struct iobref *iobref)
{
        libgf_client_local_t *local = frame->local;

        local->reply_stub = fop_readv_cbk_stub (frame, NULL, op_ret, op_errno,
                                                vector, count, stbuf, iobref);
        LIBGF_REPLY_NOTIFY (local);
        return 0;
}

int 
libgf_client_read (libglusterfs_client_ctx_t *ctx, 
                   fd_t *fd,
                   void *buf, 
                   size_t size, 
                   off_t offset)
{
        call_stub_t *stub;
        struct iovec *vector;
        int32_t op_ret = -1;
        int count = 0;
        libgf_client_local_t *local = NULL;
        struct stat     *stbuf = NULL;

        local = CALLOC (1, sizeof (*local));
        ERR_ABORT (local);
        local->fd = fd;
        LIBGF_CLIENT_FOP (ctx, stub, readv, local, fd, size, offset);

        op_ret = stub->args.readv_cbk.op_ret;
        errno = stub->args.readv_cbk.op_errno;
        count = stub->args.readv_cbk.count;
        vector = stub->args.readv_cbk.vector;
        if (op_ret > 0) {
                int i = 0;
                op_ret = 0;
                while (size && (i < count)) {
                        int len = (size < vector[i].iov_len) ? 
                                size : vector[i].iov_len;
                        memcpy (buf, vector[i++].iov_base, len);
                        buf += len;
                        size -= len;
                        op_ret += len;
                }
                stbuf = &stub->args.readv_cbk.stbuf;
                libgf_transform_devnum (ctx, stbuf);
                libgf_invalidate_iattr_cache (fd->inode, LIBGF_INVALIDATE_STAT);
        }

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "size %lu, offset %"PRIu64,
                (long unsigned)size, offset);
	call_stub_destroy (stub);
        return op_ret;
}

ssize_t 
glusterfs_read (glusterfs_file_t fd, 
                void *buf, 
                size_t nbytes)
{
        int32_t op_ret = -1;
        off_t offset = 0;
        libglusterfs_client_ctx_t *ctx = NULL;
        libglusterfs_client_fd_ctx_t *fd_ctx = NULL;

        if (nbytes < 0) {
                errno = EINVAL;
                goto out;
        }

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

        if (fd == 0) {
                errno = EINVAL;
		goto out;
        }

        fd_ctx = libgf_get_fd_ctx (fd);
        if (!fd_ctx) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "No fd context present");
                errno = EBADF;
		goto out;
        }

        pthread_mutex_lock (&fd_ctx->lock);
        {
                ctx = fd_ctx->ctx;
                offset = fd_ctx->offset;
        }
        pthread_mutex_unlock (&fd_ctx->lock);

        op_ret = libgf_client_read (ctx, (fd_t *)fd, buf, nbytes, offset);

        if (op_ret > 0) {
                offset += op_ret;
                pthread_mutex_lock (&fd_ctx->lock);
                {
                        fd_ctx->offset = offset;
                }
                pthread_mutex_unlock (&fd_ctx->lock);
        }

out:
        return op_ret;
}


ssize_t
libgf_client_readv (libglusterfs_client_ctx_t *ctx, 
                    fd_t *fd,
                    const struct iovec *dst_vector,
                    int dst_count,
                    off_t offset)
{
        call_stub_t *stub = NULL;
        struct iovec *src_vector;
        int src_count = 0;
        int32_t op_ret = -1;
        libgf_client_local_t *local = NULL;
        size_t size = 0;
        int32_t i = 0;
        struct stat     *stbuf = NULL;

        for (i = 0; i < dst_count; i++)
        {
                size += dst_vector[i].iov_len;
        }

        local = CALLOC (1, sizeof (*local));
        ERR_ABORT (local);
        local->fd = fd;
        LIBGF_CLIENT_FOP (ctx, stub, readv, local, fd, size, offset);

        op_ret = stub->args.readv_cbk.op_ret;
        errno = stub->args.readv_cbk.op_errno;
        src_count = stub->args.readv_cbk.count;
        src_vector = stub->args.readv_cbk.vector;
        if (op_ret > 0) {
                int src = 0, dst = 0;
                off_t src_offset = 0, dst_offset = 0;
    
                while ((size != 0) && (dst < dst_count) && (src < src_count)) {
                        int len = 0, src_len, dst_len;
   
                        src_len = src_vector[src].iov_len - src_offset;
                        dst_len = dst_vector[dst].iov_len - dst_offset;

                        len = (src_len < dst_len) ? src_len : dst_len;
                        if (len > size) {
                                len = size;
                        }

                        memcpy (dst_vector[dst].iov_base + dst_offset, 
				src_vector[src].iov_base + src_offset, len);

                        size -= len;
                        src_offset += len;
                        dst_offset += len;

                        if (src_offset == src_vector[src].iov_len) {
                                src_offset = 0;
                                src++;
                        }

                        if (dst_offset == dst_vector[dst].iov_len) {
                                dst_offset = 0;
                                dst++;
                        }
                }

                stbuf = &stub->args.readv_cbk.stbuf;
                libgf_transform_devnum (ctx, stbuf);
                libgf_invalidate_iattr_cache (fd->inode, LIBGF_UPDATE_STAT);
        }
 
	call_stub_destroy (stub);
        return op_ret;
}


ssize_t 
glusterfs_readv (glusterfs_file_t fd, const struct iovec *vec, int count)
{
        int32_t op_ret = -1;
        off_t offset = 0;
        libglusterfs_client_ctx_t *ctx = NULL;
        libglusterfs_client_fd_ctx_t *fd_ctx = NULL;

        if (count < 0) {
                errno = EINVAL;
                goto out;
        }

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

        if (!fd) {
                errno = EINVAL;
		goto out;
        }

        fd_ctx = libgf_get_fd_ctx (fd);
        if (!fd_ctx) {
                errno = EBADF;
		goto out;
        }

        pthread_mutex_lock (&fd_ctx->lock);
        {
                ctx = fd_ctx->ctx;
                offset = fd_ctx->offset;
        }
        pthread_mutex_unlock (&fd_ctx->lock);

        op_ret = libgf_client_readv (ctx, (fd_t *)fd, vec, count, offset);

        if (op_ret > 0) {
                offset += op_ret;
                pthread_mutex_lock (&fd_ctx->lock);
                {
                        fd_ctx->offset = offset;
                }
                pthread_mutex_unlock (&fd_ctx->lock);
        }

out:
        return op_ret;
}


ssize_t 
glusterfs_pread (glusterfs_file_t fd, 
                 void *buf, 
                 size_t count, 
                 off_t offset)
{
        int32_t op_ret = -1;
        libglusterfs_client_ctx_t *ctx = NULL;
        libglusterfs_client_fd_ctx_t *fd_ctx = NULL;

        if (count < 0) {
                errno = EINVAL;
                goto out;
        }

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

        if (!fd) {
                errno = EINVAL;
		goto out;
        }

        fd_ctx = libgf_get_fd_ctx (fd);
        if (!fd_ctx) {
                errno = EBADF;
		goto out;
        }

        ctx = fd_ctx->ctx;

        op_ret = libgf_client_read (ctx, (fd_t *)fd, buf, count, offset);

out:
        return op_ret;
}


int
libgf_client_writev_cbk (call_frame_t *frame,
                         void *cookie,
                         xlator_t *this,
                         int32_t op_ret,
                         int32_t op_errno,
                         struct stat *prebuf,
                         struct stat *postbuf)
{
        libgf_client_local_t *local = frame->local;

        local->reply_stub = fop_writev_cbk_stub (frame, NULL, op_ret, op_errno,
                                                 prebuf, postbuf);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}


int
libgf_client_iobuf_write (libglusterfs_client_ctx_t *ctx, fd_t *fd, char *addr,
                          size_t size, off_t offset)
{
        struct iobref        *ioref = NULL;
        struct iobuf         *iob = NULL;
        int                   op_ret = -1;
        struct iovec          iov = {0, };
        call_stub_t          *stub = NULL;
        libgf_client_local_t *local = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, fd, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, addr, out);

        ioref = iobref_new ();
        if (!ioref) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Out of memory");
                goto out;
        }

        iob = iobuf_get (ctx->gf_ctx.iobuf_pool);
        if (!iob) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Out of memory");
                goto out;
        }

        memcpy (iob->ptr, addr, size);
        iobref_add (ioref, iob);

        iov.iov_base = iob->ptr;
        iov.iov_len = size;

        LIBGF_CLIENT_FOP (ctx, stub, writev, local, fd, &iov,
                          1, offset, ioref);

        op_ret = stub->args.writev_cbk.op_ret;
        errno = stub->args.writev_cbk.op_errno;

        /* We need to invalidate because it is possible that write-behind
         * is a translator below us and returns a stat filled with zeroes.
         */
        libgf_invalidate_iattr_cache (fd->inode, LIBGF_INVALIDATE_STAT);

out:
        if (iob) {
                iobuf_unref (iob);
        }

        if (ioref) {
                iobref_unref (ioref);
        }

        call_stub_destroy (stub);
        return op_ret;
}

int
libgf_client_writev (libglusterfs_client_ctx_t *ctx, 
                     fd_t *fd, 
                     struct iovec *vector, 
                     int count, 
                     off_t offset)
{
        int                     op_ret = 0;
        int                     written = 0;
        int                     writesize = 0;
        int                     size = 0;
        char                   *base = NULL;
        int                     i = 0;

        for (i = 0; i < count; i++) {
                size = vector[i].iov_len;
                base = vector[i].iov_base;

                while (size > 0) {
                        writesize = (size > LIBGF_IOBUF_SIZE) ?
                                LIBGF_IOBUF_SIZE : size;

                        written = libgf_client_iobuf_write (ctx, fd, base,
                                                            writesize, offset);

                        if (written == -1)
                                goto out;

                        op_ret += written;
                        base += written;
                        size -= written;
                        offset += written;
                }
        }

out:
        return op_ret;
}


ssize_t 
glusterfs_write (glusterfs_file_t fd, 
                 const void *buf, 
                 size_t n)
{
        int32_t op_ret = -1;
        off_t offset = 0;
        struct iovec vector;
        libglusterfs_client_ctx_t *ctx = NULL;
        libglusterfs_client_fd_ctx_t *fd_ctx = NULL;

        if (n < 0) {
                errno = EINVAL;
                goto out;
        }

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

        if (!fd) {
                errno = EINVAL;
		goto out;
        }

        fd_ctx = libgf_get_fd_ctx (fd);
        if (!fd_ctx) {
                errno = EBADF;
		goto out;
        }

        ctx = fd_ctx->ctx;

        pthread_mutex_lock (&fd_ctx->lock);
        {
                offset = fd_ctx->offset;
        }
        pthread_mutex_unlock (&fd_ctx->lock);

        vector.iov_base = (void *)buf;
        vector.iov_len = n;

        op_ret = libgf_client_writev (ctx,
                                      (fd_t *)fd, 
                                      &vector, 
                                      1, 
                                      offset);

        if (op_ret >= 0) {
                offset += op_ret;
                pthread_mutex_lock (&fd_ctx->lock);
                {
                        fd_ctx->offset = offset;
                }
                pthread_mutex_unlock (&fd_ctx->lock);
        }

out:
        return op_ret;
}

ssize_t 
glusterfs_writev (glusterfs_file_t fd, 
                  const struct iovec *vector,
                  int count)
{
        int32_t op_ret = -1;
        off_t offset = 0;
        libglusterfs_client_ctx_t *ctx = NULL;
        libglusterfs_client_fd_ctx_t *fd_ctx = NULL;

        if (count < 0) {
                errno = EINVAL;
                goto out;
        }

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

        if (!fd) {
                errno = EINVAL;
		goto out;
        }

        fd_ctx = libgf_get_fd_ctx (fd);
        if (!fd_ctx) {
                errno = EBADF;
		goto out;
        }

        ctx = fd_ctx->ctx;

        pthread_mutex_lock (&fd_ctx->lock);
        {
                offset = fd_ctx->offset;
        }
        pthread_mutex_unlock (&fd_ctx->lock);


        op_ret = libgf_client_writev (ctx,
                                      (fd_t *)fd, 
                                      (struct iovec *)vector, 
                                      count,
                                      offset);

        if (op_ret >= 0) {
                offset += op_ret;
                pthread_mutex_lock (&fd_ctx->lock);
                {
                        fd_ctx->offset = offset;
                }
                pthread_mutex_unlock (&fd_ctx->lock);
        }

out:
        return op_ret;
}


ssize_t 
glusterfs_pwrite (glusterfs_file_t fd, 
                  const void *buf, 
                  size_t count, 
                  off_t offset)
{
        int32_t op_ret = -1;
        struct iovec vector;
        libglusterfs_client_ctx_t *ctx = NULL;
        libglusterfs_client_fd_ctx_t *fd_ctx = NULL;

        if (count < 0) {
                errno = EINVAL;
                goto out;
        }

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

        if (!fd) {
                errno = EINVAL;
		goto out;
        }

        fd_ctx = libgf_get_fd_ctx (fd);
        if (!fd_ctx) {
                errno = EBADF;
		goto out;
        }

        ctx = fd_ctx->ctx;

        vector.iov_base = (void *)buf;
        vector.iov_len = count;

        op_ret = libgf_client_writev (ctx,
                                      (fd_t *)fd, 
                                      &vector, 
                                      1, 
                                      offset);

out:
        return op_ret;
}


int32_t
libgf_client_readdir_cbk (call_frame_t *frame,
                          void *cookie,
                          xlator_t *this,
                          int32_t op_ret,
                          int32_t op_errno,
                          gf_dirent_t *entries)
{
        libgf_client_local_t *local = frame->local;

        /* Note, we dont let entries reach the stub because there it gets copied
         * while we can simply delink the entries here and link them into our
         * dcache, thereby avoiding the need to perform more allocations and
         * copies.
         */
        local->reply_stub = fop_readdir_cbk_stub (frame, NULL, op_ret, op_errno,
                                                  NULL);
        if (op_ret > 0)
                libgf_dcache_update (frame->root->state, local->fd, entries);
        LIBGF_REPLY_NOTIFY (local);
        return 0;
}

int 
libgf_client_readdir (libglusterfs_client_ctx_t *ctx, fd_t *fd,
                      struct dirent *dirp, off_t *offset)
{  
        call_stub_t *stub = NULL;
        int op_ret = -1;
        libgf_client_local_t *local = NULL;

        if (libgf_dcache_readdir (ctx, fd, dirp, offset))
                return 1;
        local = CALLOC (1, sizeof (*local));
        ERR_ABORT (local);
        local->fd = fd;
        LIBGF_CLIENT_FOP (ctx, stub, readdir, local, fd,
                          LIBGF_READDIR_BLOCK, *offset);

        errno = stub->args.readdir_cbk.op_errno;

        op_ret = libgf_dcache_readdir (ctx, fd, dirp, offset);
	call_stub_destroy (stub);
        return op_ret;
}


int
glusterfs_readdir_r (glusterfs_dir_t dirfd, struct dirent *entry,
                     struct dirent **result)
{
        int                           op_ret = -1;
        libglusterfs_client_ctx_t    *ctx = NULL;
        off_t                         offset = 0;
        libglusterfs_client_fd_ctx_t *fd_ctx = NULL;
        struct dirent                *dirp = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, entry, out);

        fd_ctx = libgf_get_fd_ctx (dirfd);
        if (!fd_ctx) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "fd context not present");
                errno = EBADF;
		goto out;
        }

        pthread_mutex_lock (&fd_ctx->lock);
        {
                ctx = fd_ctx->ctx;
                offset = fd_ctx->offset;
                dirp = &fd_ctx->dirp;

                gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "offset %"PRIu64, offset);
                memset (dirp, 0, sizeof (struct dirent));
                op_ret = libgf_client_readdir (ctx, (fd_t *)dirfd, dirp,
                                               &offset);
                if (op_ret <= 0) {
                        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "readdir failed:"
                                " %s", strerror (errno));
                        if (result && (op_ret == 0)) {
                                *result = NULL;
                        } else if (op_ret < 0){
                                op_ret = errno;
                        }
                        goto unlock;
                }

                fd_ctx->offset = offset;

                if (result) {
                        *result = memcpy (entry, dirp, sizeof (*entry));
                } else {
                        memcpy (entry, dirp, sizeof (*entry));
                }

                gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "new offset %"PRIu64", "
                        " entry %s", offset, entry->d_name);
                op_ret = 0;
        }
unlock:
        pthread_mutex_unlock (&fd_ctx->lock);

out:
        return op_ret;
}


struct dirent *
glusterfs_readdir (glusterfs_dir_t dirfd)
{
        int op_ret = -1;
        libglusterfs_client_ctx_t *ctx = NULL;
        off_t offset = 0;
        libglusterfs_client_fd_ctx_t *fd_ctx = NULL;
        struct dirent *dirp = NULL;

        fd_ctx = libgf_get_fd_ctx (dirfd);
        if (!fd_ctx) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "fd context not present");
                errno = EBADF;
		goto out;
        }

        pthread_mutex_lock (&fd_ctx->lock);
        {
                ctx = fd_ctx->ctx;
                offset = fd_ctx->offset;
                dirp = &fd_ctx->dirp;
        }
        pthread_mutex_unlock (&fd_ctx->lock);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "offset %"PRIu64, offset);
        memset (dirp, 0, sizeof (struct dirent));
        op_ret = libgf_client_readdir (ctx, (fd_t *)dirfd, dirp, &offset);

        if (op_ret <= 0) {
                gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "readdir failed: %s",
                        strerror (errno));
                dirp = NULL;
                goto out;
        }

        pthread_mutex_lock (&fd_ctx->lock);
        {
                fd_ctx->offset = offset;
        }
        pthread_mutex_unlock (&fd_ctx->lock);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "new offset %"PRIu64", entry %s",
                offset, dirp->d_name);
out:
        return dirp;
}


int
glusterfs_getdents (glusterfs_file_t fd, struct dirent *dirp,
                    unsigned int count)
{
        int op_ret = -1;
        libglusterfs_client_ctx_t *ctx = NULL;
        off_t offset = 0;
        libglusterfs_client_fd_ctx_t *fd_ctx = NULL;

        fd_ctx = libgf_get_fd_ctx (fd);
        if (!fd_ctx) {
                errno = EBADF;
		goto out;
        }

        pthread_mutex_lock (&fd_ctx->lock);
        {
                ctx = fd_ctx->ctx;
                offset = fd_ctx->offset;
        }
        pthread_mutex_unlock (&fd_ctx->lock);

        op_ret = libgf_client_readdir (ctx, (fd_t *)fd, dirp, &offset);

        if (op_ret > 0) {
                pthread_mutex_lock (&fd_ctx->lock);
                {
                        fd_ctx->offset = offset;
                }
                pthread_mutex_unlock (&fd_ctx->lock);
        }

out:
        return op_ret;
}


static int32_t
libglusterfs_readv_async_cbk (call_frame_t *frame,
                              void *cookie,
                              xlator_t *this,
                              int32_t op_ret,
                              int32_t op_errno,
                              struct iovec *vector,
                              int32_t count,
                              struct stat *stbuf,
                              struct iobref *iobref)
{
        glusterfs_iobuf_t *buf;
        libglusterfs_client_async_local_t *local = frame->local;
        fd_t *__fd = local->fop.readv_cbk.fd;
        glusterfs_readv_cbk_t readv_cbk = local->fop.readv_cbk.cbk;

        buf = CALLOC (1, sizeof (*buf));
        ERR_ABORT (buf);

	if (vector) {
		buf->vector = iov_dup (vector, count);
	}

        buf->count = count;

	if (iobref) {
		buf->iobref = iobref_ref (iobref);
	}

        if (op_ret > 0) {
                libglusterfs_client_fd_ctx_t *fd_ctx = NULL;
                fd_ctx = libgf_get_fd_ctx (__fd);
                
                /* update offset only if we have used offset stored in fd_ctx */
                if (local->fop.readv_cbk.update_offset) {
                        pthread_mutex_lock (&fd_ctx->lock);
                        {
                                fd_ctx->offset += op_ret;
                        }
                        pthread_mutex_unlock (&fd_ctx->lock);
                }
        }

        readv_cbk (op_ret, op_errno, buf, local->cbk_data); 

	FREE (local);
	frame->local = NULL;
        STACK_DESTROY (frame->root);

        return 0;
}

void 
glusterfs_free (glusterfs_iobuf_t *buf)
{
        //iov_free (buf->vector, buf->count);
        FREE (buf->vector);
        if (buf->iobref)
                iobref_unref ((struct iobref *) buf->iobref);
        if (buf->dictref)
                dict_unref ((dict_t *) buf->dictref);
        FREE (buf);
}

int
glusterfs_read_async (glusterfs_file_t fd, 
                      size_t nbytes, 
                      off_t offset,
                      glusterfs_readv_cbk_t readv_cbk,
                      void *cbk_data)
{
        libglusterfs_client_ctx_t *ctx;
        fd_t *__fd = (fd_t *)fd;
        libglusterfs_client_async_local_t *local = NULL;
        libglusterfs_client_fd_ctx_t *fd_ctx = NULL;
	int32_t op_ret = 0;

        if (nbytes < 0) {
                errno = EINVAL;
                op_ret = -1;
                goto out;
        }

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

        local = CALLOC (1, sizeof (*local));
        ERR_ABORT (local);
        local->fop.readv_cbk.fd = __fd;
        local->fop.readv_cbk.cbk = readv_cbk;
        local->cbk_data = cbk_data;

        fd_ctx = libgf_get_fd_ctx (fd);
        if (!fd_ctx) {
                errno = EBADF;
		op_ret = -1;
		goto out;
        }

        ctx = fd_ctx->ctx;

        if (offset < 0) {
                pthread_mutex_lock (&fd_ctx->lock);
                {
                        offset = fd_ctx->offset;
                        local->fop.readv_cbk.update_offset = 1;
                }
                pthread_mutex_unlock (&fd_ctx->lock);
        }

        LIBGF_CLIENT_FOP_ASYNC (ctx,
                                local,
                                libglusterfs_readv_async_cbk,
                                readv,
                                __fd,
                                nbytes,
                                offset);

out:
        return op_ret;
}

static int32_t
libglusterfs_writev_async_cbk (call_frame_t *frame,
                               void *cookie,
                               xlator_t *this,
                               int32_t op_ret,
                               int32_t op_errno,
                               struct stat *prebuf,
                               struct stat *postbuf)
{
        libglusterfs_client_async_local_t *local = frame->local;
        fd_t *fd = NULL;
        glusterfs_write_cbk_t write_cbk;

        write_cbk = local->fop.write_cbk.cbk;
        fd = local->fop.write_cbk.fd;

        if (op_ret > 0) {
                libglusterfs_client_fd_ctx_t *fd_ctx = NULL;
                fd_ctx = libgf_get_fd_ctx (fd);
                pthread_mutex_lock (&fd_ctx->lock);
                {
                        fd_ctx->offset += op_ret;  
                }
                pthread_mutex_unlock (&fd_ctx->lock);
        }

        write_cbk (op_ret, op_errno, local->cbk_data);

        STACK_DESTROY (frame->root);
        return 0;
}

int32_t
glusterfs_write_async (glusterfs_file_t fd, 
                       const void *buf, 
                       size_t nbytes, 
                       off_t offset,
                       glusterfs_write_cbk_t write_cbk,
                       void *cbk_data)
{
        fd_t *__fd = (fd_t *)fd;
        struct iovec vector;
        off_t __offset = offset;
        libglusterfs_client_ctx_t *ctx = NULL;
        libglusterfs_client_async_local_t *local = NULL;
        libglusterfs_client_fd_ctx_t *fd_ctx = NULL;
	int32_t op_ret = 0;
        struct iobref *iobref = NULL;

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

        if (nbytes < 0) {
                op_ret = -1;
                errno = EINVAL;
                goto out;
        }

        local = CALLOC (1, sizeof (*local));
        ERR_ABORT (local);
        local->fop.write_cbk.fd = __fd;
        local->fop.write_cbk.cbk = write_cbk;
        local->cbk_data = cbk_data;

        vector.iov_base = (void *)buf;
        vector.iov_len = nbytes;
  
        fd_ctx = libgf_get_fd_ctx (fd);
        if (!fd_ctx) {
                errno = EBADF;
		op_ret = -1;
		goto out;
        }

        ctx = fd_ctx->ctx;
 
        if (offset < 0) {
                pthread_mutex_lock (&fd_ctx->lock);
                {
                        __offset = fd_ctx->offset;
                }
                pthread_mutex_unlock (&fd_ctx->lock);
        }

        iobref = iobref_new ();
        LIBGF_CLIENT_FOP_ASYNC (ctx,
                                local,
                                libglusterfs_writev_async_cbk,
                                writev,
                                __fd,
                                &vector,
                                1,
                                __offset,
                                iobref);
        iobref_unref (iobref);

out:
        return op_ret;
}

off_t
glusterfs_lseek (glusterfs_file_t fd, off_t offset, int whence)
{
        off_t __offset = 0;
	int32_t op_ret = -1;
        fd_t *__fd = (fd_t *)fd;
        libglusterfs_client_fd_ctx_t *fd_ctx = NULL;
	libglusterfs_client_ctx_t *ctx = NULL; 

        fd_ctx = libgf_get_fd_ctx (fd);
        if (!fd_ctx) {
                errno = EBADF;
		__offset = -1;
		goto out;
        }

	ctx = fd_ctx->ctx;

        switch (whence)
        {
        case SEEK_SET:
                __offset = offset;
                break;

        case SEEK_CUR:
                pthread_mutex_lock (&fd_ctx->lock);
                {
                        __offset = fd_ctx->offset;
                }
                pthread_mutex_unlock (&fd_ctx->lock);

                __offset += offset;
                break;

        case SEEK_END:
	{
		char cache_valid = 0;
		off_t end = 0;
		loc_t loc = {0, };
		struct stat stbuf = {0, };

                cache_valid = libgf_is_iattr_cache_valid (ctx, __fd->inode,
                                                          &stbuf,
                                                          LIBGF_VALIDATE_STAT);
                if (cache_valid) {
			end = stbuf.st_size;
		} else {
			op_ret = libgf_client_loc_fill (&loc, ctx,
                                                        __fd->inode->ino, 0,
                                                        NULL);
			if (op_ret == -1) {
				gf_log ("libglusterfsclient",
					GF_LOG_ERROR,
					"libgf_client_loc_fill returned -1, returning EINVAL");
				errno = EINVAL;
				libgf_client_loc_wipe (&loc);
				__offset = -1;
				goto out;
			}
			
			op_ret = libgf_client_lookup (ctx, &loc, &stbuf, NULL,
                                                      NULL);
			if (op_ret < 0) {
				__offset = -1;
				libgf_client_loc_wipe (&loc);
				goto out;
			}

			end = stbuf.st_size;
		}

                __offset = end + offset; 
		libgf_client_loc_wipe (&loc);
	}
	break;

	default:
		gf_log ("libglusterfsclient",
			GF_LOG_ERROR,
			"invalid value for whence");
		__offset = -1;
		errno = EINVAL;
		goto out;
        }

        pthread_mutex_lock (&fd_ctx->lock);
        {
                fd_ctx->offset = __offset;
        }
        pthread_mutex_unlock (&fd_ctx->lock);
 
out: 
        return __offset;
}


int32_t
libgf_client_stat_cbk (call_frame_t *frame,
                       void *cookie,
                       xlator_t *this,
                       int32_t op_ret,
                       int32_t op_errno,
                       struct stat *buf)
{
        libgf_client_local_t *local = frame->local;

        local->reply_stub = fop_stat_cbk_stub (frame, 
                                               NULL, 
                                               op_ret, 
                                               op_errno, 
                                               buf);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}

int32_t 
libgf_client_stat (libglusterfs_client_ctx_t *ctx, 
                   loc_t *loc,
                   struct stat *stbuf)
{
        call_stub_t *stub = NULL;
        int32_t op_ret = 0;
        libgf_client_local_t *local = NULL;
        struct stat cachedbuf = {0, };

        if (libgf_is_iattr_cache_valid (ctx, loc->inode, &cachedbuf,
                                        LIBGF_VALIDATE_STAT)) {
                gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "Cache will be used");
                if (stbuf)
                        memcpy (stbuf, &cachedbuf, sizeof (struct stat));
                goto out;
        }

        LIBGF_CLIENT_FOP (ctx, stub, stat, local, loc);
 
        op_ret = stub->args.stat_cbk.op_ret;
        errno = stub->args.stat_cbk.op_errno;
        libgf_transform_devnum (ctx, &stub->args.stat_cbk.buf);
        if (stbuf)
                *stbuf = stub->args.stat_cbk.buf;

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s, status %d, errno %d",
                loc->path, op_ret, errno);
        libgf_update_iattr_cache (loc->inode, LIBGF_UPDATE_STAT,
                                        &stub->args.stat_cbk.buf);
	call_stub_destroy (stub);

out:
        return op_ret;
}

int
libgf_realpath_loc_fill (libglusterfs_client_ctx_t *ctx, char *link,
                                loc_t *targetloc)
{
        int             op_ret = -1;
        char            *target = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, link, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, targetloc, out);

        targetloc->path = glusterfs_glh_realpath (ctx, link, NULL);

        if (targetloc->path == NULL)
                goto out;

        op_ret = libgf_client_path_lookup (targetloc, ctx, 1);
        if (op_ret == -1)
                goto out;

        target = strdup (targetloc->path);
        op_ret = libgf_client_loc_fill (targetloc, ctx, 0,
                                               targetloc->parent->ino,
                                               basename (target));
        if (op_ret == -1) {
                errno = EINVAL;
                goto out;
        }

out:
        if (target)
                FREE (target);

        return op_ret;
}

#define LIBGF_DO_LSTAT  0x01
#define LIBGF_DO_STAT   0x02

int
__glusterfs_stat (glusterfs_handle_t handle, const char *path,
                        struct stat *buf, int whichstat)
{
        int32_t op_ret = -1;
        loc_t loc = {0, };
        libglusterfs_client_ctx_t *ctx = handle;
	char *name = NULL, *pathname = NULL;
        loc_t targetloc = {0, };
        loc_t *real_loc = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s, op: %d", path,
                whichstat);
        loc.path = libgf_resolve_path_light ((char *)path);
        if (!loc.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

	op_ret = libgf_client_path_lookup (&loc, ctx, 1);
	if (op_ret == -1) {
		gf_log ("libglusterfsclient", GF_LOG_ERROR,
			"path lookup failed for (%s)", loc.path);
		goto out;
	}

	pathname = strdup (loc.path);
	name = basename (pathname);

        op_ret = libgf_client_loc_fill (&loc, ctx, 0, loc.parent->ino, name);
	if (op_ret == -1) {
		gf_log ("libglusterfsclient",
			GF_LOG_ERROR,
			"libgf_client_loc_fill returned -1, returning EINVAL");
		errno = EINVAL;
		goto out;
	}
        real_loc = &loc;
        /* The stat fop in glusterfs calls lstat. So we have to
         * provide the POSIX compatible stat fop. To do so, we need to ensure
         * that if the @path is a symlink, we must perform a stat on the
         * target of that symlink than the symlink itself(..because if
         * do a stat on the symlink, we're actually doing what lstat
         * should do. See posix_stat
         */
        if (whichstat & LIBGF_DO_LSTAT)
                goto lstat_fop;

        if (!S_ISLNK (loc.inode->st_mode))
                goto lstat_fop;

        op_ret = libgf_realpath_loc_fill (ctx, (char *)loc.path, &targetloc);
        if (op_ret == -1)
                goto out;
        real_loc = &targetloc;

lstat_fop:

        if (!op_ret) {
                op_ret = libgf_client_stat (ctx, real_loc, buf);
        }

out:
	if (pathname) {
		FREE (pathname);
	}

        libgf_client_loc_wipe (&loc);
        libgf_client_loc_wipe (&targetloc);

        return op_ret;
}

int
glusterfs_glh_stat (glusterfs_handle_t handle, const char *path,
                        struct stat *buf)
{
        return __glusterfs_stat (handle, path, buf, LIBGF_DO_STAT);
}

int
glusterfs_stat (const char *path, struct stat *buf)
{
        struct vmp_entry        *entry = NULL;
        int                     op_ret = -1;
        char                    *vpath = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, buf, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        op_ret = glusterfs_glh_stat (entry->handle, vpath, buf);
out:
        if (vpath)
                free (vpath);
        return op_ret;
}

int
glusterfs_glh_lstat (glusterfs_handle_t handle, const char *path, struct stat *buf)
{
        return __glusterfs_stat (handle, path, buf, LIBGF_DO_LSTAT);
}

int
glusterfs_lstat (const char *path, struct stat *buf)
{
        struct vmp_entry        *entry = NULL;
        int                     op_ret = -1;
        char                    *vpath = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, buf, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        op_ret = glusterfs_glh_lstat (entry->handle, vpath, buf);
out:
        if (vpath)
                free (vpath);
        return op_ret;
}

static int32_t
libgf_client_fstat_cbk (call_frame_t *frame,
                        void *cookie,
                        xlator_t *this,
                        int32_t op_ret,
                        int32_t op_errno,
                        struct stat *buf)
{  
        libgf_client_local_t *local = frame->local;

        local->reply_stub = fop_fstat_cbk_stub (frame, 
                                                NULL, 
                                                op_ret, 
                                                op_errno, 
                                                buf);

        LIBGF_REPLY_NOTIFY (local);
        return 0;

}

int32_t
libgf_client_fstat (libglusterfs_client_ctx_t *ctx, 
                    fd_t *fd, 
                    struct stat *buf)
{
        call_stub_t *stub = NULL;
        int32_t op_ret = 0;
        libgf_client_local_t *local = NULL;
        struct stat cachedbuf = {0, };

        if (libgf_is_iattr_cache_valid (ctx, fd->inode, &cachedbuf,
                                        LIBGF_VALIDATE_STAT)) {
                if (buf)
                        memcpy (buf, &cachedbuf, sizeof (struct stat));
                gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "Cache will be used");
                goto out;
        }

        LIBGF_CLIENT_FOP (ctx, stub, fstat, local, fd);
 
        op_ret = stub->args.fstat_cbk.op_ret;
        errno = stub->args.fstat_cbk.op_errno;
        libgf_transform_devnum (ctx, &stub->args.fstat_cbk.buf);
        if (buf)
                *buf = stub->args.fstat_cbk.buf;

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "status %d, errno %d", op_ret,
                errno);
        libgf_update_iattr_cache (fd->inode, LIBGF_UPDATE_STAT,
                                        &stub->args.fstat_cbk.buf);
	call_stub_destroy (stub);

out:
        return op_ret;
}

int32_t 
glusterfs_fstat (glusterfs_file_t fd, struct stat *buf) 
{
        libglusterfs_client_ctx_t *ctx;
        fd_t *__fd = (fd_t *)fd;
        libglusterfs_client_fd_ctx_t *fd_ctx = NULL;
	int32_t op_ret = -1;

        fd_ctx = libgf_get_fd_ctx (fd);
        if (!fd_ctx) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "No fd context present");
                errno = EBADF;
		op_ret = -1;
		goto out;
        }

        ctx = fd_ctx->ctx;

	op_ret = libgf_client_fstat (ctx, __fd, buf);

out:
	return op_ret;
}


static int32_t
libgf_client_mkdir_cbk (call_frame_t *frame,
			void *cookie,
			xlator_t *this,
			int32_t op_ret,
			int32_t op_errno,
			inode_t *inode,
                        struct stat *buf,
                        struct stat *preparent,
                        struct stat *postparent)
{
        libgf_client_local_t *local = frame->local;

        local->reply_stub = fop_mkdir_cbk_stub (frame, NULL, op_ret, op_errno,
                                                inode, buf, preparent,
                                                postparent);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}


static int32_t
libgf_client_mkdir (libglusterfs_client_ctx_t *ctx,
		    loc_t *loc,
		    mode_t mode)
{
	int32_t op_ret = -1;
        call_stub_t *stub = NULL;
        libgf_client_local_t *local = NULL;
        inode_t *libgf_inode = NULL;

        LIBGF_CLIENT_FOP (ctx, stub, mkdir, local, loc, mode);
        op_ret = stub->args.mkdir_cbk.op_ret;
        errno = stub->args.mkdir_cbk.op_errno;

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s, status %d, errno %d",
                loc->path, op_ret, errno);
        if (op_ret == -1)
                goto out;

	libgf_inode = stub->args.mkdir_cbk.inode;
        libgf_transform_devnum (ctx, &stub->args.mkdir_cbk.buf);
        inode_link (libgf_inode, loc->parent, loc->name,
                        &stub->args.mkdir_cbk.buf);

        inode_lookup (libgf_inode);

        libgf_alloc_inode_ctx (ctx, libgf_inode);
        libgf_update_iattr_cache (libgf_inode, LIBGF_UPDATE_ALL,
                                        &stub->args.mkdir_cbk.buf);

out:
	call_stub_destroy (stub);

	return op_ret;
}


int32_t
glusterfs_glh_mkdir (glusterfs_handle_t handle, const char *path, mode_t mode)
{
	libglusterfs_client_ctx_t *ctx = handle;
	loc_t loc = {0, };
	char *pathname = NULL, *name = NULL;
	int32_t op_ret = -1;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, path, out);

        loc.path = libgf_resolve_path_light ((char *)path);
        if (!loc.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

	op_ret = libgf_client_path_lookup (&loc, ctx, 1);
	if (op_ret == 0) {
                op_ret = -1;
                errno = EEXIST;
		goto out;
	}

        op_ret = libgf_client_path_lookup (&loc, ctx, 0);
        if (op_ret == -1) {
                errno = ENOENT;
                goto out;
        }

	pathname = strdup (loc.path);
	name = basename (pathname);

        op_ret = libgf_client_loc_fill (&loc, ctx, 0, loc.parent->ino, name);
	if (op_ret == -1) {
		gf_log ("libglusterfsclient",
			GF_LOG_ERROR,
			"libgf_client_loc_fill returned -1, returning EINVAL");
		errno = EINVAL;
		goto out;
	}

        loc.inode = inode_new (ctx->itable);
	op_ret = libgf_client_mkdir (ctx, &loc, mode); 
	if (op_ret == -1) {
		goto out;
	}

out:
	libgf_client_loc_wipe (&loc);
	if (pathname) {
		free (pathname);
		pathname = NULL;
	}

	return op_ret;
}

int32_t
glusterfs_mkdir (const char *path, mode_t mode)
{
        struct vmp_entry        *entry = NULL;
        int                     op_ret = -1;
        char                    *vpath = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        op_ret = glusterfs_glh_mkdir (entry->handle, vpath, mode);
out:
        if (vpath)
                free (vpath);
        return op_ret;
}

static int32_t
libgf_client_rmdir_cbk (call_frame_t *frame, void *cookie, xlator_t *this,
                        int32_t op_ret, int32_t op_errno,struct stat *preparent,
                        struct stat *postparent)
{
        libgf_client_local_t *local = frame->local;

        local->reply_stub = fop_rmdir_cbk_stub (frame, NULL, op_ret, op_errno,
                                                preparent, postparent);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}

static int32_t
libgf_client_rmdir (libglusterfs_client_ctx_t *ctx, loc_t *loc)
{
        int32_t op_ret = -1;
        call_stub_t *stub = NULL;
        libgf_client_local_t *local = NULL;

        LIBGF_CLIENT_FOP (ctx, stub, rmdir, local, loc);

        op_ret = stub->args.rmdir_cbk.op_ret;
        errno = stub->args.rmdir_cbk.op_errno;

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s, status %d, errno %d",
                loc->path, op_ret, errno);
        if (stub->args.rmdir_cbk.op_ret != 0)
                goto out;

        inode_unlink (loc->inode, loc->parent, loc->name);

out:
	call_stub_destroy (stub);

	return op_ret;
}

int32_t
glusterfs_glh_rmdir (glusterfs_handle_t handle, const char *path)
{
	libglusterfs_client_ctx_t *ctx = handle;
	loc_t loc = {0, };
	char *pathname = NULL, *name = NULL;
	int32_t op_ret = -1;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, path, out);

        loc.path = libgf_resolve_path_light ((char *)path);
        if (!loc.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

	op_ret = libgf_client_path_lookup (&loc, ctx, 1);
	if (op_ret == -1) {
		gf_log ("libglusterfsclient", GF_LOG_ERROR,
			"path lookup failed for (%s)", loc.path);
		goto out;
	}

	pathname = strdup (loc.path);
	name = basename (pathname);

        op_ret = libgf_client_loc_fill (&loc, ctx, 0, loc.parent->ino, name);
	if (op_ret == -1) {
		gf_log ("libglusterfsclient",
			GF_LOG_ERROR,
			"libgf_client_loc_fill returned -1, returning EINVAL");
		errno = EINVAL;
		goto out;
	}

	op_ret = libgf_client_rmdir (ctx, &loc);
	if (op_ret == -1) {
		goto out;
	}

out:
	libgf_client_loc_wipe (&loc);

	if (pathname) {
		free (pathname);
		pathname = NULL;
	}

	return op_ret;
}

int32_t
glusterfs_rmdir (const char *path)
{
        struct vmp_entry        *entry = NULL;
        int                     op_ret = -1;
        char                    *vpath = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        op_ret = glusterfs_glh_rmdir (entry->handle, vpath);
out:
        if (vpath)
                free (vpath);
        return op_ret;
}

int
libgf_client_setattr_cbk (call_frame_t *frame, void *cookie, xlator_t *this,
                          int32_t op_ret, int32_t op_errno,
                          struct stat *preop, struct stat *postop)
{
        libgf_client_local_t *local = frame->local;

        local->reply_stub = fop_setattr_cbk_stub (frame, NULL,
                                                  op_ret, op_errno,
                                                  preop, postop);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}

int
libgf_client_setattr (libglusterfs_client_ctx_t *ctx, loc_t * loc,
                      struct stat *stbuf, int32_t valid)
{
        int                             op_ret = -1;
        libgf_client_local_t            *local = NULL;
        call_stub_t                     *stub = NULL;

        LIBGF_CLIENT_FOP (ctx, stub, setattr, local, loc,
                          stbuf, valid);

        op_ret = stub->args.setattr_cbk.op_ret;
        errno = stub->args.setattr_cbk.op_errno;

        if (op_ret == -1)
                goto out;

        libgf_transform_devnum (ctx, &stub->args.setattr_cbk.statpost);
        libgf_update_iattr_cache (loc->inode, LIBGF_UPDATE_STAT,
                                  &stub->args.setattr_cbk.statpost);
out:
        call_stub_destroy (stub);
        return op_ret;
}

int
libgf_client_chmod_cbk (call_frame_t *frame, void *cookie, xlator_t *this,
                int32_t op_ret, int32_t op_errno, struct stat *buf)
{
        libgf_client_local_t    *local = frame->local;

        local->reply_stub = fop_chmod_cbk_stub (frame, NULL, op_ret, op_errno,
                                                        buf);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}

int
libgf_client_chmod (libglusterfs_client_ctx_t *ctx, loc_t * loc, mode_t mode)
{
        int                             op_ret = -1;
        libgf_client_local_t            *local = NULL;
        call_stub_t                     *stub = NULL;

        LIBGF_CLIENT_FOP (ctx, stub, chmod, local, loc, mode);

        op_ret = stub->args.chmod_cbk.op_ret;
        errno = stub->args.chmod_cbk.op_errno;

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s, status %d, errno %d",
                loc->path, op_ret, errno);
        if (op_ret == -1)
                goto out;

        libgf_transform_devnum (ctx, &stub->args.chmod_cbk.buf);
        libgf_update_iattr_cache (loc->inode, LIBGF_UPDATE_STAT,
                                        &stub->args.chmod_cbk.buf);
out:
        call_stub_destroy (stub);
        return op_ret;
}

int
glusterfs_glh_chmod (glusterfs_handle_t handle, const char *path, mode_t mode)
{
        int                             op_ret = -1;
        libglusterfs_client_ctx_t       *ctx = handle;
        loc_t                           loc = {0, };
        char                            *name = NULL;
        struct stat                     stbuf = {0,};
        int32_t                         valid = 0;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, path, out);

        stbuf.st_mode = mode;
        valid |= GF_SET_ATTR_MODE;
        loc.path = libgf_resolve_path_light ((char *)path);
        if (!loc.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

        op_ret = libgf_client_path_lookup (&loc, ctx, 1);
        if (op_ret == -1)
                goto out;

        name = strdup (loc.path);
        op_ret = libgf_client_loc_fill (&loc, ctx, 0, loc.parent->ino,
                                                basename (name));
        if (op_ret == -1) {
                errno = EINVAL;
                goto out;
        }

        op_ret = libgf_client_setattr (ctx, &loc, &stbuf, valid);

out:
        if (name)
                FREE (name);

        libgf_client_loc_wipe (&loc);
        return op_ret;
}

int
glusterfs_chmod (const char *path, mode_t mode)
{
        struct vmp_entry        *entry = NULL;
        int                     op_ret = -1;
        char                    *vpath = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        op_ret = glusterfs_glh_chmod (entry->handle, vpath, mode);
out:
        if (vpath)
                free (vpath);
        return op_ret;
}

int
libgf_client_chown_cbk (call_frame_t *frame, void *cookie, xlator_t *this,
                int32_t op_ret, int32_t op_errno, struct stat *sbuf)
{
        libgf_client_local_t    *local = frame->local;

        local->reply_stub = fop_chown_cbk_stub (frame, NULL, op_ret, op_errno,
                                                sbuf);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}

int
libgf_client_chown (libglusterfs_client_ctx_t *ctx, loc_t *loc, uid_t uid,
                gid_t gid)
{
        call_stub_t             *stub = NULL;
        libgf_client_local_t    *local = NULL;
        int32_t                 op_ret = -1;

        LIBGF_CLIENT_FOP (ctx, stub, chown, local, loc, uid, gid);

        op_ret = stub->args.chown_cbk.op_ret;
        errno = stub->args.chown_cbk.op_errno;

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s, status %d, errno %d",
                loc->path, op_ret, errno);
        if (op_ret == -1)
                goto out;

        libgf_transform_devnum (ctx, &stub->args.chown_cbk.buf);
        libgf_update_iattr_cache (loc->inode, LIBGF_UPDATE_STAT,
                                        &stub->args.chown_cbk.buf);
out:
        call_stub_destroy (stub);
        return op_ret;
}

#define LIBGF_DO_CHOWN  1
#define LIBGF_DO_LCHOWN 2

int
__glusterfs_chown (glusterfs_handle_t handle, const char *path, uid_t owner,
                   gid_t group, int whichop)
{
        int                             op_ret = -1;
        libglusterfs_client_ctx_t       *ctx = handle;
        loc_t                           loc = {0, };
        char                            *name = NULL;
        loc_t                           *oploc = NULL;
        loc_t                           targetloc = {0, };

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s, op %d", path, whichop);
        loc.path = libgf_resolve_path_light ((char *)path);
        if (!loc.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

        op_ret = libgf_client_path_lookup (&loc, ctx, 1);
        if (op_ret == -1)
                goto out;

        name = strdup (loc.path);
        op_ret = libgf_client_loc_fill (&loc, ctx, 0, loc.parent->ino,
                        basename ((char *)name));
        if (op_ret == -1) {
                errno = EINVAL;
                goto out;
        }

        oploc = &loc;
        if (whichop == LIBGF_DO_LCHOWN)
                goto do_lchown;

        if (!S_ISLNK (loc.inode->st_mode))
                goto do_lchown;

        op_ret = libgf_realpath_loc_fill (ctx, (char *)loc.path, &targetloc);
        if (op_ret == -1)
                goto out;

        oploc = &targetloc;
do_lchown:
        op_ret = libgf_client_chown (ctx, oploc, owner, group);
out:
        if (name)
                FREE (name);
        libgf_client_loc_wipe (&loc);
        libgf_client_loc_wipe (&targetloc);
        return op_ret;
}

int
glusterfs_glh_chown (glusterfs_handle_t handle, const char *path, uid_t owner,
                     gid_t group)
{
        return __glusterfs_chown (handle, path, owner, group, LIBGF_DO_CHOWN);
}

int
glusterfs_chown (const char *path, uid_t owner, gid_t group)
{
        struct vmp_entry        *entry = NULL;
        int                     op_ret = -1;
        char                    *vpath = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        op_ret = glusterfs_glh_chown (entry->handle, vpath, owner, group);
out:
        if (vpath)
                free (vpath);
        return op_ret;
}

int
glusterfs_glh_lchown (glusterfs_handle_t handle, const char *path, uid_t owner,
                     gid_t group)
{
        return __glusterfs_chown (handle, path, owner, group, LIBGF_DO_LCHOWN);
}

int
glusterfs_lchown (const char *path, uid_t owner, gid_t group)
{
        struct vmp_entry        *entry = NULL;
        int                     op_ret = -1;
        char                    *vpath = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        op_ret = glusterfs_glh_lchown (entry->handle, vpath, owner, group);
out:
        if (vpath)
                free (vpath);
        return op_ret;
}

glusterfs_dir_t
glusterfs_glh_opendir (glusterfs_handle_t handle, const char *path)
{
        int                             op_ret = -1;
        libglusterfs_client_ctx_t       *ctx = handle;
        loc_t                           loc = {0, };
        fd_t                            *dirfd = NULL;
        char                            *name = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        loc.path = libgf_resolve_path_light ((char *)path);
        if (!loc.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }
        op_ret = libgf_client_path_lookup (&loc, ctx, 1);

        if (op_ret == -1)
                goto out;

        name = strdup (loc.path);
        op_ret = libgf_client_loc_fill (&loc, ctx, 0, loc.parent->ino,
                        basename (name));
        if (op_ret == -1) {
                errno = EINVAL;
                goto out;
        }

        if (!S_ISDIR (loc.inode->st_mode) && !S_ISLNK (loc.inode->st_mode)) {
                errno = ENOTDIR;
                op_ret = -1;
                goto out;
        }

        dirfd = fd_create (loc.inode, ctx->pid);
        op_ret = libgf_client_opendir (ctx, &loc, dirfd);

        if (op_ret == -1) {
                fd_unref (dirfd);
                dirfd = NULL;
                goto out;
        }

        if (!libgf_get_fd_ctx (dirfd)) {
                if (!(libgf_alloc_fd_ctx (ctx, dirfd))) {
                        gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Context "
                                "allocation failed");
                        op_ret = -1;
                        errno = EINVAL;
                        goto out;
                }
        }

out:
        if (name)
                FREE (name);

        if (op_ret == -1) {
                fd_unref (dirfd);
                dirfd = NULL;
        }

        libgf_client_loc_wipe (&loc);
        return dirfd;
}

glusterfs_dir_t
glusterfs_opendir (const char *path)
{
        struct vmp_entry        *entry = NULL;
        char                    *vpath = NULL;
        glusterfs_dir_t         dir = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);
        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);

        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        dir = glusterfs_glh_opendir (entry->handle, vpath);
out:
        if (vpath)
                free (vpath);
        return dir;
}

int
glusterfs_closedir (glusterfs_dir_t dirfd)
{
        int                             op_ret = -1;
        libglusterfs_client_fd_ctx_t    *fdctx = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, dirfd, out);
        fdctx = libgf_get_fd_ctx (dirfd);

        if (fdctx == NULL) {
                errno = EBADF;
                op_ret = -1;
                goto out;
        }

        op_ret = libgf_client_flush (fdctx->ctx, (fd_t *)dirfd);
        fd_unref ((fd_t *)dirfd);

out:
        return op_ret;
}

int
libgf_client_fchmod_cbk (call_frame_t *frame, void *cookie, xlator_t *this,
                                int32_t op_ret, int32_t op_errno,
                                struct stat *buf)
{
        libgf_client_local_t    *local = frame->local;

        local->reply_stub = fop_fchmod_cbk_stub (frame, NULL, op_ret, op_errno,
                                                        buf);
        LIBGF_REPLY_NOTIFY (local);

        return 0;
}

int
libgf_client_fchmod (libglusterfs_client_ctx_t *ctx, fd_t *fd, mode_t mode)
{
        int                     op_ret = -1;
        libgf_client_local_t    *local = NULL;
        call_stub_t             *stub = NULL;

        LIBGF_CLIENT_FOP (ctx, stub, fchmod, local, fd, mode);

        op_ret = stub->args.fchmod_cbk.op_ret;
        errno = stub->args.fchmod_cbk.op_errno;

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "status %d, errno %d", op_ret,
                errno);
        if (op_ret == -1)
                goto out;

        libgf_transform_devnum (ctx, &stub->args.fchmod_cbk.buf);
        libgf_update_iattr_cache (fd->inode, LIBGF_UPDATE_STAT,
                                        &stub->args.fchmod_cbk.buf);
out:
        call_stub_destroy (stub);
        return op_ret;
}

int
glusterfs_fchmod (glusterfs_file_t fd, mode_t mode)
{
        libglusterfs_client_fd_ctx_t    *fdctx = NULL;
        int                             op_ret = -1;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, fd, out);
        fdctx = libgf_get_fd_ctx (fd);

        if (!fdctx) {
                gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "No fd context present");
                errno = EBADF;
                goto out;
        }

        op_ret = libgf_client_fchmod (fdctx->ctx, fd, mode);

out:
        return op_ret;
}

int
libgf_client_fchown_cbk (call_frame_t *frame, void *cookie, xlator_t *xlator,
                                int32_t op_ret, int32_t op_errno,
                                struct stat *buf)
{
        libgf_client_local_t            *local = frame->local;

        local->reply_stub = fop_fchown_cbk_stub (frame, NULL, op_ret, op_errno,
                                                        buf);
        LIBGF_REPLY_NOTIFY (local);

        return 0;
}

int
libgf_client_fchown (libglusterfs_client_ctx_t *ctx, fd_t *fd, uid_t uid,
                        gid_t gid)
{
        call_stub_t             *stub  = NULL;
        libgf_client_local_t    *local = NULL;
        int                     op_ret = -1;

        LIBGF_CLIENT_FOP (ctx, stub, fchown, local, fd, uid, gid);

        op_ret = stub->args.fchown_cbk.op_ret;
        errno = stub->args.fchown_cbk.op_errno;

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "status %d, errno %d", op_ret,
                errno);
        if (op_ret == -1)
                goto out;

        libgf_transform_devnum (ctx, &stub->args.fchown_cbk.buf);
        libgf_update_iattr_cache (fd->inode, LIBGF_UPDATE_STAT,
                                        &stub->args.fchown_cbk.buf);
out:
        call_stub_destroy (stub);
        return op_ret;
}

int
glusterfs_fchown (glusterfs_file_t fd, uid_t uid, gid_t gid)
{
        int                             op_ret = -1;
        libglusterfs_client_fd_ctx_t    *fdctx = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, fd, out);

        fdctx = libgf_get_fd_ctx (fd);
        if (!fd) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "No fd context present");
                errno = EBADF;
                goto out;
        }

        op_ret = libgf_client_fchown (fdctx->ctx, fd, uid, gid);

out:
        return op_ret;
}

int
libgf_client_fsync_cbk (call_frame_t *frame, void *cookie, xlator_t *xlator,
                        int32_t op_ret, int32_t op_errno, struct stat *prebuf,
                        struct stat *postbuf)
{
        libgf_client_local_t    *local = frame->local;

        local->reply_stub = fop_fsync_cbk_stub (frame, NULL, op_ret, op_errno,
                                                prebuf, postbuf);

        LIBGF_REPLY_NOTIFY (local);

        return 0;
}

int
libgf_client_fsync (libglusterfs_client_ctx_t *ctx, fd_t *fd)
{
        libgf_client_local_t    *local = NULL;
        call_stub_t             *stub = NULL;
        int                     op_ret = -1;

        LIBGF_CLIENT_FOP (ctx, stub, fsync, local, fd, 0);

        op_ret = stub->args.fsync_cbk.op_ret;
        errno = stub->args.fsync_cbk.op_errno;

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "status %d, errno %d", op_ret,
                errno);
        call_stub_destroy (stub);

        return op_ret;
}

int
glusterfs_fsync (glusterfs_file_t *fd)
{
        libglusterfs_client_fd_ctx_t    *fdctx = NULL;
        int                             op_ret = -1;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, fd, out);

        fdctx = libgf_get_fd_ctx ((fd_t *)fd);
        if (!fdctx) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "No fd context present");
                errno = EBADF;
                goto out;
        }

        op_ret = libgf_client_fsync (fdctx->ctx, (fd_t *)fd);

out:
        return op_ret;
}

int
libgf_client_ftruncate_cbk (call_frame_t *frame, void *cookie, xlator_t *xlator
                                ,int32_t op_ret, int32_t op_errno,
                                struct stat *prebuf, struct stat *postbuf)
{
        libgf_client_local_t    *local = frame->local;

        local->reply_stub = fop_ftruncate_cbk_stub (frame, NULL, op_ret,
                                                    op_errno, prebuf, postbuf);

        LIBGF_REPLY_NOTIFY (local);

        return 0;
}

int
libgf_client_ftruncate (libglusterfs_client_ctx_t *ctx, fd_t *fd,
                                off_t length)
{
        libgf_client_local_t            *local = NULL;
        call_stub_t                     *stub = NULL;
        int                             op_ret = -1;
        libglusterfs_client_fd_ctx_t    *fdctx = NULL;

        if ((!(fd->flags & O_ACCMODE) ==  O_RDWR)
                        && (!((fd->flags & O_ACCMODE) == O_WRONLY))) {
                errno = EBADF;
                goto out;
        }

        LIBGF_CLIENT_FOP (ctx, stub, ftruncate, local, fd, length);

        op_ret = stub->args.ftruncate_cbk.op_ret;
        errno = stub->args.ftruncate_cbk.op_errno;

        if (op_ret == -1)
                goto out;

        libgf_transform_devnum (ctx, &stub->args.ftruncate_cbk.postbuf);
        libgf_update_iattr_cache (fd->inode, LIBGF_UPDATE_STAT,
                                        &stub->args.ftruncate_cbk.postbuf);

        fdctx = libgf_get_fd_ctx (fd);
        if (!fd) {
                errno = EINVAL;
                op_ret = -1;
                goto out;
        }

        pthread_mutex_lock (&fdctx->lock);
        {
                fdctx->offset = stub->args.ftruncate_cbk.postbuf.st_size;
        }
        pthread_mutex_unlock (&fdctx->lock);

out:
        call_stub_destroy (stub);
        return op_ret;
}

int
glusterfs_ftruncate (glusterfs_file_t fd, off_t length)
{
        libglusterfs_client_fd_ctx_t    *fdctx = NULL;
        int                             op_ret = -1;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, fd, out);

        fdctx = libgf_get_fd_ctx (fd);
        if (!fdctx) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "No fd context present");
                errno = EBADF;
                goto out;
        }

        op_ret = libgf_client_ftruncate (fdctx->ctx, fd, length);

out:
        return op_ret;
}

int
libgf_client_link_cbk (call_frame_t *frame, void *cookie, xlator_t *this,
                                int32_t op_ret, int32_t op_errno,
                                inode_t *inode, struct stat *buf,
                                struct stat *preparent, struct stat *postparent)
{
        libgf_client_local_t            *local = frame->local;

        local->reply_stub = fop_link_cbk_stub (frame, NULL, op_ret, op_errno,
                                               inode, buf, preparent,
                                               postparent);

        LIBGF_REPLY_NOTIFY (local);

        return 0;
}

int
libgf_client_link (libglusterfs_client_ctx_t *ctx, loc_t *old, loc_t *new)
{
        call_stub_t                     *stub = NULL;
        libgf_client_local_t            *local = NULL;
        int                             op_ret = -1;
        inode_t                         *inode = NULL;
        struct stat                     *sbuf = NULL;

        LIBGF_CLIENT_FOP (ctx, stub, link, local, old, new);

        op_ret = stub->args.link_cbk.op_ret;
        errno = stub->args.link_cbk.op_errno;

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "old %s, new %s, status %d,"
                " errno %d", old->path, new->path, op_ret, errno);
        if (op_ret == -1)
                goto out;

        inode = stub->args.link_cbk.inode;
        sbuf = &stub->args.link_cbk.buf;
        libgf_transform_devnum (ctx, sbuf);
        inode_link (inode, new->parent, basename ((char *)new->path), sbuf);
        inode_lookup (inode);
        libgf_update_iattr_cache (inode, LIBGF_UPDATE_STAT, sbuf);

out:
        call_stub_destroy (stub);
        return op_ret;
}

int
glusterfs_glh_link (glusterfs_handle_t handle, const char *oldpath,
                        const char *newpath)
{
        libglusterfs_client_ctx_t       *ctx = handle;
        int                             op_ret = -1;
        loc_t                           old = {0,};
        loc_t                           new = {0,};
        char                            *oldname = NULL;
        char                            *newname = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, oldpath, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, newpath, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "old %s, new %s", oldpath,
                newpath);
        old.path = libgf_resolve_path_light ((char *)oldpath);
        if (!old.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

        op_ret = libgf_client_path_lookup (&old, ctx, 1);
        if (op_ret == -1) {
                errno = ENOENT;
                goto out;
        }

        oldname = strdup (old.path);
        op_ret = libgf_client_loc_fill (&old, ctx, 0, old.parent->ino,
                                                basename (oldname));
        if (op_ret == -1) {
                errno = EINVAL;
                goto out;
        }

        if (S_ISDIR (old.inode->st_mode)) {
                errno = EPERM;
                op_ret = -1;
                goto out;
        }

        new.path = libgf_resolve_path_light ((char *)newpath);
        if (!new.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

        op_ret = libgf_client_path_lookup (&new, ctx, 1);
        if (op_ret == 0) {
                errno = EEXIST;
                op_ret = -1;
                goto out;
        }

        newname = strdup (new.path);
        new.inode = inode_ref (old.inode);
        libgf_client_loc_fill (&new, ctx, 0, new.parent->ino,
                        basename (newname));
        op_ret = libgf_client_link (ctx, &old, &new);

out:
        if (oldname)
                FREE (oldname);
        if (newname)
                FREE (newname);
        libgf_client_loc_wipe (&old);
        libgf_client_loc_wipe (&new);

        return op_ret;
}

int
glusterfs_link (const char *oldpath, const char *newpath)
{
        struct vmp_entry        *oldentry = NULL;
        struct vmp_entry        *newentry = NULL;
        char                    *oldvpath = NULL;
        char                    *newvpath = NULL;
        int                     op_ret = -1;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, oldpath, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, newpath, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "old %s, new %s", oldpath,
                newpath);
        oldentry = libgf_vmp_search_entry ((char *)oldpath);
        if (!oldentry) {
                errno = ENODEV;
                goto out;
        }

        newentry = libgf_vmp_search_entry ((char *)newpath);
        if (!newentry) {
                errno =  ENODEV;
                goto out;
        }

        /* Cannot hard link across glusterfs mounts. */
        if (newentry != oldentry) {
                errno = EXDEV;
                goto out;
        }

        newvpath = libgf_vmp_virtual_path (newentry, newpath);
        oldvpath = libgf_vmp_virtual_path (oldentry, oldpath);
        op_ret = glusterfs_glh_link (newentry->handle, oldvpath, newvpath);
out:
        if (newvpath)
                free (newvpath);
        if (oldvpath)
                free (oldvpath);
        return op_ret;
}

int32_t
libgf_client_statfs_cbk (call_frame_t *frame, void *cookie, xlator_t *this,
                         int32_t op_ret, int32_t op_errno, struct statvfs *buf)
{
        libgf_client_local_t    *local = frame->local;

        local->reply_stub = fop_statfs_cbk_stub (frame, NULL, op_ret, op_errno,
                                                 buf);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}

int32_t
libgf_client_statvfs (libglusterfs_client_ctx_t *ctx, loc_t *loc,
                      struct statvfs *buf)
{
        call_stub_t             *stub = NULL;
        libgf_client_local_t    *local = NULL;
        int32_t                 op_ret = -1;

        /* statfs fop receives struct statvfs as an argument */

        /* libgf_client_statfs_cbk will be the callback, not
           libgf_client_statvfs_cbk. see definition of LIBGF_CLIENT_FOP
        */
        LIBGF_CLIENT_FOP (ctx, stub, statfs, local, loc);

        op_ret = stub->args.statfs_cbk.op_ret;
        errno = stub->args.statfs_cbk.op_errno;
        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s, status %d, errno %d",
                loc->path, op_ret, errno);
        if (op_ret == -1)
                goto out;

        if (buf)
                memcpy (buf, &stub->args.statfs_cbk.buf, sizeof (*buf));
out:
        call_stub_destroy (stub);
        return op_ret;
}

int
glusterfs_glh_statfs (glusterfs_handle_t handle, const char *path,
                        struct statfs *buf)
{
        struct statvfs                  stvfs = {0, };
        int32_t                         op_ret = -1;
        loc_t                           loc = {0, };
        libglusterfs_client_ctx_t       *ctx = handle;
        char                            *name = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        loc.path = libgf_resolve_path_light ((char *)path);
        if (!loc.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

        op_ret = libgf_client_path_lookup (&loc, ctx, 1);
        if (op_ret == -1) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                        "path lookup failed for (%s)", loc.path);
                goto out;
        }

        name = strdup (loc.path);
        op_ret = libgf_client_loc_fill (&loc, ctx, 0, loc.parent->ino,
                                        basename (name));
        if (op_ret == -1) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                                "libgf_client_loc_fill returned -1, "
                                "returning EINVAL");
                        errno = EINVAL;
                goto out;
        }

        op_ret = libgf_client_statvfs (ctx, &loc, &stvfs);
        if (op_ret == 0) {
#ifdef GF_SOLARIS_HOST_OS
		buf->f_fstyp = 0;
                buf->f_bsize = stvfs.f_bsize;
                buf->f_blocks = stvfs.f_blocks;
                buf->f_bfree = stvfs.f_bfree;
		buf->f_files = stvfs.f_bavail;
                buf->f_ffree = stvfs.f_ffree;
#else
                buf->f_type = 0;
                buf->f_bsize = stvfs.f_bsize;
                buf->f_blocks = stvfs.f_blocks;
                buf->f_bfree = stvfs.f_bfree;
                buf->f_bavail = stvfs.f_bavail;
                buf->f_files = stvfs.f_bavail;
                buf->f_ffree = stvfs.f_ffree;
                /* FIXME: buf->f_fsid has either "val" or "__val" as member
                   based on conditional macro expansion. see definition of
                   fsid_t - Raghu
                   It seems have different structure member names on
                   different archs, so I am stepping down to doing a struct
                   to struct copy. :Shehjar
                */
                memcpy (&buf->f_fsid, &stvfs.f_fsid, sizeof (stvfs.f_fsid));
                buf->f_namelen = stvfs.f_namemax;
#endif
        }

out:
        if (name)
                FREE (name);
        libgf_client_loc_wipe (&loc);
        return op_ret;
}

int
glusterfs_statfs (const char *path, struct statfs *buf)
{
        struct vmp_entry        *entry = NULL;
        char                    *vpath = NULL;
        int                     op_ret = -1;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, buf, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        op_ret = glusterfs_glh_statfs (entry->handle, vpath, buf);
out:
        if (vpath)
                free (vpath);
        return op_ret;
}

int
glusterfs_glh_statvfs (glusterfs_handle_t handle, const char *path,
                                struct statvfs *buf)
{
        int32_t                         op_ret = -1;
        loc_t                           loc = {0, };
        libglusterfs_client_ctx_t       *ctx = handle;
        char                            *name = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        loc.path = libgf_resolve_path_light ((char *)path);
        if (!loc.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }
        op_ret = libgf_client_path_lookup (&loc, ctx, 1);
        if (op_ret == -1) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                        "path lookup failed for (%s)", loc.path);
                goto out;
        }

        name = strdup (loc.path);
        op_ret = libgf_client_loc_fill (&loc, ctx, 0, loc.parent->ino,
                                                basename (name));
	if (op_ret == -1) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                                "libgf_client_loc_fill returned -1, returning"
                                " EINVAL");
                errno = EINVAL;
                goto out;
	}

        op_ret = libgf_client_statvfs (ctx, &loc, buf);
        if (op_ret != -1)
                /* Should've been a call to libgf_transform_devnum but
                 * that only handles struct stat
                 */
                buf->f_fsid = (unsigned long)ctx->fake_fsid;

out:
        if (name)
                FREE (name);
        libgf_client_loc_wipe (&loc);
        return op_ret;
}

int
glusterfs_statvfs (const char *path, struct statvfs *buf)
{
        struct vmp_entry        *entry = NULL;
        char                    *vpath = NULL;
        int                     op_ret = -1;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, buf, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        op_ret = glusterfs_glh_statvfs (entry->handle, vpath, buf);
out:
        if (vpath)
                free (vpath);
        return op_ret;
}

int32_t
libgf_client_rename_cbk (call_frame_t *frame, void *cookie, xlator_t *this,
                         int32_t op_ret, int32_t op_errno, struct stat *buf,
                         struct stat *preoldparent, struct stat *postoldparent,
                         struct stat *prenewparent, struct stat *postnewparent)
{
        libgf_client_local_t *local = frame->local;

        local->reply_stub = fop_rename_cbk_stub (frame, NULL, op_ret, op_errno,
                                                 buf, preoldparent,
                                                 postoldparent, prenewparent,
                                                 postnewparent);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}

int32_t
libgf_client_rename (libglusterfs_client_ctx_t *ctx, loc_t *oldloc,
                     loc_t *newloc)
{
        int                             op_ret = -1;
        libgf_client_local_t            *local = NULL;
        call_stub_t                     *stub = NULL;

        LIBGF_CLIENT_FOP (ctx, stub, rename, local, oldloc, newloc);

        op_ret = stub->args.rename_cbk.op_ret;
        errno = stub->args.rename_cbk.op_errno;

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "old %s, new %s, status %d, errno"
                " %d", oldloc->path, newloc->path, op_ret, errno);
        if (op_ret == -1)
                goto out;

        if (!libgf_get_inode_ctx (newloc->inode))
                libgf_alloc_inode_ctx (ctx, newloc->inode);

        libgf_transform_devnum (ctx, &stub->args.rename_cbk.buf);
        libgf_update_iattr_cache (newloc->inode, LIBGF_UPDATE_STAT,
                                        &stub->args.rename_cbk.buf);

        inode_unlink (oldloc->inode, oldloc->parent, oldloc->name);
out:
        call_stub_destroy (stub);
        return op_ret;
}

int
glusterfs_glh_rename (glusterfs_handle_t handle, const char *oldpath,
                      const char *newpath)
{
        int32_t                         op_ret = -1;
        loc_t                           oldloc = {0, }, newloc = {0, };
        libglusterfs_client_ctx_t       *ctx = handle;
        char                            *newname = NULL;
        char                            *oldname = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, oldpath, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, newpath, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "old %s, new %s", oldpath,
                newpath);
        oldloc.path = libgf_resolve_path_light ((char *)oldpath);
        if (!oldloc.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

        op_ret = libgf_client_path_lookup (&oldloc, ctx, 1);
        if (op_ret == -1) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                        "path lookup failed for (%s)", oldloc.path);
                goto out;
        }

        newloc.path = libgf_resolve_path_light ((char *)newpath);
        if (!newloc.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "Path compaction failed");
                goto out;
        }

        op_ret = libgf_client_path_lookup (&newloc, ctx, 1);

        oldname = strdup (oldloc.path);
        op_ret = libgf_client_loc_fill (&oldloc, ctx, 0, oldloc.parent->ino,
                                        basename (oldname));
	if (op_ret == -1) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                                "libgf_client_loc_fill returned -1,"
                                " returning EINVAL");
                errno = EINVAL;
                goto out;
        }

        newname = strdup (newloc.path);
        op_ret = libgf_client_loc_fill (&newloc, ctx, 0, newloc.parent->ino,
                                        basename (newname));
	if (op_ret == -1) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                                "libgf_client_loc_fill returned -1,"
                                " returning EINVAL");
                errno = EINVAL;
                goto out;
        }
        op_ret = libgf_client_rename (ctx, &oldloc, &newloc);

out:
        if (oldname)
                FREE (oldname);
        if (newname)
                FREE (newname);
        libgf_client_loc_wipe (&newloc);
        libgf_client_loc_wipe (&oldloc);

        return op_ret;
}


int
glusterfs_rename (const char *oldpath, const char *newpath)
{
        int                     op_ret = -1;
        struct vmp_entry        *new = NULL;
        struct vmp_entry        *old = NULL;
        char                    *oldvpath = NULL;
        char                    *newvpath = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, oldpath, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, newpath, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "Old %s, new %s", oldpath,
                newpath);
        old = libgf_vmp_search_entry ((char *)oldpath);
        if (!old) {
                errno = ENODEV;
                goto out;
        }

        new = libgf_vmp_search_entry ((char *)newpath);
        if (!new) {
                errno = ENODEV;
                goto out;
        }

        if (old != new) {
                errno = EXDEV;
                goto out;
        }

        oldvpath = libgf_vmp_virtual_path (old, oldpath);
        newvpath = libgf_vmp_virtual_path (new, newpath);
        op_ret = glusterfs_glh_rename (old->handle, oldvpath, newvpath);

out:
        if (oldvpath)
                free (oldvpath);
        if (newvpath)
                free (newvpath);
        return op_ret;
}

int32_t
libgf_client_utimens_cbk (call_frame_t *frame, void *cookie, xlator_t *this,
                                int32_t op_ret, int32_t op_errno,
                                struct stat *buf)
{
        libgf_client_local_t *local = frame->local;

        local->reply_stub = fop_utimens_cbk_stub (frame, NULL, op_ret,
                                                        op_errno, buf);

        LIBGF_REPLY_NOTIFY (local);

        return 0;
}

int32_t
libgf_client_utimens (libglusterfs_client_ctx_t *ctx, loc_t *loc,
                      struct timespec ts[2])
{
        int                             op_ret = -1;
        libgf_client_local_t            *local = NULL;
        call_stub_t                     *stub = NULL;
        struct stat                     *stbuf = NULL;

        LIBGF_CLIENT_FOP (ctx, stub, utimens, local, loc, ts);

        op_ret = stub->args.utimens_cbk.op_ret;
        errno = stub->args.utimens_cbk.op_errno;
        stbuf = &stub->args.utimens_cbk.buf;

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s, status %d, errno %d",
                loc->path, op_ret, errno);
        if (op_ret == -1)
                goto out;

        libgf_transform_devnum (ctx, stbuf);
        libgf_update_iattr_cache (loc->inode, LIBGF_UPDATE_STAT, stbuf);

out:
        call_stub_destroy (stub);
        return op_ret;
}

int
glusterfs_glh_utimes (glusterfs_handle_t handle, const char *path,
                        const struct timeval times[2])
{
        int32_t                         op_ret = -1;
        loc_t                           loc = {0, };
        libglusterfs_client_ctx_t       *ctx = handle;
        struct timespec                 ts[2] = {{0,},{0,}};
        char                            *name = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        loc.path = libgf_resolve_path_light ((char *)path);
        if (!loc.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

        op_ret = libgf_client_path_lookup (&loc, ctx, 1);
        if (op_ret == -1) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                        "path lookup failed for (%s)", loc.path);
                goto out;
        }

        name = strdup (loc.path);
        op_ret = libgf_client_loc_fill (&loc, ctx, 0, loc.parent->ino,
                                                basename (name));
        if (op_ret == -1) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                                "libgf_client_loc_fill returned -1"
                                " returning EINVAL");
                errno = EINVAL;
                goto out;
        }

        ts[0].tv_sec = times[0].tv_sec;
        ts[0].tv_nsec = times[0].tv_usec * 1000;
        ts[1].tv_sec = times[1].tv_sec;
        ts[1].tv_nsec = times[1].tv_usec * 1000;

        op_ret = libgf_client_utimens (ctx, &loc, ts);
out:
        if (name)
                FREE (name);
        libgf_client_loc_wipe (&loc);
        return op_ret;
}

int
glusterfs_utimes (const char *path, const struct timeval times[2])
{
        struct vmp_entry        *entry = NULL;
        char                    *vpath = NULL;
        int                     op_ret = -1;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        op_ret = glusterfs_glh_utimes (entry->handle, vpath, times);
out:
        if (vpath)
                free (vpath);
        return op_ret;
}

int
glusterfs_glh_utime (glusterfs_handle_t handle, const char *path,
                        const struct utimbuf *buf)
{
        int32_t                         op_ret = -1;
        loc_t                           loc = {0, };
        libglusterfs_client_ctx_t       *ctx = handle;
        struct timespec                 ts[2] = {{0,},{0,}};
        char                            *name = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        loc.path = libgf_resolve_path_light ((char *)path);
        if (!loc.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

        op_ret = libgf_client_path_lookup (&loc, ctx, 1);
        if (op_ret == -1) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                        "path lookup failed for (%s)", loc.path);
                goto out;
        }

        name = strdup (loc.path);
        op_ret = libgf_client_loc_fill (&loc, ctx, 0, loc.parent->ino,
                                                basename (name));
        if (op_ret == -1) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                                "libgf_client_loc_fill returned -1,"
                                " returning EINVAL");
                errno = EINVAL;
                goto out;
        }

        ts[0].tv_sec = buf->actime;
        ts[0].tv_nsec = 0;

        ts[1].tv_sec = buf->modtime;
        ts[1].tv_nsec = 0;

        op_ret = libgf_client_utimens (ctx, &loc, ts);
out:
        if (name)
                FREE (name);
        libgf_client_loc_wipe (&loc);
        return op_ret;
}

int
glusterfs_utime (const char *path, const struct utimbuf *buf)
{
        struct vmp_entry        *entry = NULL;
        char                    *vpath = NULL;
        int                     op_ret = -1;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, buf, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        op_ret = glusterfs_glh_utime (entry->handle, vpath, buf);
out:
        if (vpath)
                free (vpath);
        return op_ret;
}

static int32_t
libgf_client_mknod_cbk (call_frame_t *frame, void *cookie, xlator_t *this,
                                int32_t op_ret, int32_t op_errno,
                                inode_t *inode, struct stat *buf,
                                struct stat *preparent, struct stat *postparent)
{
        libgf_client_local_t *local = frame->local;

        local->reply_stub = fop_mknod_cbk_stub (frame, NULL, op_ret, op_errno,
                                                inode, buf, preparent,
                                                postparent);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}

static int32_t
libgf_client_mknod (libglusterfs_client_ctx_t *ctx, loc_t *loc, mode_t mode,
                    dev_t rdev)
{
        int32_t                 op_ret = -1;
        call_stub_t             *stub = NULL;
        libgf_client_local_t    *local = NULL;
        inode_t                 *inode = NULL;

        LIBGF_CLIENT_FOP (ctx, stub, mknod, local, loc, mode, rdev);

        op_ret = stub->args.mknod_cbk.op_ret;
        errno = stub->args.mknod_cbk.op_errno;
        if (op_ret == -1)
                goto out;

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s, status %d, errno %d",
                loc->path, op_ret, errno);
        inode = stub->args.mknod_cbk.inode;
        libgf_transform_devnum (ctx, &stub->args.mknod_cbk.buf);
        inode_link (inode, loc->parent, loc->name, &stub->args.mknod_cbk.buf);
        inode_lookup (inode);

        if (!libgf_alloc_inode_ctx (ctx, inode))
                libgf_alloc_inode_ctx (ctx, inode);

        libgf_update_iattr_cache (inode, LIBGF_UPDATE_STAT,
                                        &stub->args.mknod_cbk.buf);

out:
	call_stub_destroy (stub);
        return op_ret;
}

int
glusterfs_glh_mknod(glusterfs_handle_t handle, const char *path, mode_t mode,
                        dev_t dev)
{
        libglusterfs_client_ctx_t       *ctx = handle;
        loc_t                           loc = {0, };
        char                            *name = NULL;
        int32_t                         op_ret = -1;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        loc.path = libgf_resolve_path_light ((char *)path);
        if (!loc.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

        op_ret = libgf_client_path_lookup (&loc, ctx, 1);
        if (op_ret == 0) {
                op_ret = -1;
                errno = EEXIST;
                goto out;
        }

        op_ret = libgf_client_path_lookup (&loc, ctx, 0);
        if (op_ret == -1) {
                errno = ENOENT;
                goto out;
        }

        name = strdup (loc.path);
        op_ret = libgf_client_loc_fill (&loc, ctx, 0, loc.parent->ino,
                                                basename (name));
	if (op_ret == -1) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                                "libgf_client_loc_fill returned -1, "
                                " returning EINVAL");
                errno = EINVAL;
                goto out;
        }

        loc.inode = inode_new (ctx->itable);
        op_ret = libgf_client_mknod (ctx, &loc, mode, dev);

out:
	libgf_client_loc_wipe (&loc);
	if (name)
                FREE (name);

	return op_ret;
}

int
glusterfs_mknod(const char *pathname, mode_t mode, dev_t dev)
{
        struct vmp_entry        *entry = NULL;
        char                    *vpath = NULL;
        int                     op_ret = -1;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, pathname, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", pathname);
        entry = libgf_vmp_search_entry ((char *)pathname);
        if (!entry) {
                errno = ENODEV;
               goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, pathname);
        op_ret = glusterfs_glh_mknod (entry->handle, vpath, mode, dev);
out:
        if (vpath)
                free (vpath);
        return op_ret;
}

int
glusterfs_glh_mkfifo (glusterfs_handle_t handle, const char *path, mode_t mode)
{

        libglusterfs_client_ctx_t       *ctx = handle;
        loc_t                           loc = {0, };
        char                            *name = NULL;
        int32_t                         op_ret = -1;
        dev_t                           dev = 0;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        loc.path = libgf_resolve_path_light ((char *)path);
        if (!loc.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Failed to resolve name");
                goto out;
        }

        op_ret = libgf_client_path_lookup (&loc, ctx, 1);
        if (op_ret == 0) {
                op_ret = -1;
                errno = EEXIST;
                goto out;
        }

        op_ret = libgf_client_path_lookup (&loc, ctx, 0);
        if (op_ret == -1) {
                errno = ENOENT;
                goto out;
        }

        name = strdup (loc.path);
        op_ret = libgf_client_loc_fill (&loc, ctx, 0, loc.parent->ino,
                                                basename (name));
        if (op_ret == -1) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                                "libgf_client_loc_fill returned -1, "
                                "returning EINVAL");
                errno = EINVAL;
                goto out;
        }

        loc.inode = inode_new (ctx->itable);
        op_ret = libgf_client_mknod (ctx, &loc, mode | S_IFIFO, dev);

out:
	libgf_client_loc_wipe (&loc);
        if (name)
                free (name);

        return op_ret;
}

int
glusterfs_mkfifo (const char *path, mode_t mode)
{
        struct vmp_entry        *entry = NULL;
        char                    *vpath = NULL;
        int                     op_ret = -1;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        op_ret = glusterfs_glh_mkfifo (entry->handle, vpath, mode);
out:
        if (vpath)
                free (vpath);
        return op_ret;
}

int32_t
libgf_client_unlink_cbk (call_frame_t *frame, void *cookie, xlator_t *this,
                         int32_t op_ret, int32_t op_errno,
                         struct stat *preparent, struct stat *postparent)
{
        libgf_client_local_t    *local = frame->local;

        local->reply_stub = fop_unlink_cbk_stub (frame, NULL, op_ret, op_errno,
                                                 preparent, postparent);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}

int
libgf_client_unlink (libglusterfs_client_ctx_t *ctx, loc_t *loc)
{
        int                             op_ret = -1;
        libgf_client_local_t            *local = NULL;
        call_stub_t                     *stub = NULL;

        LIBGF_CLIENT_FOP (ctx, stub, unlink, local, loc);

        op_ret = stub->args.unlink_cbk.op_ret;
        errno = stub->args.unlink_cbk.op_errno;

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", loc->path);
        if (op_ret == -1)
                goto out;

        inode_unlink (loc->inode, loc->parent, loc->name);

out:
        call_stub_destroy (stub);
        return op_ret;
}

int
glusterfs_glh_unlink (glusterfs_handle_t handle, const char *path)
{
        int32_t                         op_ret = -1;
        loc_t                           loc = {0, };
        libglusterfs_client_ctx_t       *ctx = handle;
        char                            *name = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        loc.path = libgf_resolve_path_light ((char *)path);
        if (!loc.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

        op_ret = libgf_client_path_lookup (&loc, ctx, 1);
        if (op_ret == -1) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                        "path lookup failed for (%s)", loc.path);
                goto out;
        }

        name = strdup (loc.path);
        op_ret = libgf_client_loc_fill (&loc, ctx, 0, loc.parent->ino,
                                                basename (name));
	if (op_ret == -1) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                                "libgf_client_loc_fill returned -1, "
                                " returning EINVAL");
                errno = EINVAL;
                goto out;
        }

        op_ret = libgf_client_unlink (ctx, &loc);

out:
        if (name)
                FREE (name);
        libgf_client_loc_wipe (&loc);
        return op_ret;
}

int
glusterfs_unlink (const char *path)
{
        struct vmp_entry        *entry = NULL;
        char                    *vpath = NULL;
        int                     op_ret = -1;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        op_ret = glusterfs_glh_unlink (entry->handle, vpath);
out:
        if (vpath)
                free (vpath);
        return op_ret;
}

static int32_t
libgf_client_symlink_cbk (call_frame_t *frame, void *cookie, xlator_t *this,
                                int32_t op_ret, int32_t op_errno,
                                inode_t *inode, struct stat *buf,
                                struct stat *preparent, struct stat *postparent)
{
        libgf_client_local_t *local = frame->local;

        local->reply_stub = fop_symlink_cbk_stub (frame, NULL, op_ret,
                                                  op_errno, inode, buf,
                                                  preparent, postparent);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}

int32_t
libgf_client_symlink (libglusterfs_client_ctx_t *ctx, const char *linkpath,
                      loc_t *loc)
{
        int                     op_ret = -1;
        libgf_client_local_t    *local = NULL;
        call_stub_t             *stub = NULL;
        inode_t                 *inode = NULL;

        LIBGF_CLIENT_FOP (ctx, stub, symlink, local, linkpath, loc);

        op_ret = stub->args.symlink_cbk.op_ret;
        errno = stub->args.symlink_cbk.op_errno;
        if (op_ret == -1)
                goto out;

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "target: %s, link: %s, status %d"
                " errno %d", linkpath, loc->path, op_ret, errno);
        inode = stub->args.symlink_cbk.inode;
        libgf_transform_devnum (ctx, &stub->args.symlink_cbk.buf);
        inode_link (inode, loc->parent, loc->name,
                        &stub->args.symlink_cbk.buf);
        inode_lookup (inode);
        if (!libgf_get_inode_ctx (inode))
                libgf_alloc_inode_ctx (ctx, inode);

        libgf_update_iattr_cache (inode, LIBGF_UPDATE_STAT,
                                        &stub->args.symlink_cbk.buf);
out:
        call_stub_destroy (stub);
        return op_ret;
}

int
glusterfs_glh_symlink (glusterfs_handle_t handle, const char *oldpath,
                                const char *newpath)
{
        int32_t                         op_ret = -1;
        libglusterfs_client_ctx_t       *ctx = handle;
        loc_t                           oldloc = {0, };
        loc_t                           newloc = {0, };
        char                            *oldname = NULL;
        char                            *newname = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, newpath, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "target: %s, link: %s", oldpath,
                newpath);
        /* Old path does not need to be interpreted or looked up */
        oldloc.path = strdup (oldpath);

	newloc.path = libgf_resolve_path_light ((char *)newpath);
        if (!newloc.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

	op_ret = libgf_client_path_lookup (&newloc, ctx, 1);
	if (op_ret == 0) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                        "new path (%s) already exists, "
                        " returning EEXIST", newloc.path);
                op_ret = -1;
                errno = EEXIST;
                goto out;
        }

        op_ret = libgf_client_path_lookup (&newloc, ctx, 0);
        if (op_ret == -1) {
                errno = ENOENT;
                goto out;
        }

        newloc.inode = inode_new (ctx->itable);
        newname = strdup (newloc.path);
        op_ret = libgf_client_loc_fill (&newloc, ctx, 0, newloc.parent->ino,
                                                basename (newname));

        if (op_ret == -1) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                                "libgf_client_loc_fill returned -1, "
                                "returning EINVAL");
                errno = EINVAL;
                goto out;
        }

        op_ret = libgf_client_symlink (ctx, oldpath, &newloc);

out:
        if (newname)
                FREE (newname);

        if (oldname)
                FREE (oldname);
        libgf_client_loc_wipe (&oldloc);
        libgf_client_loc_wipe (&newloc);
        return op_ret;
}

int
glusterfs_symlink (const char *oldpath, const char *newpath)
{
        struct vmp_entry        *entry = NULL;
        char                    *vpath = NULL;
        int                     op_ret = -1;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, oldpath, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, newpath, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "target: %s, link: %s", oldpath,
                newpath);
        entry = libgf_vmp_search_entry ((char *)newpath);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, newpath);
        op_ret = glusterfs_glh_symlink (entry->handle, oldpath, vpath);
out:
        if (vpath)
                free (vpath);
        return op_ret;
}


int32_t
libgf_client_readlink_cbk (call_frame_t *frame, void *cookie, xlator_t *this,
                                int32_t op_ret, int32_t op_errno,
                                const char *path, struct stat *sbuf)
{
        libgf_client_local_t    *local = frame->local;

        local->reply_stub = fop_readlink_cbk_stub (frame, NULL, op_ret,
                                                   op_errno, path, sbuf);

        LIBGF_REPLY_NOTIFY (local);
        return 0;
}

int32_t
libgf_client_readlink (libglusterfs_client_ctx_t *ctx, loc_t *loc, char *buf,
                       size_t bufsize)
{
        int                             op_ret = -1;
        libgf_client_local_t            *local = NULL;
        call_stub_t                     *stub = NULL;
        size_t                           cpy_size = 0;

        LIBGF_CLIENT_FOP (ctx, stub, readlink, local, loc, bufsize);

        op_ret = stub->args.readlink_cbk.op_ret;
        errno = stub->args.readlink_cbk.op_errno;

        if (op_ret != -1) {
                cpy_size = ((op_ret <= bufsize) ? op_ret : bufsize);
                memcpy (buf, stub->args.readlink_cbk.buf, cpy_size);
                op_ret = cpy_size;
                gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "link: %s, target: %s,"
                        " status %d, errno %d", loc->path, buf, op_ret, errno);
        } else
                gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "link: %s, status %d, "
                        "errno %d", loc->path, op_ret, errno);

        call_stub_destroy (stub);
        return op_ret;
}

ssize_t
glusterfs_glh_readlink (glusterfs_handle_t handle, const char *path, char *buf,
                                size_t bufsize)
{
        int32_t                         op_ret = -1;
        loc_t                           loc = {0, };
        libglusterfs_client_ctx_t       *ctx = handle;
        char                            *name = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        if (bufsize < 0) {
                errno = EINVAL;
                goto out;
        }

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

        loc.path = libgf_resolve_path_light ((char *)path);
        if (!loc.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

        op_ret = libgf_client_path_lookup (&loc, ctx, 1);
        if (op_ret == -1) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                        "path lookup failed for (%s)", loc.path);
                goto out;
        }

        name = strdup (loc.path);
        op_ret = libgf_client_loc_fill (&loc, ctx, 0, loc.parent->ino,
                                                basename (name));
        if (op_ret == -1) {
                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                                "libgf_client_loc_fill returned -1, "
                                "returning EINVAL");
                errno = EINVAL;
                goto out;
        }

        op_ret = libgf_client_readlink (ctx, &loc, buf, bufsize);

out:
        if (name)
                FREE (name);

        libgf_client_loc_wipe (&loc);
        return op_ret;
}

ssize_t
glusterfs_readlink (const char *path, char *buf, size_t bufsize)
{
        struct vmp_entry        *entry = NULL;
        char                    *vpath = NULL;
        int                     op_ret = -1;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);
        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, buf, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, path);
        op_ret = glusterfs_glh_readlink (entry->handle, vpath, buf, bufsize);
out:
        if (vpath)
                free (vpath);
        return op_ret;
}

char *
glusterfs_glh_realpath (glusterfs_handle_t handle, const char *path,
                                char *resolved_path)
{
        char                            *buf = NULL;
        char                            *rpath = NULL;
        char                            *start = NULL, *end = NULL;
        char                            *dest = NULL;
        libglusterfs_client_ctx_t       *ctx = handle;
        long int                        path_max = 0;
        char                            *ptr = NULL;
        struct stat                     stbuf = {0, };
        long int                        new_size = 0;
        char                            *new_rpath = NULL;
        int                             dest_offset = 0;
        char                            *rpath_limit = 0;
        int                             ret = 0, num_links = 0;
        char                            *vpath = NULL, *tmppath = NULL;
        char                             absolute_path[PATH_MAX];

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, ctx, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, path, out);

#ifdef PATH_MAX
        path_max = PATH_MAX;
#else
        path_max = pathconf (path, _PC_PATH_MAX);
        if (path_max <= 0) {
                path_max = 1024;
        }
#endif

        if (resolved_path == NULL) {
                rpath = CALLOC (1, path_max);
                if (rpath == NULL) {
                        errno = ENOMEM;
                        goto out;
                }
        } else {
                rpath = resolved_path;
        }

        rpath_limit = rpath + path_max;

        if (path[0] == '/') {
                rpath[0] = '/';
                dest = rpath + 1;
        } else {
                /*
                   FIXME: can $CWD be a valid path on glusterfs server? hence is
                   it better to handle this case or just return EINVAL for
                   relative paths?
                */
                ptr = getcwd (rpath, path_max);
                if (ptr == NULL) {
                        goto err;
                }
                dest = rpath + strlen (rpath);
        }

        for (start = end = (char *)path; *end; start = end) {
                if (dest[-1] != '/') {
                        *dest++ = '/';
                }

                while (*start == '/') {
                        start++;
                }

                for (end = start; *end && *end != '/'; end++);

                if ((end - start) == 0) {
                        break;
                }

                if ((end - start == 1) && (start[0] == '.')) {
                        /* do nothing */
                } else if (((end - start) == 2) && (start[0] == '.')
                           && (start[1] == '.')) {
                        if (dest > rpath + 1) {
                                while (--dest[-1] != '/');
                        }
                } else {
                        if ((dest + (end - start + 1)) >= rpath_limit) {
                                if (resolved_path == NULL) {
                                        errno = ENAMETOOLONG;
                                        if (dest > rpath + 1)
                                                dest--;
                                        *dest = '\0';
                                        goto err;
                                }

                                dest_offset = dest - rpath;
                                new_size = rpath_limit - rpath;
                                if ((end - start + 1) > path_max) {
                                        new_size = (end - start + 1);
                                } else {
                                        new_size = path_max;
                                }

                                new_rpath = realloc (rpath, new_size);
                                if (new_rpath == NULL) {
                                        goto err;
                                }


                                dest = new_rpath + dest_offset;
                                rpath = new_rpath;
                                rpath_limit = rpath + new_size;
                        }

                        memcpy (dest, start, end - start);
                        dest +=  end - start;
                        *dest = '\0';

                        ret = glusterfs_glh_lstat (handle, rpath, &stbuf);
                        if (ret == -1) {
                                gf_log ("libglusterfsclient", GF_LOG_ERROR,
                                        "glusterfs_glh_stat returned -1 for"
                                        " path (%s):(%s)", rpath,
                                        strerror (errno));
                                goto err;
                        }

                        if (S_ISLNK (stbuf.st_mode)) {
                                buf = calloc (1, path_max);
                                if (buf == NULL) {
                                        errno = ENOMEM;
                                        goto err;
                                }

                                if (++num_links > MAXSYMLINKS)
                                {
                                        errno = ELOOP;
                                        FREE (buf);
                                        goto err;
                                }

                                ret = glusterfs_glh_readlink (handle, rpath,
                                                              buf,
                                                              path_max - 1);
                                if (ret < 0) {
                                        gf_log ("libglusterfsclient",
                                                GF_LOG_ERROR,
                                                "glusterfs_readlink returned %d"
                                                " for path (%s):(%s)",
                                                ret, rpath, strerror (errno));
                                        FREE (buf);
                                        goto err;
                                }
                                buf[ret] = '\0';

                                if (buf[0] != '/') {
                                        tmppath = strdup (rpath);
                                        tmppath = dirname (tmppath);
                                        sprintf (absolute_path, "%s/%s",
                                                 tmppath, buf);
                                        FREE (buf);
                                        buf = libgf_resolve_path_light ((char *)absolute_path);
                                        FREE (tmppath);
                                }

                                rpath = glusterfs_glh_realpath (handle, buf,
                                                                rpath);
                                FREE (buf);
                                if (rpath == NULL) {
                                        goto out;
                                }
                                dest = rpath + strlen (rpath);

                        } else if (!S_ISDIR (stbuf.st_mode) && *end != '\0') {
                                errno = ENOTDIR;
                                goto err;
                        }
                }
        }
        if (dest > rpath + 1 && dest[-1] == '/')
                --dest;
        *dest = '\0';

out:
        if (vpath)
                FREE (vpath);
        return rpath;

err:
        if (vpath)
                FREE (vpath);
        if (resolved_path == NULL) {
                FREE (rpath);
        }

        return NULL;
}

char *
glusterfs_realpath (const char *path, char *resolved_path)
{
        struct vmp_entry        *entry = NULL;
        char                    *vpath = NULL;
        char                    *res = NULL;
        char                    *realp = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        entry = libgf_vmp_search_entry ((char *)path);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        realp = CALLOC (PATH_MAX, sizeof (char));
        if (!realp)
                goto out;

        vpath = libgf_vmp_virtual_path (entry, path);
        res = glusterfs_glh_realpath (entry->handle, vpath, resolved_path);
        if (!res)
                goto out;

        strncpy (realp, entry->vmp, entry->vmplen-1);
        strcat (realp, res);
        strcpy (resolved_path, realp);
        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s, resolved %s", path,
                resolved_path);
out:
        if (vpath)
                free (vpath);

        return realp;
}

int
glusterfs_glh_remove (glusterfs_handle_t handle, const char *path)
{
        loc_t                           loc = {0, };
        int                             op_ret = -1;
        libglusterfs_client_ctx_t       *ctx = handle;
        char                            *name = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, handle, out);
        GF_VALIDATE_ABSOLUTE_PATH_OR_GOTO (LIBGF_XL_NAME, path, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", path);
        loc.path = libgf_resolve_path_light ((char *)path);
        if (!loc.path) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "Path compaction failed");
                goto out;
        }

        op_ret = libgf_client_path_lookup (&loc, ctx, 1);
        if (op_ret == -1)
                goto out;

        name = strdup (loc.path);
        op_ret = libgf_client_loc_fill (&loc, ctx, 0, loc.parent->ino,
                                        basename (name));
        if (op_ret == -1)
                goto out;

        if (S_ISDIR (loc.inode->st_mode))
                op_ret = libgf_client_rmdir (ctx, &loc);
        else
                op_ret = libgf_client_unlink (ctx, &loc);

out:
        if (name)
                FREE (name);
        return op_ret;

}

int
glusterfs_remove(const char *pathname)
{
        struct vmp_entry        *entry = NULL;
        int                     op_ret = -1;
        char                    *vpath = NULL;

        GF_VALIDATE_OR_GOTO (LIBGF_XL_NAME, pathname, out);

        gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "path %s", pathname);
        entry = libgf_vmp_search_entry ((char *)pathname);
        if (!entry) {
                errno = ENODEV;
                goto out;
        }

        vpath = libgf_vmp_virtual_path (entry, pathname);
        op_ret = glusterfs_glh_remove (entry->handle, vpath);

out:
        if (vpath)
                FREE (vpath);
        return op_ret;
}

void
glusterfs_rewinddir (glusterfs_dir_t dirfd)
{
        libglusterfs_client_fd_ctx_t    *fd_ctx = NULL;

        fd_ctx = libgf_get_fd_ctx ((fd_t *)dirfd);
        if (!fd_ctx) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "No fd context present");
                errno = EBADF;
                goto out;
        }

        pthread_mutex_lock (&fd_ctx->lock);
        {
                fd_ctx->offset = 0;
                gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "Offset: %"PRIu64,
                        fd_ctx->offset);
        }
        pthread_mutex_unlock (&fd_ctx->lock);

out:
        return;
}

void
glusterfs_seekdir (glusterfs_dir_t dirfd, off_t offset)
{
        libglusterfs_client_fd_ctx_t    *fd_ctx = NULL;

        fd_ctx = libgf_get_fd_ctx ((fd_t *)dirfd);
        if (!fd_ctx) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "No fd context present");
                goto out;
        }

        pthread_mutex_lock (&fd_ctx->lock);
        {
                fd_ctx->offset = offset;
                gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "Offset: %"PRIu64,
                        fd_ctx->offset);
        }
        pthread_mutex_unlock (&fd_ctx->lock);

out:
        return;
}

off_t
glusterfs_telldir (glusterfs_dir_t dirfd)
{
        libglusterfs_client_fd_ctx_t    *fd_ctx = NULL;
	off_t                           off = -1;

        fd_ctx = libgf_get_fd_ctx ((fd_t *)dirfd);
        if (!fd_ctx) {
                gf_log (LIBGF_XL_NAME, GF_LOG_ERROR, "No fd context present");
                errno = EBADF;
                goto out;
        }

        pthread_mutex_lock (&fd_ctx->lock);
        {
                off = fd_ctx->offset;
                gf_log (LIBGF_XL_NAME, GF_LOG_DEBUG, "Offset: %"PRIu64,
                        fd_ctx->offset);
        }
        pthread_mutex_unlock (&fd_ctx->lock);

out:
        return off;
}


struct libgf_client_sendfile_data {
        int                reads_sent;
        int                reads_completed;
        int                out_fd;
        int32_t            op_ret;
        int32_t            op_errno;
        pthread_mutex_t    lock;
        pthread_cond_t     cond;
};

int
libgf_client_sendfile_read_cbk (int op_ret, int op_errno,
                                glusterfs_iobuf_t *buf, void *cbk_data)
{
        struct libgf_client_sendfile_data *sendfile_data = cbk_data;
        int                                bytes = 0;

        if (op_ret > 0) {
                bytes = writev (sendfile_data->out_fd, buf->vector, buf->count);
                if (bytes != op_ret) {
                        op_ret = -1;
                        op_errno = errno;
                }

                glusterfs_free (buf);
        }

        pthread_mutex_lock (&sendfile_data->lock);
        {
                if (sendfile_data->op_ret != -1) {
                        if (op_ret == -1) {
                                sendfile_data->op_ret = -1;
                                sendfile_data->op_errno = op_errno;
                        } else {
                                sendfile_data->op_ret += op_ret;
                        }
                }

                sendfile_data->reads_completed++;