2
* ntfsfix - Part of the Linux-NTFS project.
4
* Copyright (c) 2000-2006 Anton Altaparmakov
5
* Copyright (c) 2002-2006 Szabolcs Szakacsits
6
* Copyright (c) 2007 Yura Pakhuchiy
7
* Copyright (c) 2011-2012 Jean-Pierre Andre
9
* This utility fixes some common NTFS problems, resets the NTFS journal file
10
* and schedules an NTFS consistency check for the first boot into Windows.
12
* Anton Altaparmakov <aia21@cantab.net>
14
* This program is free software; you can redistribute it and/or modify
15
* it under the terms of the GNU General Public License as published by
16
* the Free Software Foundation; either version 2 of the License, or
17
* (at your option) any later version.
19
* This program is distributed in the hope that it will be useful,
20
* but WITHOUT ANY WARRANTY; without even the implied warranty of
21
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22
* GNU General Public License for more details.
24
* You should have received a copy of the GNU General Public License
25
* along with this program (in the main directory of the Linux-NTFS source
26
* in the file COPYING); if not, write to the Free Software Foundation,
27
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
31
* WARNING: This program might not work on architectures which do not allow
32
* unaligned access. For those, the program would need to start using
33
* get/put_unaligned macros (#include <asm/unaligned.h>), but not doing it yet,
34
* since NTFS really mostly applies to ia32 only, which does allow unaligned
35
* accesses. We might not actually have a problem though, since the structs are
36
* defined as being packed so that might be enough for gcc to insert the
39
* If anyone using a non-little endian and/or an aligned access only CPU tries
40
* this program please let me know whether it works or not!
42
* Anton Altaparmakov <aia21@cantab.net>
79
/* #include "version.h" */
83
#ifdef NO_NTFS_DEVICE_DEFAULT_IO_OPS
84
# error "No default device io operations! Cannot build ntfsfix. \
85
You need to run ./configure without the --disable-default-device-io-ops \
86
switch if you want to be able to build the NTFS utilities."
89
static const char *EXEC_NAME = "ntfsfix";
90
static const char OK[] = "OK\n";
91
static const char FAILED[] = "FAILED\n";
92
static const char FOUND[] = "FOUND\n";
94
#define DEFAULT_SECTOR_SIZE 512
99
BOOL clear_bad_sectors;
104
* Definitions for fixing the self-located MFT bug
107
#define SELFLOC_LIMIT 16
109
struct MFT_SELF_LOCATED {
114
ATTR_LIST_ENTRY *attrlist;
115
ATTR_LIST_ENTRY *attrlist_to_ref1;
119
BOOL attrlist_resident;
125
__attribute__((noreturn))
126
static void usage(void)
128
ntfs_log_info("%s v%s (libntfs-3g)\n"
130
"Usage: %s [options] device\n"
131
" Attempt to fix an NTFS partition.\n"
133
" -b, --clear-bad-sectors Clear the bad sector list\n"
134
" -d, --clear-dirty Clear the volume dirty flag\n"
135
" -h, --help Display this help\n"
136
" -n, --no-action Do not write anything\n"
137
" -V, --version Display version information\n"
139
"For example: %s /dev/hda6\n\n",
140
EXEC_NAME, VERSION, EXEC_NAME,
142
ntfs_log_info("%s%s", ntfs_bugs, ntfs_home);
149
__attribute__((noreturn))
150
static void version(void)
152
ntfs_log_info("%s v%s\n\n"
153
"Attempt to fix an NTFS partition.\n\n"
154
"Copyright (c) 2000-2006 Anton Altaparmakov\n"
155
"Copyright (c) 2002-2006 Szabolcs Szakacsits\n"
156
"Copyright (c) 2007 Yura Pakhuchiy\n"
157
"Copyright (c) 2011-2012 Jean-Pierre Andre\n\n",
159
ntfs_log_info("%s\n%s%s", ntfs_gpl, ntfs_bugs, ntfs_home);
166
static void parse_options(int argc, char **argv)
169
static const char *sopt = "-bdhnV";
170
static const struct option lopt[] = {
171
{ "help", no_argument, NULL, 'h' },
172
{ "no-action", no_argument, NULL, 'n' },
173
{ "clear-bad-sectors", no_argument, NULL, 'b' },
174
{ "clear-dirty", no_argument, NULL, 'd' },
175
{ "version", no_argument, NULL, 'V' },
179
memset(&opt, 0, sizeof(opt));
181
while ((c = getopt_long(argc, argv, sopt, lopt, NULL)) != -1) {
183
case 1: /* A non-option argument */
185
opt.volume = argv[optind - 1];
187
ntfs_log_info("ERROR: Too many arguments.\n");
192
opt.clear_bad_sectors = TRUE;
195
opt.clear_dirty = TRUE;
198
opt.no_action = TRUE;
207
ntfs_log_info("ERROR: Unknown option '%s'.\n", argv[optind - 1]);
212
if (opt.volume == NULL) {
213
ntfs_log_info("ERROR: You must specify a device.\n");
219
* OLD_ntfs_volume_set_flags
221
static int OLD_ntfs_volume_set_flags(ntfs_volume *vol, const le16 flags)
223
MFT_RECORD *m = NULL;
225
VOLUME_INFORMATION *c;
226
ntfs_attr_search_ctx *ctx;
227
int ret = -1; /* failure */
233
if (ntfs_file_record_read(vol, FILE_Volume, &m, NULL)) {
234
ntfs_log_perror("Failed to read $Volume");
238
if (!(m->flags & MFT_RECORD_IN_USE)) {
239
ntfs_log_error("$Volume has been deleted. Cannot handle this "
240
"yet. Run chkdsk to fix this.\n");
244
/* Get a pointer to the volume information attribute. */
245
ctx = ntfs_attr_get_search_ctx(NULL, m);
247
ntfs_log_debug("Failed to allocate attribute search "
251
if (ntfs_attr_lookup(AT_VOLUME_INFORMATION, AT_UNNAMED, 0,
252
CASE_SENSITIVE, 0, NULL, 0, ctx)) {
253
ntfs_log_error("Attribute $VOLUME_INFORMATION was not found in "
259
if (a->non_resident) {
260
ntfs_log_error("Attribute $VOLUME_INFORMATION must be resident "
261
"(and it isn't)!\n");
265
/* Get a pointer to the value of the attribute. */
266
c = (VOLUME_INFORMATION*)(le16_to_cpu(a->value_offset) + (char*)a);
268
if ((char*)c + le32_to_cpu(a->value_length) >
269
(char*)m + le32_to_cpu(m->bytes_in_use) ||
270
le16_to_cpu(a->value_offset) +
271
le32_to_cpu(a->value_length) > le32_to_cpu(a->length)) {
272
ntfs_log_error("Attribute $VOLUME_INFORMATION in $Volume is "
277
/* Set the volume flags. */
278
vol->flags = c->flags = flags;
279
if (ntfs_mft_record_write(vol, FILE_Volume, m)) {
280
ntfs_log_perror("Error writing $Volume");
283
ret = 0; /* success */
285
ntfs_attr_put_search_ctx(ctx);
294
static int set_dirty_flag(ntfs_volume *vol)
298
/* Porting note: We test for the current state of VOLUME_IS_DIRTY. This
299
* should actually be more appropriate than testing for NVolWasDirty. */
300
if (vol->flags & VOLUME_IS_DIRTY)
302
ntfs_log_info("Setting required flags on partition... ");
304
* Set chkdsk flag, i.e. mark the partition dirty so chkdsk will run
307
flags = vol->flags | VOLUME_IS_DIRTY;
308
if (!opt.no_action && OLD_ntfs_volume_set_flags(vol, flags)) {
309
ntfs_log_info(FAILED);
310
ntfs_log_error("Error setting volume flags.\n");
315
/* Porting note: libntfs-3g does not have the 'WasDirty' flag/property,
316
* and never touches the 'dirty' bit except when explicitly told to do
317
* so. Since we just wrote the VOLUME_IS_DIRTY bit to disk, and
318
* vol->flags is up-to-date, we can just ignore the NVolSetWasDirty
320
/* NVolSetWasDirty(vol); */
329
static int empty_journal(ntfs_volume *vol)
331
if (NVolLogFileEmpty(vol))
333
ntfs_log_info("Going to empty the journal ($LogFile)... ");
334
if (ntfs_logfile_reset(vol)) {
335
ntfs_log_info(FAILED);
336
ntfs_log_perror("Failed to reset $LogFile");
344
* Clear the bad cluster marks (option)
346
static int clear_badclus(ntfs_volume *vol)
348
static ntfschar badstream[] = {
349
const_cpu_to_le16('$'), const_cpu_to_le16('B'),
350
const_cpu_to_le16('a'), const_cpu_to_le16('d')
357
ntfs_log_info("Going to un-mark the bad clusters ($BadClus)... ");
358
ni = ntfs_inode_open(vol, FILE_BadClus);
360
na = ntfs_attr_open(ni, AT_DATA, badstream, 4);
362
* chkdsk does not adjust the data size when
363
* moving clusters to $BadClus, so we have to
366
if (na && !ntfs_attr_map_whole_runlist(na)) {
368
&& na->rl[0].length && na->rl[1].length) {
370
* Truncate the stream to free all its clusters,
371
* (which requires setting the data size according
372
* to allocation), then reallocate a sparse stream
373
* to full size of volume and reset the data size.
375
na->data_size = na->allocated_size;
376
na->initialized_size = na->allocated_size;
377
if (!ntfs_attr_truncate(na,0)
378
&& !ntfs_attr_truncate(na,vol->nr_clusters
379
<< vol->cluster_size_bits)) {
381
na->initialized_size = 0;
382
ni->flags |= FILE_ATTR_SPARSE_FILE;
383
NInoFileNameSetDirty(ni);
386
ntfs_log_perror("Failed to un-mark the bad clusters");
389
ntfs_log_info("No bad clusters...");
394
ntfs_log_perror("Failed to open $BadClus::$Bad");
396
ntfs_inode_close(ni);
398
ntfs_log_perror("Failed to open inode FILE_BadClus");
402
return (ok ? 0 : -1);
408
static int fix_mftmirr(ntfs_volume *vol)
411
unsigned char *m, *m2;
412
int i, ret = -1; /* failure */
415
ntfs_log_info("\nProcessing $MFT and $MFTMirr...\n");
417
/* Load data from $MFT and $MFTMirr and compare the contents. */
418
m = (u8*)malloc(vol->mftmirr_size << vol->mft_record_size_bits);
420
ntfs_log_perror("Failed to allocate memory");
423
m2 = (u8*)malloc(vol->mftmirr_size << vol->mft_record_size_bits);
425
ntfs_log_perror("Failed to allocate memory");
430
ntfs_log_info("Reading $MFT... ");
431
l = ntfs_attr_mst_pread(vol->mft_na, 0, vol->mftmirr_size,
432
vol->mft_record_size, m);
433
if (l != vol->mftmirr_size) {
434
ntfs_log_info(FAILED);
437
ntfs_log_perror("Failed to read $MFT");
442
ntfs_log_info("Reading $MFTMirr... ");
443
l = ntfs_attr_mst_pread(vol->mftmirr_na, 0, vol->mftmirr_size,
444
vol->mft_record_size, m2);
445
if (l != vol->mftmirr_size) {
446
ntfs_log_info(FAILED);
449
ntfs_log_perror("Failed to read $MFTMirr");
455
* FIXME: Need to actually check the $MFTMirr for being real. Otherwise
456
* we might corrupt the partition if someone is experimenting with
457
* software RAID and the $MFTMirr is not actually in the position we
458
* expect it to be... )-:
459
* FIXME: We should emit a warning it $MFTMirr is damaged and ask
460
* user whether to recreate it from $MFT or whether to abort. - The
461
* warning needs to include the danger of software RAID arrays.
462
* Maybe we should go as far as to detect whether we are running on a
463
* MD disk and if yes then bomb out right at the start of the program?
466
ntfs_log_info("Comparing $MFTMirr to $MFT... ");
468
for (i = 0; i < vol->mftmirr_size; ++i) {
469
MFT_RECORD *mrec, *mrec2;
470
const char *ESTR[12] = { "$MFT", "$MFTMirr", "$LogFile",
471
"$Volume", "$AttrDef", "root directory", "$Bitmap",
472
"$Boot", "$BadClus", "$Secure", "$UpCase", "$Extend" };
484
mrec = (MFT_RECORD*)(m + i * vol->mft_record_size);
485
if (mrec->flags & MFT_RECORD_IN_USE) {
486
if (ntfs_is_baad_record(mrec->magic)) {
487
ntfs_log_info(FAILED);
488
ntfs_log_error("$MFT error: Incomplete multi "
489
"sector transfer detected in "
490
"%s.\nCannot handle this yet. "
494
if (!ntfs_is_mft_record(mrec->magic)) {
495
ntfs_log_info(FAILED);
496
ntfs_log_error("$MFT error: Invalid mft "
497
"record for %s.\nCannot "
498
"handle this yet. )-:\n", s);
502
mrec2 = (MFT_RECORD*)(m2 + i * vol->mft_record_size);
503
if (mrec2->flags & MFT_RECORD_IN_USE) {
504
if (ntfs_is_baad_record(mrec2->magic)) {
505
ntfs_log_info(FAILED);
506
ntfs_log_error("$MFTMirr error: Incomplete "
507
"multi sector transfer "
508
"detected in %s.\n", s);
511
if (!ntfs_is_mft_record(mrec2->magic)) {
512
ntfs_log_info(FAILED);
513
ntfs_log_error("$MFTMirr error: Invalid mft "
514
"record for %s.\n", s);
517
/* $MFT is corrupt but $MFTMirr is ok, use $MFTMirr. */
518
if (!(mrec->flags & MFT_RECORD_IN_USE) &&
519
!ntfs_is_mft_record(mrec->magic))
522
if (memcmp(mrec, mrec2, ntfs_mft_record_get_data_size(mrec))) {
525
ntfs_log_info(FAILED);
527
ntfs_log_info("Correcting differences in $MFT%s "
528
"record %d...", use_mirr ? "" : "Mirr",
530
br = ntfs_mft_record_write(vol, i,
531
use_mirr ? mrec2 : mrec);
533
ntfs_log_info(FAILED);
534
ntfs_log_perror("Error correcting $MFT%s",
535
use_mirr ? "" : "Mirr");
543
ntfs_log_info("Processing of $MFT and $MFTMirr completed "
553
* Rewrite the $UpCase file as default
555
* Returns 0 if could be written
558
static int rewrite_upcase(ntfs_volume *vol, ntfs_attr *na)
563
/* writing the $UpCase may require bitmap updates */
565
vol->lcnbmp_ni = ntfs_inode_open(vol, FILE_Bitmap);
566
if (!vol->lcnbmp_ni) {
567
ntfs_log_perror("Failed to open bitmap inode");
569
vol->lcnbmp_na = ntfs_attr_open(vol->lcnbmp_ni, AT_DATA,
571
if (!vol->lcnbmp_na) {
572
ntfs_log_perror("Failed to open bitmap data attribute");
574
/* minimal consistency check on the bitmap */
575
if (((vol->lcnbmp_na->data_size << 3)
577
|| ((vol->lcnbmp_na->data_size << 3)
578
>= (vol->nr_clusters << 1))
579
|| (vol->lcnbmp_na->data_size
580
> vol->lcnbmp_na->allocated_size)) {
581
ntfs_log_error("Corrupt cluster map size %lld"
582
" (allocated %lld minimum %lld)\n",
583
(long long)vol->lcnbmp_na->data_size,
584
(long long)vol->lcnbmp_na->allocated_size,
585
(long long)(vol->nr_clusters + 7) >> 3);
587
ntfs_log_info("Rewriting $UpCase file\n");
588
l = ntfs_attr_pwrite(na, 0, vol->upcase_len*2,
590
if (l != vol->upcase_len*2) {
591
ntfs_log_error("Failed to rewrite $UpCase\n");
593
ntfs_log_info("$UpCase has been set to default\n");
597
ntfs_attr_close(vol->lcnbmp_na);
598
vol->lcnbmp_na = (ntfs_attr*)NULL;
600
ntfs_inode_close(vol->lcnbmp_ni);
601
vol->lcnbmp_ni = (ntfs_inode*)NULL;
607
* Fix the $UpCase file
609
* Returns 0 if the table is valid or has been fixed
612
static int fix_upcase(ntfs_volume *vol)
623
ni = (ntfs_inode*)NULL;
624
na = (ntfs_attr*)NULL;
625
/* Now load the upcase table from $UpCase. */
626
ntfs_log_debug("Loading $UpCase...\n");
627
ni = ntfs_inode_open(vol, FILE_UpCase);
629
ntfs_log_perror("Failed to open inode FILE_UpCase");
632
/* Get an ntfs attribute for $UpCase/$DATA. */
633
na = ntfs_attr_open(ni, AT_DATA, AT_UNNAMED, 0);
635
ntfs_log_perror("Failed to open ntfs attribute");
639
* Note: Normally, the upcase table has a length equal to 65536
640
* 2-byte Unicode characters but allow for different cases, so no
641
* checks done. Just check we don't overflow 32-bits worth of Unicode
644
if (na->data_size & ~0x1ffffffffULL) {
645
ntfs_log_error("Error: Upcase table is too big (max 32-bit "
650
upcase_len = na->data_size >> 1;
651
upcase = (ntfschar*)ntfs_malloc(na->data_size);
654
/* Read in the $DATA attribute value into the buffer. */
655
l = ntfs_attr_pread(na, 0, na->data_size, upcase);
656
if (l != na->data_size) {
657
ntfs_log_error("Failed to read $UpCase, unexpected length "
658
"(%lld != %lld).\n", (long long)l,
659
(long long)na->data_size);
663
/* Consistency check of $UpCase, restricted to plain ASCII chars */
665
while ((k < upcase_len)
667
&& (le16_to_cpu(upcase[k])
668
== ((k < 'a') || (k > 'z') ? k : k + 'A' - 'a')))
671
ntfs_log_error("Corrupted file $UpCase\n");
672
if (!opt.no_action) {
673
/* rewrite the $UpCase file from default */
674
res = rewrite_upcase(vol, na);
675
/* free the bad upcase record */
679
/* keep the default upcase but return an error */
683
/* accept the upcase table read from $UpCase */
685
vol->upcase = upcase;
686
vol->upcase_len = upcase_len;
690
/* Done with the $UpCase mft record. */
693
if (ni && ntfs_inode_close(ni)) {
694
ntfs_log_perror("Failed to close $UpCase");
700
* Rewrite the boot sector
702
* Returns 0 if successful
705
static int rewrite_boot(struct ntfs_device *dev, char *full_bs,
712
ntfs_log_info("Rewriting the bootsector\n");
713
bw = ntfs_pwrite(dev, 0, sector_size, full_bs);
714
if (bw == sector_size)
720
ntfs_log_error("Failed to rewrite the bootsector (size=0)\n");
722
ntfs_log_perror("Error rewriting the bootsector");
728
* Locate an unnamed attribute in an MFT record
730
* Returns NULL if not found (with no error message)
733
static ATTR_RECORD *find_unnamed_attr(MFT_RECORD *mrec, ATTR_TYPES type)
738
/* fetch the requested attribute */
739
offset = le16_to_cpu(mrec->attrs_offset);
740
a = (ATTR_RECORD*)((char*)mrec + offset);
741
while ((a->type != AT_END)
742
&& ((a->type != type) || a->name_length)
743
&& (offset < le32_to_cpu(mrec->bytes_in_use))) {
744
offset += le32_to_cpu(a->length);
745
a = (ATTR_RECORD*)((char*)mrec + offset);
747
if ((a->type != type)
749
a = (ATTR_RECORD*)NULL;
754
* First condition for having a self-located MFT :
755
* only 16 MFT records are defined in MFT record 0
757
* Only low-level library functions can be used.
759
* Returns TRUE if the condition is met.
762
static BOOL short_mft_selfloc_condition(struct MFT_SELF_LOCATED *selfloc)
773
mft0 = selfloc->mft0;
774
if ((ntfs_pread(vol->dev,
775
vol->mft_lcn << vol->cluster_size_bits,
776
vol->mft_record_size, mft0)
777
== vol->mft_record_size)
778
&& !ntfs_mst_post_read_fixup((NTFS_RECORD*)mft0,
779
vol->mft_record_size)) {
780
a = find_unnamed_attr(mft0,AT_DATA);
783
&& (((le64_to_cpu(a->highest_vcn) + 1)
784
<< vol->cluster_size_bits)
785
== (SELFLOC_LIMIT*vol->mft_record_size))) {
786
rl = ntfs_mapping_pairs_decompress(vol, a, NULL);
789
* The first error condition is having only
790
* 16 entries mapped in the first MFT record.
793
&& ((rl[0].length << vol->cluster_size_bits)
794
== SELFLOC_LIMIT*vol->mft_record_size)
795
&& (rl[1].vcn == rl[0].length)
796
&& (rl[1].lcn == LCN_RL_NOT_MAPPED)) {
799
mft0->sequence_number);
801
= ((MFT_REF)seqn) << 48;
811
* Second condition for having a self-located MFT :
812
* The 16th MFT record is defined in MFT record >= 16
814
* Only low-level library functions can be used.
816
* Returns TRUE if the condition is met.
819
static BOOL attrlist_selfloc_condition(struct MFT_SELF_LOCATED *selfloc)
823
ATTR_LIST_ENTRY *attrlist;
834
a = find_unnamed_attr(selfloc->mft0,AT_ATTRIBUTE_LIST);
836
selfloc->attrlist_resident = !a->non_resident;
837
selfloc->attrlist_lcn = 0;
838
if (a->non_resident) {
839
attrlist = selfloc->attrlist;
840
rl = ntfs_mapping_pairs_decompress(vol, a, NULL);
843
&& (le64_to_cpu(a->data_size) < vol->cluster_size)
844
&& (ntfs_pread(vol->dev,
845
rl->lcn << vol->cluster_size_bits,
846
vol->cluster_size, attrlist) == vol->cluster_size)) {
847
selfloc->attrlist_lcn = rl->lcn;
849
length = le64_to_cpu(a->data_size);
852
al = (ATTR_LIST_ENTRY*)
853
((char*)a + le16_to_cpu(a->value_offset));
854
length = le32_to_cpu(a->value_length);
857
/* search for a data attribute defining entry 16 */
858
vcn = (SELFLOC_LIMIT*vol->mft_record_size)
859
>> vol->cluster_size_bits;
860
levcn = cpu_to_le64(vcn);
863
&& ((al->type != AT_DATA)
864
|| ((leVCN)al->lowest_vcn != levcn))) {
865
length -= le16_to_cpu(al->length);
866
al = (ATTR_LIST_ENTRY*)
867
((char*)al + le16_to_cpu(al->length));
871
&& (al->type == AT_DATA)
873
&& ((leVCN)al->lowest_vcn == levcn)
874
&& (MREF_LE(al->mft_reference) >= SELFLOC_LIMIT)) {
876
= le64_to_cpu(al->mft_reference);
877
selfloc->attrlist_to_ref1 = al;
886
* Third condition for having a self-located MFT :
887
* The location of the second part of the MFT is defined in itself
889
* To locate the second part, we have to assume the first and the
890
* second part of the MFT data are contiguous.
892
* Only low-level library functions can be used.
894
* Returns TRUE if the condition is met.
897
static BOOL self_mapped_selfloc_condition(struct MFT_SELF_LOCATED *selfloc)
910
mft1 = selfloc->mft1;
911
inum = MREF(selfloc->mft_ref1);
912
offs = (vol->mft_lcn << vol->cluster_size_bits)
913
+ (inum << vol->mft_record_size_bits);
914
if ((ntfs_pread(vol->dev, offs, vol->mft_record_size,
915
mft1) == vol->mft_record_size)
916
&& !ntfs_mst_post_read_fixup((NTFS_RECORD*)mft1,
917
vol->mft_record_size)) {
918
lowest_vcn = (SELFLOC_LIMIT*vol->mft_record_size)
919
>> vol->cluster_size_bits;
920
a = find_unnamed_attr(mft1,AT_DATA);
922
&& (mft1->flags & MFT_RECORD_IN_USE)
923
&& ((VCN)le64_to_cpu(a->lowest_vcn) == lowest_vcn)
924
&& (le64_to_cpu(mft1->base_mft_record)
925
== selfloc->mft_ref0)
926
&& ((u16)MSEQNO(selfloc->mft_ref1)
927
== le16_to_cpu(mft1->sequence_number))) {
928
rl = ntfs_mapping_pairs_decompress(vol, a, NULL);
929
if ((rl[0].lcn == LCN_RL_NOT_MAPPED)
931
&& (rl[0].length == lowest_vcn)
932
&& (rl[1].vcn == lowest_vcn)
933
&& ((u64)(rl[1].lcn << vol->cluster_size_bits)
935
&& ((u64)((rl[1].lcn + rl[1].length)
936
<< vol->cluster_size_bits) > offs)) {
945
* Fourth condition, to be able to fix a self-located MFT :
946
* The MFT record 15 must be available.
948
* The MFT record 15 is expected to be marked in use, we assume
949
* it is available if it has no parent, no name and no attr list.
951
* Only low-level library functions can be used.
953
* Returns TRUE if the condition is met.
956
static BOOL spare_record_selfloc_condition(struct MFT_SELF_LOCATED *selfloc)
966
mft2 = selfloc->mft2;
967
inum = SELFLOC_LIMIT - 1;
968
offs = (vol->mft_lcn << vol->cluster_size_bits)
969
+ (inum << vol->mft_record_size_bits);
970
if ((ntfs_pread(vol->dev, offs, vol->mft_record_size,
971
mft2) == vol->mft_record_size)
972
&& !ntfs_mst_post_read_fixup((NTFS_RECORD*)mft2,
973
vol->mft_record_size)) {
974
if (!mft2->base_mft_record
975
&& (mft2->flags & MFT_RECORD_IN_USE)
976
&& !find_unnamed_attr(mft2,AT_ATTRIBUTE_LIST)
977
&& !find_unnamed_attr(mft2,AT_FILE_NAME)) {
985
* Fix a self-located MFT by swapping two MFT records
987
* Only low-level library functions can be used.
989
* Returns 0 if the MFT corruption could be fixed.
991
static int fix_selfloc_conditions(struct MFT_SELF_LOCATED *selfloc)
1008
* In MFT1, we must fix :
1009
* - the self-reference, if present,
1010
* - its own sequence number, must be 15
1011
* - the sizes of the data attribute.
1014
mft1 = selfloc->mft1;
1015
mft2 = selfloc->mft2;
1016
usa_ofs = le16_to_cpu(mft1->usa_ofs);
1018
mft1->mft_record_number = const_cpu_to_le32(SELFLOC_LIMIT - 1);
1019
mft1->sequence_number = const_cpu_to_le16(SELFLOC_LIMIT - 1);
1020
a = find_unnamed_attr(mft1,AT_DATA);
1022
a->allocated_size = const_cpu_to_le64(0);
1023
a->data_size = const_cpu_to_le64(0);
1024
a->initialized_size = const_cpu_to_le64(0);
1026
res = -1; /* bug : it has been found earlier */
1029
* In MFT2, we must fix :
1030
* - the self-reference, if present
1032
usa_ofs = le16_to_cpu(mft2->usa_ofs);
1034
mft2->mft_record_number = cpu_to_le32(MREF(selfloc->mft_ref1));
1037
* In the attribute list, we must fix :
1038
* - the reference to MFT1
1040
al = selfloc->attrlist_to_ref1;
1041
al->mft_reference = MK_LE_MREF(SELFLOC_LIMIT - 1, SELFLOC_LIMIT - 1);
1044
* All fixes done, we can write all if allowed
1046
if (!res && !opt.no_action) {
1047
inum = SELFLOC_LIMIT - 1;
1048
offs2 = (vol->mft_lcn << vol->cluster_size_bits)
1049
+ (inum << vol->mft_record_size_bits);
1050
inum = MREF(selfloc->mft_ref1);
1051
offs1 = (vol->mft_lcn << vol->cluster_size_bits)
1052
+ (inum << vol->mft_record_size_bits);
1054
/* rewrite the attribute list */
1055
if (selfloc->attrlist_resident) {
1056
/* write mft0 and mftmirr if it is resident */
1057
offs = vol->mft_lcn << vol->cluster_size_bits;
1058
offsm = vol->mftmirr_lcn << vol->cluster_size_bits;
1059
if (ntfs_mst_pre_write_fixup(
1060
(NTFS_RECORD*)selfloc->mft0,
1061
vol->mft_record_size)
1062
|| (ntfs_pwrite(vol->dev, offs, vol->mft_record_size,
1063
selfloc->mft0) != vol->mft_record_size)
1064
|| (ntfs_pwrite(vol->dev, offsm, vol->mft_record_size,
1065
selfloc->mft0) != vol->mft_record_size))
1068
/* write a full cluster if non resident */
1069
offs = selfloc->attrlist_lcn << vol->cluster_size_bits;
1070
if (ntfs_pwrite(vol->dev, offs, vol->cluster_size,
1071
selfloc->attrlist) != vol->cluster_size)
1074
/* replace MFT2 by MFT1 and replace MFT1 by MFT2 */
1076
&& (ntfs_mst_pre_write_fixup((NTFS_RECORD*)selfloc->mft1,
1077
vol->mft_record_size)
1078
|| ntfs_mst_pre_write_fixup((NTFS_RECORD*)selfloc->mft2,
1079
vol->mft_record_size)
1080
|| (ntfs_pwrite(vol->dev, offs2, vol->mft_record_size,
1081
mft1) != vol->mft_record_size)
1082
|| (ntfs_pwrite(vol->dev, offs1, vol->mft_record_size,
1083
mft2) != vol->mft_record_size)))
1090
* Detect and fix a Windows XP bug, leading to a corrupt MFT
1092
* Windows cannot boot anymore, so chkdsk cannot be started, which
1093
* is a good point, because chkdsk would have deleted all the files.
1094
* Older ntfs-3g fell into an endless recursion (recent versions
1097
* This situation is very rare, but it was fun to fix it.
1099
* The corrupted condition is :
1100
* - MFT entry 0 has only the runlist for MFT entries 0-15
1101
* - The attribute list for MFT shows the second part
1102
* in an MFT record beyond 15
1103
* Of course, this record has to be read in order to know where it is.
1105
* Sample case, met in 2011 (Windows XP) :
1106
* MFT record 0 has : stdinfo, nonres attrlist, the first
1107
* part of MFT data (entries 0-15), and bitmap
1108
* MFT record 16 has the name
1109
* MFT record 17 has the third part of MFT data (16-117731)
1110
* MFT record 18 has the second part of MFT data (117732-170908)
1112
* Assuming the second part of the MFT is contiguous to the first
1113
* part, we can find it, and fix the condition by relocating it
1114
* and swapping it with MFT record 15.
1115
* This record number 15 appears to be hardcoded into Windows NTFS.
1117
* Only low-level library functions can be used.
1119
* Returns 0 if the conditions for the error were not met or
1120
* the error could be fixed,
1121
* -1 if some error was encountered
1124
static int fix_self_located_mft(ntfs_volume *vol)
1126
struct MFT_SELF_LOCATED selfloc;
1129
ntfs_log_info("Checking for self-located MFT segment... ");
1132
selfloc.mft0 = (MFT_RECORD*)malloc(vol->mft_record_size);
1133
selfloc.mft1 = (MFT_RECORD*)malloc(vol->mft_record_size);
1134
selfloc.mft2 = (MFT_RECORD*)malloc(vol->mft_record_size);
1135
selfloc.attrlist = (ATTR_LIST_ENTRY*)malloc(vol->cluster_size);
1136
if (selfloc.mft0 && selfloc.mft1 && selfloc.mft2
1137
&& selfloc.attrlist) {
1138
if (short_mft_selfloc_condition(&selfloc)
1139
&& attrlist_selfloc_condition(&selfloc)
1140
&& self_mapped_selfloc_condition(&selfloc)
1141
&& spare_record_selfloc_condition(&selfloc)) {
1142
ntfs_log_info(FOUND);
1143
ntfs_log_info("Fixing the self-located MFT segment... ");
1144
res = fix_selfloc_conditions(&selfloc);
1145
ntfs_log_info(res ? FAILED : OK);
1153
free(selfloc.attrlist);
1159
* Try an alternate boot sector and fix the real one
1161
* Only after successful checks is the boot sector rewritten.
1163
* The alternate boot sector is not rewritten, either because it
1164
* was found correct, or because we truncated the file system
1165
* and the last actual sector might be part of some file.
1167
* Returns 0 if successful
1170
static int try_fix_boot(ntfs_volume *vol, char *full_bs,
1171
s64 read_sector, s64 fix_sectors, s32 sector_size)
1176
le16 sector_size_le;
1177
NTFS_BOOT_SECTOR *bs;
1180
br = ntfs_pread(vol->dev, read_sector*sector_size,
1181
sector_size, full_bs);
1182
if (br != sector_size) {
1186
ntfs_log_error("Failed to read alternate bootsector (size=0)\n");
1188
ntfs_log_perror("Error reading alternate bootsector");
1190
bs = (NTFS_BOOT_SECTOR*)full_bs;
1191
got_sectors = le64_to_cpu(bs->number_of_sectors);
1192
bs->number_of_sectors = cpu_to_le64(fix_sectors);
1193
/* alignment problem on Sparc, even doing memcpy() */
1194
sector_size_le = cpu_to_le16(sector_size);
1195
if (!memcmp(§or_size_le, &bs->bpb.bytes_per_sector,2)
1196
&& ntfs_boot_sector_is_ntfs(bs)
1197
&& !ntfs_boot_sector_parse(vol, bs)) {
1198
ntfs_log_info("The alternate bootsector is usable\n");
1199
if (fix_sectors != got_sectors)
1200
ntfs_log_info("Set sector count to %lld instead of %lld\n",
1201
(long long)fix_sectors,
1202
(long long)got_sectors);
1203
/* fix the normal boot sector */
1204
if (!opt.no_action) {
1205
res = rewrite_boot(vol->dev, full_bs,
1210
if (!res && !opt.no_action)
1211
ntfs_log_info("The boot sector has been rewritten\n");
1217
* Try the alternate boot sector if the normal one is bad
1220
* - first try the last sector of the partition (expected location)
1221
* - then try the last sector as shown in the main boot sector,
1222
* (could be meaningful for an undersized partition)
1223
* - finally try truncating the file system actual size of partition
1224
* (could be meaningful for an oversized partition)
1226
* if successful, rewrite the normal boot sector accordingly
1228
* Returns 0 if successful
1231
static int try_alternate_boot(ntfs_volume *vol, char *full_bs,
1232
s32 sector_size, s64 shown_sectors)
1238
ntfs_log_info("Trying the alternate boot sector\n");
1241
* We do not rely on the sector size defined in the
1242
* boot sector, supposed to be corrupt, so we try to get
1243
* the actual sector size and defaulting to 512 if failed
1244
* to get. This value is only used to guess the alternate
1245
* boot sector location and it is checked against the
1246
* value found in the sector itself. It should not damage
1247
* anything if wrong.
1249
* Note : the real last sector is not accounted for here.
1251
actual_sectors = ntfs_device_size_get(vol->dev,sector_size) - 1;
1253
/* first try the actual last sector */
1254
if ((actual_sectors > 0)
1255
&& !try_fix_boot(vol, full_bs, actual_sectors,
1256
actual_sectors, sector_size))
1259
/* then try the shown last sector, if less than actual */
1261
&& (shown_sectors > 0)
1262
&& (shown_sectors < actual_sectors)
1263
&& !try_fix_boot(vol, full_bs, shown_sectors,
1264
shown_sectors, sector_size))
1267
/* then try reducing the number of sectors to actual value */
1269
&& (shown_sectors > actual_sectors)
1270
&& !try_fix_boot(vol, full_bs, 0, actual_sectors, sector_size))
1277
* Check and fix the alternate boot sector
1279
* The alternate boot sector is usually in the last sector of a
1280
* partition, which should not be used by the file system
1281
* (the sector count in the boot sector should be less than
1282
* the total sector count in the partition).
1284
* chkdsk never changes the count in the boot sector.
1285
* - If this is less than the total count, chkdsk place the
1286
* alternate boot sector into the sector,
1287
* - if the count is the same as the total count, chkdsk place
1288
* the alternate boot sector into the middle sector (half
1289
* the total count rounded upwards)
1290
* - if the count is greater than the total count, chkdsk
1291
* declares the file system as raw, and refuses to fix anything.
1293
* Here, we check and fix the alternate boot sector, only in the
1294
* first situation where the file system does not overflow on the
1297
* Note : when shrinking a partition, ntfsresize cannot determine
1298
* the future size of the partition. As a consequence the number of
1299
* sectors in the boot sectors may be less than the possible size.
1301
* Returns 0 if successful
1304
static int check_alternate_boot(ntfs_volume *vol)
1308
s64 last_sector_off;
1311
NTFS_BOOT_SECTOR *bs;
1317
full_bs = (char*)malloc(vol->sector_size);
1318
alt_bs = (char*)malloc(vol->sector_size);
1319
if (!full_bs || !alt_bs) {
1320
ntfs_log_info("Error : failed to allocate memory\n");
1323
/* Now read both bootsectors. */
1324
br = ntfs_pread(vol->dev, 0, vol->sector_size, full_bs);
1325
if (br == vol->sector_size) {
1326
bs = (NTFS_BOOT_SECTOR*)full_bs;
1327
got_sectors = le64_to_cpu(bs->number_of_sectors);
1328
actual_sectors = ntfs_device_size_get(vol->dev,
1330
if (actual_sectors > got_sectors) {
1331
last_sector_off = (actual_sectors - 1)
1332
<< vol->sector_size_bits;
1333
ntfs_log_info("Checking the alternate boot sector... ");
1334
br = ntfs_pread(vol->dev, last_sector_off,
1335
vol->sector_size, alt_bs);
1337
ntfs_log_info("Checking file system overflow... ");
1340
/* accept getting no byte, needed for short image files */
1342
if ((br != vol->sector_size)
1343
|| memcmp(full_bs, alt_bs, vol->sector_size)) {
1344
if (opt.no_action) {
1345
ntfs_log_info("BAD\n");
1347
bw = ntfs_pwrite(vol->dev,
1349
vol->sector_size, full_bs);
1350
if (bw == vol->sector_size) {
1351
ntfs_log_info("FIXED\n");
1354
ntfs_log_info(FAILED);
1362
ntfs_log_info(FAILED);
1365
ntfs_log_info("Error : could not read the boot sector again\n");
1375
* Try to fix problems which may arise in the start up sequence
1377
* This is a replay of the normal start up sequence with fixes when
1378
* some problem arise.
1381
static int fix_startup(struct ntfs_device *dev, unsigned long flags)
1388
NTFS_BOOT_SECTOR *bs;
1396
full_bs = (char*)NULL;
1397
if (!dev || !dev->d_ops || !dev->d_name) {
1399
ntfs_log_perror("%s: dev = %p", __FUNCTION__, dev);
1400
vol = (ntfs_volume*)NULL;
1404
/* Allocate the volume structure. */
1405
vol = ntfs_volume_alloc();
1409
/* Create the default upcase table. */
1410
vol->upcase_len = ntfs_upcase_build_default(&vol->upcase);
1411
if (!vol->upcase_len || !vol->upcase)
1414
/* Default with no locase table and case sensitive file names */
1415
vol->locase = (ntfschar*)NULL;
1416
NVolSetCaseSensitive(vol);
1418
/* by default, all files are shown and not marked hidden */
1419
NVolSetShowSysFiles(vol);
1420
NVolSetShowHidFiles(vol);
1421
NVolClearHideDotFiles(vol);
1422
if (flags & NTFS_MNT_RDONLY)
1423
NVolSetReadOnly(vol);
1425
/* ...->open needs bracketing to compile with glibc 2.7 */
1426
if ((dev->d_ops->open)(dev, NVolReadOnly(vol) ? O_RDONLY: O_RDWR)) {
1427
ntfs_log_perror("Error opening '%s'", dev->d_name);
1431
/* Attach the device to the volume. */
1434
sector_size = ntfs_device_sector_size_get(dev);
1435
if (sector_size <= 0)
1436
sector_size = DEFAULT_SECTOR_SIZE;
1437
full_bs = (char*)malloc(sector_size);
1440
/* Now read the bootsector. */
1441
br = ntfs_pread(dev, 0, sector_size, full_bs);
1442
if (br != sector_size) {
1446
ntfs_log_error("Failed to read bootsector (size=0)\n");
1448
ntfs_log_perror("Error reading bootsector");
1451
bs = (NTFS_BOOT_SECTOR*)full_bs;
1452
if (!ntfs_boot_sector_is_ntfs(bs)
1453
/* get the bootsector data, only fails when inconsistent */
1454
|| (ntfs_boot_sector_parse(vol, bs) < 0)) {
1455
shown_sectors = le64_to_cpu(bs->number_of_sectors);
1456
/* boot sector is wrong, try the alternate boot sector */
1457
if (try_alternate_boot(vol, full_bs, sector_size,
1464
res = fix_self_located_mft(vol);
1470
ntfs_log_error("Failed to allocate memory\n");
1473
ntfs_log_error("Unrecoverable error\n");
1486
(dev->d_ops->close)(dev);
1495
static int fix_mount(void)
1497
int ret = 0; /* default success */
1499
struct ntfs_device *dev;
1500
unsigned long flags;
1502
ntfs_log_info("Attempting to correct errors... ");
1504
dev = ntfs_device_alloc(opt.volume, 0, &ntfs_device_default_io_ops,
1507
ntfs_log_info(FAILED);
1508
ntfs_log_perror("Failed to allocate device");
1511
flags = (opt.no_action ? NTFS_MNT_RDONLY : 0);
1512
vol = ntfs_volume_startup(dev, flags);
1514
ntfs_log_info(FAILED);
1515
ntfs_log_perror("Failed to startup volume");
1517
/* Try fixing the bootsector and MFT, then redo the startup */
1518
if (!fix_startup(dev, flags)) {
1520
ntfs_log_info("The startup data can be fixed, "
1521
"but no change was requested\n");
1523
vol = ntfs_volume_startup(dev, flags);
1526
ntfs_log_error("Volume is corrupt. You should run chkdsk.\n");
1527
ntfs_device_free(dev);
1531
ret = -1; /* error present and not fixed */
1533
/* if option -n proceed despite errors, to display them all */
1534
if ((!ret || opt.no_action) && (fix_mftmirr(vol) < 0))
1536
if ((!ret || opt.no_action) && (fix_upcase(vol) < 0))
1538
if ((!ret || opt.no_action) && (set_dirty_flag(vol) < 0))
1540
if ((!ret || opt.no_action) && (empty_journal(vol) < 0))
1543
* ntfs_umount() will invoke ntfs_device_free() for us.
1544
* Ignore the returned error resulting from partial mounting.
1546
ntfs_umount(vol, 1);
1553
int main(int argc, char **argv)
1556
unsigned long mnt_flags;
1557
unsigned long flags;
1558
int ret = 1; /* failure */
1561
ntfs_log_set_handler(ntfs_log_handler_outerr);
1563
parse_options(argc, argv);
1565
if (!ntfs_check_if_mounted(opt.volume, &mnt_flags)) {
1566
if ((mnt_flags & NTFS_MF_MOUNTED) &&
1567
!(mnt_flags & NTFS_MF_READONLY) && !force) {
1568
ntfs_log_error("Refusing to operate on read-write "
1569
"mounted device %s.\n", opt.volume);
1573
ntfs_log_perror("Failed to determine whether %s is mounted",
1575
/* Attempt a full mount first. */
1576
flags = (opt.no_action ? NTFS_MNT_RDONLY : 0);
1577
ntfs_log_info("Mounting volume... ");
1578
vol = ntfs_mount(opt.volume, flags);
1581
ntfs_log_info("Processing of $MFT and $MFTMirr completed "
1584
ntfs_log_info(FAILED);
1585
if (fix_mount() < 0) {
1587
ntfs_log_info("No change made\n");
1590
vol = ntfs_mount(opt.volume, 0);
1592
ntfs_log_perror("Remount failed");
1596
if (check_alternate_boot(vol)) {
1597
ntfs_log_error("Error: Failed to fix the alternate boot sector\n");
1600
/* So the unmount does not clear it again. */
1602
/* Porting note: The WasDirty flag was set here to prevent ntfs_unmount
1603
* from clearing the dirty bit (which might have been set in
1604
* fix_mount()). So the intention is to leave the dirty bit set.
1606
* libntfs-3g does not automatically set or clear dirty flags on
1607
* mount/unmount, this means that the assumption that the dirty flag is
1608
* now set does not hold. So we need to set it if not already set.
1610
* However clear the flag if requested to do so, at this stage
1611
* mounting was successful.
1613
if (opt.clear_dirty)
1614
vol->flags &= ~VOLUME_IS_DIRTY;
1616
vol->flags |= VOLUME_IS_DIRTY;
1617
if (!opt.no_action && ntfs_volume_write_flags(vol, vol->flags)) {
1618
ntfs_log_error("Error: Failed to set volume dirty flag (%d "
1619
"(%s))!\n", errno, strerror(errno));
1622
/* Check NTFS version is ok for us (in $Volume) */
1623
ntfs_log_info("NTFS volume version is %i.%i.\n", vol->major_ver,
1625
if (ntfs_version_is_supported(vol)) {
1626
ntfs_log_error("Error: Unknown NTFS version.\n");
1629
if (opt.clear_bad_sectors && !opt.no_action) {
1630
if (clear_badclus(vol)) {
1631
ntfs_log_error("Error: Failed to un-mark bad sectors.\n");
1635
if (vol->major_ver >= 3) {
1637
* FIXME: If on NTFS 3.0+, check for presence of the usn
1638
* journal and stamp it if present.
1641
/* FIXME: We should be marking the quota out of date, too. */
1642
/* That's all for now! */
1643
ntfs_log_info("NTFS partition %s was processed successfully.\n",
1645
/* Set return code to 0. */
1648
if (ntfs_umount(vol, 0))
1649
ntfs_umount(vol, 1);