Ntfs что это на жестком диске windows

Форматирование флешки или системного накопителя — стандартная задача компьютерного пользователя. В современных операционных системах процесс сильно упрощен, поэтому справится даже новичок. Система самостоятельно определяет, какие настройки подходят определенному устройству и какую файловую систему выбрать при форматировании. Так, Windows форматирует системные накопители в NTFS, а флешки превращает в FAT32. Почему так происходит? Чем отличаются эти файловые системы и вообще, зачем диску нужен «формат»? 

Если говорить простым языком, то компьютерный накопитель — это подобие библиотеки, в которой хранятся тысячи книг. Библиотека может быть устроена в виде небольшого стеллажа или многоэтажной полки с лестницей, а также в виде кластеров — огромных помещений с десятками шкафов и сотнями полок. Чтобы найти в таком масштабе интересующую книгу, необходимо ориентироваться по условным опознавательным знакам, буквам или цифрам.

Например, мы посетили библиотеку в поисках произведения «Таинственный остров». По просьбе читателя библиотекарь обращается к каталогу, ищет отдел, в котором хранятся книги с названиями, начинающимися на букву «Т», затем находит шкаф, полку и место, где хранится интересующее читателя издание. Пользуясь такой системой, библиотекарь найдет книгу за считанные секунды, гораздо дольше ему придется доставать и нести ее читателю через весь зал. Аналогично работает и файловая система в накопителе.

Теперь представим, что из библиотеки вывезли все шкафы и полки, а книги теперь лежат на столах, стульях, полу и подоконниках. Произведение Жюля Верна будет практически невозможно найти среди тысяч печатных экземпляров: оно может находиться в любом месте, так как книги разбросаны в неизвестном порядке. При этом, несмотря на беспорядок, библиотека все-таки выполняет свою основную задачу — она хранит книги. Но практической пользы от этого мало: в системе хранения нарушены структура и каталогизация. То же самое происходит, если накопитель лишен какой-либо файловой системы.

Что такое файловая система

Итак, файловая система компьютерного накопителя — это способ организации и хранения файлов на винчестерах, флешках или даже в облаке. И, если диск — это массив кластеров, то файловая система — это инструкция по заполнению этих кластеров информацией.

Например, записывая фотографию на обычный винчестер, компьютер разбивает файл на части. Каждому кусочку файла соответствует ячейка на поверхности магнитной пластины диска. При этом, если любая программа обратится к нужному файлу, то ни она, ни диск не будут знать, что это за файл, где он расположен, как он называется, сколько весит и какие ячейки занимает в накопителе. Единственное, что известно программе — это имя файла, его размер и другие атрибуты, которые она передает файловой системе как условный знак для поиска этого файла в ячейках.

Чтобы понять, кто за что отвечает и кем является, рассмотрим структуру на книгах и библиотеках. Так, в цепочке «пользователь-файл» есть несколько действующих лиц, без которых работа системы невозможна:

  • Накопитель — это библиотека (как здание или организация).
  • Пользователь — это читатель, который пришел в библиотеку за произведением Жюля Верна.
  • Файл — это книга с понятным названием (атрибутом) или другим условным опознавательным знаком, например, упомянутый выше «Таинственный остров».
  • Драйвер файловой системы — это библиотекарь, который выступает в роли посредника или проводника между читателем и книгой. Или между пользователем (компьютером, операционной системой) и файлом (ячейками с информацией в микросхемах памяти или на магнитных пластинах).
  • Файловая система — порядок, в соответствии с которым в библиотеке расставлены книги, а также каталог, с помощью которого специалист находит книги. Системы бывают разные: книги можно расставить по росту, цвету обложки, жанру, году выпуска или названию в алфавитном порядке. На диске файловая система отвечает за организацию файлов.

Дисковая система — это тоже библиотека. Вместо больших помещений здесь используются компактные корпуса накопителей, а в качестве полок с книгами выступают микросхемы памяти в твердотельных накопителях или магнитные пластины классических винчестеров. Система каталогизации библиотеки — это файловая система компьютера. Как и способы сортировки книг в библиотеке, компьютерные файловые системы делятся на несколько типов. Самые распространенные среди компьютеров на ОС Windows — это NTFS и FAT32.

NTFS — New Technology File System

Мы разобрались, что такое файловая система и для чего она нужна компьютерным дискам. Основываясь на полученных примерах, можно легко разобраться в том, как работают разные файловые системы, и чем они отличаются. Например, NTFS.

NTFS — фирменная файловая система Microsoft, которую разработчики начали внедрять в операционную систему Windows, начиная с версии NT 3.1. Несмотря на байки о ненадежности и низкой отказоустойчивости этой системы, NTFS считается самым лучшим и удачным решением для работы актуальных операционных систем Windows. Конечно, как и любая другая система, NTFS не лишена недостатков — это слишком сложное устройство ФС, особенно по современным меркам. Ведь известно — чем сложнее устройство, тем больше в нем уязвимостей.

Структура и фрагментация

Файловая система NTFS делит пространство накопителя на кластеры — блоки, размером от 512 байт до 64 КБ. По умолчанию Windows делит блоки по 4 КБ каждый.

Способ организации файлового пространства на диске с NTFS подразумевает наличие специального раздела, в котором ФС хранит сервисные данные о своей работе. А именно, ведет некий каталог, в котором записываются различные данные о файлах и разделах. Это раздел MFT (Master File Table) — свободное пространство с метафайлом, под который система выделяет 12% от общего объема.

MFT является динамическим разделом — по мере накопления информации на диске, он может сокращаться, чтобы освободить место под пользовательские файлы. Однако при первом же свободном гигабайте на диске, раздел MFT снова заберет свое «законное» место, при этом новая часть метафайла может фрагментироваться и оказаться уже не в начале диска, а в конце или в середине. Отсюда существует распространенная проблема фрагментации файловой системы, когда части каталогов разбросаны по всему диску. Тогда, чтобы найти какой-либо файл, диск судорожно ищет их по всей поверхности, отсюда снижение скорости доступа и общей производительности компьютера. Фрагментация — не самая сильная сторона NTFS.

Файлы и каталоги

Организация данных в этой ФС имеет структуру бинарного дерева: каждый элемент в системе обрабатывается не иерархически, а через бинарные запросы. Например, чтобы найти файл с именем «К» среди тысячи других файлов, система делит каталог на две части и начинает поиск с середины. Например, узнает, в какой части необходимо искать данный файл, если за середину каталога принят файл с названием «Т»? В таком случае система ответит — ищите среди тех файлов, которые идут до файла с именем «Т». То есть, имея отсортированный по алфавиту каталог, система понимает, что файл с необходимым именем находится в одной из двух частей, и время на поиск файла сокращается в два раза — это улучшает скорость работы с мелкими одиночными файлами.

Все файлы в этой системе существуют в виде потоков. Фактически, для того, чтобы превратить блоки с данными в единый файл, этой ФС необходим только файл с метаданными. Это своего рода инструкция по сборке файлов из кусочков данных, которые хранятся в ячейках по всей поверхности накопителя. Благодаря гибкой файловой структуре, объекты NTFS могут принимать множество дополнительных свойств. Например, содержать в названии до 65535 различных символов Unicode. При этом максимальная длина имени файла достигает 255 символов.

Журналирование

Современные операционные системы работают на базе журналируемых файловых систем. Это необходимо для того, чтобы в случае системного сбоя и аварийного завершения работы (вынули вилку питания ПК из розетки) файловая система компьютера смогла восстановиться до последнего рабочего состояния без потери файлов.

В журналируемой файловой системе работа с данными происходит по принципу транзакций — действие совершается полностью или не совершается совсем. Например, при записи системного файла на диск, компьютер делает пометки в метафайл в разделе MTF и ведет мини-журнал процесса копирования до тех пор, пока файл полностью не запишется в необходимый раздел диска. Если устройство перезагрузится во время записи, то при следующем включении система обратится к журналу, узнает о совершенных и несовершенных транзакциях и оставит существовать только те, которые помечены как завершенные. Остальные транзакции будет вычеркнуты, а файлы удалены или возвращены на место.

Как правило, такая система работает наиболее эффективно только с системными файлами, тогда как пользовательские данные могут повредиться или исчезнуть при сбое. Работу журналирования можно проверить с помощью контрольных точек восстановления — компьютер периодически создает слепки состояния системы, по которым позже может восстановиться до этих состояний.

Шифрование

Для защиты данных на компьютере используется шифрование. Это не просто защита компьютера паролем, а также раздача прав для доступа к файлам, что довольно легко вскрыть, взломать и просто обойти с помощью общедоступных инструкций и софта.

Шифрование — это отдельная надстройка над файловой системой компьютера, которая позволяет закрыть пользовательские данные от посторонних глаз практически на аппаратном уровне. В таком случае защищенные файлы нельзя будет просмотреть на другом компьютере, а также после смены материнской платы или операционной системы. Это можно сделать с помощью NTFS — система создает ключи и сертификаты, актуальные только для той сборки и системы, на которой было подключено это шифрование.

Файловая система NTFS также отличается:

  • Поддержкой больших томов и файлов — до 8 ПБ;
  • Несколькими уровнями безопасности, в том числе, поддержкой шифрования;
  • Распределением прав доступа к файлам;
  • Возможностью сжатия;
  • Поддержкой до 4 294 967 295 (232−1) файлов.

Вывод: система NTFS «заточена» под работу с операционной системой, а также для накопителей с большим объемом и несколькими разделами.

FAT32 — File Allocation Table

Обновленная файловая система пришла на смену устаревшей FAT16. Ее также разработали специалисты Microsoft, но, в отличие от NTFS, она распространяется в виде открытого исходного кода. Поэтому разработчики любого софта могут беспрепятственно компилировать и внедрять драйвер в свое ПО. Например, поддержка FAT32 есть не только в «родной» операционной системе, но и в любой другой — linux, MacOS, Android, даже в таких проприетарных системах, как iOS.

В ранних версиях ОС Windows файловая система FAT32 даже использовалась в качестве основной ФС для системного раздела. Но позже разработчики отказались от этого решения в пользу новой и прогрессивной NTFS. Впрочем, несмотря на некоторые особенности FAT32, эта ФС все еще повсеместно используется во флешках и картах памяти.

Проще некуда

Файловая система FAT32 — это автомат Калашникова. Она максимально упрощена:.Здесь нет продвинутых систем безопасности и шифрования, система не умеет журналировать свою работу. Это частично сказывается на производительности — в некоторых случаях скорость чтения или записи может быть выше, чем у более новой и сложной NTFS. Правда, это сильно зависит от условий работы — например, от количества обрабатываемых файлов. Так, работа с массивами мелких файлов может стать настоящим испытанием для накопителя, отформатированного в этой файловой системе.

Впрочем, такие задания редко выполняют на тех накопителях, которые используют FAT32. Обычно это внешние устройства с небольшим объемом. Более того, файловая система не умеет работать с объемными разделами. Например, штатные средства ОС Windows не позволяют создавать на диске с FAT32 разделы, объем которых превышает 32 ГБ. К этим недостаткам относятся и ограничения по максимальному размеру файла. Максимальный размер файла, который запоминает накопитель, составляет 4 ГБ.

Все это, конечно же, влияет на популярность файловой системы и ее удобство. Особенно заметны недостатки устаревшей системы стали после того, как почти у каждого пользователя в арсенале появились флешки с объемом от 64 ГБ — FAT32 такому устройству не к лицу.

Структура

Еще больше красок в устаревание вносит древняя структура: файлы в FAT32 хранятся иерархически, а не в виде бинарного дерева, где каждый отдельный объект может быть доступен независимо от остальных. Если бы такая система использовалась в обычной библиотеке, то поиск одной книги мог бы растянуться на несколько часов: чтобы найти книгу с буквой «Ц» в названии, библиотекарю придется достать все книги с полочек по очереди, начиная с экземпляров на «А», и только после этого взять нужную. Любопытно представить, как бы работала в таком режиме Научная библиотека МГУ, где на физических и виртуальных полках хранится более 10 миллионов экземпляров.

Несмотря на перечисленные особенности, FAT32 все еще неплохо справляется со своими задачами. Например, отсутствие журналирования идет на пользу накопителям, которые быстро изнашиваются от частых перезаписей ячеек. К тому же, работа с объемными файлами и разделами на обычной флешке мало кого интересует. Как правило, они «переносят» легковесные офисные файлы, фотографии, короткие видеоматериалы и установочные файлы программ. Вряд ли кто-то попытается загружать образ фильма в формате Blu-ray на флешку: для этого больше подойдет внешний жесткий диск или твердотельный накопитель с большим объемом.

Вывод: появление флешек с большим объемом внесло коррективы в существование FAT32. Однако на рынке все еще преобладают устройства с объемом не более 32 ГБ — этот формат FAT32 еще тянет.

Практичность превыше всего

Большая и сложная NTFS была разработана еще в 1990-х годах. Несмотря на это, файловая система здравствует до сих пор и спокойно переваривает все современные ОС от Microsoft. Конечно, фирменная технология из Редмонда не панацея: если отказаться от «окон» на компьютере, то и NTFS сразу станет ненужной. Правда, для этого придется смириться с Linux на борту или же переехать на платформу Apple — там, между прочим, используется совсем новая APFS, которую яблочные разработчики представили всего несколько лет назад.

Что касается неоднозначной ситуации с FAT32, то, скорее всего, файловая система уже находится на закате популярности. Специалисты пытаются заменить неактуальную файловую систему более удобными и гибкими EXT. Эти системы имеют открытый исходный код и используются в Unix подобных ОС. Драйверы для этих файловых систем легко портируются под любые операционные системы, поэтому такой накопитель поддерживается даже в актуальной Windows 10, достаточно установить распространенный пакет драйверов.

Вывод: если выбирать файловую систему, то лучше ориентироваться на практичность. Для серьезных задач и под системные нужды обязательно выделять накопитель с NTFS на борту. В то же время, для флешки с маленьким объемом будет достаточно и FAT32 — эта ФС широко поддерживается всеми возможными устройствами. Если же пользователь ставит повышенные требования к системе хранения и обработке файлов — добро пожаловать в мир ZFS.

Это целая система внутри системы, где организация файлов в дисковом пространстве происходит по другим законам. Например, при записи информации, ZFS пишет новые данные в новые блоки, а старые оставляет «жить» до того момента, пока не подтвердит, что свежие данные записаны и готовы к работе. Это необходимо для платформ с уклоном в отказоустойчивость, хотя вряд ли пригодится домашнему юзеру. Чтобы файловая система работала как надо, необходимо иметь двойной запас свободного места на диске: для старых данных и следующего потока новых данных. Поэтому ZFS чаще используют в системах хранения данных с большим объемом. Но это уже совсем другая история.

Операционные системы Microsoft семейства Windows NT нельзя представить без файловой системы NTFS — одной из самых сложных и удачных из существующих на данный момент файловых систем. Данная статья расскажет вам, в чем особенности и недостатки этой системы, на каких принципах основана организация информации, и как поддерживать систему в стабильном состоянии, какие возможности предлагает NTFS и как их можно использовать обычному пользователю.

Часть 1. Физическая структура NTFS

Начнем с общих фактов. Раздел NTFS, теоретически, может быть почти какого угодно размера. Предел, конечно, есть, но я даже не буду указывать его, так как его с запасом хватит на последующие сто лет развития вычислительной техники — при любых темпах роста. Как обстоит с этим дело на практике? Почти так же. Максимальный размер раздела NTFS в данный момент ограничен лишь размерами жестких дисков. NT4, правда, будет испытывать проблемы при попытке установки на раздел, если хоть какая-нибудь его часть отступает более чем на 8 Гб от физического начала диска, но эта проблема касается лишь загрузочного раздела.

Лирическое отступление. Метод инсталляции NT4.0 на пустой диск довольно оригинален и может навести на неправильные мысли о возможностях NTFS. Если вы укажете программе установки, что желаете отформатировать диск в NTFS, максимальный размер, который она вам предложит, будет всего 4 Гб. Почему так мало, если размер раздела NTFS на самом деле практически неограничен? Дело в том, что установочная секция просто не знает этой файловой системы :) Программа установки форматирует этот диск в обычный FAT, максимальный размер которого в NT составляет 4 Гбайт (с использованием не совсем стандартного огромного кластера 64 Кбайта), и на этот FAT устанавливает NT. А вот уже в процессе первой загрузки самой операционной системы (еще в установочной фазе) производится быстрое преобразование раздела в NTFS; так что пользователь ничего и не замечает, кроме странного «ограничения» на размер NTFS при установке. :)

Структура раздела — общий взгляд

Как и любая другая система, NTFS делит все полезное место на кластеры — блоки данных, используемые единовременно. NTFS поддерживает почти любые размеры кластеров — от 512 байт до 64 Кбайт, неким стандартом же считается кластер размером 4 Кбайт. Никаких аномалий кластерной структуры NTFS не имеет, поэтому на эту, в общем-то, довольно банальную тему, сказать особо нечего.

Диск NTFS условно делится на две части. Первые 12% диска отводятся под так называемую MFT зону — пространство, в которое растет метафайл MFT (об этом ниже). Запись каких-либо данных в эту область невозможна. MFT-зона всегда держится пустой — это делается для того, чтобы самый главный, служебный файл (MFT) не фрагментировался при своем росте. Остальные 88% диска представляют собой обычное пространство для хранения файлов.

Свободное место диска, однако, включает в себя всё физически свободное место — незаполненные куски MFT-зоны туда тоже включаются. Механизм использования MFT-зоны таков: когда файлы уже нельзя записывать в обычное пространство, MFT-зона просто сокращается (в текущих версиях операционных систем ровно в два раза), освобождая таким образом место для записи файлов. При освобождении места в обычной области MFT зона может снова расширится. При этом не исключена ситуация, когда в этой зоне остались и обычные файлы: никакой аномалии тут нет. Что ж, система старалась оставить её свободной, но ничего не получилось. Жизнь продолжается… Метафайл MFT все-таки может фрагментироваться, хоть это и было бы нежелательно.

MFT и его структура

Файловая система NTFS представляет собой выдающееся достижение структуризации: каждый элемент системы представляет собой файл — даже служебная информация. Самый главный файл на NTFS называется MFT, или Master File Table — общая таблица файлов. Именно он размещается в MFT зоне и представляет собой централизованный каталог всех остальных файлов диска, и, как не парадоксально, себя самого. MFT поделен на записи фиксированного размера (обычно 1 Кбайт), и каждая запись соответствует какому либо файлу (в общем смысле этого слова). Первые 16 файлов носят служебный характер и недоступны операционной системе — они называются метафайлами, причем самый первый метафайл — сам MFT. Эти первые 16 элементов MFT — единственная часть диска, имеющая фиксированное положение. Интересно, что вторая копия первых трех записей, для надежности — они очень важны — хранится ровно посередине диска. Остальной MFT-файл может располагаться, как и любой другой файл, в произвольных местах диска — восстановить его положение можно с помощью его самого, «зацепившись» за самую основу — за первый элемент MFT.

Метафайлы

Первые 16 файлов NTFS (метафайлы) носят служебный характер. Каждый из них отвечает за какой-либо аспект работы системы. Преимущество настолько модульного подхода заключается в поразительной гибкости — например, на FAT-е физическое повреждение в самой области FAT фатально для функционирования всего диска, а NTFS может сместить, даже фрагментировать по диску, все свои служебные области, обойдя любые неисправности поверхности — кроме первых 16 элементов MFT.

Метафайлы находятся корневом каталоге NTFS диска — они начинаются с символа имени «$», хотя получить какую-либо информацию о них стандартными средствами сложно. Любопытно, что и для этих файлов указан вполне реальный размер — можно узнать, например, сколько операционная система тратит на каталогизацию всего вашего диска, посмотрев размер файла $MFT. В следующей таблице приведены используемые в данный момент метафайлы и их назначение.

$MFT сам MFT
$MFTmirr копия первых 16 записей MFT, размещенная посередине диска
$LogFile файл поддержки журналирования (см. ниже)
$Volume служебная информация — метка тома, версия файловой системы, т. д.
$AttrDef список стандартных атрибутов файлов на томе
$. корневой каталог
$Bitmap карта свободного места тома
$Boot загрузочный сектор (если раздел загрузочный)
$Quota файл, в котором записаны права пользователей на использование дискового пространства (начал работать лишь в NT5)
$Upcase файл — таблица соответствия заглавных и прописных букв в имен файлов на текущем томе. Нужен в основном потому, что в NTFS имена файлов записываются в Unicode, что составляет 65 тысяч различных символов, искать большие и малые эквиваленты которых очень нетривиально.

Файлы и потоки

Итак, у системы есть файлы — и ничего кроме файлов. Что включает в себя это понятие на NTFS?

  • Прежде всего, обязательный элемент — запись в MFT, ведь, как было сказано ранее, все файлы диска упоминаются в MFT. В этом месте хранится вся информация о файле, за исключением собственно данных. Имя файла, размер, положение на диске отдельных фрагментов, и т. д. Если для информации не хватает одной записи MFT, то используются несколько, причем не обязательно подряд.
  • Опциональный элемент — потоки данных файла. Может показаться странным определение «опциональный», но, тем не менее, ничего странного тут нет. Во-первых, файл может не иметь данных — в таком случае на него не расходуется свободное место самого диска. Во-вторых, файл может иметь не очень большой размер. Тогда идет в ход довольно удачное решение: данные файла хранятся прямо в MFT, в оставшемся от основных данных месте в пределах одной записи MFT. Файлы, занимающие сотни байт, обычно не имеют своего «физического» воплощения в основной файловой области — все данные такого файла хранятся в одном месте — в MFT.

Довольно интересно обстоит дело и с данными файла. Каждый файл на NTFS, в общем-то, имеет несколько абстрактное строение — у него нет как таковых данных, а есть потоки (streams). Один из потоков и носит привычный нам смысл — данные файла. Но большинство атрибутов файла — тоже потоки! Таким образом, получается, что базовая сущность у файла только одна — номер в MFT, а всё остальное опционально. Данная абстракция может использоваться для создания довольно удобных вещей — например, файлу можно «прилепить» еще один поток, записав в него любые данные — например, информацию об авторе и содержании файла, как это сделано в Windows 2000 (самая правая закладка в свойствах файла, просматриваемых из проводника). Интересно, что эти дополнительные потоки не видны стандартными средствами: наблюдаемый размер файла — это лишь размер основного потока, который содержит традиционные данные. Можно, к примеру, иметь файл нулевой длинны, при стирании которого освободится 1 Гбайт свободного места — просто потому, что какая-нибудь хитрая программа или технология прилепила в нему дополнительный поток (альтернативные данные) гигабайтового размера. Но на самом деле в текущий момент потоки практически не используются, так что опасаться подобных ситуаций не следует, хотя гипотетически они возможны. Просто имейте в виду, что файл на NTFS — это более глубокое и глобальное понятие, чем можно себе вообразить просто просматривая каталоги диска. Ну и напоследок: имя файла может содержать любые символы, включая полый набор национальных алфавитов, так как данные представлены в Unicode — 16-битном представлении, которое дает 65535 разных символов. Максимальная длина имени файла — 255 символов.

Каталоги

Каталог на NTFS представляет собой специфический файл, хранящий ссылки на другие файлы и каталоги, создавая иерархическое строение данных на диске. Файл каталога поделен на блоки, каждый из которых содержит имя файла, базовые атрибуты и ссылку на элемент MFT, который уже предоставляет полную информацию об элементе каталога. Внутренняя структура каталога представляет собой бинарное дерево. Вот что это означает: для поиска файла с данным именем в линейном каталоге, таком, например, как у FAT-а, операционной системе приходится просматривать все элементы каталога, пока она не найдет нужный. Бинарное же дерево располагает имена файлов таким образом, чтобы поиск файла осуществлялся более быстрым способом — с помощью получения двухзначных ответов на вопросы о положении файла. Вопрос, на который бинарное дерево способно дать ответ, таков: в какой группе, относительно данного элемента, находится искомое имя — выше или ниже? Мы начинаем с такого вопроса к среднему элементу, и каждый ответ сужает зону поиска в среднем в два раза. Файлы, скажем, просто отсортированы по алфавиту, и ответ на вопрос осуществляется очевидным способом — сравнением начальных букв. Область поиска, суженная в два раза, начинает исследоваться аналогичным образом, начиная опять же со среднего элемента.

Вывод — для поиска одного файла среди 1000, например, FAT придется осуществить в среднем 500 сравнений (наиболее вероятно, что файл будет найден на середине поиска), а системе на основе дерева — всего около 12-ти (2^10 = 1024). Экономия времени поиска налицо. Не стоит, однако думать, что в традиционных системах (FAT) всё так запущено: во-первых, поддержание списка файлов в виде бинарного дерева довольно трудоемко, а во-вторых — даже FAT в исполнении современной системы (Windows2000 или Windows98) использует сходную оптимизацию поиска. Это просто еще один факт в вашу копилку знаний. Хочется также развеять распространенное заблуждение (которое я сам разделял совсем еще недавно) о том, что добавлять файл в каталог в виде дерева труднее, чем в линейный каталог: это достаточно сравнимые по времени операции — дело в том, что для того, чтобы добавить файл в каталог, нужно сначала убедится, что файла с таким именем там еще нет :) — и вот тут-то в линейной системе у нас будут трудности с поиском файла, описанные выше, которые с лихвой компенсируют саму простоту добавления файла в каталог.

Какую информацию можно получить, просто прочитав файл каталога? Ровно то, что выдает команда dir. Для выполнения простейшей навигации по диску не нужно лазить в MFT за каждым файлом, надо лишь читать самую общую информацию о файлах из файлов каталогов. Главный каталог диска — корневой — ничем не отличается об обычных каталогов, кроме специальной ссылки на него из начала метафайла MFT.

Журналирование

NTFS — отказоустойчивая система, которая вполне может привести себя в корректное состояние при практически любых реальных сбоях. Любая современная файловая система основана на таком понятии, как транзакция — действие, совершаемое целиком и корректно или не совершаемое вообще. У NTFS просто не бывает промежуточных (ошибочных или некорректных) состояний — квант изменения данных не может быть поделен на до и после сбоя, принося разрушения и путаницу — он либо совершен, либо отменен.

Пример 1: осуществляется запись данных на диск. Вдруг выясняется, что в то место, куда мы только что решили записать очередную порцию данных, писать не удалось — физическое повреждение поверхности. Поведение NTFS в этом случае довольно логично: транзакция записи откатывается целиком — система осознает, что запись не произведена. Место помечается как сбойное, а данные записываются в другое место — начинается новая транзакция.

Пример 2: более сложный случай — идет запись данных на диск. Вдруг, бах — отключается питание и система перезагружается. На какой фазе остановилась запись, где есть данные, а где чушь? На помощь приходит другой механизм системы — журнал транзакций. Дело в том, что система, осознав свое желание писать на диск, пометила в метафайле $LogFile это свое состояние. При перезагрузке это файл изучается на предмет наличия незавершенных транзакций, которые были прерваны аварией и результат которых непредсказуем — все эти транзакции отменяются: место, в которое осуществлялась запись, помечается снова как свободное, индексы и элементы MFT приводятся в с состояние, в котором они были до сбоя, и система в целом остается стабильна. Ну а если ошибка произошла при записи в журнал? Тоже ничего страшного: транзакция либо еще и не начиналась (идет только попытка записать намерения её произвести), либо уже закончилась — то есть идет попытка записать, что транзакция на самом деле уже выполнена. В последнем случае при следующей загрузке система сама вполне разберется, что на самом деле всё и так записано корректно, и не обратит внимания на «незаконченную» транзакцию.

И все-таки помните, что журналирование — не абсолютная панацея, а лишь средство существенно сократить число ошибок и сбоев системы. Вряд ли рядовой пользователь NTFS хоть когда-нибудь заметит ошибку системы или вынужден будет запускать chkdsk — опыт показывает, что NTFS восстанавливается в полностью корректное состояние даже при сбоях в очень загруженные дисковой активностью моменты. Вы можете даже оптимизировать диск и в самый разгар этого процесса нажать reset — вероятность потерь данных даже в этом случае будет очень низка. Важно понимать, однако, что система восстановления NTFS гарантирует корректность файловой системы, а не ваших данных. Если вы производили запись на диск и получили аварию — ваши данные могут и не записаться. Чудес не бывает.

Сжатие

Файлы NTFS имеют один довольно полезный атрибут — «сжатый». Дело в том, что NTFS имеет встроенную поддержку сжатия дисков — то, для чего раньше приходилось использовать Stacker или DoubleSpace. Любой файл или каталог в индивидуальном порядке может хранится на диске в сжатом виде — этот процесс совершенно прозрачен для приложений. Сжатие файлов имеет очень высокую скорость и только одно большое отрицательное свойство — огромная виртуальная фрагментация сжатых файлов, которая, правда, никому особо не мешает. Сжатие осуществляется блоками по 16 кластеров и использует так называемые «виртуальные кластеры» — опять же предельно гибкое решение, позволяющее добиться интересных эффектов — например, половина файла может быть сжата, а половина — нет. Это достигается благодаря тому, что хранение информации о компрессированности определенных фрагментов очень похоже на обычную фрагментацию файлов: например, типичная запись физической раскладки для реального, несжатого, файла:

кластеры файла с 1 по 43-й хранятся в кластерах диска начиная с 400-го

кластеры файла с 44 по 52-й хранятся в кластерах диска начиная с 8530-го…

Физическая раскладка типичного сжатого файла:

кластеры файла с 1 по 9-й хранятся в кластерах диска начиная с 400-го

кластеры файла с 10 по 16-й нигде не хранятся

кластеры файла с 17 по 18-й хранятся в кластерах диска начиная с 409-го

кластеры файла с 19 по 36-й нигде не хранятся

Видно, что сжатый файл имеет «виртуальные» кластеры, реальной информации в которых нет. Как только система видит такие виртуальные кластеры, она тут же понимает, что данные предыдущего блока, кратного 16-ти, должны быть разжаты, а получившиеся данные как раз заполнят виртуальные кластеры — вот, по сути, и весь алгоритм.

Безопасность

NTFS содержит множество средств разграничения прав объектов — есть мнение, что это самая совершенная файловая система из всех ныне существующих. В теории это, без сомнения, так, но в текущих реализациях, к сожалению, система прав достаточно далека от идеала и представляет собой хоть и жесткий, но не всегда логичный набор характеристик. Права, назначаемые любому объекту и однозначно соблюдаемые системой, эволюционируют — крупные изменения и дополнения прав осуществлялись уже несколько раз и к Windows 2000 все-таки они пришли к достаточно разумному набору.

Права файловой системы NTFS неразрывно связаны с самой системой — то есть они, вообще говоря, необязательны к соблюдению другой системой, если ей дать физический доступ к диску. Для предотвращения физического доступа в Windows2000 (NT5) всё же ввели стандартную возможность — об этом см. ниже. Система прав в своем текущем состоянии достаточно сложна, и я сомневаюсь, что смогу сказать широкому читателю что-нибудь интересное и полезное ему в обычной жизни. Если вас интересует эта тема — вы найдете множество книг по сетевой архитектуре NT, в которых это описано более чем подробно.

На этом описание строение файловой системы можно закончить, осталось описать лишь некоторое количество просто практичных или оригинальных вещей.

Hard Links

Эта штука была в NTFS с незапамятных времен, но использовалась очень редко — и тем не менее: Hard Link — это когда один и тот же файл имеет два имени (несколько указателей файла-каталога или разных каталогов указывают на одну и ту же MFT запись). Допустим, один и тот же файл имеет имена 1.txt и 2.txt: если пользователь сотрет файл 1, останется файл 2. Если сотрет 2 — останется файл 1, то есть оба имени, с момента создания, совершенно равноправны. Файл физически стирается лишь тогда, когда будет удалено его последнее имя.

Symbolic Links (NT5)

Гораздо более практичная возможность, позволяющая делать виртуальные каталоги — ровно так же, как и виртуальные диски командой subst в DOSе. Применения достаточно разнообразны: во-первых, упрощение системы каталогов. Если вам не нравится каталог Documents and settingsAdministratorDocuments, вы можете прилинковать его в корневой каталог — система будет по прежнему общаться с каталогом с дремучим путем, а вы — с гораздо более коротким именем, полностью ему эквивалентным. Для создания таких связей можно воспользоваться программой junction (junction.zip, 15 Кб), которую написал известный специалист Mark Russinovich. Программа работает только в NT5 (Windows 2000), как и сама возможность.

Для удаления связи можно воспользоваться стандартной командой rd.
ВНИМАНИЕ: Попытка уделения связи с помощью проводника или других файловых менеджеров, не понимающих виртуальную природу каталога (например, FAR), приведет к удалению данных, на которые ссылается ссылка! Будьте осторожны.

Шифрование (NT5)

Полезная возможность для людей, которые беспокоятся за свои секреты — каждый файл или каталог может также быть зашифрован, что не даст возможность прочесть его другой инсталляцией NT. В сочетании со стандартным и практически непрошибаемым паролем на загрузку самой системы, эта возможность обеспечивает достаточную для большинства применений безопасность избранных вами важных данных.Часть 2. Особенности дефрагментации NTFS

Вернемся к одному достаточно интересному и важному моменту — фрагментации и дефрагментации NTFS. Дело в том, что ситуация, сложившаяся с этими двумя понятиями в настоящий момент, никак не может быть названа удовлетворительной. В самом начале утверждалось, что NTFS не подвержена фрагментации файлов. Это оказалось не совсем так, и утверждение сменили — NTFS препятствует фрагментации. Оказалось, что и это не совсем так. То есть она, конечно, препятствует, но толк от этого близок к нулю… Сейчас уже понятно, что NTFS — система, которая как никакая другая предрасположена к фрагментации, что бы ни утверждалось официально. Единственное что — логически она не очень от этого страдает. Все внутренние структуры построены таким образом, что фрагментация не мешает быстро находить фрагменты данных. Но от физического последствия фрагментации — лишних движений головок — она, конечно, не спасает. И поэтому — вперед и с песней.

К истокам проблемы

Как известно, система сильнее всего фрагментирует файлы когда свободное место кончается, когда приходится использовать мелкие дырки, оставшиеся от других файлов. Тут возникает первое свойство NTFS, которое прямо способствует серьезной фрагментации.

Диск NTFS поделен на две зоны. В начала диска идет MFT зона — зона, куда растет MFT, Master File Table. Зона занимает минимум 12% диска, и запись данных в эту зону невозможна. Это сделано для того, чтобы не фрагментировался хотя бы MFT. Но когда весь остальной диск заполняется — зона сокращается ровно в два раза :). И так далее. Таким образом мы имеем не один заход окончания диска, а несколько. В результате если NTFS работает при диске, заполненном на около 90% — фрагментация растет как бешенная.

Попутное следствие — диск, заполненный более чем на 88%, дефрагментировать почти невозможно — даже API дефрагментации не может перемещать данные в MFT зону. Может оказаться так, что у нас не будет свободного места для маневра.

Далее. NTFS работает себе и работает, и всё таки фрагментируется — даже в том случае, если свободное место далеко от истощения. Этому способствует странный алгоритм нахождения свободного места для записи файлов — второе серьезное упущение. Алгоритм действий при любой записи такой: берется какой-то определенный объем диска и заполняется файлом до упора. Причем по очень интересному алгоритму: сначала заполняются большие дырки, потом маленькие. Т.е. типичное распределение фрагментов файла по размеру на фрагментированной NTFS выглядит так (размеры фрагментов):

16 — 16 — 16 — 16 — 16 — [скачек назад] — 15 — 15 — 15 — [назад] — 14 — 14 — 14 …. 1 — 1 — 1 -1 — 1…

Так процесс идет до самых мелких дырок в 1 кластер, несмотря на то, что на диске наверняка есть и гораздо более большие куски свободного места.

Вспомните сжатые файлы — при активной перезаписи больших объемов сжатой информации на NTFS образуется гигантское количество «дырок» из-за перераспределения на диске сжатых объемов — если какой-либо участок файла стал сжиматься лучше или хуже, его приходится либо изымать из непрерывной цепочки и размещать в другом месте, либо стягивать в объеме, оставляя за собой дырку.

Смысл в сего этого вступления в пояснении того простого факта, что никак нельзя сказать, что NTFS препятствует фрагментации файлов. Наоборот, она с радостью их фрагментирует. Фрагментация NTFS через пол года работы доведет до искреннего удивления любого человека, знакомого с работой файловой системой. Поэтому приходится запускать дефрагментатор. Но на этом все наши проблемы не заканчиваются, а, увы, только начинаются.

Средства решения?

В NT существует стандартное API дефрагментации. Обладающее интересным ограничением для перемещения блоков файлов: за один раз можно перемещать не менее 16 кластеров (!), причем начинаться эти кластеры должны с позиции, кратной 16 кластерам в файле. В общем, операция осуществляется исключительно по 16 кластеров. Следствия:

  1. В дырку свободного места менее 16 кластеров нельзя ничего переместить (кроме сжатых файлов, но это неинтересные в данный момент тонкости).
  2. Файл, будучи перемещенный в другое место, оставляет после себя (на новом месте) «временно занятое место», дополняющее его по размеру до кратности 16 кластерам.
  3. При попытке как-то неправильно (»не кратно 16») переместить файл результат часто непредсказуем. Что-то округляется, что-то просто не перемещается… Тем не менее, всё место действия щедро рассыпается «временно занятым местом».

«Временно занятое место» служит для облегчения восстановления системы в случае аппаратного сбоя и освобождается через некоторое время, обычно где-то пол минуты.

Тем не менее, логично было бы использовать это API, раз он есть. Его и используют. Поэтому процесс стандартной дефрагментации, с поправками на ограниченность API, состоит из следующих фаз (не обязательно в этом порядке):

  • Вынимание файлов из MFT зоны. Не специально — просто обратно туда их положить не представляется возможным :) Безобидная фаза, и даже в чем то полезная.
  • Дефрагментация файлов. Безусловно, полезный процесс, несколько, правда, осложняемый ограничениями кратности перемещений — файлы часто приходится перекладывать сильнее, чем это было бы логично сделать по уму.
  • Дефрагментация MFT, виртуалки (pagefile.sys) и каталогов. Возможна через API только в Windows2000, иначе — при перезагрузке, отдельным процессом, как в старом Diskeeper-е.
  • Складывание файлов ближе к началу — так называемая дефрагментация свободного места. Вот это — воистину страшный процесс.

Допустим, мы хотим положить файлы подряд в начало диска. Кладем один файл. Он оставляет хвост занятости дополнения до кратности 16. Кладем следующий — после хвоста, естественно. Через некоторое время, по освобождению хвоста, имеем дырку <16 кластеров размером. Которую потом невозможно заполнить через API дефрагментации! В результате, до оптимизации картина свободного места выглядела так: много дырок примерно одинакового размера. После оптимизации — одна дыра в конце диска, и много маленьких <16 кластеров дырок в заполненном файлами участке. Какие места в первую очередь заполняются? Правильно, находящиеся ближе к началу диска мелкие дырки <16 кластеров… Любой файл, плавно созданный на прооптимизированном диске, будет состоять из дикого числа фрагментов. Да, диск потом можно оптимизировать снова. А потом еще раз.. и еще.. и так — желательно каждую неделю. Бред? Реальность.

Таким образом, имеется два примерно равнозначных варианта. Первый — часто оптимизировать диск таким дефрагментатором, смиряясь при этом с дикой фрагментацией заново созданных файлов. Второй вариант — вообще ничего не трогать, и смириться с равномерной, но гораздо более слабой фрагментацией всех файлов на диске.

Пока есть всего один дефрагментатор, который игнорирует API дефрагментации и работает как-то более напрямую — Norton Speeddisk 5.0 для NT. Когда его пытаются сравнить со всеми остальными — Diskeeper, O&O defrag, т. д. — не упоминают этого главного, самого принципиального, отличия. Просто потому, что эта проблема тщательно скрывается, по крайней мере уж точно не афишируется на каждом шагу. Speeddisk — единственная на сегодняшний день программа, которая может оптимизировать диск полностью, не создавая маленьких незаполненных фрагментов свободного места. Стоит добавить также, что при помощи стандартного API невозможно дефрагментировать тома NTFS с кластером более 4 Кбайт, а SpeedDisk и это может.

К сожалению, в Windows 2000 поместили дефрагментатор, который работает через API, и, соответственно, плодит дырки <16 кластеров. Так что как только появится (если еще не появился) — так сразу надо качать Speeddisk для W2k.

Как некоторый вывод из всего этого: все остальные дефрагментаторы при одноразовом применении просто вредны. Если вы запускали его хоть раз — нужно запускать его потом хотя бы раз в месяц, чтобы избавится от фрагментации новоприбывающих файлов. В этом основная суть сложности дефрагментации NTFS теми средствами, которые сложились исторически.Часть 3. Что выбрать?

Любая из представленных ныне файловых систем уходит своими корнями в глубокое прошлое — еще к 80-м годам. Да, NTFS, как это не странно — очень старая система! Дело в том, что долгое время персональные компьютеры пользовались лишь операционной системой DOS, которой и обязана своим появлением FAT. Но параллельно разрабатывались и тихо существовали системы, нацеленные на будущее. Две таких системы, получившие всё же широкое признание — NTFS, созданная для операционной системы Windows NT 3.1 еще в незапамятные времена, и HPFS — верная спутница OS/2.

Внедрение новых систем шло трудно — еще в 95м году, с выходом Windows95, ни у кого не было и мыслей о том, что что-то нужно менять — FAT получил второе дыхание посредством налепленной сверху заплатки «длинные имена», реализация которых там хоть и близка к идеально возможной без изменения системы, но всё же довольно бестолкова. Но в последующие годы необходимость перемен назрела окончательно, поскольку естественные ограничения FAT стали давать о себе знать. FAT32, появившаяся в Windows 95 OSR2, просто сдвинула рамки — не изменив сути системы, которая просто не дает возможности организовать эффективную работу с большим количеством данных.

HPFS (High Performance File System), активно применяемая до сих пор пользователями OS/2, показала себя достаточно удачной системой, но и она имела существенные недостатки — полное отсутствие средств автоматической восстанавливаемости, излишнюю сложность организации данных и невысокую гибкость.

NTFS же долго не могла завоевать персональные компьютеры из-за того, что для организации эффективной работы с её структурами данных требовались значительные объемы памяти. Системы с 4 или 8 Мбайт (стандарт 95-96 годов) были просто неспособны получить хоть какой-либо плюс от NTFS, поэтому за ней закрепилась не очень правильная репутация медленной и громоздкой системы. На самом деле это не соответствует действительности — современные компьютерные системы с памятью более 64 Мб получают просто огромный прирост производительности от использования NTFS.

В данной таблице сведены воедино все существенные плюсы и минусы распространенных в наше время систем, таких как FAT32, FAT и NTFS. Вряд ли разумно обсуждать другие системы, так как в настоящее время 97% пользователей делают выбор между Windows98, Windows NT4.0 и Windows 2000 (NT5.0), а других вариантов там просто нет.

FAT

FAT32

NTFS

Системы, её поддерживающие DOS, Windows9Х, NT всех версий Windows98, NT5 NT4, NT5
Максимальный размер тома 2 Гбайт практически неограничен практически неограничен
Макс. число файлов на томе примерно 65 тысяч практически не ограничено практически не ограничено
Имя файла с поддержкой длинных имен — 255 символов, системный набор символов с поддержкой длинных имен — 255 символов, системный набор символов 255 символов, любые символы любых алфавитов (65 тысяч разных начертаний)
Возможные атрибуты файла Базовый набор Базовый набор всё, что придет в голову производителям программного обеспечения
Безопасность нет нет да (начиная с NT5.0 встроена возможность физически шифровать данные)
Сжатие нет нет да
Устойчивость к сбоям средняя (система слишком проста и поэтому ломаться особо нечему :)) плохая (средства оптимизации по скорости привели к появлению слабых по надежности мест) полная — автоматическое восстановление системы при любых сбоях (не считая физические ошибки записи, когда пишется одно, а на самом деле записывается другое)
Экономичность минимальная (огромные размеры кластеров на больших дисках) улучшена за счет уменьшения размеров кластеров максимальна. Очень эффективная и разнообразная система хранения данных
Быстродействие высокое для малого числа файлов, но быстро уменьшается с появлением большого количества файлов в каталогах. результат — для слабо заполненных дисков — максимальное, для заполненных — плохое полностью аналогично FAT, но на дисках большого размера (десятки гигабайт) начинаются серьезные проблемы с общей организацией данных система не очень эффективна для малых и простых разделов (до 1 Гбайт), но работа с огромными массивами данных и внушительными каталогами организована как нельзя более эффективно и очень сильно превосходит по скорости другие системы

Хотелось бы сказать, что если ваша операционная система — NT (Windows 2000), то использовать какую-либо файловую систему, отличную от NTFS — значит существенно ограничивать свое удобство и гибкость работы самой операционной системы. NT, а особенно Windows 2000, составляет с NTFS как бы две части единого целого — множество полезных возможностей NT напрямую завязано на физическую и логическую структуру файловой системы, и использовать там FAT или FAT32 имеет смысл лишь для совместимости — если у вас стоит задача читать эти диски из каких-либо других систем.

Хотелось бы выразить искреннюю признательность Андрею Шабалину, без которого эта статья просто не была бы написана, а даже будучи написанной, содержала бы много досадных неточностей

Продолжение читайте в статье «Надежность дисковой системы NT»

Операционные системы Microsoft семейства Windows NT нельзя представить без файловой системы NTFS — одной из самых сложных и удачных из существующих на данный момент файловых систем. Данная статья расскажет вам, в чем особенности и недостатки этой системы, на каких принципах основана организация информации, и как поддерживать систему в стабильном состоянии, какие возможности предлагает NTFS и как их можно использовать обычному пользователю.

Часть 1. Физическая структура NTFS

Начнем с общих фактов. Раздел NTFS, теоретически, может быть почти какого угодно размера. Предел, конечно, есть, но я даже не буду указывать его, так как его с запасом хватит на последующие сто лет развития вычислительной техники — при любых темпах роста. Как обстоит с этим дело на практике? Почти так же. Максимальный размер раздела NTFS в данный момент ограничен лишь размерами жестких дисков. NT4, правда, будет испытывать проблемы при попытке установки на раздел, если хоть какая-нибудь его часть отступает более чем на 8 Гб от физического начала диска, но эта проблема касается лишь загрузочного раздела.

Лирическое отступление. Метод инсталляции NT4.0 на пустой диск довольно оригинален и может навести на неправильные мысли о возможностях NTFS. Если вы укажете программе установки, что желаете отформатировать диск в NTFS, максимальный размер, который она вам предложит, будет всего 4 Гб. Почему так мало, если размер раздела NTFS на самом деле практически неограничен? Дело в том, что установочная секция просто не знает этой файловой системы :) Программа установки форматирует этот диск в обычный FAT, максимальный размер которого в NT составляет 4 Гбайт (с использованием не совсем стандартного огромного кластера 64 Кбайта), и на этот FAT устанавливает NT. А вот уже в процессе первой загрузки самой операционной системы (еще в установочной фазе) производится быстрое преобразование раздела в NTFS; так что пользователь ничего и не замечает, кроме странного «ограничения» на размер NTFS при установке. :)

Структура раздела — общий взгляд

Как и любая другая система, NTFS делит все полезное место на кластеры — блоки данных, используемые единовременно. NTFS поддерживает почти любые размеры кластеров — от 512 байт до 64 Кбайт, неким стандартом же считается кластер размером 4 Кбайт. Никаких аномалий кластерной структуры NTFS не имеет, поэтому на эту, в общем-то, довольно банальную тему, сказать особо нечего.

Диск NTFS условно делится на две части. Первые 12% диска отводятся под так называемую MFT зону — пространство, в которое растет метафайл MFT (об этом ниже). Запись каких-либо данных в эту область невозможна. MFT-зона всегда держится пустой — это делается для того, чтобы самый главный, служебный файл (MFT) не фрагментировался при своем росте. Остальные 88% диска представляют собой обычное пространство для хранения файлов.

Свободное место диска, однако, включает в себя всё физически свободное место — незаполненные куски MFT-зоны туда тоже включаются. Механизм использования MFT-зоны таков: когда файлы уже нельзя записывать в обычное пространство, MFT-зона просто сокращается (в текущих версиях операционных систем ровно в два раза), освобождая таким образом место для записи файлов. При освобождении места в обычной области MFT зона может снова расширится. При этом не исключена ситуация, когда в этой зоне остались и обычные файлы: никакой аномалии тут нет. Что ж, система старалась оставить её свободной, но ничего не получилось. Жизнь продолжается… Метафайл MFT все-таки может фрагментироваться, хоть это и было бы нежелательно.

MFT и его структура

Файловая система NTFS представляет собой выдающееся достижение структуризации: каждый элемент системы представляет собой файл — даже служебная информация. Самый главный файл на NTFS называется MFT, или Master File Table — общая таблица файлов. Именно он размещается в MFT зоне и представляет собой централизованный каталог всех остальных файлов диска, и, как не парадоксально, себя самого. MFT поделен на записи фиксированного размера (обычно 1 Кбайт), и каждая запись соответствует какому либо файлу (в общем смысле этого слова). Первые 16 файлов носят служебный характер и недоступны операционной системе — они называются метафайлами, причем самый первый метафайл — сам MFT. Эти первые 16 элементов MFT — единственная часть диска, имеющая фиксированное положение. Интересно, что вторая копия первых трех записей, для надежности — они очень важны — хранится ровно посередине диска. Остальной MFT-файл может располагаться, как и любой другой файл, в произвольных местах диска — восстановить его положение можно с помощью его самого, «зацепившись» за самую основу — за первый элемент MFT.

Метафайлы

Первые 16 файлов NTFS (метафайлы) носят служебный характер. Каждый из них отвечает за какой-либо аспект работы системы. Преимущество настолько модульного подхода заключается в поразительной гибкости — например, на FAT-е физическое повреждение в самой области FAT фатально для функционирования всего диска, а NTFS может сместить, даже фрагментировать по диску, все свои служебные области, обойдя любые неисправности поверхности — кроме первых 16 элементов MFT.

Метафайлы находятся корневом каталоге NTFS диска — они начинаются с символа имени «$», хотя получить какую-либо информацию о них стандартными средствами сложно. Любопытно, что и для этих файлов указан вполне реальный размер — можно узнать, например, сколько операционная система тратит на каталогизацию всего вашего диска, посмотрев размер файла $MFT. В следующей таблице приведены используемые в данный момент метафайлы и их назначение.

$MFT сам MFT
$MFTmirr копия первых 16 записей MFT, размещенная посередине диска
$LogFile файл поддержки журналирования (см. ниже)
$Volume служебная информация — метка тома, версия файловой системы, т. д.
$AttrDef список стандартных атрибутов файлов на томе
$. корневой каталог
$Bitmap карта свободного места тома
$Boot загрузочный сектор (если раздел загрузочный)
$Quota файл, в котором записаны права пользователей на использование дискового пространства (начал работать лишь в NT5)
$Upcase файл — таблица соответствия заглавных и прописных букв в имен файлов на текущем томе. Нужен в основном потому, что в NTFS имена файлов записываются в Unicode, что составляет 65 тысяч различных символов, искать большие и малые эквиваленты которых очень нетривиально.

Файлы и потоки

Итак, у системы есть файлы — и ничего кроме файлов. Что включает в себя это понятие на NTFS?

  • Прежде всего, обязательный элемент — запись в MFT, ведь, как было сказано ранее, все файлы диска упоминаются в MFT. В этом месте хранится вся информация о файле, за исключением собственно данных. Имя файла, размер, положение на диске отдельных фрагментов, и т. д. Если для информации не хватает одной записи MFT, то используются несколько, причем не обязательно подряд.
  • Опциональный элемент — потоки данных файла. Может показаться странным определение «опциональный», но, тем не менее, ничего странного тут нет. Во-первых, файл может не иметь данных — в таком случае на него не расходуется свободное место самого диска. Во-вторых, файл может иметь не очень большой размер. Тогда идет в ход довольно удачное решение: данные файла хранятся прямо в MFT, в оставшемся от основных данных месте в пределах одной записи MFT. Файлы, занимающие сотни байт, обычно не имеют своего «физического» воплощения в основной файловой области — все данные такого файла хранятся в одном месте — в MFT.

Довольно интересно обстоит дело и с данными файла. Каждый файл на NTFS, в общем-то, имеет несколько абстрактное строение — у него нет как таковых данных, а есть потоки (streams). Один из потоков и носит привычный нам смысл — данные файла. Но большинство атрибутов файла — тоже потоки! Таким образом, получается, что базовая сущность у файла только одна — номер в MFT, а всё остальное опционально. Данная абстракция может использоваться для создания довольно удобных вещей — например, файлу можно «прилепить» еще один поток, записав в него любые данные — например, информацию об авторе и содержании файла, как это сделано в Windows 2000 (самая правая закладка в свойствах файла, просматриваемых из проводника). Интересно, что эти дополнительные потоки не видны стандартными средствами: наблюдаемый размер файла — это лишь размер основного потока, который содержит традиционные данные. Можно, к примеру, иметь файл нулевой длинны, при стирании которого освободится 1 Гбайт свободного места — просто потому, что какая-нибудь хитрая программа или технология прилепила в нему дополнительный поток (альтернативные данные) гигабайтового размера. Но на самом деле в текущий момент потоки практически не используются, так что опасаться подобных ситуаций не следует, хотя гипотетически они возможны. Просто имейте в виду, что файл на NTFS — это более глубокое и глобальное понятие, чем можно себе вообразить просто просматривая каталоги диска. Ну и напоследок: имя файла может содержать любые символы, включая полый набор национальных алфавитов, так как данные представлены в Unicode — 16-битном представлении, которое дает 65535 разных символов. Максимальная длина имени файла — 255 символов.

Каталоги

Каталог на NTFS представляет собой специфический файл, хранящий ссылки на другие файлы и каталоги, создавая иерархическое строение данных на диске. Файл каталога поделен на блоки, каждый из которых содержит имя файла, базовые атрибуты и ссылку на элемент MFT, который уже предоставляет полную информацию об элементе каталога. Внутренняя структура каталога представляет собой бинарное дерево. Вот что это означает: для поиска файла с данным именем в линейном каталоге, таком, например, как у FAT-а, операционной системе приходится просматривать все элементы каталога, пока она не найдет нужный. Бинарное же дерево располагает имена файлов таким образом, чтобы поиск файла осуществлялся более быстрым способом — с помощью получения двухзначных ответов на вопросы о положении файла. Вопрос, на который бинарное дерево способно дать ответ, таков: в какой группе, относительно данного элемента, находится искомое имя — выше или ниже? Мы начинаем с такого вопроса к среднему элементу, и каждый ответ сужает зону поиска в среднем в два раза. Файлы, скажем, просто отсортированы по алфавиту, и ответ на вопрос осуществляется очевидным способом — сравнением начальных букв. Область поиска, суженная в два раза, начинает исследоваться аналогичным образом, начиная опять же со среднего элемента.

Вывод — для поиска одного файла среди 1000, например, FAT придется осуществить в среднем 500 сравнений (наиболее вероятно, что файл будет найден на середине поиска), а системе на основе дерева — всего около 12-ти (2^10 = 1024). Экономия времени поиска налицо. Не стоит, однако думать, что в традиционных системах (FAT) всё так запущено: во-первых, поддержание списка файлов в виде бинарного дерева довольно трудоемко, а во-вторых — даже FAT в исполнении современной системы (Windows2000 или Windows98) использует сходную оптимизацию поиска. Это просто еще один факт в вашу копилку знаний. Хочется также развеять распространенное заблуждение (которое я сам разделял совсем еще недавно) о том, что добавлять файл в каталог в виде дерева труднее, чем в линейный каталог: это достаточно сравнимые по времени операции — дело в том, что для того, чтобы добавить файл в каталог, нужно сначала убедится, что файла с таким именем там еще нет :) — и вот тут-то в линейной системе у нас будут трудности с поиском файла, описанные выше, которые с лихвой компенсируют саму простоту добавления файла в каталог.

Какую информацию можно получить, просто прочитав файл каталога? Ровно то, что выдает команда dir. Для выполнения простейшей навигации по диску не нужно лазить в MFT за каждым файлом, надо лишь читать самую общую информацию о файлах из файлов каталогов. Главный каталог диска — корневой — ничем не отличается об обычных каталогов, кроме специальной ссылки на него из начала метафайла MFT.

Журналирование

NTFS — отказоустойчивая система, которая вполне может привести себя в корректное состояние при практически любых реальных сбоях. Любая современная файловая система основана на таком понятии, как транзакция — действие, совершаемое целиком и корректно или не совершаемое вообще. У NTFS просто не бывает промежуточных (ошибочных или некорректных) состояний — квант изменения данных не может быть поделен на до и после сбоя, принося разрушения и путаницу — он либо совершен, либо отменен.

Пример 1: осуществляется запись данных на диск. Вдруг выясняется, что в то место, куда мы только что решили записать очередную порцию данных, писать не удалось — физическое повреждение поверхности. Поведение NTFS в этом случае довольно логично: транзакция записи откатывается целиком — система осознает, что запись не произведена. Место помечается как сбойное, а данные записываются в другое место — начинается новая транзакция.

Пример 2: более сложный случай — идет запись данных на диск. Вдруг, бах — отключается питание и система перезагружается. На какой фазе остановилась запись, где есть данные, а где чушь? На помощь приходит другой механизм системы — журнал транзакций. Дело в том, что система, осознав свое желание писать на диск, пометила в метафайле $LogFile это свое состояние. При перезагрузке это файл изучается на предмет наличия незавершенных транзакций, которые были прерваны аварией и результат которых непредсказуем — все эти транзакции отменяются: место, в которое осуществлялась запись, помечается снова как свободное, индексы и элементы MFT приводятся в с состояние, в котором они были до сбоя, и система в целом остается стабильна. Ну а если ошибка произошла при записи в журнал? Тоже ничего страшного: транзакция либо еще и не начиналась (идет только попытка записать намерения её произвести), либо уже закончилась — то есть идет попытка записать, что транзакция на самом деле уже выполнена. В последнем случае при следующей загрузке система сама вполне разберется, что на самом деле всё и так записано корректно, и не обратит внимания на «незаконченную» транзакцию.

И все-таки помните, что журналирование — не абсолютная панацея, а лишь средство существенно сократить число ошибок и сбоев системы. Вряд ли рядовой пользователь NTFS хоть когда-нибудь заметит ошибку системы или вынужден будет запускать chkdsk — опыт показывает, что NTFS восстанавливается в полностью корректное состояние даже при сбоях в очень загруженные дисковой активностью моменты. Вы можете даже оптимизировать диск и в самый разгар этого процесса нажать reset — вероятность потерь данных даже в этом случае будет очень низка. Важно понимать, однако, что система восстановления NTFS гарантирует корректность файловой системы, а не ваших данных. Если вы производили запись на диск и получили аварию — ваши данные могут и не записаться. Чудес не бывает.

Сжатие

Файлы NTFS имеют один довольно полезный атрибут — «сжатый». Дело в том, что NTFS имеет встроенную поддержку сжатия дисков — то, для чего раньше приходилось использовать Stacker или DoubleSpace. Любой файл или каталог в индивидуальном порядке может хранится на диске в сжатом виде — этот процесс совершенно прозрачен для приложений. Сжатие файлов имеет очень высокую скорость и только одно большое отрицательное свойство — огромная виртуальная фрагментация сжатых файлов, которая, правда, никому особо не мешает. Сжатие осуществляется блоками по 16 кластеров и использует так называемые «виртуальные кластеры» — опять же предельно гибкое решение, позволяющее добиться интересных эффектов — например, половина файла может быть сжата, а половина — нет. Это достигается благодаря тому, что хранение информации о компрессированности определенных фрагментов очень похоже на обычную фрагментацию файлов: например, типичная запись физической раскладки для реального, несжатого, файла:

кластеры файла с 1 по 43-й хранятся в кластерах диска начиная с 400-го

кластеры файла с 44 по 52-й хранятся в кластерах диска начиная с 8530-го…

Физическая раскладка типичного сжатого файла:

кластеры файла с 1 по 9-й хранятся в кластерах диска начиная с 400-го

кластеры файла с 10 по 16-й нигде не хранятся

кластеры файла с 17 по 18-й хранятся в кластерах диска начиная с 409-го

кластеры файла с 19 по 36-й нигде не хранятся

Видно, что сжатый файл имеет «виртуальные» кластеры, реальной информации в которых нет. Как только система видит такие виртуальные кластеры, она тут же понимает, что данные предыдущего блока, кратного 16-ти, должны быть разжаты, а получившиеся данные как раз заполнят виртуальные кластеры — вот, по сути, и весь алгоритм.

Безопасность

NTFS содержит множество средств разграничения прав объектов — есть мнение, что это самая совершенная файловая система из всех ныне существующих. В теории это, без сомнения, так, но в текущих реализациях, к сожалению, система прав достаточно далека от идеала и представляет собой хоть и жесткий, но не всегда логичный набор характеристик. Права, назначаемые любому объекту и однозначно соблюдаемые системой, эволюционируют — крупные изменения и дополнения прав осуществлялись уже несколько раз и к Windows 2000 все-таки они пришли к достаточно разумному набору.

Права файловой системы NTFS неразрывно связаны с самой системой — то есть они, вообще говоря, необязательны к соблюдению другой системой, если ей дать физический доступ к диску. Для предотвращения физического доступа в Windows2000 (NT5) всё же ввели стандартную возможность — об этом см. ниже. Система прав в своем текущем состоянии достаточно сложна, и я сомневаюсь, что смогу сказать широкому читателю что-нибудь интересное и полезное ему в обычной жизни. Если вас интересует эта тема — вы найдете множество книг по сетевой архитектуре NT, в которых это описано более чем подробно.

На этом описание строение файловой системы можно закончить, осталось описать лишь некоторое количество просто практичных или оригинальных вещей.

Hard Links

Эта штука была в NTFS с незапамятных времен, но использовалась очень редко — и тем не менее: Hard Link — это когда один и тот же файл имеет два имени (несколько указателей файла-каталога или разных каталогов указывают на одну и ту же MFT запись). Допустим, один и тот же файл имеет имена 1.txt и 2.txt: если пользователь сотрет файл 1, останется файл 2. Если сотрет 2 — останется файл 1, то есть оба имени, с момента создания, совершенно равноправны. Файл физически стирается лишь тогда, когда будет удалено его последнее имя.

Symbolic Links (NT5)

Гораздо более практичная возможность, позволяющая делать виртуальные каталоги — ровно так же, как и виртуальные диски командой subst в DOSе. Применения достаточно разнообразны: во-первых, упрощение системы каталогов. Если вам не нравится каталог Documents and settingsAdministratorDocuments, вы можете прилинковать его в корневой каталог — система будет по прежнему общаться с каталогом с дремучим путем, а вы — с гораздо более коротким именем, полностью ему эквивалентным. Для создания таких связей можно воспользоваться программой junction (junction.zip, 15 Кб), которую написал известный специалист Mark Russinovich. Программа работает только в NT5 (Windows 2000), как и сама возможность.

Для удаления связи можно воспользоваться стандартной командой rd.
ВНИМАНИЕ: Попытка уделения связи с помощью проводника или других файловых менеджеров, не понимающих виртуальную природу каталога (например, FAR), приведет к удалению данных, на которые ссылается ссылка! Будьте осторожны.

Шифрование (NT5)

Полезная возможность для людей, которые беспокоятся за свои секреты — каждый файл или каталог может также быть зашифрован, что не даст возможность прочесть его другой инсталляцией NT. В сочетании со стандартным и практически непрошибаемым паролем на загрузку самой системы, эта возможность обеспечивает достаточную для большинства применений безопасность избранных вами важных данных.Часть 2. Особенности дефрагментации NTFS

Вернемся к одному достаточно интересному и важному моменту — фрагментации и дефрагментации NTFS. Дело в том, что ситуация, сложившаяся с этими двумя понятиями в настоящий момент, никак не может быть названа удовлетворительной. В самом начале утверждалось, что NTFS не подвержена фрагментации файлов. Это оказалось не совсем так, и утверждение сменили — NTFS препятствует фрагментации. Оказалось, что и это не совсем так. То есть она, конечно, препятствует, но толк от этого близок к нулю… Сейчас уже понятно, что NTFS — система, которая как никакая другая предрасположена к фрагментации, что бы ни утверждалось официально. Единственное что — логически она не очень от этого страдает. Все внутренние структуры построены таким образом, что фрагментация не мешает быстро находить фрагменты данных. Но от физического последствия фрагментации — лишних движений головок — она, конечно, не спасает. И поэтому — вперед и с песней.

К истокам проблемы

Как известно, система сильнее всего фрагментирует файлы когда свободное место кончается, когда приходится использовать мелкие дырки, оставшиеся от других файлов. Тут возникает первое свойство NTFS, которое прямо способствует серьезной фрагментации.

Диск NTFS поделен на две зоны. В начала диска идет MFT зона — зона, куда растет MFT, Master File Table. Зона занимает минимум 12% диска, и запись данных в эту зону невозможна. Это сделано для того, чтобы не фрагментировался хотя бы MFT. Но когда весь остальной диск заполняется — зона сокращается ровно в два раза :). И так далее. Таким образом мы имеем не один заход окончания диска, а несколько. В результате если NTFS работает при диске, заполненном на около 90% — фрагментация растет как бешенная.

Попутное следствие — диск, заполненный более чем на 88%, дефрагментировать почти невозможно — даже API дефрагментации не может перемещать данные в MFT зону. Может оказаться так, что у нас не будет свободного места для маневра.

Далее. NTFS работает себе и работает, и всё таки фрагментируется — даже в том случае, если свободное место далеко от истощения. Этому способствует странный алгоритм нахождения свободного места для записи файлов — второе серьезное упущение. Алгоритм действий при любой записи такой: берется какой-то определенный объем диска и заполняется файлом до упора. Причем по очень интересному алгоритму: сначала заполняются большие дырки, потом маленькие. Т.е. типичное распределение фрагментов файла по размеру на фрагментированной NTFS выглядит так (размеры фрагментов):

16 — 16 — 16 — 16 — 16 — [скачек назад] — 15 — 15 — 15 — [назад] — 14 — 14 — 14 …. 1 — 1 — 1 -1 — 1…

Так процесс идет до самых мелких дырок в 1 кластер, несмотря на то, что на диске наверняка есть и гораздо более большие куски свободного места.

Вспомните сжатые файлы — при активной перезаписи больших объемов сжатой информации на NTFS образуется гигантское количество «дырок» из-за перераспределения на диске сжатых объемов — если какой-либо участок файла стал сжиматься лучше или хуже, его приходится либо изымать из непрерывной цепочки и размещать в другом месте, либо стягивать в объеме, оставляя за собой дырку.

Смысл в сего этого вступления в пояснении того простого факта, что никак нельзя сказать, что NTFS препятствует фрагментации файлов. Наоборот, она с радостью их фрагментирует. Фрагментация NTFS через пол года работы доведет до искреннего удивления любого человека, знакомого с работой файловой системой. Поэтому приходится запускать дефрагментатор. Но на этом все наши проблемы не заканчиваются, а, увы, только начинаются.

Средства решения?

В NT существует стандартное API дефрагментации. Обладающее интересным ограничением для перемещения блоков файлов: за один раз можно перемещать не менее 16 кластеров (!), причем начинаться эти кластеры должны с позиции, кратной 16 кластерам в файле. В общем, операция осуществляется исключительно по 16 кластеров. Следствия:

  1. В дырку свободного места менее 16 кластеров нельзя ничего переместить (кроме сжатых файлов, но это неинтересные в данный момент тонкости).
  2. Файл, будучи перемещенный в другое место, оставляет после себя (на новом месте) «временно занятое место», дополняющее его по размеру до кратности 16 кластерам.
  3. При попытке как-то неправильно (»не кратно 16») переместить файл результат часто непредсказуем. Что-то округляется, что-то просто не перемещается… Тем не менее, всё место действия щедро рассыпается «временно занятым местом».

«Временно занятое место» служит для облегчения восстановления системы в случае аппаратного сбоя и освобождается через некоторое время, обычно где-то пол минуты.

Тем не менее, логично было бы использовать это API, раз он есть. Его и используют. Поэтому процесс стандартной дефрагментации, с поправками на ограниченность API, состоит из следующих фаз (не обязательно в этом порядке):

  • Вынимание файлов из MFT зоны. Не специально — просто обратно туда их положить не представляется возможным :) Безобидная фаза, и даже в чем то полезная.
  • Дефрагментация файлов. Безусловно, полезный процесс, несколько, правда, осложняемый ограничениями кратности перемещений — файлы часто приходится перекладывать сильнее, чем это было бы логично сделать по уму.
  • Дефрагментация MFT, виртуалки (pagefile.sys) и каталогов. Возможна через API только в Windows2000, иначе — при перезагрузке, отдельным процессом, как в старом Diskeeper-е.
  • Складывание файлов ближе к началу — так называемая дефрагментация свободного места. Вот это — воистину страшный процесс.

Допустим, мы хотим положить файлы подряд в начало диска. Кладем один файл. Он оставляет хвост занятости дополнения до кратности 16. Кладем следующий — после хвоста, естественно. Через некоторое время, по освобождению хвоста, имеем дырку <16 кластеров размером. Которую потом невозможно заполнить через API дефрагментации! В результате, до оптимизации картина свободного места выглядела так: много дырок примерно одинакового размера. После оптимизации — одна дыра в конце диска, и много маленьких <16 кластеров дырок в заполненном файлами участке. Какие места в первую очередь заполняются? Правильно, находящиеся ближе к началу диска мелкие дырки <16 кластеров… Любой файл, плавно созданный на прооптимизированном диске, будет состоять из дикого числа фрагментов. Да, диск потом можно оптимизировать снова. А потом еще раз.. и еще.. и так — желательно каждую неделю. Бред? Реальность.

Таким образом, имеется два примерно равнозначных варианта. Первый — часто оптимизировать диск таким дефрагментатором, смиряясь при этом с дикой фрагментацией заново созданных файлов. Второй вариант — вообще ничего не трогать, и смириться с равномерной, но гораздо более слабой фрагментацией всех файлов на диске.

Пока есть всего один дефрагментатор, который игнорирует API дефрагментации и работает как-то более напрямую — Norton Speeddisk 5.0 для NT. Когда его пытаются сравнить со всеми остальными — Diskeeper, O&O defrag, т. д. — не упоминают этого главного, самого принципиального, отличия. Просто потому, что эта проблема тщательно скрывается, по крайней мере уж точно не афишируется на каждом шагу. Speeddisk — единственная на сегодняшний день программа, которая может оптимизировать диск полностью, не создавая маленьких незаполненных фрагментов свободного места. Стоит добавить также, что при помощи стандартного API невозможно дефрагментировать тома NTFS с кластером более 4 Кбайт, а SpeedDisk и это может.

К сожалению, в Windows 2000 поместили дефрагментатор, который работает через API, и, соответственно, плодит дырки <16 кластеров. Так что как только появится (если еще не появился) — так сразу надо качать Speeddisk для W2k.

Как некоторый вывод из всего этого: все остальные дефрагментаторы при одноразовом применении просто вредны. Если вы запускали его хоть раз — нужно запускать его потом хотя бы раз в месяц, чтобы избавится от фрагментации новоприбывающих файлов. В этом основная суть сложности дефрагментации NTFS теми средствами, которые сложились исторически.Часть 3. Что выбрать?

Любая из представленных ныне файловых систем уходит своими корнями в глубокое прошлое — еще к 80-м годам. Да, NTFS, как это не странно — очень старая система! Дело в том, что долгое время персональные компьютеры пользовались лишь операционной системой DOS, которой и обязана своим появлением FAT. Но параллельно разрабатывались и тихо существовали системы, нацеленные на будущее. Две таких системы, получившие всё же широкое признание — NTFS, созданная для операционной системы Windows NT 3.1 еще в незапамятные времена, и HPFS — верная спутница OS/2.

Внедрение новых систем шло трудно — еще в 95м году, с выходом Windows95, ни у кого не было и мыслей о том, что что-то нужно менять — FAT получил второе дыхание посредством налепленной сверху заплатки «длинные имена», реализация которых там хоть и близка к идеально возможной без изменения системы, но всё же довольно бестолкова. Но в последующие годы необходимость перемен назрела окончательно, поскольку естественные ограничения FAT стали давать о себе знать. FAT32, появившаяся в Windows 95 OSR2, просто сдвинула рамки — не изменив сути системы, которая просто не дает возможности организовать эффективную работу с большим количеством данных.

HPFS (High Performance File System), активно применяемая до сих пор пользователями OS/2, показала себя достаточно удачной системой, но и она имела существенные недостатки — полное отсутствие средств автоматической восстанавливаемости, излишнюю сложность организации данных и невысокую гибкость.

NTFS же долго не могла завоевать персональные компьютеры из-за того, что для организации эффективной работы с её структурами данных требовались значительные объемы памяти. Системы с 4 или 8 Мбайт (стандарт 95-96 годов) были просто неспособны получить хоть какой-либо плюс от NTFS, поэтому за ней закрепилась не очень правильная репутация медленной и громоздкой системы. На самом деле это не соответствует действительности — современные компьютерные системы с памятью более 64 Мб получают просто огромный прирост производительности от использования NTFS.

В данной таблице сведены воедино все существенные плюсы и минусы распространенных в наше время систем, таких как FAT32, FAT и NTFS. Вряд ли разумно обсуждать другие системы, так как в настоящее время 97% пользователей делают выбор между Windows98, Windows NT4.0 и Windows 2000 (NT5.0), а других вариантов там просто нет.

FAT

FAT32

NTFS

Системы, её поддерживающие DOS, Windows9Х, NT всех версий Windows98, NT5 NT4, NT5
Максимальный размер тома 2 Гбайт практически неограничен практически неограничен
Макс. число файлов на томе примерно 65 тысяч практически не ограничено практически не ограничено
Имя файла с поддержкой длинных имен — 255 символов, системный набор символов с поддержкой длинных имен — 255 символов, системный набор символов 255 символов, любые символы любых алфавитов (65 тысяч разных начертаний)
Возможные атрибуты файла Базовый набор Базовый набор всё, что придет в голову производителям программного обеспечения
Безопасность нет нет да (начиная с NT5.0 встроена возможность физически шифровать данные)
Сжатие нет нет да
Устойчивость к сбоям средняя (система слишком проста и поэтому ломаться особо нечему :)) плохая (средства оптимизации по скорости привели к появлению слабых по надежности мест) полная — автоматическое восстановление системы при любых сбоях (не считая физические ошибки записи, когда пишется одно, а на самом деле записывается другое)
Экономичность минимальная (огромные размеры кластеров на больших дисках) улучшена за счет уменьшения размеров кластеров максимальна. Очень эффективная и разнообразная система хранения данных
Быстродействие высокое для малого числа файлов, но быстро уменьшается с появлением большого количества файлов в каталогах. результат — для слабо заполненных дисков — максимальное, для заполненных — плохое полностью аналогично FAT, но на дисках большого размера (десятки гигабайт) начинаются серьезные проблемы с общей организацией данных система не очень эффективна для малых и простых разделов (до 1 Гбайт), но работа с огромными массивами данных и внушительными каталогами организована как нельзя более эффективно и очень сильно превосходит по скорости другие системы

Хотелось бы сказать, что если ваша операционная система — NT (Windows 2000), то использовать какую-либо файловую систему, отличную от NTFS — значит существенно ограничивать свое удобство и гибкость работы самой операционной системы. NT, а особенно Windows 2000, составляет с NTFS как бы две части единого целого — множество полезных возможностей NT напрямую завязано на физическую и логическую структуру файловой системы, и использовать там FAT или FAT32 имеет смысл лишь для совместимости — если у вас стоит задача читать эти диски из каких-либо других систем.

Хотелось бы выразить искреннюю признательность Андрею Шабалину, без которого эта статья просто не была бы написана, а даже будучи написанной, содержала бы много досадных неточностей

Продолжение читайте в статье «Надежность дисковой системы NT»

New Technology File System[1]

Developer(s) Microsoft
Full name NT File System[2]
Introduced July 1993; 29 years ago with Windows NT 3.1
Partition identifier 0x07 (MBR)
EBD0A0A2-B9E5-4433-87C0-68B6B72699C7 (GPT)
Structures
Directory contents B-tree variant[3][4]
File allocation Bitmap
Bad blocks $BadClus (MFT Record)
Limits
Max. volume size 264 clusters − 1 cluster (format);
256 TB[a] − 64 KB[a] (Windows 10 version 1703, Windows Server 2016 or earlier implementation)[5]
8 PB − 2 MB[a] (Windows 10 version 1709, Windows Server 2019 or later implementation)[6]
Max. file size 16 EB[a] − 1 KB (format);
16 TB − 64 KB (Windows 7, Windows Server 2008 R2 or earlier implementation)[5]
256 TB − 64 KB (Windows 8, Windows Server 2012 or later implementation)[7]
8 PB − 2 MB (Windows 10 version 1709, Windows Server 2019 or later implementation)[6]
Max. number of files 4,294,967,295 (232−1)[5]
Max. filename length 255 UTF-16 code units[8]
Allowed characters in filenames
  • In Win32 namespace: any UTF-16 code unit (case-insensitive) except /:*"?<>| as well as NUL[8]
  • In POSIX namespace: any UTF-16 code unit (case-sensitive) except / as well as NUL
  • Trailing spaces are not allowed and will be removed[9]
Features
Dates recorded Creation, modification, POSIX change, access
Date range 1 January 1601 – 28 May 60056 (File times are 63-bit numbers counting 100-nanosecond intervals (ten million per second) since 1601, which is 29,227 years)
Date resolution 100 ns
Forks Yes (see § Alternate data stream (ADS) below)
Attributes Read-only, hidden, system, archive, not content indexed, off-line, temporary, compressed, encrypted
File system permissions ACLs
Transparent compression Per-file, LZ77 (Windows NT 3.51 onward)
Transparent encryption Per-file,
DESX (Windows 2000 onward),
Triple DES (Windows XP onward),
AES (Windows XP Service Pack 1, Windows Server 2003 onward)
Data deduplication Yes (Windows Server 2012)[10]
Other
Supported operating systems Windows NT 3.1 and later
Mac OS X 10.3 and later (read-only)
Linux kernel version 2.6 and later
Linux kernel versions 2.2-2.4 (read-only)
FreeBSD
NetBSD
OpenBSD (read-only)
ChromeOS
Solaris
ReactOS (read-only)

New Technology File System (NTFS) is a proprietary journaling file system developed by Microsoft.[2][1] Starting with Windows NT 3.1, it is the default file system of the Windows NT family.[11] It superseded File Allocation Table (FAT) as the preferred filesystem on Windows and is supported in Linux and BSD as well. NTFS reading and writing support is provided using a free and open-source kernel implementation known as NTFS3 in Linux and the NTFS-3G driver in BSD.[12][13] By using the convert command, Windows can convert FAT32/16/12 into NTFS without the need to rewrite all files.[14] NTFS uses several files typically hidden from the user to store metadata about other files stored on the drive which can help improve speed and performance when reading data.[1] Unlike FAT and High Performance File System (HPFS), NTFS supports access control lists (ACLs), filesystem encryption, transparent compression, sparse files and file system journaling. NTFS also supports shadow copy to allow backups of a system while it is running, but the functionality of the shadow copies varies between different versions of Windows.[15]

History[edit]

In the mid-1980s, Microsoft and IBM formed a joint project to create the next generation of graphical operating system; the result was OS/2 and HPFS. Because Microsoft disagreed with IBM on many important issues, they eventually separated; OS/2 remained an IBM project and Microsoft worked to develop Windows NT and NTFS.

The HPFS file system for OS/2 contained several important new features. When Microsoft created their new operating system, they «borrowed» many of these concepts for NTFS.[16] The original NTFS developers were Tom Miller, Gary Kimura, Brian Andrew, and David Goebel.[17]

Probably as a result of this common ancestry, HPFS and NTFS use the same disk partition identification type code (07). Using the same Partition ID Record Number is highly unusual, since there were dozens of unused code numbers available, and other major file systems have their own codes. For example, FAT has more than nine (one each for FAT12, FAT16, FAT32, etc.). Algorithms identifying the file system in a partition type 07 must perform additional checks to distinguish between HPFS and NTFS.

Versions[edit]

Microsoft has released five versions of NTFS:

NTFS version number First operating system Release date New features Remarks
1.0 Windows NT 3.1 1993[11] Initial version NTFS 1.0 is incompatible with 1.1 and newer: volumes written by Windows NT 3.5x cannot be read by Windows NT 3.1 until an update (available on the NT 3.5x installation media) is installed.[18]
1.1 Windows NT 3.51 1995 Compressed files, named streams, and access control lists[19]
1.2 Windows NT 4.0 1996 Security descriptors Commonly called NTFS 4.0 after the OS release
3.0 Windows 2000 2000 Disk quotas, file-level encryption in a form of Encrypting File System, sparse files, reparse points, update sequence number (USN) journaling, distributed link tracking, the $Extend folder and its files Compatibility was also made available for Windows NT 4.0 with the Service Pack 4 update. Commonly called NTFS 5.0 after the OS release.[20]
3.1 Windows XP October 2001 Expanded the Master File Table (MFT) entries with redundant MFT record number (useful for recovering damaged MFT files) Commonly called NTFS 5.1 after the OS release. LFS version 1.1 was replaced by version 2.0 as of Windows 8 to improve performance.

The NTFS.sys version number (e.g. v5.0 in Windows 2000) is based on the operating system version; it should not be confused with the NTFS version number (v3.1 since Windows XP).[21]

Although subsequent versions of Windows added new file system-related features, they did not change NTFS itself. For example, Windows Vista implemented NTFS symbolic links, Transactional NTFS, partition shrinking, and self-healing.[22] NTFS symbolic links are a new feature in the file system; all the others are new operating system features that make use of NTFS features already in place.

Scalability[edit]

NTFS is optimized for 4 KB[a] clusters, but supports a maximum cluster size of 2 MB[a]. (Earlier implementations support up to 64 KB)[6] The maximum NTFS volume size that the specification can support is 264 − 1 clusters, but not all implementations achieve this theoretical maximum, as discussed below.

The maximum NTFS volume size implemented in Windows XP Professional is 232 − 1 clusters, partly due to partition table limitations. For example, using 64 KB clusters, the maximum size Windows XP NTFS volume is 256 TB minus 64 KB. Using the default cluster size of 4 KB, the maximum NTFS volume size is 16 TB minus 4 KB. Both of these are vastly higher than the 128 GB[a] limit in Windows XP SP1. Because partition tables on master boot record (MBR) disks support only partition sizes up to 2 TB, multiple GUID Partition Table (GPT or «dynamic») volumes must be combined to create a single NTFS volume larger than 2 TB. Booting from a GPT volume to a Windows environment in a Microsoft supported way requires a system with Unified Extensible Firmware Interface (UEFI) and 64-bit support.[23]

The NTFS maximum theoretical limit on the size of individual files is 16 EB[a][24] (16 × 10246 or 264 bytes) minus 1 KB, which totals 18,446,744,073,709,550,592 bytes. With Windows 10 version 1709 and Windows Server 2019, the maximum implemented file size is 8 PB[a] minus 2 MB or 9,007,199,252,643,840 bytes.[6]

Interoperability[edit]

Windows[edit]

While the different NTFS versions are for the most part fully forward- and backward-compatible, there are technical considerations for mounting newer NTFS volumes in older versions of Microsoft Windows. This affects dual-booting, and external portable hard drives. For example, attempting to use an NTFS partition with «Previous Versions» (Volume Shadow Copy) on an operating system that does not support it will result in the contents of those previous versions being lost.[15] A Windows command-line utility called convert.exe can convert supporting file systems to NTFS, including HPFS (only on Windows NT 3.1, 3.5, and 3.51), FAT16 and FAT32 (on Windows 2000 and later).[25][26]

FreeBSD[edit]

FreeBSD 3.2 released in May 1999 included read-only NTFS support written by Semen Ustimenko.[27][28] This implementation was ported to NetBSD by Christos Zoulas and Jaromir Dolecek and released with NetBSD 1.5 in December 2000.[29] The FreeBSD implementation of NTFS was also ported to OpenBSD by Julien Bordet and offers native read-only NTFS support by default on i386 and amd64 platforms as of version 4.9 released 1 May 2011.[30][28]

Linux[edit]

Linux kernel versions 2.1.74 and later include a driver written by Martin von Löwis which has the ability to read NTFS partitions;[31] kernel versions 2.5.11 and later contain a new driver written by Anton Altaparmakov (University of Cambridge) and Richard Russon which supports file read.[32][33][31] The ability to write to files was introduced with kernel version 2.6.15 in 2006 which allows users to write to existing files but does not allow the creation of new ones.[34] Paragon’s NTFS driver (see below) has been merged into kernel version 5.15, and it supports read/write on normal, compressed and sparse files, as well as journal replaying.[35]

NTFS-3G is a free GPL-licensed FUSE implementation of NTFS that was initially developed as a Linux kernel driver by Szabolcs Szakacsits. It was re-written as a FUSE program to work on other systems that FUSE supports like macOS, FreeBSD, NetBSD, OpenBSD,[36] Solaris, QNX, and Haiku[37] and allows reading and writing to NTFS partitions. A performance enhanced commercial version of NTFS-3G, called «Tuxera NTFS for Mac», is also available from the NTFS-3G developers.[38]

Captive NTFS, a ‘wrapping’ driver that uses Windows’ own driver ntfs.sys, exists for Linux. It was built as a Filesystem in Userspace (FUSE) program and released under the GPL but work on Captive NTFS ceased in 2006.[39]

Linux kernel versions 5.15 onwards carry NTFS3, a fully functional NTFS Read-Write driver which works on NTFS versions up to 3.1 and is maintained primarily by the Paragon Software Group with the source code found here.

Mac OS[edit]

Mac OS X 10.3 included Ustimenko’s read-only implementation of NTFS from FreeBSD. Then in 2006 Apple hired Anton Altaparmakov to write a new NTFS implementation for Mac OS X 10.6.[40] Native NTFS write support is included in 10.6 and later, but is not activated by default, although workarounds do exist to enable the functionality. However, user reports indicate the functionality is unstable and tends to cause kernel panics.[41]

Paragon Software Group sells a read-write driver named NTFS for Mac OS X,[42] which is also included on some models of Seagate hard drives.[43]

OS/2[edit]

The NetDrive package for OS/2 (and derivatives such as eComStation and ArcaOS) supports a plugin which allows read and write access to NTFS volumes.[44][45]

DOS[edit]

There is a free-for-personal-use read/write driver for MS-DOS by Avira called «NTFS4DOS».[46][47]

Ahead Software developed a «NTFSREAD» driver (version 1.200) for DR-DOS 7.0x between 2002 and 2004. It was part of their Nero Burning ROM software.

Security[edit]

NTFS uses access control lists and user-level encryption to help secure user data.

Access control lists (ACLs)[edit]

NTFS file system permissions on a modern Windows system

In NTFS, each file or folder is assigned a security descriptor that defines its owner and contains two access control lists (ACLs). The first ACL, called discretionary access control list (DACL), defines exactly what type of interactions (e.g. reading, writing, executing or deleting) are allowed or forbidden by which user or groups of users. For example, files in the C:Program Files folder may be read and executed by all users but modified only by a user holding administrative privileges.[48] Windows Vista adds mandatory access control info to DACLs. DACLs are the primary focus of User Account Control in Windows Vista and later.

The second ACL, called system access control list (SACL), defines which interactions with the file or folder are to be audited and whether they should be logged when the activity is successful, failed or both. For example, auditing can be enabled on sensitive files of a company, so that its managers get to know when someone tries to delete them or make a copy of them, and whether he or she succeeds.[48]

Encryption[edit]

Encrypting File System (EFS) provides user-transparent encryption of any file or folder on an NTFS volume.[49] EFS works in conjunction with the EFS service, Microsoft’s CryptoAPI and the EFS File System Run-Time Library (FSRTL). EFS works by encrypting a file with a bulk symmetric key (also known as the File Encryption Key, or FEK), which is used because it takes a relatively small amount of time to encrypt and decrypt large amounts of data than if an asymmetric key cipher is used. The symmetric key that is used to encrypt the file is then encrypted with a public key that is associated with the user who encrypted the file, and this encrypted data is stored in an alternate data stream of the encrypted file. To decrypt the file, the file system uses the private key of the user to decrypt the symmetric key that is stored in the data stream. It then uses the symmetric key to decrypt the file. Because this is done at the file system level, it is transparent to the user.[50] Also, in case of a user losing access to their key, support for additional decryption keys has been built into the EFS system, so that a recovery agent can still access the files if needed. NTFS-provided encryption and NTFS-provided compression are mutually exclusive; however, NTFS can be used for one and a third-party tool for the other.

The support of EFS is not available in Basic, Home, and MediaCenter versions of Windows, and must be activated after installation of Professional, Ultimate, and Server versions of Windows or by using enterprise deployment tools within Windows domains.

Features[edit]

Journaling[edit]

NTFS is a journaling file system and uses the NTFS Log ($LogFile) to record metadata changes to the volume. It is a feature that FAT does not provide and critical for NTFS to ensure that its complex internal data structures will remain consistent in case of system crashes or data moves performed by the defragmentation API, and allow easy rollback of uncommitted changes to these critical data structures when the volume is remounted. Notably affected structures are the volume allocation bitmap, modifications to MFT records such as moves of some variable-length attributes stored in MFT records and attribute lists, and indices for directories and security descriptors.

The ($LogFile) format has evolved through several versions:

Windows Version $LogFile format version
Windows NT 4.0 1.1
Windows 2000
Windows XP
Windows Vista
Windows 7
Windows 8 2.0
Windows 8.1
Windows 10

The incompatibility of the $LogFile versions implemented by Windows 8, Windows 10, Windows 11 prevents Windows 7 (and earlier versions of Windows) from recognizing version 2.0 of the $LogFile. Backward compatibility is provided by downgrading the $LogFile to version 1.1 when an NTFS volume is cleanly dismounted. It is again upgraded to version 2.0 when mounting on a compatible version of Windows. However, when hibernating to disk in the logoff state (a.k.a. Hybrid Boot or Fast Boot, which is enabled by default), mounted file systems are not dismounted, and thus the $LogFiles of any active file systems are not downgraded to version 1.1. The inability to process version 2.0 of the $LogFile by versions of Windows older than 8.0 results in an unnecessary invocation of the CHKDSK disk repair utility. This is particularly a concern in a multi-boot scenario involving pre- and post-8.0 versions of Windows, or when frequently moving a storage device between older and newer versions. A Windows Registry setting exists to prevent the automatic upgrade of the $LogFile to the newer version. The problem can also be dealt with by disabling Hybrid Boot.[51]

The USN Journal (Update Sequence Number Journal) is a system management feature that records (in $Extend$UsnJrnl) changes to files, streams and directories on the volume, as well as their various attributes and security settings. The journal is made available for applications to track changes to the volume.[52] This journal can be enabled or disabled on non-system volumes.[53]

Hard links[edit]

The hard link feature allows different file names to directly refer to the same file contents. Hard links may link only to files in the same volume, because each volume has its own MFT.
Hard links were originally included to support the POSIX subsystem in Windows NT.[54]

Although Hard links use the same MFT record (inode) which records file metadata such as file size, modification date, and attributes, NTFS also caches this data in the directory entry as a performance enhancement. This means that when listing the contents of a directory using FindFirstFile/FindNextFile family of APIs, (equivalent to the POSIX opendir/readdir APIs) you will also receive this cached information, in addition to the name and inode. However, you may not see up-to-date information, as this information is only guaranteed to be updated when a file is closed, and then only for the directory from which the file was opened.[55] This means where a file has multiple names via hard links, updating a file via one name does not update the cached data associated with the other name. You can always obtain up-to-date data using GetFileInformationByHandle (which is the true equivalent of POSIX stat function). This can be done using a handle which has no access to the file itself (passing zero to CreateFile for dwDesiredAccess), and closing this handle has the incidental effect of updating the cached information.

Windows uses hard links to support short (8.3) filenames in NTFS. Operating system support is needed because there are legacy applications that can work only with 8.3 filenames, but support can be disabled. In this case, an additional filename record and directory entry is added, but both 8.3 and long file name are linked and updated together, unlike a regular hard link.

The NTFS file system has a limit of 1024 hard links on a file.[56]

Alternate data stream (ADS)[edit]

Alternate data streams allow more than one data stream to be associated with a filename (a fork), using the format «filename:streamname» (e.g., «text.txt:extrastream»).

NTFS Streams were introduced in Windows NT 3.1, to enable Services for Macintosh (SFM) to store resource forks. Although current versions of Windows Server no longer include SFM, third-party Apple Filing Protocol (AFP) products (such as GroupLogic’s ExtremeZ-IP) still use this feature of the file system. Very small ADSs (named «Zone.Identifier») are added by Internet Explorer and recently[when?] by other browsers to mark files downloaded from external sites as possibly unsafe to run; the local shell would then require user confirmation before opening them.[57] When the user indicates that they no longer want this confirmation dialog, this ADS is deleted.

Alternate streams are not listed in Windows Explorer, and their size is not included in the file’s size. When the file is copied or moved to another file system without ADS support the user is warned that alternate data streams cannot be preserved. No such warning is typically provided if the file is attached to an e-mail, or uploaded to a website. Thus, using alternate streams for critical data may cause problems. Microsoft provides a tool called Streams[58] to view streams on a selected volume. Starting with Windows PowerShell 3.0, it is possible to manage ADS natively with six cmdlets: Add-Content, Clear-Content, Get-Content, Get-Item, Remove-Item, Set-Content.[59]

Malware has used alternate data streams to hide code.[60] As a result, malware scanners and other special tools now check for alternate data streams.

File compression[edit]

Compression is enabled on a per-folder or per-file basis by setting the ‘compressed’ attribute. When compression is enabled on a folder, any files moved or saved to that folder will be automatically compressed using LZNT1 algorithm (a variant of LZ77).[61] The compression algorithm is designed to support cluster sizes of up to 4 KB; when the cluster size is greater than 4 KB on an NTFS volume, NTFS compression is not available.[62] Data is compressed in 16-cluster chunks (up to 64 KB in size); if the compression reduces 64 KB of data to 60 KB or less, NTFS treats the unneeded 4 KB pages like empty sparse file clusters—they are not written. This allows for reasonable random-access times as the OS merely has to follow the chain of fragments.

Compression works best with files that have repetitive content, are seldom written, are usually accessed sequentially, and are not themselves compressed. Single-user systems with limited hard disk space can benefit from NTFS compression for small files, from 4 KB to 64 KB or more, depending on compressibility. Files smaller than approximately 900 bytes are stored within the directory entry of the MFT.[63]

Advantages[edit]

Users of fast multi-core processors will find improvements in application speed by compressing their applications and data as well as a reduction in space used. Even when SSD controllers already compress data, there is still a reduction in I/Os since less data is transferred.[64]

According to research by Microsoft’s NTFS Development team, 50–60 GB is a reasonable maximum size for a compressed file on an NTFS volume with a 4 KB (default) cluster (block) size. This reasonable maximum size decreases sharply for volumes with smaller cluster sizes.[65]

Disadvantages[edit]

Large compressible files become highly fragmented since every chunk smaller than 64 KB becomes a fragment.[65][66] Flash memory, such as SSD drives do not have the head movement delays and high access time of mechanical hard disk drives, so fragmentation has only a smaller penalty.

If system files that are needed at boot time (such as drivers, NTLDR, winload.exe, or BOOTMGR) are compressed, the system may fail to boot correctly, because decompression filters are not yet loaded.[67][failed verification] Later editions of Windows[which?] do not allow important system files to be compressed.

System compression[edit]


Since Windows 10, Microsoft has introduced new file compression scheme based on the XPRESS algorithm with 4K/8K/16K block size[68] and the LZX algorithm;[69] both are variants of LZ77 updated with Huffman entropy coding and range coding, which LZNT1 lacked. These compression algorithms were taken from Windows Imaging Format (WIM file).

The new compression scheme is used by CompactOS feature, which reduces disk usage by compressing Windows system files.[70] CompactOS is not an extension of NTFS file compression and does not use the ‘compressed’ attribute; instead, it sets a reparse point on each compressed file with a WOF (Windows Overlay Filter) tag,[71] but the actual data is stored in an alternate data stream named «WofCompressedData», which is decompressed on-the-fly by a WOF filesystem filter driver, and the main file is an empty sparse file.[71] This design is meant purely for read-only access, so any writes to compressed files result in an automatic decompression.[71][72][73]

CompactOS compression is intended for OEMs who prepare OS images with the /compact flag of the DISM tool in Windows ADK,[74] but it can also be manually turned on per file with the /exe flag of the compact command.[75] CompactOS algorithm avoids file fragmentation by writing compressed data in contiguously allocated chunks, unlike core NTFS compression.[citation needed]

CompactOS file compression is an improved version of WIMBoot feature introduced in Windows 8.1. WIMBoot reduces Windows disk usage by keeping system files in a compressed WIM image on a separate hidden disk partition.[76] Similarly to CompactOS, Windows system directories only contain sparse files marked by a reparse point with a WOF tag, and Windows Overlay Filter driver decompresses file contents on-the-fly from the WIM image. WIMBoot is less effective than CompactOS though, as new updated versions of system files need to be written to the system partition, consuming disk space.[71]

Sparse files[edit]

A sparse file: Empty bytes don’t need to be saved, thus they can be represented by metadata.

One petabyte (1,125,899,906,842,624 bytes) of sparse files, 0 bytes on disk.

Sparse files are files interspersed with empty segments for which no actual storage space is used. To the applications, the file looks like an ordinary file with empty regions seen as regions filled with zeros; the file system maintains an internal list of such regions for each sparse file.[77] A sparse file does not necessarily include sparse zeros areas; the «sparse file» attribute just means that the file is allowed to have them.

Database applications, for instance, may use sparse files.[78] As with compressed files, the actual sizes of sparse files are not taken into account when determining quota limits.[79]

Volume Shadow Copy[edit]

The Volume Shadow Copy Service (VSS) keeps historical versions of files and folders on NTFS volumes by copying old, newly overwritten data to shadow copy via copy-on-write technique. The user may later request an earlier version to be recovered. This also allows data backup programs to archive files currently in use by the file system.

Windows Vista also introduced persistent shadow copies for use with System Restore and Previous Versions features. Persistent shadow copies, however, are deleted when an older operating system mounts that NTFS volume. This happens because the older operating system does not understand the newer format of persistent shadow copies.[80]

Transactions[edit]

As of Windows Vista, applications can use Transactional NTFS (TxF) to group multiple changes to files together into a single transaction. The transaction will guarantee that either all of the changes happen, or none of them do, and that no application outside the transaction will see the changes until they are committed.[81]

It uses similar techniques as those used for Volume Shadow Copies (i.e. copy-on-write) to ensure that overwritten data can be safely rolled back, and a CLFS log to mark the transactions that have still not been committed, or those that have been committed but still not fully applied (in case of system crash during a commit by one of the participants).

Transactional NTFS does not restrict transactions to just the local NTFS volume, but also includes other transactional data or operations in other locations such as data stored in separate volumes, the local registry, or SQL databases, or the current states of system services or remote services. These transactions are coordinated network-wide with all participants using a specific service, the DTC, to ensure that all participants will receive same commit state, and to transport the changes that have been validated by any participant (so that the others can invalidate their local caches for old data or rollback their ongoing uncommitted changes). Transactional NTFS allows, for example, the creation of network-wide consistent distributed file systems, including with their local live or offline caches.

Microsoft now advises against using TxF: «Microsoft strongly recommends developers utilize alternative means» since «TxF may not be available in future versions of Microsoft Windows».[82]

Quotas[edit]

Disk quotas were introduced in NTFS v3. They allow the administrator of a computer that runs a version of Windows that supports NTFS to set a threshold of disk space that users may use. It also allows administrators to keep track of how much disk space each user is using. An administrator may specify a certain level of disk space that a user may use before they receive a warning, and then deny access to the user once they hit their upper limit of space. Disk quotas do not take into account NTFS’s transparent file-compression, should this be enabled. Applications that query the amount of free space will also see the amount of free space left to the user who has a quota applied to them.

Reparse points[edit]

Introduced in NTFS v3, NTFS reparse points are used by associating a reparse tag in the user space attribute of a file or directory. Microsoft includes several default tags including symbolic links, directory junction points and volume mount points. When the Object Manager parses a file system name lookup and encounters a reparse attribute, it will reparse the name lookup, passing the user controlled reparse data to every file system filter driver that is loaded into Windows. Each filter driver examines the reparse data to see whether it is associated with that reparse point, and if that filter driver determines a match, then it intercepts the file system request and performs its special functionality.

Limitations[edit]

Resizing[edit]

Starting with Windows Vista Microsoft added the built-in ability to shrink or expand a partition. However, this ability does not relocate page file fragments or files that have been marked as unmovable, so shrinking a volume will often require relocating or disabling any page file, the index of Windows Search, and any Shadow Copy used by System Restore. Various third-party tools are capable of resizing NTFS partitions.

OneDrive[edit]

Since 2017, Microsoft requires the OneDrive file structure to reside on an NTFS disk.[83] This is because OneDrive Files On-Demand feature uses NTFS reparse points to link files and folders that are stored in OneDrive to the local filesystem, making the file or folder unusable with any previous version of Windows, with any other NTFS file system driver, or any file system and backup utilities not updated to support it.[84]

Structure[edit]

NTFS is made up of several components including: a partition boot sector (PBS) that holds boot information; the master file table that stores a record of all files and folders in the filesystem; a series of meta files that help structure meta data more efficiently; data streams and locking mechanisms.

Internally, NTFS uses B-trees to index file system data. A file system journal is used to guarantee the integrity of the file system metadata but not individual files’ content. Systems using NTFS are known to have improved reliability compared to FAT file systems.[85]

NTFS allows any sequence of 16-bit values for name encoding (e.g. file names, stream names or index names) except 0x0000. This means UTF-16 code units are supported, but the file system does not check whether a sequence is valid UTF-16 (it allows any sequence of short values, not restricted to those in the Unicode standard). In Win32 namespace, any UTF-16 code units are case insensitive whereas in POSIX namespace they are case sensitive. File names are limited to 255 UTF-16 code units. Certain names are reserved in the volume root directory and cannot be used for files. These are $MFT, $MFTMirr, $LogFile, $Volume, $AttrDef, . (dot), $Bitmap, $Boot, $BadClus, $Secure, $UpCase, and $Extend.[5] . (dot) and $Extend are both directories; the others are files. The NT kernel limits full paths to 32,767 UTF-16 code units. There are some additional restrictions on code points and file names.[86]

Partition Boot Sector (PBS)[edit]

This boot partition format is roughly based upon the earlier FAT filesystem, but the fields are in different locations. Some of these fields, especially the «sectors per track», «number of heads» and «hidden sectors» fields may contain dummy values on drives where they either do not make sense or are not determinable.

The OS first looks at the 8 bytes at 0x30 to find the cluster number of the $MFT, then multiplies that number by the number of sectors per cluster (1 byte found at 0x0D). This value is the sector offset (LBA) to the $MFT, which is described below.

Master File Table[edit]

In NTFS, all file, directory and metafile data—file name, creation date, access permissions (by the use of access control lists), and size—are stored as metadata in the Master File Table (MFT). This abstract approach allowed easy addition of file system features during Windows NT’s development—an example is the addition of fields for indexing used by the Active Directory and the Windows Search. This also enables fast file search software to locate named local files and folders included in the MFT very quickly, without requiring any other index.

The MFT structure supports algorithms which minimize disk fragmentation.[89] A directory entry consists of a filename and a «file ID» (analogous to the inode number), which is the record number representing the file in the Master File Table. The file ID also contains a reuse count to detect stale references. While this strongly resembles the W_FID of Files-11, other NTFS structures radically differ.

A partial copy of the MFT, called the MFT mirror, is stored to be used in case of corruption.[90] If the first record of the MFT is corrupted, NTFS reads the second record to find the MFT mirror file. Locations for both files are stored in the boot sector.[91]

Metafiles[edit]

NTFS contains several files that define and organize the file system. In all respects, most of these files are structured like any other user file ($Volume being the most peculiar), but are not of direct interest to file system clients.[92] These metafiles define files, back up critical file system data, buffer file system changes, manage free space allocation, satisfy BIOS expectations, track bad allocation units, and store security and disk space usage information. All content is in an unnamed data stream, unless otherwise indicated.

These metafiles are treated specially by Windows, handled directly by the NTFS.SYS driver and are difficult to directly view: special purpose-built tools are needed.[93] As of Windows 7, the NTFS driver completely prohibits user access, resulting in a BSoD whenever an attempt to execute a metadata file is made. One such tool is the nfi.exe («NTFS File Sector Information Utility») that is freely distributed as part of the Microsoft «OEM Support Tools». For example, to obtain information on the «$MFT»-Master File Table Segment the following command is used: nfi.exe c:$MFT[94] Another way to bypass the restriction is to use 7-Zip’s file manager and go to the low-level NTFS path \.X: (where X: resembles any drive/partition). Here, 3 new folders will appear: $EXTEND, [DELETED] (a pseudo-folder that 7-Zip uses to attach files deleted from the file system to view), and [SYSTEM] (another pseudo-folder that contains all the NTFS metadata files). This trick can be used from removable devices (USB flash drives, external hard drives, SD Cards, etc.) inside Windows, but doing this on the active partition requires offline access (namely WinRE).

Attribute lists, attributes, and streams[edit]

For each file (or directory) described in the MFT record, there is a linear repository of stream descriptors (also named attributes), packed together in one or more MFT records (containing the so-called attributes list), with extra padding to fill the fixed 1 KB size of every MFT record, and that fully describes the effective streams associated with that file.

Each attribute has an attribute type (a fixed-size integer mapping to an attribute definition in file $AttrDef), an optional attribute name (for example, used as the name for an alternate data stream), and a value, represented in a sequence of bytes. For NTFS, the standard data of files, the alternate data streams, or the index data for directories are stored as attributes.

According to $AttrDef, some attributes can be either resident or non-resident. The $DATA attribute, which contains file data, is such an example. When the attribute is resident (which is represented by a flag), its value is stored directly in the MFT record. Otherwise, clusters are allocated for the data, and the cluster location information is stored as data runs in the attribute.

  • For each file in the MFT, the attributes identified by attribute type, attribute name must be unique. Additionally, NTFS has some ordering constraints for these attributes.
  • There is a predefined null attribute type, used to indicate the end of the list of attributes in one MFT record. It must be present as the last attribute in the record (all other storage space available after it will be ignored and just consists of padding bytes to match the record size in the MFT).
  • Some attribute types are required and must be present in each MFT record, except unused records that are just indicated by null attribute types.
    • This is the case for the $STANDARD_INFORMATION attribute that is stored as a fixed-size record and contains the timestamps and other basic single-bit attributes (compatible with those managed by FAT in DOS or Windows 9x).
  • Some attribute types cannot have a name and must remain anonymous.
    • This is the case for the standard attributes, or for the preferred NTFS «filename» attribute type, or the «short filename» attribute type, when it is also present (for compatibility with DOS-like applications, see below). It is also possible for a file to contain only a short filename, in which case it will be the preferred one, as listed in the Windows Explorer.
    • The filename attributes stored in the attribute list do not make the file immediately accessible through the hierarchical file system. In fact, all the filenames must be indexed separately in at least one other directory on the same volume. There it must have its own MFT record and its own security descriptors and attributes that reference the MFT record number for this file. This allows the same file or directory to be «hardlinked» several times from several containers on the same volume, possibly with distinct filenames.
  • The default data stream of a regular file is a stream of type $DATA but with an anonymous name, and the ADSs are similar but must be named.
  • On the other hand, the default data stream of directories has a distinct type, but are not anonymous: they have an attribute name («$I30» in NTFS 3+) that reflects its indexing format.

All attributes of a given file may be displayed by using the nfi.exe («NTFS File Sector Information Utility») that is freely distributed as part of the Microsoft «OEM Support Tools».[94]

Windows system calls may handle alternate data streams.[5] Depending on the operating system, utility and remote file system, a file transfer might silently strip data streams.[5] A safe way of copying or moving files is to use the BackupRead and BackupWrite system calls, which allow programs to enumerate streams, to verify whether each stream should be written to the destination volume and to knowingly skip unwanted streams.[5]

Resident vs. non-resident attributes[edit]

To optimize the storage and reduce the I/O overhead for the very common case of attributes with very small associated value, NTFS prefers to place the value within the attribute itself (if the size of the attribute does not then exceed the maximum size of an MFT record), instead of using the MFT record space to list clusters containing the data; in that case, the attribute will not store the data directly but will just store an allocation map (in the form of data runs) pointing to the actual data stored elsewhere on the volume.[95] When the value can be accessed directly from within the attribute, it is called «resident data» (by computer forensics workers). The amount of data that fits is highly dependent on the file’s characteristics, but 700 to 800 bytes is common in single-stream files with non-lengthy filenames and no ACLs.

  • Some attributes (such as the preferred filename, the basic file attributes) cannot be made non-resident. For non-resident attributes, their allocation map must fit within MFT records.
  • Encrypted-by-NTFS, sparse data streams, or compressed data streams cannot be made resident.
  • The format of the allocation map for non-resident attributes depends on its capability of supporting sparse data storage. In the current implementation of NTFS, once a non-resident data stream has been marked and converted as sparse, it cannot be changed back to non-sparse data, so it cannot become resident again, unless this data is fully truncated, discarding the sparse allocation map completely.
  • When a non-resident attribute is so fragmented, that its effective allocation map cannot fit entirely within one MFT record, NTFS stores the attribute in multiple records. The first one among them is called the base record, while the others are called extension records. NTFS creates a special attribute $ATTRIBUTE_LIST to store information mapping different parts of the long attribute to the MFT records, which means the allocation map may be split into multiple records. The $ATTRIBUTE_LIST itself can also be non-resident, but its own allocation map must fit within one MFT record.
  • When there are too many attributes for a file (including ADS’s, extended attributes, or security descriptors), so that they cannot fit all within the MFT record, extension records may also be used to store the other attributes, using the same format as the one used in the base MFT record, but without the space constraints of one MFT record.

The allocation map is stored in a form of data runs with compressed encoding. Each data run represents a contiguous group of clusters that store the attribute value. For files on a multi-GB volume, each entry can be encoded as 5 to 7 bytes, which means a 1 KB MFT record can store about 100 such data runs. However, as the $ATTRIBUTE_LIST also has a size limit, it is dangerous to have more than 1 million fragments of a single file on an NTFS volume, which also implies that it is in general not a good idea to use NTFS compression on a file larger than 10 GB.[96]

The NTFS file system driver will sometimes attempt to relocate the data of some of the attributes that can be made non-resident into the clusters, and will also attempt to relocate the data stored in clusters back to the attribute inside the MFT record, based on priority and preferred ordering rules, and size constraints.

Since resident files do not directly occupy clusters («allocation units»), it is possible for an NTFS volume to contain more files on a volume than there are clusters. For example, a 74.5 GB partition NTFS formats with 19,543,064 clusters of 4 KB. Subtracting system files (a 64 MB log file, a 2,442,888-byte Bitmap file, and about 25 clusters of fixed overhead) leaves 19,526,158 clusters free for files and indices. Since there are four MFT records per cluster, this volume theoretically could hold almost 4 × 19,526,158 = 78,104,632 resident files.

Opportunistic locks[edit]

Opportunistic file locks (oplocks) allow clients to alter their buffering strategy for a given file or stream in order to increase performance and reduce network use.[97] Oplocks apply to the given open stream of a file and do not affect oplocks on a different stream.

Oplocks can be used to transparently access files in the background. A network client may avoid writing information into a file on a remote server if no other process is accessing the data, or it may buffer read-ahead data if no other process is writing data.

Windows supports four different types of oplocks:

  • Level 2 (or shared) oplock: multiple readers, no writers (i.e. read caching).
  • Level 1 (or exclusive) oplock: exclusive access with arbitrary buffering (i.e. read and write caching).
  • Batch oplock (also exclusive): a stream is opened on the server, but closed on the client machine (i.e. read, write and handle caching).
  • Filter oplock (also exclusive): applications and file system filters can «back out» when others try to access the same stream (i.e. read and write caching) (since Windows 2000)

Opportunistic locks have been enhanced in Windows 7 and Windows Server 2008 R2 with per-client oplock keys.[98]

Time[edit]

Windows NT and its descendants keep internal timestamps as UTC and make the appropriate conversions for display purposes; all NTFS timestamps are in UTC.[citation needed]

For historical reasons, the versions of Windows that do not support NTFS all keep time internally as local zone time, and therefore so do all file systems – other than NTFS – that are supported by current versions of Windows. This means that when files are copied or moved between NTFS and non-NTFS partitions, the OS needs to convert timestamps on the fly. But if some files are moved when daylight saving time (DST) is in effect, and other files are moved when standard time is in effect, there can be some ambiguities in the conversions. As a result, especially shortly after one of the days on which local zone time changes, users may observe that some files have timestamps that are incorrect by one hour. Due to the differences in implementation of DST in different jurisdictions, this can result in a potential timestamp error of up to 4 hours in any given 12 months.[99]

See also[edit]

  • Comparison of file systems
  • NTFSDOS
  • ntfsresize
  • WinFS (a canceled Microsoft filesystem)
  • ReFS, a newer Microsoft filesystem

Notes[edit]

  1. ^ a b c d e f g h i 1 byte = 8 bits
    1 KB = 1,024 bytes
    1 MB = 1,048,576 bytes
    1 GB = 1,073,741,824 bytes
    1 TB = 1,099,511,627,776 bytes
    1 PB = 1,125,899,906,842,624 bytes
    1 EB = 1,152,921,504,606,846,976 bytes

References[edit]

  1. ^ a b c Karresand, Martin; Axelsson, Stefan; Dyrkolbotn, Geir Olav (2019-07-01). «Using NTFS Cluster Allocation Behavior to Find the Location of User Data». Digital Investigation. 29: –51–S60. doi:10.1016/j.diin.2019.04.018. ISSN 1742-2876. S2CID 199004263. Retrieved 2021-12-01.
  2. ^ a b «Glossary». [MS-EFSR]: Encrypting File System Remote (EFSRPC) Protocol. Microsoft. 14 November 2013.
  3. ^ «How NTFS Works». TechNet. Microsoft. Retrieved 2 December 2017.
  4. ^ «B*Trees — NTFS Directory Trees — Concept — NTFS Documentation». flatcap.org. Archived from the original on 2019-05-13. Retrieved 2019-05-13.
  5. ^ a b c d e f g «How NTFS Works». Windows Server 2003 Technical Reference. 2003-03-28. Retrieved 2011-09-12.
  6. ^ a b c d «Appendix A: Product Behavior». [MS-FSA]: File System Algorithms. Microsoft. 2018-09-12. Retrieved 2018-10-01. NTFS uses a default cluster size of 4 KB, a maximum cluster size of 64 KB on Windows 10 v1703 operating system and Windows Server 2016 and prior, and 2 MB on Windows 10 v1709 operating system and Windows Server 2019 and later, and a minimum cluster size of 512 bytes.
  7. ^ «Appendix A: Product Behavior». [MS-FSA]: File System Algorithms. Microsoft. 14 November 2013. Retrieved 2012-09-21.
  8. ^ a b Russon, Richard; Fledel, Yuval. «NTFS Documentation» (PDF). Archived (PDF) from the original on 2022-10-09. Retrieved 2011-06-26.
  9. ^ «WineHQ Bugzilla – Bug 51808 – the issue with trailing spaces (Spaces at the end of a filename)».
  10. ^ Rick Vanover (14 September 2011). «Windows Server 8 data deduplication». Retrieved 2011-12-02.
  11. ^ a b Custer, Helen (1994). Inside the Windows NT File System. Microsoft Press. ISBN 978-1-55615-660-1.
  12. ^ «NTFS3 — The Linux Kernel documentation». www.kernel.org. Retrieved 2021-12-02.
  13. ^ «ntfs-3g». www.freebsd.org. Retrieved 2021-12-02.
  14. ^ «How to Convert a Drive from FAT32 to NTFS without Data Loss». WindowsLoop. 11 July 2021. Retrieved 8 August 2021.
  15. ^ a b cfsbloggers (July 14, 2006). «How restore points and other recovery features in Windows Vista are affected when dual-booting with Windows XP». The Filing Cabinet. Retrieved 2007-03-21.
  16. ^ Kozierok, Charles (14 February 2018). «Overview and History of NTFS». The PC Guide. Retrieved May 30, 2019.
  17. ^ Custer, Helen (1994). Inside the Windows NT File System. Microsoft Press. p. vii. ISBN 978-1-55615-660-1.
  18. ^ «Recovering Windows NT After a Boot Failure on an NTFS Drive». Microsoft. November 1, 2006.
  19. ^ a b Russinovich, Mark. «Inside Win2K NTFS, Part 1». MSDN. Microsoft. Retrieved 2008-04-18.
  20. ^ «What’s New in Windows NT 4.0 Service Pack 4?». Microsoft.com. 12 January 1999. Archived from the original on 17 January 1999. Retrieved 17 August 2018.
  21. ^ «New Capabilities and Features of the NTFS 3.1 File System». Microsoft. 1 December 2007.
  22. ^ Loveall, John (2006). «Storage improvements in Windows Vista and Windows Server 2008» (PowerPoint). Microsoft. pp. 14–20. Retrieved 2007-09-04.
  23. ^ «Booting from GPT». Rodsbooks.com. Retrieved 22 September 2018.
  24. ^ «NTFS vs FAT vs exFAT — NTFS.com». www.ntfs.com. Retrieved 2021-01-19.
  25. ^ «How to Convert FAT Disks to NTFS». Microsoft. 18 December 2017. Retrieved May 30, 2019.
  26. ^ «How to use Convert.exe to convert a partition to the NTFS file system». Microsoft Corporation. 2007-02-12. Retrieved 2010-12-26.
  27. ^ «FreeBSD 3.2 Release Notes». 17 May 1999. Retrieved 2020-06-15.
  28. ^ a b «mount_ntfs — OpenBSD manual pages». Retrieved 2020-06-15.
  29. ^ «Announcing NetBSD 1.5». 6 December 2000. Retrieved 2020-06-15.
  30. ^ «OpenBSD 4.9». Openbsd.com. Retrieved 22 September 2018.
  31. ^ a b «NTFS Credits and History». Linux-NTFS Project. Retrieved 2021-09-05.
  32. ^ «Kernel development». lwn.net. 2 May 2002. Retrieved 2021-09-05.
  33. ^ «Release notes for v2.5.11». 29 April 2002. Retrieved 2021-09-05.
  34. ^ «2.6.15 changelog». Linux project. 3 January 2006. Retrieved 2021-09-05.
  35. ^ Anderson, Tim (2021-09-06). «GitHub merges ‘useless garbage’ says Linus Torvalds as new NTFS support added to Linux kernel 5.15». The Register. Retrieved 2021-09-07.
  36. ^ «OpenBSD adds fuse(4) support for adding file systems in userland». OpenBSD Journal. 2013-11-08. Retrieved 2013-11-08.
  37. ^ «NTFS-3G Stable Read/Write Driver». 2009-07-25.
  38. ^ «Tuxera NTFS for Mac». Tuxera. August 30, 2011. Retrieved September 20, 2011.
  39. ^ «Jan Kratochvil: Captive: The first free NTFS read/write filesystem for GNU/Linux». Retrieved 2020-06-15.
  40. ^ «About Tuxera». Retrieved 2020-06-15.
  41. ^ «10.6: Enable native NTFS read/write support». 1 October 2009. Retrieved 5 September 2021.
  42. ^ «NTFS for Mac OS X, communication channel between Mac OS X and Windows». Paragon Software Group. Retrieved September 20, 2011.
  43. ^ «The Leader in Mass Data Storage Solutions | Seagate US». Seagate.com. Archived from the original on February 10, 2011.
  44. ^ «NTFS plugin for NetDrive». ecsoft2.org. Retrieved 2020-09-09.
  45. ^ «NetDrive for OS/2». arcanoae.com. Retrieved 2020-09-09.
  46. ^ «Avira NTFS4DOS Personal». Archived from the original on June 19, 2010. Retrieved 2009-07-25.
  47. ^ «Download Avira NTFS4DOS Personal 1.9». Archived from the original on 10 November 2013. Retrieved 22 September 2018.
  48. ^ a b «How Security Descriptors and Access Control Lists Work». TechNet. Microsoft. Retrieved 4 September 2015.
  49. ^ Morello, John (February 2007). «Security Watch Deploying EFS: Part 1». Technet Magazine. Microsoft. Retrieved 2009-01-25.
  50. ^ «How EFS Works». Windows 2000 Resource Kit. Microsoft. Retrieved 25 February 2014.
  51. ^ «Windows 8 volume compatibility considerations with prior versions of Windows». Retrieved 2021-12-17.
  52. ^ «Change Journals (Windows)». MSDN. Retrieved 2010-04-16.
  53. ^ «Creating, Modifying, and Deleting a Change Journal (Windows)». MSDN. Retrieved 2010-04-16.
  54. ^ «Chapter 29 – POSIX Compatibility». MS Windows NT Workstation 4.0 Resource Guide. Microsoft. 1995. Retrieved 21 October 2013.
  55. ^ «Hard Links and Junctions». MSDN. Microsoft. 12 October 2013. Retrieved 21 October 2013.
  56. ^ «MSDN – CreateHardLink function». Retrieved 14 January 2016.
  57. ^ Russinovich, Mark E.; Solomon, David A.; Ionescu, Alex (2009). «File Systems». Windows Internals (5th ed.). Microsoft Press. p. 921. ISBN 978-0-7356-2530-3. One component in Windows that uses multiple data streams is the Attachment Execution Service[…] depending on which zone the file was downloaded from […] Windows Explorer might warn the user
  58. ^ «Streams — Windows Sysinternals». Technet.microsoft.com. Retrieved 22 September 2018.
  59. ^ «FileSystem Provider». Microsoft. 9 August 2012. Archived from the original on 23 January 2015. Retrieved 23 January 2015.
  60. ^ Malware utilising Alternate Data Streams? Archived 2008-07-23 at the Wayback Machine, AusCERT Web Log, 21 August 2007
  61. ^ «File Compression and Decompression». MSDN Platform SDK: File Systems. Retrieved 2005-08-18.
  62. ^ «The Default Cluster Size for the NTFS and FAT File Systems». Microsoft. January 31, 2002. Retrieved 2012-01-10.
  63. ^ «How NTFS Works». 2003-03-28. Retrieved 2011-10-24.
  64. ^ Masiero, Manuel (2011-12-01). «Should You Compress Data On Your SSD?». Tom’s Hardware. Bestofmedia Group. Retrieved 2013-04-05.
  65. ^ a b Middleton, Dennis. «Understanding NTFS Compression». Ntdebugging Blog. Microsoft. Retrieved 2011-03-16.
  66. ^ «Shrinking the gap: carving NTFS-compressed files». Retrieved 2011-05-29.
  67. ^ «Disk Concepts and Troubleshooting». Microsoft. Retrieved 2012-03-26.
  68. ^ «[MS-XCA]: Xpress Compression Algorithm».
  69. ^ wimlib: the open source Windows Imaging (WIM) library — Compression algorithm
  70. ^ «Compact OS, single-instancing, and image optimization». Microsoft. Retrieved 1 October 2019.
  71. ^ a b c d Raymond Chen.What is WofCompressedData? Does WOF mean that Windows is a dog? Microsoft DevBlogs.
  72. ^ Biggers, Eric (29 April 2019). «NTFS-3G plugin for reading «system compressed» files». GitHub. Retrieved 1 October 2019.
  73. ^ «Re: [ntfs-3g-devel] Experimental support for Windows 10 «System Compressed» files». SourceForge.net. Retrieved 1 October 2019.
  74. ^ «DISM Overview».
  75. ^ «Compact».
  76. ^ Windows Image File Boot (WIMBoot) Overview
  77. ^ «Sparse Files». MSDN. Microsoft. 12 October 2013. Retrieved 21 October 2013.
  78. ^ Kandoth, Suresh B. (4 March 2009). «Sparse File Errors: 1450 or 665 due to file fragmentation: Fixes and Workarounds». CSS SQL Server Engineers. Microsoft. Retrieved 21 October 2013.
  79. ^ «Sparse Files and Disk Quotas». MSDN Library. Microsoft. 12 October 2013. Retrieved 21 October 2013.
  80. ^ cfsbloggers (July 14, 2006). «How restore points and other recovery features in Windows Vista are affected when you dual-boot with Windows XP». The Filing Cabinet. Retrieved 2007-03-21.
  81. ^ «Transactional NTFS». MSDN. Microsoft. Retrieved 2007-02-02.
  82. ^ «Transactional NTFS (TxF)». Windows Dev Center (MSDN). Microsoft. Retrieved 24 May 2015.
  83. ^ «Unable to open content synced in a OneDrive folder on an external drive». Microsoft Support. Retrieved 2021-04-03.
  84. ^ André, Jean-Pierre (March 1, 2019). «NTFS-3G: Junction Points, Symbolic Links and Reparse Points». jp-andre.pagesperso-orange.fr.
  85. ^ «Chapter 18 – Choosing a File System». MS Windows NT Workstation 4.0 Resource Guide. Microsoft. Retrieved 25 February 2014.
  86. ^ «Naming Files, Paths, and Namespaces». MSDN. Microsoft. Naming Conventions. Retrieved 25 February 2014.
  87. ^ «NTFS. Partition Boot Sector». Ntfs.com. Retrieved 22 September 2018.
  88. ^ «Boot Sector». Technet.microsoft.com. September 11, 2008. Table 1.13 BPB and Extended BPB Fields on NTFS Volumes. Retrieved 22 September 2018.
  89. ^ «Master File Table». MSDN. July 2, 2012.
  90. ^ «Forensics: What is the MFT Mirror?». Where is Your Data?. 2009-06-05. Retrieved 2021-07-30.
  91. ^ «NTFS Master File Table (MFT)». Ntfs.com. Retrieved 22 September 2018.
  92. ^ Schwarz, Thomas. «COEN 252 Computer Forensics NTFS». Faculty of Organization and Informatics University of Zagreb. Archived from the original on 2021-02-27. Retrieved May 30, 2019.
  93. ^ Since Windows XP, it is very difficult to view a listing of these files: they exist in the root directory’s index, but the Win32 interface filters them out. In NT 4.0, the command line dir command would list the metafiles in the root directory if /a were specified. In Windows 2000, dir /a stopped working, but dir /a $MFT worked.
  94. ^ a b «OEM Support Tools Phase 3 Service Release 2 Availability». Microsoft Corporation. 2007-02-21. Archived from the original on 2015-02-23. Retrieved 2010-06-16. Windows NT File System (NTFS) File Sector Information Utility … A tool used to dump information about an NTFS volume
  95. ^ «The Four Stages of NTFS File Growth». Retrieved 22 September 2018.
  96. ^ «A heavily fragmented file in an NTFS volume may not grow beyond a certain size». Archived from the original on 2021-05-06. Retrieved 2021-05-19.
  97. ^ «How Oplocks function in the Windows Environment: Overview». Archived from the original on 2010-08-23. Retrieved 2018-12-19.
  98. ^ «What’s New in NTFS». Technet.microsoft.com. Retrieved 22 September 2018.
  99. ^ «Beating the Daylight Saving Time bug and getting correct file modification times Archived 2004-11-14 at the Wayback Machine» The Code Project

Further reading[edit]

  • Bolosky, William J.; Corbin, Scott; Goebel, David; Douceur, John R. (January 2000). «Single Instance Storage in Windows 2000». Proceedings of 4th USENIX Windows Systems Symposium.
  • Custer, Helen (1994). Inside the Windows NT File System. Microsoft Press. ISBN 978-1-55615-660-1.
  • Nagar, Rajeev (1997). Windows NT File System Internals: A Developer’s Guide. O’Reilly. ISBN 978-1-56592-249-5.
  • «NTFS Technical Reference». Microsoft TechNet. Microsoft. 28 March 2003.

New Technology File System[1]

Developer(s) Microsoft
Full name NT File System[2]
Introduced July 1993; 29 years ago with Windows NT 3.1
Partition identifier 0x07 (MBR)
EBD0A0A2-B9E5-4433-87C0-68B6B72699C7 (GPT)
Structures
Directory contents B-tree variant[3][4]
File allocation Bitmap
Bad blocks $BadClus (MFT Record)
Limits
Max. volume size 264 clusters − 1 cluster (format);
256 TB[a] − 64 KB[a] (Windows 10 version 1703, Windows Server 2016 or earlier implementation)[5]
8 PB − 2 MB[a] (Windows 10 version 1709, Windows Server 2019 or later implementation)[6]
Max. file size 16 EB[a] − 1 KB (format);
16 TB − 64 KB (Windows 7, Windows Server 2008 R2 or earlier implementation)[5]
256 TB − 64 KB (Windows 8, Windows Server 2012 or later implementation)[7]
8 PB − 2 MB (Windows 10 version 1709, Windows Server 2019 or later implementation)[6]
Max. number of files 4,294,967,295 (232−1)[5]
Max. filename length 255 UTF-16 code units[8]
Allowed characters in filenames
  • In Win32 namespace: any UTF-16 code unit (case-insensitive) except /:*"?<>| as well as NUL[8]
  • In POSIX namespace: any UTF-16 code unit (case-sensitive) except / as well as NUL
  • Trailing spaces are not allowed and will be removed[9]
Features
Dates recorded Creation, modification, POSIX change, access
Date range 1 January 1601 – 28 May 60056 (File times are 63-bit numbers counting 100-nanosecond intervals (ten million per second) since 1601, which is 29,227 years)
Date resolution 100 ns
Forks Yes (see § Alternate data stream (ADS) below)
Attributes Read-only, hidden, system, archive, not content indexed, off-line, temporary, compressed, encrypted
File system permissions ACLs
Transparent compression Per-file, LZ77 (Windows NT 3.51 onward)
Transparent encryption Per-file,
DESX (Windows 2000 onward),
Triple DES (Windows XP onward),
AES (Windows XP Service Pack 1, Windows Server 2003 onward)
Data deduplication Yes (Windows Server 2012)[10]
Other
Supported operating systems Windows NT 3.1 and later
Mac OS X 10.3 and later (read-only)
Linux kernel version 2.6 and later
Linux kernel versions 2.2-2.4 (read-only)
FreeBSD
NetBSD
OpenBSD (read-only)
ChromeOS
Solaris
ReactOS (read-only)

New Technology File System (NTFS) is a proprietary journaling file system developed by Microsoft.[2][1] Starting with Windows NT 3.1, it is the default file system of the Windows NT family.[11] It superseded File Allocation Table (FAT) as the preferred filesystem on Windows and is supported in Linux and BSD as well. NTFS reading and writing support is provided using a free and open-source kernel implementation known as NTFS3 in Linux and the NTFS-3G driver in BSD.[12][13] By using the convert command, Windows can convert FAT32/16/12 into NTFS without the need to rewrite all files.[14] NTFS uses several files typically hidden from the user to store metadata about other files stored on the drive which can help improve speed and performance when reading data.[1] Unlike FAT and High Performance File System (HPFS), NTFS supports access control lists (ACLs), filesystem encryption, transparent compression, sparse files and file system journaling. NTFS also supports shadow copy to allow backups of a system while it is running, but the functionality of the shadow copies varies between different versions of Windows.[15]

History[edit]

In the mid-1980s, Microsoft and IBM formed a joint project to create the next generation of graphical operating system; the result was OS/2 and HPFS. Because Microsoft disagreed with IBM on many important issues, they eventually separated; OS/2 remained an IBM project and Microsoft worked to develop Windows NT and NTFS.

The HPFS file system for OS/2 contained several important new features. When Microsoft created their new operating system, they «borrowed» many of these concepts for NTFS.[16] The original NTFS developers were Tom Miller, Gary Kimura, Brian Andrew, and David Goebel.[17]

Probably as a result of this common ancestry, HPFS and NTFS use the same disk partition identification type code (07). Using the same Partition ID Record Number is highly unusual, since there were dozens of unused code numbers available, and other major file systems have their own codes. For example, FAT has more than nine (one each for FAT12, FAT16, FAT32, etc.). Algorithms identifying the file system in a partition type 07 must perform additional checks to distinguish between HPFS and NTFS.

Versions[edit]

Microsoft has released five versions of NTFS:

NTFS version number First operating system Release date New features Remarks
1.0 Windows NT 3.1 1993[11] Initial version NTFS 1.0 is incompatible with 1.1 and newer: volumes written by Windows NT 3.5x cannot be read by Windows NT 3.1 until an update (available on the NT 3.5x installation media) is installed.[18]
1.1 Windows NT 3.51 1995 Compressed files, named streams, and access control lists[19]
1.2 Windows NT 4.0 1996 Security descriptors Commonly called NTFS 4.0 after the OS release
3.0 Windows 2000 2000 Disk quotas, file-level encryption in a form of Encrypting File System, sparse files, reparse points, update sequence number (USN) journaling, distributed link tracking, the $Extend folder and its files Compatibility was also made available for Windows NT 4.0 with the Service Pack 4 update. Commonly called NTFS 5.0 after the OS release.[20]
3.1 Windows XP October 2001 Expanded the Master File Table (MFT) entries with redundant MFT record number (useful for recovering damaged MFT files) Commonly called NTFS 5.1 after the OS release. LFS version 1.1 was replaced by version 2.0 as of Windows 8 to improve performance.

The NTFS.sys version number (e.g. v5.0 in Windows 2000) is based on the operating system version; it should not be confused with the NTFS version number (v3.1 since Windows XP).[21]

Although subsequent versions of Windows added new file system-related features, they did not change NTFS itself. For example, Windows Vista implemented NTFS symbolic links, Transactional NTFS, partition shrinking, and self-healing.[22] NTFS symbolic links are a new feature in the file system; all the others are new operating system features that make use of NTFS features already in place.

Scalability[edit]

NTFS is optimized for 4 KB[a] clusters, but supports a maximum cluster size of 2 MB[a]. (Earlier implementations support up to 64 KB)[6] The maximum NTFS volume size that the specification can support is 264 − 1 clusters, but not all implementations achieve this theoretical maximum, as discussed below.

The maximum NTFS volume size implemented in Windows XP Professional is 232 − 1 clusters, partly due to partition table limitations. For example, using 64 KB clusters, the maximum size Windows XP NTFS volume is 256 TB minus 64 KB. Using the default cluster size of 4 KB, the maximum NTFS volume size is 16 TB minus 4 KB. Both of these are vastly higher than the 128 GB[a] limit in Windows XP SP1. Because partition tables on master boot record (MBR) disks support only partition sizes up to 2 TB, multiple GUID Partition Table (GPT or «dynamic») volumes must be combined to create a single NTFS volume larger than 2 TB. Booting from a GPT volume to a Windows environment in a Microsoft supported way requires a system with Unified Extensible Firmware Interface (UEFI) and 64-bit support.[23]

The NTFS maximum theoretical limit on the size of individual files is 16 EB[a][24] (16 × 10246 or 264 bytes) minus 1 KB, which totals 18,446,744,073,709,550,592 bytes. With Windows 10 version 1709 and Windows Server 2019, the maximum implemented file size is 8 PB[a] minus 2 MB or 9,007,199,252,643,840 bytes.[6]

Interoperability[edit]

Windows[edit]

While the different NTFS versions are for the most part fully forward- and backward-compatible, there are technical considerations for mounting newer NTFS volumes in older versions of Microsoft Windows. This affects dual-booting, and external portable hard drives. For example, attempting to use an NTFS partition with «Previous Versions» (Volume Shadow Copy) on an operating system that does not support it will result in the contents of those previous versions being lost.[15] A Windows command-line utility called convert.exe can convert supporting file systems to NTFS, including HPFS (only on Windows NT 3.1, 3.5, and 3.51), FAT16 and FAT32 (on Windows 2000 and later).[25][26]

FreeBSD[edit]

FreeBSD 3.2 released in May 1999 included read-only NTFS support written by Semen Ustimenko.[27][28] This implementation was ported to NetBSD by Christos Zoulas and Jaromir Dolecek and released with NetBSD 1.5 in December 2000.[29] The FreeBSD implementation of NTFS was also ported to OpenBSD by Julien Bordet and offers native read-only NTFS support by default on i386 and amd64 platforms as of version 4.9 released 1 May 2011.[30][28]

Linux[edit]

Linux kernel versions 2.1.74 and later include a driver written by Martin von Löwis which has the ability to read NTFS partitions;[31] kernel versions 2.5.11 and later contain a new driver written by Anton Altaparmakov (University of Cambridge) and Richard Russon which supports file read.[32][33][31] The ability to write to files was introduced with kernel version 2.6.15 in 2006 which allows users to write to existing files but does not allow the creation of new ones.[34] Paragon’s NTFS driver (see below) has been merged into kernel version 5.15, and it supports read/write on normal, compressed and sparse files, as well as journal replaying.[35]

NTFS-3G is a free GPL-licensed FUSE implementation of NTFS that was initially developed as a Linux kernel driver by Szabolcs Szakacsits. It was re-written as a FUSE program to work on other systems that FUSE supports like macOS, FreeBSD, NetBSD, OpenBSD,[36] Solaris, QNX, and Haiku[37] and allows reading and writing to NTFS partitions. A performance enhanced commercial version of NTFS-3G, called «Tuxera NTFS for Mac», is also available from the NTFS-3G developers.[38]

Captive NTFS, a ‘wrapping’ driver that uses Windows’ own driver ntfs.sys, exists for Linux. It was built as a Filesystem in Userspace (FUSE) program and released under the GPL but work on Captive NTFS ceased in 2006.[39]

Linux kernel versions 5.15 onwards carry NTFS3, a fully functional NTFS Read-Write driver which works on NTFS versions up to 3.1 and is maintained primarily by the Paragon Software Group with the source code found here.

Mac OS[edit]

Mac OS X 10.3 included Ustimenko’s read-only implementation of NTFS from FreeBSD. Then in 2006 Apple hired Anton Altaparmakov to write a new NTFS implementation for Mac OS X 10.6.[40] Native NTFS write support is included in 10.6 and later, but is not activated by default, although workarounds do exist to enable the functionality. However, user reports indicate the functionality is unstable and tends to cause kernel panics.[41]

Paragon Software Group sells a read-write driver named NTFS for Mac OS X,[42] which is also included on some models of Seagate hard drives.[43]

OS/2[edit]

The NetDrive package for OS/2 (and derivatives such as eComStation and ArcaOS) supports a plugin which allows read and write access to NTFS volumes.[44][45]

DOS[edit]

There is a free-for-personal-use read/write driver for MS-DOS by Avira called «NTFS4DOS».[46][47]

Ahead Software developed a «NTFSREAD» driver (version 1.200) for DR-DOS 7.0x between 2002 and 2004. It was part of their Nero Burning ROM software.

Security[edit]

NTFS uses access control lists and user-level encryption to help secure user data.

Access control lists (ACLs)[edit]

NTFS file system permissions on a modern Windows system

In NTFS, each file or folder is assigned a security descriptor that defines its owner and contains two access control lists (ACLs). The first ACL, called discretionary access control list (DACL), defines exactly what type of interactions (e.g. reading, writing, executing or deleting) are allowed or forbidden by which user or groups of users. For example, files in the C:Program Files folder may be read and executed by all users but modified only by a user holding administrative privileges.[48] Windows Vista adds mandatory access control info to DACLs. DACLs are the primary focus of User Account Control in Windows Vista and later.

The second ACL, called system access control list (SACL), defines which interactions with the file or folder are to be audited and whether they should be logged when the activity is successful, failed or both. For example, auditing can be enabled on sensitive files of a company, so that its managers get to know when someone tries to delete them or make a copy of them, and whether he or she succeeds.[48]

Encryption[edit]

Encrypting File System (EFS) provides user-transparent encryption of any file or folder on an NTFS volume.[49] EFS works in conjunction with the EFS service, Microsoft’s CryptoAPI and the EFS File System Run-Time Library (FSRTL). EFS works by encrypting a file with a bulk symmetric key (also known as the File Encryption Key, or FEK), which is used because it takes a relatively small amount of time to encrypt and decrypt large amounts of data than if an asymmetric key cipher is used. The symmetric key that is used to encrypt the file is then encrypted with a public key that is associated with the user who encrypted the file, and this encrypted data is stored in an alternate data stream of the encrypted file. To decrypt the file, the file system uses the private key of the user to decrypt the symmetric key that is stored in the data stream. It then uses the symmetric key to decrypt the file. Because this is done at the file system level, it is transparent to the user.[50] Also, in case of a user losing access to their key, support for additional decryption keys has been built into the EFS system, so that a recovery agent can still access the files if needed. NTFS-provided encryption and NTFS-provided compression are mutually exclusive; however, NTFS can be used for one and a third-party tool for the other.

The support of EFS is not available in Basic, Home, and MediaCenter versions of Windows, and must be activated after installation of Professional, Ultimate, and Server versions of Windows or by using enterprise deployment tools within Windows domains.

Features[edit]

Journaling[edit]

NTFS is a journaling file system and uses the NTFS Log ($LogFile) to record metadata changes to the volume. It is a feature that FAT does not provide and critical for NTFS to ensure that its complex internal data structures will remain consistent in case of system crashes or data moves performed by the defragmentation API, and allow easy rollback of uncommitted changes to these critical data structures when the volume is remounted. Notably affected structures are the volume allocation bitmap, modifications to MFT records such as moves of some variable-length attributes stored in MFT records and attribute lists, and indices for directories and security descriptors.

The ($LogFile) format has evolved through several versions:

Windows Version $LogFile format version
Windows NT 4.0 1.1
Windows 2000
Windows XP
Windows Vista
Windows 7
Windows 8 2.0
Windows 8.1
Windows 10

The incompatibility of the $LogFile versions implemented by Windows 8, Windows 10, Windows 11 prevents Windows 7 (and earlier versions of Windows) from recognizing version 2.0 of the $LogFile. Backward compatibility is provided by downgrading the $LogFile to version 1.1 when an NTFS volume is cleanly dismounted. It is again upgraded to version 2.0 when mounting on a compatible version of Windows. However, when hibernating to disk in the logoff state (a.k.a. Hybrid Boot or Fast Boot, which is enabled by default), mounted file systems are not dismounted, and thus the $LogFiles of any active file systems are not downgraded to version 1.1. The inability to process version 2.0 of the $LogFile by versions of Windows older than 8.0 results in an unnecessary invocation of the CHKDSK disk repair utility. This is particularly a concern in a multi-boot scenario involving pre- and post-8.0 versions of Windows, or when frequently moving a storage device between older and newer versions. A Windows Registry setting exists to prevent the automatic upgrade of the $LogFile to the newer version. The problem can also be dealt with by disabling Hybrid Boot.[51]

The USN Journal (Update Sequence Number Journal) is a system management feature that records (in $Extend$UsnJrnl) changes to files, streams and directories on the volume, as well as their various attributes and security settings. The journal is made available for applications to track changes to the volume.[52] This journal can be enabled or disabled on non-system volumes.[53]

Hard links[edit]

The hard link feature allows different file names to directly refer to the same file contents. Hard links may link only to files in the same volume, because each volume has its own MFT.
Hard links were originally included to support the POSIX subsystem in Windows NT.[54]

Although Hard links use the same MFT record (inode) which records file metadata such as file size, modification date, and attributes, NTFS also caches this data in the directory entry as a performance enhancement. This means that when listing the contents of a directory using FindFirstFile/FindNextFile family of APIs, (equivalent to the POSIX opendir/readdir APIs) you will also receive this cached information, in addition to the name and inode. However, you may not see up-to-date information, as this information is only guaranteed to be updated when a file is closed, and then only for the directory from which the file was opened.[55] This means where a file has multiple names via hard links, updating a file via one name does not update the cached data associated with the other name. You can always obtain up-to-date data using GetFileInformationByHandle (which is the true equivalent of POSIX stat function). This can be done using a handle which has no access to the file itself (passing zero to CreateFile for dwDesiredAccess), and closing this handle has the incidental effect of updating the cached information.

Windows uses hard links to support short (8.3) filenames in NTFS. Operating system support is needed because there are legacy applications that can work only with 8.3 filenames, but support can be disabled. In this case, an additional filename record and directory entry is added, but both 8.3 and long file name are linked and updated together, unlike a regular hard link.

The NTFS file system has a limit of 1024 hard links on a file.[56]

Alternate data stream (ADS)[edit]

Alternate data streams allow more than one data stream to be associated with a filename (a fork), using the format «filename:streamname» (e.g., «text.txt:extrastream»).

NTFS Streams were introduced in Windows NT 3.1, to enable Services for Macintosh (SFM) to store resource forks. Although current versions of Windows Server no longer include SFM, third-party Apple Filing Protocol (AFP) products (such as GroupLogic’s ExtremeZ-IP) still use this feature of the file system. Very small ADSs (named «Zone.Identifier») are added by Internet Explorer and recently[when?] by other browsers to mark files downloaded from external sites as possibly unsafe to run; the local shell would then require user confirmation before opening them.[57] When the user indicates that they no longer want this confirmation dialog, this ADS is deleted.

Alternate streams are not listed in Windows Explorer, and their size is not included in the file’s size. When the file is copied or moved to another file system without ADS support the user is warned that alternate data streams cannot be preserved. No such warning is typically provided if the file is attached to an e-mail, or uploaded to a website. Thus, using alternate streams for critical data may cause problems. Microsoft provides a tool called Streams[58] to view streams on a selected volume. Starting with Windows PowerShell 3.0, it is possible to manage ADS natively with six cmdlets: Add-Content, Clear-Content, Get-Content, Get-Item, Remove-Item, Set-Content.[59]

Malware has used alternate data streams to hide code.[60] As a result, malware scanners and other special tools now check for alternate data streams.

File compression[edit]

Compression is enabled on a per-folder or per-file basis by setting the ‘compressed’ attribute. When compression is enabled on a folder, any files moved or saved to that folder will be automatically compressed using LZNT1 algorithm (a variant of LZ77).[61] The compression algorithm is designed to support cluster sizes of up to 4 KB; when the cluster size is greater than 4 KB on an NTFS volume, NTFS compression is not available.[62] Data is compressed in 16-cluster chunks (up to 64 KB in size); if the compression reduces 64 KB of data to 60 KB or less, NTFS treats the unneeded 4 KB pages like empty sparse file clusters—they are not written. This allows for reasonable random-access times as the OS merely has to follow the chain of fragments.

Compression works best with files that have repetitive content, are seldom written, are usually accessed sequentially, and are not themselves compressed. Single-user systems with limited hard disk space can benefit from NTFS compression for small files, from 4 KB to 64 KB or more, depending on compressibility. Files smaller than approximately 900 bytes are stored within the directory entry of the MFT.[63]

Advantages[edit]

Users of fast multi-core processors will find improvements in application speed by compressing their applications and data as well as a reduction in space used. Even when SSD controllers already compress data, there is still a reduction in I/Os since less data is transferred.[64]

According to research by Microsoft’s NTFS Development team, 50–60 GB is a reasonable maximum size for a compressed file on an NTFS volume with a 4 KB (default) cluster (block) size. This reasonable maximum size decreases sharply for volumes with smaller cluster sizes.[65]

Disadvantages[edit]

Large compressible files become highly fragmented since every chunk smaller than 64 KB becomes a fragment.[65][66] Flash memory, such as SSD drives do not have the head movement delays and high access time of mechanical hard disk drives, so fragmentation has only a smaller penalty.

If system files that are needed at boot time (such as drivers, NTLDR, winload.exe, or BOOTMGR) are compressed, the system may fail to boot correctly, because decompression filters are not yet loaded.[67][failed verification] Later editions of Windows[which?] do not allow important system files to be compressed.

System compression[edit]


Since Windows 10, Microsoft has introduced new file compression scheme based on the XPRESS algorithm with 4K/8K/16K block size[68] and the LZX algorithm;[69] both are variants of LZ77 updated with Huffman entropy coding and range coding, which LZNT1 lacked. These compression algorithms were taken from Windows Imaging Format (WIM file).

The new compression scheme is used by CompactOS feature, which reduces disk usage by compressing Windows system files.[70] CompactOS is not an extension of NTFS file compression and does not use the ‘compressed’ attribute; instead, it sets a reparse point on each compressed file with a WOF (Windows Overlay Filter) tag,[71] but the actual data is stored in an alternate data stream named «WofCompressedData», which is decompressed on-the-fly by a WOF filesystem filter driver, and the main file is an empty sparse file.[71] This design is meant purely for read-only access, so any writes to compressed files result in an automatic decompression.[71][72][73]

CompactOS compression is intended for OEMs who prepare OS images with the /compact flag of the DISM tool in Windows ADK,[74] but it can also be manually turned on per file with the /exe flag of the compact command.[75] CompactOS algorithm avoids file fragmentation by writing compressed data in contiguously allocated chunks, unlike core NTFS compression.[citation needed]

CompactOS file compression is an improved version of WIMBoot feature introduced in Windows 8.1. WIMBoot reduces Windows disk usage by keeping system files in a compressed WIM image on a separate hidden disk partition.[76] Similarly to CompactOS, Windows system directories only contain sparse files marked by a reparse point with a WOF tag, and Windows Overlay Filter driver decompresses file contents on-the-fly from the WIM image. WIMBoot is less effective than CompactOS though, as new updated versions of system files need to be written to the system partition, consuming disk space.[71]

Sparse files[edit]

A sparse file: Empty bytes don’t need to be saved, thus they can be represented by metadata.

One petabyte (1,125,899,906,842,624 bytes) of sparse files, 0 bytes on disk.

Sparse files are files interspersed with empty segments for which no actual storage space is used. To the applications, the file looks like an ordinary file with empty regions seen as regions filled with zeros; the file system maintains an internal list of such regions for each sparse file.[77] A sparse file does not necessarily include sparse zeros areas; the «sparse file» attribute just means that the file is allowed to have them.

Database applications, for instance, may use sparse files.[78] As with compressed files, the actual sizes of sparse files are not taken into account when determining quota limits.[79]

Volume Shadow Copy[edit]

The Volume Shadow Copy Service (VSS) keeps historical versions of files and folders on NTFS volumes by copying old, newly overwritten data to shadow copy via copy-on-write technique. The user may later request an earlier version to be recovered. This also allows data backup programs to archive files currently in use by the file system.

Windows Vista also introduced persistent shadow copies for use with System Restore and Previous Versions features. Persistent shadow copies, however, are deleted when an older operating system mounts that NTFS volume. This happens because the older operating system does not understand the newer format of persistent shadow copies.[80]

Transactions[edit]

As of Windows Vista, applications can use Transactional NTFS (TxF) to group multiple changes to files together into a single transaction. The transaction will guarantee that either all of the changes happen, or none of them do, and that no application outside the transaction will see the changes until they are committed.[81]

It uses similar techniques as those used for Volume Shadow Copies (i.e. copy-on-write) to ensure that overwritten data can be safely rolled back, and a CLFS log to mark the transactions that have still not been committed, or those that have been committed but still not fully applied (in case of system crash during a commit by one of the participants).

Transactional NTFS does not restrict transactions to just the local NTFS volume, but also includes other transactional data or operations in other locations such as data stored in separate volumes, the local registry, or SQL databases, or the current states of system services or remote services. These transactions are coordinated network-wide with all participants using a specific service, the DTC, to ensure that all participants will receive same commit state, and to transport the changes that have been validated by any participant (so that the others can invalidate their local caches for old data or rollback their ongoing uncommitted changes). Transactional NTFS allows, for example, the creation of network-wide consistent distributed file systems, including with their local live or offline caches.

Microsoft now advises against using TxF: «Microsoft strongly recommends developers utilize alternative means» since «TxF may not be available in future versions of Microsoft Windows».[82]

Quotas[edit]

Disk quotas were introduced in NTFS v3. They allow the administrator of a computer that runs a version of Windows that supports NTFS to set a threshold of disk space that users may use. It also allows administrators to keep track of how much disk space each user is using. An administrator may specify a certain level of disk space that a user may use before they receive a warning, and then deny access to the user once they hit their upper limit of space. Disk quotas do not take into account NTFS’s transparent file-compression, should this be enabled. Applications that query the amount of free space will also see the amount of free space left to the user who has a quota applied to them.

Reparse points[edit]

Introduced in NTFS v3, NTFS reparse points are used by associating a reparse tag in the user space attribute of a file or directory. Microsoft includes several default tags including symbolic links, directory junction points and volume mount points. When the Object Manager parses a file system name lookup and encounters a reparse attribute, it will reparse the name lookup, passing the user controlled reparse data to every file system filter driver that is loaded into Windows. Each filter driver examines the reparse data to see whether it is associated with that reparse point, and if that filter driver determines a match, then it intercepts the file system request and performs its special functionality.

Limitations[edit]

Resizing[edit]

Starting with Windows Vista Microsoft added the built-in ability to shrink or expand a partition. However, this ability does not relocate page file fragments or files that have been marked as unmovable, so shrinking a volume will often require relocating or disabling any page file, the index of Windows Search, and any Shadow Copy used by System Restore. Various third-party tools are capable of resizing NTFS partitions.

OneDrive[edit]

Since 2017, Microsoft requires the OneDrive file structure to reside on an NTFS disk.[83] This is because OneDrive Files On-Demand feature uses NTFS reparse points to link files and folders that are stored in OneDrive to the local filesystem, making the file or folder unusable with any previous version of Windows, with any other NTFS file system driver, or any file system and backup utilities not updated to support it.[84]

Structure[edit]

NTFS is made up of several components including: a partition boot sector (PBS) that holds boot information; the master file table that stores a record of all files and folders in the filesystem; a series of meta files that help structure meta data more efficiently; data streams and locking mechanisms.

Internally, NTFS uses B-trees to index file system data. A file system journal is used to guarantee the integrity of the file system metadata but not individual files’ content. Systems using NTFS are known to have improved reliability compared to FAT file systems.[85]

NTFS allows any sequence of 16-bit values for name encoding (e.g. file names, stream names or index names) except 0x0000. This means UTF-16 code units are supported, but the file system does not check whether a sequence is valid UTF-16 (it allows any sequence of short values, not restricted to those in the Unicode standard). In Win32 namespace, any UTF-16 code units are case insensitive whereas in POSIX namespace they are case sensitive. File names are limited to 255 UTF-16 code units. Certain names are reserved in the volume root directory and cannot be used for files. These are $MFT, $MFTMirr, $LogFile, $Volume, $AttrDef, . (dot), $Bitmap, $Boot, $BadClus, $Secure, $UpCase, and $Extend.[5] . (dot) and $Extend are both directories; the others are files. The NT kernel limits full paths to 32,767 UTF-16 code units. There are some additional restrictions on code points and file names.[86]

Partition Boot Sector (PBS)[edit]

This boot partition format is roughly based upon the earlier FAT filesystem, but the fields are in different locations. Some of these fields, especially the «sectors per track», «number of heads» and «hidden sectors» fields may contain dummy values on drives where they either do not make sense or are not determinable.

The OS first looks at the 8 bytes at 0x30 to find the cluster number of the $MFT, then multiplies that number by the number of sectors per cluster (1 byte found at 0x0D). This value is the sector offset (LBA) to the $MFT, which is described below.

Master File Table[edit]

In NTFS, all file, directory and metafile data—file name, creation date, access permissions (by the use of access control lists), and size—are stored as metadata in the Master File Table (MFT). This abstract approach allowed easy addition of file system features during Windows NT’s development—an example is the addition of fields for indexing used by the Active Directory and the Windows Search. This also enables fast file search software to locate named local files and folders included in the MFT very quickly, without requiring any other index.

The MFT structure supports algorithms which minimize disk fragmentation.[89] A directory entry consists of a filename and a «file ID» (analogous to the inode number), which is the record number representing the file in the Master File Table. The file ID also contains a reuse count to detect stale references. While this strongly resembles the W_FID of Files-11, other NTFS structures radically differ.

A partial copy of the MFT, called the MFT mirror, is stored to be used in case of corruption.[90] If the first record of the MFT is corrupted, NTFS reads the second record to find the MFT mirror file. Locations for both files are stored in the boot sector.[91]

Metafiles[edit]

NTFS contains several files that define and organize the file system. In all respects, most of these files are structured like any other user file ($Volume being the most peculiar), but are not of direct interest to file system clients.[92] These metafiles define files, back up critical file system data, buffer file system changes, manage free space allocation, satisfy BIOS expectations, track bad allocation units, and store security and disk space usage information. All content is in an unnamed data stream, unless otherwise indicated.

These metafiles are treated specially by Windows, handled directly by the NTFS.SYS driver and are difficult to directly view: special purpose-built tools are needed.[93] As of Windows 7, the NTFS driver completely prohibits user access, resulting in a BSoD whenever an attempt to execute a metadata file is made. One such tool is the nfi.exe («NTFS File Sector Information Utility») that is freely distributed as part of the Microsoft «OEM Support Tools». For example, to obtain information on the «$MFT»-Master File Table Segment the following command is used: nfi.exe c:$MFT[94] Another way to bypass the restriction is to use 7-Zip’s file manager and go to the low-level NTFS path \.X: (where X: resembles any drive/partition). Here, 3 new folders will appear: $EXTEND, [DELETED] (a pseudo-folder that 7-Zip uses to attach files deleted from the file system to view), and [SYSTEM] (another pseudo-folder that contains all the NTFS metadata files). This trick can be used from removable devices (USB flash drives, external hard drives, SD Cards, etc.) inside Windows, but doing this on the active partition requires offline access (namely WinRE).

Attribute lists, attributes, and streams[edit]

For each file (or directory) described in the MFT record, there is a linear repository of stream descriptors (also named attributes), packed together in one or more MFT records (containing the so-called attributes list), with extra padding to fill the fixed 1 KB size of every MFT record, and that fully describes the effective streams associated with that file.

Each attribute has an attribute type (a fixed-size integer mapping to an attribute definition in file $AttrDef), an optional attribute name (for example, used as the name for an alternate data stream), and a value, represented in a sequence of bytes. For NTFS, the standard data of files, the alternate data streams, or the index data for directories are stored as attributes.

According to $AttrDef, some attributes can be either resident or non-resident. The $DATA attribute, which contains file data, is such an example. When the attribute is resident (which is represented by a flag), its value is stored directly in the MFT record. Otherwise, clusters are allocated for the data, and the cluster location information is stored as data runs in the attribute.

  • For each file in the MFT, the attributes identified by attribute type, attribute name must be unique. Additionally, NTFS has some ordering constraints for these attributes.
  • There is a predefined null attribute type, used to indicate the end of the list of attributes in one MFT record. It must be present as the last attribute in the record (all other storage space available after it will be ignored and just consists of padding bytes to match the record size in the MFT).
  • Some attribute types are required and must be present in each MFT record, except unused records that are just indicated by null attribute types.
    • This is the case for the $STANDARD_INFORMATION attribute that is stored as a fixed-size record and contains the timestamps and other basic single-bit attributes (compatible with those managed by FAT in DOS or Windows 9x).
  • Some attribute types cannot have a name and must remain anonymous.
    • This is the case for the standard attributes, or for the preferred NTFS «filename» attribute type, or the «short filename» attribute type, when it is also present (for compatibility with DOS-like applications, see below). It is also possible for a file to contain only a short filename, in which case it will be the preferred one, as listed in the Windows Explorer.
    • The filename attributes stored in the attribute list do not make the file immediately accessible through the hierarchical file system. In fact, all the filenames must be indexed separately in at least one other directory on the same volume. There it must have its own MFT record and its own security descriptors and attributes that reference the MFT record number for this file. This allows the same file or directory to be «hardlinked» several times from several containers on the same volume, possibly with distinct filenames.
  • The default data stream of a regular file is a stream of type $DATA but with an anonymous name, and the ADSs are similar but must be named.
  • On the other hand, the default data stream of directories has a distinct type, but are not anonymous: they have an attribute name («$I30» in NTFS 3+) that reflects its indexing format.

All attributes of a given file may be displayed by using the nfi.exe («NTFS File Sector Information Utility») that is freely distributed as part of the Microsoft «OEM Support Tools».[94]

Windows system calls may handle alternate data streams.[5] Depending on the operating system, utility and remote file system, a file transfer might silently strip data streams.[5] A safe way of copying or moving files is to use the BackupRead and BackupWrite system calls, which allow programs to enumerate streams, to verify whether each stream should be written to the destination volume and to knowingly skip unwanted streams.[5]

Resident vs. non-resident attributes[edit]

To optimize the storage and reduce the I/O overhead for the very common case of attributes with very small associated value, NTFS prefers to place the value within the attribute itself (if the size of the attribute does not then exceed the maximum size of an MFT record), instead of using the MFT record space to list clusters containing the data; in that case, the attribute will not store the data directly but will just store an allocation map (in the form of data runs) pointing to the actual data stored elsewhere on the volume.[95] When the value can be accessed directly from within the attribute, it is called «resident data» (by computer forensics workers). The amount of data that fits is highly dependent on the file’s characteristics, but 700 to 800 bytes is common in single-stream files with non-lengthy filenames and no ACLs.

  • Some attributes (such as the preferred filename, the basic file attributes) cannot be made non-resident. For non-resident attributes, their allocation map must fit within MFT records.
  • Encrypted-by-NTFS, sparse data streams, or compressed data streams cannot be made resident.
  • The format of the allocation map for non-resident attributes depends on its capability of supporting sparse data storage. In the current implementation of NTFS, once a non-resident data stream has been marked and converted as sparse, it cannot be changed back to non-sparse data, so it cannot become resident again, unless this data is fully truncated, discarding the sparse allocation map completely.
  • When a non-resident attribute is so fragmented, that its effective allocation map cannot fit entirely within one MFT record, NTFS stores the attribute in multiple records. The first one among them is called the base record, while the others are called extension records. NTFS creates a special attribute $ATTRIBUTE_LIST to store information mapping different parts of the long attribute to the MFT records, which means the allocation map may be split into multiple records. The $ATTRIBUTE_LIST itself can also be non-resident, but its own allocation map must fit within one MFT record.
  • When there are too many attributes for a file (including ADS’s, extended attributes, or security descriptors), so that they cannot fit all within the MFT record, extension records may also be used to store the other attributes, using the same format as the one used in the base MFT record, but without the space constraints of one MFT record.

The allocation map is stored in a form of data runs with compressed encoding. Each data run represents a contiguous group of clusters that store the attribute value. For files on a multi-GB volume, each entry can be encoded as 5 to 7 bytes, which means a 1 KB MFT record can store about 100 such data runs. However, as the $ATTRIBUTE_LIST also has a size limit, it is dangerous to have more than 1 million fragments of a single file on an NTFS volume, which also implies that it is in general not a good idea to use NTFS compression on a file larger than 10 GB.[96]

The NTFS file system driver will sometimes attempt to relocate the data of some of the attributes that can be made non-resident into the clusters, and will also attempt to relocate the data stored in clusters back to the attribute inside the MFT record, based on priority and preferred ordering rules, and size constraints.

Since resident files do not directly occupy clusters («allocation units»), it is possible for an NTFS volume to contain more files on a volume than there are clusters. For example, a 74.5 GB partition NTFS formats with 19,543,064 clusters of 4 KB. Subtracting system files (a 64 MB log file, a 2,442,888-byte Bitmap file, and about 25 clusters of fixed overhead) leaves 19,526,158 clusters free for files and indices. Since there are four MFT records per cluster, this volume theoretically could hold almost 4 × 19,526,158 = 78,104,632 resident files.

Opportunistic locks[edit]

Opportunistic file locks (oplocks) allow clients to alter their buffering strategy for a given file or stream in order to increase performance and reduce network use.[97] Oplocks apply to the given open stream of a file and do not affect oplocks on a different stream.

Oplocks can be used to transparently access files in the background. A network client may avoid writing information into a file on a remote server if no other process is accessing the data, or it may buffer read-ahead data if no other process is writing data.

Windows supports four different types of oplocks:

  • Level 2 (or shared) oplock: multiple readers, no writers (i.e. read caching).
  • Level 1 (or exclusive) oplock: exclusive access with arbitrary buffering (i.e. read and write caching).
  • Batch oplock (also exclusive): a stream is opened on the server, but closed on the client machine (i.e. read, write and handle caching).
  • Filter oplock (also exclusive): applications and file system filters can «back out» when others try to access the same stream (i.e. read and write caching) (since Windows 2000)

Opportunistic locks have been enhanced in Windows 7 and Windows Server 2008 R2 with per-client oplock keys.[98]

Time[edit]

Windows NT and its descendants keep internal timestamps as UTC and make the appropriate conversions for display purposes; all NTFS timestamps are in UTC.[citation needed]

For historical reasons, the versions of Windows that do not support NTFS all keep time internally as local zone time, and therefore so do all file systems – other than NTFS – that are supported by current versions of Windows. This means that when files are copied or moved between NTFS and non-NTFS partitions, the OS needs to convert timestamps on the fly. But if some files are moved when daylight saving time (DST) is in effect, and other files are moved when standard time is in effect, there can be some ambiguities in the conversions. As a result, especially shortly after one of the days on which local zone time changes, users may observe that some files have timestamps that are incorrect by one hour. Due to the differences in implementation of DST in different jurisdictions, this can result in a potential timestamp error of up to 4 hours in any given 12 months.[99]

See also[edit]

  • Comparison of file systems
  • NTFSDOS
  • ntfsresize
  • WinFS (a canceled Microsoft filesystem)
  • ReFS, a newer Microsoft filesystem

Notes[edit]

  1. ^ a b c d e f g h i 1 byte = 8 bits
    1 KB = 1,024 bytes
    1 MB = 1,048,576 bytes
    1 GB = 1,073,741,824 bytes
    1 TB = 1,099,511,627,776 bytes
    1 PB = 1,125,899,906,842,624 bytes
    1 EB = 1,152,921,504,606,846,976 bytes

References[edit]

  1. ^ a b c Karresand, Martin; Axelsson, Stefan; Dyrkolbotn, Geir Olav (2019-07-01). «Using NTFS Cluster Allocation Behavior to Find the Location of User Data». Digital Investigation. 29: –51–S60. doi:10.1016/j.diin.2019.04.018. ISSN 1742-2876. S2CID 199004263. Retrieved 2021-12-01.
  2. ^ a b «Glossary». [MS-EFSR]: Encrypting File System Remote (EFSRPC) Protocol. Microsoft. 14 November 2013.
  3. ^ «How NTFS Works». TechNet. Microsoft. Retrieved 2 December 2017.
  4. ^ «B*Trees — NTFS Directory Trees — Concept — NTFS Documentation». flatcap.org. Archived from the original on 2019-05-13. Retrieved 2019-05-13.
  5. ^ a b c d e f g «How NTFS Works». Windows Server 2003 Technical Reference. 2003-03-28. Retrieved 2011-09-12.
  6. ^ a b c d «Appendix A: Product Behavior». [MS-FSA]: File System Algorithms. Microsoft. 2018-09-12. Retrieved 2018-10-01. NTFS uses a default cluster size of 4 KB, a maximum cluster size of 64 KB on Windows 10 v1703 operating system and Windows Server 2016 and prior, and 2 MB on Windows 10 v1709 operating system and Windows Server 2019 and later, and a minimum cluster size of 512 bytes.
  7. ^ «Appendix A: Product Behavior». [MS-FSA]: File System Algorithms. Microsoft. 14 November 2013. Retrieved 2012-09-21.
  8. ^ a b Russon, Richard; Fledel, Yuval. «NTFS Documentation» (PDF). Archived (PDF) from the original on 2022-10-09. Retrieved 2011-06-26.
  9. ^ «WineHQ Bugzilla – Bug 51808 – the issue with trailing spaces (Spaces at the end of a filename)».
  10. ^ Rick Vanover (14 September 2011). «Windows Server 8 data deduplication». Retrieved 2011-12-02.
  11. ^ a b Custer, Helen (1994). Inside the Windows NT File System. Microsoft Press. ISBN 978-1-55615-660-1.
  12. ^ «NTFS3 — The Linux Kernel documentation». www.kernel.org. Retrieved 2021-12-02.
  13. ^ «ntfs-3g». www.freebsd.org. Retrieved 2021-12-02.
  14. ^ «How to Convert a Drive from FAT32 to NTFS without Data Loss». WindowsLoop. 11 July 2021. Retrieved 8 August 2021.
  15. ^ a b cfsbloggers (July 14, 2006). «How restore points and other recovery features in Windows Vista are affected when dual-booting with Windows XP». The Filing Cabinet. Retrieved 2007-03-21.
  16. ^ Kozierok, Charles (14 February 2018). «Overview and History of NTFS». The PC Guide. Retrieved May 30, 2019.
  17. ^ Custer, Helen (1994). Inside the Windows NT File System. Microsoft Press. p. vii. ISBN 978-1-55615-660-1.
  18. ^ «Recovering Windows NT After a Boot Failure on an NTFS Drive». Microsoft. November 1, 2006.
  19. ^ a b Russinovich, Mark. «Inside Win2K NTFS, Part 1». MSDN. Microsoft. Retrieved 2008-04-18.
  20. ^ «What’s New in Windows NT 4.0 Service Pack 4?». Microsoft.com. 12 January 1999. Archived from the original on 17 January 1999. Retrieved 17 August 2018.
  21. ^ «New Capabilities and Features of the NTFS 3.1 File System». Microsoft. 1 December 2007.
  22. ^ Loveall, John (2006). «Storage improvements in Windows Vista and Windows Server 2008» (PowerPoint). Microsoft. pp. 14–20. Retrieved 2007-09-04.
  23. ^ «Booting from GPT». Rodsbooks.com. Retrieved 22 September 2018.
  24. ^ «NTFS vs FAT vs exFAT — NTFS.com». www.ntfs.com. Retrieved 2021-01-19.
  25. ^ «How to Convert FAT Disks to NTFS». Microsoft. 18 December 2017. Retrieved May 30, 2019.
  26. ^ «How to use Convert.exe to convert a partition to the NTFS file system». Microsoft Corporation. 2007-02-12. Retrieved 2010-12-26.
  27. ^ «FreeBSD 3.2 Release Notes». 17 May 1999. Retrieved 2020-06-15.
  28. ^ a b «mount_ntfs — OpenBSD manual pages». Retrieved 2020-06-15.
  29. ^ «Announcing NetBSD 1.5». 6 December 2000. Retrieved 2020-06-15.
  30. ^ «OpenBSD 4.9». Openbsd.com. Retrieved 22 September 2018.
  31. ^ a b «NTFS Credits and History». Linux-NTFS Project. Retrieved 2021-09-05.
  32. ^ «Kernel development». lwn.net. 2 May 2002. Retrieved 2021-09-05.
  33. ^ «Release notes for v2.5.11». 29 April 2002. Retrieved 2021-09-05.
  34. ^ «2.6.15 changelog». Linux project. 3 January 2006. Retrieved 2021-09-05.
  35. ^ Anderson, Tim (2021-09-06). «GitHub merges ‘useless garbage’ says Linus Torvalds as new NTFS support added to Linux kernel 5.15». The Register. Retrieved 2021-09-07.
  36. ^ «OpenBSD adds fuse(4) support for adding file systems in userland». OpenBSD Journal. 2013-11-08. Retrieved 2013-11-08.
  37. ^ «NTFS-3G Stable Read/Write Driver». 2009-07-25.
  38. ^ «Tuxera NTFS for Mac». Tuxera. August 30, 2011. Retrieved September 20, 2011.
  39. ^ «Jan Kratochvil: Captive: The first free NTFS read/write filesystem for GNU/Linux». Retrieved 2020-06-15.
  40. ^ «About Tuxera». Retrieved 2020-06-15.
  41. ^ «10.6: Enable native NTFS read/write support». 1 October 2009. Retrieved 5 September 2021.
  42. ^ «NTFS for Mac OS X, communication channel between Mac OS X and Windows». Paragon Software Group. Retrieved September 20, 2011.
  43. ^ «The Leader in Mass Data Storage Solutions | Seagate US». Seagate.com. Archived from the original on February 10, 2011.
  44. ^ «NTFS plugin for NetDrive». ecsoft2.org. Retrieved 2020-09-09.
  45. ^ «NetDrive for OS/2». arcanoae.com. Retrieved 2020-09-09.
  46. ^ «Avira NTFS4DOS Personal». Archived from the original on June 19, 2010. Retrieved 2009-07-25.
  47. ^ «Download Avira NTFS4DOS Personal 1.9». Archived from the original on 10 November 2013. Retrieved 22 September 2018.
  48. ^ a b «How Security Descriptors and Access Control Lists Work». TechNet. Microsoft. Retrieved 4 September 2015.
  49. ^ Morello, John (February 2007). «Security Watch Deploying EFS: Part 1». Technet Magazine. Microsoft. Retrieved 2009-01-25.
  50. ^ «How EFS Works». Windows 2000 Resource Kit. Microsoft. Retrieved 25 February 2014.
  51. ^ «Windows 8 volume compatibility considerations with prior versions of Windows». Retrieved 2021-12-17.
  52. ^ «Change Journals (Windows)». MSDN. Retrieved 2010-04-16.
  53. ^ «Creating, Modifying, and Deleting a Change Journal (Windows)». MSDN. Retrieved 2010-04-16.
  54. ^ «Chapter 29 – POSIX Compatibility». MS Windows NT Workstation 4.0 Resource Guide. Microsoft. 1995. Retrieved 21 October 2013.
  55. ^ «Hard Links and Junctions». MSDN. Microsoft. 12 October 2013. Retrieved 21 October 2013.
  56. ^ «MSDN – CreateHardLink function». Retrieved 14 January 2016.
  57. ^ Russinovich, Mark E.; Solomon, David A.; Ionescu, Alex (2009). «File Systems». Windows Internals (5th ed.). Microsoft Press. p. 921. ISBN 978-0-7356-2530-3. One component in Windows that uses multiple data streams is the Attachment Execution Service[…] depending on which zone the file was downloaded from […] Windows Explorer might warn the user
  58. ^ «Streams — Windows Sysinternals». Technet.microsoft.com. Retrieved 22 September 2018.
  59. ^ «FileSystem Provider». Microsoft. 9 August 2012. Archived from the original on 23 January 2015. Retrieved 23 January 2015.
  60. ^ Malware utilising Alternate Data Streams? Archived 2008-07-23 at the Wayback Machine, AusCERT Web Log, 21 August 2007
  61. ^ «File Compression and Decompression». MSDN Platform SDK: File Systems. Retrieved 2005-08-18.
  62. ^ «The Default Cluster Size for the NTFS and FAT File Systems». Microsoft. January 31, 2002. Retrieved 2012-01-10.
  63. ^ «How NTFS Works». 2003-03-28. Retrieved 2011-10-24.
  64. ^ Masiero, Manuel (2011-12-01). «Should You Compress Data On Your SSD?». Tom’s Hardware. Bestofmedia Group. Retrieved 2013-04-05.
  65. ^ a b Middleton, Dennis. «Understanding NTFS Compression». Ntdebugging Blog. Microsoft. Retrieved 2011-03-16.
  66. ^ «Shrinking the gap: carving NTFS-compressed files». Retrieved 2011-05-29.
  67. ^ «Disk Concepts and Troubleshooting». Microsoft. Retrieved 2012-03-26.
  68. ^ «[MS-XCA]: Xpress Compression Algorithm».
  69. ^ wimlib: the open source Windows Imaging (WIM) library — Compression algorithm
  70. ^ «Compact OS, single-instancing, and image optimization». Microsoft. Retrieved 1 October 2019.
  71. ^ a b c d Raymond Chen.What is WofCompressedData? Does WOF mean that Windows is a dog? Microsoft DevBlogs.
  72. ^ Biggers, Eric (29 April 2019). «NTFS-3G plugin for reading «system compressed» files». GitHub. Retrieved 1 October 2019.
  73. ^ «Re: [ntfs-3g-devel] Experimental support for Windows 10 «System Compressed» files». SourceForge.net. Retrieved 1 October 2019.
  74. ^ «DISM Overview».
  75. ^ «Compact».
  76. ^ Windows Image File Boot (WIMBoot) Overview
  77. ^ «Sparse Files». MSDN. Microsoft. 12 October 2013. Retrieved 21 October 2013.
  78. ^ Kandoth, Suresh B. (4 March 2009). «Sparse File Errors: 1450 or 665 due to file fragmentation: Fixes and Workarounds». CSS SQL Server Engineers. Microsoft. Retrieved 21 October 2013.
  79. ^ «Sparse Files and Disk Quotas». MSDN Library. Microsoft. 12 October 2013. Retrieved 21 October 2013.
  80. ^ cfsbloggers (July 14, 2006). «How restore points and other recovery features in Windows Vista are affected when you dual-boot with Windows XP». The Filing Cabinet. Retrieved 2007-03-21.
  81. ^ «Transactional NTFS». MSDN. Microsoft. Retrieved 2007-02-02.
  82. ^ «Transactional NTFS (TxF)». Windows Dev Center (MSDN). Microsoft. Retrieved 24 May 2015.
  83. ^ «Unable to open content synced in a OneDrive folder on an external drive». Microsoft Support. Retrieved 2021-04-03.
  84. ^ André, Jean-Pierre (March 1, 2019). «NTFS-3G: Junction Points, Symbolic Links and Reparse Points». jp-andre.pagesperso-orange.fr.
  85. ^ «Chapter 18 – Choosing a File System». MS Windows NT Workstation 4.0 Resource Guide. Microsoft. Retrieved 25 February 2014.
  86. ^ «Naming Files, Paths, and Namespaces». MSDN. Microsoft. Naming Conventions. Retrieved 25 February 2014.
  87. ^ «NTFS. Partition Boot Sector». Ntfs.com. Retrieved 22 September 2018.
  88. ^ «Boot Sector». Technet.microsoft.com. September 11, 2008. Table 1.13 BPB and Extended BPB Fields on NTFS Volumes. Retrieved 22 September 2018.
  89. ^ «Master File Table». MSDN. July 2, 2012.
  90. ^ «Forensics: What is the MFT Mirror?». Where is Your Data?. 2009-06-05. Retrieved 2021-07-30.
  91. ^ «NTFS Master File Table (MFT)». Ntfs.com. Retrieved 22 September 2018.
  92. ^ Schwarz, Thomas. «COEN 252 Computer Forensics NTFS». Faculty of Organization and Informatics University of Zagreb. Archived from the original on 2021-02-27. Retrieved May 30, 2019.
  93. ^ Since Windows XP, it is very difficult to view a listing of these files: they exist in the root directory’s index, but the Win32 interface filters them out. In NT 4.0, the command line dir command would list the metafiles in the root directory if /a were specified. In Windows 2000, dir /a stopped working, but dir /a $MFT worked.
  94. ^ a b «OEM Support Tools Phase 3 Service Release 2 Availability». Microsoft Corporation. 2007-02-21. Archived from the original on 2015-02-23. Retrieved 2010-06-16. Windows NT File System (NTFS) File Sector Information Utility … A tool used to dump information about an NTFS volume
  95. ^ «The Four Stages of NTFS File Growth». Retrieved 22 September 2018.
  96. ^ «A heavily fragmented file in an NTFS volume may not grow beyond a certain size». Archived from the original on 2021-05-06. Retrieved 2021-05-19.
  97. ^ «How Oplocks function in the Windows Environment: Overview». Archived from the original on 2010-08-23. Retrieved 2018-12-19.
  98. ^ «What’s New in NTFS». Technet.microsoft.com. Retrieved 22 September 2018.
  99. ^ «Beating the Daylight Saving Time bug and getting correct file modification times Archived 2004-11-14 at the Wayback Machine» The Code Project

Further reading[edit]

  • Bolosky, William J.; Corbin, Scott; Goebel, David; Douceur, John R. (January 2000). «Single Instance Storage in Windows 2000». Proceedings of 4th USENIX Windows Systems Symposium.
  • Custer, Helen (1994). Inside the Windows NT File System. Microsoft Press. ISBN 978-1-55615-660-1.
  • Nagar, Rajeev (1997). Windows NT File System Internals: A Developer’s Guide. O’Reilly. ISBN 978-1-56592-249-5.
  • «NTFS Technical Reference». Microsoft TechNet. Microsoft. 28 March 2003.

На чтение 4 мин. Просмотров 220 Опубликовано 27.07.2019

Содержание

  1. Определение файловой системы NTFS
  2. Как посмотреть, если диск отформатирован как NTFS
  3. Использовать управление дисками
  4. Откройте проводник Windows
  5. Введите команду командной строки
  6. Особенности NTFS
  7. NTFS Альтернативы

NTFS, аббревиатура, обозначающая Файловая система новой технологии , – это файловая система, впервые представленная Microsoft в 1993 году с выпуском Windows NT 3.1.

NTFS – это основная файловая система, используемая в операционных системах Microsoft Windows 10, Windows 8, Windows 7, Windows Vista, Windows XP, Windows 2000 и Windows NT.

Линейка операционных систем Windows Server также в основном использует NTFS. Файловая система также поддерживается в других операционных системах, таких как Linux и BSD. macOS поддерживает NTFS только для чтения.

Как посмотреть, если диск отформатирован как NTFS

Есть несколько способов проверить, был ли жесткий диск отформатирован в NTFS или использует другую файловую систему.

Использовать управление дисками

Первый и, вероятно, самый простой способ получить статус одного или нескольких дисков – это использовать Управление дисками. См. Как я могу открыть Управление дисками в Windows? если вы никогда не работали с управлением дисками раньше.

Файловая система указана прямо здесь, наряду с томом и другими сведениями о диске.

Откройте проводник Windows

Другой способ проверить, отформатирован ли диск в файловой системе NTFS, – щелкнув правой кнопкой мыши или удерживая соответствующий диск, прямо из проводника Windows.

Затем выберите Свойства в раскрывающемся меню. Узнайте, что находится рядом с Файловой системой на вкладке Общие . Если диск является файловой системой NTFS, на нем будет указано Файловая система: NTFS .

Введите команду командной строки

Еще один способ узнать, какая файловая система используется жестким диском через интерфейс командной строки.

Откройте командную строку (в некоторых версиях Windows это может быть командная строка с повышенными правами) и введите ее, чтобы отобразить различные сведения о диске C: , включая его файловую систему:

  fsutil fsinfo volumeinfo C:  

Команда fsutil fsinfo volumeinfo C: | Вместо этого можно использовать findstr “System” , чтобы урезать результаты.

Чтобы проверить другой жесткий диск, используйте букву тома этого диска вместо C: .

Если вы не знаете букву диска, вы можете получить распечатку на экране с помощью команды fsutil fsinfo жесткие диски .

Особенности NTFS

Теоретически NTFS может поддерживать жесткие диски до 16 EB. Размер отдельного файла ограничен чуть менее 256 ТБ, по крайней мере, в Windows 8 и Windows 10, а также в некоторых более новых версиях Windows Server.

NTFS поддерживает квоты использования диска. Квоты использования диска устанавливаются администратором для ограничения объема дискового пространства, которое может занимать пользователь. Он используется в основном для контроля количества общего дискового пространства, которое кто-то может использовать, обычно на сетевом диске.

Атрибуты файлов, ранее невиданные в операционных системах Windows, такие как сжатый атрибут и индексированный атрибут, доступны для дисков в формате NTFS.

Шифрованная файловая система (EFS) – это еще одна функция, поддерживаемая NTFS. EFS обеспечивает шифрование на уровне файлов, что означает, что отдельные файлы и папки могут быть зашифрованы. Эта функция отличается от полного шифрования диска , которая заключается в шифровании всего диска (как в этих программах шифрования диска).

NTFS – это файловая система journaling , что означает, что она позволяет записывать изменения системы в журнал или журнал до того, как изменения будут фактически записаны. Это позволяет файловой системе вернуться к предыдущим, хорошо работающим условиям в случае сбоя, поскольку новые изменения еще не приняты.

Служба теневого копирования томов (VSS) – это функция NTFS, которая может использоваться программами службы онлайн-резервного копирования и другими программными инструментами резервного копирования для резервного копирования файлов, которые используются в настоящее время, а также самой Windows для хранения резервных копий ваших файлов.

Другая функция, представленная в этой файловой системе, называется транзакционная NTFS . Эта функция позволяет разработчикам программного обеспечения создавать приложения, которые либо полностью успешны, либо полностью терпят неудачу. Программы, использующие транзакционную NTFS, не рискуют применить несколько изменений, которые делают , а также некоторые изменения, которые не , являются рецептом для серьезных проблемы.

Транзакционная NTFS – действительно интересная тема. Вы можете прочитать больше об этом в этих статьях из Википедии и Microsoft.

NTFS включает в себя и другие функции, такие как жесткие ссылки , разреженные файлы и точки повторной обработки .

NTFS Альтернативы

Файловая система FAT была основной файловой системой в старых операционных системах Microsoft, и по большей части NTFS заменила ее.Однако все версии Windows по-прежнему поддерживают FAT, и обычно можно найти диски, отформатированные с использованием его вместо NTFS.

Файловая система exFAT является более новой файловой системой, но предназначена для использования там, где NTFS не работает, как на флеш-накопителях.

When setting up a new hard drive or an external hard drive or USB drive, you’ll always come up with this question: Which file system should I set to my drive, right? And NTFS is always seen, recommended, and used on multiple types of storage devices in many cases.

However, do you know what is NTFS file system? What are the pros, cons, and when to use NTFS on your drives? Follow this page, and we’ll present you with a full guide to learning everything about the NTFS file system. So let’s get started here.

In this article, you’ll learn:

  • What is NTFS File System — Definition
  • NTFS (New Technology File System) File System Structure — How NTFS Stores Data
  • Do I Need NTFS File System for Windows — Advantages of NTFS
  • Which Is Better? NTFS or FAT
  • Tutorial: How to Create an NTFS File System Partition on Windows 11/10
  • Troubleshoot 1: NTFS Stop Code Error — NTFS_FILE_SYSTEM BSOD in Windows
  • Troubleshoot 2: Repair NTFS File System Corruption

What is NTFS File System — Definition

NTFS file system

NTFS file system, known as New Technology File System (NTFS), is a proprietary journaling file system developed by Microsoft. Starting with Windows NT 3.1, it is the default file system of the Windows NT family. It superseded File Allocation Table (FAT) as the preferred filesystem on Windows and is supported in Linux and BSD as well.
                                                          — by Wikipedia                          

Definition: According to Wikipedia, NTFS is a file system developed by Microsoft in July 1993, and it’s widely supported by many platforms, including Windows, Linux, BSD, etc. Compared to the FAT file system format, the NTFS file system surpasses FAT, and it gets a better reading and writing support. Users can also apply some converting commands to change the NTFS file system to other formats, such as converting NTFS to FAT32 or vice versa. 

Here is a table that lists more detailed information about the NTFS file system. Follow to check the details:

Features NTFS File System
Versions
  • 1.0 — Windows NT 3.1
  • 1.1 — Windows NT 3.51
  • 1.2 — Windows NT 4.0
  • 3.0 — Windows 2000
  • 3.1 — Windows XP
File Location Bitmap
Max File Size
  • 16EiB — 1KB
  • 16TB — 64KB: Windows 7, Windows Server 2008 R2 or earlier OS.
  • 256TB — 64KB: Windows 8, Windows Server 2012 or later OS.
  • 8PB — 2MiB: Windows 10 V1709, Windows Server 2019 or later OS.
Max Partition Size
  • 4KB — 16TB
  • 8 KB — 32 TB
  • 16 KB — 64 TB
  • 32 KB — 128 TB
  • 64 KB — 256 TB
  • 128 KB — 512 TB
  • 256 KB — 1 PB
  • 512 KB — 2 PB
  • 1024 KB — 4 PB
  • 2048 KB (max size) — 8 PB
Supported Operating Systems
  • Windows
  • Mac OS X and macOS
  • Linux
  • FreeBSD, NetBSD, OpenBSD (read-only)
  • Chrome OS
  • Solaris
  • ReactOS (read-only)

So how does an NTFS file system partition stores its data, allowing Windows or other platforms to access data saved on the drive? In the next part, we’ll be showing you the NTFS file system structure and how an NTFS drive stores data.

NTFS (New Technology File System) File System Structure — How NTFS Stores Data

In this part, you’ll learn the structure of the NTFS file system and how the NTFS partition stores and saves data. First, let’s learn how does NTFS file system structure and organize data.

NTFS Structure: NTFS file system consists of 5 components, including O.S Boot Record, MFT 1, MFT Metadata, MFT2, and Data Area. 

See how each part works:

  • Partition Boot Sector: Also known as PBS, it holds the boot information.
  • Master File Table: Short for MFT, is a directory that stores metafile data (or metadata), including file name, creation date, access permissions, size, etc.
  • Metafiles: It helps to define and organize the file system, backup critical file system data, buffer file system changes, manage free space allocation, and helps structure metadata more efficiently.
  • Data Area: The unit that stores files and data in a partition or external drive.

You can also refer to the image of the NTFS file system structure to learn the details:

NTFS file system structure

Do I need an NTFS file system on Windows or storage devices? Check the next part, and you’ll get the answer.

Do I Need NTFS File System for Windows — Advantages of NTFS

So do I need NTFS file system on my computer or external storage devices? When should I use NTFS? These two questions are we’ll discuss here, and let’s see the details:

Advantages & Benefits of NTFS:

  • Fault Tolerance: The NTFS file system can automatically repair files and folders from power failure or other errors.
  • Security: NTFS file system enables you to set access permission to some local files and folders. In other words, you can set a confidential file inaccessible to some other users.
  • Compression: NTFS supports file compression so that you can compress files and folders so to speed up the system.
  • Compatibility: The NTFS file system format is widely compatible with many operating systems, including Windows 11/10/8.1/8/7/XP, Linux, and even macOS. 

Note that the NTFS file system is read-only on Mac. You’ll need to enable NTFS on Mac to make it accessible. 

  • Large File Transfer: NTFS supports saving big files. And you can use it to transfer and store super large video files on an NTFS drive.

When Do I Need NTFS and What Can NTFS Be Used For:

  • Create a new partition on a Windows disk — NTFS (by default).
  • Format USBs, micro SD cards, HDDs, and SSDs.
  • Store and transfer large files, like games, videos, movies, etc.
  • Install Windows operating systems, programs, and games on an NTFS partition with MBR or GPT disk type.
  • NTFS keeps a log of files added, modified, or deleted on a drive. 

Which Is Better? NTFS or FAT

Some of you may want to understand the differences between NTFS and FAT further or don’t know how to select one of them as your hard drive or USB format, right? 

In the beginning, we’ve introduced you to the definition of the NTFS file system. To learn the differences, let’s first get a basic idea about FAT32 first. FAT32, known as an older standard file system format before the NTFS file system, is compatible with all operating systems. 

So which is better, NTFS or FAT32? Here is an image that compares NTFS and FAT32. You can follow to learn the differences:

Image of NTFS vs FAT32

According to this image, you can clearly see that:

  • NTFS supports a bigger volume size and file size than FAT32.
  • Also, NTFS is fault tolerant with sudden errors.
  • NTFS allows file compression.
  • FAT32 is more compatible with different operating systems while NTFS is not. (Note that NTFS is read-only on MacOS X and macOS.)

So when should I use NTFS, and when to use FAT32? Here are the tips:

  • Use FAT32 on a USB flash drive or SD card with a small capacity — 32GB or smaller.
  • Use FAT32 on external hard drives for both Windows and Mac computers.
  • Use NTFS in Windows internal hard drive partitions.
  • Use NTFS for large file transfers.

Tutorial: How to Create an NTFS File System Partition on Windows 11/10

So how do I create an NTFS file system partition on my computer? Here is a guide that you can follow:

Step 1. Right-click the Windows icon and click «Disk Management».

Step 2. Right-click the unallocated space on your hard drive, and click «New Simple Volume…».

Step 3. Set the file system of the new partition as NTFS, set the volume size, and click «Next» to continue.

Step 4. Set partition drive number, label, etc., click «Next» and «Finish».

Create NTFS partition

Windows beginners can also turn to reliable partition manager software for help. For example, EaseUS Partition Master enables you to create a new NTFS partition in only a few clicks:

Step 1. Launch EaseUS Partition Master. On the main window, right-click on the unallocated space on your hard drive or external storage device and select «Create».

Step 2. Adjust the partition size, file system (Choose the file system based on your need), label, etc. for the new partition and click «OK» to continue.

Step 3. Click on the «Execute 1 Task(s)» button and create a new partition by clicking «Apply».

Watch the following video tutorial and learn how to create a partition in NTFS, FAT, or EXT file system.

After this, you can use the NTFS file system format partition to store files, install programs, and even Windows operating system.

Sometimes, you may also need to change or switch the file system between NTFS and FAT32. Here are some tips for you to try:

Alongside setting the NTFS file system as the hard drive partition format, some of you may also encounter unexpected NTFS file system errors, such as BSOD or NTFS file system errors. In the next two guides, we’ll show you how to troubleshoot these two errors on your own successfully. 

Troubleshoot 1: NTFS Stop Code Error — NTFS_FILE_SYSTEM BSOD in Windows

The NTFS file system stop code error is also known as «NTFS_FILE_SYSTEM» error or BSOD error. It often comes with a blue screen of death error with an error message:

Your PC ran into a problem and needs to be restarted. We’re just collecting some error info, and then you’ll restart for you. (0% complete)

Image of NTFS BSOD error

When this error comes, you may also notice a sentence below the notice message that states:

«If you’d like to know more, you can search online later for this error: NTFS_FILE_SYSTEM».

So how do you quickly fix this issue? Here are two resolutions for you:

1. Wait for the PC to complete the error collection process and see if it restarts.

2. If the computer doesn’t restart, try to force the PC to reboot by pressing its power button.

After the computer reboots, if it is still stuck with the BSOD error, try to restart your PC into Safe Mode: 

  • Hold the power button for 10 seconds to turn off the PC.
  • Press the power button to turn on the computer and hold the power button for 10 seconds to turn it off.
  • Press the power button again to turn on the PC, and when Windows restarts, hold the power button for 10 seconds to turn it off.
  • Press the power button again to turn on the PC and allow it to restart, then enter winRE fully.
  • Select «Troubleshoot» > «Advanced options» > «Startup settings» > «Restart».
  • After the computer restarts, press F5 to enter Safe Mode.

Reboot PC into safe mode

 After the computer reboots into Safe mode, then follow the detailed fixes introduced in this guide for help:

related articles

Fix NTFS_FILE_SYSTEM BSOD Error in Windows

Follow this page if your computer gets stuck with an NTFS_FILE_SYSTEM blue screen of death error. You can find reliable methods to fix and remove the Windows 10/8 NTFS_FILE_SYSTEM BSOD error on your own.

Image of NTFS_FILE_SYSTEM Error

Troubleshoot 2: Repair NTFS File System Corruption

Sometimes, your NTFS file system hard drive partition or external hard drive may encounter device data access error or file system corruption issue, like RAW or other errors.

To repair the NTFS file system corruption error, you can first try Windows built-in NTFS repair tool:

Step 1. Right-click the corrupted NTFS partition

Step 2. Go to «Properties» > «Tools», click «Check» under «Error Checking».

Error check and fix NTFS file system corruption error

NTFS File System Is Perfect for Windows OS and Huge File Storage

On this page, we introduced the NTFS file system, its pros and cons, and the NTFS file system structure. According to this page, it’s clear that the NTFS file system is a perfect file system format for Windows hard drives and huge file storage and transfer.

If you are ready to get this file system on your drive, go and set up your hard drive with NTFS by creating and formatting a hard drive partition or converting FAT32/exFAT device to NTFS right now. EaseUS Partition Master will assist you in completing all these tasks with only a few simple clicks.

New Technology File System[1]

Developer(s) Microsoft
Full name NT File System[2]
Introduced July 1993; 30 years ago with Windows NT 3.1
Partition IDs 0x07 (MBR)
EBD0A0A2-B9E5-4433-87C0-68B6B72699C7 (GPT)
Structures
Directory contents B-tree variant[3][4]
File allocation Bitmap
Bad blocks $BadClus (MFT Record)
Limits
Max volume size 264 clusters − 1 cluster (format);
256 TB[a] − 64 KB[a] (Windows 10 version 1703, Windows Server 2016 or earlier implementation)[5]
8 PB[a] − 2 MB[a] (Windows 10 version 1709, Windows Server 2019 or later implementation)[6]
Max file size 16 EB[a] − 1 KB (format);
16 TB − 64 KB (Windows 7, Windows Server 2008 R2 or earlier implementation)[5]
256 TB − 64 KB (Windows 8, Windows Server 2012 or later implementation)[7]
8 PB − 2 MB (Windows 10 version 1709, Windows Server 2019 or later implementation)[6]
Max no. of files 4,294,967,295 (232−1)[5]
Max filename length 255 UTF-16 code units[8]
Allowed filename
characters
  • In Win32 namespace: any UTF-16 code unit (case-insensitive) except /\:*"?<>| as well as NUL[8]
  • In POSIX namespace: any UTF-16 code unit (case-sensitive) except / as well as NUL
Features
Dates recorded Creation, modification, POSIX change, access
Date range 1 January 1601 – 28 May 60056 (File times are 64-bit numbers counting 100-nanosecond intervals (ten million per second) since 1601, which is 58,000+ years)
Date resolution 100 ns
Forks Yes (see § Alternate data stream (ADS) below)
Attributes Read-only, hidden, system, archive, not content indexed, off-line, temporary, compressed, encrypted
File system
permissions
ACLs
Transparent
compression
Per-file, LZ77 (Windows NT 3.51 onward)
Transparent
encryption
Per-file,
DESX (Windows 2000 onward),
Triple DES (Windows XP onward),
AES (Windows XP Service Pack 1, Windows Server 2003 onward)
Data deduplication Yes (Windows Server 2012)[9]
Other
Supported
operating systems
Windows NT 3.1 and later
Mac OS X 10.3 and later (read-only)
Linux kernel version 2.6 and later
Linux kernel versions 2.2-2.4 (read-only)
FreeBSD
NetBSD
OpenBSD (read-only)
ChromeOS
Solaris
ReactOS (read-only)

New Technology File System (NTFS) is a proprietary journaling file system developed by Microsoft.[2][1] Starting with Windows NT 3.1, it is the default file system of the Windows NT family.[10] It superseded File Allocation Table (FAT) as the preferred filesystem on Windows and is supported in Linux and BSD as well. NTFS reading and writing support is provided using a free and open-source kernel implementation known as NTFS3 in Linux and the NTFS-3G driver in BSD.[11][12] By using the convert command, Windows can convert FAT32/16/12 into NTFS without the need to rewrite all files.[13] NTFS uses several files typically hidden from the user to store metadata about other files stored on the drive which can help improve speed and performance when reading data.[1] Unlike FAT and High Performance File System (HPFS), NTFS supports access control lists (ACLs), filesystem encryption, transparent compression, sparse files and file system journaling. NTFS also supports shadow copy to allow backups of a system while it is running, but the functionality of the shadow copies varies between different versions of Windows.[14]

History[edit]

In the mid-1980s, Microsoft and IBM formed a joint project to create the next generation of graphical operating system; the result was OS/2 and HPFS. Because Microsoft disagreed with IBM on many important issues, they eventually separated; OS/2 remained an IBM project and Microsoft worked to develop Windows NT and NTFS.

The HPFS file system for OS/2 contained several important new features. When Microsoft created their new operating system, they borrowed many of these concepts for NTFS.[15] The original NTFS developers were Tom Miller, Gary Kimura, Brian Andrew, and David Goebel.[16]

Probably as a result of this common ancestry, HPFS and NTFS use the same disk partition identification type code (07). Using the same Partition ID Record Number is highly unusual, since there were dozens of unused code numbers available, and other major file systems have their own codes. For example, FAT has more than nine (one each for FAT12, FAT16, FAT32, etc.). Algorithms identifying the file system in a partition type 07 must perform additional checks to distinguish between HPFS and NTFS.

Versions[edit]

Microsoft has released five versions of NTFS:

NTFS version number First operating system Release date New features Remarks
1.0 Windows NT 3.1 1993[10] Initial version NTFS 1.0 is incompatible with 1.1 and newer: volumes written by Windows NT 3.5x cannot be read by Windows NT 3.1 until an update (available on the NT 3.5x installation media) is installed.[17]
1.1 Windows NT 3.51 1995 Compressed files, named streams, and access control lists[18]
1.2 Windows NT 4.0 1996 Security descriptors Commonly called NTFS 4.0 after the OS release
3.0 Windows 2000 2000 Disk quotas, file-level encryption in a form of Encrypting File System, sparse files, reparse points, update sequence number (USN) journaling, distributed link tracking, the $Extend folder and its files Compatibility was also made available for Windows NT 4.0 with the Service Pack 4 update. Commonly called NTFS 5.0 after the OS release.[19]
3.1 Windows XP October 2001 Expanded the Master File Table (MFT) entries with redundant MFT record number (useful for recovering damaged MFT files) Commonly called NTFS 5.1 after the OS release. LFS version 1.1 was replaced by version 2.0 as of Windows 8 to improve performance.

The NTFS.sys version number (e.g. v5.0 in Windows 2000) is based on the operating system version; it should not be confused with the NTFS version number (v3.1 since Windows XP).[20]

Although subsequent versions of Windows added new file system-related features, they did not change NTFS itself. For example, Windows Vista implemented NTFS symbolic links, Transactional NTFS, partition shrinking, and self-healing.[21] NTFS symbolic links are a new feature in the file system; all the others are new operating system features that make use of NTFS features already in place.

Scalability[edit]

NTFS is optimized for 4 KB[a] clusters, but supports a maximum cluster size of 2 MB[a]. (Earlier implementations support up to 64 KB)[6] The maximum NTFS volume size that the specification can support is 264 − 1 clusters, but not all implementations achieve this theoretical maximum, as discussed below.

The maximum NTFS volume size implemented in Windows XP Professional is 232 − 1 clusters, partly due to partition table limitations. For example, using 64 KB clusters, the maximum size Windows XP NTFS volume is 256 TB minus 64 KB. Using the default cluster size of 4 KB, the maximum NTFS volume size is 16 TB minus 4 KB. Both of these are vastly higher than the 128 GB[a] limit in Windows XP SP1. Many BIOS firmware limit the Master Boot Records (MBR) partitions size to 2 TiB,[22] which is the limit for hard drives with a 512 bytes physical sector size, although for a 4 KiB physical sector the MBR partition size limit is 16 TiB. An alternative is to use multiple GUID Partition Table (GPT or «dynamic») volumes for be combined to create a single NTFS volume larger than 2 TiB. Booting from a GPT volume to a Windows environment in a Microsoft supported way requires a system with Unified Extensible Firmware Interface (UEFI) and 64-bit support.[23] GPT data disks are supported on systems with BIOS.

The NTFS maximum theoretical limit on the size of individual files is 16 EB[a][24] (16 × 10246 or 264 bytes) minus 1 KB, which totals 18,446,744,073,709,550,592 bytes. With Windows 10 version 1709 and Windows Server 2019, the maximum implemented file size is 8 PB[a] minus 2 MB or 9,007,199,252,643,840 bytes.[6]

Interoperability[edit]

Windows[edit]

While the different NTFS versions are for the most part fully forward- and backward-compatible, there are technical considerations for mounting newer NTFS volumes in older versions of Microsoft Windows. This affects dual-booting, and external portable hard drives. For example, attempting to use an NTFS partition with «Previous Versions» (Volume Shadow Copy) on an operating system that does not support it will result in the contents of those previous versions being lost.[14] A Windows command-line utility called convert.exe can convert supporting file systems to NTFS, including HPFS (only on Windows NT 3.1, 3.5, and 3.51), FAT16 and FAT32 (on Windows 2000 and later).[25][26]

FreeBSD[edit]

FreeBSD 3.2 released in May 1999 included read-only NTFS support written by Semen Ustimenko.[27][28] This implementation was ported to NetBSD by Christos Zoulas and Jaromir Dolecek and released with NetBSD 1.5 in December 2000.[29] The FreeBSD implementation of NTFS was also ported to OpenBSD by Julien Bordet and offers native read-only NTFS support by default on i386 and amd64 platforms as of version 4.9 released 1 May 2011.[30][28]

Linux[edit]

Linux kernel versions 2.1.74 and later include a driver written by Martin von Löwis which has the ability to read NTFS partitions;[31] kernel versions 2.5.11 and later contain a new driver written by Anton Altaparmakov (University of Cambridge) and Richard Russon which supports file read.[32][33][31] The ability to write to files was introduced with kernel version 2.6.15 in 2006 which allows users to write to existing files but does not allow the creation of new ones.[34] Paragon’s NTFS driver (see below) has been merged into kernel version 5.15, and it supports read/write on normal, compressed and sparse files, as well as journal replaying.[35]

NTFS-3G is a free GPL-licensed FUSE implementation of NTFS that was initially developed as a Linux kernel driver by Szabolcs Szakacsits. It was re-written as a FUSE program to work on other systems that FUSE supports like macOS, FreeBSD, NetBSD, OpenBSD,[36] Solaris, QNX, and Haiku[37] and allows reading and writing to NTFS partitions. A performance enhanced commercial version of NTFS-3G, called «Tuxera NTFS for Mac», is also available from the NTFS-3G developers.[38]

Captive NTFS, a ‘wrapping’ driver that uses Windows’ own driver ntfs.sys, exists for Linux. It was built as a Filesystem in Userspace (FUSE) program and released under the GPL but work on Captive NTFS ceased in 2006.[39]

Linux kernel versions 5.15 onwards carry NTFS3, a fully functional NTFS Read-Write driver which works on NTFS versions up to 3.1 and is maintained primarily by the Paragon Software Group.

macOS[edit]

Mac OS X 10.3 included Ustimenko’s read-only implementation of NTFS from FreeBSD. Then in 2006 Apple hired Anton Altaparmakov to write a new NTFS implementation for Mac OS X 10.6.[40] Native NTFS write support is included in 10.6 and later, but is not activated by default, although workarounds do exist to enable the functionality. However, user reports indicate the functionality is unstable and tends to cause kernel panics.[41]

Paragon Software Group sells a read-write driver named NTFS for Mac OS X,[42] which is also included on some models of Seagate hard drives.[43]

OS/2[edit]

The NetDrive package for OS/2 (and derivatives such as eComStation and ArcaOS) supports a plugin which allows read and write access to NTFS volumes.[44][45]

DOS[edit]

There is a free-for-personal-use read/write driver for MS-DOS by Avira called «NTFS4DOS».[46][47]

Ahead Software developed a «NTFSREAD» driver (version 1.200) for DR-DOS 7.0x between 2002 and 2004. It was part of their Nero Burning ROM software.

Security[edit]

NTFS uses access control lists and user-level encryption to help secure user data.

Access control lists (ACLs)[edit]

NTFS file system permissions on a modern Windows system

In NTFS, each file or folder is assigned a security descriptor that defines its owner and contains two access control lists (ACLs). The first ACL, called discretionary access control list (DACL), defines exactly what type of interactions (e.g. reading, writing, executing or deleting) are allowed or forbidden by which user or groups of users. For example, files in the C:\Program Files folder may be read and executed by all users but modified only by a user holding administrative privileges.[48] Windows Vista adds mandatory access control info to DACLs. DACLs are the primary focus of User Account Control in Windows Vista and later.

The second ACL, called system access control list (SACL), defines which interactions with the file or folder are to be audited and whether they should be logged when the activity is successful, failed or both. For example, auditing can be enabled on sensitive files of a company, so that its managers get to know when someone tries to delete them or make a copy of them, and whether he or she succeeds.[48]

Encryption[edit]

Encrypting File System (EFS) provides user-transparent encryption of any file or folder on an NTFS volume.[49] EFS works in conjunction with the EFS service, Microsoft’s CryptoAPI and the EFS File System Run-Time Library (FSRTL). EFS works by encrypting a file with a bulk symmetric key (also known as the File Encryption Key, or FEK), which is used because it takes a relatively small amount of time to encrypt and decrypt large amounts of data than if an asymmetric key cipher is used. The symmetric key that is used to encrypt the file is then encrypted with a public key that is associated with the user who encrypted the file, and this encrypted data is stored in an alternate data stream of the encrypted file. To decrypt the file, the file system uses the private key of the user to decrypt the symmetric key that is stored in the data stream. It then uses the symmetric key to decrypt the file. Because this is done at the file system level, it is transparent to the user.[50] Also, in case of a user losing access to their key, support for additional decryption keys has been built into the EFS system, so that a recovery agent can still access the files if needed. NTFS-provided encryption and NTFS-provided compression are mutually exclusive; however, NTFS can be used for one and a third-party tool for the other.

The support of EFS is not available in Basic, Home, and MediaCenter versions of Windows, and must be activated after installation of Professional, Ultimate, and Server versions of Windows or by using enterprise deployment tools within Windows domains.

Features[edit]

Journaling[edit]

NTFS is a journaling file system and uses the NTFS Log ($LogFile) to record metadata changes to the volume. It is a feature that FAT does not provide and critical for NTFS to ensure that its complex internal data structures will remain consistent in case of system crashes or data moves performed by the defragmentation API, and allow easy rollback of uncommitted changes to these critical data structures when the volume is remounted. Notably affected structures are the volume allocation bitmap, modifications to MFT records such as moves of some variable-length attributes stored in MFT records and attribute lists, and indices for directories and security descriptors.

The ($LogFile) format has evolved through several versions:

Windows Version $LogFile format version
Windows NT 4.0 1.1
Windows 2000
Windows XP
Windows Vista
Windows 7
Windows 8 2.0
Windows 8.1
Windows 10

The incompatibility of the $LogFile versions implemented by Windows 8, Windows 10, Windows 11 prevents Windows 7 (and earlier versions of Windows) from recognizing version 2.0 of the $LogFile. Backward compatibility is provided by downgrading the $LogFile to version 1.1 when an NTFS volume is cleanly dismounted. It is again upgraded to version 2.0 when mounting on a compatible version of Windows. However, when hibernating to disk in the logoff state (a.k.a. Hybrid Boot or Fast Boot, which is enabled by default), mounted file systems are not dismounted, and thus the $LogFiles of any active file systems are not downgraded to version 1.1. The inability to process version 2.0 of the $LogFile by versions of Windows older than 8.0 results in an unnecessary invocation of the CHKDSK disk repair utility. This is particularly a concern in a multi-boot scenario involving pre- and post-8.0 versions of Windows, or when frequently moving a storage device between older and newer versions. A Windows Registry setting exists to prevent the automatic upgrade of the $LogFile to the newer version. The problem can also be dealt with by disabling Hybrid Boot.[51]

The USN Journal (Update Sequence Number Journal) is a system management feature that records (in $Extend\$UsnJrnl) changes to files, streams and directories on the volume, as well as their various attributes and security settings. The journal is made available for applications to track changes to the volume.[52] This journal can be enabled or disabled on non-system volumes.[53]

Hard links[edit]

The hard link feature allows different file names to directly refer to the same file contents. Hard links may link only to files in the same volume, because each volume has its own MFT.
Hard links were originally included to support the POSIX subsystem in Windows NT.[54]

Although hard links use the same MFT record (inode) which records file metadata such as file size, modification date, and attributes, NTFS also caches this data in the directory entry as a performance enhancement. This means that when listing the contents of a directory using FindFirstFile/FindNextFile family of APIs, (equivalent to the POSIX opendir/readdir APIs) you will also receive this cached information, in addition to the name and inode. However, you may not see up-to-date information, as this information is only guaranteed to be updated when a file is closed, and then only for the directory from which the file was opened.[55] This means where a file has multiple names via hard links, updating a file via one name does not update the cached data associated with the other name. You can always obtain up-to-date data using GetFileInformationByHandle (which is the true equivalent of POSIX stat function). This can be done using a handle which has no access to the file itself (passing zero to CreateFile for dwDesiredAccess), and closing this handle has the incidental effect of updating the cached information.

Windows uses hard links to support short (8.3) filenames in NTFS. Operating system support is needed because there are legacy applications that can work only with 8.3 filenames, but support can be disabled. In this case, an additional filename record and directory entry is added, but both 8.3 and long file name are linked and updated together, unlike a regular hard link.

The NTFS file system has a limit of 1024 hard links on a file.[56]

Alternate data stream (ADS)[edit]

Alternate data streams allow more than one data stream to be associated with a filename (a fork), using the format «filename:streamname» (e.g., «text.txt:extrastream»).

NTFS Streams were introduced in Windows NT 3.1, to enable Services for Macintosh (SFM) to store resource forks. Although current versions of Windows Server no longer include SFM, third-party Apple Filing Protocol (AFP) products (such as GroupLogic’s ExtremeZ-IP) still use this feature of the file system.

A small ADS named «Zone.Identifier» is added by Internet Explorer and by most browsers to mark files downloaded from external sites as possibly unsafe to run; the local shell would then require user confirmation before opening them.[57] When the user indicates that they no longer want this confirmation dialog, this ADS is deleted. This functionality is also known as «Mark of the Web«.[58][59]

Alternate streams are not listed in Windows Explorer, and their size is not included in the file’s size. When the file is copied or moved to another file system without ADS support the user is warned that alternate data streams cannot be preserved. No such warning is typically provided if the file is attached to an e-mail, or uploaded to a website. Thus, using alternate streams for critical data may cause problems. Microsoft provides a tool called Streams[60] to view streams on a selected volume. Starting with Windows PowerShell 3.0, it is possible to manage ADS natively with six cmdlets: Add-Content, Clear-Content, Get-Content, Get-Item, Remove-Item, Set-Content.[61]

Malware has used alternate data streams to hide code.[62] As a result, malware scanners and other special tools now[when?] check for alternate data streams.

File compression[edit]

Compression is enabled on a per-folder or per-file basis by setting the ‘compressed’ attribute. When compression is enabled on a folder, any files moved or saved to that folder will be automatically compressed using LZNT1 algorithm (a variant of LZ77).[63] The compression algorithm is designed to support cluster sizes of up to 4 KB; when the cluster size is greater than 4 KB on an NTFS volume, NTFS compression is not available.[64] Data is compressed in 16-cluster chunks (up to 64 KB in size); if the compression reduces 64 KB of data to 60 KB or less, NTFS treats the unneeded 4 KB pages like empty sparse file clusters—they are not written. This allows for reasonable random-access times as the OS merely has to follow the chain of fragments.

Compression works best with files that have repetitive content, are seldom written, are usually accessed sequentially, and are not themselves compressed. Single-user systems with limited hard disk space can benefit from NTFS compression for small files, from 4 KB to 64 KB or more, depending on compressibility. Files smaller than approximately 900 bytes are stored within the directory entry of the MFT.[65]

Advantages[edit]

Users of fast multi-core processors will find improvements in application speed by compressing their applications and data as well as a reduction in space used. Even when SSD controllers already compress data, there is still a reduction in I/Os since less data is transferred.[66]

According to research by Microsoft’s NTFS Development team, 50–60 GB is a reasonable maximum size for a compressed file on an NTFS volume with a 4 KB (default) cluster (block) size. This reasonable maximum size decreases sharply for volumes with smaller cluster sizes.[67]

Disadvantages[edit]

Large compressible files become highly fragmented since every chunk smaller than 64 KB becomes a fragment.[67][68] Flash memory, such as SSD drives do not have the head movement delays and high access time of mechanical hard disk drives, so fragmentation has only a smaller penalty.

If system files that are needed at boot time (such as drivers, NTLDR, winload.exe, or BOOTMGR) are compressed, the system may fail to boot correctly, because decompression filters are not yet loaded.[69][failed verification] Later editions of Windows[which?] do not allow important system files to be compressed.

System compression[edit]


Since Windows 10, Microsoft has introduced new file compression scheme based on the XPRESS algorithm with 4K/8K/16K block size[70] and the LZX algorithm;[71] both are variants of LZ77 updated with Huffman entropy coding and range coding, which LZNT1 lacked. These compression algorithms were taken from Windows Imaging Format (WIM file).

The new compression scheme is used by CompactOS feature, which reduces disk usage by compressing Windows system files.[72] CompactOS is not an extension of NTFS file compression and does not use the ‘compressed’ attribute; instead, it sets a reparse point on each compressed file with a WOF (Windows Overlay Filter) tag,[73] but the actual data is stored in an alternate data stream named «WofCompressedData», which is decompressed on-the-fly by a WOF filesystem filter driver, and the main file is an empty sparse file.[73] This design is meant purely for read-only access, so any writes to compressed files result in an automatic decompression.[73][74][75]

CompactOS compression is intended for OEMs who prepare OS images with the /compact flag of the DISM tool in Windows ADK,[76] but it can also be manually turned on per file with the /exe flag of the compact command.[77] CompactOS algorithm avoids file fragmentation by writing compressed data in contiguously allocated chunks, unlike core NTFS compression.[citation needed]

CompactOS file compression is an improved version of WIMBoot feature introduced in Windows 8.1. WIMBoot reduces Windows disk usage by keeping system files in a compressed WIM image on a separate hidden disk partition.[78] Similarly to CompactOS, Windows system directories only contain sparse files marked by a reparse point with a WOF tag, and Windows Overlay Filter driver decompresses file contents on-the-fly from the WIM image. WIMBoot is less effective than CompactOS though, as new updated versions of system files need to be written to the system partition, consuming disk space.[73]

Sparse files[edit]

A sparse file: Empty bytes don’t need to be saved, thus they can be represented by metadata.
One petabyte (1,125,899,906,842,624 bytes) of sparse files, 0 bytes on disk.

Sparse files are files interspersed with empty segments for which no actual storage space is used. To the applications, the file looks like an ordinary file with empty regions seen as regions filled with zeros; the file system maintains an internal list of such regions for each sparse file.[79] A sparse file does not necessarily include sparse zeros areas; the «sparse file» attribute just means that the file is allowed to have them.

Database applications, for instance, may use sparse files.[80] As with compressed files, the actual sizes of sparse files are not taken into account when determining quota limits.[81]

Volume Shadow Copy[edit]

The Volume Shadow Copy Service (VSS) keeps historical versions of files and folders on NTFS volumes by copying old, newly overwritten data to shadow copy via copy-on-write technique. The user may later request an earlier version to be recovered. This also allows data backup programs to archive files currently in use by the file system.

Windows Vista also introduced persistent shadow copies for use with System Restore and Previous Versions features. Persistent shadow copies, however, are deleted when an older operating system mounts that NTFS volume. This happens because the older operating system does not understand the newer format of persistent shadow copies.[14]

Transactions[edit]

As of Windows Vista, applications can use Transactional NTFS (TxF) to group multiple changes to files together into a single transaction. The transaction will guarantee that either all of the changes happen, or none of them do, and that no application outside the transaction will see the changes until they are committed.[82]

It uses similar techniques as those used for Volume Shadow Copies (i.e. copy-on-write) to ensure that overwritten data can be safely rolled back, and a CLFS log to mark the transactions that have still not been committed, or those that have been committed but still not fully applied (in case of system crash during a commit by one of the participants).

Transactional NTFS does not restrict transactions to just the local NTFS volume, but also includes other transactional data or operations in other locations such as data stored in separate volumes, the local registry, or SQL databases, or the current states of system services or remote services. These transactions are coordinated network-wide with all participants using a specific service, the DTC, to ensure that all participants will receive same commit state, and to transport the changes that have been validated by any participant (so that the others can invalidate their local caches for old data or rollback their ongoing uncommitted changes). Transactional NTFS allows, for example, the creation of network-wide consistent distributed file systems, including with their local live or offline caches.

Microsoft now advises against using TxF: «Microsoft strongly recommends developers utilize alternative means» since «TxF may not be available in future versions of Microsoft Windows».[83]

Quotas[edit]

Disk quotas were introduced in NTFS v3. They allow the administrator of a computer that runs a version of Windows that supports NTFS to set a threshold of disk space that users may use. It also allows administrators to keep track of how much disk space each user is using. An administrator may specify a certain level of disk space that a user may use before they receive a warning, and then deny access to the user once they hit their upper limit of space. Disk quotas do not take into account NTFS’s transparent file-compression, should this be enabled. Applications that query the amount of free space will also see the amount of free space left to the user who has a quota applied to them.

Reparse points[edit]

Introduced in NTFS v3, NTFS reparse points are used by associating a reparse tag in the user space attribute of a file or directory. Microsoft includes several default tags including symbolic links, directory junction points and volume mount points. When the Object Manager parses a file system name lookup and encounters a reparse attribute, it will reparse the name lookup, passing the user controlled reparse data to every file system filter driver that is loaded into Windows. Each filter driver examines the reparse data to see whether it is associated with that reparse point, and if that filter driver determines a match, then it intercepts the file system request and performs its special functionality.

Limitations[edit]

Resizing[edit]

Starting with Windows Vista Microsoft added the built-in ability to shrink or expand a partition. However, this ability does not relocate page file fragments or files that have been marked as unmovable, so shrinking a volume will often require relocating or disabling any page file, the index of Windows Search, and any Shadow Copy used by System Restore. Various third-party tools are capable of resizing NTFS partitions.

OneDrive[edit]

Since 2017, Microsoft requires the OneDrive file structure to reside on an NTFS disk.[84] This is because OneDrive Files On-Demand feature uses NTFS reparse points to link files and folders that are stored in OneDrive to the local filesystem, making the file or folder unusable with any previous version of Windows, with any other NTFS file system driver, or any file system and backup utilities not updated to support it.[85]

Structure[edit]

NTFS is made up of several components including: a partition boot sector (PBS) that holds boot information; the master file table that stores a record of all files and folders in the filesystem; a series of meta files that help structure meta data more efficiently; data streams and locking mechanisms.

Internally, NTFS uses B-trees to index file system data. A file system journal is used to guarantee the integrity of the file system metadata but not individual files’ content. Systems using NTFS are known to have improved reliability compared to FAT file systems.[86]

NTFS allows any sequence of 16-bit values for name encoding (e.g. file names, stream names or index names) except 0x0000. This means UTF-16 code units are supported, but the file system does not check whether a sequence is valid UTF-16 (it allows any sequence of short values, not restricted to those in the Unicode standard). In Win32 namespace, any UTF-16 code units are case insensitive whereas in POSIX namespace they are case sensitive. File names are limited to 255 UTF-16 code units. Certain names are reserved in the volume root directory and cannot be used for files. These are $MFT, $MFTMirr, $LogFile, $Volume, $AttrDef, . (dot), $Bitmap, $Boot, $BadClus, $Secure, $UpCase, and $Extend.[5] . (dot) and $Extend are both directories; the others are files. The NT kernel limits full paths to 32,767 UTF-16 code units. There are some additional restrictions on code points and file names.[87]

Partition Boot Sector (PBS)[edit]

This boot partition format is roughly based upon the earlier FAT filesystem, but the fields are in different locations. Some of these fields, especially the «sectors per track», «number of heads» and «hidden sectors» fields may contain dummy values on drives where they either do not make sense or are not determinable.

The OS first looks at the 8 bytes at 0x30 to find the cluster number of the $MFT, then multiplies that number by the number of sectors per cluster (1 byte found at 0x0D). This value is the sector offset (LBA) to the $MFT, which is described below.

Master File Table[edit]

In NTFS, all file, directory and metafile data—file name, creation date, access permissions (by the use of access control lists), and size—are stored as metadata in the Master File Table (MFT). This abstract approach allowed easy addition of file system features during Windows NT’s development—an example is the addition of fields for indexing used by the Active Directory and the Windows Search. This also enables fast file search software to locate named local files and folders included in the MFT very quickly, without requiring any other index.

The MFT structure supports algorithms which minimize disk fragmentation.[90] A directory entry consists of a filename and a «file ID» (analogous to the inode number), which is the record number representing the file in the Master File Table. The file ID also contains a reuse count to detect stale references. While this strongly resembles the W_FID of Files-11, other NTFS structures radically differ.

A partial copy of the MFT, called the MFT mirror, is stored to be used in case of corruption.[91] If the first record of the MFT is corrupted, NTFS reads the second record to find the MFT mirror file. Locations for both files are stored in the boot sector.[92]

Metafiles[edit]

NTFS contains several files that define and organize the file system. In all respects, most of these files are structured like any other user file ($Volume being the most peculiar), but are not of direct interest to file system clients.[93] These metafiles define files, back up critical file system data, buffer file system changes, manage free space allocation, satisfy BIOS expectations, track bad allocation units, and store security and disk space usage information. All content is in an unnamed data stream, unless otherwise indicated.

These metafiles are treated specially by Windows, handled directly by the NTFS.SYS driver and are difficult to directly view: special purpose-built tools are needed.[b] As of Windows 7, the NTFS driver completely prohibits user access, resulting in a BSoD whenever an attempt to execute a metadata file is made. One such tool is the nfi.exe («NTFS File Sector Information Utility») that is freely distributed as part of the Microsoft «OEM Support Tools». For example, to obtain information on the «$MFT»-Master File Table Segment the following command is used: nfi.exe c:\$MFT[94] Another way to bypass the restriction is to use 7-Zip’s file manager and go to the low-level NTFS path \\.\X:\ (where X:\ resembles any drive/partition). Here, 3 new folders will appear: $EXTEND, [DELETED] (a pseudo-folder that 7-Zip uses to attach files deleted from the file system to view), and [SYSTEM] (another pseudo-folder that contains all the NTFS metadata files). This trick can be used from removable devices (USB flash drives, external hard drives, SD Cards, etc.) inside Windows, but doing this on the active partition requires offline access (namely WinRE).

Attribute lists, attributes, and streams[edit]

For each file (or directory) described in the MFT record, there is a linear repository of stream descriptors (also named attributes), packed together in one or more MFT records (containing the so-called attributes list), with extra padding to fill the fixed 1 KB size of every MFT record, and that fully describes the effective streams associated with that file.

Each attribute has an attribute type (a fixed-size integer mapping to an attribute definition in file $AttrDef), an optional attribute name (for example, used as the name for an alternate data stream), and a value, represented in a sequence of bytes. For NTFS, the standard data of files, the alternate data streams, or the index data for directories are stored as attributes.

According to $AttrDef, some attributes can be either resident or non-resident. The $DATA attribute, which contains file data, is such an example. When the attribute is resident (which is represented by a flag), its value is stored directly in the MFT record. Otherwise, clusters are allocated for the data, and the cluster location information is stored as data runs in the attribute.

  • For each file in the MFT, the attributes identified by attribute type, attribute name must be unique. Additionally, NTFS has some ordering constraints for these attributes.
  • There is a predefined null attribute type, used to indicate the end of the list of attributes in one MFT record. It must be present as the last attribute in the record (all other storage space available after it will be ignored and just consists of padding bytes to match the record size in the MFT).
  • Some attribute types are required and must be present in each MFT record, except unused records that are just indicated by null attribute types.
    • This is the case for the $STANDARD_INFORMATION attribute that is stored as a fixed-size record and contains the timestamps and other basic single-bit attributes (compatible with those managed by FAT in DOS or Windows 9x).
  • Some attribute types cannot have a name and must remain anonymous.
    • This is the case for the standard attributes, or for the preferred NTFS «filename» attribute type, or the «short filename» attribute type, when it is also present (for compatibility with DOS-like applications, see below). It is also possible for a file to contain only a short filename, in which case it will be the preferred one, as listed in the Windows Explorer.
    • The filename attributes stored in the attribute list do not make the file immediately accessible through the hierarchical file system. In fact, all the filenames must be indexed separately in at least one other directory on the same volume. There it must have its own MFT record and its own security descriptors and attributes that reference the MFT record number for this file. This allows the same file or directory to be «hardlinked» several times from several containers on the same volume, possibly with distinct filenames.
  • The default data stream of a regular file is a stream of type $DATA but with an anonymous name, and the ADSs are similar but must be named.
  • On the other hand, the default data stream of directories has a distinct type, but are not anonymous: they have an attribute name («$I30» in NTFS 3+) that reflects its indexing format.

All attributes of a given file may be displayed by using the nfi.exe («NTFS File Sector Information Utility») that is freely distributed as part of the Microsoft «OEM Support Tools».[94]

Windows system calls may handle alternate data streams.[5] Depending on the operating system, utility and remote file system, a file transfer might silently strip data streams.[5] A safe way of copying or moving files is to use the BackupRead and BackupWrite system calls, which allow programs to enumerate streams, to verify whether each stream should be written to the destination volume and to knowingly skip unwanted streams.[5]

Resident vs. non-resident attributes[edit]

To optimize the storage and reduce the I/O overhead for the very common case of attributes with very small associated value, NTFS prefers to place the value within the attribute itself (if the size of the attribute does not then exceed the maximum size of an MFT record), instead of using the MFT record space to list clusters containing the data; in that case, the attribute will not store the data directly but will just store an allocation map (in the form of data runs) pointing to the actual data stored elsewhere on the volume.[95] When the value can be accessed directly from within the attribute, it is called «resident data» (by computer forensics workers). The amount of data that fits is highly dependent on the file’s characteristics, but 700 to 800 bytes is common in single-stream files with non-lengthy filenames and no ACLs.

  • Some attributes (such as the preferred filename, the basic file attributes) cannot be made non-resident. For non-resident attributes, their allocation map must fit within MFT records.
  • Encrypted-by-NTFS, sparse data streams, or compressed data streams cannot be made resident.
  • The format of the allocation map for non-resident attributes depends on its capability of supporting sparse data storage. In the current implementation of NTFS, once a non-resident data stream has been marked and converted as sparse, it cannot be changed back to non-sparse data, so it cannot become resident again, unless this data is fully truncated, discarding the sparse allocation map completely.
  • When a non-resident attribute is so fragmented, that its effective allocation map cannot fit entirely within one MFT record, NTFS stores the attribute in multiple records. The first one among them is called the base record, while the others are called extension records. NTFS creates a special attribute $ATTRIBUTE_LIST to store information mapping different parts of the long attribute to the MFT records, which means the allocation map may be split into multiple records. The $ATTRIBUTE_LIST itself can also be non-resident, but its own allocation map must fit within one MFT record.
  • When there are too many attributes for a file (including ADS’s, extended attributes, or security descriptors), so that they cannot fit all within the MFT record, extension records may also be used to store the other attributes, using the same format as the one used in the base MFT record, but without the space constraints of one MFT record.

The allocation map is stored in a form of data runs with compressed encoding. Each data run represents a contiguous group of clusters that store the attribute value. For files on a multi-GB volume, each entry can be encoded as 5 to 7 bytes, which means a 1 KB MFT record can store about 100 such data runs. However, as the $ATTRIBUTE_LIST also has a size limit, it is dangerous to have more than 1 million fragments of a single file on an NTFS volume, which also implies that it is in general not a good idea to use NTFS compression on a file larger than 10 GB.[96]

The NTFS file system driver will sometimes attempt to relocate the data of some of the attributes that can be made non-resident into the clusters, and will also attempt to relocate the data stored in clusters back to the attribute inside the MFT record, based on priority and preferred ordering rules, and size constraints.

Since resident files do not directly occupy clusters («allocation units»), it is possible for an NTFS volume to contain more files on a volume than there are clusters. For example, a 74.5 GB partition NTFS formats with 19,543,064 clusters of 4 KB. Subtracting system files (a 64 MB log file, a 2,442,888-byte Bitmap file, and about 25 clusters of fixed overhead) leaves 19,526,158 clusters free for files and indices. Since there are four MFT records per cluster, this volume theoretically could hold almost 4 × 19,526,158 = 78,104,632 resident files.

Opportunistic locks[edit]

Opportunistic file locks (oplocks) allow clients to alter their buffering strategy for a given file or stream in order to increase performance and reduce network use.[97] Oplocks apply to the given open stream of a file and do not affect oplocks on a different stream.

Oplocks can be used to transparently access files in the background. A network client may avoid writing information into a file on a remote server if no other process is accessing the data, or it may buffer read-ahead data if no other process is writing data.

Windows supports four different types of oplocks:

  • Level 2 (or shared) oplock: multiple readers, no writers (i.e. read caching).
  • Level 1 (or exclusive) oplock: exclusive access with arbitrary buffering (i.e. read and write caching).
  • Batch oplock (also exclusive): a stream is opened on the server, but closed on the client machine (i.e. read, write and handle caching).
  • Filter oplock (also exclusive): applications and file system filters can «back out» when others try to access the same stream (i.e. read and write caching) (since Windows 2000)

Opportunistic locks have been enhanced in Windows 7 and Windows Server 2008 R2 with per-client oplock keys.[98]

Time[edit]

Windows NT and its descendants keep internal timestamps as UTC and make the appropriate conversions for display purposes; all NTFS timestamps are in UTC.[citation needed]

For historical reasons, the versions of Windows that do not support NTFS all keep time internally as local zone time, and therefore so do all file systems – other than NTFS – that are supported by current versions of Windows. This means that when files are copied or moved between NTFS and non-NTFS partitions, the OS needs to convert timestamps on the fly. But if some files are moved when daylight saving time (DST) is in effect, and other files are moved when standard time is in effect, there can be some ambiguities in the conversions. As a result, especially shortly after one of the days on which local zone time changes, users may observe that some files have timestamps that are incorrect by one hour. Due to the differences in implementation of DST in different jurisdictions, this can result in a potential timestamp error of up to 4 hours in any given 12 months.[99]

See also[edit]

  • Comparison of file systems
  • NTFSDOS
  • ntfsresize
  • WinFS (a canceled Microsoft filesystem)
  • ReFS, a newer Microsoft filesystem

Notes[edit]

  1. ^ a b c d e f g h i j 1 byte = 8 bits
    1 KB = 1,024 bytes
    1 MB = 1,048,576 bytes
    1 GB = 1,073,741,824 bytes
    1 TB = 1,099,511,627,776 bytes
    1 PB = 1,125,899,906,842,624 bytes
    1 EB = 1,152,921,504,606,846,976 bytes
  2. ^ Since Windows XP, it is very difficult to view a listing of these files: they exist in the root directory’s index, but the Win32 interface filters them out. In NT 4.0, the command line dir command would list the metafiles in the root directory if /a were specified. In Windows 2000, dir /a stopped working, but dir /a \$MFT worked.

References[edit]

  1. ^ a b c Karresand, Martin; Axelsson, Stefan; Dyrkolbotn, Geir Olav (2019-07-01). «Using NTFS Cluster Allocation Behavior to Find the Location of User Data». Digital Investigation. 29: –51–S60. doi:10.1016/j.diin.2019.04.018. ISSN 1742-2876. S2CID 199004263.
  2. ^ a b «Glossary». [MS-EFSR]: Encrypting File System Remote (EFSRPC) Protocol. Microsoft. 14 November 2013.
  3. ^ «How NTFS Works». TechNet. Microsoft. 8 October 2009. Retrieved 2 December 2017.
  4. ^ «B*Trees — NTFS Directory Trees — Concept — NTFS Documentation». flatcap.org. Archived from the original on 2019-05-13. Retrieved 2019-05-13.
  5. ^ a b c d e f g «How NTFS Works». Windows Server 2003 Technical Reference. 2003-03-28. Retrieved 2011-09-12.
  6. ^ a b c d «Appendix A: Product Behavior». [MS-FSA]: File System Algorithms. Microsoft. 2018-09-12. Retrieved 2018-10-01. NTFS uses a default cluster size of 4 KB, a maximum cluster size of 64 KB on Windows 10 v1703 operating system and Windows Server 2016 and prior, and 2 MB on Windows 10 v1709 operating system and Windows Server 2019 and later, and a minimum cluster size of 512 bytes.
  7. ^ «Appendix A: Product Behavior». [MS-FSA]: File System Algorithms. Microsoft. 14 November 2013. Retrieved 2012-09-21.
  8. ^ a b Russon, Richard; Fledel, Yuval. «NTFS Documentation» (PDF). Archived (PDF) from the original on 2022-10-09. Retrieved 2011-06-26.
  9. ^ Rick Vanover (14 September 2011). «Windows Server 8 data deduplication». Archived from the original on 2016-07-18. Retrieved 2011-12-02.
  10. ^ a b Custer, Helen (1994). Inside the Windows NT File System. Microsoft Press. ISBN 978-1-55615-660-1.
  11. ^ «NTFS3 — The Linux Kernel documentation». www.kernel.org. Retrieved 2021-12-02.
  12. ^ «ntfs-3g». www.freebsd.org. Retrieved 2021-12-02.
  13. ^ «How to Convert a Drive from FAT32 to NTFS without Data Loss». WindowsLoop. 11 July 2021. Retrieved 8 August 2021.
  14. ^ a b c cfsbloggers (July 14, 2006). «How restore points and other recovery features in Windows Vista are affected when dual-booting with Windows XP». The Filing Cabinet. Archived from the original on 2006-07-18. Retrieved 2007-03-21.
  15. ^ Kozierok, Charles (14 February 2018). «Overview and History of NTFS». The PC Guide. Retrieved May 30, 2019.
  16. ^ Custer, Helen (1994). Inside the Windows NT File System. Microsoft Press. p. vii. ISBN 978-1-55615-660-1.
  17. ^ «Recovering Windows NT After a Boot Failure on an NTFS Drive». Microsoft. November 1, 2006.
  18. ^ a b Russinovich, Mark (30 June 2006). «Inside Win2K NTFS, Part 1». MSDN. Microsoft. Retrieved 2008-04-18.
  19. ^ «What’s New in Windows NT 4.0 Service Pack 4?». Microsoft.com. 12 January 1999. Archived from the original on 17 January 1999. Retrieved 17 August 2018.
  20. ^ «New Capabilities and Features of the NTFS 3.1 File System». Microsoft. 1 December 2007.
  21. ^ Loveall, John (2006). «Storage improvements in Windows Vista and Windows Server 2008» (PowerPoint). Microsoft. pp. 14–20. Retrieved 2007-09-04.
  22. ^ «Default cluster size for NTFS, FAT, and exFAT». Microsoft Support.
  23. ^ «Booting from GPT». Rodsbooks.com. Retrieved 22 September 2018.
  24. ^ «NTFS vs FAT vs exFAT — NTFS.com». www.ntfs.com. Retrieved 2021-01-19.
  25. ^ «How to Convert FAT Disks to NTFS». Microsoft. 18 December 2017. Retrieved May 30, 2019.
  26. ^ «How to use Convert.exe to convert a partition to the NTFS file system». Microsoft Corporation. 2007-02-12. Retrieved 2010-12-26.
  27. ^ «FreeBSD 3.2 Release Notes». 17 May 1999. Retrieved 2020-06-15.
  28. ^ a b «mount_ntfs — OpenBSD manual pages». Retrieved 2020-06-15.
  29. ^ «Announcing NetBSD 1.5». 6 December 2000. Retrieved 2020-06-15.
  30. ^ «OpenBSD 4.9». Openbsd.com. Retrieved 22 September 2018.
  31. ^ a b «NTFS Credits and History». Linux-NTFS Project. Archived from the original on 2021-09-24. Retrieved 2021-09-24.
  32. ^ «Kernel development». lwn.net. 2 May 2002. Retrieved 2021-09-05.
  33. ^ «Release notes for v2.5.11». 29 April 2002. Retrieved 2021-09-05.
  34. ^ «2.6.15 changelog». Linux project. 3 January 2006. Retrieved 2021-09-05.
  35. ^ Anderson, Tim (2021-09-06). «GitHub merges ‘useless garbage’ says Linus Torvalds as new NTFS support added to Linux kernel 5.15». The Register. Retrieved 2021-09-07.
  36. ^ «OpenBSD adds fuse(4) support for adding file systems in userland». OpenBSD Journal. 2013-11-08. Retrieved 2013-11-08.
  37. ^ «NTFS-3G Stable Read/Write Driver». 2009-07-25.
  38. ^ «Tuxera NTFS for Mac». Tuxera. August 30, 2011. Retrieved September 20, 2011.
  39. ^ «Jan Kratochvil: Captive: The first free NTFS read/write filesystem for GNU/Linux». Retrieved 2020-06-15.
  40. ^ «About Tuxera». Retrieved 2020-06-15.
  41. ^ «10.6: Enable native NTFS read/write support». 1 October 2009. Archived from the original on 5 September 2021. Retrieved 5 September 2021.
  42. ^ «NTFS for Mac OS X, communication channel between Mac OS X and Windows». Paragon Software Group. Retrieved September 20, 2011.
  43. ^ «The Leader in Mass Data Storage Solutions | Seagate US». Seagate.com. Archived from the original on February 10, 2011.
  44. ^ «NTFS plugin for NetDrive». ecsoft2.org. Retrieved 2020-09-09.
  45. ^ «NetDrive for OS/2». arcanoae.com. Retrieved 2020-09-09.
  46. ^ «Avira NTFS4DOS Personal». Archived from the original on June 19, 2010. Retrieved 2009-07-25.
  47. ^ «Download Avira NTFS4DOS Personal 1.9». Archived from the original on 10 November 2013. Retrieved 22 September 2018.
  48. ^ a b «How Security Descriptors and Access Control Lists Work». TechNet. Microsoft. Retrieved 4 September 2015.
  49. ^ Morello, John (February 2007). «Security Watch Deploying EFS: Part 1». Technet Magazine. Microsoft. Retrieved 2009-01-25.
  50. ^ «How EFS Works». Windows 2000 Resource Kit. Microsoft. 18 July 2012. Retrieved 25 February 2014.
  51. ^ «Windows 8 volume compatibility considerations with prior versions of Windows». Retrieved 2021-12-17.
  52. ^ «Change Journals». Microsoft Docs. 7 January 2021. Retrieved 2023-08-12.
  53. ^ «Creating, Modifying, and Deleting a Change Journal (Windows)». Microsoft Docs. 7 January 2021. Retrieved 2023-08-12.
  54. ^ «Chapter 29 – POSIX Compatibility». MS Windows NT Workstation 4.0 Resource Guide. Microsoft. 1995. Retrieved 21 October 2013.
  55. ^ «Hard Links and Junctions». MSDN. Microsoft. 12 October 2013. Retrieved 21 October 2013.
  56. ^ «MSDN – CreateHardLink function». Retrieved 14 January 2016.
  57. ^ Russinovich, Mark E.; Solomon, David A.; Ionescu, Alex (2009). «File Systems». Windows Internals (5th ed.). Microsoft Press. p. 921. ISBN 978-0-7356-2530-3. One component in Windows that uses multiple data streams is the Attachment Execution Service[…] depending on which zone the file was downloaded from […] Windows Explorer might warn the user
  58. ^ Boyd, Christopher (26 October 2022). «Malformed signature trick can bypass Mark of the Web». Malwarebytes. Retrieved 2023-05-15.
  59. ^ DHB-MSFT (28 February 2023). «Macros from the internet are blocked by default in Office — Deploy Office». learn.microsoft.com. Retrieved 2023-05-15.
  60. ^ «Streams — Sysinternals». Microsoft Docs. 23 March 2021. Retrieved 12 August 2023.
  61. ^ «FileSystem Provider». Microsoft. 9 August 2012. Archived from the original on 23 January 2015. Retrieved 23 January 2015.
  62. ^ «Malware utilising Alternate Data Streams?». AusCERT Web Log. 21 August 2007. Archived from the original on 2011-02-23.
  63. ^ «File Compression and Decompression». MSDN Platform SDK: File Systems. Retrieved 2005-08-18.
  64. ^ «The Default Cluster Size for the NTFS and FAT File Systems». Microsoft. January 31, 2002. Retrieved 2012-01-10.
  65. ^ «How NTFS Works». 2003-03-28. Retrieved 2011-10-24.
  66. ^ Masiero, Manuel (2011-12-01). «Should You Compress Data On Your SSD?». Tom’s Hardware. Bestofmedia Group. Retrieved 2013-04-05.
  67. ^ a b Middleton, Dennis. «Understanding NTFS Compression». Ntdebugging Blog. Microsoft. Archived from the original on 29 June 2011. Retrieved 2011-03-16.
  68. ^ «Shrinking the gap: carving NTFS-compressed files». Retrieved 2011-05-29.
  69. ^ «Disk Concepts and Troubleshooting». Microsoft. 11 September 2008. Retrieved 2012-03-26.
  70. ^ «[MS-XCA]: Xpress Compression Algorithm». 31 January 2023.
  71. ^ «wimlib: the open source Windows Imaging (WIM) library — Compression algorithm».
  72. ^ «Compact OS, single-instancing, and image optimization». Microsoft. Retrieved 1 October 2019.
  73. ^ a b c d Raymond Chen (18 June 2019). «What is WofCompressedData? Does WOF mean that Windows is a dog?». Microsoft DevBlogs.
  74. ^ Biggers, Eric (29 April 2019). «NTFS-3G plugin for reading «system compressed» files». GitHub. Retrieved 1 October 2019.
  75. ^ «Re: [ntfs-3g-devel] Experimental support for Windows 10 «System Compressed» files». SourceForge.net. Retrieved 1 October 2019.
  76. ^ «DISM Overview». 15 December 2021.
  77. ^ «Compact». 3 February 2023.
  78. ^ «Windows Image File Boot (WIMBoot) Overview». 10 March 2015.
  79. ^ «Sparse Files». MSDN. Microsoft. 12 October 2013. Retrieved 21 October 2013.
  80. ^ Kandoth, Suresh B. (4 March 2009). «Sparse File Errors: 1450 or 665 due to file fragmentation: Fixes and Workarounds». CSS SQL Server Engineers. Microsoft. Archived from the original on 21 October 2013. Retrieved 21 October 2013.
  81. ^ «Sparse Files and Disk Quotas». MSDN Library. Microsoft. 12 October 2013. Retrieved 21 October 2013.
  82. ^ «Transactional NTFS». MSDN. Microsoft. Archived from the original on 2007-02-21. Retrieved 2007-02-02.
  83. ^ «Transactional NTFS (TxF)». Microsoft Docs. Microsoft. 20 July 2022. Retrieved 12 August 2023.
  84. ^ «Unable to open content synced in a OneDrive folder on an external drive». Microsoft Support. Retrieved 2021-04-03.
  85. ^ André, Jean-Pierre (March 1, 2019). «NTFS-3G: Junction Points, Symbolic Links and Reparse Points». jp-andre.pagesperso-orange.fr.
  86. ^ «Chapter 18 – Choosing a File System». MS Windows NT Workstation 4.0 Resource Guide. Microsoft. 20 February 2014. Retrieved 25 February 2014.
  87. ^ «Naming Files, Paths, and Namespaces». MSDN. Microsoft. Naming Conventions. Retrieved 25 February 2014.
  88. ^ «NTFS. Partition Boot Sector». Ntfs.com. Retrieved 22 September 2018.
  89. ^ «Boot Sector». Technet.microsoft.com. September 11, 2008. Table 1.13 BPB and Extended BPB Fields on NTFS Volumes. Retrieved 22 September 2018.
  90. ^ «Master File Table». MSDN. July 2, 2012.
  91. ^ «Forensics: What is the MFT Mirror?». Where is Your Data?. 2009-06-05. Retrieved 2021-07-30.
  92. ^ «NTFS Master File Table (MFT)». Ntfs.com. Retrieved 22 September 2018.
  93. ^ Schwarz, Thomas. «COEN 252 Computer Forensics NTFS». Faculty of Organization and Informatics University of Zagreb. Archived from the original on 2021-02-27. Retrieved May 30, 2019.
  94. ^ a b «OEM Support Tools Phase 3 Service Release 2 Availability». Microsoft Corporation. 2007-02-21. Archived from the original on 2015-02-23. Retrieved 2010-06-16. Windows NT File System (NTFS) File Sector Information Utility … A tool used to dump information about an NTFS volume
  95. ^ «The Four Stages of NTFS File Growth». Archived from the original on 23 September 2018. Retrieved 22 September 2018.
  96. ^ «A heavily fragmented file in an NTFS volume may not grow beyond a certain size». Archived from the original on 2021-05-06. Retrieved 2021-05-19.
  97. ^ «How Oplocks function in the Windows Environment: Overview». Archived from the original on 2010-08-23. Retrieved 2018-12-19.
  98. ^ «What’s New in NTFS». Technet.microsoft.com. 2 July 2012. Retrieved 22 September 2018.
  99. ^ Gilligan, Jonathan (28 May 2001). «Beating the Daylight Saving Time bug and getting correct file modification times». The Code Project.

Further reading[edit]

  • Bolosky, William J.; Corbin, Scott; Goebel, David; Douceur, John R. (January 2000). «Single Instance Storage in Windows 2000». Proceedings of 4th USENIX Windows Systems Symposium.
  • Custer, Helen (1994). Inside the Windows NT File System. Microsoft Press. ISBN 978-1-55615-660-1.
  • Nagar, Rajeev (1997). Windows NT File System Internals: A Developer’s Guide. O’Reilly. ISBN 978-1-56592-249-5.
  • «NTFS Technical Reference». Microsoft TechNet. Microsoft. 28 March 2003.

External links[edit]

  • NTFS3
  • NTFS3 source code

  • Npm command not found windows
  • Nt kernel system синий экран windows 10
  • Nt kernel and system что это windows 7
  • Ntfs или exfat для ssd windows 10
  • Nt 5890k driver windows 10