en:docs:boot:mbr

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
en:docs:boot:mbr [2014/05/10 17:05] – external edit 127.0.0.1en:docs:boot:mbr [2023/11/16 08:04] (current) prokushev
Line 1: Line 1:
-==== Описание MBR-загрузчика ====+====== Description of the MBR bootloader ======
  
-  Данный  загрузчик  должен  находиться  в нулевом секторе первого жесткого диска (MBR) и  предназначен для загрузки бутсектора активного раздела или же раздела  с  заданным  номером  на указанном жестком диске. MBR, загрузившись с первого  жесткого  диска,  может  выбрать,  с какого жесткого диска продолжать загрузку  дальше.  На  выбранном жестком диске загружается бутсектор активного раздела,  либо раздела с определенным номером. Номер следующего жесткого диска и  номер  раздела  на  нем  прописываются  в двух байтах внутри сектора MBR на первом  жестком диске. Активный раздел определяется по первому байту описателя раздела  в  таблице  разделов (Partition table или PT). Если данное поле равно 80h, то раздел считается активным, если же оно равно 00h, то раздел неактивен. +**This is machine-translated text**
-  Для  загрузки  с первичного (primary) или логического (logical) раздела с заданным  номером  предназначено поле BootPart в MBR-секторе, имеющее размер в +
-  байт и расположенное в MBR по смещению 0x1bb от начала сектора. Данное поле прописывается  в MBR при установке загрузчика. Если данное поле равно нулю, то это  значит,  что загрузчик должен определить активный primary-раздел жесткого диска,  и  загрузить  с  него  бутсектор,  передав  ему  управление. Если поле BootPart ненулевое, то это является указанием загрузчику принудительно выбрать загрузочный  раздел,  логический  или первичный, не проверяя байт активности в таблице  разделов.  В  этом  случае  проверяется значение байта BootPart. Если BootPart  имеет  значение  от  1  до  4,  то  это  число  трактуется как номер primary-раздела.  Если  его  значение  от  5 и более, то BootPart - 4 является омером логического диска внутри Extended раздела. +
-  Таким образом, так как максимальное значение байта BootPart равно 255, то число  логических  дисков  может  быть  от  0  до  255  -  4  =  251. То есть, по-максимуму  может  быть  3  primary-раздела плюс 1 extended и 251 логический диск внутри extended. +
-  * Данный  загрузчик использует LBA для загрузки секторов с жесткого диска в память,  если LBA поддерживается. В противном случае используется функция BIOS для чтения секторов с помощью CHS. +
-  * Перед таблицей разделов, по смещению 0x1bd, находится байт ForceLBA. Если этот байт не равен нулю, то LBA используется принудительно. +
-  * Перед  ForceLBA  и  после  BootPart,  по  смещению 0x1bc, расположен байт BootDev.  Он  определяет  физическое устройство, на котором искать загрузочный раздел  с  бутсектором.  Значение  этого  байта  равно номеру жесткого диска в формате  int  13h. Например, первый жесткий диск имеет номер 80h, второй 81h и т.  д.  По  умолчанию  этот  байт  равен 80h, то есть, производится загрузка с первого жесткого диска в системе. +
-  * Таблица  разделов расположена начиная со следующего за ForceLBA байта, по смещению  0x1be,  и,  согласно  стандарту, состоит из 4-ех описателей разделов размером по 16 байт каждый. +
-  * Заканчивается  сектор  сигнатурой  MBR,  равной  0x55aa.  Эти  два  байта предназначены  для  контроля  целостности MBR, а также для удобства при поиске MBR и бутсекторов при восстановлении данных на рухнувшем жестком диске. +
-  * Данный  загрузчик  выводит  в  аварийных  ситуациях два сообщения.  +
-    * Первое общение  --  "R"  (первая  буква  фразы  "Read error") выводится при ошибках чтения  диска,   +
-      * а  именно,  если  ни LBA, ни CHS не дали успешного статуса при чтении сектора с диска. +
-    * Сообщение  "P"  означает  "Partition not found" и выводится, когда:  +
-      - Не найден  активный  раздел  в таблице разделов  +
-      - Не найден расширенный раздел и байт  BootPart  >  4   +
-      - Просматривая  цепочку  EBR  (Extended boot records), (!!! Fix it) загрузчик  не  нашел  ссылки на следующую EBR и текущая EBR, согласно значению байта  BootPart, не является последней.  +
-      - Не найден описатель нужного раздела в  EBR  (должен  быть  помечен  байтом  активности  80h).   +
-      - Описатель в MBR primary-раздела состоит из нулей и не описывает никакого раздела. +
-  * Загрузчик  при  запуске  (BIOS int 19h загружает его по адресу 0x7c0:0x0) перемещает  себя  по  адресу  0x60:0x0 и передает управление по новому адресу. Прежнее  место  загрузчика  (от  0x7c0:0x0  до  0x7e0:0x0  размером  в сектор) используется  как  буфер  для  загрузки  секторов.  В  это  место  попеременно загружаются  MBR  первого  жесткого  диска, MBR следующего жесткого диска, 1-я EBR,  2-я  EBR, ..., n-я EBR и, наконец, бутсектор загрузочного раздела. После этого, управление передается бутсектору. +
-  * Пространство  от 0x7e0:0 до 0x800:0 используется MBR-загрузчиком, а также бутсектором,  для  хранения  некоторых  переменных.  Стек и MBR-загрузчиком, и бутсектором используется такой: ss = 0, дно стека инициализируется в 0x7bff. +
-  * Данный загрузчик, загрузив бутсектор,  +
-    * "поправляет" значение hiddensectors в  BPB, прибавляя к нему номер первого сектора данного логического диска (того самого сектора, где находится EBR, то есть за 63 сектора до бутсектора).  +
-    * Также в  соответствующие поля BPB бутсектора MBR-загрузчик заносит номер физического диска  и  номер,  соответствующий  букве  логического  диска.   +
-    * Эти манипуляции выполняются  для возможности загрузки OS/2 с логических  дисков в Extended-разделе. Аналогичные  операции  выполняет  OS/2  boot  manager  при загрузке  OS/2  с  логических  дисков.  Дело  в том, что для логических дисков значение  hiddensectors  равно  63,  а для primary-разделов оно равно смещению диска от начала физического диска. Поэтому обычно нормальная загрузка возможна только  с  primary-дисков.  Чтобы  OS/2  могла грузиться с логического диска и чтобы  (если  используется  pre-LVM  версия  OS/2) назначалась правильно буква загрузочного диска, нужна помощь со стороны boot manager'а.  +
-    * До данного момента существовало  три  бутменеджера,  умеющих грузить OS/2 с логического диска:  +
-      - OS/2  bootmanager   +
-      - бутменеджер VPart от Veit'а Kannegieser'а  +
-      - AirBoot от Martin'а  Kiewitz'а.+
  
-Теперь  список  можно  дополнить  нашим MBR-загрузчикомкоторый  выполняет  роль  мини-бутменеджераНо наш MBR-загрузчик в отличие от настоящего  бутменеджера  не  позволяет диалоговый выбор загрузочного разделавместо  этого выбор загружаемого раздела у нас будет производиться из FreeLdr, который  будет  выполнять  функции  OS Loader'а и bootmanager'а одновременно и будет   грузиться   blackbox'ом  (То  есть это  будет  продвинутая  замена одновременно  для  OS/2  bootmanager'а  и  os2ldr  одновременно Идея  такого совмещенного  bootloader'а  и bootmanager'а впервые появилась в GNU GRUB, и мы хотим  следовать  аналогичному  принципу Преимущество  такого подхода прежде всего  в  том что  можно  из  одного  меню  выбирать  и  ОС для загрузки и различные  параметры  ОС,  которые  могут  из лоадера передаваться дальше ядру через  config.sys.  Кроме  того мы  сможем  выбирать  из  лоадера  несколько версий/сборок ядра и os2ldr, что также очень удобно.).+This bootloader must be located in sector zero of the first hard disk (MBR) and is designed to load the boot sector of the active partition or a partition with a given number on the specified hard disk. The MBR, having booted from the first hard drive, can choose which hard drive to continue booting from next. On the selected hard drive, the boot sector of the active partition, or a partition with a specific number, is loaded. The number of the next hard drive and the partition number on it are written in two bytes inside the MBR sector on the first hard drive. The active partition is determined by the first byte of the partition descriptor in the Partition table (PT). If this field is equal to 80h, then the section is considered active, but if it is equal to 00h, then the section is inactive. 
 + 
 +To boot from a primary or logical partition with a given number, the BootPart field in the MBR sector is intended, having a size of byte and located in the MBR at offset 0x1bb from the beginning of the sector. This field is written to the MBR when installing the bootloader. If this field is zero, this means that the bootloader must determine the active primary partition of the hard disk and load the boot sector from it, transferring control to it. If the BootPart field is non-zero, this is an indication to the bootloader to force the selection of a boot partition, logical or primary, without checking the activity byte in the partition table. In this case, the value of the BootPart byte is checked. If BootPart has a value from 1 to 4, then this number is interpreted as the number of the primary partition. If its value is 5 or more, then BootPart - 4 is the number of the logical disk inside the Extended partition. 
 + 
 +Thus, since the maximum value of the BootPart byte is 255, the number of logical disks can be from 0 to 255 - 4 = 251. That is, there can be a maximum of 3 primary partitions plus 1 extended and 251 logical disks inside extended. 
 + 
 +This bootloader uses LBA to load sectors from the hard drive into memory if LBA is supported. Otherwise, the BIOS feature is used to read sectors using CHS. 
 + 
 +Before the partition table, at offset 0x1bd, there is the ForceLBA byte. If this byte is not zero, then the LBA is forced. 
 + 
 +Before ForceLBA and after BootPart, at offset 0x1bc, there is the BootDev byte. It determines the physical device on which to look for the boot partition with the boot sector. The value of this byte is equal to the hard disk number in the format int 13h. For example, the first hard drive has the number 80h, the second 81h, etc. By default, this byte is 80h, that is, it boots from the first hard drive in the system. 
 + 
 +The partition table is located starting from the byte next to ForceLBA, at offset 0x1be, and, according to the standard, consists of 4 partition descriptors, each 16 bytes in size. 
 + 
 +The sector ends with an MBR signature of 0x55aa. These two bytes are intended to monitor the integrity of the MBR, as well as for convenience when searching for MBRs and bootsectors when restoring data on a crashed hard drive. 
 + 
 +This bootloader displays two messages in emergency situations. 
 + 
 +The first message – “R” (the first letter of the phrase “Read error”) is displayed when there are disk read errors, namely, if neither the LBA nor the CHS gave a successful status when reading a sector from the disk. 
 + 
 +The message “P” means “Partition not found” and is displayed when: 
 +  * No active partition found in partition table 
 +  * Extended partition not found and BootPart byte > 4 
 +  * Looking through the EBR (Extended boot records) chain, (!!! Fix it) the bootloader did not find a link to the next EBR and the current EBR, according to the value of the BootPart byte, is not the last one. 
 +  * The descriptor for the required section in the EBR was not found (should be marked with activity byte 80h). 
 +  * The descriptor in the MBR of the primary partition consists of zeros and does not describe any partition. 
 + 
 +The boot loader at startup (BIOS int 19h loads it at address 0x7c0:0x0) moves itself to address 0x60:0x0 and transfers control to the new address. The previous bootloader location (from 0x7c0:0x0 to 0x7e0:0x0 of sector size) is used as a buffer for loading sectors. The MBR of the first hard drive, the MBR of the next hard drive, the 1st EBR, the 2nd EBR, ..., the nth EBR and, finally, the boot partition boot sector are alternately loaded into this location. After this, control is transferred to the bootsector. 
 + 
 +The space from 0x7e0:0 to 0x800:0 is used by the MBR bootloader, as well as the boot sector, to store some variables. The stack used by both the MBR loader and the bootsector is as follows: ss = 0, the bottom of the stack is initialized to 0x7bff. 
 + 
 +This bootloader, after loading the bootsector, 'corrects' the hiddensectors value in BPB by adding to it the number of the first sector of the given logical disk (the same sector where the EBR is located, that is, 63 sectors before the bootsector). 
 + 
 +The MBR bootloader also enters the physical disk number and the number corresponding to the logical disk letter in the corresponding BPB fields of the bootsector. 
 + 
 +These manipulations are performed to make it possible to boot OS /2 from logical drives in the Extended partition. Similar operations are performed by the OS /2 boot manager when loading OS /2 from logical drives. The fact is that for logical disks the hiddensectors value is 63, and for primary partitions it is equal to the disk offset from the beginning of the physical disk. Therefore, normal booting is usually only possible from primary disks. To ensure that OS /2 can boot from a logical disk and that (if a pre-LVM version of OS /2 is used) the correct boot drive letter is assignedhelp is needed from the boot manager. 
 + 
 +Until now, there were three boot managers that could boot OS /2 from a logical disk: 
 + 
 +  * OS /2 bootmanager 
 +  * bootmanager of VPart from Veit Kannegieser 
 +  * AirBoot by Martin Kiewitz. 
 + 
 +Now the list can be supplemented with our MBR bootloader, which acts as a mini-boot manager. But our MBR bootloaderunlike a real bootmanager, does not allow interactive selection of the boot partition; instead, we will select the boot partition from FreeLdr, which will perform the functions of OS Loader and bootmanager at the same time and will be booted by blackbox. (That isit will be an advanced replacement for both OS / 2 bootmanager and os2ldr at the same timeThe idea of ​​such a combined bootloader and bootmanager first appeared in GNU GRUB, and we want to follow a similar principleThe advantage of this approach is primarily that that from one menu we can select both the OS to load and various OS parameterswhich can be passed from the loader to the kernel via config.sys.In additionwe will be able to select from the loader several versions/builds of the kernel and os2ldr, which is also very convenient. ).
  
 (c) osFree project, 2006, Oct 10. (c) osFree project, 2006, Oct 10.