嵌入式 Linux 常需要格式化硬盤,最常用的工具莫過於 fdisk,busybox 裡也實作了一版。不過 busybox 的 fdisk 是簡化版,和 GNU 原版差異不小,缺的多半是細節功能——例如寫入磁盤可選 ID 這件事,就得自己動手。
MBR 的開頭 440 個位元組是開機碼,緊接著的 4 個位元組是 disk signature(可選),也就是本文要操作的區域,它能用來唯一標記一塊硬盤,共有 2 的 32 次方種取值。MBR 結構如下(摘自維基百科):
Structure of a master boot record
Address Description Size in bytes
Hex Oct Dec
0000 0000 0 code area 440 (max. 446)
01B8 0670 440 disk signature (optional) 4 ← 本文重點
01BC 0674 444 Usually nulls; 0x0000 2
01BE 0676 446 Table of primary partitions
(Four 16-byte entries, IBM scheme) 64
01FE 0776 510 55h MBR signature 2
01FF 0777 511 AAh (共 512)
MBR total: 446 + 64 + 2 = 512
要讀寫這塊區域,位址是 440–443,剛好 4 個位元組,用一個 int 變數就能一次讀出。
int main(void)
{
int fd;
unsigned int id;
fd = open("/dev/sda", O_RDONLY);
if (fd < 0) {
perror("open");
exit(1);
}
lseek(fd, 440, SEEK_SET);
if (read(fd, &id, 4) != 4) {
perror("read");
close(fd);
exit(1);
}
close(fd);
return 0;
}
既然 busybox 未必提供這個功能,需要標記硬盤時就自己造一個隨機數。GNU fdisk 的做法是向 /dev/urandom 取亂數,取不到才退回「行程 PID 加當前 Unix 時間」的折衷方案:
static unsigned int get_random_id(void) {
int fd;
unsigned int v;
ssize_t rv = -1;
fd = open("/dev/urandom", O_RDONLY);
if (fd >= 0) {
rv = read(fd, &v, sizeof v);
close(fd);
}
if (rv == sizeof v)
return v;
/* Fallback: 不理想,但聊勝於無 */
return (unsigned int)(getpid() + time(NULL));
}
有了 ID 之後,把它寫進 MBR 的可選區域:
int main(void)
{
int fd;
unsigned int id;
id = get_random_id();
fd = open("/dev/sda", O_RDONLY);
if (fd < 0) {
perror("open");
exit(1);
}
lseek(fd, 440, SEEK_SET);
if (write(fd, &id, 4) != 4) {
perror("write");
close(fd);
exit(1);
}
close(fd);
return 0;
}
寫入時一定要明確指定 4 個位元組,長度寫錯可能造成越界,波及後面的分割表而讓整顆硬盤無法開機。好消息是這個區域本來就是保留給系統商自由使用的,寫入 ID 不影響 MBR 的正常開機流程。