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
184 extern unsigned char extlinux_bootsect[];
185 extern unsigned int extlinux_bootsect_len;
186 #define boot_block extlinux_bootsect
187 #define boot_block_len extlinux_bootsect_len
192 extern unsigned char extlinux_image[];
193 extern unsigned int extlinux_image_len;
194 #define boot_image extlinux_image
195 #define boot_image_len extlinux_image_len
198 * Common abort function
200 void __attribute__ ((noreturn)) die(const char *msg)
207 * read/write wrapper functions
209 ssize_t xpread(int fd, void *buf, size_t count, off_t offset)
211 char *bufp = (char *)buf;
216 rv = pread(fd, bufp, count, offset);
219 } else if (rv == -1) {
220 if (errno == EINTR) {
223 die(strerror(errno));
236 ssize_t xpwrite(int fd, const void *buf, size_t count, off_t offset)
238 const char *bufp = (const char *)buf;
243 rv = pwrite(fd, bufp, count, offset);
246 } else if (rv == -1) {
247 if (errno == EINTR) {
250 die(strerror(errno));
266 int sectmap(int fd, uint32_t * sectors, int nsectors)
268 unsigned int blksize, blk, nblk;
272 if (ioctl(fd, FIGETBSZ, &blksize))
275 /* Number of sectors per block */
276 blksize >>= SECTOR_SHIFT;
282 dprintf("querying block %u\n", blk);
283 if (ioctl(fd, FIBMAP, &blk))
287 for (i = 0; i < blksize; i++) {
291 dprintf("Sector: %10u\n", blk);
301 * Get the size of a block device
303 uint64_t get_size(int devfd)
310 if (!ioctl(devfd, BLKGETSIZE64, &bytes))
313 if (!ioctl(devfd, BLKGETSIZE, §s))
314 return (uint64_t) sects << 9;
315 else if (!fstat(devfd, &st) && st.st_size)
322 * Get device geometry and partition offset
324 struct geometry_table {
326 struct hd_geometry g;
329 /* Standard floppy disk geometries, plus LS-120. Zipdisk geometry
330 (x/64/32) is the final fallback. I don't know what LS-240 has
331 as its geometry, since I don't have one and don't know anyone that does,
332 and Google wasn't helpful... */
333 static const struct geometry_table standard_geometries[] = {
334 {360 * 1024, {2, 9, 40, 0}},
335 {720 * 1024, {2, 9, 80, 0}},
336 {1200 * 1024, {2, 15, 80, 0}},
337 {1440 * 1024, {2, 18, 80, 0}},
338 {1680 * 1024, {2, 21, 80, 0}},
339 {1722 * 1024, {2, 21, 80, 0}},
340 {2880 * 1024, {2, 36, 80, 0}},
341 {3840 * 1024, {2, 48, 80, 0}},
342 {123264 * 1024, {8, 32, 963, 0}}, /* LS120 */
346 int get_geometry(int devfd, uint64_t totalbytes, struct hd_geometry *geo)
348 struct floppy_struct fd_str;
349 const struct geometry_table *gp;
351 memset(geo, 0, sizeof *geo);
353 if (!ioctl(devfd, HDIO_GETGEO, &geo)) {
355 } else if (!ioctl(devfd, FDGETPRM, &fd_str)) {
356 geo->heads = fd_str.head;
357 geo->sectors = fd_str.sect;
358 geo->cylinders = fd_str.track;
363 /* Didn't work. Let's see if this is one of the standard geometries */
364 for (gp = standard_geometries; gp->bytes; gp++) {
365 if (gp->bytes == totalbytes) {
366 memcpy(geo, &gp->g, sizeof *geo);
371 /* Didn't work either... assign a geometry of 64 heads, 32 sectors; this is
372 what zipdisks use, so this would help if someone has a USB key that
373 they're booting in USB-ZIP mode. */
375 geo->heads = opt.heads ? : 64;
376 geo->sectors = opt.sectors ? : 32;
377 geo->cylinders = totalbytes / (geo->heads * geo->sectors << SECTOR_SHIFT);
380 if (!opt.sectors && !opt.heads)
382 "Warning: unable to obtain device geometry (defaulting to %d heads, %d sectors)\n"
383 " (on hard disks, this is usually harmless.)\n",
384 geo->heads, geo->sectors);
390 * Query the device geometry and put it into the boot sector.
391 * Map the file and put the map in the boot sector and file.
392 * Stick the "current directory" inode number into the file.
394 void patch_file_and_bootblock(int fd, int dirfd, int devfd)
397 struct hd_geometry geo;
399 uint64_t totalbytes, totalsectors;
401 unsigned char *p, *patcharea;
405 if (fstat(dirfd, &dirst)) {
406 perror("fstat dirfd");
407 exit(255); /* This should never happen */
410 totalbytes = get_size(devfd);
411 get_geometry(devfd, totalbytes, &geo);
414 geo.heads = opt.heads;
416 geo.sectors = opt.sectors;
418 /* Patch this into a fake FAT superblock. This isn't because
419 FAT is a good format in any way, it's because it lets the
420 early bootstrap share code with the FAT version. */
421 dprintf("heads = %u, sect = %u\n", geo.heads, geo.sectors);
423 totalsectors = totalbytes >> SECTOR_SHIFT;
424 if (totalsectors >= 65536) {
425 set_16(boot_block + bsSectors, 0);
427 set_16(boot_block + bsSectors, totalsectors);
429 set_32(boot_block + bsHugeSectors, totalsectors);
431 set_16(boot_block + bsBytesPerSec, SECTOR_SIZE);
432 set_16(boot_block + bsSecPerTrack, geo.sectors);
433 set_16(boot_block + bsHeads, geo.heads);
434 set_32(boot_block + bsHiddenSecs, geo.start);
436 /* If we're in RAID mode then patch the appropriate instruction;
437 either way write the proper boot signature */
438 i = get_16(boot_block + 0x1FE);
440 set_16(boot_block + i, 0x18CD); /* INT 18h */
442 set_16(boot_block + 0x1FE, 0xAA55);
444 /* Construct the boot file */
446 dprintf("directory inode = %lu\n", (unsigned long)dirst.st_ino);
447 nsect = (boot_image_len + SECTOR_SIZE - 1) >> SECTOR_SHIFT;
448 nsect += 2; /* Two sectors for the ADV */
449 sectp = alloca(sizeof(uint32_t) * nsect);
450 if (sectmap(fd, sectp, nsect)) {
455 /* First sector need pointer in boot sector */
456 set_32(boot_block + 0x1F8, *sectp++);
459 /* Search for LDLINUX_MAGIC to find the patch area */
460 for (p = boot_image; get_32(p) != LDLINUX_MAGIC; p += 4) ;
463 /* Set up the totals */
464 dw = boot_image_len >> 2; /* COMPLETE dwords, excluding ADV */
465 set_16(patcharea, dw);
466 set_16(patcharea + 2, nsect); /* Not including the first sector, but
468 set_32(patcharea + 8, dirst.st_ino); /* "Current" directory */
470 /* Set the sector pointers */
473 memset(p, 0, 64 * 4);
479 /* Now produce a checksum */
480 set_32(patcharea + 4, 0);
482 csum = LDLINUX_MAGIC;
483 for (i = 0, p = boot_image; i < dw; i++, p += 4)
484 csum -= get_32(p); /* Negative checksum */
486 set_32(patcharea + 4, csum);
490 * Read the ADV from an existing instance, or initialize if invalid.
491 * Returns -1 on fatal errors, 0 if ADV is okay, and 1 if no valid
494 int read_adv(const char *path)
501 asprintf(&file, "%s%sextlinux.sys",
502 path, path[0] && path[strlen(path) - 1] == '/' ? "" : "/");
509 fd = open(file, O_RDONLY);
511 if (errno != ENOENT) {
514 syslinux_reset_adv(syslinux_adv);
516 } else if (fstat(fd, &st)) {
518 } else if (st.st_size < 2 * ADV_SIZE) {
519 /* Too small to be useful */
520 syslinux_reset_adv(syslinux_adv);
521 err = 0; /* Nothing to read... */
522 } else if (xpread(fd, syslinux_adv, 2 * ADV_SIZE,
523 st.st_size - 2 * ADV_SIZE) != 2 * ADV_SIZE) {
526 /* We got it... maybe? */
527 err = syslinux_validate_adv(syslinux_adv) ? 1 : 0;
542 * Update the ADV in an existing installation.
544 int write_adv(const char *path)
546 unsigned char advtmp[2 * ADV_SIZE];
553 asprintf(&file, "%s%sextlinux.sys",
554 path, path[0] && path[strlen(path) - 1] == '/' ? "" : "/");
561 fd = open(file, O_RDONLY);
564 } else if (fstat(fd, &st)) {
566 } else if (st.st_size < 2 * ADV_SIZE) {
567 /* Too small to be useful */
569 } else if (xpread(fd, advtmp, 2 * ADV_SIZE,
570 st.st_size - 2 * ADV_SIZE) != 2 * ADV_SIZE) {
573 /* We got it... maybe? */
574 err = syslinux_validate_adv(advtmp) ? -2 : 0;
576 /* Got a good one, write our own ADV here */
577 if (!ioctl(fd, EXT2_IOC_GETFLAGS, &flags)) {
578 nflags = flags & ~EXT2_IMMUTABLE_FL;
580 ioctl(fd, EXT2_IOC_SETFLAGS, &nflags);
582 if (!(st.st_mode & S_IWUSR))
583 fchmod(fd, st.st_mode | S_IWUSR);
585 /* Need to re-open read-write */
587 fd = open(file, O_RDWR | O_SYNC);
590 } else if (fstat(fd, &xst) || xst.st_ino != st.st_ino ||
591 xst.st_dev != st.st_dev || xst.st_size != st.st_size) {
592 fprintf(stderr, "%s: race condition on write\n", file);
595 /* Write our own version ... */
596 if (xpwrite(fd, syslinux_adv, 2 * ADV_SIZE,
597 st.st_size - 2 * ADV_SIZE) != 2 * ADV_SIZE) {
603 if (!(st.st_mode & S_IWUSR))
604 fchmod(fd, st.st_mode);
607 ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
612 fprintf(stderr, "%s: cannot write auxilliary data (need --update)?\n",
626 * Make any user-specified ADV modifications
633 if (syslinux_setadv(ADV_BOOTONCE, strlen(opt.set_once), opt.set_once)) {
634 fprintf(stderr, "%s: not enough space for boot-once command\n",
644 * Install the boot block on the specified device.
645 * Must be run AFTER install_file()!
647 int install_bootblock(int fd, const char *device)
649 struct ext2_super_block sb;
651 if (xpread(fd, &sb, sizeof sb, EXT2_SUPER_OFFSET) != sizeof sb) {
652 perror("reading superblock");
656 if (sb.s_magic != EXT2_SUPER_MAGIC) {
657 fprintf(stderr, "no ext2/ext3 superblock found on %s\n", device);
661 if (xpwrite(fd, boot_block, boot_block_len, 0) != boot_block_len) {
662 perror("writing bootblock");
669 int install_file(const char *path, int devfd, struct stat *rst)
672 int fd = -1, dirfd = -1, flags;
675 asprintf(&file, "%s%sextlinux.sys",
676 path, path[0] && path[strlen(path) - 1] == '/' ? "" : "/");
682 dirfd = open(path, O_RDONLY | O_DIRECTORY);
688 fd = open(file, O_RDONLY);
690 if (errno != ENOENT) {
695 /* If file exist, remove the immutable flag and set u+w mode */
696 if (!ioctl(fd, EXT2_IOC_GETFLAGS, &flags)) {
697 flags &= ~EXT2_IMMUTABLE_FL;
698 ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
700 if (!fstat(fd, &st)) {
701 fchmod(fd, st.st_mode | S_IWUSR);
706 fd = open(file, O_WRONLY | O_TRUNC | O_CREAT | O_SYNC,
707 S_IRUSR | S_IRGRP | S_IROTH);
713 /* Write it the first time */
714 if (xpwrite(fd, boot_image, boot_image_len, 0) != boot_image_len ||
715 xpwrite(fd, syslinux_adv, 2 * ADV_SIZE,
716 boot_image_len) != 2 * ADV_SIZE) {
717 fprintf(stderr, "%s: write failure on %s\n", program, file);
721 /* Map the file, and patch the initial sector accordingly */
722 patch_file_and_bootblock(fd, dirfd, devfd);
724 /* Write the first sector again - this relies on the file being
725 overwritten in place! */
726 if (xpwrite(fd, boot_image, SECTOR_SIZE, 0) != SECTOR_SIZE) {
727 fprintf(stderr, "%s: write failure on %s\n", program, file);
731 /* Attempt to set immutable flag and remove all write access */
732 /* Only set immutable flag if file is owned by root */
733 if (!fstat(fd, &st)) {
734 fchmod(fd, st.st_mode & (S_IRUSR | S_IRGRP | S_IROTH));
735 if (st.st_uid == 0 && !ioctl(fd, EXT2_IOC_GETFLAGS, &flags)) {
736 flags |= EXT2_IMMUTABLE_FL;
737 ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
741 if (fstat(fd, rst)) {
759 /* EXTLINUX installs the string 'EXTLINUX' at offset 3 in the boot
760 sector; this is consistent with FAT filesystems. */
761 int already_installed(int devfd)
765 xpread(devfd, buffer, 8, 3);
766 return !memcmp(buffer, "EXTLINUX", 8);
770 static char devname_buf[64];
772 static void device_cleanup(void)
778 /* Verify that a device fd and a pathname agree.
779 Return 0 on valid, -1 on error. */
780 static int validate_device(const char *path, int devfd)
782 struct stat pst, dst;
784 if (stat(path, &pst) || fstat(devfd, &dst))
787 return (pst.st_dev == dst.st_rdev) ? 0 : -1;
791 static const char *find_device(const char *mtab_file, dev_t dev)
796 const char *devname = NULL;
798 mtab = setmntent(mtab_file, "r");
802 while ((mnt = getmntent(mtab))) {
803 if ((!strcmp(mnt->mnt_type, "ext2") ||
804 !strcmp(mnt->mnt_type, "ext3")) &&
805 !stat(mnt->mnt_fsname, &dst) && dst.st_rdev == dev) {
806 devname = strdup(mnt->mnt_fsname);
816 int install_loader(const char *path, int update_only)
820 const char *devname = NULL;
823 if (stat(path, &st) || !S_ISDIR(st.st_mode)) {
824 fprintf(stderr, "%s: Not a directory: %s\n", program, path);
828 if (statfs(path, &sfs)) {
829 fprintf(stderr, "%s: statfs %s: %s\n", program, path, strerror(errno));
833 if (sfs.f_type != EXT2_SUPER_MAGIC) {
834 fprintf(stderr, "%s: not an ext2/ext3 filesystem: %s\n", program, path);
842 /* klibc doesn't have getmntent and friends; instead, just create
843 a new device with the appropriate device type */
844 snprintf(devname_buf, sizeof devname_buf, "/tmp/dev-%u:%u",
845 major(st.st_dev), minor(st.st_dev));
847 if (mknod(devname_buf, S_IFBLK | 0600, st.st_dev)) {
848 fprintf(stderr, "%s: cannot create device %s\n", program, devname);
852 atexit(device_cleanup); /* unlink the device node on exit */
853 devname = devname_buf;
857 devname = find_device("/proc/mounts", st.st_dev);
859 /* Didn't find it in /proc/mounts, try /etc/mtab */
860 devname = find_device("/etc/mtab", st.st_dev);
863 fprintf(stderr, "%s: cannot find device for path %s\n", program, path);
867 fprintf(stderr, "%s is device %s\n", path, devname);
870 if ((devfd = open(devname, O_RDWR | O_SYNC)) < 0) {
871 fprintf(stderr, "%s: cannot open device %s\n", program, devname);
875 /* Verify that the device we opened is the device intended */
876 if (validate_device(path, devfd)) {
877 fprintf(stderr, "%s: path %s doesn't match device %s\n",
878 program, path, devname);
882 if (update_only && !already_installed(devfd)) {
883 fprintf(stderr, "%s: no previous extlinux boot sector found\n",
888 /* Read a pre-existing ADV, if already installed */
890 syslinux_reset_adv(syslinux_adv);
891 else if (read_adv(path) < 0)
894 if (modify_adv() < 0)
897 /* Install extlinux.sys */
898 if (install_file(path, devfd, &fst))
901 if (fst.st_dev != st.st_dev) {
902 fprintf(stderr, "%s: file system changed under us - aborting!\n",
908 rv = install_bootblock(devfd, devname);
916 * Modify the ADV of an existing installation
918 int modify_existing_adv(const char *path)
921 syslinux_reset_adv(syslinux_adv);
922 else if (read_adv(path) < 0)
925 if (modify_adv() < 0)
928 if (write_adv(path) < 0)
934 int main(int argc, char *argv[])
937 const char *directory;
938 int update_only = -1;
942 while ((o = getopt_long(argc, argv, short_options,
943 long_options, NULL)) != EOF) {
950 opt.sectors = strtoul(optarg, NULL, 0);
951 if (opt.sectors < 1 || opt.sectors > 63) {
953 "%s: invalid number of sectors: %u (must be 1-63)\n",
954 program, opt.sectors);
959 opt.heads = strtoul(optarg, NULL, 0);
960 if (opt.heads < 1 || opt.heads > 256) {
962 "%s: invalid number of heads: %u (must be 1-256)\n",
981 opt.set_once = optarg;
990 fputs("extlinux " VERSION_STR
991 " Copyright 1994-" YEAR_STR " H. Peter Anvin \n", stderr);
998 directory = argv[optind];
1003 if (update_only == -1) {
1004 if (opt.reset_adv || opt.set_once) {
1005 return modify_existing_adv(directory);
1011 return install_loader(directory, update_only);