File: linux.c

package info (click to toggle)
parted 3.2-7
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 15,312 kB
  • ctags: 12,128
  • sloc: ansic: 68,106; sh: 18,156; makefile: 632; perl: 179; python: 45; asm: 36; sed: 16
file content (3269 lines) | stat: -rw-r--r-- 109,063 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
/* libparted - a library for manipulating disk partitions
    Copyright (C) 1999-2014 Free Software Foundation, Inc.

    This program 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.

    This program 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/>.
*/

#define PROC_DEVICES_BUFSIZ 16384

#include <config.h>
#include <arch/linux.h>
#include <linux/blkpg.h>
#include <parted/parted.h>
#include <parted/debug.h>
#if defined __s390__ || defined __s390x__
#include <parted/fdasd.h>
#endif

#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <stdio.h>
#include <syscall.h>
#include <unistd.h>
#include <stdbool.h>
#include <dirent.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/utsname.h>        /* for uname() */
#include <scsi/scsi.h>
#include <assert.h>
#ifdef ENABLE_DEVICE_MAPPER
#include <libdevmapper.h>
#endif

#include "../architecture.h"
#include "dirname.h"
#include "xstrtol.h"
#include "xalloc.h"

#if ENABLE_NLS
#  include <libintl.h>
#  define _(String) dgettext (PACKAGE, String)
#else
#  define _(String) (String)
#endif /* ENABLE_NLS */

/* The __attribute__ feature is available in gcc versions 2.5 and later.
   The __-protected variants of the attributes 'format' and 'printf' are
   accepted by gcc versions 2.6.4 (effectively 2.7) and later.  */
#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 7)
# define _GL_ATTRIBUTE_FORMAT(spec) __attribute__ ((__format__ spec))
#else
# define _GL_ATTRIBUTE_FORMAT(spec) /* empty */
#endif

#define STRPREFIX(a, b) (strncmp (a, b, strlen (b)) == 0)

#define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))

#ifndef __NR__llseek
#define __NR__llseek 140
#endif

#ifndef SCSI_IOCTL_SEND_COMMAND
#define SCSI_IOCTL_SEND_COMMAND 1
#endif

/* from <linux/hdreg.h> */
#define HDIO_GETGEO             0x0301  /* get device geometry */
#define HDIO_GET_IDENTITY       0x030d  /* get IDE identification info */

#define RD_MODE (O_RDONLY)
#define WR_MODE (O_WRONLY)
#define RW_MODE (O_RDWR)

struct hd_geometry {
        unsigned char heads;
        unsigned char sectors;
        unsigned short cylinders;
        unsigned long start;
};

struct ata7_sectinfo {
        int valid1:1;
        int valid2:1;
        int rsv:26;
        int multiplier:4;
};

/* structure returned by HDIO_GET_IDENTITY, as per ANSI ATA2 rev.2f spec */
struct hd_driveid {
        unsigned short  config;         /* lots of obsolete bit flags */
        unsigned short  cyls;           /* "physical" cyls */
        unsigned short  reserved2;      /* reserved (word 2) */
        unsigned short  heads;          /* "physical" heads */
        unsigned short  track_bytes;    /* unformatted bytes per track */
        unsigned short  sector_bytes;   /* unformatted bytes per sector */
        unsigned short  sectors;        /* "physical" sectors per track */
        unsigned short  vendor0;        /* vendor unique */
        unsigned short  vendor1;        /* vendor unique */
        unsigned short  vendor2;        /* vendor unique */
        unsigned char   serial_no[20];  /* 0 = not_specified */
        unsigned short  buf_type;
        unsigned short  buf_size;       /* 512 byte increments;
                                                         0 = not_specified */
        unsigned short  ecc_bytes;      /* for r/w long cmds;
                                                         0 = not_specified */
        unsigned char   fw_rev[8];      /* 0 = not_specified */
        char            model[40];      /* 0 = not_specified */
        unsigned char   max_multsect;   /* 0=not_implemented */
        unsigned char   vendor3;        /* vendor unique */
        unsigned short  dword_io;       /* 0=not_implemented; 1=implemented */
        unsigned char   vendor4;        /* vendor unique */
        unsigned char   capability;     /* bits 0:DMA 1:LBA 2:IORDYsw
                                                3:IORDYsup*/
        unsigned short  reserved50;     /* reserved (word 50) */
        unsigned char   vendor5;        /* vendor unique */
        unsigned char   tPIO;           /* 0=slow, 1=medium, 2=fast */
        unsigned char   vendor6;        /* vendor unique */
        unsigned char   tDMA;           /* 0=slow, 1=medium, 2=fast */
        unsigned short  field_valid;    /* bits 0:cur_ok 1:eide_ok */
        unsigned short  cur_cyls;       /* logical cylinders */
        unsigned short  cur_heads;      /* logical heads */
        unsigned short  cur_sectors;    /* logical sectors per track */
        unsigned short  cur_capacity0;  /* logical total sectors on drive */
        unsigned short  cur_capacity1;  /*  (2 words, misaligned int)     */
        unsigned char   multsect;       /* current multiple sector count */
        unsigned char   multsect_valid; /* when (bit0==1) multsect is ok */
        unsigned int    lba_capacity;   /* total number of sectors */
        unsigned short  dma_1word;      /* single-word dma info */
        unsigned short  dma_mword;      /* multiple-word dma info */
        unsigned short  eide_pio_modes; /* bits 0:mode3 1:mode4 */
        unsigned short  eide_dma_min;   /* min mword dma cycle time (ns) */
        unsigned short  eide_dma_time;  /* recommended mword dma cycle
                                           time (ns) */
        unsigned short  eide_pio;       /* min cycle time (ns), no IORDY  */
        unsigned short  eide_pio_iordy; /* min cycle time (ns), with IORDY */
        unsigned short  words69_70[2];  /* reserved words 69-70 */
        /* HDIO_GET_IDENTITY currently returns only words 0 through 70 */
        unsigned short  words71_74[4];  /* reserved words 71-74 */
        unsigned short  queue_depth;    /*  */
        unsigned short  words76_79[4];  /* reserved words 76-79 */
        unsigned short  major_rev_num;  /*  */
        unsigned short  minor_rev_num;  /*  */
        unsigned short  command_set_1;  /* bits 0:Smart 1:Security 2:Removable
                                                3:PM */
        unsigned short  command_set_2;  /* bits 14:Smart Enabled 13:0 zero */
        unsigned short  cfsse;          /* command set-feature supported
                                           extensions */
        unsigned short  cfs_enable_1;   /* command set-feature enabled */
        unsigned short  cfs_enable_2;   /* command set-feature enabled */
        unsigned short  csf_default;    /* command set-feature default */
        unsigned short  dma_ultra;      /*  */
        unsigned short  word89;         /* reserved (word 89) */
        unsigned short  word90;         /* reserved (word 90) */
        unsigned short  CurAPMvalues;   /* current APM values */
        unsigned short  word92;         /* reserved (word 92) */
        unsigned short  hw_config;      /* hardware config */
        unsigned short  words94_105[12];/* reserved words 94-105 */
        struct ata7_sectinfo ata7_sectinfo; /* ATAPI/ATA7 physical and logical
                                               sector size */
        unsigned short  words107_116[10];/* reserved words 107-116 */
        unsigned int    logical_sectsize;/* ATAPI/ATA7 logical sector size */
        unsigned short  words119_125[7];/* reserved words 119-125 */
        unsigned short  last_lun;       /* reserved (word 126) */
        unsigned short  word127;        /* reserved (word 127) */
        unsigned short  dlf;            /* device lock function
                                         * 15:9 reserved
                                         * 8    security level 1:max 0:high
                                         * 7:6  reserved
                                         * 5    enhanced erase
                                         * 4    expire
                                         * 3    frozen
                                         * 2    locked
                                         * 1    en/disabled
                                         * 0    capability
                                         */
        unsigned short  csfo;           /* current set features options
                                         * 15:4 reserved
                                         * 3    auto reassign
                                         * 2    reverting
                                         * 1    read-look-ahead
                                         * 0    write cache
                                         */
        unsigned short  words130_155[26];/* reserved vendor words 130-155 */
        unsigned short  word156;
        unsigned short  words157_159[3]; /* reserved vendor words 157-159 */
        unsigned short  words160_255[95];/* reserved words 160-255 */
};

/* from <linux/fs.h> */
#define BLKRRPART  _IO(0x12,95) /* re-read partition table */
#define BLKGETSIZE _IO(0x12,96) /* return device size */
#define BLKFLSBUF  _IO(0x12,97) /* flush buffer cache */
#define BLKSSZGET  _IO(0x12,104) /* get block device sector size */
#define BLKGETLASTSECT  _IO(0x12,108) /* get last sector of block device */
#define BLKSETLASTSECT  _IO(0x12,109) /* set last sector of block device */

/* return device size in bytes (u64 *arg) */
#define BLKGETSIZE64 _IOR(0x12,114,size_t)

struct blkdev_ioctl_param {
        unsigned int block;
        size_t content_length;
        char * block_contents;
};

/* from <linux/major.h> */
#define IDE0_MAJOR              3
#define IDE1_MAJOR              22
#define IDE2_MAJOR              33
#define IDE3_MAJOR              34
#define IDE4_MAJOR              56
#define IDE5_MAJOR              57
#define SCSI_CDROM_MAJOR        11
#define SCSI_DISK0_MAJOR        8
#define SCSI_DISK1_MAJOR        65
#define SCSI_DISK2_MAJOR        66
#define SCSI_DISK3_MAJOR        67
#define SCSI_DISK4_MAJOR        68
#define SCSI_DISK5_MAJOR        69
#define SCSI_DISK6_MAJOR        70
#define SCSI_DISK7_MAJOR        71
#define SCSI_DISK8_MAJOR        128
#define SCSI_DISK9_MAJOR        129
#define SCSI_DISK10_MAJOR       130
#define SCSI_DISK11_MAJOR       131
#define SCSI_DISK12_MAJOR       132
#define SCSI_DISK13_MAJOR       133
#define SCSI_DISK14_MAJOR       134
#define SCSI_DISK15_MAJOR       135
#define COMPAQ_SMART2_MAJOR     72
#define COMPAQ_SMART2_MAJOR1    73
#define COMPAQ_SMART2_MAJOR2    74
#define COMPAQ_SMART2_MAJOR3    75
#define COMPAQ_SMART2_MAJOR4    76
#define COMPAQ_SMART2_MAJOR5    77
#define COMPAQ_SMART2_MAJOR6    78
#define COMPAQ_SMART2_MAJOR7    79
#define COMPAQ_SMART_MAJOR      104
#define COMPAQ_SMART_MAJOR1     105
#define COMPAQ_SMART_MAJOR2     106
#define COMPAQ_SMART_MAJOR3     107
#define COMPAQ_SMART_MAJOR4     108
#define COMPAQ_SMART_MAJOR5     109
#define COMPAQ_SMART_MAJOR6     110
#define COMPAQ_SMART_MAJOR7     111
#define DAC960_MAJOR            48
#define ATARAID_MAJOR           114
#define I2O_MAJOR1              80
#define I2O_MAJOR2              81
#define I2O_MAJOR3              82
#define I2O_MAJOR4              83
#define I2O_MAJOR5              84
#define I2O_MAJOR6              85
#define I2O_MAJOR7              86
#define I2O_MAJOR8              87
#define UBD_MAJOR               98
#define DASD_MAJOR              94
#define VIODASD_MAJOR           112
#define AOE_MAJOR               152
#define SX8_MAJOR1              160
#define SX8_MAJOR2              161
#define XVD_MAJOR               202
#define SDMMC_MAJOR             179
#define LOOP_MAJOR              7
#define MD_MAJOR                9

#define SCSI_BLK_MAJOR(M) (                                             \
                (M) == SCSI_DISK0_MAJOR                                 \
                || (M) == SCSI_CDROM_MAJOR                              \
                || ((M) >= SCSI_DISK1_MAJOR && (M) <= SCSI_DISK7_MAJOR) \
                || ((M) >= SCSI_DISK8_MAJOR && (M) <= SCSI_DISK15_MAJOR))

/* Maximum number of partitions supported by linux. */
#define MAX_NUM_PARTS		64

static char* _device_get_part_path (PedDevice const *dev, int num);
static int _partition_is_mounted_by_path (const char* path);
static unsigned int _device_get_partition_range(PedDevice const* dev);


static int
_read_fd (int fd, char **buf)
{
        char* p;
        size_t size = PROC_DEVICES_BUFSIZ;
        int s, filesize = 0;

        *buf = malloc (size * sizeof (char));
        if (*buf == 0) {
                return -1;
        }

        do {
                p = &(*buf) [filesize];
                s = read (fd, p, PROC_DEVICES_BUFSIZ);
                /* exit if there is an error or EOF is reached */
                if (s <= 0)
                        break;
                filesize += s;
                size += s;
                char *new_buf = realloc (*buf, size);
                if (new_buf == NULL) {
                        int saved_errno = errno;
                        free (*buf);
                        errno = saved_errno;
                        return -1;
                }
                *buf = new_buf;
        } while (1);

        if (filesize == 0 && s < 0) {
                free (*buf);
                *buf = NULL;
                return -1;
        } else {
                char *new_buf = realloc (*buf, filesize + 1);
                if (new_buf == NULL) {
                        int saved_errno = errno;
                        free (*buf);
                        errno = saved_errno;
                        return -1;
                }
                *buf = new_buf;
                (*buf)[filesize] = '\0';
        }

        return filesize;
}

static int
_major_type_in_devices (int major, const char* type)
{
        int fd;
        char* buf = NULL;
        char* line;
        char* end;
        int bd = 0;
        char c;

        fd = open ("/proc/devices", O_RDONLY);
        if (fd < 0)
                return 0;

        if (_read_fd(fd, &buf) < 0) {
                close(fd);
                return 0;
        }

        line = buf;
        end = strchr(line, '\n');
        while (end) {
                char *name;
                int maj;

                c = *end;
                *end = '\0';

                if (!bd) {
                        if (!strncmp(line, "Block devices:", 14))
                                bd = 1;
                        goto next;
                }

                name = strrchr(line, ' ');
                if (!name || strcmp(name+1, type))
                        goto next;

                maj = strtol(line, &name, 10);
                if (maj == major) {
                        free(buf);
                        close(fd);
                        return 1;
                }

next:
                *end = c;
                line = end+1;
                end = strchr(line, '\n');
        }
        free(buf);
        close(fd);
        return 0;
}

static int
_is_ide_major (int major)
{
        switch (major) {
                case IDE0_MAJOR:
                case IDE1_MAJOR:
                case IDE2_MAJOR:
                case IDE3_MAJOR:
                case IDE4_MAJOR:
                case IDE5_MAJOR:
                        return 1;

                default:
                        return 0;
        }
}

static int
_is_cpqarray_major (int major)
{
        return ((COMPAQ_SMART2_MAJOR <= major && major <= COMPAQ_SMART2_MAJOR7)
             || (COMPAQ_SMART_MAJOR <= major && major <= COMPAQ_SMART_MAJOR7));
}

static int
_is_i2o_major (int major)
{
        return (I2O_MAJOR1 <= major && major <= I2O_MAJOR8);
}

static int
_is_sx8_major (int major)
{
        return (SX8_MAJOR1 <= major && major <= SX8_MAJOR2);
}

static int
_is_virtblk_major (int major)
{
        return _major_type_in_devices (major, "virtblk");
}

#ifdef ENABLE_DEVICE_MAPPER
static int
_dm_task_run_wait (struct dm_task *task, uint32_t cookie)
{
        int rc = 0;

        rc = dm_task_run (task);
        dm_udev_wait (cookie);

        return rc;
}

static int
_is_dm_major (int major)
{
        return _major_type_in_devices (major, "device-mapper");
}

static int
_dm_maptype (PedDevice *dev)
{
        LinuxSpecific*  arch_specific = LINUX_SPECIFIC (dev);
        struct dm_task *dmt;
        uint64_t start, length;
        char *target_type = NULL;
        char *params;
        int r = -1;
        const char* dev_dir = getenv ("DM_DEV_DIR");

        if (dev_dir && *dev_dir && !dm_set_dev_dir(dev_dir))
                return r;

        if (!(dmt = dm_task_create(DM_DEVICE_TABLE)))
                return r;

        if (!dm_task_set_major_minor(dmt, arch_specific->major,
                                     arch_specific->minor, 0))
                goto bad;

        dm_task_no_open_count(dmt);

        if (!dm_task_run(dmt))
                goto bad;

        dm_get_next_target(dmt, NULL, &start, &length, &target_type, &params);

        arch_specific->dmtype = strdup(target_type ? target_type : "NO-TARGET");
        if (arch_specific->dmtype == NULL)
                goto bad;
        r = 0;
bad:
        dm_task_destroy(dmt);
        return r;
}

/* Return nonzero if device-mapper device, DEVPATH, is part of a dmraid
   array.  Use the heuristic of checking for the string "DMRAID-" at the
   start of its UUID.  */
static int
_is_dmraid_device (const char *devpath)
{
        int rc = 0;

        char const *dm_name = strrchr (devpath, '/');
        char const *dm_basename = dm_name && *(++dm_name) ? dm_name : devpath;
        struct dm_task *task = dm_task_create (DM_DEVICE_DEPS);
        if (!task)
                return 0;

        dm_task_set_name (task, dm_basename);
        if (!dm_task_run (task))
                goto err;

        const char *dmraid_uuid = dm_task_get_uuid (task);
        if (STRPREFIX (dmraid_uuid, "DMRAID-"))
                rc = 1;

err:
        dm_task_destroy (task);
        return rc;
}

/* We consider a dm device that is a linear mapping with a  *
 * single target that also is a dm device to be a partition */

static int
_dm_is_part (const char *path)
{
        int rc = 0;
        struct dm_task *task = dm_task_create (DM_DEVICE_DEPS);
        if (!task)
                return 0;

        dm_task_set_name(task, path);
        if (!dm_task_run(task))
                goto err;

        struct dm_info *info = alloca (sizeof *info);
        memset(info, '\0', sizeof *info);
        dm_task_get_info (task, info);
        if (!info->exists)
                goto err;

        struct dm_deps *deps = dm_task_get_deps (task);
        if (!deps)
                goto err;

        if (deps->count != 1)
                goto err;
        if (!_is_dm_major (major (deps->device[0])))
                goto err;
        dm_task_destroy (task);
        if (!(task = dm_task_create (DM_DEVICE_TABLE)))
                return 0;
        dm_task_set_name (task, path);
        if (!dm_task_run (task))
                goto err;

        char *target_type = NULL;
        char *params = NULL;
        uint64_t start, length;

        dm_get_next_target (task, NULL, &start, &length, &target_type, &params);
        if (strcmp (target_type, "linear"))
                goto err;
        rc = 1;

err:
        dm_task_destroy(task);
        return rc;
}

static int
_probe_dm_devices ()
{
       DIR*            mapper_dir;
       struct dirent*  dent;
       char            buf [512];      /* readdir(3) claims d_name[256] */
       struct stat     st;

       mapper_dir = opendir ("/dev/mapper");
       if (!mapper_dir)
               return 0;

       /* Search the /dev/mapper directory for devices w/ the same major
        * number that was returned from _probe_lvm_major().
        */
       while ((dent = readdir (mapper_dir))) {
               if (strcmp (dent->d_name, ".")  == 0 ||
                   strcmp (dent->d_name, "..") == 0)
                       continue;

               snprintf (buf, sizeof (buf), "/dev/mapper/%s", dent->d_name);

               if (stat (buf, &st) != 0)
                       continue;

               if (_is_dm_major(major(st.st_rdev))
                   && !(_is_dmraid_device(buf) && _dm_is_part(buf)))
                       _ped_device_probe (buf);
       }
       closedir (mapper_dir);

       return 1;
}
#endif

static int
_device_stat (PedDevice* dev, struct stat * dev_stat)
{
        PED_ASSERT (dev != NULL);
        PED_ASSERT (!dev->external_mode);

        while (1) {
                if (!stat (dev->path, dev_stat)) {
                        return 1;
                } else {
                        if (ped_exception_throw (
                                PED_EXCEPTION_ERROR,
                                PED_EXCEPTION_RETRY_CANCEL,
                                _("Could not stat device %s - %s."),
                                dev->path,
                                strerror (errno))
                                        != PED_EXCEPTION_RETRY)
                                return 0;
                }
        }
}

static int
_device_probe_type (PedDevice* dev)
{
        struct stat             dev_stat;
        int                     dev_major;
        int                     dev_minor;
        LinuxSpecific*          arch_specific = LINUX_SPECIFIC (dev);

        if (!_device_stat (dev, &dev_stat))
                return 0;

        if (!S_ISBLK(dev_stat.st_mode)) {
                dev->type = PED_DEVICE_FILE;
                return 1;
        }

        arch_specific->major = dev_major = major (dev_stat.st_rdev);
        arch_specific->minor = dev_minor = minor (dev_stat.st_rdev);

        if (SCSI_BLK_MAJOR (dev_major) && (dev_minor % 0x10 == 0)) {
                dev->type = PED_DEVICE_SCSI;
        } else if (_is_ide_major (dev_major) && (dev_minor % 0x40 == 0)) {
                dev->type = PED_DEVICE_IDE;
        } else if (dev_major == DAC960_MAJOR && (dev_minor % 0x8 == 0)) {
                dev->type = PED_DEVICE_DAC960;
        } else if (dev_major == ATARAID_MAJOR && (dev_minor % 0x10 == 0)) {
                dev->type = PED_DEVICE_ATARAID;
        } else if (dev_major == AOE_MAJOR && (dev_minor % 0x10 == 0)) {
                dev->type = PED_DEVICE_AOE;
        } else if (dev_major == DASD_MAJOR && (dev_minor % 0x4 == 0)) {
                dev->type = PED_DEVICE_DASD;
        } else if (dev_major == VIODASD_MAJOR && (dev_minor % 0x8 == 0)) {
                dev->type = PED_DEVICE_VIODASD;
        } else if (_is_sx8_major(dev_major) && (dev_minor % 0x20 == 0)) {
                dev->type = PED_DEVICE_SX8;
        } else if (_is_i2o_major (dev_major) && (dev_minor % 0x10 == 0)) {
                dev->type = PED_DEVICE_I2O;
        } else if (_is_cpqarray_major (dev_major) && (dev_minor % 0x10 == 0)) {
                dev->type = PED_DEVICE_CPQARRAY;
        } else if (dev_major == UBD_MAJOR && (dev_minor % 0x10 == 0)) {
                dev->type = PED_DEVICE_UBD;
#ifdef ENABLE_DEVICE_MAPPER
        } else if (_is_dm_major(dev_major)) {
                dev->type = PED_DEVICE_DM;
                if (_dm_maptype(dev)) {
                        ped_exception_throw (
                                PED_EXCEPTION_BUG,
                                PED_EXCEPTION_CANCEL,
                                _("Unable to determine the dm type of %s."),
                                dev->path);
                }
#endif
        } else if (dev_major == XVD_MAJOR && (dev_minor % 0x10 == 0)) {
                dev->type = PED_DEVICE_XVD;
        } else if (dev_major == SDMMC_MAJOR && (dev_minor % 0x08 == 0)) {
                dev->type = PED_DEVICE_SDMMC;
        } else if (_is_virtblk_major(dev_major)) {
                dev->type = PED_DEVICE_VIRTBLK;
        } else if (dev_major == LOOP_MAJOR) {
                dev->type = PED_DEVICE_LOOP;
        } else if (dev_major == MD_MAJOR) {
                dev->type = PED_DEVICE_MD;
        } else {
                dev->type = PED_DEVICE_UNKNOWN;
        }

        return 1;
}

static int
_get_linux_version ()
{
        static int kver = -1;

        struct utsname uts;
        int major = 0;
        int minor = 0;
        int teeny = 0;

        if (kver != -1)
                return kver;

        if (uname (&uts))
                return kver = 0;
        int n = sscanf (uts.release, "%u.%u.%u", &major, &minor, &teeny);
        assert (n == 2 || n == 3);
        return kver = KERNEL_VERSION (major, minor, teeny);
}

#if USE_BLKID
static void
get_blkid_topology (LinuxSpecific *arch_specific)
{
        arch_specific->probe = blkid_new_probe ();
        if (!arch_specific->probe)
                return;

        if (blkid_probe_set_device(arch_specific->probe,
                                   arch_specific->fd, 0, 0))
                return;

        arch_specific->topology =
                blkid_probe_get_topology(arch_specific->probe);
}
#endif

static void
_device_set_sector_size (PedDevice* dev)
{
        LinuxSpecific*  arch_specific = LINUX_SPECIFIC (dev);
        int sector_size;

        dev->sector_size = PED_SECTOR_SIZE_DEFAULT;
        dev->phys_sector_size = PED_SECTOR_SIZE_DEFAULT;

        PED_ASSERT (dev->open_count);

        if (_get_linux_version() < KERNEL_VERSION (2,3,0)) {
                dev->sector_size = PED_SECTOR_SIZE_DEFAULT;
                return;
        }

        if (ioctl (arch_specific->fd, BLKSSZGET, &sector_size)) {
                ped_exception_throw (
                        PED_EXCEPTION_WARNING,
                        PED_EXCEPTION_OK,
                        _("Could not determine sector size for %s: %s.\n"
                          "Using the default sector size (%lld)."),
                        dev->path, strerror (errno), PED_SECTOR_SIZE_DEFAULT);
        } else {
                dev->sector_size = (long long)sector_size;
                dev->phys_sector_size = dev->sector_size;
        }

#if USE_BLKID
        get_blkid_topology(arch_specific);
        if (!arch_specific->topology) {
                dev->phys_sector_size = 0;
        } else {
                dev->phys_sector_size =
                        blkid_topology_get_physical_sector_size(
                                arch_specific->topology);
        }
        if (dev->phys_sector_size == 0) {
                ped_exception_throw (
                        PED_EXCEPTION_WARNING,
                        PED_EXCEPTION_OK,
                        _("Could not determine physical sector size for %s.\n"
                          "Using the logical sector size (%lld)."),
                        dev->path, dev->sector_size);
                dev->phys_sector_size = dev->sector_size;
        }
#endif

#if defined __s390__ || defined __s390x__
        /* Return PED_SECTOR_SIZE_DEFAULT for DASDs. */
        if (dev->type == PED_DEVICE_DASD) {
                arch_specific->real_sector_size = dev->sector_size;
                dev->sector_size = PED_SECTOR_SIZE_DEFAULT;
        }
#endif
}

static int
_kernel_has_blkgetsize64(void)
{
        int version = _get_linux_version();

        if (version >= KERNEL_VERSION (2,5,4)) return 1;
        if (version <  KERNEL_VERSION (2,5,0) &&
            version >= KERNEL_VERSION (2,4,18)) return 1;
        return 0;
}

/* TODO: do a binary search if BLKGETSIZE doesn't work?! */
static PedSector
_device_get_length (PedDevice* dev)
{
        unsigned long           size;
        LinuxSpecific*          arch_specific = LINUX_SPECIFIC (dev);
        uint64_t bytes=0;
        const char*             test_str;
        PedSector               test_size;


        PED_ASSERT (dev->open_count > 0);
        PED_ASSERT (dev->sector_size % PED_SECTOR_SIZE_DEFAULT == 0);

        test_str = getenv ("PARTED_TEST_DEVICE_LENGTH");
        if (test_str
            && xstrtoll (test_str, NULL, 10, &test_size, NULL) == LONGINT_OK)
                return test_size;

        if (_kernel_has_blkgetsize64()) {
                if (ioctl(arch_specific->fd, BLKGETSIZE64, &bytes) == 0) {
                        return bytes / dev->sector_size;
                }
        }

        if (ioctl (arch_specific->fd, BLKGETSIZE, &size)) {
                ped_exception_throw (
                        PED_EXCEPTION_BUG,
                        PED_EXCEPTION_CANCEL,
                        _("Unable to determine the size of %s (%s)."),
                        dev->path,
                        strerror (errno));
                return 0;
        }

        return size;
}

static int
_device_probe_geometry (PedDevice* dev)
{
        LinuxSpecific*          arch_specific = LINUX_SPECIFIC (dev);
        struct stat             dev_stat;
        struct hd_geometry      geometry;

        if (!_device_stat (dev, &dev_stat))
                return 0;
        PED_ASSERT (S_ISBLK (dev_stat.st_mode));

        _device_set_sector_size (dev);

        dev->length = _device_get_length (dev);
        if (!dev->length)
                return 0;

        /* The GETGEO ioctl is no longer useful (as of linux 2.6.x).  We could
         * still use it in 2.4.x, but this is contentious.  Perhaps we should
         * move to EDD. */
        dev->bios_geom.sectors = 63;
        dev->bios_geom.heads = 255;
        dev->bios_geom.cylinders
                = dev->length / (63 * 255);

        /* FIXME: what should we put here?  (TODO: discuss on linux-kernel) */
        if (!ioctl (arch_specific->fd, HDIO_GETGEO, &geometry)
                        && geometry.sectors && geometry.heads) {
                dev->hw_geom.sectors = geometry.sectors;
                dev->hw_geom.heads = geometry.heads;
                dev->hw_geom.cylinders
                        = dev->length / (dev->hw_geom.heads
                                         * dev->hw_geom.sectors);
        } else {
                dev->hw_geom = dev->bios_geom;
        }

        return 1;
}

static char*
strip_name(char* str)
{
        int     i;
        int     end = 0;

        for (i = 0; str[i] != 0; i++) {
                if (!isspace (str[i])
                    || (isspace (str[i]) && !isspace (str[i+1]) && str[i+1])) {
                        str [end] = str[i];
                        end++;
                }
        }
        str[end] = 0;
        return strdup (str);
}

static int
init_ide (PedDevice* dev)
{
        LinuxSpecific*          arch_specific = LINUX_SPECIFIC (dev);
        struct stat             dev_stat;
        struct hd_driveid       hdi;
        PedExceptionOption      ex_status;
        char                    hdi_buf[41];
        int                     sector_multiplier = 0;

        if (!_device_stat (dev, &dev_stat))
                goto error;

        if (!ped_device_open (dev))
                goto error;

        if (ioctl (arch_specific->fd, HDIO_GET_IDENTITY, &hdi)) {
                ex_status = ped_exception_throw (
                                PED_EXCEPTION_WARNING,
                                PED_EXCEPTION_IGNORE_CANCEL,
                                _("Could not get identity of device %s - %s"),
                                dev->path, strerror (errno));
                switch (ex_status) {
                        case PED_EXCEPTION_CANCEL:
                                goto error_close_dev;

                        case PED_EXCEPTION_UNHANDLED:
                                ped_exception_catch ();
                        case PED_EXCEPTION_IGNORE:
                                dev->model = strdup(_("Generic IDE"));
                                break;
                        default:
                                PED_ASSERT (0);
                                break;
                }
        } else {
                /* hdi.model is not guaranteed to be NULL terminated */
                memcpy (hdi_buf, hdi.model, 40);
                hdi_buf[40] = '\0';
                dev->model = strip_name (hdi_buf);

                if (!hdi.ata7_sectinfo.valid1 && hdi.ata7_sectinfo.valid2)
                        sector_multiplier = hdi.ata7_sectinfo.multiplier;
                else
                        sector_multiplier = 1;

                if (sector_multiplier != 1) {
                        ex_status = ped_exception_throw (
                                PED_EXCEPTION_WARNING,
                                PED_EXCEPTION_IGNORE_CANCEL,
                                _("Device %s has multiple (%d) logical sectors "
                                  "per physical sector.\n"
                                  "GNU Parted supports this EXPERIMENTALLY for "
                                  "some special disk label/file system "
                                  "combinations, e.g. GPT and ext2/3.\n"
                                  "Please consult the web site for up-to-date "
                                  "information."),
                                dev->path, sector_multiplier);

                        switch (ex_status) {
                                case PED_EXCEPTION_CANCEL:
                                        goto error_close_dev;

                                case PED_EXCEPTION_UNHANDLED:
                                        ped_exception_catch ();
                                case PED_EXCEPTION_IGNORE:
                                        break;
                                default:
                                        PED_ASSERT (0);
                                        break;
                        }
                }

                /* XXX sector_size has not been set yet! */
                /* dev->phys_sector_size = dev->sector_size
                   * sector_multiplier;*/
                dev->phys_sector_size = PED_SECTOR_SIZE_DEFAULT;
        }

        if (!_device_probe_geometry (dev))
                goto error_close_dev;

        ped_device_close (dev);
        return 1;

error_close_dev:
        ped_device_close (dev);
error:
        return 0;
}

/* This function reads the /sys entry named "file" for device "dev". */
static char *
read_device_sysfs_file (PedDevice *dev, const char *file)
{
        FILE *f;
        char name_buf[128];
        char buf[256];

        snprintf (name_buf, 127, "/sys/block/%s/device/%s",
                  last_component (dev->path), file);

        if ((f = fopen (name_buf, "r")) == NULL)
                return NULL;

        if (fgets (buf, 255, f) == NULL) {
                fclose (f);
                return NULL;
        }

        fclose (f);
        return strip_name (buf);
}

/* This function sends a query to a SCSI device for vendor and product
 * information.  It uses the deprecated SCSI_IOCTL_SEND_COMMAND to
 * issue this query.
 */
static int
scsi_query_product_info (PedDevice* dev, char **vendor, char **product)
{
        /* The following are defined by the SCSI-2 specification. */
        typedef struct _scsi_inquiry_cmd
        {
                uint8_t op;
                uint8_t lun;          /* bits 5-7 denote the LUN */
                uint8_t page_code;
                uint8_t reserved;
                uint8_t alloc_length;
                uint8_t control;
        } __attribute__((packed)) scsi_inquiry_cmd_t;

        typedef struct _scsi_inquiry_data
        {
                uint8_t peripheral_info;
                uint8_t device_info;
                uint8_t version_info;
                uint8_t _field1;
                uint8_t additional_length;
                uint8_t _reserved1;
                uint8_t _reserved2;
                uint8_t _field2;
                uint8_t vendor_id[8];
                uint8_t product_id[16];
                uint8_t product_revision[4];
                uint8_t vendor_specific[20];
                uint8_t _reserved3[40];
        } __attribute__((packed)) scsi_inquiry_data_t;

        struct scsi_arg
        {
                unsigned int inlen;
                unsigned int outlen;

                union arg_data
                {
                        scsi_inquiry_data_t out;
                        scsi_inquiry_cmd_t  in;
                } data;
        } arg;

        LinuxSpecific* arch_specific = LINUX_SPECIFIC (dev);
        char    buf[32];

        *vendor = NULL;
        *product = NULL;

        memset (&arg, 0x00, sizeof(struct scsi_arg));
        arg.inlen  = 0;
        arg.outlen = sizeof(scsi_inquiry_data_t);
        arg.data.in.op  = INQUIRY;
        arg.data.in.lun = dev->host << 5;
        arg.data.in.alloc_length = sizeof(scsi_inquiry_data_t);
        arg.data.in.page_code = 0;
        arg.data.in.reserved = 0;
        arg.data.in.control = 0;

        if (ioctl (arch_specific->fd, SCSI_IOCTL_SEND_COMMAND, &arg) < 0)
                return 0;

        memcpy (buf, arg.data.out.vendor_id, 8);
        buf[8] = '\0';
        *vendor = strip_name (buf);

        memcpy (buf, arg.data.out.product_id, 16);
        buf[16] = '\0';
        *product = strip_name (buf);

        return 1;
}

/* This function provides the vendor and product name for a SCSI device.
 * It supports both the modern /sys interface and direct queries
 * via the deprecated ioctl, SCSI_IOCTL_SEND_COMMAND.
 */
static int
scsi_get_product_info (PedDevice* dev, char **vendor, char **product)
{
        *vendor = read_device_sysfs_file (dev, "vendor");
        *product = read_device_sysfs_file (dev, "model");
        if (*vendor && *product)
                return 1;

        return scsi_query_product_info (dev, vendor, product);
}

static int
init_scsi (PedDevice* dev)
{
        struct scsi_idlun
        {
                uint32_t dev_id;
                uint32_t host_unique_id;
        } idlun;

        LinuxSpecific* arch_specific = LINUX_SPECIFIC (dev);
        char* vendor;
        char* product;

        if (!ped_device_open (dev))
                goto error;

        if (ioctl (arch_specific->fd, SCSI_IOCTL_GET_IDLUN, &idlun) < 0) {
                dev->host = 0;
                dev->did = 0;
                if (ped_exception_throw (
                        PED_EXCEPTION_ERROR, PED_EXCEPTION_IGNORE_CANCEL,
                        _("Error initialising SCSI device %s - %s"),
                        dev->path, strerror (errno))
                                != PED_EXCEPTION_IGNORE)
                        goto error_close_dev;
                if (!_device_probe_geometry (dev))
                        goto error_close_dev;
                ped_device_close (dev);
                return 1;
        }

        dev->host = idlun.host_unique_id;
        dev->did  = idlun.dev_id;

        dev->model = (char*) ped_malloc (8 + 16 + 2);
        if (!dev->model)
                goto error_close_dev;

        if (scsi_get_product_info (dev, &vendor, &product)) {
                sprintf (dev->model, "%.8s %.16s", vendor, product);
                free (vendor);
                free (product);
        } else {
                strcpy (dev->model, "Generic SCSI");
        }

        if (!_device_probe_geometry (dev))
                goto error_close_dev;

        ped_device_close (dev);
        return 1;

error_close_dev:
        ped_device_close (dev);
error:
        return 0;
}

static int
init_file (PedDevice* dev)
{
        struct stat     dev_stat;

        if (!_device_stat (dev, &dev_stat))
                goto error;
        if (!ped_device_open (dev))
                goto error;

        dev->sector_size = PED_SECTOR_SIZE_DEFAULT;
        char *p = getenv ("PARTED_SECTOR_SIZE");
        if (p) {
                int s = atoi (p);
                if (0 < s && s % 512 == 0)
                        dev->sector_size = s;
        }
        dev->phys_sector_size = dev->sector_size;

        if (S_ISBLK(dev_stat.st_mode))
                dev->length = _device_get_length (dev);
        else
                dev->length = dev_stat.st_size / dev->sector_size;
        if (dev->length <= 0) {
                ped_exception_throw (
                        PED_EXCEPTION_ERROR,
                        PED_EXCEPTION_CANCEL,
                        _("The device %s is so small that it cannot possibly "
                          "store a file system or partition table.  Perhaps "
                          "you selected the wrong device?"),
                        dev->path);
                goto error_close_dev;
        }

        ped_device_close (dev);

        dev->bios_geom.cylinders = dev->length / 4 / 32;
        dev->bios_geom.heads = 4;
        dev->bios_geom.sectors = 32;
        dev->hw_geom = dev->bios_geom;
        dev->model = strdup ("");

        return 1;

error_close_dev:
        ped_device_close (dev);
error:
        return 0;
}

#if defined __s390__ || defined __s390x__
static int
init_dasd (PedDevice* dev, const char* model_name)
{
        struct stat             dev_stat;
        struct hd_geometry      geo;
        dasd_information_t dasd_info;

        if (!_device_stat (dev, &dev_stat))
                goto error;

        if (!ped_device_open (dev))
                goto error;

        LinuxSpecific* arch_specific = LINUX_SPECIFIC (dev);

        PED_ASSERT (S_ISBLK (dev_stat.st_mode));

        _device_set_sector_size (dev);
        if (!dev->sector_size)
                goto error_close_dev;

        dev->length = _device_get_length (dev);
        if (!dev->length)
                goto error_close_dev;

        if (!ioctl (arch_specific->fd, HDIO_GETGEO, &geo)) {
                dev->hw_geom.sectors = geo.sectors;
                dev->hw_geom.heads = geo.heads;
                dev->hw_geom.cylinders = dev->length
                        / (dev->hw_geom.heads * dev->hw_geom.sectors)
                        / (dev->sector_size / PED_SECTOR_SIZE_DEFAULT);
                dev->bios_geom = dev->hw_geom;
        } else {
                dev->bios_geom.sectors = 12;
                dev->bios_geom.heads = 15;
                dev->bios_geom.cylinders = dev->length
                        / (dev->hw_geom.heads * dev->hw_geom.sectors)
                        / (dev->sector_size / PED_SECTOR_SIZE_DEFAULT);
                dev->hw_geom = dev->bios_geom;
        }

        if (!ioctl(arch_specific->fd, BIODASDINFO, &dasd_info)) {
                arch_specific->devno = dasd_info.devno;
        } else {
                arch_specific->devno = arch_specific->major * 256 +
                                       arch_specific->minor;
        }

        dev->model = strdup (model_name);

        ped_device_close (dev);
        return 1;

error_close_dev:
        ped_device_close (dev);
error:
        return 0;
}
#endif

static int
init_generic (PedDevice* dev, const char* model_name)
{
        struct stat             dev_stat;
        PedExceptionOption      ex_status;

        if (!_device_stat (dev, &dev_stat))
                goto error;

        if (!ped_device_open (dev))
                goto error;

        ped_exception_fetch_all ();
        if (_device_probe_geometry (dev)) {
                ped_exception_leave_all ();
        } else {
		if (!_device_get_length (dev)) {
			ped_exception_catch ();
			ped_exception_leave_all ();
			goto error_close_dev;
		}

                /* hack to allow use of files, for testing */
                ped_exception_catch ();
                ped_exception_leave_all ();

                ex_status = ped_exception_throw (
                                PED_EXCEPTION_WARNING,
                                PED_EXCEPTION_IGNORE_CANCEL,
                                _("Unable to determine geometry of "
                                "file/device %s.  You should not use Parted "
                                "unless you REALLY know what you're doing!"),
                                dev->path);
                switch (ex_status) {
                        case PED_EXCEPTION_CANCEL:
                                goto error_close_dev;

                        case PED_EXCEPTION_UNHANDLED:
                                ped_exception_catch ();
                        case PED_EXCEPTION_IGNORE:
                                break;
                        default:
                                PED_ASSERT (0);
                                break;
                }

                /* what should we stick in here? */
                dev->length = dev_stat.st_size / PED_SECTOR_SIZE_DEFAULT;
                dev->bios_geom.cylinders = dev->length / 4 / 32;
                dev->bios_geom.heads = 4;
                dev->bios_geom.sectors = 32;
                dev->sector_size = PED_SECTOR_SIZE_DEFAULT;
                dev->phys_sector_size = PED_SECTOR_SIZE_DEFAULT;
        }

        dev->model = strdup (model_name);

        ped_device_close (dev);
        return 1;

error_close_dev:
        ped_device_close (dev);
error:
        return 0;
}

static int
sdmmc_get_product_info (PedDevice* dev, char **type, char **name)
{
        *type = read_device_sysfs_file (dev, "type");
        *name = read_device_sysfs_file (dev, "name");
        if (*type && *name)
                return 1;

        return 0;
}

static int
init_sdmmc (PedDevice* dev)
{
        char id[128];
        char *type, *name;

        if (sdmmc_get_product_info (dev, &type, &name)) {
                snprintf (id, sizeof(id) - 1, "%s %s", type, name);
                free (type);
                free (name);
        } else {
                snprintf (id, sizeof(id) - 1, "%s",
                          _("Generic SD/MMC Storage Card"));
        }
        return init_generic(dev, id);
}

static PedDevice*
linux_new (const char* path)
{
        PedDevice*      dev;
        LinuxSpecific*  arch_specific;

        PED_ASSERT (path != NULL);

        dev = (PedDevice*) ped_malloc (sizeof (PedDevice));
        if (!dev)
                goto error;

        dev->path = strdup (path);
        if (!dev->path)
                goto error_free_dev;

        dev->arch_specific
                = (LinuxSpecific*) ped_malloc (sizeof (LinuxSpecific));
        if (!dev->arch_specific)
                goto error_free_path;
        arch_specific = LINUX_SPECIFIC (dev);
        arch_specific->dmtype = NULL;
#if USE_BLKID
        arch_specific->probe = NULL;
        arch_specific->topology = NULL;
#endif

        dev->open_count = 0;
        dev->read_only = 0;
        dev->external_mode = 0;
        dev->dirty = 0;
        dev->boot_dirty = 0;

#ifdef ENABLE_DEVICE_MAPPER
        dm_udev_set_sync_support(1);
#endif

        if (!_device_probe_type (dev))
                goto error_free_arch_specific;

        switch (dev->type) {
        case PED_DEVICE_IDE:
                if (!init_ide (dev))
                        goto error_free_arch_specific;
                break;

        case PED_DEVICE_SCSI:
                if (!init_scsi (dev))
                        goto error_free_arch_specific;
                break;

        case PED_DEVICE_DAC960:
                if (!init_generic (dev, _("DAC960 RAID controller")))
                        goto error_free_arch_specific;
                break;

        case PED_DEVICE_SX8:
                if (!init_generic (dev, _("Promise SX8 SATA Device")))
                        goto error_free_arch_specific;
                break;

        case PED_DEVICE_AOE:
                if (!init_generic (dev, _("ATA over Ethernet Device")))
                    goto error_free_arch_specific;
                break;

#if defined __s390__ || defined __s390x__
        case PED_DEVICE_DASD:
                if (!init_dasd (dev, _("IBM S390 DASD drive")))
                        goto error_free_arch_specific;
                break;
#endif

        case PED_DEVICE_VIODASD:
                if (!init_generic (dev, _("IBM iSeries Virtual DASD")))
                        goto error_free_arch_specific;
                break;

        case PED_DEVICE_CPQARRAY:
                if (!init_generic (dev, _("Compaq Smart Array")))
                        goto error_free_arch_specific;
                break;

        case PED_DEVICE_ATARAID:
                if (!init_generic (dev, _("ATARAID Controller")))
                        goto error_free_arch_specific;
                break;

        case PED_DEVICE_I2O:
                if (!init_generic (dev, _("I2O Controller")))
                        goto error_free_arch_specific;
                break;

        case PED_DEVICE_UBD:
                if (!init_generic (dev, _("User-Mode Linux UBD")))
                        goto error_free_arch_specific;
                break;

        case PED_DEVICE_FILE:
                if (!init_file (dev))
                        goto error_free_arch_specific;
                break;

        case PED_DEVICE_LOOP:
                if (!init_generic (dev, _("Loopback device")))
                        goto error_free_arch_specific;
                break;

        case PED_DEVICE_DM:
                {
                  char* type;
                  if (arch_specific->dmtype == NULL
                      || asprintf(&type, _("Linux device-mapper (%s)"),
                                  arch_specific->dmtype) == -1)
                        goto error_free_arch_specific;
                  bool ok = init_generic (dev, type);
                  free (type);
                  if (!ok)
                    goto error_free_arch_specific;
                  break;
                }

        case PED_DEVICE_XVD:
                if (!init_generic (dev, _("Xen Virtual Block Device")))
                        goto error_free_arch_specific;
                break;

        case PED_DEVICE_UNKNOWN:
                if (!init_generic (dev, _("Unknown")))
                        goto error_free_arch_specific;
                break;

        case PED_DEVICE_SDMMC:
                if (!init_sdmmc (dev))
                        goto error_free_arch_specific;
                break;
        case PED_DEVICE_VIRTBLK:
                if (!init_generic(dev, _("Virtio Block Device")))
                        goto error_free_arch_specific;
                break;

        case PED_DEVICE_MD:
                if (!init_generic(dev, _("Linux Software RAID Array")))
                        goto error_free_arch_specific;
                break;

        default:
                ped_exception_throw (PED_EXCEPTION_NO_FEATURE,
                                PED_EXCEPTION_CANCEL,
                                _("ped_device_new()  Unsupported device type"));
                goto error_free_arch_specific;
        }
        return dev;

error_free_arch_specific:
        free (dev->arch_specific);
error_free_path:
        free (dev->path);
error_free_dev:
        free (dev);
error:
        return NULL;
}

static void
linux_destroy (PedDevice* dev)
{
        LinuxSpecific *arch_specific = LINUX_SPECIFIC(dev);
        void *p = arch_specific->dmtype;

#if USE_BLKID
        if (arch_specific->probe)
                blkid_free_probe(arch_specific->probe);
#endif
        free (p);
        free (dev->arch_specific);
        free (dev->path);
        free (dev->model);
        free (dev);
}

static int
linux_is_busy (PedDevice* dev)
{
        int     i;
        char*   part_name;

        if (_partition_is_mounted_by_path (dev->path))
                return 1;

        for (i = 0; i < 32; i++) {
                int status;

                part_name = _device_get_part_path (dev, i);
                if (!part_name)
                        return 1;
                status = _partition_is_mounted_by_path (part_name);
                free (part_name);

                if (status)
                        return 1;
        }

        return 0;
}

/* we need to flush the master device, and all the partition devices,
 * because there is no coherency between the caches.
 * We should only flush unmounted partition devices, because:
 *  - there is never a need to flush them (we're not doing IO there)
 *  - flushing a device that is mounted causes unnecessary IO, and can
 * even screw journaling & friends up.  Even cause oopsen!
 */
static void
_flush_cache (PedDevice* dev)
{
        LinuxSpecific*  arch_specific = LINUX_SPECIFIC (dev);
        int             i;
	int             lpn = _device_get_partition_range(dev);

        if (dev->read_only)
                return;
        dev->dirty = 0;

        ioctl (arch_specific->fd, BLKFLSBUF);

        for (i = 1; i < lpn; i++) {
                char*           name;
                int             fd;

                name = _device_get_part_path (dev, i);
                if (!name)
                        break;
                if (!_partition_is_mounted_by_path (name)) {
                        fd = open (name, WR_MODE, 0);
                        if (fd > 0) {
                                ioctl (fd, BLKFLSBUF);
retry:
                                if (fsync (fd) < 0 || close (fd) < 0)
					if (ped_exception_throw (
						PED_EXCEPTION_WARNING,
						PED_EXCEPTION_RETRY +
							PED_EXCEPTION_IGNORE,
						_("Error fsyncing/closing %s: %s"),
						name, strerror (errno))
							== PED_EXCEPTION_RETRY)
						goto retry;
                        }
                }
                free (name);
        }
}

static int
linux_open (PedDevice* dev)
{
        LinuxSpecific*  arch_specific = LINUX_SPECIFIC (dev);

retry:
        arch_specific->fd = open (dev->path, RW_MODE);

        if (arch_specific->fd == -1) {
                char*   rw_error_msg = strerror (errno);

                arch_specific->fd = open (dev->path, RD_MODE);

                if (arch_specific->fd == -1) {
                        if (ped_exception_throw (
                                PED_EXCEPTION_ERROR,
                                PED_EXCEPTION_RETRY_CANCEL,
                                _("Error opening %s: %s"),
                                dev->path, strerror (errno))
                                        != PED_EXCEPTION_RETRY) {
                                return 0;
                        } else {
                                goto retry;
                        }
                } else {
                        ped_exception_throw (
                                PED_EXCEPTION_WARNING,
                                PED_EXCEPTION_OK,
                                _("Unable to open %s read-write (%s).  %s has "
                                  "been opened read-only."),
                                dev->path, rw_error_msg, dev->path);
                        dev->read_only = 1;
                }
        } else {
                dev->read_only = 0;
        }

        _flush_cache (dev);

        return 1;
}

static int
linux_refresh_open (PedDevice* dev)
{
        return 1;
}

static int
linux_close (PedDevice* dev)
{
        LinuxSpecific*          arch_specific = LINUX_SPECIFIC (dev);

        if (dev->dirty)
                _flush_cache (dev);
retry:
        if (fsync (arch_specific->fd) < 0 || close (arch_specific->fd) < 0)
		if (ped_exception_throw (
			PED_EXCEPTION_WARNING,
			PED_EXCEPTION_RETRY + PED_EXCEPTION_IGNORE,
			_("Error fsyncing/closing %s: %s"),
			dev->path, strerror (errno))
				== PED_EXCEPTION_RETRY)
			goto retry;
        return 1;
}

static int
linux_refresh_close (PedDevice* dev)
{
        if (dev->dirty)
                _flush_cache (dev);
        return 1;
}

#if SIZEOF_OFF_T < 8

static _syscall5(int,_llseek,
                 unsigned int, fd,
                 unsigned long, offset_high,
                 unsigned long, offset_low,
                 loff_t*, result,
                 unsigned int, origin)

loff_t
llseek (unsigned int fd, loff_t offset, unsigned int whence)
{
        loff_t result;
        int retval;

        retval = _llseek(fd,
                         ((unsigned long long)offset) >> 32,
                         ((unsigned long long)offset) & 0xffffffff,
                         &result,
                         whence);
        return (retval==-1 ? (loff_t) retval : result);
}

#endif /* SIZEOF_OFF_T < 8 */

static int
_device_seek (const PedDevice* dev, PedSector sector)
{
        LinuxSpecific*  arch_specific;

        PED_ASSERT (dev->sector_size % PED_SECTOR_SIZE_DEFAULT == 0);
        PED_ASSERT (dev != NULL);
        PED_ASSERT (!dev->external_mode);

        arch_specific = LINUX_SPECIFIC (dev);

#if SIZEOF_OFF_T < 8
        if (sizeof (off_t) < 8) {
                loff_t  pos = (loff_t)(sector * dev->sector_size);
                return llseek (arch_specific->fd, pos, SEEK_SET) == pos;
        } else
#endif
        {
                off_t   pos = sector * dev->sector_size;
                return lseek (arch_specific->fd, pos, SEEK_SET) == pos;
        }
}

static int
_read_lastoddsector (const PedDevice* dev, void* buffer)
{
        LinuxSpecific*                  arch_specific;
        struct blkdev_ioctl_param       ioctl_param;

        PED_ASSERT(dev != NULL);
        PED_ASSERT(buffer != NULL);

        arch_specific = LINUX_SPECIFIC (dev);

retry:
        ioctl_param.block = 0; /* read the last sector */
        ioctl_param.content_length = dev->sector_size;
        ioctl_param.block_contents = buffer;

        if (ioctl(arch_specific->fd, BLKGETLASTSECT, &ioctl_param) == -1) {
                PedExceptionOption      opt;
                opt = ped_exception_throw (
                        PED_EXCEPTION_ERROR,
                        PED_EXCEPTION_RETRY_IGNORE_CANCEL,
                        _("%s during read on %s"),
                        strerror (errno), dev->path);

                if (opt == PED_EXCEPTION_CANCEL)
                        return 0;
                if (opt == PED_EXCEPTION_RETRY)
                        goto retry;
        }

        return 1;
}

static int
linux_read (const PedDevice* dev, void* buffer, PedSector start,
            PedSector count)
{
        LinuxSpecific*          arch_specific = LINUX_SPECIFIC (dev);
        PedExceptionOption      ex_status;
        void*                   diobuf = NULL;

        PED_ASSERT (dev != NULL);
        PED_ASSERT (dev->sector_size % PED_SECTOR_SIZE_DEFAULT == 0);

        if (_get_linux_version() < KERNEL_VERSION (2,6,0)) {
                /* Kludge.  This is necessary to read/write the last
                   block of an odd-sized disk, until Linux 2.5.x kernel fixes.
                */
                if (dev->type != PED_DEVICE_FILE && (dev->length & 1)
                    && start + count - 1 == dev->length - 1)
                        return ped_device_read (dev, buffer, start, count - 1)
                                && _read_lastoddsector (
                                        dev, (char *) buffer + (count-1) * 512);
        }
        while (1) {
                if (_device_seek (dev, start))
                        break;

                ex_status = ped_exception_throw (
                        PED_EXCEPTION_ERROR,
                        PED_EXCEPTION_RETRY_IGNORE_CANCEL,
                        _("%s during seek for read on %s"),
                        strerror (errno), dev->path);

                switch (ex_status) {
                        case PED_EXCEPTION_IGNORE:
                                return 1;

                        case PED_EXCEPTION_RETRY:
                                break;

                        case PED_EXCEPTION_UNHANDLED:
                                ped_exception_catch ();
                        case PED_EXCEPTION_CANCEL:
                                return 0;
                        default:
                                PED_ASSERT (0);
                                break;
                }
        }

        size_t read_length = count * dev->sector_size;
        if (posix_memalign (&diobuf, dev->sector_size, read_length) != 0)
                return 0;

        while (1) {
                ssize_t status = read (arch_specific->fd, diobuf, read_length);
                if (status > 0)
                        memcpy(buffer, diobuf, status);
                if (status == (ssize_t) read_length)
                        break;
                if (status > 0) {
                        read_length -= status;
                        buffer = (char *) buffer + status;
                        continue;
                }

                ex_status = ped_exception_throw (
                        PED_EXCEPTION_ERROR,
                        PED_EXCEPTION_RETRY_IGNORE_CANCEL,
                        (status == 0
                         ? _("%0.0send of file while reading %s")
                         : _("%s during read on %s")),
                        strerror (errno),
                        dev->path);

                switch (ex_status) {
                        case PED_EXCEPTION_IGNORE:
                                free(diobuf);
                                return 1;

                        case PED_EXCEPTION_RETRY:
                                break;

                        case PED_EXCEPTION_UNHANDLED:
                                ped_exception_catch ();
                        case PED_EXCEPTION_CANCEL:
                                free(diobuf);
                                return 0;
                        default:
                                PED_ASSERT (0);
                                break;
                }
        }

        free (diobuf);

        return 1;
}

static int
_write_lastoddsector (PedDevice* dev, const void* buffer)
{
        LinuxSpecific*                  arch_specific;
        struct blkdev_ioctl_param       ioctl_param;

        PED_ASSERT(dev != NULL);
        PED_ASSERT(buffer != NULL);

        arch_specific = LINUX_SPECIFIC (dev);

retry:
        ioctl_param.block = 0; /* write the last sector */
        ioctl_param.content_length = dev->sector_size;
        ioctl_param.block_contents = (void*) buffer;

        if (ioctl(arch_specific->fd, BLKSETLASTSECT, &ioctl_param) == -1) {
                PedExceptionOption      opt;
                opt = ped_exception_throw (
                        PED_EXCEPTION_ERROR,
                        PED_EXCEPTION_RETRY_IGNORE_CANCEL,
                        _("%s during write on %s"),
                        strerror (errno), dev->path);

                if (opt == PED_EXCEPTION_CANCEL)
                        return 0;
                if (opt == PED_EXCEPTION_RETRY)
                        goto retry;
        }

        return 1;
}

static int
linux_write (PedDevice* dev, const void* buffer, PedSector start,
             PedSector count)
{
        LinuxSpecific*          arch_specific = LINUX_SPECIFIC (dev);
        PedExceptionOption      ex_status;
        void*                   diobuf;
        void*                   diobuf_start;

        PED_ASSERT(dev->sector_size % PED_SECTOR_SIZE_DEFAULT == 0);

        if (dev->read_only) {
                if (ped_exception_throw (
                        PED_EXCEPTION_ERROR,
                        PED_EXCEPTION_IGNORE_CANCEL,
                        _("Can't write to %s, because it is opened read-only."),
                        dev->path)
                                != PED_EXCEPTION_IGNORE)
                        return 0;
                else
                        return 1;
        }

        if (_get_linux_version() < KERNEL_VERSION (2,6,0)) {
                /* Kludge.  This is necessary to read/write the last
                   block of an odd-sized disk, until Linux 2.5.x kernel fixes.
                */
                if (dev->type != PED_DEVICE_FILE && (dev->length & 1)
                    && start + count - 1 == dev->length - 1)
                        return ped_device_write (dev, buffer, start, count - 1)
                                && _write_lastoddsector (
                                        dev, ((char*) buffer
                                              + (count-1) * dev->sector_size));
        }
        while (1) {
                if (_device_seek (dev, start))
                        break;

                ex_status = ped_exception_throw (
                        PED_EXCEPTION_ERROR, PED_EXCEPTION_RETRY_IGNORE_CANCEL,
                        _("%s during seek for write on %s"),
                        strerror (errno), dev->path);

                switch (ex_status) {
                        case PED_EXCEPTION_IGNORE:
                                return 1;

                        case PED_EXCEPTION_RETRY:
                                break;

                        case PED_EXCEPTION_UNHANDLED:
                                ped_exception_catch ();
                        case PED_EXCEPTION_CANCEL:
                                return 0;
                        default:
                                PED_ASSERT (0);
                                break;
                }
        }

#ifdef READ_ONLY
        printf ("ped_device_write (\"%s\", %p, %d, %d)\n",
                dev->path, buffer, (int) start, (int) count);
#else
        size_t write_length = count * dev->sector_size;
        dev->dirty = 1;
        if (posix_memalign(&diobuf, dev->sector_size, write_length) != 0)
                return 0;
        memcpy(diobuf, buffer, write_length);
        diobuf_start = diobuf;
        while (1) {
                ssize_t status = write (arch_specific->fd, diobuf, write_length);
                if (status == write_length) break;
                if (status > 0) {
                        write_length -= status;
                        diobuf = (char *) diobuf + status;
                        continue;
                }

                ex_status = ped_exception_throw (
                        PED_EXCEPTION_ERROR,
                        PED_EXCEPTION_RETRY_IGNORE_CANCEL,
                        _("%s during write on %s"),
                        strerror (errno), dev->path);

                switch (ex_status) {
                        case PED_EXCEPTION_IGNORE:
                                free(diobuf_start);
                                return 1;

                        case PED_EXCEPTION_RETRY:
                                break;

                        case PED_EXCEPTION_UNHANDLED:
                                ped_exception_catch ();
                        case PED_EXCEPTION_CANCEL:
                                free(diobuf_start);
                                return 0;
                        default:
                                PED_ASSERT (0);
                                break;
                }
        }
        free(diobuf_start);
#endif /* !READ_ONLY */
        return 1;
}

/* returns the number of sectors that are ok.
 */
static PedSector
linux_check (PedDevice* dev, void* buffer, PedSector start, PedSector count)
{
        LinuxSpecific*  arch_specific = LINUX_SPECIFIC (dev);
        PedSector       done = 0;
        int             status;
        void*           diobuf;

        PED_ASSERT(dev != NULL);

        if (!_device_seek (dev, start))
                return 0;

        if (posix_memalign(&diobuf, PED_SECTOR_SIZE_DEFAULT,
                           count * PED_SECTOR_SIZE_DEFAULT) != 0)
                return 0;

        for (done = 0; done < count; done += status / dev->sector_size) {
                status = read (arch_specific->fd, diobuf,
                               (size_t) ((count-done) * dev->sector_size));
                if (status > 0)
                        memcpy(buffer, diobuf, status);
                if (status < 0)
                        break;
        }
        free(diobuf);

        return done;
}

static int
_do_fsync (PedDevice* dev)
{
        LinuxSpecific*          arch_specific = LINUX_SPECIFIC (dev);
        int                     status;
        PedExceptionOption      ex_status;

        while (1) {
                status = fsync (arch_specific->fd);
                if (status >= 0) break;

                ex_status = ped_exception_throw (
                        PED_EXCEPTION_ERROR,
                        PED_EXCEPTION_RETRY_IGNORE_CANCEL,
                        _("%s during write on %s"),
                        strerror (errno), dev->path);

                switch (ex_status) {
                        case PED_EXCEPTION_IGNORE:
                                return 1;

                        case PED_EXCEPTION_RETRY:
                                break;

                        case PED_EXCEPTION_UNHANDLED:
                                ped_exception_catch ();
                        case PED_EXCEPTION_CANCEL:
                                return 0;
                        default:
                                PED_ASSERT (0);
                                break;
                }
        }
        return 1;
}

static int
linux_sync (PedDevice* dev)
{
        PED_ASSERT (dev != NULL);
        PED_ASSERT (!dev->external_mode);

        if (dev->read_only)
                return 1;
        if (!_do_fsync (dev))
                return 0;
        _flush_cache (dev);
        return 1;
}

static int
linux_sync_fast (PedDevice* dev)
{
        PED_ASSERT (dev != NULL);
        PED_ASSERT (!dev->external_mode);

        if (dev->read_only)
                return 1;
        if (!_do_fsync (dev))
                return 0;
        /* no cache flush... */
        return 1;
}

static inline int
_compare_digit_state (char ch, int need_digit)
{
        return !!isdigit (ch) == need_digit;
}

/* matches the regexp "[^0-9]+[0-9]+[^0-9]+[0-9]+$".
 * Motivation: accept devices looking like /dev/rd/c0d0, but
 * not looking like /dev/hda1 and /dev/rd/c0d0p1
 */
static int _GL_ATTRIBUTE_PURE
_match_rd_device (const char* name)
{
        const char* pos;
        int state;

        /* exclude directory names from test */
        pos = strrchr(name, '/') ?: name;

        /* states:
         *      0       non-digits
         *      1       digits
         *      2       non-digits
         *      3       digits
         */
        for (state = 0; state < 4; state++) {
                int want_digits = (state % 2 == 1);
                do {
                        if (!*pos)
                                return 0;
                        if (!_compare_digit_state (*pos, want_digits))
                                return 0;
                        pos++;
                } while (_compare_digit_state (*pos, want_digits));
        }

        return *pos == 0;
}

static int
_probe_proc_partitions ()
{
        FILE*           proc_part_file;
        int             major, minor, size;
        char            buf [512];
        char            part_name [256];
        char            dev_name [256];
        int ok = 0;

        proc_part_file = fopen ("/proc/partitions", "r");
        if (!proc_part_file)
                return 0;

        if (fgets (buf, 256, proc_part_file) == NULL)
                goto done;

        if (fgets (buf, 256, proc_part_file) == NULL)
                goto done;

        while (fgets (buf, 512, proc_part_file)
               && sscanf (buf, "%d %d %d %255s", &major, &minor, &size,
                          part_name) == 4) {
                /* Heuristic for telling partitions and devices apart
                 * Probably needs to be improved
                 */
                if (!_match_rd_device (part_name)
                    && isdigit (part_name [strlen (part_name) - 1]))
                        continue;

                strcpy (dev_name, "/dev/");
                strcat (dev_name, part_name);
                _ped_device_probe (dev_name);
        }

        ok = 1;
 done:
        fclose (proc_part_file);
        return ok;
}

struct _entry {
	const char *name;
	size_t len;
};

static int _GL_ATTRIBUTE_PURE
_skip_entry (const char *name)
{
	struct _entry *i;
	static struct _entry entries[] = {
		{ ".",		sizeof (".") - 1	},
		{ "..",		sizeof ("..") - 1	},
		{ "dm-",	sizeof ("dm-") - 1	},
		{ "loop",	sizeof ("loop") - 1	},
		{ "ram",	sizeof ("ram") - 1	},
		{ "fd",		sizeof ("fd") - 1	},
		{ 0, 0 },
	};

	for (i = entries; i->name != 0; i++) {
		if (strncmp (name, i->name, i->len) == 0)
			return 1;
	}

	return 0;
}

static int
_probe_sys_block ()
{
	DIR *blockdir;
	struct dirent *dirent;
	char dev_name [256];
	char *ptr;

	if (!(blockdir = opendir ("/sys/block")))
		return 0;
	while ((dirent = readdir (blockdir))) {
		if (_skip_entry (dirent->d_name))
			continue;

		if (strlen (dirent->d_name) > sizeof (dev_name) - 6)
			continue; /* device name too long! */

		strcpy (dev_name, "/dev/");
		strcat (dev_name, dirent->d_name);
		/* in /sys/block, '/'s are replaced with '!' or '.' */
		for (ptr = dev_name; *ptr != '\0'; ptr++) {
			if (*ptr == '!' || *ptr == '.')
				*ptr = '/';
		}
		_ped_device_probe (dev_name);
	}

	closedir (blockdir);
	return 1;
}

static int
_probe_standard_devices ()
{
        _ped_device_probe ("/dev/hda");
        _ped_device_probe ("/dev/hdb");
        _ped_device_probe ("/dev/hdc");
        _ped_device_probe ("/dev/hdd");
        _ped_device_probe ("/dev/hde");
        _ped_device_probe ("/dev/hdf");
        _ped_device_probe ("/dev/hdg");
        _ped_device_probe ("/dev/hdh");

        _ped_device_probe ("/dev/sda");
        _ped_device_probe ("/dev/sdb");
        _ped_device_probe ("/dev/sdc");
        _ped_device_probe ("/dev/sdd");
        _ped_device_probe ("/dev/sde");
        _ped_device_probe ("/dev/sdf");

        return 1;
}

static void
linux_probe_all ()
{
        /* we should probe the standard devs too, even with /proc/partitions,
         * because /proc/partitions might return devfs stuff, and we might not
         * have devfs available
         */
        _probe_standard_devices ();

#ifdef ENABLE_DEVICE_MAPPER
        /* device-mapper devices aren't listed in /proc/partitions; or, if
         * they are, they're listed as dm-X.  So, instead of relying on that,
         * we do our own checks.
         */
        _probe_dm_devices ();
#endif

        /* /sys/block is more reliable and consistent; fall back to using
         * /proc/partitions if the former is unavailable, however.
         */
        if (!_probe_sys_block ())
                _probe_proc_partitions ();
}

static char * _GL_ATTRIBUTE_FORMAT ((__printf__, 1, 2))
zasprintf (const char *format, ...)
{
  va_list args;
  char *resultp;
  va_start (args, format);
  int r = vasprintf (&resultp, format, args);
  va_end (args);
  return r < 0 ? NULL : resultp;
}

static char *
dm_canonical_path (PedDevice const *dev)
{
        LinuxSpecific const *arch_specific = LINUX_SPECIFIC (dev);

        /* Get map name from devicemapper */
        struct dm_task *task = dm_task_create (DM_DEVICE_INFO);
        if (!task)
                goto err;
        if (!dm_task_set_major_minor (task, arch_specific->major,
                                      arch_specific->minor, 0))
                goto err;
        if (!dm_task_run(task))
                goto err;
        char *dev_name = zasprintf ("/dev/mapper/%s", dm_task_get_name (task));
        if (dev_name == NULL)
                goto err;
        dm_task_destroy (task);
        return dev_name;
err:
        return NULL;
}

static char*
_device_get_part_path (PedDevice const *dev, int num)
{
        char *devpath = (dev->type == PED_DEVICE_DM
                         ? dm_canonical_path (dev) : dev->path);
        size_t path_len = strlen (devpath);
        char *result;
        /* Check for devfs-style /disc => /partN transformation
           unconditionally; the system might be using udev with devfs rules,
           and if not the test is harmless. */
        if (5 < path_len && !strcmp (devpath + path_len - 5, "/disc")) {
                /* replace /disc with /part%d */
                result = zasprintf ("%.*s/part%d",
                                    (int) (path_len - 5), devpath, num);
        } else {
                char const *p = (dev->type == PED_DEVICE_DAC960
                                 || dev->type == PED_DEVICE_CPQARRAY
                                 || dev->type == PED_DEVICE_ATARAID
                                 || isdigit (devpath[path_len - 1])
                                 ? "p" : "");
                result = zasprintf ("%s%s%d", devpath, p, num);
        }
        if (dev->type == PED_DEVICE_DM)
                free (devpath);
        return result;
}

static char*
linux_partition_get_path (const PedPartition* part)
{
        /* loop label means use the whole disk */
        if (strcmp (part->disk->type->name, "loop") == 0)
                return xstrdup (part->disk->dev->path);
        return _device_get_part_path (part->disk->dev, part->num);
}

static int
_mount_table_search (const char* file_name, dev_t dev)
{
        struct stat part_stat;
        char line[512];
        char part_name[512];
        FILE* file;

        file = fopen (file_name, "r");
        if (!file)
                return 0;
        while (fgets (line, 512, file)) {
                if (sscanf (line, "%s", part_name) == 1
                    && stat (part_name, &part_stat) == 0) {
                        if (part_stat.st_rdev == dev) {
                                fclose (file);
                                return 1;
                        }
                }
        }
        fclose (file);
        return 0;
}

static int
_partition_is_mounted_by_dev (dev_t dev)
{
        return  _mount_table_search( "/proc/mounts", dev)
                || _mount_table_search( "/proc/swaps", dev)
                || _mount_table_search( "/etc/mtab", dev);
}

static int
_partition_is_mounted_by_path (const char *path)
{
        struct stat part_stat;
        if (stat (path, &part_stat) != 0)
                return 0;
        if (!S_ISBLK(part_stat.st_mode))
                return 0;
        return _partition_is_mounted_by_dev (part_stat.st_rdev);
}

/* If partition PART is mounted, or if we encounter an out-of-memory error
   while trying to determine its status, return 1.  Otherwise, return 0.  */
static int
_partition_is_mounted (const PedPartition *part)
{
	if (!ped_partition_is_active (part))
		return 0;
	char *part_name = _device_get_part_path (part->disk->dev, part->num);
	if (!part_name)
		return 1;
	int status = _partition_is_mounted_by_path (part_name);
	free (part_name);
	return !!status;
}

static int
linux_partition_is_busy (const PedPartition* part)
{
        PedPartition*   walk;

        PED_ASSERT (part != NULL);

        if (strcmp (part->disk->type->name, "loop") == 0)
                return linux_is_busy (part->disk->dev);
        if (_partition_is_mounted (part))
                return 1;
        if (part->type == PED_PARTITION_EXTENDED) {
                for (walk = part->part_list; walk; walk = walk->next) {
                        if (linux_partition_is_busy (walk))
                                return 1;
                }
        }
        return 0;
}

static int
_blkpg_part_command (PedDevice* dev, struct blkpg_partition* part, int op)
{
        LinuxSpecific*          arch_specific = LINUX_SPECIFIC (dev);
        struct blkpg_ioctl_arg  ioctl_arg;

        ioctl_arg.op = op;
        ioctl_arg.flags = 0;
        ioctl_arg.datalen = sizeof (struct blkpg_partition);
        ioctl_arg.data = (void*) part;

        return ioctl (arch_specific->fd, BLKPG, &ioctl_arg) == 0;
}

static int
_blkpg_add_partition (PedDisk* disk, const PedPartition *part)
{
        struct blkpg_partition  linux_part;
        const char*             vol_name;
        char*                   dev_name;

        PED_ASSERT(disk != NULL);
        PED_ASSERT(disk->dev->sector_size % PED_SECTOR_SIZE_DEFAULT == 0);

        if (ped_disk_type_check_feature (disk->type,
                                         PED_DISK_TYPE_PARTITION_NAME))
                vol_name = ped_partition_get_name (part);
        else
                vol_name = NULL;

        dev_name = _device_get_part_path (disk->dev, part->num);
        if (!dev_name)
                return 0;

        memset (&linux_part, 0, sizeof (linux_part));
        linux_part.start = part->geom.start * disk->dev->sector_size;
        /* see fs/partitions/msdos.c:msdos_partition(): "leave room for LILO" */
        if (part->type & PED_PARTITION_EXTENDED) {
                linux_part.length = 1;
                if (disk->dev->sector_size == 512) {
                        if (linux_part.length == 1)
                                linux_part.length = 2;
                        PedPartition *walk;
                        /* if the second sector is claimed by a logical partition,
                           then there's just no room for lilo, so don't try to use it */
                        for (walk = part->part_list; walk; walk = walk->next) {
                                if (walk->geom.start == part->geom.start+1)
                                        linux_part.length = 1;
                        }
                }
                linux_part.length *= disk->dev->sector_size;
        }
        else {
                linux_part.length = part->geom.length * disk->dev->sector_size;
        }
        linux_part.pno = part->num;
        strncpy (linux_part.devname, dev_name, BLKPG_DEVNAMELTH);
        if (vol_name)
                strncpy (linux_part.volname, vol_name, BLKPG_VOLNAMELTH);

        free (dev_name);

        if (!_blkpg_part_command (disk->dev, &linux_part,
                                  BLKPG_ADD_PARTITION)) {
                return 0;
        }

        return 1;
}

static int
_blkpg_remove_partition (PedDisk* disk, int n)
{
        struct blkpg_partition  linux_part;

        memset (&linux_part, 0, sizeof (linux_part));
        linux_part.pno = n;
        return _blkpg_part_command (disk->dev, &linux_part,
                                    BLKPG_DEL_PARTITION);
}

#ifdef BLKPG_RESIZE_PARTITION
static int _blkpg_resize_partition (PedDisk* disk, const PedPartition *part)
{
        struct blkpg_partition  linux_part;
        char*                   dev_name;

        PED_ASSERT(disk != NULL);
        PED_ASSERT(disk->dev->sector_size % PED_SECTOR_SIZE_DEFAULT == 0);

        dev_name = _device_get_part_path (disk->dev, part->num);
        if (!dev_name)
                return 0;
        memset (&linux_part, 0, sizeof (linux_part));
        linux_part.start = part->geom.start * disk->dev->sector_size;
        /* see fs/partitions/msdos.c:msdos_partition(): "leave room for LILO" */
        if (part->type & PED_PARTITION_EXTENDED) {
                if (disk->dev->sector_size == 512) {
                        linux_part.length = 2;
                        PedPartition *walk;
                        /* if the second sector is claimed by a logical partition,
                           then there's just no room for lilo, so don't try to use it */
                        for (walk = part->part_list; walk; walk = walk->next) {
                                if (walk->geom.start == part->geom.start+1)
                                        linux_part.length = 1;
                        }
                } else linux_part.length = 1;
        }
        else
                linux_part.length = part->geom.length * disk->dev->sector_size;
        linux_part.pno = part->num;
        strncpy (linux_part.devname, dev_name, BLKPG_DEVNAMELTH);

        free (dev_name);

        if (!_blkpg_part_command (disk->dev, &linux_part,
                                  BLKPG_RESIZE_PARTITION)) {
                return ped_exception_throw (
                        PED_EXCEPTION_ERROR,
                        PED_EXCEPTION_IGNORE_CANCEL,
                        _("Error informing the kernel about modifications to "
                          "partition %s -- %s.  This means Linux won't know "
                          "about any changes you made to %s until you reboot "
                          "-- so you shouldn't mount it or use it in any way "
                          "before rebooting."),
                        linux_part.devname,
                        strerror (errno),
                        linux_part.devname)
                                == PED_EXCEPTION_IGNORE;
        }

        return 1;
}
#endif

/* Read the integer from /sys/block/DEV_BASE/ENTRY and set *VAL
   to that value, where DEV_BASE is the last component of DEV->path.
   Upon success, return true.  Otherwise, return false. */
static bool
_sysfs_int_entry_from_dev(PedDevice const* dev, const char *entry, int *val)
{
        char        path[128];
        int r = snprintf(path, sizeof(path), "/sys/block/%s/%s",
			 last_component(dev->path), entry);
        if (r < 0 || r >= sizeof(path))
                return false;

        FILE *fp = fopen(path, "r");
        if (!fp)
                return false;

        bool ok = fscanf(fp, "%d", val) == 1;
        fclose(fp);

        return ok;
}

/* Read the unsigned long long from /sys/block/DEV_BASE/PART_BASE/ENTRY
   and set *VAL to that value, where DEV_BASE is the last component of path to
   block device corresponding to PART and PART_BASE is the sysfs name of PART.
   Upon success, return true. Otherwise, return false. */
static bool
_sysfs_ull_entry_from_part(PedPartition const* part, const char *entry,
                           unsigned long long *val)
{
        char path[128];
        char *part_name = _device_get_part_path (part->disk->dev, part->num);
        if (!part_name)
                return false;

        int r = snprintf(path, sizeof(path), "/sys/block/%s/%s/%s",
                last_component(part->disk->dev->path),
                last_component(part_name), entry);
        free(part_name);
        if (r < 0 || r >= sizeof(path))
                return false;

        FILE *fp = fopen(path, "r");
        if (!fp)
                return false;

        bool ok = fscanf(fp, "%llu", val) == 1;
        fclose(fp);

        return ok;
}


/* Get the starting sector and length of a partition PART within a block device
   Use blkpg if available, then check sysfs and then use HDIO_GETGEO and
   BLKGETSIZE64 ioctls as fallback.  Upon success, return true.  Otherwise,
   return false. */
static bool
_kernel_get_partition_start_and_length(PedPartition const *part,
                                       unsigned long long *start,
                                       unsigned long long *length)
{
        PED_ASSERT(part);
        PED_ASSERT(start);
        PED_ASSERT(length);

        char *dev_name = _device_get_part_path (part->disk->dev, part->num);
        if (!dev_name)
                return false;

        int ok = _sysfs_ull_entry_from_part (part, "start", start);
        if (!ok) {
                struct hd_geometry geom;
                int dev_fd = open (dev_name, O_RDONLY);
                if (dev_fd != -1 && ioctl (dev_fd, HDIO_GETGEO, &geom)) {
                        *start = geom.start;
                        ok = true;
                } else {
                        if (dev_fd != -1)
                                close(dev_fd);
                        free (dev_name);
                        return false;
                }
        }
        *start = (*start * 512) / part->disk->dev->sector_size;
        ok = _sysfs_ull_entry_from_part (part, "size", length);

        int fd;
        if (!ok) {
                fd = open (dev_name, O_RDONLY);
                if (fd != -1 && ioctl (fd, BLKGETSIZE64, length))
                        ok = true;
        } else {
                fd = -1;
                *length *= 512;
        }
        *length /= part->disk->dev->sector_size;
        if (fd != -1)
                close (fd);

        if (!ok)
                ped_exception_throw (
                        PED_EXCEPTION_BUG,
                        PED_EXCEPTION_CANCEL,
                        _("Unable to determine the start and length of %s."),
                        dev_name);
        free (dev_name);
        return ok;
}


/*
 * The number of partitions that a device can have depends on the kernel.
 * If we don't find this value in /sys/block/DEV/ext_range, we will use our own
 * value.
 */
static unsigned int
_device_get_partition_range(PedDevice const* dev)
{
        int range;
        if (dev->type == PED_DEVICE_DM)
                return MAX_NUM_PARTS;
        bool ok = _sysfs_int_entry_from_dev(dev, "ext_range", &range);

        if (!ok)
                return MAX_NUM_PARTS;
        /* both 0 and 1 mean no partitions */
        return range > 1 ? range : 0;
}

#ifdef ENABLE_DEVICE_MAPPER
static int
_dm_remove_partition(PedDisk* disk, int partno)
{
        int             rc = 0;
        uint32_t        cookie = 0;
        char            *part_name = _device_get_part_path (disk->dev, partno);

        int fd = open (part_name, O_RDONLY | O_EXCL);
        if (fd == -1) {
                if (errno == ENOENT)
                        errno = ENXIO; /* nothing to remove, device already doesn't exist */
                goto err;
        }
        close (fd);
        struct dm_task *task = dm_task_create(DM_DEVICE_REMOVE);
        if (!task)
                goto err;
        dm_task_set_name (task, part_name);
        if (!dm_task_set_cookie (task, &cookie, 0))
                goto err;
        rc = _dm_task_run_wait (task, cookie);
        dm_task_update_nodes();
        dm_task_destroy(task);
err:
        free (part_name);
        return rc;
}

static bool
_dm_get_partition_start_and_length(PedPartition const *part,
                                   unsigned long long *start,
                                   unsigned long long *length)
{
        struct dm_task* task = NULL;
        int             rc = 0;

        if (!(task = dm_task_create(DM_DEVICE_TABLE)))
                return 0;
        char *path = _device_get_part_path (part->disk->dev, part->num);
        PED_ASSERT(path);
        /* libdevmapper likes to complain on stderr instead of quietly
           returning ENOENT or ENXIO, so try to stat first */
        struct stat st;
        if (stat(path, &st))
                goto err;
        dm_task_set_name(task, path);
        if (!dm_task_run(task))
                goto err;

        int major, minor;
        char *params;
        char *target_type;
        dm_get_next_target(task, NULL, (uint64_t *)start, (uint64_t *)length, &target_type, &params);
        if (sscanf (params, "%d:%d %Ld", &major, &minor, start) != 3)
                goto err;
        rc = 1;
err:
        free (path);
        dm_task_destroy(task);
        return rc;
}


static int
_dm_add_partition (PedDisk* disk, const PedPartition* part)
{
        LinuxSpecific*  arch_specific = LINUX_SPECIFIC (disk->dev);
        char*           params = NULL;
        char*           vol_name = NULL;
        const char*     dev_name = NULL;
        char*           vol_uuid = NULL;
        const char*     dev_uuid = NULL;
        uint32_t        cookie = 0;

        /* Get map name from devicemapper */
        struct dm_task *task = dm_task_create (DM_DEVICE_INFO);
        if (!task)
                goto err;

        if (!dm_task_set_major_minor (task, arch_specific->major,
                                      arch_specific->minor, 0))
                goto err;

        if (!dm_task_run(task))
                goto err;

        dev_name = dm_task_get_name (task);
        size_t name_len = strlen (dev_name);
        vol_name = zasprintf ("%s%s%d",
                              dev_name,
                              isdigit (dev_name[name_len - 1]) ? "p" : "",
                              part->num);
        if (vol_name == NULL)
                goto err;

        dev_uuid = dm_task_get_uuid (task);
        if (dev_uuid && (strlen(dev_uuid) > 0)
             && !(vol_uuid = zasprintf ("part%d-%s", part->num, dev_uuid)))
            goto err;

        /* Caution: dm_task_destroy frees dev_name.  */
        dm_task_destroy (task);
        task = NULL;
        if ( ! (params = zasprintf ("%d:%d %lld", arch_specific->major,
                                    arch_specific->minor, part->geom.start)))
                goto err;

        task = dm_task_create (DM_DEVICE_CREATE);
        if (!task)
                goto err;

        dm_task_set_name (task, vol_name);
        if (vol_uuid)
                dm_task_set_uuid (task, vol_uuid);
        dm_task_add_target (task, 0, part->geom.length,
                "linear", params);
        if (!dm_task_set_cookie (task, &cookie, 0))
                goto err;
        if (_dm_task_run_wait (task, cookie)) {
                dm_task_update_nodes ();
                dm_task_destroy (task);
                free (params);
                free (vol_uuid);
                free (vol_name);
                return 1;
        } else {
                _dm_remove_partition (disk, part->num);
        }
err:
        dm_task_update_nodes();
        if (task)
                dm_task_destroy (task);
        free (params);
        free (vol_uuid);
        free (vol_name);
        return 0;
}

static int
_dm_resize_partition (PedDisk* disk, const PedPartition* part)
{
        LinuxSpecific*  arch_specific = LINUX_SPECIFIC (disk->dev);
        char*           params = NULL;
        char*           vol_name = NULL;
        const char*     dev_name = NULL;
        uint32_t        cookie = 0;

        /* Get map name from devicemapper */
        struct dm_task *task = dm_task_create (DM_DEVICE_INFO);
        if (!task)
                goto err;

        if (!dm_task_set_major_minor (task, arch_specific->major,
                                      arch_specific->minor, 0))
                goto err;

        if (!dm_task_run(task))
                goto err;

        dev_name = dm_task_get_name (task);
        size_t name_len = strlen (dev_name);
        vol_name = zasprintf ("%s%s%d",
                              dev_name,
                              isdigit (dev_name[name_len - 1]) ? "p" : "",
                              part->num);
        if (vol_name == NULL)
                goto err;

        /* Caution: dm_task_destroy frees dev_name.  */
        dm_task_destroy (task);
        task = NULL;
        if ( ! (params = zasprintf ("%d:%d %lld", arch_specific->major,
                                    arch_specific->minor, part->geom.start)))
                goto err;

        task = dm_task_create (DM_DEVICE_RELOAD);
        if (!task)
                goto err;

        dm_task_set_name (task, vol_name);
        dm_task_add_target (task, 0, part->geom.length,
                "linear", params);
        if (!dm_task_set_cookie (task, &cookie, 0))
                goto err;
        if (dm_task_run (task)) {
                dm_task_destroy (task);
                task = dm_task_create (DM_DEVICE_RESUME);
                if (!task)
                        goto err;
                dm_task_set_name (task, vol_name);
                if (!dm_task_set_cookie (task, &cookie, 0))
                        goto err;
                if (dm_task_run (task)) {
                        free (params);
                        free (vol_name);
                        return 1;
                }
        }
err:
        dm_task_update_nodes();
        if (task)
                dm_task_destroy (task);
        free (params);
        free (vol_name);
        return 0;
}

#endif

/*
 * Sync the partition table in two step process:
 * 1. Remove all of the partitions from the kernel's tables, but do not attempt
 *    removal of any partition for which the corresponding ioctl call fails.
 * 2. Add all the partitions that we hold in disk, throwing a warning
 *    if we cannot because step 1 failed to remove it and it is not being
 *    added back with the same start and length.
 *
 * To achieve this two step process we must calculate the minimum number of
 * maximum possible partitions between what linux supports and what the label
 * type supports. EX:
 *
 * number=MIN(max_parts_supported_in_linux,max_parts_supported_in_msdos_tables)
 */
static int
_disk_sync_part_table (PedDisk* disk)
{
        PED_ASSERT(disk != NULL);
        PED_ASSERT(disk->dev != NULL);
        int lpn, lpn2;
        unsigned int part_range = _device_get_partition_range(disk->dev);
        int (*add_partition)(PedDisk* disk, const PedPartition *part);
        int (*resize_partition)(PedDisk* disk, const PedPartition *part);
        int (*remove_partition)(PedDisk* disk, int partno);
        bool (*get_partition_start_and_length)(PedPartition const *part,
                                               unsigned long long *start,
                                               unsigned long long *length);


        if (disk->dev->type == PED_DEVICE_DM) {
                add_partition = _dm_add_partition;
                remove_partition = _dm_remove_partition;
                resize_partition = _dm_resize_partition;
                get_partition_start_and_length = _dm_get_partition_start_and_length;
        } else {
                add_partition = _blkpg_add_partition;
                remove_partition = _blkpg_remove_partition;
#ifdef BLKPG_RESIZE_PARTITION
                resize_partition = _blkpg_resize_partition;
#else
                resize_partition = NULL;
#endif
                get_partition_start_and_length = _kernel_get_partition_start_and_length;
        }

        /* lpn = largest partition number.
         * for remove pass, use greater of device or label limit */
        if (ped_disk_get_max_supported_partition_count(disk, &lpn))
                lpn = PED_MAX(lpn, part_range);
        else
                lpn = part_range;
        /* for add pass, use lesser of device or label limit */
        if (ped_disk_get_max_supported_partition_count(disk, &lpn2))
                lpn2 = PED_MIN(lpn2, part_range);
        else
                lpn2 = part_range;
        /* Its not possible to support largest_partnum < 0.
         * largest_partnum == 0 would mean does not support partitions.
         * */
        if (lpn < 1)
                return 0;
        int ret = 0;
        int *ok = calloc (lpn, sizeof *ok);
        if (!ok)
                return 0;
        int *errnums = ped_malloc(sizeof(int) * lpn);
        if (!errnums)
                goto cleanup;

        int i;
        /* remove old partitions first */
        for (i = 1; i <= lpn; i++) {
                PedPartition *part = ped_disk_get_partition (disk, i);
                if (part) {
                        unsigned long long length;
                        unsigned long long start;
                        /* get start and length of existing partition */
                        if (get_partition_start_and_length(part,
                                                           &start, &length)
                            && start == part->geom.start
                            && (length == part->geom.length
                                || (resize_partition && part->num < lpn2)))
                        {
                                /* partition is unchanged, or will be resized so nothing to do */
                                ok[i - 1] = 1;
                                continue;
                        }
                }
                /* Attempt to remove the partition, retrying for
                   up to max_sleep_seconds upon any failure due to EBUSY. */
                unsigned int sleep_microseconds = 10000;
                unsigned int max_sleep_seconds = 1;
                unsigned int n_sleep = (max_sleep_seconds
                                        * 1000000 / sleep_microseconds);
                do {
                        ok[i - 1] = remove_partition (disk, i);
                        errnums[i - 1] = errno;
                        if (ok[i - 1] || errnums[i - 1] != EBUSY)
                                break;
                        usleep (sleep_microseconds);
                } while (n_sleep--);
                if (!ok[i - 1] && errnums[i - 1] == ENXIO)
                        ok[i - 1] = 1; /* it already doesn't exist */
        }
        lpn = lpn2;
        /* don't actually add partitions for loop */
        if (strcmp (disk->type->name, "loop") == 0)
                lpn = 0;
        for (i = 1; i <= lpn; i++) {
                PedPartition *part = ped_disk_get_partition (disk, i);
                if (!part)
                        continue;
                unsigned long long length;
                unsigned long long start;
                /* get start and length of existing partition */
                if (get_partition_start_and_length(part,
                                                   &start, &length)
                    && start == part->geom.start)
                {
                        if (length == part->geom.length) {
                                ok[i - 1] = 1;
                                /* partition is unchanged, so nothing to do */
                                continue;
                        }
                        if (resize_partition
                            && start == part->geom.start)
                        {
                                /* try to resize */
                                if (resize_partition (disk, part)) {
                                        ok[i - 1] = 1;
                                        continue;
                                }
                        }
                }
                /* add the (possibly modified or new) partition */
                if (!add_partition (disk, part)) {
                        ok[i - 1] = 0;
                        errnums[i - 1] = errno;
                }
        }

        char *bad_part_list = NULL;
        /* now warn about any errors */
        for (i = 1; i <= lpn; i++) {
                if (ok[i - 1] || errnums[i - 1] == ENXIO)
                        continue;
                if (bad_part_list == NULL) {
                        bad_part_list = malloc (lpn * 5);
                        if (!bad_part_list)
                                goto cleanup;
                        bad_part_list[0] = 0;
                }
                sprintf (bad_part_list + strlen (bad_part_list), "%d, ", i);
        }
        if (bad_part_list == NULL)
                ret = 1;
        else {
                bad_part_list[strlen (bad_part_list) - 2] = 0;
                if (ped_exception_throw (
                        PED_EXCEPTION_ERROR,
                        PED_EXCEPTION_IGNORE_CANCEL,
                        _("Partition(s) %s on %s have been written, but we have "
                          "been unable to inform the kernel of the change, "
                          "probably because it/they are in use.  As a result, "
                          "the old partition(s) will remain in use.  You "
                          "should reboot now before making further changes."),
                        bad_part_list, disk->dev->path) == PED_EXCEPTION_IGNORE)
                        ret = 1;
                free (bad_part_list);
        }
 cleanup:
        free (errnums);
        free (ok);
        return ret;
}

static int
_have_blkpg ()
{
        static int have_blkpg = -1;
        int kver;

        if (have_blkpg != -1)
                return have_blkpg;

        kver = _get_linux_version();
        return have_blkpg = kver >= KERNEL_VERSION (2,4,0) ? 1 : 0;
}

static int
_chrooted ()
{
        static int cached = -1;
        struct stat root, init_root;

        if (cached != -1)
                return cached;

        if (stat ("/", &root) || stat ("/proc/1/root", &init_root))
                /* We can't tell, but are unlikely to be able to tell in the
                 * future either.
                 */
                cached = 0;
        else if (root.st_dev == init_root.st_dev &&
                 root.st_ino == init_root.st_ino)
                /* / has the same dev/ino as /sbin/init's root, so we're not
                 * in a chroot.
                 */
                cached = 0;
        else
                /* We must be in a chroot. */
                cached = 1;

        return cached;
}

/* Return nonzero upon success, 0 if something fails.  */
static int
linux_disk_commit (PedDisk* disk)
{
        int ret = 1;

        /* Modern versions of udev may notice the write activity on
         * partition devices caused by _flush_cache, and may decide to
         * synthesise some change events as a result. These may in turn run
         * programs that open partition devices, which will race with us
         * trying to remove those devices. To avoid this, we need to wait
         * until udevd has finished processing its event queue.
         * TODO: for upstream submission, this should check whether udevadm
         * exists on $PATH.
         */
        if (!_chrooted () && system ("udevadm settle") != 0) {
                /* ignore failures */
        }

        if (disk->dev->type != PED_DEVICE_FILE) {

		/* We now require BLKPG support.  If this assertion fails,
		   please write to the mailing list describing your system.
		   Assuming it's never triggered, ...
		   FIXME: remove this assertion in 2012.  */
		assert (_have_blkpg ());

		if (!_disk_sync_part_table (disk))
			ret = 0;
        }

        /* Now we wait for udevd to finish creating device nodes based on
         * the above activity, so that callers can reliably use them.
         * TODO: for upstream submission, this should check whether udevadm
         * exists on $PATH.
         */
        if (!_chrooted () && system ("udevadm settle") != 0) {
                /* ignore failures */
        }

        return ret;
}

#if USE_BLKID
static PedAlignment*
linux_get_minimum_alignment(const PedDevice *dev)
{
        blkid_topology tp = LINUX_SPECIFIC(dev)->topology;
        if (!tp)
                return NULL;

        if (blkid_topology_get_minimum_io_size(tp) == 0)
                return ped_alignment_new(
                        blkid_topology_get_alignment_offset(tp) /
                                dev->sector_size,
                        dev->phys_sector_size / dev->sector_size);

        return ped_alignment_new(
                blkid_topology_get_alignment_offset(tp) / dev->sector_size,
                blkid_topology_get_minimum_io_size(tp) / dev->sector_size);
}

static PedAlignment*
linux_get_optimum_alignment(const PedDevice *dev)
{
        blkid_topology tp = LINUX_SPECIFIC(dev)->topology;
        if (!tp)
                return NULL;

        /* When PED_DEFAULT_ALIGNMENT is divisible by the *_io_size or
	   there are no *_io_size values, use the PED_DEFAULT_ALIGNMENT
           If one or the other will not divide evenly, fall through to
           previous logic. */
        unsigned long optimal_io = blkid_topology_get_optimal_io_size(tp);
        unsigned long minimum_io = blkid_topology_get_minimum_io_size(tp);
        if (
            (!optimal_io && !minimum_io)
	    || (optimal_io && PED_DEFAULT_ALIGNMENT % optimal_io == 0
		&& minimum_io && PED_DEFAULT_ALIGNMENT % minimum_io == 0)
	    || (!minimum_io && optimal_io
		&& PED_DEFAULT_ALIGNMENT % optimal_io == 0)
	    || (!optimal_io && minimum_io
		&& PED_DEFAULT_ALIGNMENT % minimum_io == 0)
           ) {
            /* DASD needs to use minimum alignment */
            if (dev->type == PED_DEVICE_DASD)
                return linux_get_minimum_alignment(dev);

            return ped_alignment_new(
                    blkid_topology_get_alignment_offset(tp) / dev->sector_size,
                    PED_DEFAULT_ALIGNMENT / dev->sector_size);
        }

        /* If optimal_io_size is 0 and we don't meet the other criteria
           for using the device.c default, return the minimum alignment. */
        if (blkid_topology_get_optimal_io_size(tp) == 0)
                return linux_get_minimum_alignment(dev);

        return ped_alignment_new(
                blkid_topology_get_alignment_offset(tp) / dev->sector_size,
                blkid_topology_get_optimal_io_size(tp) / dev->sector_size);
}
#endif

static PedDeviceArchOps linux_dev_ops = {
        _new:           linux_new,
        destroy:        linux_destroy,
        is_busy:        linux_is_busy,
        open:           linux_open,
        refresh_open:   linux_refresh_open,
        close:          linux_close,
        refresh_close:  linux_refresh_close,
        read:           linux_read,
        write:          linux_write,
        check:          linux_check,
        sync:           linux_sync,
        sync_fast:      linux_sync_fast,
        probe_all:      linux_probe_all,
#if USE_BLKID
        get_minimum_alignment:	linux_get_minimum_alignment,
        get_optimum_alignment:	linux_get_optimum_alignment,
#endif
};

PedDiskArchOps linux_disk_ops =  {
        partition_get_path:     linux_partition_get_path,
        partition_is_busy:      linux_partition_is_busy,
        disk_commit:            linux_disk_commit
};

PedArchitecture ped_linux_arch = {
        dev_ops:        &linux_dev_ops,
        disk_ops:       &linux_disk_ops
};