Эта статья может быть слишком технической, чтобы ее могло понять большинство читателей . ( Сентябрь 2021 г. ) |
Разработчики) | Microsoft , SCP , IBM , Compaq , Digital Research , Novell , Caldera |
---|---|
Полное имя | Таблица размещения файлов: FAT12 (12-битная версия), FAT16 (16-битные версии), FAT32 (32-битная версия с 28 используемыми битами), exFAT (64-битные версии) |
Введено | 1977 г. ( автономный диск BASIC-80 ) FAT12: август 1980 г. (SCP QDOS ) FAT16: август 1984 г. (IBM PC DOS 3.0) FAT16B: ноябрь 1987 г. ( Compaq MS-DOS 3.31) FAT32: август 1996 г. ( Windows 95 OSR2 ) exFAT: ноябрь 2006 г. ( Windows Embedded CE 6.0 ) |
Идентификатор раздела | MBR / EBR : FAT12 : ea FAT16 : ea FAT32 : ea exFAT : ea BDP : 0x01 0x04 0x06 0x0E 0x0B 0x0C 0x07 EBD0A0A2-B9E5-443387C0-68B6B72699C7 |
Структуры | |
Содержимое каталога | Стол |
Размещение файлов | Связанный список |
Плохие блоки | Теги кластера |
Пределы | |
Максимум. размер тома | FAT12: 32 МБ (256 МБ для кластеров по 64 КБ ) FAT16: 2 ГБ (4 ГБ для кластеров по 64 КБ ) FAT32: 2 ТБ (16 ТБ для секторов по 4 КБ ) |
Максимум. размер файла | 4 294 967 295 байт (4 ГБ - 1) с FAT16B и FAT32 [1] |
Максимум. количество файлов | FAT12: 4068 для кластеров 8 КБ FAT16: 65 460 для кластеров 32 КБ FAT32: 268 173 300 для кластеров 32 КБ |
Максимум. длина имени файла | 8.3 имя файла или 255 символов UCS-2 при использовании LFN |
Функции | |
Даты записаны | Дата / время изменения, дата / время создания (только для DOS 7.0 и выше), дата доступа (доступно только при включенном ACCDATE ), [2] дата / время удаления (только с DELWATCH 2) |
Диапазон дат | 1980-01-01 по 2099-12-31 ( 2107-12-31 ) |
Разрешение даты | 2 секунды для времени последнего изменения, 10 мс для времени создания, 1 день для даты доступа, 2 секунды для времени удаления |
Вилки | Не изначально |
Атрибуты | Только для чтения , Скрытый , Система , Том , Каталог , Архив |
Разрешения файловой системы | FAT12 / FAT16: права доступа к файлам, каталогам и томам для чтения , записи , выполнения , удаления только с DR-DOS , PalmDOS , Novell DOS , OpenDOS , FlexOS , 4680 OS , 4690 OS , Concurrent DOS , Multiuser DOS , System Manager , REAL / 32 (Право выполнения только в FlexOS, 4680 OS, 4690 OS; пароли отдельных файлов / каталогов не в FlexOS, 4680 OS, 4690 OS; World / Group / Ownerклассы разрешений только с загруженной многопользовательской безопасностью) FAT32: Частично, только с DR-DOS, REAL / 32 и 4690 OS |
Прозрачное сжатие | FAT12 / FAT16: на том, SuperStor , Stacker , DoubleSpace , DriveSpace FAT32: Нет |
Прозрачное шифрование | FAT12 / FAT16: только по объему с DR-DOS FAT32: нет |
Файл FAT система представляет собой особый тип компьютерной файловой системы архитектуры и семейство стандартных промышленных файловых систем , использующих его.
Файловая система FAT - это устаревшая файловая система, простая и надежная. [3] Он предлагает хорошую производительность даже в очень легких реализациях, но не может обеспечить такую же производительность, надежность и масштабируемость, как некоторые современные файловые системы. Тем не менее, он поддерживается по соображениям совместимости почти всеми разрабатываемыми в настоящее время операционными системами для персональных компьютеров и многих домашних компьютеров , мобильных устройств и встроенных систем и, таким образом, является хорошо подходящим форматом для обмена данными между компьютерами и устройствами практически любого типа и возраста. с 1981 года по настоящее время.
Первоначально разработанная в 1977 году для использования на гибких дисках , FAT вскоре была адаптирована и использовалась почти повсеместно на жестких дисках в эпоху DOS и Windows 9x в течение двух десятилетий. Сегодня файловые системы FAT все еще часто встречаются на гибких дисках, USB-накопителях , флэш- дисках и других твердотельных картах и модулях памяти , а также на многих портативных и встроенных устройствах. DCF реализует FAT в качестве стандартной файловой системы для цифровых камер с 1998 года. [4] FAT также используется для системного раздела EFI (тип раздела 0xEF ) на этапе загрузкиEFI- совместимые компьютеры.
Для гибких дисков FAT стандартизирован как ECMA- 107 [5] и ISO / IEC 9293: 1994 [6] (заменяющий ISO 9293: 1987 [7] ). Эти стандарты охватывают FAT12 и FAT16 с поддержкой только коротких файлов 8.3 ; длинные имена файлов с VFAT являются частично запатентованы . [8] Согласно патентам Google, статус «Общее пространство имен для длинных и коротких имен файлов» (US5758352A) истек в 2019 году, что может означать, что срок действия патента истек полностью. [9]
Название файловой системы происходит из-за того, что файловая система часто использует индексную таблицу, таблицу размещения файлов , статически выделяемую во время форматирования. Таблица содержит записи для каждого кластера , непрерывной области дискового хранилища. Каждая запись содержит либо номер следующего кластера в файле, либо маркер, указывающий конец файла, неиспользуемое дисковое пространство или специальные зарезервированные области диска. Корневой каталог диска содержит номер первого кластера каждого файла в каталоге; затем операционная система может просматривать таблицу FAT, ища номер кластера каждой последующей части дискового файла в виде цепочки кластеров до тех пор, пока не будет достигнут конец файла. Во многом таким же образом,подкаталоги реализованы как специальные файлы, содержащие записи каталогов соответствующих файлов.
Первоначально разработанная как 8-битная файловая система, максимальное количество кластеров было значительно увеличено по мере развития дисковых накопителей, и поэтому количество битов, используемых для идентификации каждого кластера, увеличилось. Последовательные основные версии формата FAT названы по количеству битов элемента таблицы: 12 ( FAT12 ), 16 ( FAT16 ) и 32 ( FAT32 ). За исключением исходного 8-битного предшественника FAT , каждый из этих вариантов все еще используется. Стандарт FAT также был расширен другими способами, при этом в целом сохранена обратная совместимость с существующим программным обеспечением.
Область | Размер в секторах | СОДЕРЖАНИЕ |
---|---|---|
Зарезервированные секторы | (количество зарезервированных секторов ) | Загрузочный сектор |
Информационный сектор ФС (только FAT32) | ||
Больше зарезервированных секторов (необязательно) | ||
FAT регион | (количество FAT) * (секторов на FAT) | Таблица размещения файлов №1 |
Таблица размещения файлов №2 ... (необязательно) | ||
Регион корневого каталога | (количество корневых записей * 32) / (байтов на сектор) | Корневой каталог (только FAT12 и FAT16) |
Область данных | (количество кластеров) * (секторов в кластере) | Область данных (для файлов и каталогов) ... (до конца раздела или диска) |
Файловая система FAT состоит из четырех областей:
FAT использует формат с прямым порядком байтов для всех записей в заголовке (за исключением, если это явно указано, для некоторых записей в загрузочных секторах Atari ST) и FAT (ов). [12]Можно выделить больше секторов FAT, чем необходимо для количества кластеров. Конец последнего сектора каждой копии FAT может не использоваться, если нет соответствующих кластеров. Общее количество секторов (как указано в загрузочной записи) может быть больше, чем количество секторов, используемых данными (кластеры × секторы на кластер), FAT (количество FAT × секторов на FAT), корневой каталог (n / a для FAT32) и скрытых секторов, включая загрузочный сектор: это приведет к появлению неиспользуемых секторов в конце тома. Если раздел содержит больше секторов, чем общее количество секторов, занятых файловой системой, это также приведет к появлению неиспользуемых секторов в конце раздела после тома.
На устройствах без разделов, таких как дискеты , загрузочный сектор ( VBR ) является первым сектором (логический сектор 0 с физическим адресом CHS 0/0/1 или адресом LBA 0). Для разделенных на разделы устройств, таких как жесткие диски, первый сектор является главной загрузочной записью, определяющей разделы, а первый сектор разделов, отформатированных с файловой системой FAT, снова является загрузочным сектором.
Общая структура первых 11 байтов, используемых большинством версий FAT для IBM-совместимых x86-машин, начиная с DOS 2.0:
Смещение байта | Длина (байты) | СОДЕРЖАНИЕ |
---|---|---|
0x000 | 3 | Инструкция по переходу. Если у загрузочного сектора есть действительная подпись, находящаяся в последних двух байтах загрузочного сектора (проверенная большинством загрузчиков, находящихся в системной BIOS или MBR), и этот том загружается с, предыдущий загрузчик передаст выполнение этой записи точки с определенными значениями регистров, и тогда инструкция перехода пропустит оставшуюся часть (неисполняемого) заголовка. См. Раздел Загрузочная запись тома . Начиная с DOS 2.0, допустимые загрузочные диски x86 должны начинаться либо с короткого перехода, за которым следует NOP ( последовательность opstring 0xEB 0x ?? 0x90 [13] [14], как это видно с DOS 3.0 [nb 3] - и в DOS 1.1 [15]). ] [16] ) или близкий скачок ( 0xE9 0x ?? 0x ?? [13] [14], как это видно на большинстве ( Compaq , TeleVideo ) дисков, отформатированных под DOS 2.x, а также на некоторых ( Epson , Olivetti ) DOS 3.1 диски). Для обратной совместимости MS-DOS, PC DOS и DR-DOS также принимают переход ( 0x69 0x ?? 0x ?? ) [13] [14] [17]на съемных дисках. На жестких дисках DR DOS дополнительно принимает замененную последовательность JMPS, начиная с NOP ( 0x90 0xEB 0x ?? ), [17] тогда как MS-DOS / PC DOS этого не делает. (См. Ниже совместимость с Atari ST.) Присутствие одного из этих шаблонов opstring (в сочетании с проверкой действительного значения дескриптора носителя по смещению 0x015 ) служит индикатором для DOS 3.3 и выше, что присутствует какой-то BPB (хотя точный размер не должен определяться из цели перехода, поскольку некоторые загрузочные секторы содержат данные частного загрузчика после BPB), тогда как для томов DOS 1.x (и некоторых DOS 3.0) им придется вернуться к DOS 1. x для определения формата через байт мультимедиа в FAT (в логическом секторе 1 ). |
0x003 | 8 | OEM-имя (заполнено пробелами 0x20 ). Это значение определяет, в какой системе был отформатирован диск. Хотя официально зарегистрировано как бесплатное использование OEM, MS-DOS / PC DOS (начиная с версии 3.1), Windows 95/98 / SE / ME и OS / 2 проверяют это поле, чтобы определить, на какие другие части загрузочной записи можно полагаться и как интерпретировать их. Следовательно, установка произвольных или фиктивных значений метки OEM может привести к тому, что MS-DOS, PC DOS и OS / 2 не смогут правильно распознать том и вызвать повреждение данных при записи. [18] [19] [20] Распространенными примерами являются " Некоторые поставщики хранят лицензионную информацию или ключи доступа в этой записи. Volume Tracker в Windows 95/98 / SE / ME перезапишет метку OEM Некоторые загрузчики вносят изменения или отказываются передавать управление загрузочному сектору в зависимости от определенных здесь значений (например, смещения NEWLDR 0x018 ). Загрузочное ПЗУ профессионального компьютера Wang будет рассматривать диск как загрузочный только в том случае, если первые четыре символа метки OEM - « Если в FAT32 EBPB подпись со смещением сектора 0x042 равна 0x29 и обе записи общего сектора равны 0, запись файловой системы может служить 64-битной записью общего счетчика секторов, а запись OEM-метки может использоваться как альтернативная файловая система. введите вместо обычной записи по смещению 0x052 . Аналогичным образом, если для этой записи установлено значение « |
0x00B | варьируется | Блок параметров BIOS ( 13 , 19 , 21 или 25 байтов), расширенный блок параметров BIOS (32 или 51 байт) или расширенный блок параметров BIOS FAT32 (60 или 79 байтов); размер и содержимое различаются в зависимости от операционной системы и версии, см. ниже |
варьируется | варьируется | Загрузочный код, специфичный для файловой системы и операционной системы; часто начинается сразу после [E] BPB, но иногда между концом [E] BPB и началом загрузочного кода сохраняются дополнительные «частные» данные загрузчика; поэтому переход со смещением 0x001 не может использоваться для надежного получения точного формата [E] BPB. (В сочетании как минимум с DOS 3.31 BPB некоторые загрузчики GPT (например, BootDuet ) используют 0x1FA - 0x1FD для хранения старших 4 байтов скрытых секторов для томов, расположенных за пределами первых 2 32 -1 секторов. Поскольку это место может содержать код или другие данные в других загрузочных секторах, они не могут быть записаны, если 0x1F9 - 0x1FD не все содержат ноль.) |
0x1FD | 1 | Номер физического диска (только в загрузочных секторах DOS от 3.2 до 3.31). В OS / 2 1.0 и DOS 4.0 эта запись перемещена на смещение сектора 0x024 (со смещением 0x19 в EBPB ). Большинство загрузочных секторов Microsoft и IBM с тех пор поддерживают значения 0x00 по смещению 0x1FC и 0x1FD , хотя они не являются частью подписи по адресу 0x1FE . Если он принадлежит загрузочному тому, расширенную MBR DR-DOS 7.07 можно настроить (см. Смещение NEWLDR 0x014 ) для динамического обновления этой записи до значения DL, предоставленного во время загрузки, или значения, хранящегося в таблице разделов. Это позволяет загружать альтернативные диски, даже если код VBR игнорирует значение DL. |
0x1FE | 2 | Подпись загрузочного сектора ( 0x55 0xAA ). [10] [nb 4] Эта подпись указывает на загрузочный код, совместимый с IBM PC, и проверяется большинством загрузчиков, находящихся в системном BIOS или MBR, перед передачей выполнения в загрузочный код загрузочного сектора (но, например, не исходной IBM ПЗУ-BIOS ПК [23] ). Эта подпись не указывает на конкретную файловую систему или операционную систему. Поскольку эта подпись отсутствует на всех дисках с форматом FAT (например, не на DOS 1.x [15] [16]или тома FAT, не предназначенные для загрузки x86), операционные системы не должны полагаться на наличие этой подписи при входе в тома (старые выпуски MS-DOS / PC DOS до 3.3 проверяли эту подпись, но более новые проблемы, а также DR- DOS нет). Инструменты форматирования не должны записывать эту подпись, если записанный загрузочный сектор не содержит хотя бы x86-совместимой фиктивной заглушки загрузчика; как минимум, он должен останавливать ЦП в бесконечном цикле ( 0xF4 0xEB 0xFD ) или выдавать INT 19h и RETF ( 0xCD 0x19 0xCB ). Однако эти opstrings не должны использоваться при смещении сектора 0x000 , потому что DOS проверяет другие коды операций как сигнатуры. Многие дискеты MSX-DOS 2 используют 0xEB 0xFE 0x90 при смещении сектора 0x000 чтобы поймать ЦП в замкнутом цикле, сохраняя при этом шаблон кода операции, распознаваемый MS-DOS / PC DOS. Эта подпись должна быть расположена по фиксированному смещению сектора 0x1FE для секторов размером 512 или выше. Если размер физического сектора больше, он может повторяться в конце физического сектора. ST Atari считает , что диск является загрузочным для Atari 68000, если контрольная сумма по 256 словам с прямым порядком байтов в загрузочном секторе равна 0x1234 . [24] [nb 5] Если код загрузчика совместим с IBM, важно убедиться, что контрольная сумма в загрузочном секторе не совпадает с этой контрольной суммой случайно. Если это произойдет, можно использовать изменение неиспользуемого бита (например, до или после области загрузочного кода), чтобы гарантировать, что это условие не выполняется. В редких случаях на образах дисков наблюдалась обратная подпись 0xAA 0x55 . Это может быть результатом неправильной реализации в инструменте форматирования на основе ошибочной документации [nb 4], но также может указывать на поменяемый местами порядок байтов образа диска, который мог иметь место при передаче между платформами с использованием другого порядка байтов . Значения BPB и файловые системы FAT12, FAT16 и FAT32 предназначены для использования только прямого порядка байтов, и нет известных реализаций вариантов, использующих вместо этого значения с прямым порядком байтов . |
Дискеты Atari ST в формате FAT имеют очень похожую структуру загрузочного сектора:
Смещение байта | Длина (байты) | СОДЕРЖАНИЕ |
---|---|---|
0x000 | 2 | Инструкция по переходу. Исходные загрузочные секторы Atari ST начинаются с инструкции 68000 BRA.S ( 0x60 0x ?? ). [12] Для совместимости с операционными системами ПК, диски, отформатированные в Atari ST, начиная с TOS 1.4, начинаются с 0xE9 0x ?? вместо. |
0x002 | 6 | OEM-имя (заполненное пробелами 0x20 ), например " " ( 0x4C 0x6F 0x61 0x64 0x65 0x72 ) на томах, содержащих загрузчик Atari ST. См. Меры предосторожности при использовании имен OEM для дисков, отформатированных на ПК выше. Смещение и длина этой записи отличаются от записи на дисках, отформатированных на ПК.Loader |
0x008 | 3 | Серийный номер диска [12] (по умолчанию: 0x00 0x00 0x00 ), используемый Atari ST для обнаружения смены диска. (Windows 9x Volume Tracker всегда будет хранить " " здесь на незащищенных от записи гибких дисках; см. Выше.) Это значение необходимо изменить, если содержимое диска было изменено извне, в противном случае ST Atari могут не распознать изменение при повторной вставке. Эта запись перекрывает поле OEM Name на дисках, отформатированных на ПК. Для максимальной совместимости здесь может потребоваться сопоставление определенных шаблонов; см. выше.IHC |
0x00B | 19 | Блок параметров BIOS DOS 3.0 (формат с прямым порядком байтов ) |
0x01E | варьируется | Данные частного загрузочного сектора (смешанный формат с прямым порядком байтов и прямым порядком байтов ) |
варьируется | варьируется | Загрузочный код Atari ST, специфичный для файловой и операционной системы. Не следует делать никаких предположений относительно позиции загрузки кода, которая должна быть перемещаемой. При загрузке операционной системы (TOS.IMG [12] ) терпит неудачу, код может вернуться к Atari ST BIOS с 68000 RTS ( коды операции 0x4E75 с большой обратным порядком байт последовательности байт 0x4e 0x75 [нб 4] ) инструкции и все регистры неизмененными. |
0x1FE | 2 | Контрольная сумма. 16-битная контрольная сумма за 256 тупоконечника слов 512 байт загрузочного сектора , включая это слово должно соответствовать значение магического 0x1234 для того , чтобы указать код сектора 68000 исполняемый загрузочный Atari ST. [24] Эта запись контрольной суммы может использоваться для соответствующего выравнивания контрольной суммы. [№ 5] Если размер логического сектора превышает 512 байт, остаток не включается в контрольную сумму и обычно заполняется нулями. [24] Поскольку некоторые операционные системы ПК ошибочно не принимают дискеты в формате FAT, если здесь нет сигнатуры 0x55 0xAA [nb 4] , рекомендуется поместить на это место 0x55 0xAA (и добавить IBM-совместимый загрузчик или заглушку ) и используйте неиспользуемое слово в личных данных, в области загрузочного кода или в серийном номере, чтобы гарантировать, что контрольная сумма 0x1234 [nb 5] не совпадает (если только общий оверлей жирного кода не будет одновременно исполняемым файлом IBM PC и Atari ST в то же время). |
Тома MSX-DOS в формате FAT12 имеют очень похожую структуру загрузочного сектора:
Смещение байта | Длина (байты) | СОДЕРЖАНИЕ |
---|---|---|
0x000 | 3 | Фиктивная инструкция перехода (например, 0xEB 0xFE 0x90 ). |
0x003 | 8 | OEM-имя (заполнено пробелами 0x20 ). |
0x00B | 19 | DOS 3.0 BPB |
0x01E | варьируется (2) | Точка входа кода MSX-DOS 1 для процессоров Z80 в загрузочный код MSX. Это то место, куда машины MSX-DOS 1 переходят при передаче управления загрузочному сектору. Это расположение пересекается с форматами BPB, начиная с DOS 3.2, или с кодом загрузочного сектора, совместимым с x86, для загрузочных секторов, совместимых с IBM PC, и приведет к сбою на компьютере MSX, если не будут приняты особые меры предосторожности, такие как замыкание ЦП здесь (opstring 0x18 0xFE для JR 0x01E ). |
0x020 | 6 | Подпись тома MSX-DOS 2 " VOL_ID ". |
0x026 | 1 | Флаг восстановления MSX-DOS 2 (по умолчанию: 0x00 . Если подпись " " присутствует со смещением сектора 0x020 , этот флаг указывает, содержит ли том удаленные файлы, которые можно восстановить (см. Смещение 0x0C в записях каталога).VOL_ID |
0x027 | 4 | Серийный номер диска MSX-DOS 2 (по умолчанию: 0x00000000 ). Если подпись присутствует при смещении сектора 0x020 , MSX-DOS 2 сохраняет здесь серийный номер тома для обнаружения смены носителя.VOL_ID |
0x02B | 5 | зарезервированный |
0x030 | варьируется (2) | Точка входа кода MSX-DOS 2 для процессоров Z80 в загрузочный код MSX. Это то место, куда машины MSX-DOS 2 переходят при передаче управления загрузочному сектору. Это расположение перекрывается с форматами EBPB, начиная с DOS 4.0 / OS / 2 1.2, или с кодом загрузочного сектора, совместимым с x86, для загрузочных секторов, совместимых с IBM PC, и приведет к сбою на компьютере MSX, если не будут приняты особые меры предосторожности, такие как застревание процессора в здесь жесткий цикл (opstring 0x18 0xFE для JR 0x030 ). |
0x1FE | 2 | Подпись |
Общая структура первых 25 байтов блока параметров BIOS (BPB), используемых версиями FAT, начиная с DOS 2.0 (байты со смещением сектора от 0x00B до 0x017 сохраняются с DOS 2.0, но не всегда используются до DOS 3.2, значения от 0x018 до 0x01B являются используется с DOS 3.0):
Смещение сектора | Смещение BPB | Длина (байты) | СОДЕРЖАНИЕ |
---|---|---|---|
0x00B | 0x00 | 2 | Байт на логический сектор в степени двойки; наиболее распространенное значение - 512. Некоторые операционные системы не поддерживают секторы других размеров. Для простоты и максимальной производительности размер логического сектора часто идентичен размеру физического сектора диска, но в некоторых сценариях может быть больше или меньше. Минимально допустимое значение для незагрузочных томов FAT12 / FAT16, содержащих до 65535 логических секторов, составляет 32 байта или 64 байта для более чем 65535 логических секторов. Минимальное практическое значение - 128. Некоторые OEM-версии DOS до DOS 3.31 использовали размер логических секторов до 8192 байтов для логических секторных файлов FAT . Atari ST GEMDOS поддерживает размеры логических секторов от 512 до 4096. [24] DR-DOS поддерживает загрузку с томов FAT12 / FAT16 с размером логических секторов до 32 КБ, а реализации INT 13h поддерживают физические сектора размером до 1024 байт / сектор. [nb 6] Минимальный размер логического сектора для стандартных томов FAT32 составляет 512 байт, который может быть уменьшен до 128 байт без поддержки информационного сектора FS . Дисководы и контроллеры используют физические сектора размером 128, 256, 512 и 1024 байта (например, PC / AX). Портфель Атари поддерживает размер сектора 512 томов размером более 64 Кбайт, 256 байт для томов больше 32 Кбайт и 128 байт для небольших объемов. Магнитооптические приводы использовали размеры секторов 512, 1024 и 2048 байтов. В 2005 году на некоторых пользовательских жестких дисках Seagate использовались сектора размером 1024 байта вместо 512 байтов по умолчанию. [25] Жесткие диски Advanced Format с 2010 года используют 4096 байт на сектор ( 4Kn ), но также смогут имитировать 512-байтовые сектора ( 512e ) в течение переходного периода. Linux и, соответственно, Android, поддерживают размер логического сектора намного больше, официально задокументированный на странице Man для утилит файловой системы, как до 32 КБ. |
0x00D | 0x02 | 1 | Логических секторов на кластер. Допустимые значения: 1, 2, 4, 8, 16, 32, 64 и 128. Некоторые версии MS-DOS 3.x поддерживали максимальный размер кластера только 4 КБ, тогда как современные MS-DOS / PC DOS и Windows 95 поддерживают максимальный размер кластера 32 КБ. Windows 98 / SE / ME также частично поддерживает кластер размером 64 КБ, но некоторые службы FCB недоступны на таких дисках, и различные приложения не работают. Семейство Windows NT и некоторые альтернативные версии DOS, такие как PTS-DOS, полностью поддерживают кластеры размером 64 КБ. Для большинства операционных систем на основе DOS максимальный размер кластера остается равным 32 КБ (или 64 КБ) даже для секторов размером более 512 байт. Для логических секторов размером 1 КБ, 2 КБ и 4 КБ Windows NT 4.0 поддерживает размер кластера 128 КБ, в то время как для секторов 2 КБ и 4 КБ размер кластера может достигать 256 КБ. Некоторые версии DR-DOS обеспечивают ограниченную поддержку кластеров 128 КБ с 512 байтами / сектором с использованием значения секторов / кластера 0. MS-DOS / PC DOS будет зависать при запуске, если это значение ошибочно указано как 0. [26] : INT 21h AX = 53h |
0x00E | 0x03 | 2 | Количество зарезервированных логических секторов . Количество логических секторов перед первой FAT в образе файловой системы. По крайней мере, 1 для этого сектора, обычно 32 для FAT32 (для хранения расширенного загрузочного сектора, информационного сектора FS и резервных загрузочных секторов). Поскольку тома, отформатированные в DR-DOS 7.0x FAT32, используют односекторный загрузочный сектор, информационный сектор FS и резервный сектор, некоторые тома, отформатированные под DR-DOS, используют здесь значение 4. |
0x010 | 0x05 | 1 | Количество таблиц размещения файлов. Почти всегда 2; RAM-диски могут использовать 1. Большинство версий MS-DOS / PC DOS не поддерживают более двух файловых систем. Некоторые операционные системы DOS поддерживают только две FAT во встроенном драйвере диска, но поддерживают другие подсчеты FAT для драйверов блочных устройств, загружаемых позже. Тома, объявляющие 2 FAT в этой записи, никогда не будут рассматриваться как тома TFAT . Если значение отличается от 2, некоторые операционные системы Microsoft могут попытаться смонтировать том как том TFAT и использовать второй кластер ( кластер 1 ) первой FAT для определения статуса TFAT. |
0x011 | 0x06 | 2 | Максимальное количество записей корневого каталога FAT12 или FAT16. 0 для FAT32, где корневой каталог хранится в обычных кластерах данных; см. смещение 0x02C в EBPB FAT32. Значение 0 без FAT32 EBPB (без подписи 0x29 или 0x28 по смещению 0x042 ) также может указывать на корневой каталог переменного размера в некоторых нестандартных реализациях FAT12 и FAT16, которые хранят начальный кластер корневого каталога в записи кластера 1 в жир. [27] Это расширение, однако, не поддерживается основными операционными системами, [27] поскольку оно может конфликтовать с другими видами использования записи кластера 1 для флагов обслуживания, текущего маркера конца цепочки или расширений TFAT . Это значение необходимо настроить так, чтобы записи каталога всегда занимали полные логические секторы, учитывая, что каждая запись каталога занимает 32 байта. MS-DOS / PC DOS требует, чтобы это значение было кратным 16. Максимальное значение, поддерживаемое на гибких дисках, - 240, [13] максимальное значение, поддерживаемое MS-DOS / PC DOS на жестких дисках, - 512. [13] DR -DOS поддерживает загрузку с томов FAT12 / FAT16, если загрузочный файл находится в первых 2048 записях корневого каталога. |
0x013 | 0x08 | 2 | Всего логических секторов. 0 для FAT32. (Если ноль, используйте 4-байтовое значение по смещению 0x020 ) |
0x015 | 0x0A | 1 | Дескриптор мультимедиа (сравните: FAT ID ): [28] [29] [30] [nb 3]
Это значение должно отражать дескриптор носителя, хранящийся (в записи для кластера 0 ) в первом байте каждой копии FAT. Некоторые операционные системы до DOS 3.2 ( 86-DOS , MS-DOS / PC DOS 1.x и MSX-DOS версии 1.0) полностью игнорируют параметры загрузочного сектора и используют значение дескриптора носителя из первого байта FAT для внутреннего выбора. предварительно определенные шаблоны параметров. Должен быть больше или равен 0xF0, начиная с DOS 4.0. [13] На съемных дисках DR-DOS предполагает наличие BPB, если это значение больше или равно 0xF0 , [13] тогда как для фиксированных дисков оно должно быть 0xF8, чтобы предполагать наличие BPB. Первоначально эти значения предназначались для использования в качестве битовых флагов; для любых съемных носителей без распознанного формата BPB и дескриптора носителя от 0xF8 или от 0xFA до 0xFF MS-DOS / PC DOS обрабатывает бит 1 как флаг для выбора формата с 9 секторами на дорожку, а не с форматом с 8 секторами, и бит 0 как флаг для обозначения двустороннего носителя. [14] Значения от 0x00 до 0xEF и от 0xF1 до 0xF7 зарезервированы и не должны использоваться. |
0x016 | 0x0B | 2 | Логические секторы в таблице размещения файлов для FAT12 / FAT16. FAT32 устанавливает это значение в 0 и вместо этого использует 32-битное значение со смещением 0x024 . |
DOS 3.0 BPB:
Следующие расширения были задокументированы, начиная с DOS 3.0, однако они уже поддерживались некоторыми выпусками DOS 2.11. [32] MS-DOS 3.10 по-прежнему поддерживает формат DOS 2.0, но может также использовать формат DOS 3.0.
Смещение сектора | Смещение BPB | Длина (байты) | СОДЕРЖАНИЕ |
---|---|---|---|
0x00B | 0x00 | 13 | DOS 2.0 BPB |
0x018 | 0x0D | 2 | Физических секторов на дорожку для дисков с геометрией INT 13h CHS, [10] например, 15 для дискеты «1,20 МБ» (1200 КБ). Нулевой элемент указывает, что этот элемент зарезервирован, но не используется. |
0x01A | 0x0F | 2 | Количество головок для дисков с геометрией INT 13h CHS, [10] например, 2 для двусторонней дискеты. Ошибка во всех версиях MS-DOS / PC DOS до 7.10 приводит к сбою этих операционных систем для геометрии CHS с 256 головками, поэтому почти все BIOS выбирают максимум 255 головок. Нулевой элемент указывает, что этот элемент зарезервирован, но не используется. |
0x01C | 0x11 | 2 | Количество скрытых секторов, предшествующих разделу, содержащему этот том FAT. Это поле всегда должно быть нулевым на носителях, которые не разбиты на разделы. Эта запись DOS 3.0 несовместима с аналогичной записью по смещению 0x01C в BPB, начиная с DOS 3.31. Его нельзя использовать, если запись логических секторов по смещению 0x013 равна нулю. |
DOS 3.2 BPB:
Официально MS-DOS 3.20 еще используется формат DOS 3.0, но SYS
и FORMAT
были приспособлены для поддержки 6 байт длиннее формат уже (из которых были использованы не все записи).
Смещение сектора | Смещение BPB | Длина (байты) | СОДЕРЖАНИЕ |
---|---|---|---|
0x00B | 0x00 | 19 | DOS 3.0 BPB |
0x01E | 0x13 | 2 | Всего логических секторов, включая скрытые. Эта запись DOS 3.2 несовместима с аналогичной записью по смещению 0x020 в BPB, начиная с DOS 3.31. Его нельзя использовать, если запись логических секторов по смещению 0x013 равна нулю. |
DOS 3.31 BPB:
Официально представленные в DOS 3.31 и не используемые в DOS 3.2, некоторые утилиты DOS 3.2 были разработаны с учетом этого нового формата. Официальная документация рекомендует доверять этим значениям только в том случае, если запись логических секторов по смещению 0x013 равна нулю.
Смещение сектора | Смещение BPB | Длина (байты) | СОДЕРЖАНИЕ |
---|---|---|---|
0x00B | 0x00 | 13 | DOS 2.0 BPB |
0x018 | 0x0D | 2 | Физических секторов на дорожку для дисков с геометрией INT 13h CHS, [10] например, 18 для дискеты «1,44 МБ» (1440 КБ). Не используется для дисков, которые больше не поддерживают доступ по CHS. Идентично записи, доступной с DOS 3.0 . Нулевой элемент указывает, что этот элемент зарезервирован, но не используется. Значение 0 может указывать на доступ только LBA, но может вызывать исключение деления на ноль в некоторых загрузчиках, чего можно избежать, сохранив здесь нейтральное значение 1, если никакая геометрия CHS не может быть разумно эмулирована. |
0x01A | 0x0F | 2 | Количество головок для дисков с геометрией INT 13h CHS, [10] например, 2 для двусторонней дискеты. Не используется для дисков, которые больше не поддерживают доступ по протоколу CHS. Идентично записи, доступной с DOS 3.0 . Ошибка во всех версиях MS-DOS / PC DOS до 7.10 приводит к сбою этих операционных систем для геометрии CHS с 256 головками, поэтому почти все BIOS выбирают максимум 255 головок. Нулевой элемент указывает, что этот элемент зарезервирован, но не используется. Значение 0 может указывать на доступ только LBA, но может вызывать исключение деления на ноль в некоторых загрузчиках, чего можно избежать, сохранив здесь нейтральное значение 1, если никакая геометрия CHS не может быть разумно эмулирована. |
0x01C | 0x11 | 4 | Количество скрытых секторов, предшествующих разделу, содержащему этот том FAT. Это поле всегда должно быть нулевым на носителях, которые не разделены на разделы. [5] [6] [7] Эта запись DOS 3.31 несовместима с аналогичной записью по смещению 0x01C в BPB DOS 3.0–3.3. По крайней мере, ему можно доверять, если он содержит ноль или если запись логических секторов по смещению 0x013 равна нулю. Если это относится к расширенному активному разделу (AAP), выбранному во время загрузки, запись BPB будет динамически обновляться расширенной MBR, чтобы отразить значение «относительных секторов» в таблице разделов, сохраненное по смещению 0x1B6 в AAP или NEWLDR MBR. , чтобы появилась возможность загружать операционную систему с EBR . (Некоторые загрузчики GPT (например, BootDuet ) используют смещения загрузочного сектора 0x1FA - 0x1FD для хранения старших 4 байтов значения 64-битных скрытых секторов для томов, расположенных за пределами первых 2 32 -1 секторов.) |
0x020 | 0x15 | 4 | Всего логических секторов (если больше 65535; в противном случае см. Смещение 0x013 ). Эта запись DOS 3.31 несовместима с аналогичной записью по смещению 0x01E в DOS 3.2–3.3 BPB. Официально его следует использовать только в том случае, если запись логических секторов по смещению 0x013 равна нулю, но некоторые операционные системы (некоторые старые версии DR DOS) используют эту запись также для дисков меньшего размера. Для многораздельных носителей, если это и запись в 0x013 оба равны 0 (как видно на некоторых томах DOS 3.x FAT16), многие операционные системы (включая MS-DOS / PC DOS) будут извлекать значение из записи соответствующего раздела (в смещение 0xC ) в MBR . Если обе эти записи равны 0 на томах, использующих FAT32 EBPB с подписью 0x29 , значения, превышающие предел 4 294 967 295 (2 32 -1) (например, некоторые тома DR-DOS с 32-разрядными записями кластера) могут использовать 64-разрядную запись в смещение 0x052 вместо этого. |
Простая формула переводит заданный номер кластера тома CN
в логический номер сектора LSN
: [5] [6] [7]
SSA=RSC+FN×SF+ceil((32×RDE)/SS)
RSC
FN
SF
RDE
SS
ceil(x)
LSN=SSA+(CN−2)×SC
SC
На неразмеченных СМИ номер тома скрытых секторов равно нуль , и , следовательно , LSN
и LBA
адреса становятся такими же , так долго , как размер логического сектора тома идентичен размером физического сектора подстилающего медиума. В этих условиях также легко переводить между CHS
адресами, LSNs
а также:
LSN=SPT×(HN+(NOS×TN))+SN−1
, где секторы на дорожку SPT
хранятся со смещением 0x018 , а количество сторон - со смещением 0x01A . Номер дорожки, номер головки и номер сектора соответствуют сектору головки цилиндра : формула дает известное преобразование CHS в LBA .NOS
TN
HN
SN
Дополнительная структура, используемая FAT12 и FAT16 начиная с OS / 2 1.0 и DOS 4.0, также известная как расширенный блок параметров BIOS (EBPB) (байты ниже смещения сектора 0x024 такие же, как для DOS 3.31 BPB):
Смещение сектора | EBPB смещение | Длина (байты) | СОДЕРЖАНИЕ |
---|---|---|---|
0x00B | 0x00 | 25 | DOS 3.31 BPB |
0x024 | 0x19 | 1 | Номер физического диска ( 0x00 для (первого) съемного носителя, 0x80 для (первого) фиксированного диска согласно INT 13h ). Допустимые значения для возможных физических дисков в зависимости от BIOS: 0x00 - 0x7E и 0x80 - 0xFE . Значения 0x7F и 0xFF зарезервированы для внутренних целей, таких как удаленная загрузка или загрузка из ПЗУ, и никогда не должны появляться на диске. Некоторые загрузчики , такие как загрузки MS-DOS / PC DOS загрузчика использовать это значение при загрузке операционной системы, другие игнорируют его вообще или использовать номер диска , представленный в регистре DL с помощью базового загрузчика(например, со многими BIOS и MBR). Запись иногда изменяется инструментами SYS или может быть динамически исправлена предыдущим загрузчиком начальной загрузки, чтобы заставить код загрузочного сектора загружать операционную систему с физических дисков, альтернативных по умолчанию. Аналогичная запись существовала (только) в загрузочных секторах DOS 3.2–3.31 со смещением сектора 0x1FD . Если он принадлежит загрузочному тому, расширенную MBR DR-DOS 7.07 можно настроить (см. Смещение NEWLDR 0x014 ) для динамического обновления этой записи EBPB до значения DL, предоставленного во время загрузки, или значения, хранящегося в таблице разделов. Это позволяет загружать альтернативные диски, даже если код VBR игнорирует значение DL. |
0x025 | 0x1A | 1 | Зарезервированный;
|
0x026 | 0x1B | 1 | Расширенная загрузочная подпись. (Должно быть 0x29 [5] [6] [7] [28], чтобы указать, что EBPB со следующими 3 записями существует (начиная с OS / 2 1.2 и DOS 4.0). Может быть 0x28 в некоторых OS / 2 1.0-1.1 и Диски PC DOS 3.4, указывающие на более раннюю форму формата EBPB с только последующим серийным номером. MS-DOS / PC DOS 4.0 и выше, OS / 2 1.2 и выше, а также семейство Windows NT распознают обе сигнатуры соответственно.) |
0x027 | 0x1C | 4 | ID тома (серийный номер) Обычно серийный номер «xxxx-xxxx» создается путем 16-битного сложения обоих значений DX, возвращаемых INT 21h / AH = 2Ah (получить системную дату) [nb 7] и INT 21h / AH = 2Ch (получить системное время). [nb 7] для старшего слова и еще одно 16-битное сложение обоих значений CX для младшего слова серийного номера. В качестве альтернативы, некоторые дисковые утилиты DR-DOS предоставляют |
0x02B | 0x20 | 11 | Метка тома раздела, заполненная пробелами ( 0x20 ), например, « » Программное обеспечение, изменяющее метку тома каталога в файловой системе, также должно обновлять эту запись, но не все программное обеспечение это делает. Метка тома раздела обычно отображается в инструментах создания разделов, поскольку она доступна без монтирования тома. Поддерживается с OS / 2 1.2 и MS-DOS 4.0 и выше.NO␠NAME␠␠␠␠ Недоступно, если для сигнатуры 0x026 установлено значение 0x28 . Эта область использовалась загрузочными секторами DOS 3.2–3.3 для хранения частной копии таблицы параметров диска (DPT) вместо использования указателя INT 1Eh для получения таблицы ROM, как в более поздних выпусках загрузочного сектора. Повторное использование этого места для в основном косметической метки тома раздела сводило к минимуму проблемы, если некоторые старые системные утилиты все еще пытались исправить прежний DPT. |
0x036 | 0x2B | 8 | Тип файловой системы, заполненный пробелами ( 0x20 ), например, " ", " ", " "FAT12␠␠␠ FAT16␠␠␠ FAT␠␠␠␠␠ Эта запись предназначена только для отображения и не должна использоваться операционной системой для определения типа файловой системы. Тем не менее, он иногда используется для целей идентификации сторонним программным обеспечением, поэтому значения не должны отличаться от официально используемых. Поддерживается с OS / 2 1.2 и MS-DOS 4.0 и выше. Недоступно, если для сигнатуры 0x026 установлено значение 0x28 . |
По сути, FAT32 вставляет 28 байтов в EBPB, за которыми следуют оставшиеся 26 (а иногда только 7) байтов EBPB, как показано выше для FAT12 и FAT16. Операционные системы Microsoft и IBM определяют тип файловой системы FAT, используемой на томе, исключительно по количеству кластеров, а не по используемому формату BPB или указанному типу файловой системы, то есть технически возможно использовать «FAT32 EBPB» также для томов FAT12 и FAT16, а также EBPB DOS 4.0 для небольших томов FAT32. Поскольку было обнаружено, что такие тома создаются операционными системами Windows при некоторых странных условиях, операционные системы [nb 8] должны быть готовы к работе с этими гибридными формами.
Смещение сектора | FAT32 EBPB смещение | Длина (байты) | СОДЕРЖАНИЕ |
---|---|---|---|
0x00B | 0x00 | 25 | DOS 3.31 BPB |
0x024 | 0x19 | 4 | Логических секторов в таблице размещения файлов (соответствует старой записи по смещению 0x0B в DOS 2.0 BPB ). Байт со смещением 0x026 в этой записи никогда не должен становиться 0x28 или 0x29 , чтобы избежать неправильной интерпретации формата EBPB в операционных системах, не поддерживающих FAT32. К счастью, в обычных условиях (размер сектора 512 байт) этого не может произойти, поскольку файловая система FAT32 имеет не более 0xffffff6 = 268435446 кластеров. Один Fat-сектор соответствует 512/4 = 128 дескрипторам кластера. Таким образом, потребуется не более чем ceil (268435446/128) = 2097152 = 0x200000 секторов, что сделает третий байт числа секторов FAT не более 0x20, что меньше запрещенных значений 0x28 и 0x29. |
0x028 | 0x1D | 2 | Описание накопителя / флаги зеркалирования (биты 3-0: отсчитываемое от нуля количество активной FAT, если установлен бит 7. [10] Если бит 7 очищен, все FAT зеркалируются как обычно. Остальные биты зарезервированы и должны быть равны 0.) Загрузочные секторы DR-DOS 7.07 FAT32 с двойной поддержкой LBA и CHS используют биты 15-8 для хранения флага доступа и части сообщения. Эти биты содержат либо комбинацию битов 0110: 1111b ( строчная буква «o», бит 13 установлен для доступа CHS) или 0100: 1111b ( заглавная буква «O», бит 13 очищен для доступа к LBA). Байт также используется для второго символа в потенциальном сообщении об ошибке «No␠IBMBIO␠␠COM» (см. Смещение 0x034 ), отображаемом либо в смешанном, либо в верхнем регистре, тем самым указывая, какой тип доступа потерпел неудачу). Инструменты форматирования или инструменты, не относящиеся к типу DR SYS, могут очищать эти биты, но другие инструменты для работы с дисками должны оставлять биты 15-8 без изменений. |
0x02A | 0x1F | 2 | Версия (определена как 0.0). Старший байт номера версии сохраняется по смещению 0x02B , а младший байт - по смещению 0x02A . [10] Реализации FAT32 должны отказываться от монтирования томов с неизвестными им номерами версий. |
0x02C | 0x21 | 4 | Номер кластера начала корневого каталога, обычно 2 (первый кластер [37] ), если он не содержит плохих секторов. (Реализация Microsoft FAT32 налагает искусственное ограничение в 65 535 записей на каталог, в то время как многие сторонние реализации этого не делают.) Значение кластера 0 официально не разрешено и никогда не может указывать на допустимый начальный кластер корневого каталога. Некоторые нестандартные реализации FAT32 могут рассматривать это как индикатор для поиска корневого каталога фиксированного размера там, где это ожидается на томах FAT16; см. смещение 0x011 . |
0x030 | 0x25 | 2 | Номер логического сектора информационного сектора FS , обычно 1, т. Е. Второй из трех загрузочных секторов FAT32. Некоторые реализации FAT32 поддерживают небольшую вариацию спецификации Microsoft, в которой информационный сектор FS становится необязательным путем указания в этой записи значения 0xFFFF [26] (или 0x0000 ). Поскольку логический сектор 0 никогда не может быть действительным информационным сектором FS, но информационные секторы FS используют ту же сигнатуру, что и во многих загрузочных секторах [ необходима ссылка ] , реализации файловой системы никогда не должны пытаться использовать логический сектор 0 в качестве информационного сектора FS и вместо этого предполагать что эта функция не поддерживается на этом конкретном томе. Без информационного сектора FS минимально допустимый размер логического сектора томов FAT32 может быть уменьшен до 128 байтов для специальных целей. |
0x032 | 0x27 | 2 | Номер первого логического сектора копии трех загрузочных секторов FAT32, обычно 6. [10] Поскольку тома в формате DR-DOS 7.0x FAT32 используют односекторный загрузочный сектор, некоторые тома, отформатированные под DR-DOS, используют здесь значение 2. Значения 0x0000 [10] (и / или 0xFFFF [26] ) зарезервированы и показывают, что резервный сектор недоступен. |
0x034 | 0x29 | 12 | Зарезервировано (может быть изменен MS-DOS на байт-заполнитель формата 0xF6 [nb 2] как артефакт , должен быть инициализирован на 0 с помощью инструментов форматирования, но не должен быть изменен реализациями файловой системы или дисковыми инструментами позже).FDISK Загрузочные секторы DR-DOS 7.07 FAT32 используют эти 12 байтов для хранения имени файла " |
0x040 | 0x35 | 1 | Ср. 0x024 для FAT12 / FAT16 (номер физического диска) BPB exFAT расположены по смещению сектора от 0x040 до 0x077 , перекрывая все остальные записи стандартного EBPB FAT32, включая этот. Их можно обнаружить по их подписи OEM-метки " " по смещению сектора 0x003 . В этом случае байты от 0x00B до 0x03F обычно устанавливаются в 0x00 . |
0x041 | 0x36 | 1 | Ср. 0x025 для FAT12 / FAT16 (используется для различных целей; см. FAT12 / FAT16) Может содержать артефакты байта заполнителя формата 0xF6 [nb 2] после разделения с помощью MS-DOS FDISK, но еще не отформатирован. |
0x042 | 0x37 | 1 | Ср. 0x026 для FAT12 / FAT16 (расширенная подпись загрузки, 0x29 ) Большинство реализаций файловой системы FAT32 не поддерживают альтернативную сигнатуру 0x28 [22] для обозначения сокращенной формы FAT32 EBPB только с последующим серийным номером (без записей типа тома и типа файловой системы), но поскольку эти 19 в основном неиспользуемых байтов может служить различным целям в некоторых сценариях, реализации должны принять 0x28 в качестве альтернативной сигнатуры, а затем вернуться к использованию метки тома каталога в файловой системе вместо EBPB для совместимости с потенциальными расширениями. |
0x043 | 0x38 | 4 | Ср. 0x027 для FAT12 / FAT16 (идентификатор тома) |
0x047 | 0x3C | 11 | Ср. 0x02B для FAT12 / FAT16 (метка тома) Недоступно, если для сигнатуры по смещению 0x042 установлено значение 0x28 . |
0x052 | 0x47 | 8 | Ср. 0x036 для FAT12 / FAT16 (Тип файловой системы, заполненный пробелами ( 0x20 ), например, " ").FAT32␠␠␠ Недоступно, если для сигнатуры 0x042 установлено значение 0x28 . Если обе общие записи логических секторов по смещению 0x020 и 0x013 равны 0 на томах, использующих FAT32 EBPB с подписью 0x29 , тома с более чем 4294967295 (2 32 -1) секторов (например, некоторые тома DR-DOS с 32-битными записями кластера) могут вместо этого используйте эту запись как запись общего количества 64-битных логических секторов . В этом случае метка OEM со смещением сектора 0x003 может быть получена как тип файловой системы нового стиля . |
Версии DOS до 3.2 полностью или частично полагались на байт дескриптора носителя в BPB или байт идентификатора FAT в кластере 0 первой FAT для определения форматов дискет FAT12, даже если присутствует BPB. В зависимости от найденного FAT ID и обнаруженного типа диска они по умолчанию используют один из следующих прототипов BPB вместо значений, фактически хранящихся в BPB. [№ 3]
Первоначально FAT ID должен был быть битовым флагом со всеми установленными битами, за исключением бита 2, очищенного для указания формата 80 дорожек (против 40 дорожек), бит 1 очищен, чтобы указать формат 9 секторов (против 8 секторов), и бит 0 очищен для обозначения одностороннего (по сравнению с двусторонним) формата [14], но эта схема не соблюдалась всеми OEM-производителями и устарела с появлением жестких дисков и форматов высокой плотности. Кроме того, различные 8-дюймовые форматы, поддерживаемые 86-DOS и MS-DOS, не подходят для этой схемы.
FAT ID (сравните с ID носителя при смещении BPB 0x0A ) [29] [30] | 0xFF | 0xFE | 0xFD | 0xFC | 0xFB | 0xFA | 0xF9 | 0xF8 | 0xF0 | 0xED | 0xE5 | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Размер | 8 " | 5,25 " | 8 " | 8 " | 5,25 " | 8 " | 8 " | 5,25 " | 5,25 " | 5,25 дюйма / 3,5 дюйма | 5,25 дюйма / 3,5 дюйма | 5,25 " | 3,5 дюйма | 3,5 дюйма | 5,25 " | 5,25 дюйма / 3,5 дюйма | 3,5 дюйма | 3,5 дюйма | 3,5 дюйма | 5,25 " | 8 " |
Плотность | ? | DD 48tpi | SD | DD | DD 48tpi | SD | SD | DD 48tpi | DD 48tpi | ? | ? | HD 96 точек на дюйм | DD 135tpi | HD 135 точек на дюйм | QD 96tpi | ? | DD | HD 135 точек на дюйм | ED | QD 96tpi | SD |
Модуляция | ? | MFM | FM | MFM | MFM | FM | FM | MFM | MFM | MFM | MFM | MFM | MFM | MFM | MFM | MFM | MFM | MFM | MFM | MFM | FM |
Форматированная емкость (КБ) | ? | 320 | 250 («старый») [32] [36] | 1200 | 160 | 250 («новый») [32] [36] | 500 | 360 | 180 | 640 | 320 | 1200 | 720 | 1440 | 720 | 360 | 360 | 1440 | 2880 | 720 | 243/250 |
Цилиндры (CHS) | 77 | 40 | 77 | 77 | 40 | 77 | 77 | 40 | 40 | 80 | 80 | 80 | 80 | 80 | 80 | 80 | 80 | 80 | 80 | 80 | 77 |
Физические секторы / дорожка (смещение BPB 0x0D ) | ? | 8 | 26 год | 8 | 8 | 26 год | 26 год | 9 | 9 | 8 | 8 | 15 | 9 | 18 | 9 (8 [35] ) | 9 | 9 | 18 | 36 | 9 (8 [35] ) | 26 год |
Количество головок (смещение BPB 0x0F ) | ? | 2 | 1 [32] [36] | 2 [14] [29] [36] (1) | 1 | 1 [14] [32] [36] | 2 [29] | 2 | 1 | 2 | 1 | 2 | 2 | 2 | 2 | 1 | 1 | 2 | 2 | 2 | 1 |
Байт полезной нагрузки / физический сектор | ? | 512 | 128 | 1024 | 512 | 128 | 128 | 512 | 512 | 512 | 512 | 512 | 512 | 512 | 512 | 512 | 512 | 512 | 512 | 512 | 128 |
Байт / логический сектор (смещение BPB 0x00 ) | ? | 512 | 128 | 1024 | 512 | 128 | 128 | 512 | 512 | 512 | 512 | 512 | 512 | 512 | 512 | 512 | 512 | 512 | 512 | 512 | 128 |
Логические секторы / кластер (смещение BPB 0x02 ) | ? | 2 | 4 | 1 | 1 | 4 | 4 | 2 | 1 | 2 | 1 [29] (2? [14] ) | 1 | 2 | 1 | ? | 2 | ? | 1 | 2 | ? | 4 |
Зарезервированные логические секторы (смещение BPB 0x03 ) | ? | 1 | 1 [32] [36] | 1 | 1 | 4 [32] [36] | 4 | 1 | 1 | 1 | 1 | 1 | 1 (2) | 1 | 1 | 1 | 1 | 1 | 1 | ? | 1 |
Количество файлов FAT (смещение BPB 0x05 ) | ? | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 |
Записи корневого каталога (смещение BPB 0x06 ) | ? | 112 (7 секторов) | 68 (17 секторов) | 192 (6 секторов) | 64 (4 сектора) | 68 (17 секторов) | 68 (17 секторов) | 112 (7 секторов) | 64 (4 сектора) | 112 (7 секторов) | 112 (7 секторов) | 224 (14 секторов) | 112 (7 секторов) | 224 (14 секторов) | ? | 112 (7 секторов) | ? | 224 (14 секторов) | 240 (15 секторов) | ? | 64 (16 секторов) |
Всего логических секторов (смещение BPB 0x08 ) | ? | 640 | 2002 [32] [36] | 1232 [29] [36] (616 [14] ) | 320 | 2002 [14] [32] [36] | 4004 [29] | 720 | 360 | 1280 | 640 | 2400 | 1440 | 2880 | ? | 720 | ? | 2880 | 5760 | ? | 2002 г. |
Логические секторы / FAT (смещение BPB 0x0B ) | ? | 1 | 6 [32] [36] | 2 | 1 | 6 [32] [36] | 6? [29] | 2 | 2 | 2 | 2 [29] (1? [14] ) | 7 | 3 | 9 (7) | ? | 2 | ? | 9 | 9 | ? | 1 |
Скрытые секторы (смещение BPB 0x11 ) | ? | 0 | 3 [29] (0 [14] ) | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ? | 0 |
Общее количество кластеров | ? | 315 | 497 | 1227 | 313 | ? | 997? [29] | 354 | 351 | ? | ? | 2371 | 713 | 2847? | ? | ? | ? | 2847 | 2863 | ? | ? |
Логический порядок секторов | ? | ? | ? | ? | ? | ? | ? | ? | ? | ? | ? | ? | ? | ? | ? | ? | ? | ? | ? | ? | ? |
Отображение секторов | ? | ? | ? | ||||||||||||||||||
Первый физический сектор (CHS) | ? | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | ? | ? | 1 | 1 | 1 | ? | 1 | ? | 1 | 1 | ? | 1 |
DRIVER.SYS /F:n | ? | 0 | 3 | 4 | 0 | ? | 3 | 0 | 0 | ? | ? | 1 | 2 | 7 | ? | ? | ? | 7 | 9 | ? | 3 |
Наличие BPB | ? | ? | ? | ? | ? | ? | ? | ? | ? | ? | ? | да | да | да | ? | ? | ? | да | да | ? | ? |
Служба поддержки | ? | ? [32] [36] | ? | ? |
Microsoft рекомендует различать два 8-дюймовых формата для FAT ID 0xFE , пытаясь прочитать адресную метку с одинарной плотностью. Если это приводит к ошибке, среда должна быть двойной плотности. [30]
В таблице не указан ряд несовместимых форматов 8-дюймовых и 5,25-дюймовых гибких дисков FAT12, поддерживаемых 86-DOS , которые различаются либо размером записей каталога (16 байтов против 32 байтов), либо размером зарезервированного область секторов (несколько целых дорожек против только одного логического сектора).
Реализация одностороннего формата FAT12 размером 315 КБ, используемого в MS-DOS для ПК Apricot и F1e [38], имела разную компоновку загрузочного сектора для соответствия BIOS этого компьютера, несовместимого с IBM. Команда перехода и имя OEM были опущены, а параметры BPB MS-DOS (смещения 0x00B - 0x017 в стандартном загрузочном секторе) были расположены по смещению 0x050 . Портативное , F1 , дуэт ПК и Си FD поддерживают нестандартный двухсторонние 720 КБ формата FAT12 вместо этого. [38]Различия в макете загрузочного сектора и идентификаторах носителей сделали эти форматы несовместимыми со многими другими операционными системами. Параметры геометрии для этих форматов:
В более поздних версиях Apricot MS-DOS появилась возможность читать и записывать диски со стандартным загрузочным сектором в дополнение к дискам с Apricot. Эти форматы также поддерживались DOS Plus 2.1e / g для серии Apricot ACT.
Адаптация DOS Plus для BBC Master 512 поддерживала два формата FAT12 на 80-дорожечных двусторонних 5,25-дюймовых накопителях с двойной плотностью, которые вообще не использовали обычные загрузочные секторы. единственная копия FAT. [39] Для определения емкости диска использовался первый байт перемещенной FAT в логическом секторе 0. Загрузочные диски размером 640 КБ начинались с миниатюрной файловой системы ADFS, содержащей загрузчик, за которой следовала единственная файловая система FAT . [39] [40] Кроме того, формат 640 КБ отличался тем, что использовались физические номера секторов CHS, начинающиеся с 0 (а не 1, как обычно), и увеличивались сектора в порядке сектор-заголовок (а не сектор-заголовок-дорожка, как общий). [40]FAT стартовал в начале следующего трека. Эти различия делают эти форматы нераспознаваемыми другими операционными системами. Параметры геометрии для этих форматов:
DOS Plus для Master 512 может также получить доступ к стандартным дискам ПК, отформатированным до 180 или 360 КБ , используя первый байт FAT в логическом секторе 1 для определения емкости.
DEC Rainbow 100 (все варианты) поддерживает один формат FAT12 на 80-дорожечных односторонних 5,25-дюймовых накопителях с четырехканальной плотностью. Первые две дорожки были зарезервированы для загрузчика, но не содержали MBR или BPB ( MS-DOS вместо этого использовала статический BPB в памяти). Загрузочный сектор (дорожка 0, сторона 0, сектор 1) представлял собой код Z80, начинающийся с DI 0xF3 . Загрузочная программа 8088 была загружена Z80. Дорожка 1, сторона 0, сектор 2 начинается с байта идентификатора Media / FAT 0xFA . Неформатированные диски используют 0xE5.вместо. Файловая система начинается на дорожке 2, сторона 0, сектор 1. В корневом каталоге есть 2 копии FAT и 96 записей. Кроме того, существует отображение физических и логических дорожек для осуществления перемежения секторов 2: 1. Диски были отформатированы с физическими секторами в порядке пронумерованных от 1 до 10 на каждой дорожке после зарезервированных дорожек, но логические сектора от 1 до 10 были сохранены в физических секторах 1, 6, 2, 7, 3, 8, 4, 9. , 5, 10. [41]
«Информационный сектор FS» был введен в FAT32 [42] для ускорения времени доступа к определенным операциям (в частности, для получения количества свободного места). Он расположен в номере логического сектора, указанного в загрузочной записи FAT32 EBPB в позиции 0x030 (обычно логический сектор 1, сразу после самой загрузочной записи).
Смещение байта | Длина (байты) | СОДЕРЖАНИЕ |
---|---|---|
0x000 | 4 | Подпись сектора информации ФС ( 0x52 0x52 0x61 0x41 = " ")RRaA Пока информационный сектор FS расположен в логическом секторе 1, месте, где FAT обычно запускается в файловых системах FAT12 и FAT16 (только с одним зарезервированным сектором), наличие этой подписи гарантирует, что ранние версии DOS никогда не будут пытаются смонтировать том FAT32, поскольку они ожидают, что значения в кластере 0 и кластере 1 будут соответствовать определенным битовым шаблонам, которые не соответствуют этой сигнатуре. |
0x004 | 480 | Зарезервировано (байтовые значения должны быть установлены на 0x00 во время форматирования, но на них нельзя полагаться и никогда не изменяться в дальнейшем) |
0x1E4 | 4 | Подпись сектора информации ФС ( 0x72 0x72 0x41 0x61 = " ")rrAa |
0x1E8 | 4 | Последнее известное количество свободных кластеров данных на томе или 0xFFFFFFFF, если неизвестно. Должен быть установлен на 0xFFFFFFFF во время форматирования и обновлен операционной системой позже. Не следует полностью полагаться на правильность во всех сценариях. Перед использованием этого значения операционная система должна проверить работоспособность этого значения, чтобы оно было меньше или равно количеству кластеров тома. |
0x1EC | 4 | Номер кластера данных, который был назначен последним. Должен быть установлен на 0xFFFFFFFF во время форматирования и обновлен операционной системой позже. При 0xFFFFFFFF система должна запускаться с кластера 0x00000002 . Не следует полностью полагаться на правильность во всех сценариях. Перед использованием этого значения операционная система должна проверить работоспособность этого значения, чтобы оно было допустимым номером кластера на томе. |
0x1F0 | 12 | Зарезервировано (байтовые значения должны быть установлены на 0x00 во время форматирования, но на них нельзя полагаться и никогда не изменяться в дальнейшем) |
0x1FC | 4 | Подпись информационного сектора FS ( 0x00 0x00 0x55 0xAA ) [10] [nb 4] (все четыре байта должны совпадать, прежде чем содержимое этого сектора следует считать допустимым форматом.) |
Данные сектора могут быть устаревшими и не отражать текущее содержимое мультимедиа, потому что не все операционные системы обновляют или используют этот сектор, и даже если они это делают, содержимое недействительно, когда носитель был извлечен без надлежащего размонтирования тома или после сбой питания. Следовательно, операционные системы должны сначала проверить дополнительные битовые флаги состояния выключения тома, находящиеся в записи FAT кластера 1 или FAT32 EBPB по смещению 0x041, и игнорировать данные, хранящиеся в информационном секторе FS, если эти битовые флаги указывают, что том не был должным образом размонтирован. до. Это не вызывает никаких проблем, кроме возможного снижения скорости для первого запроса свободного пространства или выделения кластера данных; увидеть фрагментацию .
Если этот сектор присутствует на томе FAT32, минимально допустимый размер логического сектора составляет 512 байтов, тогда как в противном случае он был бы 128 байтов. Некоторые реализации FAT32 поддерживают небольшую вариацию спецификации Microsoft, делая информационный сектор FS необязательным путем указания значения 0xFFFF [26] (или 0x0000 ) в записи со смещением 0x030 .
Область данных тома разделена на кластеры одинакового размера - небольшие блоки непрерывного пространства. Размеры кластера различаются в зависимости от типа используемой файловой системы FAT и размера раздела; типичный размер кластера составляет от 2 до 32 КБ . [ необходима цитата ]
Каждый файл может занимать один или несколько кластеров в зависимости от своего размера. Таким образом, файл представлен цепочкой кластеров (называемой односвязным списком ). Эти кластеры не обязательно хранятся рядом друг с другом на поверхности диска, а часто вместо этого фрагментированы по всей области данных.
Каждая версия файловой системы FAT использует разный размер для записей FAT. Меньшие числа приводят к меньшему размеру FAT, но тратят пространство в больших разделах из-за необходимости выделения в больших кластерах.
FAT12 файловая система использует 12 бит на входе FAT, таким образом , две записи охватывают 3 байта. Он последовательно является прямым порядком байтов : если эти три байта рассматриваются как одно 24-битное число с прямым порядком байтов, 12 младших битов представляют первую запись (например, кластер 0), а 12 старших битов - вторую (например, кластер 1). . Другими словами, в то время как младшие восемь бит первого кластера в строке хранятся в первом байте, верхние четыре бита хранятся в младшем полубайте второго байта, тогда как младшие четыре бита последующего кластера в строке хранятся в старшем полубайте второго байта и его старших восьми битах в третьем байте.
Компенсировать | +0 | +1 | +2 | +3 | +4 | +5 | +6 | +7 | +8 | +9 | + А | + B | + C | + D | + E | + F |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
+0000 | F0 | F F | FF | 03 | 40 | 00 | 05 | 60 | 00 | 07 | 80 | 00 | FF | А Ф | 00 | 14 |
+0010 | С 0 | 00 | 0D | E0 | 00 | 0F | 00 | 01 | 11 | F 0 | FF | 00 | F 0 | FF | 15 | 60 |
+0020 | 01 | 19 | 7 0 | FF | F7 | А Ф | 01 | FF | 0 F | 00 | 00 | 7 0 | FF | 00 | 00 | 00 |
FAT16 файловой система использует 16 бит на вход FAT, таким образом , один ввод занимает два байта в обратном порядке байт:
Компенсировать | +0 | +1 | +2 | +3 | +4 | +5 | +6 | +7 | +8 | +9 | + А | + B | + C | + D | + E | + F |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
+0000 | F0 | FF | FF | FF | 03 | 00 | 04 | 00 | 05 | 00 | 06 | 00 | 07 | 00 | 08 | 00 |
+0010 | FF | FF | 0A | 00 | 14 | 00 | 0C | 00 | 0D | 00 | 0E | 00 | 0F | 00 | 10 | 00 |
+0020 | 11 | 00 | FF | FF | 00 | 00 | FF | FF | 15 | 00 | 16 | 00 | 19 | 00 | F7 | FF |
+0030 | F7 | FF | 1А | 00 | FF | FF | 00 | 00 | 00 | 00 | F7 | FF | 00 | 00 | 00 | 00 |
FAT32 файловая система использует 32 бита на запись FAT, таким образом один ввод охватывает четыре байта в прямой порядок байтов порядка байтов. Четыре старших бита каждой записи зарезервированы для других целей; они очищаются во время форматирования и не должны изменяться в противном случае. Они должны быть замаскированы перед интерпретацией записи как 28-битного адреса кластера.
Компенсировать | +0 | +1 | +2 | +3 | +4 | +5 | +6 | +7 | +8 | +9 | + А | + B | + C | + D | + E | + F |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
+0000 | F0 | FF | FF | 0F | FF | FF | FF | 0F | FF | FF | FF | 0F | 04 | 00 | 00 | 00 |
+0010 | 05 | 00 | 00 | 00 | 06 | 00 | 00 | 00 | 07 | 00 | 00 | 00 | 08 | 00 | 00 | 00 |
+0020 | FF | FF | FF | 0F | 0A | 00 | 00 | 00 | 14 | 00 | 00 | 00 | 0C | 00 | 00 | 00 |
+0030 | 0D | 00 | 00 | 00 | 0E | 00 | 00 | 00 | 0F | 00 | 00 | 00 | 10 | 00 | 00 | 00 |
+0040 | 11 | 00 | 00 | 00 | FF | FF | FF | 0F | 00 | 00 | 00 | 00 | FF | FF | FF | 0F |
+0050 | 15 | 00 | 00 | 00 | 16 | 00 | 00 | 00 | 19 | 00 | 00 | 00 | F7 | FF | FF | 0F |
+0060 | F7 | FF | FF | 0F | 1А | 00 | 00 | 00 | FF | FF | FF | 0F | 00 | 00 | 00 | 00 |
+0070 | 00 | 00 | 00 | 00 | F7 | FF | FF | 0F | 00 | 00 | 00 | 00 | 00 | 00 | 00 | 00 |
Таблица размещения файлов ( FAT ) представляет собой непрерывный ряд секторов сразу после зоны зарезервированных секторов. Он представляет собой список записей, которые сопоставляются каждому кластеру тома. Каждая запись записывает одну из пяти вещей:
Для очень ранних версий DOS, чтобы распознать файловую систему, система должна быть загружена с тома или FAT тома должна начинаться со второго сектора тома (логический сектор 1 с физическим адресом CHS 0/0/2 или адресом LBA 1) , то есть сразу после загрузочного сектора. Операционные системы предполагают, что это жестко привязанное расположение FAT, чтобы найти идентификатор FAT в записи кластера 0 FAT на дискетах с DOS 1.0-1.1 FAT, где не найдено действительных BPB.
Первые две записи в FAT хранят специальные значения:
Первая запись (кластер 0 в FAT) содержит идентификатор FAT, начиная с MS-DOS 1.20 и PC DOS 1.1 (допустимые значения 0xF0 - 0xFF с 0xF1 - 0xF7 зарезервированы) в битах 7-0, который также копируется в BPB файла загрузочный сектор, смещение 0x015 начиная с DOS 2.0. Оставшиеся 4 бита (если FAT12), 8 бит (если FAT16) или 20 бит (если FAT32) этой записи всегда равны 1. Эти значения были организованы таким образом, чтобы запись также функционировала как «перехватчик всех» в конце записи. -chain маркер для всех кластеров данных, содержащих нулевое значение. Кроме того, для идентификаторов FAT, отличных от 0xFF (и 0x00) можно определить правильный порядок полубайтов и байтов (который будет использоваться) драйвером файловой системы, однако файловая система FAT официально использует только прямое представление, и нет известных реализаций вариантов, использующих значения с прямым порядком байтов. вместо. 86-DOS 0.42 до MS-DOS 1.14 использовали профили жестких дисков вместо FAT ID, но использовали этот байт, чтобы различать носители, отформатированные с 32-байтовыми или 16-байтовыми записями каталога, поскольку они использовались до 86- ДОС 0.42.
Вторая запись (кластер 1 в FAT) номинально хранит маркер конца цепочки кластера, используемый форматером, но обычно всегда содержит 0xFFF / 0xFFFF / 0x0FFFFFFF , то есть, за исключением битов 31-28 в FAT32. Обычно эти биты устанавливаются всегда. Однако некоторые операционные системы Microsoft устанавливают эти биты, если том не является томом, содержащим работающую операционную систему (то есть здесь используется 0xFFFFFFFF вместо 0x0FFFFFFF ). [43] (В сочетании с альтернативными маркерами конца цепочки младшие биты 2-0 могут стать нулевыми для самого низкого разрешенного маркера конца цепочки 0xFF8 / 0xFFF8 / 0x? FFFFFF8; бит 3 также должен быть зарезервирован, учитывая, что кластеры 0xFF0 / 0xFFF0 / 0x? FFFFFF0 и выше официально зарезервированы. Некоторые операционные системы могут не иметь возможности монтировать некоторые тома, если какой-либо из этих битов не установлен, поэтому маркер конца цепочки по умолчанию не следует изменять.) Для DOS 1 и 2 запись была задокументирована как зарезервированная для использования в будущем. .
Начиная с DOS 7.1, два наиболее значимых бита этой записи кластера могут содержать два необязательных битовых флага, представляющих текущий статус тома в FAT16 и FAT32, но не в томах FAT12. Эти битовые флаги поддерживаются не всеми операционными системами, но операционные системы, поддерживающие эту функцию, будут устанавливать эти биты при завершении работы и сбрасывать наиболее значимый бит при запуске:
если бит 15 (в FAT16) или бит 27 (в FAT32) [44] не установлен. установленный при монтировании тома, том не был должным образом размонтирован перед выключением или извлечением и, таким образом, находится в неизвестном и, возможно, «грязном» состоянии. [31] На томах FAT32 информационный сектор FS может содержать устаревшие данные, поэтому его не следует использовать. Операционная система обычно запускает SCANDISK илиCHKDSK при следующем запуске [nb 10] [44] (но не при вставке съемного носителя), чтобы гарантировать и, возможно, восстановить целостность тома.
Если бит 14 (в FAT16) или бит 26 (в FAT32) [44] очищен, операционная система обнаружила ошибки дискового ввода-вывода при запуске [44], что может указывать на наличие сбойных секторов. Операционные системы, знающие об этом расширении, будут интерпретировать это как рекомендацию выполнить сканирование поверхности ( SCANDISK ) при следующей загрузке. [31] [44] (Аналогичный набор битовых флагов существует в FAT12 / FAT16 EBPB со смещением 0x1A или в FAT32 EBPB со смещением 0x36. Хотя запись кластера 1 может быть доступна драйверам файловой системы после того, как они смонтировали том, запись EBPB доступна, даже если том не смонтирован, и, таким образом, ее проще использовать драйверам блочных устройств диска или инструментам разбиения.)
Если количество жиров в ВРВЕ не установлено в положении 2, второй элемент кластера в первой FAT (кластер 1) может также отражать статус TFAT объема для TFAT-осведомленных операционные систем. Если запись кластера 1 в этой FAT содержит значение 0, это может означать, что вторая FAT представляет последнее известное действительное состояние транзакции и должна быть скопирована поверх первой FAT, тогда как первая FAT должна быть скопирована поверх второй FAT, если все биты установлены.
Некоторые нестандартные реализации FAT12 / FAT16 используют запись кластера 1 для хранения начального кластера корневого каталога переменного размера (обычно 2 [37] ). Это может произойти, если количество записей корневого каталога в BPB имеет значение 0, а FAT32 EBPB не найден (нет подписи 0x29 или 0x28 по смещению 0x042 ). [27] Это расширение, однако, не поддерживается основными операционными системами [27], поскольку оно конфликтует с другими возможными вариантами использования записи кластера 1. Большинство конфликтов можно исключить, если это расширение разрешено только для FAT12 с менее 0xFEF и FAT16 с менее чем 0x3FEF. кластеры и 2 FAT.
Поскольку эти первые две записи FAT хранят специальные значения, нет кластеров данных 0 или 1. Первым кластером данных (после корневого каталога, если FAT12 / FAT16) является кластер 2, [37] обозначающий начало области данных.
Значения записи FAT:
FAT12 | FAT16 | FAT32 | Описание |
---|---|---|---|
0x000 | 0x0000 | 0x? 0000000 | Бесплатный кластер; также используется DOS для ссылки на родительский каталог, запускающий кластер в записях ".." подкаталогов корневого каталога на томах FAT12 / FAT16. [11] [13] В противном случае, если это значение встречается в цепочках кластера (например, в записях каталога нулевой длины или в удаленных файлах), реализации файловой системы должны рассматривать это как маркер конца цепочки. [14] |
0x001 | 0x0001 | 0x? 0000001 | Зарезервировано для внутренних целей; MS-DOS / PC DOS используют это значение кластера в качестве временного индикатора несвободного кластера при построении цепочек кластеров во время выделения файлов (отображается на диске только в случае сбоя или сбоя питания в середине этого процесса). [11] [13] Если это значение встречается в цепочках кластеров на диске, реализации файловой системы должны рассматривать это как маркер конца цепочки. |
0x002 - 0xFEF | 0x0002 - 0xFFEF (0x0002 - 0x7FFF) | 0x? 0000002 - 0x? FFFFFEF | Используется как кластеры данных; значение указывает на следующий кластер. MS-DOS / PC DOS принимает значения до 0xFEF / 0xFFEF / 0x0FFFFFEF (иногда больше; см. Ниже), тогда как для Atari GEMDOS на томах FAT16 разрешены только значения до 0x7FFF . |
0xFF0 [nb 11] - 0xFF5 (0xFF1 - 0xFF5) | 0xFFF0 - 0xFFF5 | 0x? FFFFFF0 - 0x? FFFFFF5 | Зарезервировано в некоторых контекстах [45] или также используется [5] [6] [7] [10] [46] в качестве кластеров данных в некоторых нестандартных системах. Следует избегать размеров томов, которые использовали бы эти значения в качестве кластеров данных, но если эти значения встречаются в существующих томах, файловая система должна обрабатывать их как обычные кластеры данных в цепочках кластеров (в идеале с применением дополнительных проверок работоспособности), аналогично тому, что MS- DOS, PC DOS и DR-DOS делают, [13] и в противном случае следует избегать выделения их для файлов. MS-DOS / PC DOS 3.3 и выше обрабатывает значение 0xFF0 [nb 11] [13] на томах FAT12 (но не на FAT16 или FAT32) как дополнительный маркер конца цепи, аналогичный 0xFF8 - 0xFFF . [13] Для совместимости с MS-DOS / PC DOS файловым системам следует избегать использования кластера данных 0xFF0 в цепочках кластеров на томах FAT12 (то есть рассматривать его как зарезервированный кластер, аналогичный 0xFF7 ). (NB. Соответствие младшего байта номера кластера значениям FAT ID и дескриптора носителя является причиной, по которой эти значения кластера зарезервированы.) |
0xFF6 | 0xFFF6 | 0x? FFFFFF6 | Зарезервированный; не используйте. [5] [6] [7] [10] [28] [46] (NB. Соответствует значению заполнителя формата по умолчанию 0xF6 на IBM-совместимых машинах.) Не следует создавать тома, которые будут использовать это значение в качестве кластера данных, но если это значение встречается в существующих томах, файловая система должна рассматривать его как обычный кластер данных в цепочках кластеров (в идеале с применением дополнительных проверок работоспособности) и в противном случае не следует выделять его для файлов. [14] |
0xFF7 | 0xFFF7 | 0x? FFFFFF7 | Плохой сектор в кластере или зарезервированный кластер (начиная с DOS 2.0). Значения переключения для максимального количества кластеров для файловых систем FAT12 и FAT16 определены так, что максимально возможные значения кластера данных ( 0xFF5 и 0xFFF5 , [13] соответственно) всегда будут меньше этого значения. [13] Таким образом, это значение не может обычно встречаться в цепочках кластеров, но если это так, его можно рассматривать как обычный кластер данных, поскольку 0xFF7 мог быть нестандартным кластером данных на томах FAT12 до появления плохого маркер кластера с DOS 2.0 или введение FAT16 с DOS 3.0, [14] и 0xFFF7мог быть нестандартным кластером данных на томах FAT16 до появления FAT32 с DOS 7.10. Теоретически 0x0FFFFFF7 может быть частью допустимой цепочки кластеров на томах FAT32, но дисковые утилиты должны избегать создания томов FAT32, где это могло произойти. Файловой системе следует избегать выделения этого кластера для файлов. [14] Дисковые утилиты не должны пытаться восстановить «потерянные кластеры», содержащие это значение в FAT, но считают их неисправными. |
0xFF8 - 0xFFF (и необязательно 0xFF0; [nb 11] см. Примечание) | 0xFFF8 - 0xFFFF | 0x? FFFFFF8 - 0x? FFFFFFF | Последний кластер в файле (EOC). Реализации файловой системы должны одновременно обрабатывать все эти значения как маркер конца цепочки. [14] Большинство реализаций файловых систем (включая 86-DOS, MS-DOS, PC DOS и DR-DOS) используют 0xFFF [14] / 0xFFFF [14] / 0x0FFFFFFF в качестве маркера конца файла при размещении файлов, но версии Linux до 2.5.40 использовал 0xFF8 / 0xFFF8 / 0x0FFFFFF8 . [47] Версии mkdosfs ( dosfstools до 3.0.26 ) продолжают использовать 0x0FFFFFF8для корневого каталога на томах FAT32, тогда как некоторые инструменты восстановления и дефрагментации дисков используют другие значения в наборе (например, SCANDISK может вместо этого использовать 0xFF8 / 0xFFF8 / 0x0FFFFFF8 ). В то время как в исходной 8-битной реализации FAT в Microsoft Standalone Disk BASIC разные конечные маркеры ( 0xC0 .. 0xCD ) использовались для обозначения количества секторов (от 0 до 13), использованных в последнем кластере, занятом файлом, разные конечные маркеры были перепрофилированы под DOS для обозначения различных типов носителей, [14] с текущим используемым конечным маркером, указанным в кластере 1входа, однако, эта концепция, похоже, не получила широкого распространения на практике - и до такой степени, что в некоторых сценариях тома могут не распознаваться некоторыми операционными системами, если некоторые из младших битов значения, хранящегося в кластере 1 не установлены. Кроме того, некоторые ошибочные реализации файловой системы принимают только 0xFFF / 0xFFFF / 0x? FFFFFFF как допустимый маркер конца цепочки. Реализации файловой системы должны проверять значения кластеров в цепочках кластеров на соответствие максимально допустимому значению кластера, рассчитанному по фактическому размеру тома, и обрабатывать более высокие значения, как если бы они также были маркерами конца цепочки. (Младший байт номера кластера концептуально соответствует значениям FAT ID и дескриптора носителя ; [14] см. Примечание выше для MS-DOS / PC DOS специального использования 0xFF0 [nb 11] на томах FAT12. [13] ) |
FAT32 использует 28 бит для номеров кластеров. Остальные 4 бита в 32-битной записи FAT обычно равны нулю, но зарезервированы и должны оставаться нетронутыми. Стандартный совместимый драйвер файловой системы FAT32 или инструмент обслуживания не должен полагаться на то, что верхние 4 бита равны нулю, и он должен удалить их перед оценкой номера кластера, чтобы справиться с возможными будущими расширениями, где эти биты могут использоваться для других целей. Они не должны очищаться драйвером файловой системы при выделении новых кластеров, но должны очищаться во время переформатирования.
Варианты FAT12, FAT16, FAT16B и FAT32 файловых систем FAT имеют четкие ограничения, основанные на количестве кластеров и количестве секторов в кластере (1, 2, 4, ..., 128). Для типичного значения 512 байт на сектор:
Требования FAT12: 3 сектора на каждую копию FAT на каждые 1024 кластера
Требования FAT16: 1 сектор на каждую копию FAT на каждые 256 кластеров
Требования FAT32: 1 сектор на каждую копию FAT на каждые 128 кластеров
Диапазон FAT12: от 1 до 4084 кластера:
От 1 до 12 секторов на копию FAT Диапазон FAT16: от 4085 до 65 524 кластеров: от 16 до 256 секторов на копию FAT
Диапазон FAT32: от 65 525 до 268 435 444 кластера: от 512 до 2097 152 секторов на копию FAT
FAT12 минимум: 1 сектор на кластер × 1 кластер = 512 байт (0,5 КБ)
Минимум FAT16: 1 сектор на кластер × 4085 кластеров = 2 091 520 байт (2042,5 КБ)
Минимум FAT32: 1 сектор на кластер × 65 525 кластеров = 33 548 800 байт (32 762,5 КБ)
FAT12 maximum : 64 sectors per cluster × 4,084 clusters = 133,824,512 bytes (≈ 127 MB)
[FAT12 maximum : 128 sectors per cluster × 4,084 clusters = 267,694,024 bytes (≈ 255 MB)]
FAT16 maximum : 64 sectors per cluster × 65,524 clusters = 2,147,090,432 bytes (≈2,047 MB)
[FAT16 maximum : 128 sectors per cluster × 65,524 clusters = 4,294,180,864 bytes (≈4,095 MB)]
FAT32 maximum : 8 sectors per cluster × 268,435,444 clusters = 1,099,511,578,624 bytes (≈1,024 GB)
FAT32 maximum : 16 sectors per cluster × 268,173,557 clusters = 2,196,877,778,944 bytes (≈2,046 GB)
[FAT32 maximum : 32 sectors per cluster × 134,152,181 clusters = 2,197,949,333,504 bytes (≈2,047 GB)]
[FAT32 maximum : 64 sectors per cluster × 67,092,469 clusters = 2,198,486,024,192 bytes (≈2,047 GB)]
[FAT32 maximum : 128 sectors per cluster × 33,550,325 clusters = 2,198,754,099,200 bytes (≈2,047 GB)]
Because each FAT32 entry occupies 32 bits (4 bytes) the maximal number of clusters (268435444) requires 2097152 FAT sectors for a sector size of 512 bytes. 2097152 is 0x200000, and storing this value needs more than two bytes. Therefore, FAT32 introduced a new 32-bit value in the FAT32 boot sector immediately following the 32-bit value for the total number of sectors introduced in the FAT16B variant.
The boot record extensions introduced with DOS 4.0 start with a magic 40 (0x28) or 41 (0x29). Typically FAT drivers look only at the number of clusters to distinguish FAT12, FAT16, and FAT32: the human readable strings identifying the FAT variant in the boot record are ignored, because they exist only for media formatted with DOS 4.0 or later.
Determining the number of directory entries per cluster is straightforward. Each entry occupies 32 bytes; this results in 16 entries per sector for a sector size of 512 bytes. The DOS 5 RMDIR
/RD
command removes the initial ".
" (this directory) and "..
" (parent directory) entries in subdirectories directly, therefore sector size 32 on a RAM disk is possible for FAT12, but requires 2 or more sectors per cluster. A FAT12 boot sector without the DOS 4 extensions needs 29 bytes before the first unnecessary FAT16B 32-bit number of hidden sectors, this leaves three bytes for the (on a RAM disk unused) boot code and the magic 0x55 0xAA at the end of all boot sectors. On Windows NT the smallest supported sector size is 128.
On Windows NT operating systems the FORMAT
command options /A:128K
and /A:256K
correspond to the maximal cluster size 0x80
(128) with a sector size 1024 and 2048, respectively. For the common sector size 512 /A:64K
yields 128 sectors per cluster.
Both editions of each ECMA-107[5] and ISO/IEC 9293[6][7] specify a Max Cluster Number MAX
determined by the formula MAX=1+trunc((TS-SSA)/SC)
, and reserve cluster numbers MAX+1
up to 4086 (0xFF6, FAT12) and later 65526 (0xFFF6, FAT16) for future standardization.
Microsoft's EFI FAT32 specification[10] states that any FAT file system with less than 4085 clusters is FAT12, else any FAT file system with less than 65525 clusters is FAT16, and otherwise it is FAT32. The entry for cluster 0 at the beginning of the FAT must be identical to the media descriptor byte found in the BPB, whereas the entry for cluster 1 reflects the end-of-chain value used by the formatter for cluster chains (0xFFF, 0xFFFF or 0x0FFFFFFF). The entries for cluster numbers 0 and 1 end at a byte boundary even for FAT12, e.g., 0xF9FFFF for media descriptor 0xF9.
The first data cluster is 2,[37] and consequently the last cluster MAX
gets number MAX+1
. This results in data cluster numbers 2...4085 (0xFF5) for FAT12, 2...65525 (0xFFF5) for FAT16, and 2...268435445 (0x0FFFFFF5) for FAT32.
The only available values reserved for future standardization are therefore 0xFF6 (FAT12) and 0xFFF6 (FAT16). As noted below "less than 4085" is also used for Linux implementations,[46] or as Microsoft's FAT specification puts it:[10]
...when it says <, it does not mean <=. Note also that the numbers are correct. The first number for FAT12 is 4085; the second number for FAT16 is 65525. These numbers and the "<" signs are not wrong.
The FAT file system does not contain built-in mechanisms which prevent newly written files from becoming scattered across the partition.[49] On volumes where files are created and deleted frequently or their lengths often changed, the medium will become increasingly fragmented over time.
While the design of the FAT file system does not cause any organizational overhead in disk structures or reduce the amount of free storage space with increased amounts of fragmentation, as it occurs with external fragmentation, the time required to read and write fragmented files will increase as the operating system will have to follow the cluster chains in the FAT (with parts having to be loaded into memory first in particular on large volumes) and read the corresponding data physically scattered over the whole medium reducing chances for the low-level block device driver to perform multi-sector disk I/O or initiate larger DMA transfers, thereby effectively increasing I/O protocol overhead as well as arm movement and head settle times inside the disk drive. Also, file operations will become slower with growing fragmentation as it takes increasingly longer for the operating system to find files or free clusters.
Other file systems, e.g., HPFS or exFAT, use free space bitmaps that indicate used and available clusters, which could then be quickly looked up in order to find free contiguous areas. Another solution is the linkage of all free clusters into one or more lists (as is done in Unix file systems). Instead, the FAT has to be scanned as an array to find free clusters, which can lead to performance penalties with large disks.
In fact, seeking for files in large subdirectories or computing the free disk space on FAT volumes is one of the most resource intensive operations, as it requires reading the directory tables or even the entire FAT linearly. Since the total amount of clusters and the size of their entries in the FAT was still small on FAT12 and FAT16 volumes, this could still be tolerated on FAT12 and FAT16 volumes most of the time, considering that the introduction of more sophisticated disk structures would have also increased the complexity and memory footprint of real-mode operating systems with their minimum total memory requirements of 128 KB or less (such as with DOS) for which FAT has been designed and optimized originally.
With the introduction of FAT32, long seek and scan times became more apparent, particularly on very large volumes. A possible justification suggested by Microsoft's Raymond Chen for limiting the maximum size of FAT32 partitions created on Windows was the time required to perform a "DIR
" operation, which always displays the free disk space as the last line.[50] Displaying this line took longer and longer as the number of clusters increased. FAT32 therefore introduced a special file system information sector where the previously computed amount of free space is preserved over power cycles, so that the free space counter needs to be recalculated only when a removable FAT32 formatted medium gets ejected without first unmounting it or if the system is switched off without properly shutting down the operating system, a problem mostly visible with pre-ATX-style PCs, on plain DOS systems and some battery-powered consumer products.
With the huge cluster sizes (16 KB, 32 KB, 64 KB) forced by larger FAT partitions, internal fragmentation in form of disk space waste by file slack due to cluster overhang (as files are rarely exact multiples of cluster size) starts to be a problem as well, especially when there are a great many small files.
Various optimizations and tweaks to the implementation of FAT file system drivers, block device drivers and disk tools have been devised to overcome most of the performance bottlenecks in the file system's inherent design without having to change the layout of the on-disk structures.[51][52] They can be divided into on-line and off-line methods and work by trying to avoid fragmentation in the file system in the first place, deploying methods to better cope with existing fragmentation, and by reordering and optimizing the on-disk structures. With optimizations in place, the performance on FAT volumes can often reach that of more sophisticated file systems in practical scenarios, while at the same time retaining the advantage of being accessible even on very small or old systems.
DOS 3.0 and higher will not immediately reuse disk space of deleted files for new allocations but instead seek for previously unused space before starting to use disk space of previously deleted files as well. This not only helps to maintain the integrity of deleted files for as long as possible but also speeds up file allocations and avoids fragmentation, since never before allocated disk space is always unfragmented. DOS accomplishes this by keeping a pointer to the last allocated cluster on each mounted volume in memory and starts searching for free space from this location upwards instead of at the beginning of the FAT, as it was still done by DOS 2.x.[20] If the end of the FAT is reached, it would wrap around to continue the search at the beginning of the FAT until either free space has been found or the original position has been reached again without having found free space.[20] These pointers are initialized to point to the start of the FATs after bootup,[20] but on FAT32 volumes, DOS 7.1 and higher will attempt to retrieve the last position from the FS Information Sector. This mechanism is defeated, however, if an application often deletes and recreates temporary files as the operating system would then try to maintain the integrity of void data effectively causing more fragmentation in the end.[20] In some DOS versions, the usage of a special API function to create temporary files can be used to avoid this problem.
Additionally, directory entries of deleted files will be marked 0xE5 since DOS 3.0.[11] DOS 5.0 and higher will start to reuse these entries only when previously unused directory entries have been used up in the table and the system would otherwise have to expand the table itself.[13]
Since DOS 3.3 the operating system provides means to improve the performance of file operations with FASTOPEN
by keeping track of the position of recently opened files or directories in various forms of lists (MS-DOS/PC DOS) or hash tables (DR-DOS), which can reduce file seek and open times significantly. Before DOS 5.0 special care must be taken when using such mechanisms in conjunction with disk defragmentation software bypassing the file system or disk drivers.
Windows NT will allocate disk space to files on FAT in advance, selecting large contiguous areas, but in case of a failure, files which were being appended will appear larger than they were ever written into, with a lot of random data at the end.
Other high-level mechanisms may read in and process larger parts or the complete FAT on startup or on demand when needed and dynamically build up in-memory tree representations of the volume's file structures different from the on-disk structures.[51][52] This may, on volumes with many free clusters, occupy even less memory than an image of the FAT itself. In particular on highly fragmented or filled volumes, seeks become much faster than with linear scans over the actual FAT, even if an image of the FAT would be stored in memory. Also, operating on the logically high level of files and cluster-chains instead of on sector or track level, it becomes possible to avoid some degree of file fragmentation in the first place or to carry out local file defragmentation and reordering of directory entries based on their names or access patterns in the background.
Some of the perceived problems with fragmentation of FAT file systems also result from performance limitations of the underlying block device drivers, which becomes more visible the lesser memory is available for sector buffering and track blocking/deblocking:
While the single-tasking DOS had provisions for multi-sector reads and track blocking/deblocking, the operating system and the traditional PC hard disk architecture (only one outstanding input/output request at a time and no DMA transfers) originally did not contain mechanisms which could alleviate fragmentation by asynchronously prefetching next data while the application was processing the previous chunks. Such features became available later. Later DOS versions also provided built-in support for look-ahead sector buffering and came with dynamically loadable disk caching programs working on physical or logical sector level, often utilizing EMS or XMS memory and sometimes providing adaptive caching strategies or even run in protected mode through DPMS or Cloaking to increase performance by gaining direct access to the cached data in linear memory rather than through conventional DOS APIs.
Write-behind caching was often not enabled by default with Microsoft software (if present) given the problem of data loss in case of a power failure or crash, made easier by the lack of hardware protection between applications and the system.
A directory table is a special type of file that represents a directory (also known as a folder). Since 86-DOS 0.42,[53] each file or (since MS-DOS 1.40 and PC DOS 2.0) subdirectory stored within it is represented by a 32-byte entry in the table. Each entry records the name, extension, attributes (archive, directory, hidden, read-only, system and volume), the address of the first cluster of the file/directory's data, the size of the file/directory, and the date[53] and (since PC DOS 1.1) also the time of last modification. Earlier versions of 86-DOS used 16-byte directory entries only, supporting no files larger than 16 MB and no time of last modification.[53]
Aside from the root directory table in FAT12 and FAT16 file systems, which occupies the special Root Directory Region location, all directory tables are stored in the data region. The actual number of entries in a directory stored in the data region can grow by adding another cluster to the chain in the FAT.
The FAT file system itself does not impose any limits on the depth of a subdirectory tree for as long as there are free clusters available to allocate the subdirectories, however, the internal Current Directory Structure (CDS) under MS-DOS/PC DOS limits the absolute path of a directory to 66 characters (including the drive letter, but excluding the NUL byte delimiter),[5][6][7] thereby limiting the maximum supported depth of subdirectories to 32, whatever occurs earlier. Concurrent DOS, Multiuser DOS and DR DOS 3.31 to 6.0 (up to including the 1992-11 updates) do not store absolute paths to working directories internally and therefore do not show this limitation.[54] The same applies to Atari GEMDOS, but the Atari Desktop does not support more than 8 sub-directory levels. Most applications aware of this extension support paths up to at least 127 bytes. FlexOS, 4680 OS and 4690 OS support a length of up to 127 bytes as well, allowing depths down to 60 levels.[55] PalmDOS, DR DOS 6.0 (since BDOS 7.1) and higher, Novell DOS, and OpenDOS sport a MS-DOS-compatible CDS and therefore have the same length limits as MS-DOS/PC DOS.
Each entry can be preceded by "fake entries" to support a VFAT long filename (LFN); see further below.
Legal characters for DOS short filenames include the following:
A
–Z
0
–9
MKDIR
/MD
and RMDIR
/RD
under DR-DOS which accept single arguments and therefore allow spaces to be entered.! # $ % & ' ( ) - @ ^ _ ` { } ~
This excludes the following ASCII characters:
" * / : < > ? \ |
+ , . ; = [ ]
a
–z
A
–Z
; allowed in long file namesCharacter 229 (0xE5) was not allowed as first character in a filename in DOS 1 and 2 due to its use as free entry marker. A special case was added to circumvent this limitation with DOS 3.0 and higher.
The following additional characters are allowed on Atari's GEMDOS, but should be avoided for compatibility with MS-DOS/PC DOS:
" + , ; < = > [ ] |
The semicolon (;
) should be avoided in filenames under DR DOS 3.31 and higher, PalmDOS, Novell DOS, OpenDOS, Concurrent DOS, Multiuser DOS, System Manager and REAL/32, because it may conflict with the syntax to specify file and directory passwords: "...\DIRSPEC.EXT;DIRPWD\FILESPEC.EXT;FILEPWD
". The operating system will strip off one[54] (and also two—since DR-DOS 7.02) semicolons and pending passwords from the filenames before storing them on disk. (The command processor 4DOS uses semicolons for include lists and requires the semicolon to be doubled for password protected files with any commands supporting wildcards.[54])
The at-sign character (@
) is used for filelists by many DR-DOS, PalmDOS, Novell DOS, OpenDOS and Multiuser DOS, System Manager and REAL/32 commands, as well as by 4DOS and may therefore sometimes be difficult to use in filenames.[54]
Under Multiuser DOS and REAL/32, the exclamation mark (!) is not a valid filename character since it is used to separate multiple commands in a single command line.[54]
Under IBM 4680 OS and 4690 OS, the following characters are not allowed in filenames:
? * : . ; , [ ] ! + = < > " - / \ |
Additionally, the following special characters are not allowed in the first, fourth, fifth and eight character of a filename, as they conflict with the host command processor (HCP) and input sequence table build file names:
@ # ( ) { } $ &
The DOS file names are in the current OEM character set: this can have surprising effects if characters handled in one way for a given code page are interpreted differently for another code page (DOS command CHCP
) with respect to lower and upper case, sorting, or validity as file name character.
Before Microsoft added support for long filenames and creation/access time stamps, bytes 0x0C–0x15 of the directory entry were used by other operating systems to store additional metadata, most notably the operating systems of the Digital Research family stored file passwords, access rights, owner IDs, and file deletion data there. While Microsoft's newer extensions are not fully compatible with these extensions by default, most of them can coexist in third-party FAT implementations (at least on FAT12 and FAT16 volumes).
32-byte directory entries, both in the Root Directory Region and in subdirectories, are of the following format (see also 8.3 filename):
Byte offset | Length (bytes) | Contents | ||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0x00 | 8 | Short file name (padded with spaces) The first byte can have the following special values:
Versions of DOS prior to 5.0 start scanning directory tables from the top of the directory table to the bottom. In order to increase chances for successful file undeletion, DOS 5.0 and higher will remember the position of the last written directory entry and use this as a starting point for directory table scans. | ||||||||||||||||||||||||||||||||||||||||||
0x08 | 3 | Short file extension (padded with spaces) | ||||||||||||||||||||||||||||||||||||||||||
0x0B | 1 | File Attributes
Under DR DOS 6.0 and higher, including PalmDOS, Novell DOS and OpenDOS, the volume attribute is set for pending delete files and directories under DELWATCH. An attribute combination of 0x0F is used to designate a VFAT long file name entry since MS-DOS 7.0. Older versions of DOS can mistake this for a directory volume label, as they take the first entry with volume attribute set as volume label. This problem can be avoided if a directory volume label is enforced as part of the format process; for this reason some disk tools explicitly write dummy " | ||||||||||||||||||||||||||||||||||||||||||
0x0C | 1 |
| ||||||||||||||||||||||||||||||||||||||||||
0x0D | 1 |
Double usage for create time ms and file char does not create a conflict, since the creation time is no longer important for deleted files. | ||||||||||||||||||||||||||||||||||||||||||
0x0E | 2 |
If bits 15-11 > 23 or bits 10-5 > 59 or bits 4-0 > 29 here, or when bits 12-0 at offset 0x14 hold an access bitmap and this is not a FAT32 volume or a volume using OS/2 Extended Attributes, then this entry actually holds a password hash, otherwise it can be assumed to be a file creation time. | ||||||||||||||||||||||||||||||||||||||||||
0x10 | 2 |
The usage for creation date for existing files does not conflict with last modified time for deleted files because they are never used at the same time. For the same reason, the usage for the record size of existing files and last modified time of deleted files does not conflict. Creation dates and record sizes cannot be used at the same time, however, both are stored only on file creation and never changed later on, thereby limiting the conflict to FlexOS, 4680 OS and 4690 OS systems accessing files created under foreign operating systems as well as potential display or file sorting problems on systems trying to interpret a record size as creation time. To avoid the conflict, the storage of creation dates should be an optional feature of operating systems supporting it. | ||||||||||||||||||||||||||||||||||||||||||
0x12 | 2 |
The usage for the owner IDs of existing files does not conflict with last modified date stamp for deleted files because they are never used at the same time.[54] The usage of the last modified date stamp for deleted files does not conflict with access date since access dates are no longer important for deleted files. However, owner IDs and access dates cannot be used at the same time. | ||||||||||||||||||||||||||||||||||||||||||
0x14 | 2 |
The storage of the high two bytes of the first cluster in a file on FAT32 partially conflicts with access rights bitmaps. | ||||||||||||||||||||||||||||||||||||||||||
0x16 | 2 |
| ||||||||||||||||||||||||||||||||||||||||||
0x18 | 2 |
| ||||||||||||||||||||||||||||||||||||||||||
0x1A | 2 | Start of file in clusters in FAT12 and FAT16. Low two bytes of first cluster in FAT32; with the high two bytes stored at offset 0x14. Entries with the Volume Label flag, subdirectory ".." pointing to the FAT12 and FAT16 root, and empty files with size 0 should have first cluster 0. VFAT LFN entries also have this entry set to 0; on FAT12 and FAT16 volumes this can be used as part of a detection mechanism to distinguish between pending delete files under DELWATCH and VFAT LFNs; see above. | ||||||||||||||||||||||||||||||||||||||||||
0x1C | 4 | File size in bytes. Entries with the Volume Label or Subdirectory flag set should have a size of 0. VFAT LFN entries never store the value 0x00000000 here. This can be used as part of a detection mechanism to distinguish between pending delete files under DELWATCH and VFAT LFNs; see above. |
The FlexOS-based operating systems IBM 4680 OS and IBM 4690 OS support unique distribution attributes stored in some bits of the previously reserved areas in the directory entries:[68]
Some incompatible extensions found in some operating systems include:
Byte offset | Length (bytes) | System | Description |
---|---|---|---|
0x0C | 2 | RISC OS | File type, 0x0000–0x0FFF |
0x0C | 4 | Petrov DOSFS | File load address |
0x0E | 2 | ANDOS | File address in the memory |
0x10 | 4 | Petrov DOSFS | File execution address |
VFAT Long File Names (LFNs) are stored on a FAT file system using a trick: adding additional entries into the directory before the normal file entry. The additional entries are marked with the Volume Label, System, Hidden, and Read Only attributes (yielding 0x0F), which is a combination that is not expected in the MS-DOS environment, and therefore ignored by MS-DOS programs and third-party utilities. Notably, a directory containing only volume labels is considered as empty and is allowed to be deleted; such a situation appears if files created with long names are deleted from plain DOS. This method is very similar to the DELWATCH method to utilize the volume attribute to hide pending delete files for possible future undeletion since DR DOS 6.0 (1991) and higher. It is also similar to a method publicly discussed to store long filenames on Ataris and under Linux in 1992.[70][71]
Because older versions of DOS could mistake LFN names in the root directory for the volume label, VFAT was designed to create a blank volume label in the root directory before adding any LFN name entries (if a volume label did not already exist).[nb 13]
Each phony entry can contain up to 13 UCS-2 characters (26 bytes) by using fields in the record which contain file size or time stamps (but not the starting cluster field, for compatibility with disk utilities, the starting cluster field is set to a value of 0. See 8.3 filename for additional explanations). Up to 20 of these 13-character entries may be chained, supporting a maximum length of 255 UCS-2 characters.[61]
After the last UCS-2 character, a 0x0000 is added. The remaining unused characters are filled with 0xFFFF.
LFN entries use the following format:
Byte offset | Length (bytes) | Description |
---|---|---|
0x00 | 1 | Sequence Number (bit 6: last logical, first physical LFN entry, bit 5: 0; bits 4-0: number 0x01..0x14 (0x1F), deleted entry: 0xE5) |
0x01 | 10 | Name characters (five UCS-2 characters) |
0x0B | 1 | Attributes (always 0x0F) |
0x0C | 1 | Type (always 0x00 for VFAT LFN, other values reserved for future use; for special usage of bits 4 and 3 in SFNs see further up) |
0x0D | 1 | Checksum of DOS file name |
0x0E | 12 | Name characters (six UCS-2 characters) |
0x1A | 2 | First cluster (always 0x0000) |
0x1C | 4 | Name characters (two UCS-2 characters) |
If there are multiple LFN entries required to represent a file name, the entry representing the end of the filename comes first. The sequence number of this entry has bit 6 (0x40) set to represent that it is the last logical LFN entry, and it has the highest sequence number. The sequence number decreases in the following entries. The entry representing the start of the filename has sequence number 1. A value of 0xE5 is used to indicate that the entry is deleted.
On FAT12 and FAT16 volumes, testing for the values at 0x1A to be zero and at 0x1C to be non-zero can be used to distinguish between VFAT LFNs and pending delete files under DELWATCH.
For example, a filename like "File with very long filename.ext" would be formatted like this:
Sequence number | Entry data |
---|---|
0x43 | "me.ext" |
0x02 | "y long filena" |
0x01 | "File with ver" |
??? | Normal 8.3 entry |
A checksum also allows verification of whether a long file name matches the 8.3 name; such a mismatch could occur if a file was deleted and re-created using DOS in the same directory position. The checksum is calculated using the algorithm below. (pFCBName is a pointer to the name as it appears in a regular directory entry, i.e. the first eight characters are the filename, and the last three are the extension. The dot is implicit. Any unused space in the filename is padded with space characters (ASCII 0x20). For example, "Readme.txt" would be "README␠␠TXT
".)
unsigned char lfn_checksum(const unsigned char *pFCBName){ int i; unsigned char sum = 0; for (i = 11; i; i--) sum = ((sum & 1) << 7) + (sum >> 1) + *pFCBName++; return sum;}
If a filename contains only lowercase letters, or is a combination of a lowercase basename with an uppercase extension, or vice versa; and has no special characters, and fits within the 8.3 limits, a VFAT entry is not created on Windows NT and later versions of Windows such as XP. Instead, two bits in byte 0x0C of the directory entry are used to indicate that the filename should be considered as entirely or partially lowercase. Specifically, bit 4 means lowercase extension and bit 3 lowercase basename, which allows for combinations such as "example.TXT
" or "HELLO.txt
" but not "Mixed.txt
". Few other operating systems support it. This creates a backwards-compatibility problem with older Windows versions (Windows 95 / 98 / 98 SE / ME) that see all-uppercase filenames if this extension has been used, and therefore can change the name of a file when it is transported between operating systems, such as on a USB flash drive. Current 2.6.x versions of Linux will recognize this extension when reading (source: kernel 2.6.18 /fs/fat/dir.c
and fs/vfat/namei.c
); the mount option shortname
determines whether this feature is used when writing.[72]
/W:246
. In contrast to other FDISK utilities, DR-DOS FDISK is not only a partitioning tool, but can also format freshly created partitions as FAT12, FAT16 or FAT32. This reduces the risk to accidentally format wrong volumes.IBMBIO␠␠COM
" boot file name can be changed using the SYS /DR:ext
option, where ext represents the new extension. Other potential DR-DOS boot file names to be expected in special scenarios are "DRBIOS␠␠SYS
", "DRDOS␠␠␠SYS
", "IO␠␠␠␠␠␠SYS
", "JO␠␠␠␠␠␠SYS
"./O
(for old) to fill the first byte of all directory entries with 0xE5 instead of utilizing the end marker 0x00. Thereby. the volume remained accessible under PC DOS 1.0-1.1, while formatting took somewhat longer and newer versions of DOS could not take advantage of the considerable speed-up caused by using the end marker 0x00.NO␠NAME␠␠␠␠
" directory volume labels if the user skips entering a volume label. The operating system would internally default to return the same string if no directory volume label could be found in the root of a volume, but without a real volume label stored as the first entry (after the directory entries), older operating systems could erroneously pick up VFAT LFN entries instead.ACCDATE=drive1+|- [drive2+|-]...
"In regard to the jump instruction at the start of a boot sector: "Determine if the first byte of the boot sector is an E9H or EBIT (the first byte of a 3-byte NEAR or 2-byte short jump) or an EBH (the first byte of a 2-byte jump followed by a NOP). If so, a BPB is located beginning at offset 3."(NB. This book contains many errors.)
The numbering starts with 2; the first two numbers, 0 and 1, are reserved.
Clusters cannot be 64 kilobytes or larger