1 /* ----------------------------------------------------------------------- *
3 * Copyright 1998-2008 H. Peter Anvin - All Rights Reserved
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, Inc., 53 Temple Place Ste 330,
8 * Boston MA 02111-1307, USA; either version 2 of the License, or
9 * (at your option) any later version; incorporated herein by reference.
11 * ----------------------------------------------------------------------- */
16 * Install the extlinux boot block on an ext2/3 filesystem
19 #define _GNU_SOURCE /* Enable everything */
21 /* This is needed to deal with the kernel headers imported into glibc 3.3.3. */
35 #include <sys/ioctl.h>
37 #include <sys/types.h>
38 #include <sys/mount.h>
41 #include <linux/fd.h> /* Floppy geometry */
42 #include <linux/hdreg.h> /* Hard disk geometry */
43 #define statfs _kernel_statfs /* HACK to deal with broken 2.4 distros */
44 #include <linux/fs.h> /* FIGETBSZ, FIBMAP */
48 #include "../version.h"
52 # define dprintf printf
54 # define dprintf(...) ((void)0)
57 /* Global option handling */
61 /* These are the options we can set and their values */
69 .sectors
= 0,.heads
= 0,.raid_mode
= 0,.reset_adv
= 0,.set_once
= NULL
,};
71 static void __attribute__ ((noreturn
)) usage(int rv
)
74 "Usage: %s [options] directory\n"
75 " --install -i Install over the current bootsector\n"
76 " --update -U Update a previous EXTLINUX installation\n"
77 " --zip -z Force zipdrive geometry (-H 64 -S 32)\n"
78 " --sectors=# -S Force the number of sectors per track\n"
79 " --heads=# -H Force number of heads\n"
80 " --raid -r Fall back to the next device on boot failure\n"
81 " --once=... -o Execute a command once upon boot\n"
82 " --clear-once -O Clear the boot-once command\n"
83 " --reset-adv Reset auxilliary data\n"
85 " Note: geometry is determined at boot time for devices which\n"
86 " are considered hard disks by the BIOS. Unfortunately, this is\n"
87 " not possible for devices which are considered floppy disks,\n"
88 " which includes zipdisks and LS-120 superfloppies.\n"
90 " The -z option is useful for USB devices which are considered\n"
91 " hard disks by some BIOSes and zipdrives by other BIOSes.\n",
102 static const struct option long_options
[] = {
103 {"install", 0, NULL
, 'i'},
104 {"update", 0, NULL
, 'U'},
105 {"zipdrive", 0, NULL
, 'z'},
106 {"sectors", 1, NULL
, 'S'},
107 {"heads", 1, NULL
, 'H'},
108 {"raid-mode", 0, NULL
, 'r'},
109 {"version", 0, NULL
, 'v'},
110 {"help", 0, NULL
, 'h'},
111 {"once", 1, NULL
, 'o'},
112 {"clear-once", 0, NULL
, 'O'},
113 {"reset-adv", 0, NULL
, OPT_RESET_ADV
},
117 static const char short_options
[] = "iUuzS:H:rvho:O";
119 #if defined(__linux__) && !defined(BLKGETSIZE64)
120 /* This takes a u64, but the size field says size_t. Someone screwed big. */
121 # define BLKGETSIZE64 _IOR(0x12,114,size_t)
124 #define LDLINUX_MAGIC 0x3eb202fe
129 bsBytesPerSec
= 0x0b,
130 bsSecPerClust
= 0x0d,
133 bsRootDirEnts
= 0x11,
137 bsSecPerTrack
= 0x18,
140 bsHugeSectors
= 0x20,
143 bs16DriveNumber
= 0x24,
144 bs16Reserved1
= 0x25,
145 bs16BootSignature
= 0x26,
147 bs16VolumeLabel
= 0x2b,
148 bs16FileSysType
= 0x36,
159 bs32DriveNumber
= 64,
161 bs32BootSignature
= 66,
163 bs32VolumeLabel
= 71,
164 bs32FileSysType
= 82,
170 #define bsHead bsJump
171 #define bsHeadLen (bsOemName-bsHead)
172 #define bsCode bs32Code /* The common safe choice */
173 #define bsCodeLen (bsSignature-bs32Code)
175 #ifndef EXT2_SUPER_OFFSET
176 #define EXT2_SUPER_OFFSET 1024
182 extern unsigned char extlinux_bootsect
[];
183 extern unsigned int extlinux_bootsect_len
;
184 #define boot_block extlinux_bootsect
185 #define boot_block_len extlinux_bootsect_len
190 extern unsigned char extlinux_image
[];
191 extern unsigned int extlinux_image_len
;
192 #define boot_image extlinux_image
193 #define boot_image_len extlinux_image_len
196 * Common abort function
198 void __attribute__ ((noreturn
)) die(const char *msg
)
205 * read/write wrapper functions
207 ssize_t
xpread(int fd
, void *buf
, size_t count
, off_t offset
)
209 char *bufp
= (char *)buf
;
214 rv
= pread(fd
, bufp
, count
, offset
);
217 } else if (rv
== -1) {
218 if (errno
== EINTR
) {
221 die(strerror(errno
));
234 ssize_t
xpwrite(int fd
, const void *buf
, size_t count
, off_t offset
)
236 const char *bufp
= (const char *)buf
;
241 rv
= pwrite(fd
, bufp
, count
, offset
);
244 } else if (rv
== -1) {
245 if (errno
== EINTR
) {
248 die(strerror(errno
));
264 int sectmap(int fd
, uint32_t * sectors
, int nsectors
)
266 unsigned int blksize
, blk
, nblk
;
270 if (ioctl(fd
, FIGETBSZ
, &blksize
))
273 /* Number of sectors per block */
274 blksize
>>= SECTOR_SHIFT
;
280 dprintf("querying block %u\n", blk
);
281 if (ioctl(fd
, FIBMAP
, &blk
))
285 for (i
= 0; i
< blksize
; i
++) {
289 dprintf("Sector: %10u\n", blk
);
299 * Get the size of a block device
301 uint64_t get_size(int devfd
)
308 if (!ioctl(devfd
, BLKGETSIZE64
, &bytes
))
311 if (!ioctl(devfd
, BLKGETSIZE
, §s
))
312 return (uint64_t) sects
<< 9;
313 else if (!fstat(devfd
, &st
) && st
.st_size
)
320 * Get device geometry and partition offset
322 struct geometry_table
{
324 struct hd_geometry g
;
327 /* Standard floppy disk geometries, plus LS-120. Zipdisk geometry
328 (x/64/32) is the final fallback. I don't know what LS-240 has
329 as its geometry, since I don't have one and don't know anyone that does,
330 and Google wasn't helpful... */
331 static const struct geometry_table standard_geometries
[] = {
332 {360 * 1024, {2, 9, 40, 0}},
333 {720 * 1024, {2, 9, 80, 0}},
334 {1200 * 1024, {2, 15, 80, 0}},
335 {1440 * 1024, {2, 18, 80, 0}},
336 {1680 * 1024, {2, 21, 80, 0}},
337 {1722 * 1024, {2, 21, 80, 0}},
338 {2880 * 1024, {2, 36, 80, 0}},
339 {3840 * 1024, {2, 48, 80, 0}},
340 {123264 * 1024, {8, 32, 963, 0}}, /* LS120 */
344 int get_geometry(int devfd
, uint64_t totalbytes
, struct hd_geometry
*geo
)
346 struct floppy_struct fd_str
;
347 const struct geometry_table
*gp
;
349 memset(geo
, 0, sizeof *geo
);
351 if (!ioctl(devfd
, HDIO_GETGEO
, &geo
)) {
353 } else if (!ioctl(devfd
, FDGETPRM
, &fd_str
)) {
354 geo
->heads
= fd_str
.head
;
355 geo
->sectors
= fd_str
.sect
;
356 geo
->cylinders
= fd_str
.track
;
361 /* Didn't work. Let's see if this is one of the standard geometries */
362 for (gp
= standard_geometries
; gp
->bytes
; gp
++) {
363 if (gp
->bytes
== totalbytes
) {
364 memcpy(geo
, &gp
->g
, sizeof *geo
);
369 /* Didn't work either... assign a geometry of 64 heads, 32 sectors; this is
370 what zipdisks use, so this would help if someone has a USB key that
371 they're booting in USB-ZIP mode. */
373 geo
->heads
= opt
.heads
? : 64;
374 geo
->sectors
= opt
.sectors
? : 32;
375 geo
->cylinders
= totalbytes
/ (geo
->heads
* geo
->sectors
<< SECTOR_SHIFT
);
378 if (!opt
.sectors
&& !opt
.heads
)
380 "Warning: unable to obtain device geometry (defaulting to %d heads, %d sectors)\n"
381 " (on hard disks, this is usually harmless.)\n",
382 geo
->heads
, geo
->sectors
);
388 * Query the device geometry and put it into the boot sector.
389 * Map the file and put the map in the boot sector and file.
390 * Stick the "current directory" inode number into the file.
392 void patch_file_and_bootblock(int fd
, int dirfd
, int devfd
)
395 struct hd_geometry geo
;
397 uint64_t totalbytes
, totalsectors
;
399 unsigned char *p
, *patcharea
;
403 if (fstat(dirfd
, &dirst
)) {
404 perror("fstat dirfd");
405 exit(255); /* This should never happen */
408 totalbytes
= get_size(devfd
);
409 get_geometry(devfd
, totalbytes
, &geo
);
412 geo
.heads
= opt
.heads
;
414 geo
.sectors
= opt
.sectors
;
416 /* Patch this into a fake FAT superblock. This isn't because
417 FAT is a good format in any way, it's because it lets the
418 early bootstrap share code with the FAT version. */
419 dprintf("heads = %u, sect = %u\n", geo
.heads
, geo
.sectors
);
421 totalsectors
= totalbytes
>> SECTOR_SHIFT
;
422 if (totalsectors
>= 65536) {
423 set_16(boot_block
+ bsSectors
, 0);
425 set_16(boot_block
+ bsSectors
, totalsectors
);
427 set_32(boot_block
+ bsHugeSectors
, totalsectors
);
429 set_16(boot_block
+ bsBytesPerSec
, SECTOR_SIZE
);
430 set_16(boot_block
+ bsSecPerTrack
, geo
.sectors
);
431 set_16(boot_block
+ bsHeads
, geo
.heads
);
432 set_32(boot_block
+ bsHiddenSecs
, geo
.start
);
434 /* If we're in RAID mode then patch the appropriate instruction;
435 either way write the proper boot signature */
436 i
= get_16(boot_block
+ 0x1FE);
438 set_16(boot_block
+ i
, 0x18CD); /* INT 18h */
440 set_16(boot_block
+ 0x1FE, 0xAA55);
442 /* Construct the boot file */
444 dprintf("directory inode = %lu\n", (unsigned long)dirst
.st_ino
);
445 nsect
= (boot_image_len
+ SECTOR_SIZE
- 1) >> SECTOR_SHIFT
;
446 nsect
+= 2; /* Two sectors for the ADV */
447 sectp
= alloca(sizeof(uint32_t) * nsect
);
448 if (sectmap(fd
, sectp
, nsect
)) {
453 /* First sector need pointer in boot sector */
454 set_32(boot_block
+ 0x1F8, *sectp
++);
457 /* Search for LDLINUX_MAGIC to find the patch area */
458 for (p
= boot_image
; get_32(p
) != LDLINUX_MAGIC
; p
+= 4) ;
461 /* Set up the totals */
462 dw
= boot_image_len
>> 2; /* COMPLETE dwords, excluding ADV */
463 set_16(patcharea
, dw
);
464 set_16(patcharea
+ 2, nsect
); /* Not including the first sector, but
466 set_32(patcharea
+ 8, dirst
.st_ino
); /* "Current" directory */
468 /* Set the sector pointers */
471 memset(p
, 0, 64 * 4);
477 /* Now produce a checksum */
478 set_32(patcharea
+ 4, 0);
480 csum
= LDLINUX_MAGIC
;
481 for (i
= 0, p
= boot_image
; i
< dw
; i
++, p
+= 4)
482 csum
-= get_32(p
); /* Negative checksum */
484 set_32(patcharea
+ 4, csum
);
488 * Read the ADV from an existing instance, or initialize if invalid.
489 * Returns -1 on fatal errors, 0 if ADV is okay, and 1 if no valid
492 int read_adv(const char *path
)
499 asprintf(&file
, "%s%sextlinux.sys",
500 path
, path
[0] && path
[strlen(path
) - 1] == '/' ? "" : "/");
507 fd
= open(file
, O_RDONLY
);
509 if (errno
!= ENOENT
) {
512 syslinux_reset_adv(syslinux_adv
);
514 } else if (fstat(fd
, &st
)) {
516 } else if (st
.st_size
< 2 * ADV_SIZE
) {
517 /* Too small to be useful */
518 syslinux_reset_adv(syslinux_adv
);
519 err
= 0; /* Nothing to read... */
520 } else if (xpread(fd
, syslinux_adv
, 2 * ADV_SIZE
,
521 st
.st_size
- 2 * ADV_SIZE
) != 2 * ADV_SIZE
) {
524 /* We got it... maybe? */
525 err
= syslinux_validate_adv(syslinux_adv
) ? 1 : 0;
540 * Update the ADV in an existing installation.
542 int write_adv(const char *path
)
544 unsigned char advtmp
[2 * ADV_SIZE
];
551 asprintf(&file
, "%s%sextlinux.sys",
552 path
, path
[0] && path
[strlen(path
) - 1] == '/' ? "" : "/");
559 fd
= open(file
, O_RDONLY
);
562 } else if (fstat(fd
, &st
)) {
564 } else if (st
.st_size
< 2 * ADV_SIZE
) {
565 /* Too small to be useful */
567 } else if (xpread(fd
, advtmp
, 2 * ADV_SIZE
,
568 st
.st_size
- 2 * ADV_SIZE
) != 2 * ADV_SIZE
) {
571 /* We got it... maybe? */
572 err
= syslinux_validate_adv(advtmp
) ? -2 : 0;
574 /* Got a good one, write our own ADV here */
575 if (!ioctl(fd
, EXT2_IOC_GETFLAGS
, &flags
)) {
576 nflags
= flags
& ~EXT2_IMMUTABLE_FL
;
578 ioctl(fd
, EXT2_IOC_SETFLAGS
, &nflags
);
580 if (!(st
.st_mode
& S_IWUSR
))
581 fchmod(fd
, st
.st_mode
| S_IWUSR
);
583 /* Need to re-open read-write */
585 fd
= open(file
, O_RDWR
| O_SYNC
);
588 } else if (fstat(fd
, &xst
) || xst
.st_ino
!= st
.st_ino
||
589 xst
.st_dev
!= st
.st_dev
|| xst
.st_size
!= st
.st_size
) {
590 fprintf(stderr
, "%s: race condition on write\n", file
);
593 /* Write our own version ... */
594 if (xpwrite(fd
, syslinux_adv
, 2 * ADV_SIZE
,
595 st
.st_size
- 2 * ADV_SIZE
) != 2 * ADV_SIZE
) {
601 if (!(st
.st_mode
& S_IWUSR
))
602 fchmod(fd
, st
.st_mode
);
605 ioctl(fd
, EXT2_IOC_SETFLAGS
, &flags
);
610 fprintf(stderr
, "%s: cannot write auxilliary data (need --update)?\n",
624 * Make any user-specified ADV modifications
631 if (syslinux_setadv(ADV_BOOTONCE
, strlen(opt
.set_once
), opt
.set_once
)) {
632 fprintf(stderr
, "%s: not enough space for boot-once command\n",
642 * Install the boot block on the specified device.
643 * Must be run AFTER install_file()!
645 int install_bootblock(int fd
, const char *device
)
647 struct ext2_super_block sb
;
649 if (xpread(fd
, &sb
, sizeof sb
, EXT2_SUPER_OFFSET
) != sizeof sb
) {
650 perror("reading superblock");
654 if (sb
.s_magic
!= EXT2_SUPER_MAGIC
) {
655 fprintf(stderr
, "no ext2/ext3 superblock found on %s\n", device
);
659 if (xpwrite(fd
, boot_block
, boot_block_len
, 0) != boot_block_len
) {
660 perror("writing bootblock");
667 int install_file(const char *path
, int devfd
, struct stat
*rst
)
670 int fd
= -1, dirfd
= -1, flags
;
673 asprintf(&file
, "%s%sextlinux.sys",
674 path
, path
[0] && path
[strlen(path
) - 1] == '/' ? "" : "/");
680 dirfd
= open(path
, O_RDONLY
| O_DIRECTORY
);
686 fd
= open(file
, O_RDONLY
);
688 if (errno
!= ENOENT
) {
693 /* If file exist, remove the immutable flag and set u+w mode */
694 if (!ioctl(fd
, EXT2_IOC_GETFLAGS
, &flags
)) {
695 flags
&= ~EXT2_IMMUTABLE_FL
;
696 ioctl(fd
, EXT2_IOC_SETFLAGS
, &flags
);
698 if (!fstat(fd
, &st
)) {
699 fchmod(fd
, st
.st_mode
| S_IWUSR
);
704 fd
= open(file
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_SYNC
,
705 S_IRUSR
| S_IRGRP
| S_IROTH
);
711 /* Write it the first time */
712 if (xpwrite(fd
, boot_image
, boot_image_len
, 0) != boot_image_len
||
713 xpwrite(fd
, syslinux_adv
, 2 * ADV_SIZE
,
714 boot_image_len
) != 2 * ADV_SIZE
) {
715 fprintf(stderr
, "%s: write failure on %s\n", program
, file
);
719 /* Map the file, and patch the initial sector accordingly */
720 patch_file_and_bootblock(fd
, dirfd
, devfd
);
722 /* Write the first sector again - this relies on the file being
723 overwritten in place! */
724 if (xpwrite(fd
, boot_image
, SECTOR_SIZE
, 0) != SECTOR_SIZE
) {
725 fprintf(stderr
, "%s: write failure on %s\n", program
, file
);
729 /* Attempt to set immutable flag and remove all write access */
730 /* Only set immutable flag if file is owned by root */
731 if (!fstat(fd
, &st
)) {
732 fchmod(fd
, st
.st_mode
& (S_IRUSR
| S_IRGRP
| S_IROTH
));
733 if (st
.st_uid
== 0 && !ioctl(fd
, EXT2_IOC_GETFLAGS
, &flags
)) {
734 flags
|= EXT2_IMMUTABLE_FL
;
735 ioctl(fd
, EXT2_IOC_SETFLAGS
, &flags
);
739 if (fstat(fd
, rst
)) {
757 /* EXTLINUX installs the string 'EXTLINUX' at offset 3 in the boot
758 sector; this is consistent with FAT filesystems. */
759 int already_installed(int devfd
)
763 xpread(devfd
, buffer
, 8, 3);
764 return !memcmp(buffer
, "EXTLINUX", 8);
768 static char devname_buf
[64];
770 static void device_cleanup(void)
776 /* Verify that a device fd and a pathname agree.
777 Return 0 on valid, -1 on error. */
778 static int validate_device(const char *path
, int devfd
)
780 struct stat pst
, dst
;
782 if (stat(path
, &pst
) || fstat(devfd
, &dst
))
785 return (pst
.st_dev
== dst
.st_rdev
) ? 0 : -1;
789 static const char *find_device(const char *mtab_file
, dev_t dev
)
794 const char *devname
= NULL
;
796 mtab
= setmntent(mtab_file
, "r");
800 while ((mnt
= getmntent(mtab
))) {
801 if ((!strcmp(mnt
->mnt_type
, "ext2") ||
802 !strcmp(mnt
->mnt_type
, "ext3")) &&
803 !stat(mnt
->mnt_fsname
, &dst
) && dst
.st_rdev
== dev
) {
804 devname
= strdup(mnt
->mnt_fsname
);
814 int install_loader(const char *path
, int update_only
)
818 const char *devname
= NULL
;
821 if (stat(path
, &st
) || !S_ISDIR(st
.st_mode
)) {
822 fprintf(stderr
, "%s: Not a directory: %s\n", program
, path
);
826 if (statfs(path
, &sfs
)) {
827 fprintf(stderr
, "%s: statfs %s: %s\n", program
, path
, strerror(errno
));
831 if (sfs
.f_type
!= EXT2_SUPER_MAGIC
) {
832 fprintf(stderr
, "%s: not an ext2/ext3 filesystem: %s\n", program
, path
);
840 /* klibc doesn't have getmntent and friends; instead, just create
841 a new device with the appropriate device type */
842 snprintf(devname_buf
, sizeof devname_buf
, "/tmp/dev-%u:%u",
843 major(st
.st_dev
), minor(st
.st_dev
));
845 if (mknod(devname_buf
, S_IFBLK
| 0600, st
.st_dev
)) {
846 fprintf(stderr
, "%s: cannot create device %s\n", program
, devname
);
850 atexit(device_cleanup
); /* unlink the device node on exit */
851 devname
= devname_buf
;
855 devname
= find_device("/proc/mounts", st
.st_dev
);
857 /* Didn't find it in /proc/mounts, try /etc/mtab */
858 devname
= find_device("/etc/mtab", st
.st_dev
);
861 fprintf(stderr
, "%s: cannot find device for path %s\n", program
, path
);
865 fprintf(stderr
, "%s is device %s\n", path
, devname
);
868 if ((devfd
= open(devname
, O_RDWR
| O_SYNC
)) < 0) {
869 fprintf(stderr
, "%s: cannot open device %s\n", program
, devname
);
873 /* Verify that the device we opened is the device intended */
874 if (validate_device(path
, devfd
)) {
875 fprintf(stderr
, "%s: path %s doesn't match device %s\n",
876 program
, path
, devname
);
880 if (update_only
&& !already_installed(devfd
)) {
881 fprintf(stderr
, "%s: no previous extlinux boot sector found\n",
886 /* Read a pre-existing ADV, if already installed */
888 syslinux_reset_adv(syslinux_adv
);
889 else if (read_adv(path
) < 0)
892 if (modify_adv() < 0)
895 /* Install extlinux.sys */
896 if (install_file(path
, devfd
, &fst
))
899 if (fst
.st_dev
!= st
.st_dev
) {
900 fprintf(stderr
, "%s: file system changed under us - aborting!\n",
906 rv
= install_bootblock(devfd
, devname
);
914 * Modify the ADV of an existing installation
916 int modify_existing_adv(const char *path
)
919 syslinux_reset_adv(syslinux_adv
);
920 else if (read_adv(path
) < 0)
923 if (modify_adv() < 0)
926 if (write_adv(path
) < 0)
932 int main(int argc
, char *argv
[])
935 const char *directory
;
936 int update_only
= -1;
940 while ((o
= getopt_long(argc
, argv
, short_options
,
941 long_options
, NULL
)) != EOF
) {
948 opt
.sectors
= strtoul(optarg
, NULL
, 0);
949 if (opt
.sectors
< 1 || opt
.sectors
> 63) {
951 "%s: invalid number of sectors: %u (must be 1-63)\n",
952 program
, opt
.sectors
);
957 opt
.heads
= strtoul(optarg
, NULL
, 0);
958 if (opt
.heads
< 1 || opt
.heads
> 256) {
960 "%s: invalid number of heads: %u (must be 1-256)\n",
979 opt
.set_once
= optarg
;
988 fputs("extlinux " VERSION_STR
989 " Copyright 1994-" YEAR_STR
" H. Peter Anvin \n", stderr
);
996 directory
= argv
[optind
];
1001 if (update_only
== -1) {
1002 if (opt
.reset_adv
|| opt
.set_once
) {
1003 return modify_existing_adv(directory
);
1009 return install_loader(directory
, update_only
);