http://linux-ntfs.sourceforge.net/snapshots/ntfsprogs-200307311516.tar.bz2
[ntfsprogs.git] / libntfs / volume.c
1 /*
2  * volume.c - NTFS volume handling code. Part of the Linux-NTFS project.
3  *
4  * Copyright (c) 2000-2003 Anton Altaparmakov
5  *
6  * This program/include file is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as published
8  * by the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program/include file is distributed in the hope that it will be
12  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program (in the main directory of the Linux-NTFS
18  * distribution in the file COPYING); if not, write to the Free Software
19  * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <fcntl.h>
26 #include <unistd.h>
27 #include <errno.h>
28 #include <sys/stat.h>
29 #include <limits.h>
30
31 #include "volume.h"
32 #include "attrib.h"
33 #include "mft.h"
34 #include "bootsect.h"
35 #include "disk_io.h"
36 #include "debug.h"
37 #include "inode.h"
38 #include "runlist.h"
39
40 /**
41  * ntfs_volume_alloc -
42  *
43  */
44 ntfs_volume *ntfs_volume_alloc(void)
45 {
46         ntfs_volume *vol;
47
48         vol = (ntfs_volume*)calloc(1, sizeof(ntfs_volume));
49         if (vol) {
50                 vol->dev = NULL;
51                 vol->vol_name = NULL;
52                 vol->lcnbmp_ni = NULL;
53                 vol->lcnbmp_na = NULL;
54                 vol->mft_ni = NULL;
55                 vol->mft_na = NULL;
56                 vol->mftbmp_na = NULL;
57                 vol->mftmirr_ni = NULL;
58                 vol->mftmirr_na = NULL;
59                 vol->upcase = NULL;
60                 vol->attrdef = NULL;
61         }
62         return vol;
63 }
64
65 /**
66  * Internal:
67  *
68  * __ntfs_volume_release -
69  *
70  */
71 static void __ntfs_volume_release(ntfs_volume *v)
72 {
73         if (v->lcnbmp_na)
74                 ntfs_attr_close(v->lcnbmp_na);
75         if (v->lcnbmp_ni)
76                 ntfs_inode_close(v->lcnbmp_ni);
77         if (v->mftbmp_na)
78                 ntfs_attr_close(v->mftbmp_na);
79         if (v->mft_na)
80                 ntfs_attr_close(v->mft_na);
81         if (v->mft_ni)
82                 ntfs_inode_close(v->mft_ni);
83         if (v->mftmirr_na)
84                 ntfs_attr_close(v->mftmirr_na);
85         if (v->mftmirr_ni)
86                 ntfs_inode_close(v->mftmirr_ni);
87         if (v->dev) {
88                 struct ntfs_device *dev = v->dev;
89
90                 if (NDevDirty(dev))
91                         dev->d_ops->sync(dev);
92                 if (dev->d_ops->close(dev))
93                         fprintf(stderr, "%s(): Eeek! Failed to close the "
94                                         "device. Error: %s\n", __FUNCTION__,
95                                         strerror(errno));
96         }
97         if (v->vol_name)
98                 free(v->vol_name);
99         if (v->upcase)
100                 free(v->upcase);
101         if (v->attrdef)
102                 free(v->attrdef);
103         free(v);
104 }
105
106 /* External declaration for internal function. */
107 extern ntfs_inode *ntfs_inode_allocate(ntfs_volume *);
108
109 /**
110  * Internal:
111  *
112  * ntfs_mft_load - load the $MFT and setup the ntfs volume with it
113  * @vol:        ntfs volume whose $MFT to load
114  *
115  * Load $MFT from @vol and setup @vol with it. After calling this function the
116  * volume @vol is ready for use by all read access functions provided by the
117  * ntfs library.
118  *
119  * Return 0 on success and -1 on error with errno set to the error code.
120  */
121 static int ntfs_mft_load(ntfs_volume *vol)
122 {
123         VCN next_vcn, last_vcn, highest_vcn;
124         s64 l;
125         MFT_RECORD *mb = NULL;
126         ntfs_attr_search_ctx *ctx = NULL;
127         ATTR_RECORD *a;
128         int eo;
129
130         /* Manually setup an ntfs_inode. */
131         vol->mft_ni = ntfs_inode_allocate(vol);
132         mb = (MFT_RECORD*)malloc(vol->mft_record_size);
133         if (!vol->mft_ni || !mb) {
134                 Dperror("Error allocating memory for $MFT");
135                 goto error_exit;
136         }
137         vol->mft_ni->mft_no = 0;
138         vol->mft_ni->mrec = mb;
139         /* Can't use any of the higher level functions yet! */
140         l = ntfs_mst_pread(vol->dev, vol->mft_lcn << vol->cluster_size_bits, 1,
141                         vol->mft_record_size, mb);
142         if (l != 1) {
143                 if (l != -1)
144                         errno = EIO;
145                 Dperror("Error reading $MFT");
146                 goto error_exit;
147         }
148         if (ntfs_is_baad_record(mb->magic)) {
149                 Dputs("Error: Incomplete multi sector transfer detected in "
150                                 "$MFT.");
151                 goto io_error_exit;
152         }
153         if (!ntfs_is_mft_record(mb->magic)) {
154                 Dputs("Error: $MFT has invalid magic.");
155                 goto io_error_exit;
156         }
157         ctx = ntfs_attr_get_search_ctx(vol->mft_ni, mb);
158         if (!ctx) {
159                 Dperror("Failed to allocate attribute search context");
160                 goto error_exit;
161         }
162         if (p2n(ctx->attr) < p2n(mb) ||
163                         (char*)ctx->attr > (char*)mb + vol->mft_record_size) {
164                 Dputs("Error: $MFT is corrupt.");
165                 goto io_error_exit;
166         }
167         /* Find the $ATTRIBUTE_LIST attribute in $MFT if present. */
168         if (ntfs_attr_lookup(AT_ATTRIBUTE_LIST, AT_UNNAMED, 0, 0, 0, NULL, 0,
169                         ctx)) {
170                 if (errno != ENOENT) {
171                         Dputs("Error: $MFT has corrupt attribute list.");
172                         goto io_error_exit;
173                 }
174                 goto mft_has_no_attr_list;
175         }
176         NInoSetAttrList(vol->mft_ni);
177         l = ntfs_get_attribute_value_length(ctx->attr);
178         if (l <= 0 || l > 0x40000) {
179                 Dputs("Error: $MFT/$ATTRIBUTE_LIST has invalid length.");
180                 goto io_error_exit;
181         }
182         vol->mft_ni->attr_list_size = l;
183         vol->mft_ni->attr_list = malloc(l);
184         if (!vol->mft_ni->attr_list) {
185                 Dputs("Error: failed to allocate buffer for attribute list.");
186                 goto error_exit;
187         }
188         l = ntfs_get_attribute_value(vol, vol->mft_ni->mrec, ctx->attr,
189                         vol->mft_ni->attr_list);
190         if (!l) {
191                 Dputs("Error: failed to get value of $MFT/$ATTRIBUTE_LIST.");
192                 goto io_error_exit;
193         }
194         if (l != vol->mft_ni->attr_list_size) {
195                 Dputs("Error: got unexepected amount of data when reading "
196                                 "$MFT/$ATTRIBUTE_LIST.");
197                 goto io_error_exit;
198         }
199         if (ctx->attr->non_resident) {
200                 NInoSetAttrListNonResident(vol->mft_ni);
201                 // FIXME: We are duplicating work here! (AIA)
202                 vol->mft_ni->attr_list_rl = ntfs_mapping_pairs_decompress(vol,
203                                 ctx->attr, NULL);
204                 if (!vol->mft_ni->attr_list_rl) {
205                         Dperror("Error: failed to get runlist for "
206                                         "$MFT/$ATTRIBUTE_LIST");
207                         goto error_exit;
208                 }
209         }
210 mft_has_no_attr_list:
211         /* We now have a fully setup ntfs inode for $MFT in vol->mft_ni. */
212
213         /* Get an ntfs attribute for $MFT/$DATA and set it up, too. */
214         vol->mft_na = ntfs_attr_open(vol->mft_ni, AT_DATA, AT_UNNAMED, 0);
215         if (!vol->mft_na) {
216                 Dperror("Failed to open ntfs attribute");
217                 goto error_exit;
218         }
219         /* Set the number of mft records. */
220         vol->nr_mft_records = vol->mft_na->data_size >>
221                         vol->mft_record_size_bits;
222         /* Read all extents from the $DATA attribute in $MFT. */
223         ntfs_attr_reinit_search_ctx(ctx);
224         last_vcn = vol->mft_na->allocated_size >> vol->cluster_size_bits;
225         highest_vcn = next_vcn = 0;
226         a = NULL;
227         while (!ntfs_attr_lookup(AT_DATA, AT_UNNAMED, 0, 0, next_vcn, NULL, 0,
228                         ctx)) {
229                 runlist_element *nrl;
230
231                 a = ctx->attr;
232                 /* $MFT must be non-resident. */
233                 if (!a->non_resident) {
234                         Dputs("$MFT must be non-resident but a resident "
235                                         "extent was found. $MFT is corrupt. "
236                                         "Run chkdsk.");
237                         goto io_error_exit;
238                 }
239                 /* $MFT must be uncompressed and unencrypted. */
240                 if (a->flags & ATTR_COMPRESSION_MASK ||
241                                 a->flags & ATTR_IS_ENCRYPTED) {
242                         Dputs("$MFT must be uncompressed and unencrypted but "
243                                         "a compressed/encrypted extent was "
244                                         "found. $MFT is corrupt. Run chkdsk.");
245                         goto io_error_exit;
246                 }
247                 /*
248                  * Decompress the mapping pairs array of this extent and merge
249                  * the result into the existing runlist. No need for locking
250                  * as we have exclusive access to the inode at this time and we
251                  * are a mount in progress task, too.
252                  */
253                 nrl = ntfs_mapping_pairs_decompress(vol, a, vol->mft_na->rl);
254                 if (!nrl) {
255                         Dperror("ntfs_mapping_pairs_decompress() failed");
256                         goto error_exit;
257                 }
258                 vol->mft_na->rl = nrl;
259
260                 /* Get the lowest vcn for the next extent. */
261                 highest_vcn = sle64_to_cpu(a->highest_vcn);
262                 next_vcn = highest_vcn + 1;
263
264                 /* Only one extent or error, which we catch below. */
265                 if (next_vcn <= 0)
266                         break;
267
268                 /* Avoid endless loops due to corruption. */
269                 if (next_vcn < sle64_to_cpu(a->lowest_vcn)) {
270                         Dputs("$MFT has corrupt attribute list attribute. "
271                                         "Run chkdsk.");
272                         goto io_error_exit;
273                 }
274         }
275         if (!a) {
276                 Dputs("$MFT/$DATA attribute not found. $MFT is corrupt. "
277                                 "Run chkdsk.");
278                 goto io_error_exit;
279         }
280         if (highest_vcn && highest_vcn != last_vcn - 1) {
281                 Dputs("Failed to load the complete runlist for $MFT/$DATA. "
282                                 "Bug or corrupt $MFT. Run chkdsk.");
283                 Dprintf("highest_vcn = 0x%Lx, last_vcn - 1 = 0x%Lx\n",
284                                 (long long)highest_vcn,
285                                 (long long)last_vcn - 1);
286                 goto io_error_exit;
287         }
288         /* Done with the $Mft mft record. */
289         ntfs_attr_put_search_ctx(ctx);
290         ctx = NULL;
291         /*
292          * The volume is now setup so we can use all read access functions.
293          */
294         vol->mftbmp_na = ntfs_attr_open(vol->mft_ni, AT_BITMAP, AT_UNNAMED, 0);
295         if (!vol->mftbmp_na) {
296                 Dperror("Failed to open $MFT/$BITMAP");
297                 goto error_exit;
298         }
299         return 0;
300 io_error_exit:
301         errno = EIO;
302 error_exit:
303         eo = errno;
304         if (ctx)
305                 ntfs_attr_put_search_ctx(ctx);
306         if (vol->mft_na) {
307                 ntfs_attr_close(vol->mft_na);
308                 vol->mft_na = NULL;
309         }
310         if (vol->mft_ni) {
311                 ntfs_inode_close(vol->mft_ni);
312                 vol->mft_ni = NULL;
313         }
314         errno = eo;
315         return -1;
316 }
317
318 /**
319  * Internal:
320  *
321  * ntfs_mftmirr_load - load the $MFTMirr and setup the ntfs volume with it
322  * @vol:        ntfs volume whose $MFTMirr to load
323  *
324  * Load $MFTMirr from @vol and setup @vol with it. After calling this function
325  * the volume @vol is ready for use by all write access functions provided by
326  * the ntfs library (assuming ntfs_mft_load() has been called successfully
327  * beforehand).
328  *
329  * Return 0 on success and -1 on error with errno set to the error code.
330  */
331 static int ntfs_mftmirr_load(ntfs_volume *vol)
332 {
333         int i;
334         runlist_element rl[2];
335
336         vol->mftmirr_ni = ntfs_inode_open(vol, FILE_MFTMirr);
337         if (!vol->mftmirr_ni) {
338                 Dperror("Failed to open inode $MFTMirr");
339                 return -1;
340         }
341         /* Get an ntfs attribute for $MFTMirr/$DATA, too. */
342         vol->mftmirr_na = ntfs_attr_open(vol->mftmirr_ni, AT_DATA, AT_UNNAMED, 0);
343         if (!vol->mftmirr_na) {
344                 Dperror("Failed to open $MFTMirr/$DATA");
345                 goto error_exit;
346         }
347         if (ntfs_attr_map_runlist(vol->mftmirr_na, 0) < 0) {
348                 Dperror("Failed to map runlist of $MFTMirr/$DATA");
349                 goto error_exit;
350         }
351         /* Construct the mft mirror runlist. */
352         rl[0].vcn = 0;
353         rl[0].lcn = vol->mftmirr_lcn;
354         rl[0].length = (vol->mftmirr_size * vol->mft_record_size +
355                         vol->cluster_size - 1) / vol->cluster_size;
356         rl[1].vcn = rl[0].length;
357         rl[1].lcn = LCN_ENOENT;
358         rl[1].length = 0;
359         /* Compare the two runlists. They must be identical. */
360         i = 0;
361         do {
362                 if (rl[i].vcn != vol->mftmirr_na->rl[i].vcn ||
363                                 rl[i].lcn != vol->mftmirr_na->rl[i].lcn ||
364                                 rl[i].length != vol->mftmirr_na->rl[i].length) {
365                         Dputs("Error: $MFTMirr location mismatch! Run chkdsk.");
366                         errno = EIO;
367                         goto error_exit;
368                 }
369         } while (rl[i++].length);
370         return 0;
371 error_exit:
372         i = errno;
373         if (vol->mftmirr_na) {
374                 ntfs_attr_close(vol->mftmirr_na);
375                 vol->mftmirr_na = NULL;
376         }
377         ntfs_inode_close(vol->mftmirr_ni);
378         vol->mftmirr_ni = NULL;
379         errno = i;
380         return -1;
381 }
382
383 /**
384  * ntfs_volume_startup - allocate and setup an ntfs volume
385  * @dev:        device to open
386  * @rwflag:     optional mount flags
387  *
388  * Load, verify, and parse bootsector; load and setup $MFT and $MFTMirr. After
389  * calling this function, the volume is setup sufficiently to call all read
390  * and write access functions provided by the library.
391  *
392  * Return the allocated volume structure on success and NULL on error with
393  * errno set to the error code.
394  */
395 ntfs_volume *ntfs_volume_startup(struct ntfs_device *dev, unsigned long rwflag)
396 {
397         LCN mft_zone_size, mft_lcn;
398         s64 br;
399         const char *OK = "OK";
400         const char *FAILED = "FAILED";
401         ntfs_volume *vol;
402         NTFS_BOOT_SECTOR *bs;
403         int eo;
404 #ifdef DEBUG
405         BOOL debug = 1;
406 #else
407         BOOL debug = 0;
408 #endif
409
410         if (!dev || !dev->d_ops || !dev->d_name) {
411                 errno = EINVAL;
412                 return NULL;
413         }
414
415         /* Allocate the boot sector structure. */
416         if (!(bs = (NTFS_BOOT_SECTOR *)malloc(sizeof(NTFS_BOOT_SECTOR))))
417                 return NULL;
418         /* Allocate the volume structure. */
419         vol = ntfs_volume_alloc();
420         if (!vol)
421                 goto error_exit;
422         if ((rwflag & MS_RDONLY) == MS_RDONLY)
423                 NVolSetReadOnly(vol);
424         Dprintf("Reading bootsector... ");
425         if (dev->d_ops->open(dev, NVolReadOnly(vol) ? O_RDONLY: O_RDWR)) {
426                 Dputs(FAILED);
427                 Dperror("Error opening partition device");
428                 goto error_exit;
429         }
430         /* Attach the device to the volume. */
431         vol->dev = dev;
432         /* Now read the bootsector. */
433         br = ntfs_pread(dev, 0, sizeof(NTFS_BOOT_SECTOR), bs);
434         if (br != sizeof(NTFS_BOOT_SECTOR)) {
435                 Dputs(FAILED);
436                 if (br != -1)
437                         errno = EINVAL;
438                 if (!br)
439                         Dputs("Error: partition is smaller than bootsector "
440                                         "size. Weird!");
441                 else
442                         Dperror("Error reading bootsector");
443                 goto error_exit;
444         }
445         Dputs(OK);
446         if (!ntfs_boot_sector_is_ntfs(bs, !debug)) {
447                 Dprintf("Error: %s is not a valid NTFS partition!\n",
448                                 dev->d_name);
449                 errno = EINVAL;
450                 goto error_exit;
451         }
452         if (ntfs_boot_sector_parse(vol, bs) < 0) {
453                 Dperror("Failed to parse ntfs bootsector");
454                 goto error_exit;
455         }
456         free(bs);
457         bs = NULL;
458
459         /*
460          * We now initialize the cluster allocator.
461          *
462          * FIXME: Move this to its own function? (AIA)
463          */
464
465         // TODO: Make this tunable at mount time. (AIA)
466         vol->mft_zone_multiplier = 1;
467
468         /* Determine the size of the MFT zone. */
469         mft_zone_size = vol->nr_clusters;
470         switch (vol->mft_zone_multiplier) {  /* % of volume size in clusters */
471         case 4:
472                 mft_zone_size >>= 1;                    /* 50%   */
473                 break;
474         case 3:
475                 mft_zone_size = mft_zone_size * 3 >> 3; /* 37.5% */
476                 break;
477         case 2:
478                 mft_zone_size >>= 2;                    /* 25%   */
479                 break;
480         /* case 1: */
481         default:
482                 mft_zone_size >>= 3;                    /* 12.5% */
483                 break;
484         }
485
486         /* Setup the mft zone. */
487         vol->mft_zone_start = vol->mft_zone_pos = vol->mft_lcn;
488         Dprintf("mft_zone_pos = 0x%Lx\n", (long long)vol->mft_zone_pos);
489
490         /*
491          * Calculate the mft_lcn for an unmodified NTFS volume (see mkntfs
492          * source) and if the actual mft_lcn is in the expected place or even
493          * further to the front of the volume, extend the mft_zone to cover the
494          * beginning of the volume as well. This is in order to protect the
495          * area reserved for the mft bitmap as well within the mft_zone itself.
496          * On non-standard volumes we don't protect it as the overhead would be
497          * higher than the speed increase we would get by doing it.
498          */
499         mft_lcn = (8192 + 2 * vol->cluster_size - 1) / vol->cluster_size;
500         if (mft_lcn * vol->cluster_size < 16 * 1024)
501                 mft_lcn = (16 * 1024 + vol->cluster_size - 1) /
502                                 vol->cluster_size;
503         if (vol->mft_zone_start <= mft_lcn)
504                 vol->mft_zone_start = 0;
505         Dprintf("mft_zone_start = 0x%Lx\n", (long long)vol->mft_zone_start);
506
507         /*
508          * Need to cap the mft zone on non-standard volumes so that it does
509          * not point outside the boundaries of the volume. We do this by
510          * halving the zone size until we are inside the volume.
511          */
512         vol->mft_zone_end = vol->mft_lcn + mft_zone_size;
513         while (vol->mft_zone_end >= vol->nr_clusters) {
514                 mft_zone_size >>= 1;
515                 vol->mft_zone_end = vol->mft_lcn + mft_zone_size;
516         }
517         Dprintf("mft_zone_end = 0x%Lx\n", (long long)vol->mft_zone_end);
518
519         /*
520          * Set the current position within each data zone to the start of the
521          * respective zone.
522          */
523         vol->data1_zone_pos = vol->mft_zone_end;
524         Dprintf("data1_zone_pos = 0x%Lx\n", vol->data1_zone_pos);
525         vol->data2_zone_pos = 0;
526         Dprintf("data2_zone_pos = 0x%Lx\n", vol->data2_zone_pos);
527
528         /* Set the mft data allocation position to mft record 24. */
529         vol->mft_data_pos = 24;
530
531         /*
532          * The cluster allocator is now fully operational.
533          */
534
535         /* Need to setup $MFT so we can use the library read functions. */
536         Dprintf("Loading $MFT... ");
537         if (ntfs_mft_load(vol) < 0) {
538                 Dputs(FAILED);
539                 Dperror("Failed to load $MFT");
540                 goto error_exit;
541         }
542         Dputs(OK);
543
544         /* Need to setup $MFTMirr so we can use the write functions, too. */
545         Dprintf("Loading $MFTMirr... ");
546         if (ntfs_mftmirr_load(vol) < 0) {
547                 Dputs(FAILED);
548                 Dperror("Failed to load $MFTMirr");
549                 goto error_exit;
550         }
551         Dputs(OK);
552         return vol;
553 error_exit:
554         eo = errno;
555         free(bs);
556         if (vol)
557                 __ntfs_volume_release(vol);
558         errno = eo;
559         return NULL;
560 }
561
562 /**
563  * ntfs_device_mount - open ntfs volume
564  * @dev:        device to open
565  * @rwflag:     optional mount flags
566  *
567  * This function mounts an ntfs volume. @dev should describe the device which
568  * to mount as the ntfs volume.
569  *
570  * @rwflags is an optional second parameter. The same flags are used as for
571  * the mount system call (man 2 mount). Currently only the following flag
572  * is implemented:
573  *      MS_RDONLY       - mount volume read-only
574  *
575  * The function opens the device @dev and verifies that it contains a valid
576  * bootsector. Then, it allocates an ntfs_volume structure and initializes
577  * some of the values inside the structure from the information stored in the
578  * bootsector. It proceeds to load the necessary system files and completes
579  * setting up the structure.
580  *
581  * Return the allocated volume structure on success and NULL on error with
582  * errno set to the error code.
583  */
584 ntfs_volume *ntfs_device_mount(struct ntfs_device *dev, unsigned long rwflag)
585 {
586         s64 l;
587         const char *OK = "OK";
588         const char *FAILED = "FAILED";
589         ntfs_volume *vol;
590         u8 *m = NULL, *m2 = NULL;
591         ntfs_attr_search_ctx *ctx = NULL;
592         ntfs_inode *ni;
593         ntfs_attr *na;
594         ATTR_RECORD *a;
595         VOLUME_INFORMATION *vinf;
596         uchar_t *vname;
597         int i, j, eo;
598         u32 u;
599
600         vol = ntfs_volume_startup(dev, rwflag);
601         if (!vol) {
602                 Dperror("Failed to startup volume");
603                 return NULL;
604         }
605
606         /* Load data from $MFT and $MFTMirr and compare the contents. */
607         m = (u8*)malloc(vol->mftmirr_size << vol->mft_record_size_bits);
608         m2 = (u8*)malloc(vol->mftmirr_size << vol->mft_record_size_bits);
609         if (!m || !m2) {
610                 Dperror("Failed to allocate memory");
611                 goto error_exit;
612         }
613
614         l = ntfs_attr_mst_pread(vol->mft_na, 0, vol->mftmirr_size,
615                         vol->mft_record_size, m);
616         if (l != vol->mftmirr_size) {
617                 if (l == -1)
618                         Dperror("Failed to read $MFT");
619                 else {
620                         Dputs("Length of data not equal expected length.");
621                         errno = EIO;
622                 }
623                 goto error_exit;
624         }
625         l = ntfs_attr_mst_pread(vol->mftmirr_na, 0, vol->mftmirr_size,
626                         vol->mft_record_size, m2);
627         if (l != vol->mftmirr_size) {
628                 if (l == -1)
629                         Dperror("Failed to read $MFTMirr");
630                 else {
631                         Dputs("Length of data not equal expected length.");
632                         errno = EIO;
633                 }
634                 goto error_exit;
635         }
636         Dprintf("Comparing $MFTMirr to $MFT... ");
637         for (i = 0; i < vol->mftmirr_size; ++i) {
638                 const char *ESTR[12] = { "$MFT", "$MFTMirr", "$LogFile",
639                         "$Volume", "$AttrDef", "root directory", "$Bitmap",
640                         "$Boot", "$BadClus", "$Secure", "$UpCase", "$Extend" };
641                 const char *s;
642
643                 if (i < 12)
644                         s = ESTR[i];
645                 else if (i < 16)
646                         s = "system file";
647                 else
648                         s = "mft record";
649
650                 if (ntfs_is_baad_recordp(m + i * vol->mft_record_size)) {
651                         Dputs("FAILED");
652                         Dprintf("$MFT error: Incomplete multi sector transfer "
653                                         "detected in %s.\n", s);
654                         goto io_error_exit;
655                 }
656                 if (!ntfs_is_mft_recordp(m + i * vol->mft_record_size)) {
657                         Dputs("FAILED");
658                         Dprintf("$MFT error: Invalid mft record for %s.\n", s);
659                         goto io_error_exit;
660                 }
661                 if (ntfs_is_baad_recordp(m2 + i * vol->mft_record_size)) {
662                         Dputs("FAILED");
663                         Dprintf("$MFTMirr error: Incomplete multi sector "
664                                         "transfer detected in %s.\n", s);
665                         goto io_error_exit;
666                 }
667                 if (!ntfs_is_mft_recordp(m2 + i * vol->mft_record_size)) {
668                         Dputs("FAILED");
669                         Dprintf("$MFTMirr error: Invalid mft record for %s.\n",
670                                         s);
671                         goto io_error_exit;
672                 }
673                 if (memcmp((u8*)m + i * vol->mft_record_size, (u8*)m2 +
674                                 i * vol->mft_record_size,
675                                 ntfs_mft_record_get_data_size((MFT_RECORD*)(
676                                 (u8*)m + i * vol->mft_record_size)))) {
677                         Dputs(FAILED);
678                         Dputs("$MFTMirr does not match $MFT. Run chkdsk.");
679                         goto io_error_exit;
680                 }
681         }
682         Dputs(OK);
683
684         free(m2);
685         free(m);
686         m = m2 = NULL;
687
688         /* Now load the bitmap from $Bitmap. */
689         Dprintf("Loading $Bitmap... ");
690         vol->lcnbmp_ni = ntfs_inode_open(vol, FILE_Bitmap);
691         if (!vol->lcnbmp_ni) {
692                 Dputs(FAILED);
693                 Dperror("Failed to open inode");
694                 goto error_exit;
695         }
696         /* Get an ntfs attribute for $Bitmap/$DATA. */
697         vol->lcnbmp_na = ntfs_attr_open(vol->lcnbmp_ni, AT_DATA, AT_UNNAMED, 0);
698         if (!vol->lcnbmp_na) {
699                 Dputs(FAILED);
700                 Dperror("Failed to open ntfs attribute");
701                 goto error_exit;
702         }
703         /* Done with the $Bitmap mft record. */
704         Dputs(OK);
705
706         /* Now load the upcase table from $UpCase. */
707         Dprintf("Loading $UpCase... ");
708         ni = ntfs_inode_open(vol, FILE_UpCase);
709         if (!ni) {
710                 Dputs(FAILED);
711                 Dperror("Failed to open inode");
712                 goto error_exit;
713         }
714         /* Get an ntfs attribute for $UpCase/$DATA. */
715         na = ntfs_attr_open(ni, AT_DATA, AT_UNNAMED, 0);
716         if (!na) {
717                 Dputs(FAILED);
718                 Dperror("Failed to open ntfs attribute");
719                 goto error_exit;
720         }
721         /*
722          * Note: Normally, the upcase table has a length equal to 65536
723          * 2-byte Unicode characters but allow for different cases, so no
724          * checks done. Just check we don't overflow 32-bits worth of Unicode
725          * characters.
726          */
727         if (na->data_size & ~0x1ffffffffULL) {
728                 Dputs(FAILED);
729                 Dputs("Error: Upcase table is too big (max 32-bit allowed).");
730                 errno = EINVAL;
731                 goto error_exit;
732         }
733         vol->upcase_len = na->data_size >> 1;
734         vol->upcase = (uchar_t*)malloc(na->data_size);
735         if (!vol->upcase) {
736                 Dputs(FAILED);
737                 Dputs("Not enough memory to load $UpCase.");
738                 goto error_exit;
739         }
740         /* Read in the $DATA attribute value into the buffer. */
741         l = ntfs_attr_pread(na, 0, na->data_size, vol->upcase);
742         if (l != na->data_size) {
743                 Dputs(FAILED);
744                 Dputs("Amount of data read does not correspond to expected "
745                                 "length!");
746                 errno = EIO;
747                 goto error_exit;
748         }
749         /* Done with the $UpCase mft record. */
750         Dputs(OK);
751         ntfs_attr_close(na);
752         if (ntfs_inode_close(ni))
753                 Dperror("Failed to close inode, leaking memory");
754
755         /*
756          * Now load $Volume and set the version information and flags in the
757          * vol structure accordingly.
758          */
759         Dprintf("Loading $Volume... ");
760         ni = ntfs_inode_open(vol, FILE_Volume);
761         if (!ni) {
762                 Dputs(FAILED);
763                 Dperror("Failed to open inode");
764                 goto error_exit;
765         }
766         /* Get an ntfs attribute for $UpCase/$DATA. */
767         ctx = ntfs_attr_get_search_ctx(ni, NULL);
768         if (!ctx) {
769                 Dputs(FAILED);
770                 Dperror("Failed to allocate attribute search context");
771                 goto error_exit;
772         }
773         /* Find the $VOLUME_INFORMATION attribute. */
774         if (ntfs_attr_lookup(AT_VOLUME_INFORMATION, AT_UNNAMED, 0, 0, 0, NULL,
775                         0, ctx)) {
776                 Dputs(FAILED);
777                 Dputs("$VOLUME_INFORMATION attribute not found in "
778                                 "$Volume?!?");
779                 goto error_exit;
780         }
781         a = ctx->attr;
782         /* Has to be resident. */
783         if (a->non_resident) {
784                 Dputs(FAILED);
785                 Dputs("Error: Attribute $VOLUME_INFORMATION must be resident "
786                                 "(and it isn't)!");
787                 errno = EIO;
788                 goto error_exit;
789         }
790         /* Get a pointer to the value of the attribute. */
791         vinf = (VOLUME_INFORMATION*)(le16_to_cpu(a->value_offset) + (char*)a);
792         /* Sanity checks. */
793         if ((char*)vinf + le32_to_cpu(a->value_length) > (char*)ctx->mrec +
794                         le16_to_cpu(ctx->mrec->bytes_in_use) ||
795                         le16_to_cpu(a->value_offset) + le32_to_cpu(
796                         a->value_length) > le32_to_cpu(a->length)) {
797                 Dputs(FAILED);
798                 Dputs("Error: Attribute $VOLUME_INFORMATION in $Volume is "
799                                 "corrupt!");
800                 errno = EIO;
801                 goto error_exit;
802         }
803         /* Setup vol from the volume information attribute value. */
804         vol->major_ver = vinf->major_ver;
805         vol->minor_ver = vinf->minor_ver;
806         /* Do not use le16_to_cpu() macro here as our VOLUME_FLAGS are
807            defined using cpu_to_le16() macro and hence are consistent. */
808         vol->flags = vinf->flags;
809         /* Find the $VOLUME_NAME attribute. */
810         ntfs_attr_reinit_search_ctx(ctx);
811         if (ntfs_attr_lookup(AT_VOLUME_NAME, AT_UNNAMED, 0, 0, 0, NULL, 0,
812                         ctx)) {
813                 Dputs(FAILED);
814                 Dputs("$VOLUME_NAME attribute not found in $Volume?!?");
815                 goto error_exit;
816         }
817         a = ctx->attr;
818         /* Has to be resident. */
819         if (a->non_resident) {
820                 Dputs(FAILED);
821                 Dputs("Error: Attribute $VOLUME_NAME must be resident!");
822                 errno = EIO;
823                 goto error_exit;
824         }
825         /* Get a pointer to the value of the attribute. */
826         vname = (uchar_t*)(le16_to_cpu(a->value_offset) + (char*)a);
827         u = le32_to_cpu(a->value_length) / 2;
828         /* Convert Unicode volume name to current locale multibyte format. */
829         vol->vol_name = NULL;
830         if (ntfs_ucstombs(vname, u, &vol->vol_name, 0) == -1) {
831                 Dperror("Error: Volume name could not be converted to "
832                                 "current locale");
833                 Dputs("Forcing name into ASCII by replacing non-ASCII "
834                                 "characters with underscores.");
835                 vol->vol_name = malloc(u + 1);
836                 if (!vol->vol_name) {
837                         Dputs(FAILED);
838                         Dputs("Error: Unable to allocate memory for volume "
839                                         "name!");
840                         goto error_exit;
841                 }
842                 for (j = 0; j < u; j++) {
843                         uchar_t uc = le16_to_cpu(vname[j]);
844                         if (uc > 0xff)
845                                 uc = (uchar_t)'_';
846                         vol->vol_name[j] = (char)uc;
847                 }
848                 vol->vol_name[u] = '\0';
849         }
850         Dputs(OK);
851         ntfs_attr_put_search_ctx(ctx);
852         ctx = NULL;
853         if (ntfs_inode_close(ni))
854                 Dperror("Failed to close inode, leaking memory");
855
856         /* Now load the attribute definitions from $AttrDef. */
857         Dprintf("Loading $AttrDef... ");
858         ni = ntfs_inode_open(vol, FILE_AttrDef);
859         if (!ni) {
860                 Dputs(FAILED);
861                 Dperror("Failed to open inode");
862                 goto error_exit;
863         }
864         /* Get an ntfs attribute for $AttrDef/$DATA. */
865         na = ntfs_attr_open(ni, AT_DATA, AT_UNNAMED, 0);
866         if (!na) {
867                 Dputs(FAILED);
868                 Dperror("Failed to open ntfs attribute");
869                 goto error_exit;
870         }
871         /* Check we don't overflow 32-bits. */
872         if (na->data_size > 0xffffffffLL) {
873                 Dputs(FAILED);
874                 Dputs("Error: Attribute definition table is too big "
875                                 "(max 32-bit allowed).");
876                 errno = EINVAL;
877                 goto error_exit;
878         }
879         vol->attrdef_len = na->data_size;
880         vol->attrdef = (ATTR_DEF*)malloc(na->data_size);
881         if (!vol->attrdef) {
882                 Dputs(FAILED);
883                 Dputs("Not enough memory to load $AttrDef.");
884                 goto error_exit;
885         }
886         /* Read in the $DATA attribute value into the buffer. */
887         l = ntfs_attr_pread(na, 0, na->data_size, vol->attrdef);
888         if (l != na->data_size) {
889                 Dputs(FAILED);
890                 Dputs("Amount of data read does not correspond to expected "
891                                 "length!");
892                 errno = EIO;
893                 goto error_exit;
894         }
895         /* Done with the $AttrDef mft record. */
896         Dputs(OK);
897         ntfs_attr_close(na);
898         if (ntfs_inode_close(ni))
899                 Dperror("Failed to close inode, leaking memory");
900
901         return vol;
902 io_error_exit:
903         errno = EIO;
904 error_exit:
905         eo = errno;
906         if (ctx)
907                 ntfs_attr_put_search_ctx(ctx);
908         if (m)
909                 free(m);
910         if (m2)
911                 free(m2);
912         __ntfs_volume_release(vol);
913         errno = eo;
914         return NULL;
915 }
916
917 /**
918  * ntfs_mount - open ntfs volume
919  * @name:       name of device/file to open
920  * @rwflag:     optional mount flags
921  *
922  * This function mounts an ntfs volume. @name should contain the name of the
923  * device/file to mount as the ntfs volume.
924  *
925  * @rwflags is an optional second parameter. The same flags are used as for
926  * the mount system call (man 2 mount). Currently only the following flag
927  * is implemented:
928  *      MS_RDONLY       - mount volume read-only
929  *
930  * The function opens the device or file @name and verifies that it contains a
931  * valid bootsector. Then, it allocates an ntfs_volume structure and initializes
932  * some of the values inside the structure from the information stored in the
933  * bootsector. It proceeds to load the necessary system files and completes
934  * setting up the structure.
935  *
936  * Return the allocated volume structure on success and NULL on error with
937  * errno set to the error code.
938  *
939  * Note, that a copy is made of @name, and hence it can be discarded as
940  * soon as the function returns.
941  */
942 ntfs_volume *ntfs_mount(const char *name, unsigned long rwflag)
943 {
944         struct ntfs_device *dev;
945
946         /* Allocate an ntfs_device structure. */
947         dev = ntfs_device_alloc(name, 0, &ntfs_device_disk_io_ops, NULL);
948         if (!dev)
949                 return NULL;
950         /* Call ntfs_device_mount() to do the actual mount. */
951         return ntfs_device_mount(dev, rwflag);
952 }
953
954 /**
955  * ntfs_device_umount - close ntfs volume
956  * @vol: address of ntfs_volume structure of volume to close
957  * @force: if true force close the volume even if it is busy
958  *
959  * Deallocate all structures (including @vol itself) associated with the ntfs
960  * volume @vol.
961  *
962  * Note it is up to the caller to destroy the device associated with the volume
963  * being unmounted after this function returns.
964  *
965  * Return 0 on success. On error return -1 with errno set appropriately
966  * (most likely to one of EAGAIN, EBUSY or EINVAL). The EAGAIN error means that
967  * an operation is in progress and if you try the close later the operation
968  * might be completed and the close succeed.
969  *
970  * If @force is true (i.e. not zero) this function will close the volume even
971  * if this means that data might be lost.
972  *
973  * @vol must have previously been returned by a call to ntfs_device_mount().
974  *
975  * @vol itself is deallocated and should no longer be dereferenced after this
976  * function returns success. If it returns an error then nothing has been done
977  * so it is safe to continue using @vol.
978  */
979 int ntfs_device_umount(ntfs_volume *vol, const BOOL force)
980 {
981         if (!vol) {
982                 errno = EINVAL;
983                 return -1;
984         }
985         __ntfs_volume_release(vol);
986         return 0;
987 }
988
989 /**
990  * ntfs_umount - close ntfs volume
991  * @vol: address of ntfs_volume structure of volume to close
992  * @force: if true force close the volume even if it is busy
993  *
994  * Deallocate all structures (including @vol itself) associated with the ntfs
995  * volume @vol.
996  *
997  * Return 0 on success. On error return -1 with errno set appropriately
998  * (most likely to one of EAGAIN, EBUSY or EINVAL). The EAGAIN error means that
999  * an operation is in progress and if you try the close later the operation
1000  * might be completed and the close succeed.
1001  *
1002  * If @force is true (i.e. not zero) this function will close the volume even
1003  * if this means that data might be lost.
1004  *
1005  * @vol must have previously been returned by a call to ntfs_mount().
1006  *
1007  * @vol itself is deallocated and should no longer be dereferenced after this
1008  * function returns success. If it returns an error then nothing has been done
1009  * so it is safe to continue using @vol.
1010  */
1011 int ntfs_umount(ntfs_volume *vol, const BOOL force)
1012 {
1013         struct ntfs_device *dev;
1014
1015         if (!vol) {
1016                 errno = EINVAL;
1017                 return -1;
1018         }
1019         dev = vol->dev;
1020         __ntfs_volume_release(vol);
1021         ntfs_device_free(dev);
1022         return 0;
1023 }
1024
1025 #ifdef HAVE_MNTENT_H
1026 /**
1027  * Internal:
1028  *
1029  * ntfs_mntent_check - desc
1030  *
1031  * If you are wanting to use this, you actually wanted to use
1032  * ntfs_check_if_mounted(), you just didn't realize. (-:
1033  *
1034  * See description of ntfs_check_if_mounted(), below.
1035  */
1036 static int ntfs_mntent_check(const char *file, unsigned long *mnt_flags)
1037 {
1038         struct mntent *mnt;
1039         FILE *f;
1040
1041         if (!(f = setmntent(MOUNTED, "r")))
1042                 return -1;
1043         while ((mnt = getmntent(f)))
1044                 if (!strcmp(file, mnt->mnt_fsname))
1045                         break;
1046         endmntent(f);
1047         if (!mnt)
1048                 return 0;
1049         *mnt_flags = NTFS_MF_MOUNTED;
1050         if (!strcmp(mnt->mnt_dir, "/"))
1051                 *mnt_flags |= NTFS_MF_ISROOT;
1052 #ifdef HAVE_HASMNTOPT
1053         if (hasmntopt(mnt, "ro") && !hasmntopt(mnt, "rw"))
1054                 *mnt_flags |= NTFS_MF_READONLY;
1055 #endif
1056         return 0;
1057 }
1058 #endif /* HAVE_MNTENT_H */
1059
1060 /**
1061  * ntfs_check_if_mounted - check if an ntfs volume is currently mounted
1062  * @file:       device file to check
1063  * @mnt_flags:  pointer into which to return the ntfs mount flags (see volume.h)
1064  *
1065  * If the running system does not support the {set,get,end}mntent() calls,
1066  * just return 0 and set *@mnt_flags to zero.
1067  *
1068  * When the system does support the calls, ntfs_check_if_mounted() first tries
1069  * to find the device @file in /etc/mtab (or wherever this is kept on the
1070  * running system). If it is not found, assume the device is not mounted and
1071  * return 0 and set *@mnt_flags to zero.
1072  *
1073  * If the device @file is found, set the NTFS_MF_MOUNTED flags in *@mnt_flags.
1074  *
1075  * Further if @file is mounted as the file system root ("/"), set the flag
1076  * NTFS_MF_ISROOT in *@mnt_flags.
1077  *
1078  * Finally, check if the file system is mounted read-only, and if so set the
1079  * NTFS_MF_READONLY flag in *@mnt_flags.
1080  *
1081  * On sucess return 0 with *@mnt_flags set to the ntfs mount flags.
1082  *
1083  * On error return -1 with errno set to the error code.
1084  */
1085 int ntfs_check_if_mounted(const char *file, unsigned long *mnt_flags)
1086 {
1087         *mnt_flags = 0;
1088 #ifdef HAVE_MNTENT_H
1089         return ntfs_mntent_check(file, mnt_flags);
1090 #else
1091         return 0;
1092 #endif
1093 }
1094
1095 /**
1096  * ntfs_version_is_supported - check if NTFS version is supported.
1097  * @vol:        ntfs volume whose version we're interested in.
1098  *
1099  * The function checks if the NTFS volume version is known or not.
1100  * Version 1.1 and 1.2 are used by Windows NT4.
1101  * Version 2.x is used by Windows 2000 Beta's
1102  * Version 3.0 is used by Windows 2000.
1103  * Version 3.1 is used by Windows XP and .NET.
1104  *
1105  * Return 0 if NTFS version is supported otherwise -1 with errno set.
1106  *
1107  * The following error codes are defined:
1108  *      ENOTSUP   Unknown NTFS versions
1109  *      EINVAL    Invalid argument
1110  */
1111 int ntfs_version_is_supported(ntfs_volume *vol)
1112 {
1113         u8 major, minor;
1114
1115         if (!vol) {
1116                 errno = EINVAL;
1117                 return -1;
1118         }
1119
1120         major = vol->major_ver;
1121         minor = vol->minor_ver;
1122
1123         if (NTFS_V1_1(major, minor) || NTFS_V1_2(major, minor))
1124                 return 0;
1125
1126         if (NTFS_V2_X(major, minor))
1127                 return 0;
1128
1129         if (NTFS_V3_0(major, minor) || NTFS_V3_1(major, minor))
1130                 return 0;
1131
1132         errno = ENOTSUP;
1133         return -1;
1134 }
1135
1136 /**
1137  * ntfs_logfile_reset - "empty" $LogFile data attribute value
1138  * @vol:        ntfs volume whose $LogFile we intend to reset.
1139  *
1140  * Fill the value of the $LogFile data attribute, i.e. the contents of
1141  * the file, with 0xff's, thus marking the journal as empty.
1142  *
1143  * FIXME(?): We might need to zero the LSN field of every single mft
1144  * record as well. (But, first try without doing that and see what
1145  * happens, since chkdsk might pickup the pieces and do it for us...)
1146  *
1147  * On success return 0.
1148  *
1149  * On error return -1 with errno set to the error code.
1150  */
1151 int ntfs_logfile_reset(ntfs_volume *vol)
1152 {
1153         ntfs_inode *ni;
1154         ntfs_attr *na;
1155         s64 len, pos, count;
1156         char buf[NTFS_BUF_SIZE];
1157         int eo;
1158
1159         if (!vol) {
1160                 errno = EINVAL;
1161                 return -1;
1162         }
1163
1164         if ((ni = ntfs_inode_open(vol, FILE_LogFile)) == NULL) {
1165                 Dperror("Failed to open inode FILE_LogFile.\n");
1166                 return -1;
1167         }
1168
1169         if ((na = ntfs_attr_open(ni, AT_DATA, AT_UNNAMED, 0)) == NULL) {
1170                 Dperror("Failed to open $FILE_LogFile/$DATA\n");
1171                 goto error_exit;
1172         }
1173
1174         /* The $DATA attribute of the $LogFile has to be non-resident. */
1175         if (!NAttrNonResident(na)) {
1176                 Dprintf("$LogFile $DATA attribute is resident!?!\n");
1177                 errno = EIO;
1178                 goto io_error_exit;
1179         }
1180
1181         /* Get length of $LogFile contents. */
1182         len = na->data_size;
1183         if (!len) {
1184                 Dprintf("$LogFile has zero length, no disk write needed.\n");
1185                 return 0;
1186         }
1187
1188         /* Read $LogFile until its end. We do this as a check for correct
1189            length thus making sure we are decompressing the mapping pairs
1190            array correctly and hence writing below is safe as well. */
1191         pos = 0;
1192         while ((count = ntfs_attr_pread(na, pos, NTFS_BUF_SIZE, buf)) > 0)
1193                 pos += count;
1194
1195         if (count == -1 || pos != len) {
1196                 Dprintf("Amount of $LogFile data read does not "
1197                         "correspond to expected length!");
1198                 if (count != -1)
1199                         errno = EIO;
1200                 goto io_error_exit;
1201         }
1202
1203         /* Fill the buffer with 0xff's. */
1204         memset(buf, -1, NTFS_BUF_SIZE);
1205
1206         /* Set the $DATA attribute. */
1207         pos = 0;
1208         while ((count = len - pos) > 0) {
1209                 if (count > NTFS_BUF_SIZE)
1210                         count = NTFS_BUF_SIZE;
1211
1212                 if ((count = ntfs_attr_pwrite(na, pos, count, buf)) <= 0) {
1213                         Dprintf("Failed to set the $LogFile attribute value.");
1214                         if (count != -1)
1215                                 errno = EIO;
1216                         goto io_error_exit;
1217                 }
1218                 pos += count;
1219         }
1220
1221         ntfs_attr_close(na);
1222         return ntfs_inode_close(ni);
1223
1224 io_error_exit:
1225         eo = errno;
1226         ntfs_attr_close(na);
1227         errno = eo;
1228 error_exit:
1229         eo = errno;
1230         ntfs_inode_close(ni);
1231         errno = eo;
1232         return -1;
1233 }
1234
1235 /**
1236  * ntfs_volume_set_flags - set the flags of an ntfs volume
1237  * @vol:        ntfs volume where we set the volume flags
1238  * @flags:      new flags
1239  *
1240  * Set the on-disk volume flags in the mft record of $Volume and
1241  * on volume @vol to @flags.
1242  *
1243  * Return 0 if successful and -1 if not with errno set to the error code.
1244  */
1245 int ntfs_volume_set_flags(ntfs_volume *vol, const u16 flags)
1246 {
1247         MFT_RECORD *m = NULL;
1248         ATTR_RECORD *r;
1249         VOLUME_INFORMATION *c;
1250         ntfs_attr_search_ctx *ctx;
1251         int ret = -1;   /* failure */
1252
1253         if (!vol) {
1254                 errno = EINVAL;
1255                 return -1;
1256         }
1257
1258         if (ntfs_file_record_read(vol, FILE_Volume, &m, NULL)) {
1259                 Dperror("Failed to read $Volume");
1260                 return -1;
1261         }
1262
1263         /* Sanity check */
1264         if (!(m->flags & MFT_RECORD_IN_USE)) {
1265                 Dprintf("Error: $Volume has been deleted. Cannot "
1266                         "handle this yet. Run chkdsk to fix this.\n");
1267                 errno = EIO;
1268                 goto err_exit;
1269         }
1270
1271         /* Get a pointer to the volume information attribute. */
1272         ctx = ntfs_attr_get_search_ctx(NULL, m);
1273         if (!ctx) {
1274                 Dperror("Failed to allocate attribute search context");
1275                 goto err_exit;
1276         }
1277         if (ntfs_attr_lookup(AT_VOLUME_INFORMATION, AT_UNNAMED, 0, 0, 0, NULL,
1278                         0, ctx)) {
1279                 Dputs("Error: Attribute $VOLUME_INFORMATION was not found in "
1280                                 "$Volume!");
1281                 goto err_out;
1282         }
1283         r = ctx->attr;
1284         /* Sanity check. */
1285         if (r->non_resident) {
1286                 Dputs("Error: Attribute $VOLUME_INFORMATION must be resident "
1287                                 "(and it isn't)!");
1288                 errno = EIO;
1289                 goto err_out;
1290         }
1291         /* Get a pointer to the value of the attribute. */
1292         c = (VOLUME_INFORMATION*)(le16_to_cpu(r->value_offset) + (char*)r);
1293         /* Sanity checks. */
1294         if ((char*)c + le32_to_cpu(r->value_length) >
1295                         le16_to_cpu(m->bytes_in_use) + (char*)m ||
1296                         le16_to_cpu(r->value_offset) +
1297                         le32_to_cpu(r->value_length) > le32_to_cpu(r->length)) {
1298                 Dputs("Error: Attribute $VOLUME_INFORMATION in $Volume is "
1299                                 "corrupt!");
1300                 errno = EIO;
1301                 goto err_out;
1302         }
1303         /* Set the volume flags. */
1304         vol->flags = c->flags = cpu_to_le16(flags);
1305
1306         if (ntfs_mft_record_write(vol, FILE_Volume, m)) {
1307                 Dperror("Error writing $Volume");
1308                 goto err_out;
1309         }
1310
1311         ret = 0; /* success */
1312 err_out:
1313         ntfs_attr_put_search_ctx(ctx);
1314 err_exit:
1315         if (m)
1316                 free(m);
1317         return ret;
1318 }
1319