1 /* ----------------------------------------------------------------------- *
3 * Copyright 1998-2008 H. Peter Anvin - All Rights Reserved
4 * Copyright 2009 Intel Corporation; author: H. Peter Anvin
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, Inc., 53 Temple Place Ste 330,
9 * Boston MA 02111-1307, USA; either version 2 of the License, or
10 * (at your option) any later version; incorporated herein by reference.
12 * ----------------------------------------------------------------------- */
17 * Install the extlinux boot block on an ext2/3 filesystem
20 #define _GNU_SOURCE /* Enable everything */
22 /* This is needed to deal with the kernel headers imported into glibc 3.3.3. */
36 #include <sys/ioctl.h>
38 #include <sys/types.h>
39 #include <sys/mount.h>
42 #include <linux/fd.h> /* Floppy geometry */
43 #include <linux/hdreg.h> /* Hard disk geometry */
44 #define statfs _kernel_statfs /* HACK to deal with broken 2.4 distros */
45 #include <linux/fs.h> /* FIGETBSZ, FIBMAP */
49 #include "../version.h"
53 # define dprintf printf
55 # define dprintf(...) ((void)0)
58 /* Global option handling */
62 /* These are the options we can set and their values */
71 .sectors = 0,.heads = 0,.raid_mode = 0,.stupid_mode = 0,.reset_adv =
74 static void __attribute__ ((noreturn)) usage(int rv)
77 "Usage: %s [options] directory\n"
78 " --install -i Install over the current bootsector\n"
79 " --update -U Update a previous EXTLINUX installation\n"
80 " --zip -z Force zipdrive geometry (-H 64 -S 32)\n"
81 " --sectors=# -S Force the number of sectors per track\n"
82 " --heads=# -H Force number of heads\n"
83 " --stupid -s Slow, safe and stupid mode\n"
84 " --raid -r Fall back to the next device on boot failure\n"
85 " --once=... -o Execute a command once upon boot\n"
86 " --clear-once -O Clear the boot-once command\n"
87 " --reset-adv Reset auxilliary data\n"
89 " Note: geometry is determined at boot time for devices which\n"
90 " are considered hard disks by the BIOS. Unfortunately, this is\n"
91 " not possible for devices which are considered floppy disks,\n"
92 " which includes zipdisks and LS-120 superfloppies.\n"
94 " The -z option is useful for USB devices which are considered\n"
95 " hard disks by some BIOSes and zipdrives by other BIOSes.\n",
106 static const struct option long_options[] = {
107 {"install", 0, NULL, 'i'},
108 {"update", 0, NULL, 'U'},
109 {"zipdrive", 0, NULL, 'z'},
110 {"sectors", 1, NULL, 'S'},
111 {"stupid", 0, NULL, 's'},
112 {"heads", 1, NULL, 'H'},
113 {"raid-mode", 0, NULL, 'r'},
114 {"version", 0, NULL, 'v'},
115 {"help", 0, NULL, 'h'},
116 {"once", 1, NULL, 'o'},
117 {"clear-once", 0, NULL, 'O'},
118 {"reset-adv", 0, NULL, OPT_RESET_ADV},
122 static const char short_options[] = "iUuzS:H:rvho:O";
124 #if defined(__linux__) && !defined(BLKGETSIZE64)
125 /* This takes a u64, but the size field says size_t. Someone screwed big. */
126 # define BLKGETSIZE64 _IOR(0x12,114,size_t)
129 #ifndef EXT2_SUPER_OFFSET
130 #define EXT2_SUPER_OFFSET 1024
136 extern unsigned char extlinux_bootsect[];
137 extern unsigned int extlinux_bootsect_len;
138 #define boot_block extlinux_bootsect
139 #define boot_block_len extlinux_bootsect_len
144 extern unsigned char extlinux_image[];
145 extern unsigned int extlinux_image_len;
146 #define boot_image extlinux_image
147 #define boot_image_len extlinux_image_len
150 * Common abort function
152 void __attribute__ ((noreturn)) die(const char *msg)
159 * read/write wrapper functions
161 ssize_t xpread(int fd, void *buf, size_t count, off_t offset)
163 char *bufp = (char *)buf;
168 rv = pread(fd, bufp, count, offset);
171 } else if (rv == -1) {
172 if (errno == EINTR) {
175 die(strerror(errno));
188 ssize_t xpwrite(int fd, const void *buf, size_t count, off_t offset)
190 const char *bufp = (const char *)buf;
195 rv = pwrite(fd, bufp, count, offset);
198 } else if (rv == -1) {
199 if (errno == EINTR) {
202 die(strerror(errno));
218 int sectmap(int fd, uint32_t * sectors, int nsectors)
220 unsigned int blksize, blk, nblk;
224 if (ioctl(fd, FIGETBSZ, &blksize))
227 /* Number of sectors per block */
228 blksize >>= SECTOR_SHIFT;
234 dprintf("querying block %u\n", blk);
235 if (ioctl(fd, FIBMAP, &blk))
239 for (i = 0; i < blksize; i++) {
243 dprintf("Sector: %10u\n", blk);
253 * Get the size of a block device
255 uint64_t get_size(int devfd)
262 if (!ioctl(devfd, BLKGETSIZE64, &bytes))
265 if (!ioctl(devfd, BLKGETSIZE, §s))
266 return (uint64_t) sects << 9;
267 else if (!fstat(devfd, &st) && st.st_size)
274 * Get device geometry and partition offset
276 struct geometry_table {
278 struct hd_geometry g;
281 /* Standard floppy disk geometries, plus LS-120. Zipdisk geometry
282 (x/64/32) is the final fallback. I don't know what LS-240 has
283 as its geometry, since I don't have one and don't know anyone that does,
284 and Google wasn't helpful... */
285 static const struct geometry_table standard_geometries[] = {
286 {360 * 1024, {2, 9, 40, 0}},
287 {720 * 1024, {2, 9, 80, 0}},
288 {1200 * 1024, {2, 15, 80, 0}},
289 {1440 * 1024, {2, 18, 80, 0}},
290 {1680 * 1024, {2, 21, 80, 0}},
291 {1722 * 1024, {2, 21, 80, 0}},
292 {2880 * 1024, {2, 36, 80, 0}},
293 {3840 * 1024, {2, 48, 80, 0}},
294 {123264 * 1024, {8, 32, 963, 0}}, /* LS120 */
298 int get_geometry(int devfd, uint64_t totalbytes, struct hd_geometry *geo)
300 struct floppy_struct fd_str;
301 const struct geometry_table *gp;
303 memset(geo, 0, sizeof *geo);
305 if (!ioctl(devfd, HDIO_GETGEO, &geo)) {
307 } else if (!ioctl(devfd, FDGETPRM, &fd_str)) {
308 geo->heads = fd_str.head;
309 geo->sectors = fd_str.sect;
310 geo->cylinders = fd_str.track;
315 /* Didn't work. Let's see if this is one of the standard geometries */
316 for (gp = standard_geometries; gp->bytes; gp++) {
317 if (gp->bytes == totalbytes) {
318 memcpy(geo, &gp->g, sizeof *geo);
323 /* Didn't work either... assign a geometry of 64 heads, 32 sectors; this is
324 what zipdisks use, so this would help if someone has a USB key that
325 they're booting in USB-ZIP mode. */
327 geo->heads = opt.heads ? : 64;
328 geo->sectors = opt.sectors ? : 32;
329 geo->cylinders = totalbytes / (geo->heads * geo->sectors << SECTOR_SHIFT);
332 if (!opt.sectors && !opt.heads)
334 "Warning: unable to obtain device geometry (defaulting to %d heads, %d sectors)\n"
335 " (on hard disks, this is usually harmless.)\n",
336 geo->heads, geo->sectors);
342 * Query the device geometry and put it into the boot sector.
343 * Map the file and put the map in the boot sector and file.
344 * Stick the "current directory" inode number into the file.
346 void patch_file_and_bootblock(int fd, int dirfd, int devfd)
349 struct hd_geometry geo;
351 uint64_t totalbytes, totalsectors;
354 struct boot_sector *bs;
355 struct patch_area *patcharea;
359 if (fstat(dirfd, &dirst)) {
360 perror("fstat dirfd");
361 exit(255); /* This should never happen */
364 totalbytes = get_size(devfd);
365 get_geometry(devfd, totalbytes, &geo);
368 geo.heads = opt.heads;
370 geo.sectors = opt.sectors;
372 /* Patch this into a fake FAT superblock. This isn't because
373 FAT is a good format in any way, it's because it lets the
374 early bootstrap share code with the FAT version. */
375 dprintf("heads = %u, sect = %u\n", geo.heads, geo.sectors);
377 bs = (struct boot_sector *)boot_block;
379 totalsectors = totalbytes >> SECTOR_SHIFT;
380 if (totalsectors >= 65536) {
381 set_16(&bs->bsSectors, 0);
383 set_16(&bs->bsSectors, totalsectors);
385 set_32(&bs->bsHugeSectors, totalsectors);
387 set_16(&bs->bsBytesPerSec, SECTOR_SIZE);
388 set_16(&bs->bsSecPerTrack, geo.sectors);
389 set_16(&bs->bsHeads, geo.heads);
390 set_32(&bs->bsHiddenSecs, geo.start);
392 /* If we're in RAID mode then patch the appropriate instruction;
393 either way write the proper boot signature */
394 i = get_16(&bs->bsSignature);
396 set_16((uint16_t *) (boot_block + i), 0x18CD); /* INT 18h */
398 set_16(&bs->bsSignature, 0xAA55);
400 /* Construct the boot file */
402 dprintf("directory inode = %lu\n", (unsigned long)dirst.st_ino);
403 nsect = (boot_image_len + SECTOR_SIZE - 1) >> SECTOR_SHIFT;
404 nsect += 2; /* Two sectors for the ADV */
405 sectp = alloca(sizeof(uint32_t) * nsect);
406 if (sectmap(fd, sectp, nsect)) {
411 /* First sector need pointer in boot sector */
412 set_32(&bs->NextSector, *sectp++);
416 set_16(&bs->MaxTransfer, 1);
418 /* Search for LDLINUX_MAGIC to find the patch area */
419 for (wp = (uint32_t *) boot_image; get_32(wp) != LDLINUX_MAGIC; wp++) ;
420 patcharea = (struct patch_area *)wp;
422 /* Set up the totals */
423 dw = boot_image_len >> 2; /* COMPLETE dwords, excluding ADV */
424 set_16(&patcharea->data_sectors, nsect - 2); /* -2 for the ADVs */
425 set_16(&patcharea->adv_sectors, 2);
426 set_32(&patcharea->dwords, dw);
427 set_32(&patcharea->currentdir, dirst.st_ino);
429 /* Set the sector pointers */
430 wp = (uint32_t *) ((char *)boot_image + get_16(&patcharea->secptroffset));
431 nptrs = get_16(&patcharea->secptrcnt);
433 memset(wp, 0, nptrs * 4);
435 set_32(wp++, *sectp++);
437 /* Now produce a checksum */
438 set_32(&patcharea->checksum, 0);
440 csum = LDLINUX_MAGIC;
441 for (i = 0, wp = (uint32_t *) boot_image; i < dw; i++, wp++)
442 csum -= get_32(wp); /* Negative checksum */
444 set_32(&patcharea->checksum, csum);
448 * Read the ADV from an existing instance, or initialize if invalid.
449 * Returns -1 on fatal errors, 0 if ADV is okay, and 1 if no valid
452 int read_adv(const char *path)
459 asprintf(&file, "%s%sextlinux.sys",
460 path, path[0] && path[strlen(path) - 1] == '/' ? "" : "/");
467 fd = open(file, O_RDONLY);
469 if (errno != ENOENT) {
472 syslinux_reset_adv(syslinux_adv);
474 } else if (fstat(fd, &st)) {
476 } else if (st.st_size < 2 * ADV_SIZE) {
477 /* Too small to be useful */
478 syslinux_reset_adv(syslinux_adv);
479 err = 0; /* Nothing to read... */
480 } else if (xpread(fd, syslinux_adv, 2 * ADV_SIZE,
481 st.st_size - 2 * ADV_SIZE) != 2 * ADV_SIZE) {
484 /* We got it... maybe? */
485 err = syslinux_validate_adv(syslinux_adv) ? 1 : 0;
500 * Update the ADV in an existing installation.
502 int write_adv(const char *path)
504 unsigned char advtmp[2 * ADV_SIZE];
511 asprintf(&file, "%s%sextlinux.sys",
512 path, path[0] && path[strlen(path) - 1] == '/' ? "" : "/");
519 fd = open(file, O_RDONLY);
522 } else if (fstat(fd, &st)) {
524 } else if (st.st_size < 2 * ADV_SIZE) {
525 /* Too small to be useful */
527 } else if (xpread(fd, advtmp, 2 * ADV_SIZE,
528 st.st_size - 2 * ADV_SIZE) != 2 * ADV_SIZE) {
531 /* We got it... maybe? */
532 err = syslinux_validate_adv(advtmp) ? -2 : 0;
534 /* Got a good one, write our own ADV here */
535 if (!ioctl(fd, EXT2_IOC_GETFLAGS, &flags)) {
536 nflags = flags & ~EXT2_IMMUTABLE_FL;
538 ioctl(fd, EXT2_IOC_SETFLAGS, &nflags);
540 if (!(st.st_mode & S_IWUSR))
541 fchmod(fd, st.st_mode | S_IWUSR);
543 /* Need to re-open read-write */
545 fd = open(file, O_RDWR | O_SYNC);
548 } else if (fstat(fd, &xst) || xst.st_ino != st.st_ino ||
549 xst.st_dev != st.st_dev || xst.st_size != st.st_size) {
550 fprintf(stderr, "%s: race condition on write\n", file);
553 /* Write our own version ... */
554 if (xpwrite(fd, syslinux_adv, 2 * ADV_SIZE,
555 st.st_size - 2 * ADV_SIZE) != 2 * ADV_SIZE) {
561 if (!(st.st_mode & S_IWUSR))
562 fchmod(fd, st.st_mode);
565 ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
570 fprintf(stderr, "%s: cannot write auxilliary data (need --update)?\n",
584 * Make any user-specified ADV modifications
591 if (syslinux_setadv(ADV_BOOTONCE, strlen(opt.set_once), opt.set_once)) {
592 fprintf(stderr, "%s: not enough space for boot-once command\n",
602 * Install the boot block on the specified device.
603 * Must be run AFTER install_file()!
605 int install_bootblock(int fd, const char *device)
607 struct ext2_super_block sb;
609 if (xpread(fd, &sb, sizeof sb, EXT2_SUPER_OFFSET) != sizeof sb) {
610 perror("reading superblock");
614 if (sb.s_magic != EXT2_SUPER_MAGIC) {
615 fprintf(stderr, "no ext2/ext3 superblock found on %s\n", device);
619 if (xpwrite(fd, boot_block, boot_block_len, 0) != boot_block_len) {
620 perror("writing bootblock");
627 int install_file(const char *path, int devfd, struct stat *rst)
630 int fd = -1, dirfd = -1, flags;
633 asprintf(&file, "%s%sextlinux.sys",
634 path, path[0] && path[strlen(path) - 1] == '/' ? "" : "/");
640 dirfd = open(path, O_RDONLY | O_DIRECTORY);
646 fd = open(file, O_RDONLY);
648 if (errno != ENOENT) {
653 /* If file exist, remove the immutable flag and set u+w mode */
654 if (!ioctl(fd, EXT2_IOC_GETFLAGS, &flags)) {
655 flags &= ~EXT2_IMMUTABLE_FL;
656 ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
658 if (!fstat(fd, &st)) {
659 fchmod(fd, st.st_mode | S_IWUSR);
664 fd = open(file, O_WRONLY | O_TRUNC | O_CREAT | O_SYNC,
665 S_IRUSR | S_IRGRP | S_IROTH);
671 /* Write it the first time */
672 if (xpwrite(fd, boot_image, boot_image_len, 0) != boot_image_len ||
673 xpwrite(fd, syslinux_adv, 2 * ADV_SIZE,
674 boot_image_len) != 2 * ADV_SIZE) {
675 fprintf(stderr, "%s: write failure on %s\n", program, file);
679 /* Map the file, and patch the initial sector accordingly */
680 patch_file_and_bootblock(fd, dirfd, devfd);
682 /* Write the first sector again - this relies on the file being
683 overwritten in place! */
684 if (xpwrite(fd, boot_image, SECTOR_SIZE, 0) != SECTOR_SIZE) {
685 fprintf(stderr, "%s: write failure on %s\n", program, file);
689 /* Attempt to set immutable flag and remove all write access */
690 /* Only set immutable flag if file is owned by root */
691 if (!fstat(fd, &st)) {
692 fchmod(fd, st.st_mode & (S_IRUSR | S_IRGRP | S_IROTH));
693 if (st.st_uid == 0 && !ioctl(fd, EXT2_IOC_GETFLAGS, &flags)) {
694 flags |= EXT2_IMMUTABLE_FL;
695 ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
699 if (fstat(fd, rst)) {
717 /* EXTLINUX installs the string 'EXTLINUX' at offset 3 in the boot
718 sector; this is consistent with FAT filesystems. */
719 int already_installed(int devfd)
723 xpread(devfd, buffer, 8, 3);
724 return !memcmp(buffer, "EXTLINUX", 8);
728 static char devname_buf[64];
730 static void device_cleanup(void)
736 /* Verify that a device fd and a pathname agree.
737 Return 0 on valid, -1 on error. */
738 static int validate_device(const char *path, int devfd)
740 struct stat pst, dst;
742 if (stat(path, &pst) || fstat(devfd, &dst))
745 return (pst.st_dev == dst.st_rdev) ? 0 : -1;
749 static const char *find_device(const char *mtab_file, dev_t dev)
754 const char *devname = NULL;
756 mtab = setmntent(mtab_file, "r");
760 while ((mnt = getmntent(mtab))) {
761 if ((!strcmp(mnt->mnt_type, "ext2") ||
762 !strcmp(mnt->mnt_type, "ext3")) &&
763 !stat(mnt->mnt_fsname, &dst) && dst.st_rdev == dev) {
764 devname = strdup(mnt->mnt_fsname);
774 int install_loader(const char *path, int update_only)
778 const char *devname = NULL;
781 if (stat(path, &st) || !S_ISDIR(st.st_mode)) {
782 fprintf(stderr, "%s: Not a directory: %s\n", program, path);
786 if (statfs(path, &sfs)) {
787 fprintf(stderr, "%s: statfs %s: %s\n", program, path, strerror(errno));
791 if (sfs.f_type != EXT2_SUPER_MAGIC) {
792 fprintf(stderr, "%s: not an ext2/ext3 filesystem: %s\n", program, path);
800 /* klibc doesn't have getmntent and friends; instead, just create
801 a new device with the appropriate device type */
802 snprintf(devname_buf, sizeof devname_buf, "/tmp/dev-%u:%u",
803 major(st.st_dev), minor(st.st_dev));
805 if (mknod(devname_buf, S_IFBLK | 0600, st.st_dev)) {
806 fprintf(stderr, "%s: cannot create device %s\n", program, devname);
810 atexit(device_cleanup); /* unlink the device node on exit */
811 devname = devname_buf;
815 devname = find_device("/proc/mounts", st.st_dev);
817 /* Didn't find it in /proc/mounts, try /etc/mtab */
818 devname = find_device("/etc/mtab", st.st_dev);
821 fprintf(stderr, "%s: cannot find device for path %s\n", program, path);
825 fprintf(stderr, "%s is device %s\n", path, devname);
828 if ((devfd = open(devname, O_RDWR | O_SYNC)) < 0) {
829 fprintf(stderr, "%s: cannot open device %s\n", program, devname);
833 /* Verify that the device we opened is the device intended */
834 if (validate_device(path, devfd)) {
835 fprintf(stderr, "%s: path %s doesn't match device %s\n",
836 program, path, devname);
840 if (update_only && !already_installed(devfd)) {
841 fprintf(stderr, "%s: no previous extlinux boot sector found\n",
846 /* Read a pre-existing ADV, if already installed */
848 syslinux_reset_adv(syslinux_adv);
849 else if (read_adv(path) < 0)
852 if (modify_adv() < 0)
855 /* Install extlinux.sys */
856 if (install_file(path, devfd, &fst))
859 if (fst.st_dev != st.st_dev) {
860 fprintf(stderr, "%s: file system changed under us - aborting!\n",
866 rv = install_bootblock(devfd, devname);
874 * Modify the ADV of an existing installation
876 int modify_existing_adv(const char *path)
879 syslinux_reset_adv(syslinux_adv);
880 else if (read_adv(path) < 0)
883 if (modify_adv() < 0)
886 if (write_adv(path) < 0)
892 int main(int argc, char *argv[])
895 const char *directory;
896 int update_only = -1;
900 while ((o = getopt_long(argc, argv, short_options,
901 long_options, NULL)) != EOF) {
908 opt.sectors = strtoul(optarg, NULL, 0);
909 if (opt.sectors < 1 || opt.sectors > 63) {
911 "%s: invalid number of sectors: %u (must be 1-63)\n",
912 program, opt.sectors);
917 opt.heads = strtoul(optarg, NULL, 0);
918 if (opt.heads < 1 || opt.heads > 256) {
920 "%s: invalid number of heads: %u (must be 1-256)\n",
942 opt.set_once = optarg;
951 fputs("extlinux " VERSION_STR
952 " Copyright 1994-" YEAR_STR " H. Peter Anvin \n", stderr);
959 directory = argv[optind];
964 if (update_only == -1) {
965 if (opt.reset_adv || opt.set_once) {
966 return modify_existing_adv(directory);
972 return install_loader(directory, update_only);