summaryrefslogtreecommitdiff
path: root/core/fs/ntfs/ntfs.c
blob: 500d0fd3290be1fbe855e66404d4c6f90c9a53f3 (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
/*
 * Copyright (C) 2011-2012 Paulo Alcantara <pcacjr@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the
 * Free Software Foundation, Inc.,
 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/

/* Note: No support for compressed files */

#include <dprintf.h>
#include <stdio.h>
#include <string.h>
#include <sys/dirent.h>
#include <cache.h>
#include <core.h>
#include <disk.h>
#include <fs.h>
#include <ilog2.h>
#include <klibc/compiler.h>
#include <ctype.h>

#include "codepage.h"
#include "ntfs.h"
#include "runlist.h"

static struct ntfs_readdir_state *readdir_state;

/*** Function declarations */
static f_mft_record_lookup ntfs_mft_record_lookup_3_0;
static f_mft_record_lookup ntfs_mft_record_lookup_3_1;

/*** Function definitions */

/* Check if there are specific zero fields in an NTFS boot sector */
static inline int ntfs_check_zero_fields(const struct ntfs_bpb *sb)
{
    return !sb->res_sectors && (!sb->zero_0[0] && !sb->zero_0[1] &&
            !sb->zero_0[2]) && !sb->zero_1 && !sb->zero_2 &&
            !sb->zero_3;
}

static inline int ntfs_check_sb_fields(const struct ntfs_bpb *sb)
{
    return ntfs_check_zero_fields(sb) &&
            (!memcmp(sb->oem_name, "NTFS    ", 8) ||
             !memcmp(sb->oem_name, "MSWIN4.0", 8) ||
             !memcmp(sb->oem_name, "MSWIN4.1", 8));
}

static inline struct inode *new_ntfs_inode(struct fs_info *fs)
{
    struct inode *inode;

    inode = alloc_inode(fs, 0, sizeof(struct ntfs_inode));
    if (!inode)
        malloc_error("inode structure");

    return inode;
}

static void ntfs_fixups_writeback(struct fs_info *fs, struct ntfs_record *nrec)
{
    uint16_t *usa;
    uint16_t usa_no;
    uint16_t usa_count;
    uint16_t *blk;

    dprintf("in %s()\n", __func__);

    if (nrec->magic != NTFS_MAGIC_FILE && nrec->magic != NTFS_MAGIC_INDX)
        return;

    /* get the Update Sequence Array offset */
    usa = (uint16_t *)((uint8_t *)nrec + nrec->usa_ofs);
    /* get the Update Sequence Array Number and skip it */
    usa_no = *usa++;
    /* get the Update Sequene Array count */
    usa_count = nrec->usa_count - 1;    /* exclude the USA number */
    /* make it to point to the last two bytes of the RECORD's first sector */
    blk = (uint16_t *)((uint8_t *)nrec + SECTOR_SIZE(fs) - 2);

    while (usa_count--) {
        if (*blk != usa_no)
            break;

        *blk = *usa++;
        blk = (uint16_t *)((uint8_t *)blk + SECTOR_SIZE(fs));
    }
}

/* read content from cache */
static int ntfs_read(struct fs_info *fs, void *buf, size_t len, uint64_t count,
                    block_t *blk, uint64_t *blk_offset,
                    uint64_t *blk_next_offset, uint64_t *lcn)
{
    uint8_t *data;
    uint64_t offset = *blk_offset;
    const uint32_t clust_byte_shift = NTFS_SB(fs)->clust_byte_shift;
    const uint64_t blk_size = UINT64_C(1) << BLOCK_SHIFT(fs);
    uint64_t bytes;
    uint64_t lbytes;
    uint64_t loffset;
    uint64_t k;

    dprintf("in %s()\n", __func__);

    if (count > len)
        goto out;

    data = (uint8_t *)get_cache(fs->fs_dev, *blk);
    if (!data)
        goto out;

    if (!offset)
        offset = (*lcn << clust_byte_shift) % blk_size;

    dprintf("LCN:            0x%X\n", *lcn);
    dprintf("offset:         0x%X\n", offset);

    bytes = count;              /* bytes to copy */
    lbytes = blk_size - offset; /* bytes left to copy */
    if (lbytes >= bytes) {
        /* so there's room enough, then copy the whole content */
        memcpy(buf, data + offset, bytes);
        loffset = offset;
        offset += count;
    } else {
        dprintf("bytes:             %u\n", bytes);
        dprintf("bytes left:        %u\n", lbytes);
        /* otherwise, let's copy it partially... */
        k = 0;
        while (bytes) {
            memcpy(buf + k, data + offset, lbytes);
            bytes -= lbytes;
            loffset = offset;
            offset += lbytes;
            k += lbytes;
            if (offset >= blk_size) {
                /* then fetch a new FS block */
                data = (uint8_t *)get_cache(fs->fs_dev, ++*blk);
                if (!data)
                    goto out;

                lbytes = bytes;
                loffset = offset;
                offset = 0;
            }
        }
    }

    if (loffset >= blk_size)
        loffset = 0;    /* it must be aligned on a block boundary */

    *blk_offset = loffset;

    if (blk_next_offset)
        *blk_next_offset = offset;

    *lcn += blk_size / count;   /* update LCN */

    return 0;

out:
    return -1;
}

static struct ntfs_mft_record *ntfs_mft_record_lookup_3_0(struct fs_info *fs,
                                                uint32_t file, block_t *blk)
{
    const uint64_t mft_record_size = NTFS_SB(fs)->mft_record_size;
    uint8_t *buf;
    const block_t mft_blk = NTFS_SB(fs)->mft_blk;
    block_t cur_blk;
    block_t right_blk;
    uint64_t offset;
    uint64_t next_offset;
    const uint32_t mft_record_shift = ilog2(mft_record_size);
    const uint32_t clust_byte_shift = NTFS_SB(fs)->clust_byte_shift;
    uint64_t lcn;
    int err;
    struct ntfs_mft_record *mrec;

    dprintf("in %s()\n", __func__);

    buf = (uint8_t *)malloc(mft_record_size);
    if (!buf)
        malloc_error("uint8_t *");

    /* determine MFT record's LCN and block number */
    lcn = NTFS_SB(fs)->mft_lcn + (file << mft_record_shift >> clust_byte_shift);
    cur_blk = (lcn << clust_byte_shift >> BLOCK_SHIFT(fs)) - mft_blk;
    offset = (file << mft_record_shift) % BLOCK_SIZE(fs);
    for (;;) {
        right_blk = cur_blk + mft_blk;
        err = ntfs_read(fs, buf, mft_record_size, mft_record_size, &right_blk,
                        &offset, &next_offset, &lcn);
        if (err) {
            printf("Error while reading from cache.\n");
            break;
        }

        ntfs_fixups_writeback(fs, (struct ntfs_record *)buf);

        mrec = (struct ntfs_mft_record *)buf;
        /* check if it has a valid magic number */
        if (mrec->magic == NTFS_MAGIC_FILE) {
            if (blk)
                *blk = cur_blk;     /* update record starting block */

            return mrec;            /* found MFT record */
        }

        if (next_offset >= BLOCK_SIZE(fs)) {
            /* try the next FS block */
            offset = 0;
            cur_blk = right_blk - mft_blk + 1;
        } else {
            /* there's still content to fetch in the current block */
            cur_blk = right_blk - mft_blk;
            offset = next_offset;   /* update FS block offset */
        }
    }

    free(buf);

    return NULL;
}

static struct ntfs_mft_record *ntfs_mft_record_lookup_3_1(struct fs_info *fs,
                                                uint32_t file, block_t *blk)
{
    const uint64_t mft_record_size = NTFS_SB(fs)->mft_record_size;
    uint8_t *buf;
    const block_t mft_blk = NTFS_SB(fs)->mft_blk;
    block_t cur_blk;
    block_t right_blk;
    uint64_t offset;
    uint64_t next_offset;
    const uint32_t mft_record_shift = ilog2(mft_record_size);
    const uint32_t clust_byte_shift = NTFS_SB(fs)->clust_byte_shift;
    uint64_t lcn;
    int err;
    struct ntfs_mft_record *mrec;

    dprintf("in %s()\n", __func__);

    buf = (uint8_t *)malloc(mft_record_size);
    if (!buf)
        malloc_error("uint8_t *");

    lcn = NTFS_SB(fs)->mft_lcn + (file << mft_record_shift >> clust_byte_shift);
    cur_blk = (lcn << clust_byte_shift >> BLOCK_SHIFT(fs)) - mft_blk;
    offset = (file << mft_record_shift) % BLOCK_SIZE(fs);
    for (;;) {
        right_blk = cur_blk + NTFS_SB(fs)->mft_blk;
        err = ntfs_read(fs, buf, mft_record_size, mft_record_size, &right_blk,
                        &offset, &next_offset, &lcn);
        if (err) {
            printf("Error while reading from cache.\n");
            break;
        }

        ntfs_fixups_writeback(fs, (struct ntfs_record *)buf);

        mrec = (struct ntfs_mft_record *)buf;
        /* Check if the NTFS 3.1 MFT record number matches */
        if (mrec->magic == NTFS_MAGIC_FILE && mrec->mft_record_no == file) {
            if (blk)
                *blk = cur_blk;     /* update record starting block */

            return mrec;            /* found MFT record */
        }

        if (next_offset >= BLOCK_SIZE(fs)) {
            /* try the next FS block */
            offset = 0;
            cur_blk = right_blk - NTFS_SB(fs)->mft_blk + 1;
        } else {
            /* there's still content to fetch in the current block */
            cur_blk = right_blk - NTFS_SB(fs)->mft_blk;
            offset = next_offset;   /* update FS block offset */
        }
    }

    free(buf);

    return NULL;
}

static bool ntfs_filename_cmp(const char *dname, struct ntfs_idx_entry *ie)
{
    const uint16_t *entry_fn;
    uint8_t entry_fn_len;
    unsigned i;

    dprintf("in %s()\n", __func__);

    entry_fn = ie->key.file_name.file_name;
    entry_fn_len = ie->key.file_name.file_name_len;

    if (strlen(dname) != entry_fn_len)
        return false;

    /* Do case-sensitive compares for Posix file names */
    if (ie->key.file_name.file_name_type == FILE_NAME_POSIX) {
        for (i = 0; i < entry_fn_len; i++)
            if (entry_fn[i] != dname[i])
                return false;
    } else {
        for (i = 0; i < entry_fn_len; i++)
            if (tolower(entry_fn[i]) != tolower(dname[i]))
                return false;
    }

    return true;
}

static inline uint8_t *mapping_chunk_init(struct ntfs_attr_record *attr,
                                        struct mapping_chunk *chunk,
                                        uint32_t *offset)
{
    memset(chunk, 0, sizeof *chunk);
    *offset = 0U;

    return (uint8_t *)attr + attr->data.non_resident.mapping_pairs_offset;
}

/* Parse data runs.
 *
 * return 0 on success or -1 on failure.
 */
static int parse_data_run(const void *stream, uint32_t *offset,
                            uint8_t *attr_len, struct mapping_chunk *chunk)
{
    uint8_t *buf;   /* Pointer to the zero-terminated byte stream */
    uint8_t count;  /* The count byte */
    uint8_t v, l;   /* v is the number of changed low-order VCN bytes;
                     * l is the number of changed low-order LCN bytes
                     */
    uint8_t *byte;
    int byte_shift = 8;
    int mask;
    uint8_t val;
    int64_t res;

    (void)attr_len;

    dprintf("in %s()\n", __func__);

    chunk->flags &= ~MAP_MASK;

    buf = (uint8_t *)stream + *offset;
    if (buf > attr_len || !*buf) {
        chunk->flags |= MAP_END;    /* we're done */
        return 0;
    }

    if (!*offset)
        chunk->flags |= MAP_START;  /* initial chunk */

    count = *buf;
    v = count & 0x0F;
    l = count >> 4;

    if (v > 8 || l > 8) /* more than 8 bytes ? */
        goto out;

    byte = (uint8_t *)buf + v;
    count = v;

    res = 0LL;
    while (count--) {
        val = *byte--;
        mask = val >> (byte_shift - 1);
        res = (res << byte_shift) | ((val + mask) ^ mask);
    }

    chunk->len = res;   /* get length data */

    byte = (uint8_t *)buf + v + l;
    count = l;

    mask = 0xFFFFFFFF;
    res = 0LL;
    if (*byte & 0x80)
        res |= (int64_t)mask;   /* sign-extend it */

    while (count--)
        res = (res << byte_shift) | *byte--;

    chunk->lcn += res;
    /* are VCNS from cur_vcn to next_vcn - 1 unallocated ? */
    if (!chunk->lcn)
        chunk->flags |= MAP_UNALLOCATED;
    else
        chunk->flags |= MAP_ALLOCATED;

    *offset += v + l + 1;

    return 0;

out:
    return -1;
}

static struct ntfs_mft_record *
ntfs_attr_list_lookup(struct fs_info *fs, struct ntfs_attr_record *attr,
                      uint32_t type, struct ntfs_mft_record *mrec)
{
    uint8_t *attr_len;
    struct mapping_chunk chunk;
    uint32_t offset;
    uint8_t *stream;
    int err;
    const uint64_t blk_size = UINT64_C(1) << BLOCK_SHIFT(fs);
    uint8_t buf[blk_size];
    uint64_t blk_offset;
    int64_t vcn;
    int64_t lcn;
    int64_t last_lcn;
    block_t blk;
    struct ntfs_attr_list_entry *attr_entry;
    uint32_t len = 0;
    struct ntfs_mft_record *retval;
    uint64_t start_blk = 0;

    dprintf("in %s()\n", __func__);

    if (attr->non_resident)
        goto handle_non_resident_attr;

    attr_entry = (struct ntfs_attr_list_entry *)
        ((uint8_t *)attr + attr->data.resident.value_offset);
    len = attr->data.resident.value_len;
    for (; (uint8_t *)attr_entry < (uint8_t *)attr + len;
         attr_entry = (struct ntfs_attr_list_entry *)((uint8_t *)attr_entry +
                                                      attr_entry->length)) {
        dprintf("<$ATTRIBUTE_LIST> Attribute type: 0x%X\n",
                attr_entry->type);
        if (attr_entry->type == type)
            goto found; /* We got the attribute! :-) */
    }

    printf("No attribute found.\n");
    goto out;

handle_non_resident_attr:
    attr_len = (uint8_t *)attr + attr->len;
    stream = mapping_chunk_init(attr, &chunk, &offset);
    do {
        err = parse_data_run(stream, &offset, attr_len, &chunk);
        if (err) {
            printf("parse_data_run()\n");
            goto out;
        }

        if (chunk.flags & MAP_UNALLOCATED)
            continue;
        if (chunk.flags & MAP_END)
            break;
        if (chunk.flags & MAP_ALLOCATED) {
            vcn = 0;
            lcn = chunk.lcn;
            while (vcn < chunk.len) {
                blk = (lcn + vcn) << NTFS_SB(fs)->clust_byte_shift >>
                    BLOCK_SHIFT(fs);
                blk_offset = 0;
                last_lcn = lcn;
                lcn += vcn;
                err = ntfs_read(fs, buf, blk_size, blk_size, &blk,
                                &blk_offset, NULL, (uint64_t *)&lcn);
                if (err) {
                    printf("Error while reading from cache.\n");
                    goto out;
                }

                attr_entry = (struct ntfs_attr_list_entry *)&buf;
                len = attr->data.non_resident.data_size;
                for (; (uint8_t *)attr_entry < (uint8_t *)&buf[0] + len;
                     attr_entry = (struct ntfs_attr_list_entry *)
                         ((uint8_t *)attr_entry + attr_entry->length)) {
                    dprintf("<$ATTRIBUTE_LIST> Attribute type: 0x%x\n",
                            attr_entry->type);
                    if (attr_entry->type == type)
                        goto found; /* We got the attribute! :-) */
                }

                lcn = last_lcn; /* restore original LCN */
                /* go to the next VCN */
                vcn += (blk_size / (1 << NTFS_SB(fs)->clust_byte_shift));
            }
        }
    } while (!(chunk.flags & MAP_END));

    printf("No attribute found.\n");

out:
    return NULL;

found:
    /* At this point we have the attribute we were looking for. Now we
     * will look for the MFT record that stores information about this
     * attribute.
     */

    /* Check if the attribute type we're looking for is in the same
     * MFT record. If so, we do not need to look it up again - return it.
     */
    if (mrec->mft_record_no == attr_entry->mft_ref)
        return mrec;

    retval = NTFS_SB(fs)->mft_record_lookup(fs, attr_entry->mft_ref,
                                            &start_blk);
    if (!retval) {
        printf("No MFT record found!\n");
        goto out;
    }

    /* return the found MFT record */
    return retval;
}

static struct ntfs_attr_record *
__ntfs_attr_lookup(struct fs_info *fs, uint32_t type,
                   struct ntfs_mft_record **mrec)
{
    struct ntfs_mft_record *_mrec = *mrec;
    struct ntfs_attr_record *attr;
    struct ntfs_attr_record *attr_list_attr;

    dprintf("in %s()\n", __func__);

    if (!_mrec || type == NTFS_AT_END)
        goto out;

again:
    attr_list_attr = NULL;

    attr = (struct ntfs_attr_record *)((uint8_t *)_mrec + _mrec->attrs_offset);
    /* walk through the file attribute records */
    for (;; attr = (struct ntfs_attr_record *)((uint8_t *)attr + attr->len)) {
        if (attr->type == NTFS_AT_END)
            break;

        if (attr->type == NTFS_AT_ATTR_LIST) {
            dprintf("MFT record #%lu has an $ATTRIBUTE_LIST attribute.\n",
                    _mrec->mft_record_no);
            attr_list_attr = attr;
            continue;
        }

        if (attr->type == type)
            break;
    }

    /* if the record has an $ATTRIBUTE_LIST attribute associated
     * with it, then we need to look for the wanted attribute in
     * it as well.
     */
    if (attr->type == NTFS_AT_END && attr_list_attr) {
        struct ntfs_mft_record *retval;

        retval = ntfs_attr_list_lookup(fs, attr_list_attr, type, _mrec);
        if (!retval)
            goto out;

        _mrec = retval;
        goto again;
    } else if (attr->type == NTFS_AT_END && !attr_list_attr) {
        attr = NULL;
    }

    return attr;

out:
    return NULL;
}

static inline struct ntfs_attr_record *
ntfs_attr_lookup(struct fs_info *fs, uint32_t type,
                 struct ntfs_mft_record **mmrec,
                 struct ntfs_mft_record *mrec)
{
    struct ntfs_mft_record *_mrec = mrec;
    struct ntfs_mft_record *other = *mmrec;
    struct ntfs_attr_record *retval = NULL;

    if (mrec == other)
        return __ntfs_attr_lookup(fs, type, &other);

    retval = __ntfs_attr_lookup(fs, type, &_mrec);
    if (!retval) {
        _mrec = other;
        retval = __ntfs_attr_lookup(fs, type, &other);
        if (!retval)
            other = _mrec;
    } else if (retval && (_mrec != mrec)) {
        other = _mrec;
    }

    return retval;
}

static inline enum dirent_type get_inode_mode(struct ntfs_mft_record *mrec)
{
    return mrec->flags & MFT_RECORD_IS_DIRECTORY ? DT_DIR : DT_REG;
}

static int index_inode_setup(struct fs_info *fs, unsigned long mft_no,
                            struct inode *inode)
{
    uint64_t start_blk = 0;
    struct ntfs_mft_record *mrec, *lmrec;
    struct ntfs_attr_record *attr;
    enum dirent_type d_type;
    uint8_t *attr_len;
    struct mapping_chunk chunk;
    int err;
    uint8_t *stream;
    uint32_t offset;

    dprintf("in %s()\n", __func__);

    mrec = NTFS_SB(fs)->mft_record_lookup(fs, mft_no, &start_blk);
    if (!mrec) {
        printf("No MFT record found.\n");
        goto out;
    }

    lmrec = mrec;

    NTFS_PVT(inode)->mft_no = mft_no;
    NTFS_PVT(inode)->seq_no = mrec->seq_no;

    NTFS_PVT(inode)->start_cluster = start_blk >> NTFS_SB(fs)->clust_shift;
    NTFS_PVT(inode)->here = start_blk;

    d_type = get_inode_mode(mrec);
    if (d_type == DT_DIR) {    /* directory stuff */
        dprintf("Got a directory.\n");
        attr = ntfs_attr_lookup(fs, NTFS_AT_INDEX_ROOT, &mrec, lmrec);
        if (!attr) {
            printf("No attribute found.\n");
            goto out;
        }

        /* check if we have a previous allocated state structure */
        if (readdir_state) {
            free(readdir_state);
            readdir_state = NULL;
        }

        /* allocate our state structure */
        readdir_state = malloc(sizeof *readdir_state);
        if (!readdir_state)
            malloc_error("ntfs_readdir_state structure");

        readdir_state->mft_no = mft_no;
        /* obviously, the ntfs_readdir() caller will start from INDEX root */
        readdir_state->in_idx_root = true;
    } else if (d_type == DT_REG) {        /* file stuff */
        dprintf("Got a file.\n");
        attr = ntfs_attr_lookup(fs, NTFS_AT_DATA, &mrec, lmrec);
        if (!attr) {
            printf("No attribute found.\n");
            goto out;
        }

        NTFS_PVT(inode)->non_resident = attr->non_resident;
        NTFS_PVT(inode)->type = attr->type;

        if (!attr->non_resident) {
            NTFS_PVT(inode)->data.resident.offset =
                (uint32_t)((uint8_t *)attr + attr->data.resident.value_offset);
            inode->size = attr->data.resident.value_len;
        } else {
            attr_len = (uint8_t *)attr + attr->len;

            stream = mapping_chunk_init(attr, &chunk, &offset);
            NTFS_PVT(inode)->data.non_resident.rlist = NULL;
            for (;;) {
                err = parse_data_run(stream, &offset, attr_len, &chunk);
                if (err) {
                    printf("parse_data_run()\n");
                    goto out;
                }

                if (chunk.flags & MAP_UNALLOCATED)
                    continue;
                if (chunk.flags & MAP_END)
                    break;
                if (chunk.flags &  MAP_ALLOCATED) {
                    /* append new run to the runlist */
                    runlist_append(&NTFS_PVT(inode)->data.non_resident.rlist,
                                    (struct runlist_element *)&chunk);
                    /* update for next VCN */
                    chunk.vcn += chunk.len;
                }
            }

            if (runlist_is_empty(NTFS_PVT(inode)->data.non_resident.rlist)) {
                printf("No mapping found\n");
                goto out;
            }

            inode->size = attr->data.non_resident.initialized_size;
        }
    }

    inode->mode = d_type;

    free(mrec);

    return 0;

out:
    free(mrec);

    return -1;
}

static struct inode *ntfs_index_lookup(const char *dname, struct inode *dir)
{
    struct fs_info *fs = dir->fs;
    struct ntfs_mft_record *mrec, *lmrec;
    block_t blk;
    uint64_t blk_offset;
    struct ntfs_attr_record *attr;
    struct ntfs_idx_root *ir;
    struct ntfs_idx_entry *ie;
    const uint64_t blk_size = UINT64_C(1) << BLOCK_SHIFT(fs);
    uint8_t buf[blk_size];
    struct ntfs_idx_allocation *iblk;
    int err;
    uint8_t *stream;
    uint8_t *attr_len;
    struct mapping_chunk chunk;
    uint32_t offset;
    int64_t vcn;
    int64_t lcn;
    int64_t last_lcn;
    struct inode *inode;

    dprintf("in %s()\n", __func__);

    mrec = NTFS_SB(fs)->mft_record_lookup(fs, NTFS_PVT(dir)->mft_no, NULL);
    if (!mrec) {
        printf("No MFT record found.\n");
        goto out;
    }

    lmrec = mrec;
    attr = ntfs_attr_lookup(fs, NTFS_AT_INDEX_ROOT, &mrec, lmrec);
    if (!attr) {
        printf("No attribute found.\n");
        goto out;
    }

    ir = (struct ntfs_idx_root *)((uint8_t *)attr +
                            attr->data.resident.value_offset);
    ie = (struct ntfs_idx_entry *)((uint8_t *)&ir->index +
                                ir->index.entries_offset);
    for (;; ie = (struct ntfs_idx_entry *)((uint8_t *)ie + ie->len)) {
        /* bounds checks */
        if ((uint8_t *)ie < (uint8_t *)mrec ||
            (uint8_t *)ie + sizeof(struct ntfs_idx_entry_header) >
            (uint8_t *)&ir->index + ir->index.index_len ||
            (uint8_t *)ie + ie->len >
            (uint8_t *)&ir->index + ir->index.index_len)
            goto index_err;

        /* last entry cannot contain a key. it can however contain
         * a pointer to a child node in the B+ tree so we just break out
         */
        if (ie->flags & INDEX_ENTRY_END)
            break;

        if (ntfs_filename_cmp(dname, ie))
            goto found;
    }

    /* check for the presence of a child node */
    if (!(ie->flags & INDEX_ENTRY_NODE)) {
        printf("No child node, aborting...\n");
        goto out;
    }

    /* then descend into child node */

    attr = ntfs_attr_lookup(fs, NTFS_AT_INDEX_ALLOCATION, &mrec, lmrec);
    if (!attr) {
        printf("No attribute found.\n");
        goto out;
    }

    if (!attr->non_resident) {
        printf("WTF ?! $INDEX_ALLOCATION isn't really resident.\n");
        goto out;
    }

    attr_len = (uint8_t *)attr + attr->len;
    stream = mapping_chunk_init(attr, &chunk, &offset);
    do {
        err = parse_data_run(stream, &offset, attr_len, &chunk);
        if (err)
            break;

        if (chunk.flags & MAP_UNALLOCATED)
            continue;

        if (chunk.flags & MAP_ALLOCATED) {
            dprintf("%d cluster(s) starting at 0x%08llX\n", chunk.len,
                    chunk.lcn);

            vcn = 0;
            lcn = chunk.lcn;
            while (vcn < chunk.len) {
                blk = (lcn + vcn) << NTFS_SB(fs)->clust_shift <<
                    SECTOR_SHIFT(fs) >> BLOCK_SHIFT(fs);

                blk_offset = 0;
                last_lcn = lcn;
                lcn += vcn;
                err = ntfs_read(fs, &buf, blk_size, blk_size, &blk,
                                &blk_offset, NULL, (uint64_t *)&lcn);
                if (err) {
                    printf("Error while reading from cache.\n");
                    goto not_found;
                }

                ntfs_fixups_writeback(fs, (struct ntfs_record *)&buf);

                iblk = (struct ntfs_idx_allocation *)&buf;
                if (iblk->magic != NTFS_MAGIC_INDX) {
                    printf("Not a valid INDX record.\n");
                    goto not_found;
                }

                ie = (struct ntfs_idx_entry *)((uint8_t *)&iblk->index +
                                            iblk->index.entries_offset);
                for (;; ie = (struct ntfs_idx_entry *)((uint8_t *)ie +
                        ie->len)) {
                    /* bounds checks */
                    if ((uint8_t *)ie < (uint8_t *)iblk || (uint8_t *)ie +
                        sizeof(struct ntfs_idx_entry_header) >
                        (uint8_t *)&iblk->index + iblk->index.index_len ||
                        (uint8_t *)ie + ie->len >
                        (uint8_t *)&iblk->index + iblk->index.index_len)
                        goto index_err;

                    /* last entry cannot contain a key */
                    if (ie->flags & INDEX_ENTRY_END)
                        break;

                    if (ntfs_filename_cmp(dname, ie))
                        goto found;
                }

                lcn = last_lcn; /* restore the original LCN */
                /* go to the next VCN */
                vcn += (blk_size / (1 << NTFS_SB(fs)->clust_byte_shift));
            }
        }
    } while (!(chunk.flags & MAP_END));

not_found:
    dprintf("Index not found\n");

out:
    free(mrec);

    return NULL;

found:
    dprintf("Index found\n");
    inode = new_ntfs_inode(fs);
    err = index_inode_setup(fs, ie->data.dir.indexed_file, inode);
    if (err) {
        printf("Error in index_inode_setup()\n");
        free(inode);
        goto out;
    }

    free(mrec);

    return inode;

index_err:
    printf("Corrupt index. Aborting lookup...\n");
    goto out;
}

/* Convert an UTF-16LE LFN to OEM LFN */
static uint8_t ntfs_cvt_filename(char *filename,
                                const struct ntfs_idx_entry *ie)
{
    const uint16_t *entry_fn;
    uint8_t entry_fn_len;
    unsigned i;

    entry_fn = ie->key.file_name.file_name;
    entry_fn_len = ie->key.file_name.file_name_len;

    for (i = 0; i < entry_fn_len; i++)
        filename[i] = (char)entry_fn[i];

    filename[i] = '\0';

    return entry_fn_len;
}

static int ntfs_next_extent(struct inode *inode, uint32_t lstart)
{
    struct fs_info *fs = inode->fs;
    struct ntfs_sb_info *sbi = NTFS_SB(fs);
    sector_t pstart = 0;
    struct runlist *rlist;
    struct runlist *ret;
    const uint32_t sec_size = SECTOR_SIZE(fs);
    const uint32_t sec_shift = SECTOR_SHIFT(fs);

    dprintf("in %s()\n", __func__);

    if (!NTFS_PVT(inode)->non_resident) {
        pstart = (sbi->mft_blk + NTFS_PVT(inode)->here) << BLOCK_SHIFT(fs) >>
                sec_shift;
        inode->next_extent.len = (inode->size + sec_size - 1) >> sec_shift;
    } else {
        rlist = NTFS_PVT(inode)->data.non_resident.rlist;

        if (!lstart || lstart >= NTFS_PVT(inode)->here) {
            if (runlist_is_empty(rlist))
                goto out;   /* nothing to do ;-) */

            ret = runlist_remove(&rlist);

            NTFS_PVT(inode)->here =
                ((ret->run.len << sbi->clust_byte_shift) >> sec_shift);

            pstart = ret->run.lcn << sbi->clust_shift;
            inode->next_extent.len =
                ((ret->run.len << sbi->clust_byte_shift) + sec_size - 1) >>
                sec_shift;

            NTFS_PVT(inode)->data.non_resident.rlist = rlist;

            free(ret);
            ret = NULL;
        }
    }

    inode->next_extent.pstart = pstart;

    return 0;

out:
    return -1;
}

static uint32_t ntfs_getfssec(struct file *file, char *buf, int sectors,
                                bool *have_more)
{
    uint8_t non_resident;
    uint32_t ret;
    struct fs_info *fs = file->fs;
    struct inode *inode = file->inode;
    struct ntfs_mft_record *mrec, *lmrec;
    struct ntfs_attr_record *attr;
    char *p;

    dprintf("in %s()\n", __func__);

    non_resident = NTFS_PVT(inode)->non_resident;

    ret = generic_getfssec(file, buf, sectors, have_more);
    if (!ret)
        return ret;

    if (!non_resident) {
        mrec = NTFS_SB(fs)->mft_record_lookup(fs, NTFS_PVT(inode)->mft_no,
                                              NULL);
        if (!mrec) {
            printf("No MFT record found.\n");
            goto out;
        }

        lmrec = mrec;
        attr = ntfs_attr_lookup(fs, NTFS_AT_DATA, &mrec, lmrec);
        if (!attr) {
            printf("No attribute found.\n");
            goto out;
        }

        p = (char *)((uint8_t *)attr + attr->data.resident.value_offset);

        /* p now points to the data offset, so let's copy it into buf */
        memcpy(buf, p, inode->size);

        ret = inode->size;

        free(mrec);
    }

    return ret;

out:
    free(mrec);

    return 0;
}

static inline bool is_filename_printable(const char *s)
{
    return s && (*s != '.' && *s != '$');
}

static int ntfs_readdir(struct file *file, struct dirent *dirent)
{
    struct fs_info *fs = file->fs;
    struct inode *inode = file->inode;
    struct ntfs_mft_record *mrec, *lmrec;
    block_t blk;
    uint64_t blk_offset;
    const uint64_t blk_size = UINT64_C(1) << BLOCK_SHIFT(fs);
    struct ntfs_attr_record *attr;
    struct ntfs_idx_root *ir;
    uint32_t count;
    int len;
    struct ntfs_idx_entry *ie = NULL;
    uint8_t buf[BLOCK_SIZE(fs)];
    struct ntfs_idx_allocation *iblk;
    int err;
    uint8_t *stream;
    uint8_t *attr_len;
    struct mapping_chunk chunk;
    uint32_t offset;
    int64_t vcn;
    int64_t lcn;
    char filename[NTFS_MAX_FILE_NAME_LEN + 1];

    dprintf("in %s()\n", __func__);

    mrec = NTFS_SB(fs)->mft_record_lookup(fs, NTFS_PVT(inode)->mft_no, NULL);
    if (!mrec) {
        printf("No MFT record found.\n");
        goto out;
    }

    lmrec = mrec;
    attr = ntfs_attr_lookup(fs, NTFS_AT_INDEX_ROOT, &mrec, lmrec);
    if (!attr) {
        printf("No attribute found.\n");
        goto out;
    }

    ir = (struct ntfs_idx_root *)((uint8_t *)attr +
                            attr->data.resident.value_offset);

    if (!file->offset && readdir_state->in_idx_root) {
        file->offset = (uint32_t)((uint8_t *)&ir->index +
                                        ir->index.entries_offset);
    }

idx_root_next_entry:
    if (readdir_state->in_idx_root) {
        ie = (struct ntfs_idx_entry *)(uint8_t *)file->offset;
        if (ie->flags & INDEX_ENTRY_END) {
            file->offset = 0;
            readdir_state->in_idx_root = false;
            readdir_state->idx_blks_count = 1;
            readdir_state->entries_count = 0;
            readdir_state->last_vcn = 0;
            goto descend_into_child_node;
        }

        file->offset = (uint32_t)((uint8_t *)ie + ie->len);
        len = ntfs_cvt_filename(filename, ie);
        if (!is_filename_printable(filename))
            goto idx_root_next_entry;

        goto done;
    }

descend_into_child_node:
    if (!(ie->flags & INDEX_ENTRY_NODE))
        goto out;

    attr = ntfs_attr_lookup(fs, NTFS_AT_INDEX_ALLOCATION, &mrec, lmrec);
    if (!attr)
        goto out;

    if (!attr->non_resident) {
        printf("WTF ?! $INDEX_ALLOCATION isn't really resident.\n");
        goto out;
    }

    attr_len = (uint8_t *)attr + attr->len;

next_run:
    stream = mapping_chunk_init(attr, &chunk, &offset);
    count = readdir_state->idx_blks_count;
    while (count--) {
        err = parse_data_run(stream, &offset, attr_len, &chunk);
        if (err) {
            printf("Error while parsing data runs.\n");
            goto out;
        }

        if (chunk.flags & MAP_UNALLOCATED)
            break;
        if (chunk.flags & MAP_END)
            goto out;
    }

    if (chunk.flags & MAP_UNALLOCATED) {
       readdir_state->idx_blks_count++;
       goto next_run;
    }

next_vcn:
    vcn = readdir_state->last_vcn;
    if (vcn >= chunk.len) {
        readdir_state->last_vcn = 0;
        readdir_state->idx_blks_count++;
        goto next_run;
    }

    lcn = chunk.lcn;
    blk = (lcn + vcn) << NTFS_SB(fs)->clust_shift << SECTOR_SHIFT(fs) >>
            BLOCK_SHIFT(fs);

    blk_offset = 0;
    err = ntfs_read(fs, &buf, blk_size, blk_size, &blk, &blk_offset, NULL,
                    (uint64_t *)&lcn);
    if (err) {
        printf("Error while reading from cache.\n");
        goto not_found;
    }

    ntfs_fixups_writeback(fs, (struct ntfs_record *)&buf);

    iblk = (struct ntfs_idx_allocation *)&buf;
    if (iblk->magic != NTFS_MAGIC_INDX) {
        printf("Not a valid INDX record.\n");
        goto not_found;
    }

idx_block_next_entry:
    ie = (struct ntfs_idx_entry *)((uint8_t *)&iblk->index +
                        iblk->index.entries_offset);
    count = readdir_state->entries_count;
    for ( ; count--; ie = (struct ntfs_idx_entry *)((uint8_t *)ie + ie->len)) {
        /* bounds checks */
        if ((uint8_t *)ie < (uint8_t *)iblk || (uint8_t *)ie +
            sizeof(struct ntfs_idx_entry_header) >
            (uint8_t *)&iblk->index + iblk->index.index_len ||
            (uint8_t *)ie + ie->len >
            (uint8_t *)&iblk->index + iblk->index.index_len)
            goto index_err;

        /* last entry cannot contain a key */
        if (ie->flags & INDEX_ENTRY_END) {
            /* go to the next VCN */
            readdir_state->last_vcn += (blk_size / (1 <<
                                NTFS_SB(fs)->clust_byte_shift));
            readdir_state->entries_count = 0;
            goto next_vcn;
        }
    }

    readdir_state->entries_count++;

    /* Need to check if this entry has INDEX_ENTRY_END flag set. If
     * so, then it won't contain a indexed_file file, so continue the
     * lookup on the next VCN/LCN (if any).
     */
    if (ie->flags & INDEX_ENTRY_END)
        goto next_vcn;

    len = ntfs_cvt_filename(filename, ie);
    if (!is_filename_printable(filename))
        goto idx_block_next_entry;

    goto done;

out:
    readdir_state->in_idx_root = true;

    free(mrec);

    return -1;

done:
    dirent->d_ino = ie->data.dir.indexed_file;
    dirent->d_off = file->offset;
    dirent->d_reclen = offsetof(struct dirent, d_name) + len + 1;

    free(mrec);

    mrec = NTFS_SB(fs)->mft_record_lookup(fs, ie->data.dir.indexed_file, NULL);
    if (!mrec) {
        printf("No MFT record found.\n");
        goto out;
    }

    dirent->d_type = get_inode_mode(mrec);
    memcpy(dirent->d_name, filename, len + 1);

    free(mrec);

    return 0;

not_found:
    printf("Index not found\n");
    goto out;

index_err:
    printf("Corrupt index. Aborting lookup...\n");
    goto out;
}

static inline struct inode *ntfs_iget(const char *dname, struct inode *parent)
{
    return ntfs_index_lookup(dname, parent);
}

static struct inode *ntfs_iget_root(struct fs_info *fs)
{
    uint64_t start_blk;
    struct ntfs_mft_record *mrec, *lmrec;
    struct ntfs_attr_record *attr;
    struct ntfs_vol_info *vol_info;
    struct inode *inode;
    int err;

    dprintf("in %s()\n", __func__);

    /* Fetch the $Volume MFT record */
    start_blk = 0;
    mrec = NTFS_SB(fs)->mft_record_lookup(fs, FILE_Volume, &start_blk);
    if (!mrec) {
        printf("Could not fetch $Volume MFT record!\n");
        goto err_mrec;
    }

    lmrec = mrec;

    /* Fetch the volume information attribute */
    attr = ntfs_attr_lookup(fs, NTFS_AT_VOL_INFO, &mrec, lmrec);
    if (!attr) {
        printf("Could not find volume info attribute!\n");
        goto err_attr;
    }

    /* Note NTFS version and choose version-dependent functions */
    vol_info = (void *)((char *)attr + attr->data.resident.value_offset);
    NTFS_SB(fs)->major_ver = vol_info->major_ver;
    NTFS_SB(fs)->minor_ver = vol_info->minor_ver;
    if (vol_info->major_ver == 3 && vol_info->minor_ver == 0)
        NTFS_SB(fs)->mft_record_lookup = ntfs_mft_record_lookup_3_0;
    else if (vol_info->major_ver == 3 && vol_info->minor_ver == 1 &&
            mrec->mft_record_no == FILE_Volume)
        NTFS_SB(fs)->mft_record_lookup = ntfs_mft_record_lookup_3_1;

    /* Free MFT record */
    free(mrec);
    mrec = NULL;

    inode = new_ntfs_inode(fs);
    inode->fs = fs;

    err = index_inode_setup(fs, FILE_root, inode);
    if (err)
        goto err_setup;

    NTFS_PVT(inode)->start = NTFS_PVT(inode)->here;

    return inode;

err_setup:

    free(inode);
err_attr:

    free(mrec);
err_mrec:

    return NULL;
}

/* Initialize the filesystem metadata and return blk size in bits */
static int ntfs_fs_init(struct fs_info *fs)
{
    int read_count;
    struct ntfs_bpb ntfs;
    struct ntfs_sb_info *sbi;
    struct disk *disk = fs->fs_dev->disk;
    uint8_t mft_record_shift;

    dprintf("in %s()\n", __func__);

    read_count = disk->rdwr_sectors(disk, &ntfs, 0, 1, 0);
    if (!read_count)
        return -1;

    if (!ntfs_check_sb_fields(&ntfs))
        return -1;

    SECTOR_SHIFT(fs) = disk->sector_shift;

    /* Note: ntfs.clust_per_mft_record can be a negative number.
     * If negative, it represents a shift count, else it represents
     * a multiplier for the cluster size.
     */
    mft_record_shift = ntfs.clust_per_mft_record < 0 ?
                    -ntfs.clust_per_mft_record :
                    ilog2(ntfs.sec_per_clust) + SECTOR_SHIFT(fs) +
                    ilog2(ntfs.clust_per_mft_record);

    SECTOR_SIZE(fs) = 1 << SECTOR_SHIFT(fs);

    sbi = malloc(sizeof *sbi);
    if (!sbi)
        malloc_error("ntfs_sb_info structure");

    fs->fs_info = sbi;

    sbi->clust_shift            = ilog2(ntfs.sec_per_clust);
    sbi->clust_byte_shift       = sbi->clust_shift + SECTOR_SHIFT(fs);
    sbi->clust_mask             = ntfs.sec_per_clust - 1;
    sbi->clust_size             = ntfs.sec_per_clust << SECTOR_SHIFT(fs);
    sbi->mft_record_size        = 1 << mft_record_shift;
    sbi->clust_per_idx_record   = ntfs.clust_per_idx_record;

    BLOCK_SHIFT(fs) = ilog2(ntfs.clust_per_idx_record) + sbi->clust_byte_shift;
    BLOCK_SIZE(fs) = 1 << BLOCK_SHIFT(fs);

    sbi->mft_lcn = ntfs.mft_lclust;
    sbi->mft_blk = ntfs.mft_lclust << sbi->clust_shift << SECTOR_SHIFT(fs) >>
                BLOCK_SHIFT(fs);
    /* 16 MFT entries reserved for metadata files (approximately 16 KiB) */
    sbi->mft_size = mft_record_shift << sbi->clust_shift << 4;

    sbi->clusters = ntfs.total_sectors << SECTOR_SHIFT(fs) >> sbi->clust_shift;
    if (sbi->clusters > 0xFFFFFFFFFFF4ULL)
        sbi->clusters = 0xFFFFFFFFFFF4ULL;

    /*
     * Assume NTFS version 3.0 to begin with. If we find that the
     * volume is a different version later on, we will adjust at
     * that time.
     */
    sbi->major_ver = 3;
    sbi->minor_ver = 0;
    sbi->mft_record_lookup = ntfs_mft_record_lookup_3_0;

    /* Initialize the cache */
    cache_init(fs->fs_dev, BLOCK_SHIFT(fs));

    return BLOCK_SHIFT(fs);
}

const struct fs_ops ntfs_fs_ops = {
    .fs_name        = "ntfs",
    .fs_flags       = FS_USEMEM | FS_THISIND,
    .fs_init        = ntfs_fs_init,
    .searchdir      = NULL,
    .getfssec       = ntfs_getfssec,
    .close_file     = generic_close_file,
    .mangle_name    = generic_mangle_name,
    .load_config    = generic_load_config,
    .readdir        = ntfs_readdir,
    .iget_root      = ntfs_iget_root,
    .iget           = ntfs_iget,
    .next_extent    = ntfs_next_extent,
};