[NTFS] - Add some fixes and improvements to mft.c from CR-123:
[reactos.git] / drivers / filesystems / ntfs / mft.c
index e78be29..539b8f2 100644 (file)
@@ -32,7 +32,6 @@
 #include "ntfs.h"
 
 #define NDEBUG
-#undef NDEBUG
 #include <debug.h>
 
 /* FUNCTIONS ****************************************************************/
@@ -120,7 +119,7 @@ FindAttribute(PDEVICE_EXTENSION Vcb,
     FIND_ATTR_CONTXT Context;
     PNTFS_ATTR_RECORD Attribute;
 
-    DPRINT("FindAttribute(%p, %p, 0x%x, %S, %u, %p)\n", Vcb, MftRecord, Type, Name, NameLength, AttrCtx);
+    DPRINT("FindAttribute(%p, %p, 0x%x, %S, %lu, %p, %p)\n", Vcb, MftRecord, Type, Name, NameLength, AttrCtx, Offset);
 
     Found = FALSE;
     Status = FindFirstAttribute(&Context, Vcb, MftRecord, FALSE, &Attribute);
@@ -134,7 +133,7 @@ FindAttribute(PDEVICE_EXTENSION Vcb,
 
                 AttrName = (PWCHAR)((PCHAR)Attribute + Attribute->NameOffset);
                 DPRINT("%.*S, %.*S\n", Attribute->NameLength, AttrName, NameLength, Name);
-                if (RtlCompareMemory(AttrName, Name, NameLength << 1) == (NameLength << 1))
+                if (RtlCompareMemory(AttrName, Name, NameLength * sizeof(WCHAR)) == (NameLength  * sizeof(WCHAR)))
                 {
                     Found = TRUE;
                 }
@@ -187,6 +186,168 @@ AttributeDataLength(PNTFS_ATTR_RECORD AttrRecord)
         return AttrRecord->Resident.ValueLength;
 }
 
+/**
+* @name IncreaseMftSize
+* @implemented
+*
+* Increases the size of the master file table on a volume, increasing the space available for file records.
+*
+* @param Vcb
+* Pointer to the VCB (DEVICE_EXTENSION) of the target volume.
+*
+*
+* @param CanWait
+* Boolean indicating if the function is allowed to wait for exclusive access to the master file table.
+* This will only be relevant if the MFT doesn't have any free file records and needs to be enlarged.
+*
+* @return
+* STATUS_SUCCESS on success.
+* STATUS_INSUFFICIENT_RESOURCES if an allocation fails.
+* STATUS_INVALID_PARAMETER if there was an error reading the Mft's bitmap.
+* STATUS_CANT_WAIT if CanWait was FALSE and the function could not get immediate, exclusive access to the MFT.
+*
+* @remarks
+* Increases the size of the Master File Table by 8 records. Bitmap entries for the new records are cleared,
+* and the bitmap is also enlarged if needed. Mimicking Windows' behavior when enlarging the mft is still TODO.
+* This function will wait for exlusive access to the volume fcb.
+*/
+NTSTATUS
+IncreaseMftSize(PDEVICE_EXTENSION Vcb, BOOLEAN CanWait)
+{
+    PNTFS_ATTR_CONTEXT BitmapContext;
+    LARGE_INTEGER BitmapSize;
+    LARGE_INTEGER DataSize;
+    LONGLONG BitmapSizeDifference;
+    ULONG DataSizeDifference = Vcb->NtfsInfo.BytesPerFileRecord * 8;
+    ULONG BitmapOffset;
+    PUCHAR BitmapBuffer;
+    ULONGLONG BitmapBytes;
+    ULONGLONG NewBitmapSize;
+    ULONG BytesRead;
+    ULONG LengthWritten;
+    NTSTATUS Status;
+
+    DPRINT1("IncreaseMftSize(%p, %s)\n", Vcb, CanWait ? "TRUE" : "FALSE");
+
+    // We need exclusive access to the mft while we change its size
+    if (!ExAcquireResourceExclusiveLite(&(Vcb->DirResource), CanWait))
+    {
+        return STATUS_CANT_WAIT;
+    }
+
+    // Find the bitmap attribute of master file table
+    Status = FindAttribute(Vcb, Vcb->MasterFileTable, AttributeBitmap, L"", 0, &BitmapContext, &BitmapOffset);
+    if (!NT_SUCCESS(Status))
+    {
+        DPRINT1("ERROR: Couldn't find $BITMAP attribute of Mft!\n");
+        ExReleaseResourceLite(&(Vcb->DirResource));
+        return Status;
+    }
+
+    // Get size of Bitmap Attribute
+    BitmapSize.QuadPart = AttributeDataLength(&BitmapContext->Record);
+
+    // Calculate the new mft size
+    DataSize.QuadPart = AttributeDataLength(&(Vcb->MFTContext->Record)) + DataSizeDifference;
+
+    // Determine how many bytes will make up the bitmap
+    BitmapBytes = DataSize.QuadPart / Vcb->NtfsInfo.BytesPerFileRecord / 8;
+    
+    // Determine how much we need to adjust the bitmap size (it's possible we don't)
+    BitmapSizeDifference = BitmapBytes - BitmapSize.QuadPart;
+    NewBitmapSize = max(BitmapSize.QuadPart + BitmapSizeDifference, BitmapSize.QuadPart);
+
+    // Allocate memory for the bitmap
+    BitmapBuffer = ExAllocatePoolWithTag(NonPagedPool, NewBitmapSize, TAG_NTFS);
+    if (!BitmapBuffer)
+    {
+        DPRINT1("ERROR: Unable to allocate memory for bitmap attribute!\n");
+        ExReleaseResourceLite(&(Vcb->DirResource));
+        ReleaseAttributeContext(BitmapContext);
+        return STATUS_INSUFFICIENT_RESOURCES;
+    }
+
+    // Zero the bytes we'll be adding
+    RtlZeroMemory(BitmapBuffer, NewBitmapSize);
+
+    // Read the bitmap attribute
+    BytesRead = ReadAttribute(Vcb,
+                              BitmapContext,
+                              0,
+                              (PCHAR)BitmapBuffer,
+                              BitmapSize.LowPart);
+    if (BytesRead != BitmapSize.LowPart)
+    {
+        DPRINT1("ERROR: Bytes read != Bitmap size!\n");
+        ExReleaseResourceLite(&(Vcb->DirResource));
+        ExFreePoolWithTag(BitmapBuffer, TAG_NTFS);
+        ReleaseAttributeContext(BitmapContext);
+        return STATUS_INVALID_PARAMETER;
+    }
+
+    // Increase the mft size
+    Status = SetNonResidentAttributeDataLength(Vcb, Vcb->MFTContext, Vcb->MftDataOffset, Vcb->MasterFileTable, &DataSize);
+    if (!NT_SUCCESS(Status))
+    {
+        DPRINT1("ERROR: Failed to set size of $MFT data attribute!\n");
+        ExReleaseResourceLite(&(Vcb->DirResource));
+        ExFreePoolWithTag(BitmapBuffer, TAG_NTFS);
+        ReleaseAttributeContext(BitmapContext);
+        return Status;
+    }
+
+    // If the bitmap grew
+    if (BitmapSizeDifference > 0)
+    {
+        // Set the new bitmap size
+        BitmapSize.QuadPart += BitmapSizeDifference;
+        if (BitmapContext->Record.IsNonResident)
+            Status = SetNonResidentAttributeDataLength(Vcb, BitmapContext, BitmapOffset, Vcb->MasterFileTable, &BitmapSize);
+        else
+            Status = SetResidentAttributeDataLength(Vcb, BitmapContext, BitmapOffset, Vcb->MasterFileTable, &BitmapSize);
+    
+        if (!NT_SUCCESS(Status))
+        {
+            DPRINT1("ERROR: Failed to set size of bitmap attribute!\n");
+            ExReleaseResourceLite(&(Vcb->DirResource));
+            ExFreePoolWithTag(BitmapBuffer, TAG_NTFS);
+            ReleaseAttributeContext(BitmapContext);
+            return Status;
+        }
+    }
+
+    //NtfsDumpFileAttributes(Vcb, FileRecord);
+
+    // Update the file record with the new attribute sizes
+    Status = UpdateFileRecord(Vcb, Vcb->VolumeFcb->MFTIndex, Vcb->MasterFileTable);
+    if (!NT_SUCCESS(Status))
+    {
+        DPRINT1("ERROR: Failed to update $MFT file record!\n");
+        ExReleaseResourceLite(&(Vcb->DirResource));
+        ExFreePoolWithTag(BitmapBuffer, TAG_NTFS);
+        ReleaseAttributeContext(BitmapContext);
+        return Status;
+    }
+
+    // Write out the new bitmap
+    Status = WriteAttribute(Vcb, BitmapContext, BitmapOffset, BitmapBuffer, BitmapSize.LowPart, &LengthWritten);
+    if (!NT_SUCCESS(Status))
+    {
+        ExReleaseResourceLite(&(Vcb->DirResource));
+        ExFreePoolWithTag(BitmapBuffer, TAG_NTFS);
+        ReleaseAttributeContext(BitmapContext);
+        DPRINT1("ERROR: Couldn't write to bitmap attribute of $MFT!\n");
+        return Status;
+    }
+
+    // Cleanup
+    ExReleaseResourceLite(&(Vcb->DirResource));
+    ExFreePoolWithTag(BitmapBuffer, TAG_NTFS);
+    ReleaseAttributeContext(BitmapContext);
+
+    return STATUS_SUCCESS;
+}
+
 VOID
 InternalSetResidentAttributeLength(PNTFS_ATTR_CONTEXT AttrContext,
                                    PFILE_RECORD_HEADER FileRecord,
@@ -198,6 +359,8 @@ InternalSetResidentAttributeLength(PNTFS_ATTR_CONTEXT AttrContext,
 
     DPRINT("InternalSetResidentAttributeLength( %p, %p, %lu, %lu )\n", AttrContext, FileRecord, AttrOffset, DataSize);
 
+    ASSERT(!AttrContext->Record.IsNonResident);
+
     // update ValueLength Field
     AttrContext->Record.Resident.ValueLength =
     Destination->Resident.ValueLength = DataSize;
@@ -235,7 +398,14 @@ SetAttributeDataLength(PFILE_OBJECT FileObject,
                        PLARGE_INTEGER DataSize)
 {
     NTSTATUS Status = STATUS_SUCCESS;
-    ULONG BytesPerCluster = Fcb->Vcb->NtfsInfo.BytesPerCluster;
+
+    DPRINT1("SetAttributeDataLenth(%p, %p, %p, %lu, %p, %I64u)\n",
+            FileObject,
+            Fcb,
+            AttrContext,
+            AttrOffset,
+            FileRecord,
+            DataSize->QuadPart);
 
     // are we truncating the file?
     if (DataSize->QuadPart < AttributeDataLength(&AttrContext->Record))
@@ -249,129 +419,26 @@ SetAttributeDataLength(PFILE_OBJECT FileObject,
 
     if (AttrContext->Record.IsNonResident)
     {
-        ULONGLONG AllocationSize = ROUND_UP(DataSize->QuadPart, BytesPerCluster);
-        PNTFS_ATTR_RECORD DestinationAttribute = (PNTFS_ATTR_RECORD)((ULONG_PTR)FileRecord + AttrOffset);
-        ULONG ExistingClusters = AttrContext->Record.NonResident.AllocatedSize / BytesPerCluster;
-
-        // do we need to increase the allocation size?
-        if (AttrContext->Record.NonResident.AllocatedSize < AllocationSize)
-        {              
-            ULONG ClustersNeeded = (AllocationSize / BytesPerCluster) - ExistingClusters;
-            LARGE_INTEGER LastClusterInDataRun;
-            ULONG NextAssignedCluster;
-            ULONG AssignedClusters;
-
-            if (ExistingClusters == 0)
-            {
-               LastClusterInDataRun.QuadPart = 0;
-            }
-            else
-            {
-                if (!FsRtlLookupLargeMcbEntry(&AttrContext->DataRunsMCB,
-                                              (LONGLONG)AttrContext->Record.NonResident.HighestVCN,
-                                              (PLONGLONG)&LastClusterInDataRun.QuadPart,
-                                              NULL,
-                                              NULL,
-                                              NULL,
-                                              NULL))
-                {
-                    DPRINT1("Error looking up final large MCB entry!\n");
-
-                    // Most likely, HighestVCN went above the largest mapping
-                    DPRINT1("Highest VCN of record: %I64u\n", AttrContext->Record.NonResident.HighestVCN);
-                    return STATUS_INVALID_PARAMETER;
-                }
-            }
-
-            DPRINT("LastClusterInDataRun: %I64u\n", LastClusterInDataRun.QuadPart);
-            DPRINT("Highest VCN of record: %I64u\n", AttrContext->Record.NonResident.HighestVCN);
-
-            while (ClustersNeeded > 0)
-            {
-                Status = NtfsAllocateClusters(Fcb->Vcb,
-                                              LastClusterInDataRun.LowPart + 1,
-                                              ClustersNeeded,
-                                              &NextAssignedCluster,
-                                              &AssignedClusters);
-                
-                if (!NT_SUCCESS(Status))
-                {
-                    DPRINT1("Error: Unable to allocate requested clusters!\n");
-                    return Status;
-                }
-
-                // now we need to add the clusters we allocated to the data run
-                Status = AddRun(Fcb->Vcb, AttrContext, AttrOffset, FileRecord, NextAssignedCluster, AssignedClusters);
-                if (!NT_SUCCESS(Status))
-                {
-                    DPRINT1("Error: Unable to add data run!\n");
-                    return Status;
-                }
-
-                ClustersNeeded -= AssignedClusters;
-                LastClusterInDataRun.LowPart = NextAssignedCluster + AssignedClusters - 1;
-            }
-        }
-        else if (AttrContext->Record.NonResident.AllocatedSize > AllocationSize)
-        {
-            // shrink allocation size
-            ULONG ClustersToFree = ExistingClusters - (AllocationSize / BytesPerCluster);
-            Status = FreeClusters(Fcb->Vcb, AttrContext, AttrOffset, FileRecord, ClustersToFree);
-        }
-
-        // TODO: is the file compressed, encrypted, or sparse?
-
-        // NOTE: we need to have acquired the main resource exclusively, as well as(?) the PagingIoResource
-
-        Fcb->RFCB.AllocationSize.QuadPart = AllocationSize;
-        AttrContext->Record.NonResident.AllocatedSize = AllocationSize;
-        AttrContext->Record.NonResident.DataSize = DataSize->QuadPart;
-        AttrContext->Record.NonResident.InitializedSize = DataSize->QuadPart;
-
-        DestinationAttribute->NonResident.AllocatedSize = AllocationSize;
-        DestinationAttribute->NonResident.DataSize = DataSize->QuadPart;
-        DestinationAttribute->NonResident.InitializedSize = DataSize->QuadPart;
-
-        DPRINT("Allocated Size: %I64u\n", DestinationAttribute->NonResident.AllocatedSize);
+        Status = SetNonResidentAttributeDataLength(Fcb->Vcb,
+                                                   AttrContext,
+                                                   AttrOffset,
+                                                   FileRecord,
+                                                   DataSize);
     }
     else
     {
         // resident attribute
+        Status = SetResidentAttributeDataLength(Fcb->Vcb,
+                                                AttrContext,
+                                                AttrOffset,
+                                                FileRecord,
+                                                DataSize);
+    }
 
-        // find the next attribute
-        ULONG NextAttributeOffset = AttrOffset + AttrContext->Record.Length;
-        PNTFS_ATTR_RECORD NextAttribute = (PNTFS_ATTR_RECORD)((PCHAR)FileRecord + NextAttributeOffset);
-
-        //NtfsDumpFileAttributes(Fcb->Vcb, FileRecord);
-
-        // Do we need to increase the data length?
-        if (DataSize->QuadPart > AttrContext->Record.Resident.ValueLength)
-        {
-            // There's usually padding at the end of a record. Do we need to extend past it?
-            ULONG MaxValueLength = AttrContext->Record.Length - AttrContext->Record.Resident.ValueOffset;
-            if (MaxValueLength < DataSize->LowPart)
-            {
-                // If this is the last attribute, we could move the end marker to the very end of the file record
-                MaxValueLength += Fcb->Vcb->NtfsInfo.BytesPerFileRecord - NextAttributeOffset - (sizeof(ULONG) * 2);
-
-                if (MaxValueLength < DataSize->LowPart || NextAttribute->Type != AttributeEnd)
-                {
-                    DPRINT1("FIXME: Need to convert attribute to non-resident!\n");
-                    return STATUS_NOT_IMPLEMENTED;
-                }
-            }
-        }
-        else if (DataSize->LowPart < AttrContext->Record.Resident.ValueLength)
-        {
-            // we need to decrease the length
-            if (NextAttribute->Type != AttributeEnd)
-            {
-                DPRINT1("FIXME: Don't know how to decrease length of resident attribute unless it's the final attribute!\n");
-                return STATUS_NOT_IMPLEMENTED;
-            }
-        }
-
-        InternalSetResidentAttributeLength(AttrContext, FileRecord, AttrOffset, DataSize->LowPart);
+    if (!NT_SUCCESS(Status))
+    {
+        DPRINT1("ERROR: Failed to set size of attribute!\n");
+        return Status;
     }
 
     //NtfsDumpFileAttributes(Fcb->Vcb, FileRecord);
@@ -381,6 +448,10 @@ SetAttributeDataLength(PFILE_OBJECT FileObject,
 
     if (NT_SUCCESS(Status))
     {
+        if(AttrContext->Record.IsNonResident)
+            Fcb->RFCB.AllocationSize.QuadPart = AttrContext->Record.NonResident.AllocatedSize;
+        else
+            Fcb->RFCB.AllocationSize = *DataSize;
         Fcb->RFCB.FileSize = *DataSize;
         Fcb->RFCB.ValidDataLength = *DataSize;
         CcSetFileSizes(FileObject, (PCC_FILE_SIZES)&Fcb->RFCB.AllocationSize);
@@ -424,6 +495,322 @@ SetFileRecordEnd(PFILE_RECORD_HEADER FileRecord,
     FileRecord->BytesInUse = (ULONG_PTR)AttrEnd - (ULONG_PTR)FileRecord + sizeof(ULONG) * 2;
 }
 
+/**
+* @name SetNonResidentAttributeDataLength
+* @implemented
+*
+* Called by SetAttributeDataLength() to set the size of a non-resident attribute. Doesn't update the file record.
+*
+* @param Vcb
+* Pointer to a DEVICE_EXTENSION describing the target disk.
+*
+* @param AttrContext
+* PNTFS_ATTR_CONTEXT describing the location of the attribute whose size is being set.
+*
+* @param AttrOffset
+* Offset, from the beginning of the record, of the attribute being sized.
+*
+* @param FileRecord
+* Pointer to a file record containing the attribute to be resized. Must be a complete file record,
+* not just the header.
+*
+* @param DataSize
+* Pointer to a LARGE_INTEGER describing the new size of the attribute's data.
+*
+* @return
+* STATUS_SUCCESS on success;
+* STATUS_INSUFFICIENT_RESOURCES if an allocation fails.
+* STATUS_INVALID_PARAMETER if we can't find the last cluster in the data run.
+*
+* @remarks
+* Called by SetAttributeDataLength() and IncreaseMftSize(). Use SetAttributeDataLength() unless you have a good 
+* reason to use this. Doesn't update the file record on disk. Doesn't inform the cache controller of changes with
+* any associated files. Synchronization is the callers responsibility.
+*/
+NTSTATUS
+SetNonResidentAttributeDataLength(PDEVICE_EXTENSION Vcb,
+                                  PNTFS_ATTR_CONTEXT AttrContext,
+                                  ULONG AttrOffset,
+                                  PFILE_RECORD_HEADER FileRecord,
+                                  PLARGE_INTEGER DataSize)
+{
+    NTSTATUS Status = STATUS_SUCCESS;
+    ULONG BytesPerCluster = Vcb->NtfsInfo.BytesPerCluster;
+    ULONGLONG AllocationSize = ROUND_UP(DataSize->QuadPart, BytesPerCluster);
+    PNTFS_ATTR_RECORD DestinationAttribute = (PNTFS_ATTR_RECORD)((ULONG_PTR)FileRecord + AttrOffset);
+    ULONG ExistingClusters = AttrContext->Record.NonResident.AllocatedSize / BytesPerCluster;
+
+    ASSERT(AttrContext->Record.IsNonResident);
+
+    // do we need to increase the allocation size?
+    if (AttrContext->Record.NonResident.AllocatedSize < AllocationSize)
+    {
+        ULONG ClustersNeeded = (AllocationSize / BytesPerCluster) - ExistingClusters;
+        LARGE_INTEGER LastClusterInDataRun;
+        ULONG NextAssignedCluster;
+        ULONG AssignedClusters;
+
+        if (ExistingClusters == 0)
+        {
+            LastClusterInDataRun.QuadPart = 0;
+        }
+        else
+        {
+            if (!FsRtlLookupLargeMcbEntry(&AttrContext->DataRunsMCB,
+                                          (LONGLONG)AttrContext->Record.NonResident.HighestVCN,
+                                          (PLONGLONG)&LastClusterInDataRun.QuadPart,
+                                          NULL,
+                                          NULL,
+                                          NULL,
+                                          NULL))
+            {
+                DPRINT1("Error looking up final large MCB entry!\n");
+
+                // Most likely, HighestVCN went above the largest mapping
+                DPRINT1("Highest VCN of record: %I64u\n", AttrContext->Record.NonResident.HighestVCN);
+                return STATUS_INVALID_PARAMETER;
+            }
+        }
+
+        DPRINT("LastClusterInDataRun: %I64u\n", LastClusterInDataRun.QuadPart);
+        DPRINT("Highest VCN of record: %I64u\n", AttrContext->Record.NonResident.HighestVCN);
+
+        while (ClustersNeeded > 0)
+        {
+            Status = NtfsAllocateClusters(Vcb,
+                                          LastClusterInDataRun.LowPart + 1,
+                                          ClustersNeeded,
+                                          &NextAssignedCluster,
+                                          &AssignedClusters);
+
+            if (!NT_SUCCESS(Status))
+            {
+                DPRINT1("Error: Unable to allocate requested clusters!\n");
+                return Status;
+            }
+
+            // now we need to add the clusters we allocated to the data run
+            Status = AddRun(Vcb, AttrContext, AttrOffset, FileRecord, NextAssignedCluster, AssignedClusters);
+            if (!NT_SUCCESS(Status))
+            {
+                DPRINT1("Error: Unable to add data run!\n");
+                return Status;
+            }
+
+            ClustersNeeded -= AssignedClusters;
+            LastClusterInDataRun.LowPart = NextAssignedCluster + AssignedClusters - 1;
+        }
+    }
+    else if (AttrContext->Record.NonResident.AllocatedSize > AllocationSize)
+    {
+        // shrink allocation size
+        ULONG ClustersToFree = ExistingClusters - (AllocationSize / BytesPerCluster);
+        Status = FreeClusters(Vcb, AttrContext, AttrOffset, FileRecord, ClustersToFree);
+    }
+
+    // TODO: is the file compressed, encrypted, or sparse?
+
+    AttrContext->Record.NonResident.AllocatedSize = AllocationSize;
+    AttrContext->Record.NonResident.DataSize = DataSize->QuadPart;
+    AttrContext->Record.NonResident.InitializedSize = DataSize->QuadPart;
+
+    DestinationAttribute->NonResident.AllocatedSize = AllocationSize;
+    DestinationAttribute->NonResident.DataSize = DataSize->QuadPart;
+    DestinationAttribute->NonResident.InitializedSize = DataSize->QuadPart;
+
+    DPRINT("Allocated Size: %I64u\n", DestinationAttribute->NonResident.AllocatedSize);
+
+    return Status;
+}
+
+/**
+* @name SetResidentAttributeDataLength
+* @implemented
+*
+* Called by SetAttributeDataLength() to set the size of a non-resident attribute. Doesn't update the file record.
+*
+* @param Vcb
+* Pointer to a DEVICE_EXTENSION describing the target disk.
+*
+* @param AttrContext
+* PNTFS_ATTR_CONTEXT describing the location of the attribute whose size is being set.
+*
+* @param AttrOffset
+* Offset, from the beginning of the record, of the attribute being sized.
+*
+* @param FileRecord
+* Pointer to a file record containing the attribute to be resized. Must be a complete file record,
+* not just the header.
+*
+* @param DataSize
+* Pointer to a LARGE_INTEGER describing the new size of the attribute's data.
+*
+* @return
+* STATUS_SUCCESS on success;
+* STATUS_INSUFFICIENT_RESOURCES if an allocation fails.
+* STATUS_INVALID_PARAMETER if AttrContext describes a non-resident attribute.
+* STATUS_NOT_IMPLEMENTED if requested to decrease the size of an attribute that isn't the
+* last attribute listed in the file record.
+*
+* @remarks
+* Called by SetAttributeDataLength() and IncreaseMftSize(). Use SetAttributeDataLength() unless you have a good
+* reason to use this. Doesn't update the file record on disk. Doesn't inform the cache controller of changes with
+* any associated files. Synchronization is the callers responsibility.
+*/
+NTSTATUS
+SetResidentAttributeDataLength(PDEVICE_EXTENSION Vcb,
+                               PNTFS_ATTR_CONTEXT AttrContext,
+                               ULONG AttrOffset,
+                               PFILE_RECORD_HEADER FileRecord,
+                               PLARGE_INTEGER DataSize)
+{
+    NTSTATUS Status;
+
+    // find the next attribute
+    ULONG NextAttributeOffset = AttrOffset + AttrContext->Record.Length;
+    PNTFS_ATTR_RECORD NextAttribute = (PNTFS_ATTR_RECORD)((PCHAR)FileRecord + NextAttributeOffset);
+
+    ASSERT(!AttrContext->Record.IsNonResident);
+
+    //NtfsDumpFileAttributes(Vcb, FileRecord);
+
+    // Do we need to increase the data length?
+    if (DataSize->QuadPart > AttrContext->Record.Resident.ValueLength)
+    {
+        // There's usually padding at the end of a record. Do we need to extend past it?
+        ULONG MaxValueLength = AttrContext->Record.Length - AttrContext->Record.Resident.ValueOffset;
+        if (MaxValueLength < DataSize->LowPart)
+        {
+            // If this is the last attribute, we could move the end marker to the very end of the file record
+            MaxValueLength += Vcb->NtfsInfo.BytesPerFileRecord - NextAttributeOffset - (sizeof(ULONG) * 2);
+
+            if (MaxValueLength < DataSize->LowPart || NextAttribute->Type != AttributeEnd)
+            {
+                // convert attribute to non-resident
+                PNTFS_ATTR_RECORD Destination = (PNTFS_ATTR_RECORD)((ULONG_PTR)FileRecord + AttrOffset);
+                LARGE_INTEGER AttribDataSize;
+                PVOID AttribData;
+                ULONG EndAttributeOffset;
+                ULONG LengthWritten;
+
+                DPRINT1("Converting attribute to non-resident.\n");
+
+                AttribDataSize.QuadPart = AttrContext->Record.Resident.ValueLength;
+
+                // Is there existing data we need to back-up?
+                if (AttribDataSize.QuadPart > 0)
+                {
+                    AttribData = ExAllocatePoolWithTag(NonPagedPool, AttribDataSize.QuadPart, TAG_NTFS);
+                    if (AttribData == NULL)
+                    {
+                        DPRINT1("ERROR: Couldn't allocate memory for attribute data. Can't migrate to non-resident!\n");
+                        return STATUS_INSUFFICIENT_RESOURCES;
+                    }
+
+                    // read data to temp buffer
+                    Status = ReadAttribute(Vcb, AttrContext, 0, AttribData, AttribDataSize.QuadPart);
+                    if (!NT_SUCCESS(Status))
+                    {
+                        DPRINT1("ERROR: Unable to read attribute before migrating!\n");
+                        ExFreePoolWithTag(AttribData, TAG_NTFS);
+                        return Status;
+                    }
+                }
+
+                // Start by turning this attribute into a 0-length, non-resident attribute, then enlarge it.
+
+                // Zero out the NonResident structure
+                RtlZeroMemory(&AttrContext->Record.NonResident.LowestVCN,
+                              FIELD_OFFSET(NTFS_ATTR_RECORD, NonResident.CompressedSize) - FIELD_OFFSET(NTFS_ATTR_RECORD, NonResident.LowestVCN));
+                RtlZeroMemory(&Destination->NonResident.LowestVCN,
+                              FIELD_OFFSET(NTFS_ATTR_RECORD, NonResident.CompressedSize) - FIELD_OFFSET(NTFS_ATTR_RECORD, NonResident.LowestVCN));
+
+                // update the mapping pairs offset, which will be 0x40 + length in bytes of the name
+                AttrContext->Record.NonResident.MappingPairsOffset = Destination->NonResident.MappingPairsOffset = 0x40 + (Destination->NameLength * 2);
+
+                // update the end of the file record
+                // calculate position of end markers (1 byte for empty data run)
+                EndAttributeOffset = AttrOffset + AttrContext->Record.NonResident.MappingPairsOffset + 1;
+                EndAttributeOffset = ALIGN_UP_BY(EndAttributeOffset, 8);
+
+                // Update the length
+                Destination->Length = EndAttributeOffset - AttrOffset;
+                AttrContext->Record.Length = Destination->Length;
+
+                // Update the file record end
+                SetFileRecordEnd(FileRecord,
+                                 (PNTFS_ATTR_RECORD)((ULONG_PTR)FileRecord + EndAttributeOffset),
+                                 FILE_RECORD_END);
+
+                // Initialize the MCB, potentially catch an exception
+                _SEH2_TRY
+                {
+                    FsRtlInitializeLargeMcb(&AttrContext->DataRunsMCB, NonPagedPool);
+                }
+                _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER) 
+                {
+                    DPRINT1("Unable to create LargeMcb!\n");
+                    ExFreePoolWithTag(AttribData, TAG_NTFS);
+                    _SEH2_YIELD(return _SEH2_GetExceptionCode());
+                } _SEH2_END;
+
+                // Mark the attribute as non-resident (we wait until after we know the LargeMcb was initialized)
+                AttrContext->Record.IsNonResident = Destination->IsNonResident = 1;
+
+                // Update file record on disk
+                Status = UpdateFileRecord(Vcb, AttrContext->FileMFTIndex, FileRecord);
+                if (!NT_SUCCESS(Status))
+                {
+                    DPRINT1("ERROR: Couldn't update file record to continue migration!\n");
+                    if (AttribDataSize.QuadPart > 0)
+                        ExFreePoolWithTag(AttribData, TAG_NTFS);
+                    return Status;
+                }
+
+                // Now we can treat the attribute as non-resident and enlarge it normally
+                Status = SetNonResidentAttributeDataLength(Vcb, AttrContext, AttrOffset, FileRecord, DataSize);
+                if (!NT_SUCCESS(Status))
+                {
+                    DPRINT1("ERROR: Unable to migrate resident attribute!\n");
+                    if (AttribDataSize.QuadPart > 0)
+                        ExFreePoolWithTag(AttribData, TAG_NTFS);
+                    return Status;
+                }
+
+                // restore the back-up attribute, if we made one
+                if (AttribDataSize.QuadPart > 0)
+                {
+                    Status = WriteAttribute(Vcb, AttrContext, 0, AttribData, AttribDataSize.QuadPart, &LengthWritten);
+                    if (!NT_SUCCESS(Status))
+                    {
+                        DPRINT1("ERROR: Unable to write attribute data to non-resident clusters during migration!\n");
+                        // TODO: Reverse migration so no data is lost
+                        ExFreePoolWithTag(AttribData, TAG_NTFS);
+                        return Status;
+                    }
+
+                    ExFreePoolWithTag(AttribData, TAG_NTFS);
+                }
+            }
+        }
+    }
+    else if (DataSize->LowPart < AttrContext->Record.Resident.ValueLength)
+    {
+        // we need to decrease the length
+        if (NextAttribute->Type != AttributeEnd)
+        {
+            DPRINT1("FIXME: Don't know how to decrease length of resident attribute unless it's the final attribute!\n");
+            return STATUS_NOT_IMPLEMENTED;
+        }
+    }
+
+    // set the new length of the resident attribute (if we didn't migrate it)
+    if (!AttrContext->Record.IsNonResident)
+        InternalSetResidentAttributeLength(AttrContext, FileRecord, AttrOffset, DataSize->LowPart);
+
+    return STATUS_SUCCESS;
+}
+
 ULONG
 ReadAttribute(PDEVICE_EXTENSION Vcb,
               PNTFS_ATTR_CONTEXT Context,
@@ -957,7 +1344,7 @@ ReadFileRecord(PDEVICE_EXTENSION Vcb,
     BytesRead = ReadAttribute(Vcb, Vcb->MFTContext, index * Vcb->NtfsInfo.BytesPerFileRecord, (PCHAR)file, Vcb->NtfsInfo.BytesPerFileRecord);
     if (BytesRead != Vcb->NtfsInfo.BytesPerFileRecord)
     {
-        DPRINT1("ReadFileRecord failed: %I64u read, %u expected\n", BytesRead, Vcb->NtfsInfo.BytesPerFileRecord);
+        DPRINT1("ReadFileRecord failed: %I64u read, %lu expected\n", BytesRead, Vcb->NtfsInfo.BytesPerFileRecord);
         return STATUS_PARTIAL_COPY;
     }
 
@@ -980,7 +1367,8 @@ UpdateFileNameRecord(PDEVICE_EXTENSION Vcb,
                      PUNICODE_STRING FileName,
                      BOOLEAN DirSearch,
                      ULONGLONG NewDataSize,
-                     ULONGLONG NewAllocationSize)
+                     ULONGLONG NewAllocationSize,
+                     BOOLEAN CaseSensitive)
 {
     PFILE_RECORD_HEADER MftRecord;
     PNTFS_ATTR_CONTEXT IndexRootCtx;
@@ -990,7 +1378,14 @@ UpdateFileNameRecord(PDEVICE_EXTENSION Vcb,
     NTSTATUS Status;
     ULONG CurrentEntry = 0;
 
-    DPRINT("UpdateFileNameRecord(%p, %I64d, %wZ, %u, %I64u, %I64u)\n", Vcb, ParentMFTIndex, FileName, DirSearch, NewDataSize, NewAllocationSize);
+    DPRINT("UpdateFileNameRecord(%p, %I64d, %wZ, %s, %I64u, %I64u, %s)\n",
+           Vcb,
+           ParentMFTIndex,
+           FileName,
+           DirSearch ? "TRUE" : "FALSE",
+           NewDataSize,
+           NewAllocationSize,
+           CaseSensitive ? "TRUE" : "FALSE");
 
     MftRecord = ExAllocatePoolWithTag(NonPagedPool,
                                       Vcb->NtfsInfo.BytesPerFileRecord,
@@ -1023,7 +1418,15 @@ UpdateFileNameRecord(PDEVICE_EXTENSION Vcb,
         return STATUS_INSUFFICIENT_RESOURCES;
     }
 
-    ReadAttribute(Vcb, IndexRootCtx, 0, IndexRecord, Vcb->NtfsInfo.BytesPerIndexRecord);
+    Status = ReadAttribute(Vcb, IndexRootCtx, 0, IndexRecord, AttributeDataLength(&IndexRootCtx->Record));
+    if (!NT_SUCCESS(Status))
+    {
+        DPRINT1("ERROR: Failed to read Index Root!\n");
+        ExFreePoolWithTag(IndexRecord, TAG_NTFS);
+        ReleaseAttributeContext(IndexRootCtx);
+        ExFreePoolWithTag(MftRecord, TAG_NTFS);
+    }
+
     IndexRoot = (PINDEX_ROOT_ATTRIBUTE)IndexRecord;
     IndexEntry = (PINDEX_ENTRY_ATTRIBUTE)((PCHAR)&IndexRoot->Header + IndexRoot->Header.FirstEntryOffset);
     // Index root is always resident. 
@@ -1042,7 +1445,20 @@ UpdateFileNameRecord(PDEVICE_EXTENSION Vcb,
                                           &CurrentEntry,
                                           DirSearch,
                                           NewDataSize,
-                                          NewAllocationSize);
+                                          NewAllocationSize,
+                                          CaseSensitive);
+
+    if (Status == STATUS_PENDING)
+    {
+        // we need to write the index root attribute back to disk
+        ULONG LengthWritten;
+        Status = WriteAttribute(Vcb, IndexRootCtx, 0, IndexRecord, AttributeDataLength(&IndexRootCtx->Record), &LengthWritten);
+        if (!NT_SUCCESS(Status))
+        {
+            DPRINT1("ERROR: Couldn't update Index Root!\n");
+        }
+
+    }
 
     ReleaseAttributeContext(IndexRootCtx);
     ExFreePoolWithTag(IndexRecord, TAG_NTFS);
@@ -1068,7 +1484,8 @@ UpdateIndexEntryFileNameSize(PDEVICE_EXTENSION Vcb,
                              PULONG CurrentEntry,
                              BOOLEAN DirSearch,
                              ULONGLONG NewDataSize,
-                             ULONGLONG NewAllocatedSize)
+                             ULONGLONG NewAllocatedSize,
+                             BOOLEAN CaseSensitive)
 {
     NTSTATUS Status;
     ULONG RecordOffset;
@@ -1077,7 +1494,20 @@ UpdateIndexEntryFileNameSize(PDEVICE_EXTENSION Vcb,
     ULONGLONG IndexAllocationSize;
     PINDEX_BUFFER IndexBuffer;
 
-    DPRINT("UpdateIndexEntrySize(%p, %p, %p, %u, %p, %p, %wZ, %u, %u, %u, %I64u, %I64u)\n", Vcb, MftRecord, IndexRecord, IndexBlockSize, FirstEntry, LastEntry, FileName, *StartEntry, *CurrentEntry, DirSearch, NewDataSize, NewAllocatedSize);
+    DPRINT("UpdateIndexEntrySize(%p, %p, %p, %lu, %p, %p, %wZ, %lu, %lu, %s, %I64u, %I64u, %s)\n",
+           Vcb,
+           MftRecord,
+           IndexRecord,
+           IndexBlockSize,
+           FirstEntry,
+           LastEntry,
+           FileName,
+           *StartEntry,
+           *CurrentEntry,
+           DirSearch ? "TRUE" : "FALSE",
+           NewDataSize,
+           NewAllocatedSize,
+           CaseSensitive ? "TRUE" : "FALSE");
 
     // find the index entry responsible for the file we're trying to update
     IndexEntry = FirstEntry;
@@ -1087,7 +1517,7 @@ UpdateIndexEntryFileNameSize(PDEVICE_EXTENSION Vcb,
         if ((IndexEntry->Data.Directory.IndexedFile & NTFS_MFT_MASK) > 0x10 &&
             *CurrentEntry >= *StartEntry &&
             IndexEntry->FileName.NameType != NTFS_FILE_NAME_DOS &&
-            CompareFileName(FileName, IndexEntry, DirSearch))
+            CompareFileName(FileName, IndexEntry, DirSearch, CaseSensitive))
         {
             *StartEntry = *CurrentEntry;
             IndexEntry->FileName.DataSize = NewDataSize;
@@ -1138,7 +1568,19 @@ UpdateIndexEntryFileNameSize(PDEVICE_EXTENSION Vcb,
         LastEntry = (PINDEX_ENTRY_ATTRIBUTE)((ULONG_PTR)&IndexBuffer->Header + IndexBuffer->Header.TotalSizeOfEntries);
         ASSERT(LastEntry <= (PINDEX_ENTRY_ATTRIBUTE)((ULONG_PTR)IndexBuffer + IndexBlockSize));
 
-        Status = UpdateIndexEntryFileNameSize(NULL, NULL, NULL, 0, FirstEntry, LastEntry, FileName, StartEntry, CurrentEntry, DirSearch, NewDataSize, NewAllocatedSize);
+        Status = UpdateIndexEntryFileNameSize(NULL,
+                                              NULL,
+                                              NULL,
+                                              0,
+                                              FirstEntry,
+                                              LastEntry,
+                                              FileName,
+                                              StartEntry,
+                                              CurrentEntry,
+                                              DirSearch,
+                                              NewDataSize,
+                                              NewAllocatedSize,
+                                              CaseSensitive);
         if (Status == STATUS_PENDING)
         {
             // write the index record back to disk
@@ -1262,28 +1704,40 @@ FixupUpdateSequenceArray(PDEVICE_EXTENSION Vcb,
 * @param DeviceExt
 * Pointer to the DEVICE_EXTENSION of the target drive.
 *
+* @param DestinationIndex
+* Pointer to a ULONGLONG which will receive the MFT index where the file record was stored.
+*
+* @param CanWait
+* Boolean indicating if the function is allowed to wait for exclusive access to the master file table.
+* This will only be relevant if the MFT doesn't have any free file records and needs to be enlarged.
+*
 * @return
 * STATUS_SUCCESS on success.
 * STATUS_OBJECT_NAME_NOT_FOUND if we can't find the MFT's $Bitmap or if we weren't able 
 * to read the attribute.
 * STATUS_INSUFFICIENT_RESOURCES if we can't allocate enough memory for a copy of $Bitmap.
-* STATUS_NOT_IMPLEMENTED if we need to increase the size of the MFT.
-* 
+* STATUS_CANT_WAIT if CanWait was FALSE and the function could not get immediate, exclusive access to the MFT.
 */
 NTSTATUS
 AddNewMftEntry(PFILE_RECORD_HEADER FileRecord,
-               PDEVICE_EXTENSION DeviceExt)
+               PDEVICE_EXTENSION DeviceExt,
+               PULONGLONG DestinationIndex,
+               BOOLEAN CanWait)
 {
     NTSTATUS Status = STATUS_SUCCESS;
     ULONGLONG MftIndex;
     RTL_BITMAP Bitmap;
     ULONGLONG BitmapDataSize;
     ULONGLONG AttrBytesRead;
-    PVOID BitmapData;
+    PUCHAR BitmapData;
     ULONG LengthWritten;
+    PNTFS_ATTR_CONTEXT BitmapContext;
+    LARGE_INTEGER BitmapBits;
+    UCHAR SystemReservedBits;
+
+    DPRINT1("AddNewMftEntry(%p, %p, %p, %s)\n", FileRecord, DeviceExt, DestinationIndex, CanWait ? "TRUE" : "FALSE");
 
     // First, we have to read the mft's $Bitmap attribute
-    PNTFS_ATTR_CONTEXT BitmapContext;
     Status = FindAttribute(DeviceExt, DeviceExt->MasterFileTable, AttributeBitmap, L"", 0, &BitmapContext, NULL);
     if (!NT_SUCCESS(Status))
     {
@@ -1311,20 +1765,43 @@ AddNewMftEntry(PFILE_RECORD_HEADER FileRecord,
         return STATUS_OBJECT_NAME_NOT_FOUND;
     }
 
+    // We need to backup the bits for records 0x10 - 0x17 (3rd byte of bitmap) and mark these records
+    // as in-use so we don't assign files to those indices. They're reserved for the system (e.g. ChkDsk).
+    SystemReservedBits = BitmapData[2];
+    BitmapData[2] = 0xff;
+
+    // Calculate bit count
+    BitmapBits.QuadPart = AttributeDataLength(&(DeviceExt->MFTContext->Record)) /
+                          DeviceExt->NtfsInfo.BytesPerFileRecord;
+    if (BitmapBits.HighPart != 0)
+    {
+        DPRINT1("\tFIXME: bitmap sizes beyond 32bits are not yet supported! (Your NTFS volume is too large)\n");
+        ExFreePoolWithTag(BitmapData, TAG_NTFS);
+        ReleaseAttributeContext(BitmapContext);
+        return STATUS_NOT_IMPLEMENTED;
+    }
+
     // convert buffer into bitmap
-    RtlInitializeBitMap(&Bitmap, (PULONG)BitmapData, BitmapDataSize * 8);
+    RtlInitializeBitMap(&Bitmap, (PULONG)BitmapData, BitmapBits.LowPart);
 
     // set next available bit, preferrably after 23rd bit
     MftIndex = RtlFindClearBitsAndSet(&Bitmap, 1, 24);
     if ((LONG)MftIndex == -1)
     {
-        DPRINT1("ERROR: Couldn't find free space in MFT for file record!\n");
+        DPRINT1("Couldn't find free space in MFT for file record, increasing MFT size.\n");
 
         ExFreePoolWithTag(BitmapData, TAG_NTFS);
         ReleaseAttributeContext(BitmapContext);
 
-        // TODO: increase mft size
-        return STATUS_NOT_IMPLEMENTED;
+        // Couldn't find a free record in the MFT, add some blank records and try again
+        Status = IncreaseMftSize(DeviceExt, CanWait);
+        if (!NT_SUCCESS(Status))
+        {
+            DPRINT1("ERROR: Couldn't find space in MFT for file or increase MFT size!\n");
+            return Status;
+        }
+
+        return AddNewMftEntry(FileRecord, DeviceExt, DestinationIndex, CanWait);
     }
 
     DPRINT1("Creating file record at MFT index: %I64u\n", MftIndex);
@@ -1334,6 +1811,9 @@ AddNewMftEntry(PFILE_RECORD_HEADER FileRecord,
 
     // [BitmapData should have been updated via RtlFindClearBitsAndSet()]
 
+    // Restore the system reserved bits
+    BitmapData[2] = SystemReservedBits;
+
     // write the bitmap back to the MFT's $Bitmap attribute
     Status = WriteAttribute(DeviceExt, BitmapContext, 0, BitmapData, BitmapDataSize, &LengthWritten);
     if (!NT_SUCCESS(Status))
@@ -1355,6 +1835,8 @@ AddNewMftEntry(PFILE_RECORD_HEADER FileRecord,
         return Status;
     }
 
+    *DestinationIndex = MftIndex;
+
     ExFreePoolWithTag(BitmapData, TAG_NTFS);
     ReleaseAttributeContext(BitmapContext);
 
@@ -1366,9 +1848,9 @@ AddFixupArray(PDEVICE_EXTENSION Vcb,
               PNTFS_RECORD_HEADER Record)
 {
     USHORT *pShortToFixUp;
-    unsigned int ArrayEntryCount = Record->UsaCount - 1;
-    unsigned int Offset = Vcb->NtfsInfo.BytesPerSector - 2;
-    int i;
+    ULONG ArrayEntryCount = Record->UsaCount - 1;
+    ULONG Offset = Vcb->NtfsInfo.BytesPerSector - 2;
+    ULONG i;
 
     PFIXUP_ARRAY fixupArray = (PFIXUP_ARRAY)((UCHAR*)Record + Record->UsaOffset);
 
@@ -1411,7 +1893,8 @@ ReadLCN(PDEVICE_EXTENSION Vcb,
 BOOLEAN
 CompareFileName(PUNICODE_STRING FileName,
                 PINDEX_ENTRY_ATTRIBUTE IndexEntry,
-                BOOLEAN DirSearch)
+                BOOLEAN DirSearch,
+                BOOLEAN CaseSensitive)
 {
     BOOLEAN Ret, Alloc = FALSE;
     UNICODE_STRING EntryName;
@@ -1423,7 +1906,7 @@ CompareFileName(PUNICODE_STRING FileName,
     if (DirSearch)
     {
         UNICODE_STRING IntFileName;
-        if (IndexEntry->FileName.NameType != NTFS_FILE_NAME_POSIX)
+        if (!CaseSensitive)
         {
             NT_VERIFY(NT_SUCCESS(RtlUpcaseUnicodeString(&IntFileName, FileName, TRUE)));
             Alloc = TRUE;
@@ -1433,7 +1916,7 @@ CompareFileName(PUNICODE_STRING FileName,
             IntFileName = *FileName;
         }
 
-        Ret = FsRtlIsNameInExpression(&IntFileName, &EntryName, (IndexEntry->FileName.NameType != NTFS_FILE_NAME_POSIX), NULL);
+        Ret = FsRtlIsNameInExpression(&IntFileName, &EntryName, !CaseSensitive, NULL);
 
         if (Alloc)
         {
@@ -1444,7 +1927,7 @@ CompareFileName(PUNICODE_STRING FileName,
     }
     else
     {
-        return (RtlCompareUnicodeString(FileName, &EntryName, (IndexEntry->FileName.NameType != NTFS_FILE_NAME_POSIX)) == 0);
+        return (RtlCompareUnicodeString(FileName, &EntryName, !CaseSensitive) == 0);
     }
 }
 
@@ -1484,6 +1967,7 @@ BrowseIndexEntries(PDEVICE_EXTENSION Vcb,
                    PULONG StartEntry,
                    PULONG CurrentEntry,
                    BOOLEAN DirSearch,
+                   BOOLEAN CaseSensitive,
                    ULONGLONG *OutMFTIndex)
 {
     NTSTATUS Status;
@@ -1493,16 +1977,28 @@ BrowseIndexEntries(PDEVICE_EXTENSION Vcb,
     ULONGLONG IndexAllocationSize;
     PINDEX_BUFFER IndexBuffer;
 
-    DPRINT("BrowseIndexEntries(%p, %p, %p, %u, %p, %p, %wZ, %u, %u, %u, %p)\n", Vcb, MftRecord, IndexRecord, IndexBlockSize, FirstEntry, LastEntry, FileName, *StartEntry, *CurrentEntry, DirSearch, OutMFTIndex);
+    DPRINT("BrowseIndexEntries(%p, %p, %p, %lu, %p, %p, %wZ, %lu, %lu, %s, %s, %p)\n",
+           Vcb,
+           MftRecord,
+           IndexRecord,
+           IndexBlockSize,
+           FirstEntry,
+           LastEntry,
+           FileName,
+           *StartEntry,
+           *CurrentEntry,
+           DirSearch ? "TRUE" : "FALSE",
+           CaseSensitive ? "TRUE" : "FALSE",
+           OutMFTIndex);
 
     IndexEntry = FirstEntry;
     while (IndexEntry < LastEntry &&
            !(IndexEntry->Flags & NTFS_INDEX_ENTRY_END))
     {
-        if ((IndexEntry->Data.Directory.IndexedFile & NTFS_MFT_MASK) > 0x10 &&
+        if ((IndexEntry->Data.Directory.IndexedFile & NTFS_MFT_MASK) >= 0x10 &&
             *CurrentEntry >= *StartEntry &&
             IndexEntry->FileName.NameType != NTFS_FILE_NAME_DOS &&
-            CompareFileName(FileName, IndexEntry, DirSearch))
+            CompareFileName(FileName, IndexEntry, DirSearch, CaseSensitive))
         {
             *StartEntry = *CurrentEntry;
             *OutMFTIndex = (IndexEntry->Data.Directory.IndexedFile & NTFS_MFT_MASK);
@@ -1529,7 +2025,7 @@ BrowseIndexEntries(PDEVICE_EXTENSION Vcb,
     Status = FindAttribute(Vcb, MftRecord, AttributeIndexAllocation, L"$I30", 4, &IndexAllocationCtx, NULL);
     if (!NT_SUCCESS(Status))
     {
-        DPRINT("Corrupted filesystem!\n");
+        DPRINT1("Corrupted filesystem!\n");
         return Status;
     }
 
@@ -1551,7 +2047,18 @@ BrowseIndexEntries(PDEVICE_EXTENSION Vcb,
         LastEntry = (PINDEX_ENTRY_ATTRIBUTE)((ULONG_PTR)&IndexBuffer->Header + IndexBuffer->Header.TotalSizeOfEntries);
         ASSERT(LastEntry <= (PINDEX_ENTRY_ATTRIBUTE)((ULONG_PTR)IndexBuffer + IndexBlockSize));
 
-        Status = BrowseIndexEntries(NULL, NULL, NULL, 0, FirstEntry, LastEntry, FileName, StartEntry, CurrentEntry, DirSearch, OutMFTIndex);
+        Status = BrowseIndexEntries(NULL,
+                                    NULL,
+                                    NULL,
+                                    0,
+                                    FirstEntry,
+                                    LastEntry,
+                                    FileName,
+                                    StartEntry,
+                                    CurrentEntry,
+                                    DirSearch,
+                                    CaseSensitive,
+                                    OutMFTIndex);
         if (NT_SUCCESS(Status))
         {
             break;
@@ -1568,6 +2075,7 @@ NtfsFindMftRecord(PDEVICE_EXTENSION Vcb,
                   PUNICODE_STRING FileName,
                   PULONG FirstEntry,
                   BOOLEAN DirSearch,
+                  BOOLEAN CaseSensitive,
                   ULONGLONG *OutMFTIndex)
 {
     PFILE_RECORD_HEADER MftRecord;
@@ -1578,7 +2086,14 @@ NtfsFindMftRecord(PDEVICE_EXTENSION Vcb,
     NTSTATUS Status;
     ULONG CurrentEntry = 0;
 
-    DPRINT("NtfsFindMftRecord(%p, %I64d, %wZ, %u, %u, %p)\n", Vcb, MFTIndex, FileName, *FirstEntry, DirSearch, OutMFTIndex);
+    DPRINT("NtfsFindMftRecord(%p, %I64d, %wZ, %lu, %s, %s, %p)\n",
+           Vcb,
+           MFTIndex,
+           FileName,
+           *FirstEntry,
+           DirSearch ? "TRUE" : "FALSE",
+           CaseSensitive ? "TRUE" : "FALSE",
+           OutMFTIndex);
 
     MftRecord = ExAllocatePoolWithTag(NonPagedPool,
                                       Vcb->NtfsInfo.BytesPerFileRecord,
@@ -1620,7 +2135,18 @@ NtfsFindMftRecord(PDEVICE_EXTENSION Vcb,
 
     DPRINT("IndexRecordSize: %x IndexBlockSize: %x\n", Vcb->NtfsInfo.BytesPerIndexRecord, IndexRoot->SizeOfEntry);
 
-    Status = BrowseIndexEntries(Vcb, MftRecord, IndexRecord, IndexRoot->SizeOfEntry, IndexEntry, IndexEntryEnd, FileName, FirstEntry, &CurrentEntry, DirSearch, OutMFTIndex);
+    Status = BrowseIndexEntries(Vcb,
+                                MftRecord,
+                                IndexRecord,
+                                IndexRoot->SizeOfEntry,
+                                IndexEntry,
+                                IndexEntryEnd,
+                                FileName,
+                                FirstEntry,
+                                &CurrentEntry,
+                                DirSearch,
+                                CaseSensitive,
+                                OutMFTIndex);
 
     ExFreePoolWithTag(IndexRecord, TAG_NTFS);
     ExFreePoolWithTag(MftRecord, TAG_NTFS);
@@ -1631,6 +2157,7 @@ NtfsFindMftRecord(PDEVICE_EXTENSION Vcb,
 NTSTATUS
 NtfsLookupFileAt(PDEVICE_EXTENSION Vcb,
                  PUNICODE_STRING PathName,
+                 BOOLEAN CaseSensitive,
                  PFILE_RECORD_HEADER *FileRecord,
                  PULONGLONG MFTIndex,
                  ULONGLONG CurrentMFTIndex)
@@ -1639,7 +2166,13 @@ NtfsLookupFileAt(PDEVICE_EXTENSION Vcb,
     NTSTATUS Status;
     ULONG FirstEntry = 0;
 
-    DPRINT("NtfsLookupFileAt(%p, %wZ, %p, %I64x)\n", Vcb, PathName, FileRecord, CurrentMFTIndex);
+    DPRINT("NtfsLookupFileAt(%p, %wZ, %s, %p, %p, %I64x)\n",
+           Vcb,
+           PathName,
+           CaseSensitive ? "TRUE" : "FALSE",
+           FileRecord,
+           MFTIndex,
+           CurrentMFTIndex);
 
     FsRtlDissectName(*PathName, &Current, &Remaining);
 
@@ -1647,7 +2180,7 @@ NtfsLookupFileAt(PDEVICE_EXTENSION Vcb,
     {
         DPRINT("Current: %wZ\n", &Current);
 
-        Status = NtfsFindMftRecord(Vcb, CurrentMFTIndex, &Current, &FirstEntry, FALSE, &CurrentMFTIndex);
+        Status = NtfsFindMftRecord(Vcb, CurrentMFTIndex, &Current, &FirstEntry, FALSE, CaseSensitive, &CurrentMFTIndex);
         if (!NT_SUCCESS(Status))
         {
             return Status;
@@ -1682,10 +2215,11 @@ NtfsLookupFileAt(PDEVICE_EXTENSION Vcb,
 NTSTATUS
 NtfsLookupFile(PDEVICE_EXTENSION Vcb,
                PUNICODE_STRING PathName,
+               BOOLEAN CaseSensitive,
                PFILE_RECORD_HEADER *FileRecord,
                PULONGLONG MFTIndex)
 {
-    return NtfsLookupFileAt(Vcb, PathName, FileRecord, MFTIndex, NTFS_FILE_ROOT);
+    return NtfsLookupFileAt(Vcb, PathName, CaseSensitive, FileRecord, MFTIndex, NTFS_FILE_ROOT);
 }
 
 /**
@@ -1734,13 +2268,21 @@ NtfsFindFileAt(PDEVICE_EXTENSION Vcb,
                PULONG FirstEntry,
                PFILE_RECORD_HEADER *FileRecord,
                PULONGLONG MFTIndex,
-               ULONGLONG CurrentMFTIndex)
+               ULONGLONG CurrentMFTIndex,
+               BOOLEAN CaseSensitive)
 {
     NTSTATUS Status;
 
-    DPRINT("NtfsFindFileAt(%p, %wZ, %u, %p, %p, %I64x)\n", Vcb, SearchPattern, *FirstEntry, FileRecord, MFTIndex, CurrentMFTIndex);
+    DPRINT("NtfsFindFileAt(%p, %wZ, %lu, %p, %p, %I64x, %s)\n",
+           Vcb,
+           SearchPattern,
+           *FirstEntry,
+           FileRecord,
+           MFTIndex,
+           CurrentMFTIndex,
+           (CaseSensitive ? "TRUE" : "FALSE"));
 
-    Status = NtfsFindMftRecord(Vcb, CurrentMFTIndex, SearchPattern, FirstEntry, TRUE, &CurrentMFTIndex);
+    Status = NtfsFindMftRecord(Vcb, CurrentMFTIndex, SearchPattern, FirstEntry, TRUE, CaseSensitive, &CurrentMFTIndex);
     if (!NT_SUCCESS(Status))
     {
         DPRINT("NtfsFindFileAt: NtfsFindMftRecord() failed with status 0x%08lx\n", Status);