VeraCrypt
aboutsummaryrefslogtreecommitdiff
path: root/src/Format/InPlace.c
blob: d844be2ce0f862d95bbf07239eb5de8d7c9b8c86 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
/*
 Derived from source code of TrueCrypt 7.1a, which is
 Copyright (c) 2008-2012 TrueCrypt Developers Association and which is governed
 by the TrueCrypt License 3.0.

 Modifications and additions to the original source code (contained in this file)
 and all other portions of this file are Copyright (c) 2013-2017 IDRIX
 and are governed by the Apache License 2.0 the full text of which is
 contained in the file License.txt included in VeraCrypt binary and source
 code distribution packages.
*/


/* In this file, _WIN32_WINNT is defined as 0x0600 to make filesystem shrink available (Vista
or later). _WIN32_WINNT cannot be defined as 0x0600 for the entire user-space projects
because it breaks the main font app when the app is running on XP (likely an MS bug).
IMPORTANT: Due to this issue, functions in this file must not directly interact with GUI. */
#define TC_LOCAL_WIN32_WINNT_OVERRIDE	 1
#if (_WIN32_WINNT < 0x0600)
#	undef _WIN32_WINNT
#	define _WIN32_WINNT 0x0600
#endif


#include <stdlib.h>
#include <string.h>
#include <string>
#include <intsafe.h>

#include "Tcdefs.h"
#include "Platform/Finally.h"

#include "Common.h"
#include "Crc.h"
#include "Dlgcode.h"
#include "Language.h"
#include "Tcformat.h"
#include "Volumes.h"

#include "InPlace.h"

#include <Strsafe.h>

using namespace std;
using namespace VeraCrypt;

#if TC_VOLUME_DATA_OFFSET != 131072
#	error TC_VOLUME_DATA_OFFSET != 131072
#endif

#if TC_VOLUME_HEADER_EFFECTIVE_SIZE != 512
#	error TC_VOLUME_HEADER_EFFECTIVE_SIZE != 512
#endif

#if TC_TOTAL_VOLUME_HEADERS_SIZE != 262144
#	error TC_TOTAL_VOLUME_HEADERS_SIZE != 262144
#endif

#define TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE	(2048 * BYTES_PER_KB)
#define TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE		(2 * TC_MAX_VOLUME_SECTOR_SIZE)
#define TC_NTFS_CONCEAL_CONSTANT	0xFF
#define TC_NONSYS_INPLACE_ENC_HEADER_UPDATE_INTERVAL	(64 * BYTES_PER_MB)
#define TC_NONSYS_INPLACE_ENC_MIN_VOL_SIZE			(TC_TOTAL_VOLUME_HEADERS_SIZE + TC_MIN_NTFS_FS_SIZE * 2)


// If the returned value is greater than 0, it is the desired volume size in NTFS sectors (not in bytes)
// after shrinking has been performed. If there's any error, returns -1.
static __int64 NewFileSysSizeAfterShrink (HANDLE dev, const wchar_t *devicePath, int64 *totalClusterCount, DWORD *bytesPerCluster, BOOL silent)
{
	NTFS_VOLUME_DATA_BUFFER ntfsVolData;
	DWORD nBytesReturned;
	__int64 fileSysSize, desiredNbrSectors;

	// Filesystem size and sector size

	if (!DeviceIoControl (dev,
		FSCTL_GET_NTFS_VOLUME_DATA,
		NULL,
		0,
		(LPVOID) &ntfsVolData,
		sizeof (ntfsVolData),
		&nBytesReturned,
		NULL))
	{
		if (!silent)
			handleWin32Error (MainDlg, SRC_POS);

		return -1;
	}

	if (	(ntfsVolData.NumberSectors.QuadPart <= 0)
		||	(ntfsVolData.NumberSectors.QuadPart > (INT64_MAX / (__int64) ntfsVolData.BytesPerSector)) // overflow test
		)
	{
		SetLastError (ERROR_INTERNAL_ERROR);
		if (!silent)
			handleWin32Error (MainDlg, SRC_POS);

		return -1;
	}

	fileSysSize = ntfsVolData.NumberSectors.QuadPart * ntfsVolData.BytesPerSector;

	desiredNbrSectors = (fileSysSize - TC_TOTAL_VOLUME_HEADERS_SIZE) / ntfsVolData.BytesPerSector;

	if (desiredNbrSectors <= 0)
		return -1;

	if (totalClusterCount)
		*totalClusterCount = ntfsVolData.TotalClusters.QuadPart;
	if (bytesPerCluster)
		*bytesPerCluster = ntfsVolData.BytesPerCluster;

	return desiredNbrSectors;
}


BOOL CheckRequirementsForNonSysInPlaceEnc (HWND hwndDlg, const wchar_t *devicePath, BOOL silent)
{
	NTFS_VOLUME_DATA_BUFFER ntfsVolData;
	DWORD nBytesReturned;
	HANDLE dev;
	WCHAR szFileSysName [256];
	WCHAR devPath [MAX_PATH];
	WCHAR dosDev [TC_MAX_PATH] = {0};
	WCHAR devName [MAX_PATH] = {0};
	int driveLetterNo = -1;
	WCHAR szRootPath[4] = {0, L':', L'\\', 0};
	__int64 deviceSize;
	int partitionNumber = -1, driveNumber = -1;


	/* ---------- Checks that do not require admin rights ----------- */


	/* Operating system */

	if (CurrentOSMajor < 6)
	{
		if (!silent)
			ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "OS_NOT_SUPPORTED_FOR_NONSYS_INPLACE_ENC", FALSE);

		return FALSE;
	}


	/* Volume type (must be a partition or a dynamic volume) */

	if (swscanf (devicePath, L"\\Device\\HarddiskVolume%d", &partitionNumber) != 1
		&& swscanf (devicePath, L"\\Device\\Harddisk%d\\Partition%d", &driveNumber, &partitionNumber) != 2)
	{
		if (!silent)
			Error ("INPLACE_ENC_INVALID_PATH", hwndDlg);

		return FALSE;
	}

	if (partitionNumber == 0)
	{
		if (!silent)
			Warning ("RAW_DEV_NOT_SUPPORTED_FOR_INPLACE_ENC", hwndDlg);

		return FALSE;
	}


	/* Admin rights */

	if (!IsAdmin())
	{
		// We rely on the wizard process to call us only when the whole wizard process has been elevated (so UAC
		// status can be ignored). In case the IsAdmin() detection somehow fails, we allow the user to continue.

		if (!silent)
			Warning ("ADMIN_PRIVILEGES_WARN_DEVICES", hwndDlg);
	}


	/* ---------- Checks that may require admin rights ----------- */


	/* Access to the partition */

	StringCbCopyW (devPath, sizeof(devPath), devicePath);

	driveLetterNo = GetDiskDeviceDriveLetter (devPath);

	if (driveLetterNo >= 0)
		szRootPath[0] = (wchar_t) driveLetterNo + L'A';

	if (FakeDosNameForDevice (devicePath, dosDev, sizeof(dosDev), devName, sizeof(devName),FALSE) != 0)
	{
		if (!silent)
		{
			handleWin32Error (hwndDlg, SRC_POS);
			Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", hwndDlg);
		}
		return FALSE;
	}

	dev = OpenPartitionVolume (hwndDlg, devName,
		FALSE,	// Do not require exclusive access
		TRUE,	// Require shared access (must be TRUE; otherwise, volume properties will not be possible to obtain)
		FALSE,	// Do not ask the user to confirm shared access (if exclusive fails)
		FALSE,	// Do not append alternative instructions how to encrypt the data (to applicable error messages)
		silent);	// Silent mode

	if (dev == INVALID_HANDLE_VALUE)
		return FALSE;


	/* File system type */

	GetVolumeInformation (szRootPath, NULL, 0, NULL, NULL, NULL, szFileSysName, ARRAYSIZE (szFileSysName));

	if (wcsncmp (szFileSysName, L"NTFS", 4))
	{
		// The previous filesystem type detection method failed (or it's not NTFS) -- try an alternative method

		if (!DeviceIoControl (dev,
			FSCTL_GET_NTFS_VOLUME_DATA,
			NULL,
			0,
			(LPVOID) &ntfsVolData,
			sizeof (ntfsVolData),
			&nBytesReturned,
			NULL))
		{
			if (!silent)
			{
				// The filesystem is not NTFS or the filesystem type could not be determined (or the NTFS filesystem
				// is dismounted).

				if (IsDeviceMounted (devName))
					ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "ONLY_NTFS_SUPPORTED_FOR_NONSYS_INPLACE_ENC", FALSE);
				else
					Warning ("ONLY_MOUNTED_VOL_SUPPORTED_FOR_NONSYS_INPLACE_ENC", hwndDlg);
			}

			CloseHandle (dev);
			return FALSE;
		}
	}


	/* Attempt to determine whether the filesystem can be safely shrunk */

	if (NewFileSysSizeAfterShrink (dev, devicePath, NULL, NULL, silent) == -1)
	{
		// Cannot determine whether shrinking is required
		if (!silent)
			ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE);

		CloseHandle (dev);
		return FALSE;
	}


	/* Partition size */

	deviceSize = GetDeviceSize (devicePath);
	if (deviceSize < 0)
	{
		// Cannot determine the size of the partition
		if (!silent)
			Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", hwndDlg);

		CloseHandle (dev);
		return FALSE;
	}

	if (deviceSize < TC_NONSYS_INPLACE_ENC_MIN_VOL_SIZE)
	{
		// The partition is too small
		if (!silent)
		{
			ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "PARTITION_TOO_SMALL_FOR_NONSYS_INPLACE_ENC", FALSE);
		}

		CloseHandle (dev);
		return FALSE;
	}


	/* Free space on the filesystem */

	if (!DeviceIoControl (dev,
		FSCTL_GET_NTFS_VOLUME_DATA,
		NULL,
		0,
		(LPVOID) &ntfsVolData,
		sizeof (ntfsVolData),
		&nBytesReturned,
		NULL))
	{
		if (!silent)
			ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", TRUE);

		CloseHandle (dev);
		return FALSE;
	}

	if (ntfsVolData.FreeClusters.QuadPart * ntfsVolData.BytesPerCluster < TC_TOTAL_VOLUME_HEADERS_SIZE)
	{
		if (!silent)
			ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "NOT_ENOUGH_FREE_FILESYS_SPACE_FOR_SHRINK", TRUE);

		CloseHandle (dev);
		return FALSE;
	}


	/* Filesystem sector size */

	if (ntfsVolData.BytesPerSector > TC_MAX_VOLUME_SECTOR_SIZE
		|| ntfsVolData.BytesPerSector % ENCRYPTION_DATA_UNIT_SIZE != 0)
	{
		if (!silent)
			ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "SECTOR_SIZE_UNSUPPORTED", TRUE);

		CloseHandle (dev);
		return FALSE;
	}


	CloseHandle (dev);
	return TRUE;
}

BOOL CheckRequirementsForNonSysInPlaceDec (HWND hwndDlg, const wchar_t *devicePath, BOOL silent)
{
	int partitionNumber = -1, driveNumber = -1;

	/* ---------- Checks that do not require admin rights ----------- */

	/* Volume type (must be a partition or a dynamic volume) */
	if ((swscanf (devicePath, L"\\Device\\HarddiskVolume%d", &partitionNumber) != 1
		&& swscanf (devicePath, L"\\Device\\Harddisk%d\\Partition%d", &driveNumber, &partitionNumber) != 2)
		|| partitionNumber == 0)
	{
		if (!silent)
			Error ("INPLACE_ENC_INVALID_PATH", hwndDlg);

		return FALSE;
	}


	/* Admin rights */
	if (!IsAdmin())
	{
		// We rely on the wizard process to call us only when the whole wizard process has been elevated (so UAC
		// status can be ignored). In case the IsAdmin() detection somehow fails, we allow the user to continue.

		if (!silent)
			Warning ("ADMIN_PRIVILEGES_WARN_DEVICES", hwndDlg);
	}


	/* ---------- Checks that may require admin rights ----------- */

	// [Currently none]

	return TRUE;
}


int EncryptPartitionInPlaceBegin (volatile FORMAT_VOL_PARAMETERS *volParams, volatile HANDLE *outHandle, WipeAlgorithmId wipeAlgorithm)
{
	SHRINK_VOLUME_INFORMATION shrinkVolInfo;
	signed __int64 sizeToShrinkTo;
	int nStatus = ERR_SUCCESS;
	PCRYPTO_INFO cryptoInfo = NULL;
	PCRYPTO_INFO cryptoInfo2 = NULL;
	HANDLE dev = INVALID_HANDLE_VALUE;
	DWORD dwError;
	char *header;
	WCHAR dosDev[TC_MAX_PATH] = {0};
	WCHAR devName[MAX_PATH] = {0};
	int driveLetter = -1;
	WCHAR deviceName[MAX_PATH];
	uint64 dataAreaSize;
	__int64 deviceSize;
	LARGE_INTEGER offset;
	DWORD dwResult;
	HWND hwndDlg = volParams->hwndDlg;

	SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PREPARING);


	if (!CheckRequirementsForNonSysInPlaceEnc (hwndDlg, volParams->volumePath, FALSE))
		return ERR_DONT_REPORT;


	header = (char *) TCalloc (TC_VOLUME_HEADER_EFFECTIVE_SIZE);
	if (!header)
		return ERR_OUTOFMEMORY;

	VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);

	deviceSize = GetDeviceSize (volParams->volumePath);
	if (deviceSize < 0)
	{
		// Cannot determine the size of the partition
		nStatus = ERR_PARAMETER_INCORRECT;
		goto closing_seq;
	}

	if (deviceSize < TC_NONSYS_INPLACE_ENC_MIN_VOL_SIZE)
	{
		ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "PARTITION_TOO_SMALL_FOR_NONSYS_INPLACE_ENC", TRUE);
		nStatus = ERR_DONT_REPORT;
		goto closing_seq;
	}

	dataAreaSize = GetVolumeDataAreaSize (volParams->hiddenVol, deviceSize);

	StringCchCopyW (deviceName, ARRAYSIZE(deviceName), volParams->volumePath);

	driveLetter = GetDiskDeviceDriveLetter (deviceName);


	if (FakeDosNameForDevice (volParams->volumePath, dosDev, sizeof(dosDev),devName, sizeof(devName),FALSE) != 0)
	{
		nStatus = ERR_OS_ERROR;
		goto closing_seq;
	}

	if (IsDeviceMounted (devName))
	{
		dev = OpenPartitionVolume (hwndDlg, devName,
			FALSE,	// Do not require exclusive access (must be FALSE; otherwise, it will not be possible to dismount the volume or obtain its properties and FSCTL_ALLOW_EXTENDED_DASD_IO will fail too)
			TRUE,	// Require shared access (must be TRUE; otherwise, it will not be possible to dismount the volume or obtain its properties and FSCTL_ALLOW_EXTENDED_DASD_IO will fail too)
			FALSE,	// Do not ask the user to confirm shared access (if exclusive fails)
			FALSE,	// Do not append alternative instructions how to encrypt the data (to applicable error messages)
			FALSE);	// Non-silent mode

		if (dev == INVALID_HANDLE_VALUE)
		{
			nStatus = ERR_DONT_REPORT;
			goto closing_seq;
		}
	}
	else
	{
		// The volume is not mounted so we can't work with the filesystem.
		Error ("ONLY_MOUNTED_VOL_SUPPORTED_FOR_NONSYS_INPLACE_ENC", hwndDlg);
		nStatus = ERR_DONT_REPORT;
		goto closing_seq;
	}


	/* Gain "raw" access to the partition (the NTFS driver guards hidden sectors). */

	if (!DeviceIoControl (dev,
		FSCTL_ALLOW_EXTENDED_DASD_IO,
		NULL,
		0,
		NULL,
		0,
		&dwResult,
		NULL))
	{
		handleWin32Error (MainDlg, SRC_POS);
		ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE);
		nStatus = ERR_DONT_REPORT;
		goto closing_seq;
	}



	/* Shrink the filesystem */

	int64 totalClusterCount;
	DWORD bytesPerCluster;

	sizeToShrinkTo = NewFileSysSizeAfterShrink (dev, volParams->volumePath, &totalClusterCount, &bytesPerCluster, FALSE);

	if (sizeToShrinkTo == -1)
	{
		ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE);
		nStatus = ERR_DONT_REPORT;
		goto closing_seq;
	}

	SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_RESIZING);

	memset (&shrinkVolInfo, 0, sizeof (shrinkVolInfo));

	shrinkVolInfo.ShrinkRequestType = ShrinkPrepare;
	shrinkVolInfo.NewNumberOfSectors = sizeToShrinkTo;

	if (!DeviceIoControl (dev,
		FSCTL_SHRINK_VOLUME,
		(LPVOID) &shrinkVolInfo,
		sizeof (shrinkVolInfo),
		NULL,
		0,
		&dwResult,
		NULL))
	{
		handleWin32Error (hwndDlg, SRC_POS);
		ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "CANNOT_RESIZE_FILESYS", TRUE);
		nStatus = ERR_DONT_REPORT;
		goto closing_seq;
	}

	BOOL clustersMovedBeforeVolumeEnd = FALSE;

	while (true)
	{
		shrinkVolInfo.ShrinkRequestType = ShrinkCommit;
		shrinkVolInfo.NewNumberOfSectors = 0;

		if (!DeviceIoControl (dev, FSCTL_SHRINK_VOLUME, &shrinkVolInfo, sizeof (shrinkVolInfo), NULL, 0, &dwResult, NULL))
		{
			// If there are any occupied clusters beyond the new desired end of the volume, the call fails with
			// ERROR_ACCESS_DENIED (STATUS_ALREADY_COMMITTED).
			if (GetLastError () == ERROR_ACCESS_DENIED)
			{
				if (!clustersMovedBeforeVolumeEnd)
				{
					if (MoveClustersBeforeThreshold (dev, deviceName, totalClusterCount - (bytesPerCluster > TC_TOTAL_VOLUME_HEADERS_SIZE ? 1 : TC_TOTAL_VOLUME_HEADERS_SIZE / bytesPerCluster)))
					{
						clustersMovedBeforeVolumeEnd = TRUE;
						continue;
					}

					handleWin32Error (hwndDlg, SRC_POS);
				}
			}
			else
				handleWin32Error (hwndDlg, SRC_POS);

			ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "CANNOT_RESIZE_FILESYS", TRUE);
			nStatus = ERR_DONT_REPORT;
			goto closing_seq;
		}

		break;
	}

	SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PREPARING);


	/* Gain exclusive access to the volume */

	nStatus = DismountFileSystem (hwndDlg, dev,
		driveLetter,
		TRUE,
		TRUE,
		FALSE);

	if (nStatus != ERR_SUCCESS)
	{
		nStatus = ERR_DONT_REPORT;
		goto closing_seq;
	}



	/* Create header backup on the partition. Until the volume is fully encrypted, the backup header will provide
	us with the master key, encrypted range, and other data for pause/resume operations. We cannot create the
	primary header until the entire partition is encrypted (because we encrypt backwards and the primary header
	area is occuppied by data until the very end of the process). */

	// Prepare the backup header
	for (int wipePass = 0; wipePass < (wipeAlgorithm == TC_WIPE_NONE ? 1 : PRAND_HEADER_WIPE_PASSES); wipePass++)
	{
		PCRYPTO_INFO dummyInfo = NULL;

		nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE,
			header,
			volParams->ea,
			FIRST_MODE_OF_OPERATION_ID,
			volParams->password,
			volParams->pkcs5,
			volParams->pim,
			wipePass == 0 ? NULL : (char *) cryptoInfo->master_keydata,
			&cryptoInfo,
			dataAreaSize,
			0,
			TC_VOLUME_DATA_OFFSET + dataAreaSize,	// Start of the encrypted area = the first byte of the backup heeader (encrypting from the end)
			0,	// No data is encrypted yet
			0,
			volParams->headerFlags | TC_HEADER_FLAG_NONSYS_INPLACE_ENC,
			volParams->sectorSize,
			wipeAlgorithm == TC_WIPE_NONE ? FALSE : (wipePass < PRAND_HEADER_WIPE_PASSES - 1));

		if (nStatus != 0)
			goto closing_seq;

		offset.QuadPart = TC_VOLUME_DATA_OFFSET + dataAreaSize;

		if (!SetFilePointerEx (dev, offset, NULL, FILE_BEGIN))
		{
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}

		// Write the backup header to the partition
		if (!WriteEffectiveVolumeHeader (TRUE, dev, (byte *) header))
		{
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}

		// Fill the reserved sectors of the backup header area with random data
		nStatus = WriteRandomDataToReservedHeaderAreas (hwndDlg, dev, cryptoInfo, dataAreaSize, FALSE, TRUE);

		if (nStatus != ERR_SUCCESS)
			goto closing_seq;

		// write fake hidden volume header to protect against attacks that use statistical entropy
		// analysis to detect presence of hidden volumes
		nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE,
			header,
			volParams->ea,
			FIRST_MODE_OF_OPERATION_ID,
			NULL,
			0,
			0,
			NULL,
			&dummyInfo,
			dataAreaSize,
			dataAreaSize,
			TC_VOLUME_DATA_OFFSET + dataAreaSize,	// Start of the encrypted area = the first byte of the backup heeader (encrypting from the end)
			dataAreaSize,	// No data is encrypted yet
			0,
			volParams->headerFlags | TC_HEADER_FLAG_NONSYS_INPLACE_ENC,
			volParams->sectorSize,
			wipeAlgorithm == TC_WIPE_NONE ? FALSE : (wipePass < PRAND_HEADER_WIPE_PASSES - 1));

		if (nStatus != ERR_SUCCESS)
			goto closing_seq;

		crypto_close (dummyInfo);

		offset.QuadPart += TC_HIDDEN_VOLUME_HEADER_OFFSET;

		if (!SetFilePointerEx (dev, offset, NULL, FILE_BEGIN))
		{
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}

		// Write the fake hidden backup header to the partition
		if (!WriteEffectiveVolumeHeader (TRUE, dev, (byte *) header))
		{
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}

	}


	/* Now we will try to decrypt the backup header to verify it has been correctly written. */

	nStatus = OpenBackupHeader (dev, volParams->volumePath, volParams->password, volParams->pkcs5, volParams->pim, &cryptoInfo2, NULL, deviceSize);

	if (nStatus != ERR_SUCCESS
		|| cryptoInfo->EncryptedAreaStart.Value != cryptoInfo2->EncryptedAreaStart.Value
		|| cryptoInfo2->EncryptedAreaStart.Value == 0)
	{
		if (nStatus == ERR_SUCCESS)
			nStatus = ERR_PARAMETER_INCORRECT;

		goto closing_seq;
	}

	// The backup header is valid so we know we should be able to safely resume in-place encryption
	// of this partition even if the system/app crashes.



	/* Conceal the NTFS filesystem (by performing an easy-to-undo modification). This will prevent Windows
	and apps from interfering with the volume until it has been fully encrypted. */

	nStatus = ConcealNTFS (dev);

	if (nStatus != ERR_SUCCESS)
		goto closing_seq;



	// /* If a drive letter is assigned to the device, remove it (so that users do not try to open it, which
	//would cause Windows to ask them if they want to format the volume and other dangerous things). */

	//if (driveLetter >= 0)
	//{
	//	char rootPath[] = { driveLetter + 'A', ':', '\\', 0 };

	//	// Try to remove the assigned drive letter
	//	if (DeleteVolumeMountPoint (rootPath))
	//		driveLetter = -1;
	//}



	/* Update config files and app data */

	// In the config file, increase the number of partitions where in-place encryption is in progress

	SaveNonSysInPlaceEncSettings (1, wipeAlgorithm, FALSE);


	// Add the wizard to the system startup sequence if appropriate

	if (!IsNonInstallMode ())
		ManageStartupSeqWiz (FALSE, L"/prinplace");


	nStatus = ERR_SUCCESS;


closing_seq:

	dwError = GetLastError();

	if (cryptoInfo != NULL)
	{
		crypto_close (cryptoInfo);
		cryptoInfo = NULL;
	}

	if (cryptoInfo2 != NULL)
	{
		crypto_close (cryptoInfo2);
		cryptoInfo2 = NULL;
	}

	burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
	VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
	TCfree (header);

	if (dosDev[0])
		RemoveFakeDosName (volParams->volumePath, dosDev);

	*outHandle = dev;

	if (nStatus != ERR_SUCCESS)
		SetLastError (dwError);

	return nStatus;
}


int EncryptPartitionInPlaceResume (HANDLE dev,
								   volatile FORMAT_VOL_PARAMETERS *volParams,
								   WipeAlgorithmId wipeAlgorithm,
								   volatile BOOL *bTryToCorrectReadErrors)
{
	PCRYPTO_INFO masterCryptoInfo = NULL, headerCryptoInfo = NULL, tmpCryptoInfo = NULL;
	UINT64_STRUCT unitNo;
	char *buf = NULL, *header = NULL;
	byte *wipeBuffer = NULL;
	byte wipeRandChars [TC_WIPE_RAND_CHAR_COUNT];
	byte wipeRandCharsUpdate [TC_WIPE_RAND_CHAR_COUNT];
	WCHAR dosDev[TC_MAX_PATH] = {0};
	WCHAR devName[MAX_PATH] = {0};
	WCHAR deviceName[MAX_PATH];
	int nStatus = ERR_SUCCESS;
	__int64 deviceSize;
	uint64 remainingBytes, lastHeaderUpdateDistance = 0, zeroedSectorCount = 0;
	uint32 workChunkSize;
	DWORD dwError, dwResult;
	BOOL bPause = FALSE, bEncryptedAreaSizeChanged = FALSE;
	LARGE_INTEGER offset;
	int sectorSize;
	int i;
	DWORD n;
	WCHAR *devicePath = volParams->volumePath;
	Password *password = volParams->password;
	int pkcs5_prf = volParams->pkcs5;
	int pim = volParams->pim;
	DISK_GEOMETRY driveGeometry;
	HWND hwndDlg = volParams->hwndDlg;


	bInPlaceEncNonSysResumed = TRUE;

	buf = (char *) TCalloc (TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE);
	if (!buf)
	{
		nStatus = ERR_OUTOFMEMORY;
		goto closing_seq;
	}

	header = (char *) TCalloc (TC_VOLUME_HEADER_EFFECTIVE_SIZE);
	if (!header)
	{
		nStatus = ERR_OUTOFMEMORY;
		goto closing_seq;
	}

	VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);

	if (wipeAlgorithm != TC_WIPE_NONE)
	{
		wipeBuffer = (byte *) TCalloc (TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE);
		if (!wipeBuffer)
		{
			nStatus = ERR_OUTOFMEMORY;
			goto closing_seq;
		}
	}

	headerCryptoInfo = crypto_open();

	if (headerCryptoInfo == NULL)
	{
		nStatus = ERR_OUTOFMEMORY;
		goto closing_seq;
	}

	deviceSize = GetDeviceSize (devicePath);
	if (deviceSize < 0)
	{
		// Cannot determine the size of the partition
		nStatus = ERR_OS_ERROR;
		goto closing_seq;
	}

	if (dev == INVALID_HANDLE_VALUE)
	{
		StringCchCopyW (deviceName, ARRAYSIZE(deviceName), devicePath);

		if (FakeDosNameForDevice (deviceName, dosDev, sizeof(dosDev),devName, sizeof(devName),FALSE) != 0)
		{
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}

		dev = OpenPartitionVolume (hwndDlg, devName,
			FALSE,	// Do not require exclusive access
			FALSE,	// Do not require shared access
			TRUE,	// Ask the user to confirm shared access (if exclusive fails)
			FALSE,	// Do not append alternative instructions how to encrypt the data (to applicable error messages)
			FALSE);	// Non-silent mode

		if (dev == INVALID_HANDLE_VALUE)
		{
			nStatus = ERR_DONT_REPORT;
			goto closing_seq;
		}
	}

	// This should never be needed, but is still performed for extra safety (without checking the result)
	DeviceIoControl (dev,
		FSCTL_ALLOW_EXTENDED_DASD_IO,
		NULL,
		0,
		NULL,
		0,
		&dwResult,
		NULL);


	if (!DeviceIoControl (dev, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &driveGeometry, sizeof (driveGeometry), &dwResult, NULL))
	{
		nStatus = ERR_OS_ERROR;
		goto closing_seq;
	}

	sectorSize = driveGeometry.BytesPerSector;


	nStatus = OpenBackupHeader (dev, devicePath, password, pkcs5_prf, pim, &masterCryptoInfo, headerCryptoInfo, deviceSize);

	if (nStatus != ERR_SUCCESS)
		goto closing_seq;

#ifdef _WIN64
	if (IsRamEncryptionEnabled ())
	{
		VcProtectKeys (masterCryptoInfo, VcGetEncryptionID (masterCryptoInfo));
		VcProtectKeys (headerCryptoInfo, VcGetEncryptionID (headerCryptoInfo));
	}
#endif


    remainingBytes = masterCryptoInfo->VolumeSize.Value - masterCryptoInfo->EncryptedAreaLength.Value;

	lastHeaderUpdateDistance = 0;


	ExportProgressStats (masterCryptoInfo->EncryptedAreaLength.Value, masterCryptoInfo->VolumeSize.Value);

	SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_ENCRYPTING);

	bFirstNonSysInPlaceEncResumeDone = TRUE;


	/* The in-place encryption core */

	while (remainingBytes > 0)
	{
		workChunkSize = (uint32) min (remainingBytes, TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE);

		if (workChunkSize % ENCRYPTION_DATA_UNIT_SIZE != 0)
		{
			nStatus = ERR_PARAMETER_INCORRECT;
			goto closing_seq;
		}

		unitNo.Value = (remainingBytes - workChunkSize + TC_VOLUME_DATA_OFFSET) / ENCRYPTION_DATA_UNIT_SIZE;


		// Read the plaintext into RAM

inplace_enc_read:

		offset.QuadPart = masterCryptoInfo->EncryptedAreaStart.Value - workChunkSize - TC_VOLUME_DATA_OFFSET;

		if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0)
		{
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}

		if (ReadFile (dev, buf, workChunkSize, &n, NULL) == 0)
		{
			// Read error

			DWORD dwTmpErr = GetLastError ();

			if (IsDiskReadError (dwTmpErr) && !bVolTransformThreadCancel)
			{
				// Physical defect or data corruption

				if (!*bTryToCorrectReadErrors)
				{
					*bTryToCorrectReadErrors = (AskWarnYesNo ("ENABLE_BAD_SECTOR_ZEROING", hwndDlg) == IDYES);
				}

				if (*bTryToCorrectReadErrors)
				{
					// Try to correct the read errors physically

					offset.QuadPart = masterCryptoInfo->EncryptedAreaStart.Value - workChunkSize - TC_VOLUME_DATA_OFFSET;

					nStatus = ZeroUnreadableSectors (dev, offset, workChunkSize, sectorSize, &zeroedSectorCount);

					if (nStatus != ERR_SUCCESS)
					{
						// Due to write errors, we can't correct the read errors
						nStatus = ERR_OS_ERROR;
						goto closing_seq;
					}

					goto inplace_enc_read;
				}
			}

			SetLastError (dwTmpErr);		// Preserve the original error code

			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}

		if (remainingBytes - workChunkSize < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE)
		{
			// We reached the inital portion of the filesystem, which we had concealed (in order to prevent
			// Windows from interfering with the volume). Now we need to undo that modification.

			for (i = 0; i < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE - (remainingBytes - workChunkSize); i++)
				buf[i] ^= TC_NTFS_CONCEAL_CONSTANT;
		}


		// Encrypt the plaintext in RAM

		EncryptDataUnits ((byte *) buf, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo);


		// If enabled, wipe the area to which we will write the ciphertext

		if (wipeAlgorithm != TC_WIPE_NONE)
		{
			byte wipePass;
			int wipePassCount = GetWipePassCount (wipeAlgorithm);

			if (wipePassCount <= 0)
			{
				SetLastError (ERROR_INVALID_PARAMETER);
				nStatus = ERR_PARAMETER_INCORRECT;
				goto closing_seq;
			}

			offset.QuadPart = masterCryptoInfo->EncryptedAreaStart.Value - workChunkSize;

			for (wipePass = 1; wipePass <= wipePassCount; ++wipePass)
			{
				if (!WipeBuffer (wipeAlgorithm, wipeRandChars, wipePass, wipeBuffer, workChunkSize))
				{
					ULONG i;
					for (i = 0; i < workChunkSize; ++i)
					{
						wipeBuffer[i] = buf[i] + wipePass;
					}

					EncryptDataUnits (wipeBuffer, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo);
					memcpy (wipeRandCharsUpdate, wipeBuffer, sizeof (wipeRandCharsUpdate));
				}

				if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
					|| WriteFile (dev, wipeBuffer, workChunkSize, &n, NULL) == 0)
				{
					// Write error
					dwError = GetLastError();

					// Undo failed write operation
					if (workChunkSize > TC_VOLUME_DATA_OFFSET && SetFilePointerEx (dev, offset, NULL, FILE_BEGIN))
					{
						DecryptDataUnits ((byte *) buf, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo);
						WriteFile (dev, buf + TC_VOLUME_DATA_OFFSET, workChunkSize - TC_VOLUME_DATA_OFFSET, &n, NULL);
					}

					SetLastError (dwError);
					nStatus = ERR_OS_ERROR;
					goto closing_seq;
				}
			}

			memcpy (wipeRandChars, wipeRandCharsUpdate, sizeof (wipeRandCharsUpdate));
		}


		// Write the ciphertext

		offset.QuadPart = masterCryptoInfo->EncryptedAreaStart.Value - workChunkSize;

		if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0)
		{
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}

		if (WriteFile (dev, buf, workChunkSize, &n, NULL) == 0)
		{
			// Write error
			dwError = GetLastError();

			// Undo failed write operation
			if (workChunkSize > TC_VOLUME_DATA_OFFSET && SetFilePointerEx (dev, offset, NULL, FILE_BEGIN))
			{
				DecryptDataUnits ((byte *) buf, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo);
				WriteFile (dev, buf + TC_VOLUME_DATA_OFFSET, workChunkSize - TC_VOLUME_DATA_OFFSET, &n, NULL);
			}

			SetLastError (dwError);
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}


		masterCryptoInfo->EncryptedAreaStart.Value -= workChunkSize;
		masterCryptoInfo->EncryptedAreaLength.Value += workChunkSize;

		remainingBytes -= workChunkSize;
		lastHeaderUpdateDistance += workChunkSize;

		bEncryptedAreaSizeChanged = TRUE;

		if (lastHeaderUpdateDistance >= TC_NONSYS_INPLACE_ENC_HEADER_UPDATE_INTERVAL)
		{
			nStatus = FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize);

			if (nStatus != ERR_SUCCESS)
				goto closing_seq;

			lastHeaderUpdateDistance = 0;
		}

		ExportProgressStats (masterCryptoInfo->EncryptedAreaLength.Value, masterCryptoInfo->VolumeSize.Value);

		if (bVolTransformThreadCancel)
		{
			bPause = TRUE;
			break;
		}
	}

	nStatus = FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize);


	if (nStatus != ERR_SUCCESS)
		goto closing_seq;


	if (!bPause)
	{
		/* The data area has been fully encrypted; create and write the primary volume header */

		SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_FINALIZING);

		for (int wipePass = 0; wipePass < (wipeAlgorithm == TC_WIPE_NONE ? 1 : PRAND_HEADER_WIPE_PASSES); wipePass++)
		{
			PCRYPTO_INFO dummyInfo = NULL;

#ifdef _WIN64
			CRYPTO_INFO tmpCI;
			PCRYPTO_INFO cryptoInfoBackup = NULL;
			if (IsRamEncryptionEnabled ())
			{
				VirtualLock (&tmpCI, sizeof(tmpCI));
				memcpy (&tmpCI, masterCryptoInfo, sizeof (CRYPTO_INFO));
				VcUnprotectKeys (&tmpCI, VcGetEncryptionID (masterCryptoInfo));
				cryptoInfoBackup = masterCryptoInfo;
				masterCryptoInfo = &tmpCI;
			}
#endif

			nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE,
				header,
				headerCryptoInfo->ea,
				headerCryptoInfo->mode,
				password,
				masterCryptoInfo->pkcs5,
				pim,
				(char *) masterCryptoInfo->master_keydata,
				&tmpCryptoInfo,
				masterCryptoInfo->VolumeSize.Value,
				0,
				masterCryptoInfo->EncryptedAreaStart.Value,
				masterCryptoInfo->EncryptedAreaLength.Value,
				masterCryptoInfo->RequiredProgramVersion,
				masterCryptoInfo->HeaderFlags | TC_HEADER_FLAG_NONSYS_INPLACE_ENC,
				masterCryptoInfo->SectorSize,
				wipeAlgorithm == TC_WIPE_NONE ? FALSE : (wipePass < PRAND_HEADER_WIPE_PASSES - 1));

#ifdef _WIN64
			if (IsRamEncryptionEnabled ())
			{
				masterCryptoInfo = cryptoInfoBackup;
				burn (&tmpCI, sizeof (CRYPTO_INFO));
				VirtualUnlock (&tmpCI, sizeof(tmpCI));
			}
#endif

			if (nStatus != ERR_SUCCESS)
				goto closing_seq;


			offset.QuadPart = TC_VOLUME_HEADER_OFFSET;

			if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
				|| !WriteEffectiveVolumeHeader (TRUE, dev, (byte *) header))
			{
				nStatus = ERR_OS_ERROR;
				goto closing_seq;
			}

#ifdef _WIN64
			if (IsRamEncryptionEnabled ())
			{
				VirtualLock (&tmpCI, sizeof(tmpCI));
				memcpy (&tmpCI, headerCryptoInfo, sizeof (CRYPTO_INFO));
				VcUnprotectKeys (&tmpCI, VcGetEncryptionID (headerCryptoInfo));
				cryptoInfoBackup = headerCryptoInfo;
				headerCryptoInfo = &tmpCI;
			}
#endif
			// Fill the reserved sectors of the header area with random data
			nStatus = WriteRandomDataToReservedHeaderAreas (hwndDlg, dev, headerCryptoInfo, masterCryptoInfo->VolumeSize.Value, TRUE, FALSE);

#ifdef _WIN64
			if (IsRamEncryptionEnabled ())
			{
				headerCryptoInfo = cryptoInfoBackup;
				burn (&tmpCI, sizeof (CRYPTO_INFO));
				VirtualUnlock (&tmpCI, sizeof(tmpCI));
			}
#endif

			if (nStatus != ERR_SUCCESS)
				goto closing_seq;

			// write fake hidden volume header to protect against attacks that use statistical entropy
			// analysis to detect presence of hidden volumes
			nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE,
				header,
				headerCryptoInfo->ea,
				headerCryptoInfo->mode,
				NULL,
				0,
				0,
				NULL,
				&dummyInfo,
				masterCryptoInfo->VolumeSize.Value,
				masterCryptoInfo->VolumeSize.Value,
				masterCryptoInfo->EncryptedAreaStart.Value,
				masterCryptoInfo->EncryptedAreaLength.Value,
				masterCryptoInfo->RequiredProgramVersion,
				masterCryptoInfo->HeaderFlags | TC_HEADER_FLAG_NONSYS_INPLACE_ENC,
				masterCryptoInfo->SectorSize,
				wipeAlgorithm == TC_WIPE_NONE ? FALSE : (wipePass < PRAND_HEADER_WIPE_PASSES - 1));

			if (nStatus != ERR_SUCCESS)
				goto closing_seq;

			crypto_close (dummyInfo);

			offset.QuadPart += TC_HIDDEN_VOLUME_HEADER_OFFSET;

			if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
				|| !WriteEffectiveVolumeHeader (TRUE, dev, (byte *) header))
			{
				nStatus = ERR_OS_ERROR;
				goto closing_seq;
			}
		}

		// Update the configuration files

		SaveNonSysInPlaceEncSettings (-1, wipeAlgorithm, FALSE);



		SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_FINISHED);

		nStatus = ERR_SUCCESS;
	}
	else
	{
		// The process has been paused by the user or aborted by the wizard (e.g. on app exit)

		nStatus = ERR_USER_ABORT;

		SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PAUSED);
	}


closing_seq:

	dwError = GetLastError();

	if (bEncryptedAreaSizeChanged
		&& dev != INVALID_HANDLE_VALUE
		&& masterCryptoInfo != NULL
		&& headerCryptoInfo != NULL
		&& deviceSize > 0)
	{
		// Execution of the core loop may have been interrupted due to an error or user action without updating the header
		FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize);
	}

	if (masterCryptoInfo != NULL)
	{
		crypto_close (masterCryptoInfo);
		masterCryptoInfo = NULL;
	}

	if (headerCryptoInfo != NULL)
	{
		crypto_close (headerCryptoInfo);
		headerCryptoInfo = NULL;
	}

	if (tmpCryptoInfo != NULL)
	{
		crypto_close (tmpCryptoInfo);
		tmpCryptoInfo = NULL;
	}

	if (dosDev[0])
		RemoveFakeDosName (devicePath, dosDev);

	if (dev != INVALID_HANDLE_VALUE)
	{
		CloseHandle (dev);
		dev = INVALID_HANDLE_VALUE;
	}

	if (buf != NULL)
		TCfree (buf);

	if (header != NULL)
	{
		burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
		VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
		TCfree (header);
	}

	if (wipeBuffer != NULL)
		TCfree (wipeBuffer);

	if (zeroedSectorCount > 0)
	{
		wchar_t msg[30000] = {0};
		wchar_t sizeStr[500] = {0};

		GetSizeString (zeroedSectorCount * sectorSize, sizeStr, sizeof(sizeStr));

		StringCbPrintfW (msg, sizeof(msg),
			GetString ("ZEROED_BAD_SECTOR_COUNT"),
			zeroedSectorCount,
			sizeStr);

		WarningDirect (msg, hwndDlg);
	}

	if (nStatus != ERR_SUCCESS && nStatus != ERR_USER_ABORT)
		SetLastError (dwError);

	return nStatus;
}

int DecryptPartitionInPlace (volatile FORMAT_VOL_PARAMETERS *volParams, volatile BOOL *DiscardUnreadableEncryptedSectors)
{
	HANDLE dev = INVALID_HANDLE_VALUE;
	PCRYPTO_INFO masterCryptoInfo = NULL, headerCryptoInfo = NULL;
	UINT64_STRUCT unitNo;
	char *buf = NULL;
	byte *tmpSectorBuf = NULL;
	WCHAR dosDev[TC_MAX_PATH] = {0};
	WCHAR devName[MAX_PATH] = {0};
	WCHAR deviceName[MAX_PATH];
	int nStatus = ERR_SUCCESS;
	__int64 deviceSize;
	uint64 remainingBytes, workChunkStartByteOffset, lastHeaderUpdateDistance = 0, skippedBadSectorCount = 0;
	uint32 workChunkSize;
	DWORD dwError, dwResult;
	BOOL bPause = FALSE, bEncryptedAreaSizeChanged = FALSE;
	LARGE_INTEGER offset;
	int sectorSize;
	int i;
	DWORD n;
	WCHAR *devicePath = volParams->volumePath;
	Password *password = volParams->password;
	HWND hwndDlg = volParams->hwndDlg;
	int pkcs5_prf = volParams->pkcs5;
	int pim = volParams->pim;
	DISK_GEOMETRY driveGeometry;


	buf = (char *) TCalloc (TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE);
	if (!buf)
	{
		nStatus = ERR_OUTOFMEMORY;
		goto closing_seq;
	}

	headerCryptoInfo = crypto_open();

	if (headerCryptoInfo == NULL)
	{
		nStatus = ERR_OUTOFMEMORY;
		goto closing_seq;
	}

	deviceSize = GetDeviceSize (devicePath);
	if (deviceSize < 0)
	{
		// Cannot determine the size of the partition
		nStatus = ERR_OS_ERROR;
		goto closing_seq;
	}


	// The wizard should have dismounted the TC volume if it was mounted, but for extra safety we will check this again.
	if (IsMountedVolume (devicePath))
	{
		int driveLetter = GetMountedVolumeDriveNo (devicePath);

		if (driveLetter == -1
			|| !UnmountVolume (hwndDlg, driveLetter, TRUE))
		{
			handleWin32Error (hwndDlg, SRC_POS);
			AbortProcess ("CANT_DISMOUNT_VOLUME");
		}
	}


	StringCchCopyW (deviceName, ARRAYSIZE(deviceName), devicePath);

	if (FakeDosNameForDevice (deviceName, dosDev, sizeof(dosDev), devName, sizeof(devName), FALSE) != 0)
	{
		nStatus = ERR_OS_ERROR;
		goto closing_seq;
	}

	dev = OpenPartitionVolume (hwndDlg, devName,
		TRUE,	// Require exclusive access
		FALSE,	// Do not require shared access
		TRUE,	// Ask the user to confirm shared access (if exclusive fails)
		FALSE,	// Do not append alternative instructions how to encrypt the data (to applicable error messages)
		FALSE);	// Non-silent mode

	if (dev == INVALID_HANDLE_VALUE)
	{
		nStatus = ERR_DONT_REPORT;
		goto closing_seq;
	}



	// This should never be needed, but is still performed for extra safety (without checking the result)
	DeviceIoControl (dev,
		FSCTL_ALLOW_EXTENDED_DASD_IO,
		NULL,
		0,
		NULL,
		0,
		&dwResult,
		NULL);


	if (!DeviceIoControl (dev, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &driveGeometry, sizeof (driveGeometry), &dwResult, NULL))
	{
		nStatus = ERR_OS_ERROR;
		goto closing_seq;
	}

	if (	(driveGeometry.BytesPerSector == 0)
		||	(driveGeometry.BytesPerSector > TC_MAX_VOLUME_SECTOR_SIZE)
		|| (driveGeometry.BytesPerSector % ENCRYPTION_DATA_UNIT_SIZE != 0)
		)
	{
		Error ("SECTOR_SIZE_UNSUPPORTED", hwndDlg);
		nStatus = ERR_DONT_REPORT;
		goto closing_seq;
	}

	sectorSize = driveGeometry.BytesPerSector;


	tmpSectorBuf = (byte *) TCalloc (sectorSize);
	if (!tmpSectorBuf)
	{
		nStatus = ERR_OUTOFMEMORY;
		goto closing_seq;
	}


	nStatus = OpenBackupHeader (dev, devicePath, password, pkcs5_prf, pim, &masterCryptoInfo, headerCryptoInfo, deviceSize);

	if (nStatus != ERR_SUCCESS)
		goto closing_seq;

#ifdef _WIN64
	if (IsRamEncryptionEnabled ())
	{
		VcProtectKeys (masterCryptoInfo, VcGetEncryptionID (masterCryptoInfo));
		VcProtectKeys (headerCryptoInfo, VcGetEncryptionID (headerCryptoInfo));
	}
#endif

	if (masterCryptoInfo->LegacyVolume)
	{
		Error ("NONSYS_INPLACE_DECRYPTION_BAD_VOL_FORMAT", hwndDlg);
		nStatus = ERR_DONT_REPORT;
		goto closing_seq;
	}

	if (masterCryptoInfo->hiddenVolume)
	{
		Error ("NONSYS_INPLACE_DECRYPTION_CANT_DECRYPT_HID_VOL", hwndDlg);
		nStatus = ERR_DONT_REPORT;
		goto closing_seq;
	}

	if (!bInPlaceEncNonSysResumed
		&& masterCryptoInfo->VolumeSize.Value == masterCryptoInfo->EncryptedAreaLength.Value)
	{
		/* Decryption started (not resumed) */

		if ((masterCryptoInfo->HeaderFlags & TC_HEADER_FLAG_NONSYS_INPLACE_ENC) == 0)
		{
			// The volume has not been encrypted in-place so it may contain a hidden volume.
			// Ask the user to confirm it does not.

			char *tmpStr[] = {0,
				"CONFIRM_VOL_CONTAINS_NO_HIDDEN_VOL",
				"VOL_CONTAINS_NO_HIDDEN_VOL",
				"VOL_CONTAINS_A_HIDDEN_VOL",
				0};

			switch (AskMultiChoice ((void **) tmpStr, FALSE, hwndDlg))
			{
			case 1:
				// NOP
				break;
			case 2:
			default:
				// Cancel
				nStatus = ERR_DONT_REPORT;
				goto closing_seq;
			}
		}

		// Update config files and app data

		// In the config file, increase the number of partitions where in-place decryption is in progress
		SaveNonSysInPlaceEncSettings (1, TC_WIPE_NONE, TRUE);

		// Add the wizard to the system startup sequence if appropriate
		if (!IsNonInstallMode ())
			ManageStartupSeqWiz (FALSE, L"/prinplace");
	}



	bInPlaceEncNonSysResumed = TRUE;
	bFirstNonSysInPlaceEncResumeDone = TRUE;


	remainingBytes = masterCryptoInfo->EncryptedAreaLength.Value;

	lastHeaderUpdateDistance = 0;


	ExportProgressStats (masterCryptoInfo->EncryptedAreaLength.Value, masterCryptoInfo->VolumeSize.Value);

	SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_DECRYPTING);



	/* The in-place decryption core */

	while (remainingBytes > 0)
	{
		workChunkSize = (uint32) min (remainingBytes, TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE);

		if (workChunkSize % ENCRYPTION_DATA_UNIT_SIZE != 0)
		{
			nStatus = ERR_PARAMETER_INCORRECT;
			goto closing_seq;
		}

		workChunkStartByteOffset = masterCryptoInfo->EncryptedAreaStart.Value;

		unitNo.Value = workChunkStartByteOffset / ENCRYPTION_DATA_UNIT_SIZE;


		// Read the ciphertext into RAM

		offset.QuadPart = workChunkStartByteOffset;

		if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0)
		{
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}

		if (ReadFile (dev, buf, workChunkSize, &n, NULL) == 0)
		{
			// Read error

			DWORD dwTmpErr = GetLastError ();

			if (IsDiskReadError (dwTmpErr) && !bVolTransformThreadCancel)
			{
				// Physical defect or data corruption

				if (!*DiscardUnreadableEncryptedSectors)
				{
					*DiscardUnreadableEncryptedSectors = (AskWarnYesNo ("DISCARD_UNREADABLE_ENCRYPTED_SECTORS", hwndDlg) == IDYES);
				}

				if (*DiscardUnreadableEncryptedSectors)
				{
					// Read the work chunk again, but this time each sector individually and skiping each bad sector

					LARGE_INTEGER tmpSectorOffset;
					uint64 tmpSectorCount;
					uint64 tmpBufOffset = 0;
					DWORD tmpNbrReadBytes = 0;

					tmpSectorOffset.QuadPart = offset.QuadPart;

					for (tmpSectorCount = workChunkSize / sectorSize; tmpSectorCount > 0; --tmpSectorCount)
					{
						if (SetFilePointerEx (dev, tmpSectorOffset, NULL, FILE_BEGIN) == 0)
						{
							nStatus = ERR_OS_ERROR;
							goto closing_seq;
						}

						if (ReadFile (dev, tmpSectorBuf, sectorSize, &tmpNbrReadBytes, NULL) == 0
							|| tmpNbrReadBytes != (DWORD) sectorSize)
						{
							// Read error

							// Clear the buffer so the content of each unreadable sector is replaced with decrypted all-zero blocks (producing pseudorandom data)
							memset (tmpSectorBuf, 0, sectorSize);

							skippedBadSectorCount++;
						}

						memcpy (buf + tmpBufOffset, tmpSectorBuf, sectorSize);

						tmpSectorOffset.QuadPart += sectorSize;
						tmpBufOffset += sectorSize;
					}
				}
				else
				{
					SetLastError (dwTmpErr);		// Preserve the original error code

					nStatus = ERR_OS_ERROR;
					goto closing_seq;
				}
			}
			else
			{
				SetLastError (dwTmpErr);		// Preserve the original error code

				nStatus = ERR_OS_ERROR;
				goto closing_seq;
			}
		}

		// Decrypt the ciphertext in RAM

		DecryptDataUnits ((byte *) buf, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo);



		// Conceal initial portion of the filesystem

		if (workChunkStartByteOffset - TC_VOLUME_DATA_OFFSET < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE)
		{
			// We are decrypting the initial TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE bytes of the filesystem. We will
			// conceal this portion to prevent Windows and applications from interfering with the volume.

			for (i = 0; i < min (TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, workChunkStartByteOffset - TC_VOLUME_DATA_OFFSET + workChunkSize); i++)
				buf[i] ^= TC_NTFS_CONCEAL_CONSTANT;
		}


		// Write the plaintext

		offset.QuadPart = workChunkStartByteOffset - TC_VOLUME_DATA_OFFSET;

		if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0)
		{
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}

		if (WriteFile (dev, buf, workChunkSize, &n, NULL) == 0)
		{
			// Write error
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}


		masterCryptoInfo->EncryptedAreaStart.Value += workChunkSize;
		masterCryptoInfo->EncryptedAreaLength.Value -= workChunkSize;

		remainingBytes -= workChunkSize;
		lastHeaderUpdateDistance += workChunkSize;

		bEncryptedAreaSizeChanged = TRUE;

		if (lastHeaderUpdateDistance >= TC_NONSYS_INPLACE_ENC_HEADER_UPDATE_INTERVAL)
		{
			nStatus = FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize);

			if (nStatus != ERR_SUCCESS)
			{
				// Possible write error
				goto closing_seq;
			}

			lastHeaderUpdateDistance = 0;
		}

		ExportProgressStats (masterCryptoInfo->EncryptedAreaLength.Value, masterCryptoInfo->VolumeSize.Value);

		if (bVolTransformThreadCancel)
		{
			bPause = TRUE;
			break;
		}
	}

	nStatus = FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize);


	if (nStatus != ERR_SUCCESS)
	{
		// Possible write error
		goto closing_seq;
	}


	if (!bPause)
	{
		/* Volume has been fully decrypted. */


		// Prevent attempts to update volume header during the closing sequence
		bEncryptedAreaSizeChanged = FALSE;


		SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_FINALIZING);



		/* Undo concealing of the filesystem */

		nStatus = ConcealNTFS (dev);

		if (nStatus != ERR_SUCCESS)
			goto closing_seq;



		/* Ovewrite the backup header and the remaining ciphertext with all-zero blocks (the primary header was overwritten with the decrypted data). */

		memset (tmpSectorBuf, 0, sectorSize);

		for (offset.QuadPart = masterCryptoInfo->VolumeSize.Value;
			offset.QuadPart <= deviceSize - sectorSize;
			offset.QuadPart += sectorSize)
		{
			if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0)
			{
				nStatus = ERR_OS_ERROR;
				goto closing_seq;
			}

			if (WriteFile (dev, tmpSectorBuf, sectorSize, &n, NULL) == 0)
			{
				// Write error
				dwError = GetLastError();

				SetLastError (dwError);
				nStatus = ERR_OS_ERROR;
				goto closing_seq;
			}
		}



		/* Update the configuration files */

		SaveNonSysInPlaceEncSettings (-1, TC_WIPE_NONE, TRUE);



		SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_FINISHED);

		nStatus = ERR_SUCCESS;

	}
	else
	{
		// The process has been paused by the user or aborted by the wizard (e.g. on app exit)

		nStatus = ERR_USER_ABORT;

		SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PAUSED);
	}

	if (dev != INVALID_HANDLE_VALUE)
	{
		CloseHandle (dev);
		dev = INVALID_HANDLE_VALUE;
	}


closing_seq:

	dwError = GetLastError();

	if (bEncryptedAreaSizeChanged
		&& dev != INVALID_HANDLE_VALUE
		&& masterCryptoInfo != NULL
		&& headerCryptoInfo != NULL
		&& deviceSize > 0)
	{
		// Execution of the core loop may have been interrupted due to an error or user action without updating the header
		FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize);
	}

	if (dev != INVALID_HANDLE_VALUE)
	{
		CloseHandle (dev);
		dev = INVALID_HANDLE_VALUE;
	}

	if (masterCryptoInfo != NULL)
	{
		crypto_close (masterCryptoInfo);
		masterCryptoInfo = NULL;
	}

	if (headerCryptoInfo != NULL)
	{
		crypto_close (headerCryptoInfo);
		headerCryptoInfo = NULL;
	}

	if (dosDev[0])
		RemoveFakeDosName (devicePath, dosDev);

	if (buf != NULL)
	{
		TCfree (buf);
		buf = NULL;
	}

	if (tmpSectorBuf != NULL)
	{
		TCfree (tmpSectorBuf);
		tmpSectorBuf = NULL;
	}

	if (skippedBadSectorCount > 0)
	{
		wchar_t msg[30000] = {0};
		wchar_t sizeStr[500] = {0};

		GetSizeString (skippedBadSectorCount * sectorSize, sizeStr, sizeof(sizeStr));

		StringCbPrintfW (msg, sizeof(msg),
			GetString ("SKIPPED_BAD_SECTOR_COUNT"),
			skippedBadSectorCount,
			sizeStr);

		WarningDirect (msg, hwndDlg);
	}

	if (nStatus != ERR_SUCCESS && nStatus != ERR_USER_ABORT)
		SetLastError (dwError);

	return nStatus;
}

int FastVolumeHeaderUpdate (HANDLE dev, CRYPTO_INFO *headerCryptoInfo, CRYPTO_INFO *masterCryptoInfo, __int64 deviceSize)
{
	LARGE_INTEGER offset;
	DWORD n;
	int nStatus = ERR_SUCCESS;
	byte *header;
	DWORD dwError;
	uint32 headerCrc32;
	byte *fieldPos;
	PCRYPTO_INFO pCryptoInfo = headerCryptoInfo;

	header = (byte *) TCalloc (TC_VOLUME_HEADER_EFFECTIVE_SIZE);

	if (!header)
		return ERR_OUTOFMEMORY;

	VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);


	fieldPos = (byte *) header + TC_HEADER_OFFSET_ENCRYPTED_AREA_START;

	offset.QuadPart = deviceSize - TC_VOLUME_HEADER_GROUP_SIZE;

	if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
		|| !ReadEffectiveVolumeHeader (TRUE, dev, header, &n) || n < TC_VOLUME_HEADER_EFFECTIVE_SIZE)
	{
		nStatus = ERR_OS_ERROR;
		goto closing_seq;
	}

#ifdef _WIN64
	if (IsRamEncryptionEnabled())
	{
		pCryptoInfo = crypto_open();
		if (!pCryptoInfo)
		{
			nStatus = ERR_OUTOFMEMORY;
			goto closing_seq;
		}

		memcpy (pCryptoInfo, headerCryptoInfo, sizeof (CRYPTO_INFO));
		VcUnprotectKeys (pCryptoInfo, VcGetEncryptionID (headerCryptoInfo));
	}
#endif


	DecryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, pCryptoInfo);

	if (GetHeaderField32 (header, TC_HEADER_OFFSET_MAGIC) != 0x56455241)
	{
		nStatus = ERR_PARAMETER_INCORRECT;
		goto closing_seq;
	}

	mputInt64 (fieldPos, (masterCryptoInfo->EncryptedAreaStart.Value));
	mputInt64 (fieldPos, (masterCryptoInfo->EncryptedAreaLength.Value));

	// We need to ensure the TC_HEADER_FLAG_NONSYS_INPLACE_ENC flag bit is set, because if volumes created by TC-format
	// were decrypted in place, it would be possible to mount them partially encrypted and it wouldn't be possible
	// to resume interrupted decryption after the wizard exits.
	masterCryptoInfo->HeaderFlags |= TC_HEADER_FLAG_NONSYS_INPLACE_ENC;
	fieldPos = (byte *) header + TC_HEADER_OFFSET_FLAGS;
	mputLong (fieldPos, (masterCryptoInfo->HeaderFlags));


	headerCrc32 = GetCrc32 (header + TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC);
	fieldPos = (byte *) header + TC_HEADER_OFFSET_HEADER_CRC;
	mputLong (fieldPos, headerCrc32);

	EncryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, pCryptoInfo);


	if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
		|| !WriteEffectiveVolumeHeader (TRUE, dev, header))
	{
		nStatus = ERR_OS_ERROR;
		goto closing_seq;
	}


closing_seq:

	dwError = GetLastError();

#ifdef _WIN64
	if (IsRamEncryptionEnabled() && pCryptoInfo)
	{
		crypto_close(pCryptoInfo);
	}
#endif

	burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
	VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
	TCfree (header);

	if (nStatus != ERR_SUCCESS)
		SetLastError (dwError);

	return nStatus;
}


static HANDLE OpenPartitionVolume (HWND hwndDlg, const wchar_t *devName,
							 BOOL bExclusiveRequired,
							 BOOL bSharedRequired,
							 BOOL bSharedRequiresConfirmation,
							 BOOL bShowAlternativeSteps,
							 BOOL bSilent)
{
	HANDLE dev = INVALID_HANDLE_VALUE;
	int retryCount = 0;

	if (bExclusiveRequired)
		bSharedRequired = FALSE;

	if (bExclusiveRequired || !bSharedRequired)
	{
		// Exclusive access
		// Note that when exclusive access is denied, it is worth retrying (usually succeeds after a few tries).
		while (dev == INVALID_HANDLE_VALUE && retryCount++ < EXCL_ACCESS_MAX_AUTO_RETRIES)
		{
			dev = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_WRITE_THROUGH, NULL);

			if (retryCount > 1)
				Sleep (EXCL_ACCESS_AUTO_RETRY_DELAY);
		}
	}

	if (dev == INVALID_HANDLE_VALUE)
	{
		if (bExclusiveRequired)
		{
			if (!bSilent)
			{
				handleWin32Error (hwndDlg, SRC_POS);

				if (bShowAlternativeSteps)
					ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE);
				else
					Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", hwndDlg);
			}
			return INVALID_HANDLE_VALUE;
		}

		// Shared mode
		dev = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_WRITE_THROUGH, NULL);
		if (dev != INVALID_HANDLE_VALUE)
		{
			if (bSharedRequiresConfirmation
				&& !bSilent
				&& AskWarnNoYes ("DEVICE_IN_USE_INPLACE_ENC", hwndDlg) == IDNO)
			{
				CloseHandle (dev);
				return INVALID_HANDLE_VALUE;
			}
		}
		else
		{
			if (!bSilent)
			{
				handleWin32Error (MainDlg, SRC_POS);

				if (bShowAlternativeSteps)
					ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE);
				else
					Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", hwndDlg);
			}
			return INVALID_HANDLE_VALUE;
		}
	}

	return dev;
}


static int DismountFileSystem (HWND hwndDlg, HANDLE dev,
					int driveLetter,
					BOOL bForcedAllowed,
					BOOL bForcedRequiresConfirmation,
					BOOL bSilent)
{
	int attempt;
	BOOL bResult;
	DWORD dwResult;

	CloseVolumeExplorerWindows (MainDlg, driveLetter);

	attempt = UNMOUNT_MAX_AUTO_RETRIES * 10;

	while (!(bResult = DeviceIoControl (dev, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL))
		&& attempt > 0)
	{
		Sleep (UNMOUNT_AUTO_RETRY_DELAY);
		attempt--;
	}

	if (!bResult)
	{
		if (!bForcedAllowed)
		{
			if (!bSilent)
				ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_LOCK_OR_DISMOUNT_FILESYS", TRUE);

			return ERR_DONT_REPORT;
		}

		if (bForcedRequiresConfirmation
			&& !bSilent
			&& AskWarnYesNo ("VOL_LOCK_FAILED_OFFER_FORCED_DISMOUNT", hwndDlg) == IDNO)
		{
			return ERR_DONT_REPORT;
		}
	}

	// Dismount the volume

	attempt = UNMOUNT_MAX_AUTO_RETRIES * 10;

	while (!(bResult = DeviceIoControl (dev, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL))
		&& attempt > 0)
	{
		Sleep (UNMOUNT_AUTO_RETRY_DELAY);
		attempt--;
	}

	if (!bResult)
	{
		if (!bSilent)
			ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_LOCK_OR_DISMOUNT_FILESYS", TRUE);

		return ERR_DONT_REPORT;
	}

	return ERR_SUCCESS;
}


// Easy-to-undo modification applied to conceal the NTFS filesystem (to prevent Windows and apps from
// interfering with it until the volume has been fully encrypted). Note that this function will precisely
// undo any modifications it made to the filesystem automatically if an error occurs when writing (including
// physical drive defects).
static int ConcealNTFS (HANDLE dev)
{
	char buf [TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE];
	DWORD nbrBytesProcessed, nbrBytesProcessed2;
	int i;
	LARGE_INTEGER offset;
	DWORD dwError;

	offset.QuadPart = 0;

	if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0)
		return ERR_OS_ERROR;

	if (ReadFile (dev, buf, TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, &nbrBytesProcessed, NULL) == 0)
		return ERR_OS_ERROR;

	for (i = 0; i < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE; i++)
		buf[i] ^= TC_NTFS_CONCEAL_CONSTANT;

	offset.QuadPart = 0;

	if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0)
		return ERR_OS_ERROR;

	if (WriteFile (dev, buf, TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, &nbrBytesProcessed, NULL) == 0)
	{
		// One or more of the sectors is/are probably damaged and cause write errors.
		// We must undo the modifications we made.

		dwError = GetLastError();

		for (i = 0; i < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE; i++)
			buf[i] ^= TC_NTFS_CONCEAL_CONSTANT;

		offset.QuadPart = 0;

		do
		{
			Sleep (1);
		}
		while (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
			|| WriteFile (dev, buf, TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, &nbrBytesProcessed2, NULL) == 0);

		SetLastError (dwError);

		return ERR_OS_ERROR;
	}

	return ERR_SUCCESS;
}


void ShowInPlaceEncErrMsgWAltSteps (HWND hwndDlg, char *iniStrId, BOOL bErr)
{
	wchar_t msg[30000];

	StringCbCopyW (msg, sizeof(msg), GetString (iniStrId));

	StringCbCatW (msg, sizeof(msg), L"\n\n\n");
	StringCbCatW (msg, sizeof(msg), GetString ("INPLACE_ENC_ALTERNATIVE_STEPS"));

	if (bErr)
		ErrorDirect (msg, hwndDlg);
	else
		WarningDirect (msg, hwndDlg);
}


static void ExportProgressStats (__int64 bytesDone, __int64 totalSize)
{
	NonSysInplaceEncBytesDone = bytesDone;
	NonSysInplaceEncTotalSize = totalSize;
}


void SetNonSysInplaceEncUIStatus (int nonSysInplaceEncStatus)
{
	NonSysInplaceEncStatus = nonSysInplaceEncStatus;
}


BOOL SaveNonSysInPlaceEncSettings (int delta, WipeAlgorithmId newWipeAlgorithm, BOOL bDecrypt)
{
	int count;
	char str[32];
	WipeAlgorithmId savedWipeAlgorithm = TC_WIPE_NONE;

	if (delta == 0)
		return TRUE;

	count = LoadNonSysInPlaceEncSettings (&savedWipeAlgorithm) + delta;

	if (count < 1)
	{
		RemoveNonSysInPlaceEncNotifications();
		return TRUE;
	}
	else if (!bDecrypt)
	{
		if (newWipeAlgorithm != TC_WIPE_NONE)
		{
			StringCbPrintfA (str, sizeof(str), "%d", (int) newWipeAlgorithm);

			SaveBufferToFile (str, GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE), (DWORD) strlen(str), FALSE, FALSE);
		}
		else if (FileExists (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE)))
		{
			_wremove (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE));
		}
	}

	StringCbPrintfA (str, sizeof(str), "%d", count);

	return SaveBufferToFile (str, GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC), (DWORD) strlen(str), FALSE, FALSE);
}


// Repairs damaged sectors (i.e. those with read errors) by zeroing them.
// Note that this operating fails if there are any write errors.
int ZeroUnreadableSectors (HANDLE dev, LARGE_INTEGER startOffset, int64 size, int sectorSize, uint64 *zeroedSectorCount)
{
	int nStatus;
	DWORD n;
	int64 sectorCount;
	LARGE_INTEGER workOffset;
	byte *sectorBuffer = NULL;
	DWORD dwError;

	workOffset.QuadPart = startOffset.QuadPart;

	sectorBuffer = (byte *) TCalloc (sectorSize);

	if (!sectorBuffer)
		return ERR_OUTOFMEMORY;

	if (SetFilePointerEx (dev, startOffset, NULL, FILE_BEGIN) == 0)
	{
		nStatus = ERR_OS_ERROR;
		goto closing_seq;
	}


	for (sectorCount = size / sectorSize; sectorCount > 0; --sectorCount)
	{
		if (ReadFile (dev, sectorBuffer, sectorSize, &n, NULL) == 0)
		{
			memset (sectorBuffer, 0, sectorSize);

			if (SetFilePointerEx (dev, workOffset, NULL, FILE_BEGIN) == 0)
			{
				nStatus = ERR_OS_ERROR;
				goto closing_seq;
			}

			if (WriteFile (dev, sectorBuffer, sectorSize, &n, NULL) == 0)
			{
				nStatus = ERR_OS_ERROR;
				goto closing_seq;
			}
			++(*zeroedSectorCount);
		}

		workOffset.QuadPart += n;
	}

	nStatus = ERR_SUCCESS;

closing_seq:

	dwError = GetLastError();

	if (sectorBuffer != NULL)
		TCfree (sectorBuffer);

	if (nStatus != ERR_SUCCESS)
		SetLastError (dwError);

	return nStatus;
}


static int OpenBackupHeader (HANDLE dev, const wchar_t *devicePath, Password *password, int pkcs5, int pim, PCRYPTO_INFO *retMasterCryptoInfo, CRYPTO_INFO *headerCryptoInfo, __int64 deviceSize)
{
	LARGE_INTEGER offset;
	DWORD n;
	int nStatus = ERR_SUCCESS;
	char *header;
	DWORD dwError;

	header = (char *) TCalloc (TC_VOLUME_HEADER_EFFECTIVE_SIZE);
	if (!header)
		return ERR_OUTOFMEMORY;

	VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);



	offset.QuadPart = deviceSize - TC_VOLUME_HEADER_GROUP_SIZE;

	if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
		|| !ReadEffectiveVolumeHeader (TRUE, dev, (byte *) header, &n) || n < TC_VOLUME_HEADER_EFFECTIVE_SIZE)
	{
		nStatus = ERR_OS_ERROR;
		goto closing_seq;
	}


	nStatus = ReadVolumeHeader (FALSE, header, password, pkcs5, pim, FALSE, retMasterCryptoInfo, headerCryptoInfo);
	if (nStatus != ERR_SUCCESS)
		goto closing_seq;


closing_seq:

	dwError = GetLastError();

	burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
	VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
	TCfree (header);

	dwError = GetLastError();

	if (nStatus != ERR_SUCCESS)
		SetLastError (dwError);

	return nStatus;
}


static BOOL GetFreeClusterBeforeThreshold (HANDLE volumeHandle, int64 *freeCluster, int64 clusterThreshold)
{
	const int bitmapSize = 65536;
	byte bitmapBuffer[bitmapSize + sizeof (VOLUME_BITMAP_BUFFER)];
	VOLUME_BITMAP_BUFFER *bitmap = (VOLUME_BITMAP_BUFFER *) bitmapBuffer;
	STARTING_LCN_INPUT_BUFFER startLcn;
	startLcn.StartingLcn.QuadPart = 0;

	DWORD bytesReturned;
	while (DeviceIoControl (volumeHandle, FSCTL_GET_VOLUME_BITMAP, &startLcn, sizeof (startLcn), &bitmapBuffer, sizeof (bitmapBuffer), &bytesReturned, NULL)
		|| GetLastError() == ERROR_MORE_DATA)
	{
		for (int64 bitmapIndex = 0; bitmapIndex < min (bitmapSize, (bitmap->BitmapSize.QuadPart / 8)); ++bitmapIndex)
		{
			if (bitmap->StartingLcn.QuadPart + bitmapIndex * 8 >= clusterThreshold)
				goto err;

			if (bitmap->Buffer[bitmapIndex] != 0xff)
			{
				for (int bit = 0; bit < 8; ++bit)
				{
					if ((bitmap->Buffer[bitmapIndex] & (1 << bit)) == 0)
					{
						*freeCluster = bitmap->StartingLcn.QuadPart + bitmapIndex * 8 + bit;

						if (*freeCluster >= clusterThreshold)
							goto err;

						return TRUE;
					}
				}
			}
		}

		startLcn.StartingLcn.QuadPart += min (bitmapSize * 8, bitmap->BitmapSize.QuadPart);
	}

err:
	SetLastError (ERROR_DISK_FULL);
	return FALSE;
}


static BOOL MoveClustersBeforeThresholdInDir (HANDLE volumeHandle, const wstring &directory, int64 clusterThreshold)
{
	WIN32_FIND_DATAW findData;

	HANDLE findHandle = FindFirstFileW (((directory.size() <= 3 ? L"" : L"\\\\?\\") + directory + L"\\*").c_str(), &findData);
	if (findHandle == INVALID_HANDLE_VALUE)
		return TRUE;	// Error ignored

	finally_do_arg (HANDLE, findHandle, { FindClose (finally_arg); });

	// Find all files and directories
	do
	{
		if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			wstring subDir = findData.cFileName;

			if (subDir == L"." || subDir == L"..")
				continue;

			if (!MoveClustersBeforeThresholdInDir (volumeHandle, directory + L"\\" + subDir, clusterThreshold))
				return FALSE;
		}

		DWORD access = FILE_READ_ATTRIBUTES;

		if (findData.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED)
			access = FILE_READ_DATA;

		HANDLE fsObject = CreateFileW ((directory + L"\\" + findData.cFileName).c_str(), access, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
		if (fsObject == INVALID_HANDLE_VALUE)
			continue;

		finally_do_arg (HANDLE, fsObject, { CloseHandle (finally_arg); });

		STARTING_VCN_INPUT_BUFFER startVcn;
		startVcn.StartingVcn.QuadPart = 0;
		RETRIEVAL_POINTERS_BUFFER retPointers;
		DWORD bytesReturned;

		// Find clusters allocated beyond the threshold
		while (DeviceIoControl (fsObject, FSCTL_GET_RETRIEVAL_POINTERS, &startVcn, sizeof (startVcn), &retPointers, sizeof (retPointers), &bytesReturned, NULL)
			|| GetLastError() == ERROR_MORE_DATA)
		{
			if (retPointers.ExtentCount == 0)
				break;

			if (retPointers.Extents[0].Lcn.QuadPart != -1)
			{
				int64 extentStartCluster = retPointers.Extents[0].Lcn.QuadPart;
				int64 extentLen = retPointers.Extents[0].NextVcn.QuadPart - retPointers.StartingVcn.QuadPart;
				int64 extentEndCluster = extentStartCluster + extentLen - 1;

				if (extentEndCluster >= clusterThreshold)
				{
					// Move clusters before the threshold
					for (int64 movedCluster = max (extentStartCluster, clusterThreshold); movedCluster <= extentEndCluster; ++movedCluster)
					{
						for (int retry = 0; ; ++retry)
						{
							MOVE_FILE_DATA moveData;

							if (GetFreeClusterBeforeThreshold (volumeHandle, &moveData.StartingLcn.QuadPart, clusterThreshold))
							{
								moveData.FileHandle = fsObject;
								moveData.StartingVcn.QuadPart = movedCluster - extentStartCluster + retPointers.StartingVcn.QuadPart;
								moveData.ClusterCount = 1;

								if (DeviceIoControl (volumeHandle, FSCTL_MOVE_FILE, &moveData, sizeof (moveData), NULL, 0, &bytesReturned, NULL))
									break;
							}

							if (retry > 600)
								return FALSE;

							// There are possible race conditions as we work on a live filesystem
							Sleep (100);
						}
					}
				}
			}

			startVcn.StartingVcn = retPointers.Extents[0].NextVcn;
		}

	} while (FindNextFileW (findHandle, &findData));

	return TRUE;
}


BOOL MoveClustersBeforeThreshold (HANDLE volumeHandle, PWSTR volumeDevicePath, int64 clusterThreshold)
{
	int drive = GetDiskDeviceDriveLetter (volumeDevicePath);
	if (drive == -1)
	{
		SetLastError (ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	wstring volumeRoot = L"X:";
	volumeRoot[0] = L'A' + (wchar_t) drive;

	return MoveClustersBeforeThresholdInDir (volumeHandle, volumeRoot, clusterThreshold);
}