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 */
76 static void __attribute__((noreturn)) usage(int rv)
79 "Usage: %s [options] directory\n"
80 " --install -i Install over the current bootsector\n"
81 " --update -U Update a previous EXTLINUX installation\n"
82 " --zip -z Force zipdrive geometry (-H 64 -S 32)\n"
83 " --sectors=# -S Force the number of sectors per track\n"
84 " --heads=# -H Force number of heads\n"
85 " --raid -r Fall back to the next device on boot failure\n"
86 " --once=... -o Execute a command once upon boot\n"
87 " --clear-once -O Clear the boot-once command\n"
88 " --reset-adv Reset auxilliary data\n"
90 " Note: geometry is determined at boot time for devices which\n"
91 " are considered hard disks by the BIOS. Unfortunately, this is\n"
92 " not possible for devices which are considered floppy disks,\n"
93 " which includes zipdisks and LS-120 superfloppies.\n"
95 " The -z option is useful for USB devices which are considered\n"
96 " hard disks by some BIOSes and zipdrives by other BIOSes.\n",
107 static const struct option long_options[] = {
108 { "install", 0, NULL, 'i' },
109 { "update", 0, NULL, 'U' },
110 { "zipdrive", 0, NULL, 'z' },
111 { "sectors", 1, 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 #define LDLINUX_MAGIC 0x3eb202fe
134 bsBytesPerSec = 0x0b,
135 bsSecPerClust = 0x0d,
138 bsRootDirEnts = 0x11,
142 bsSecPerTrack = 0x18,
145 bsHugeSectors = 0x20,
148 bs16DriveNumber = 0x24,
149 bs16Reserved1 = 0x25,
150 bs16BootSignature = 0x26,
152 bs16VolumeLabel = 0x2b,
153 bs16FileSysType = 0x36,
164 bs32DriveNumber = 64,
166 bs32BootSignature = 66,
168 bs32VolumeLabel = 71,
169 bs32FileSysType = 82,
175 #define bsHead bsJump
176 #define bsHeadLen (bsOemName-bsHead)
177 #define bsCode bs32Code /* The common safe choice */
178 #define bsCodeLen (bsSignature-bs32Code)
180 #ifndef EXT2_SUPER_OFFSET
181 #define EXT2_SUPER_OFFSET 1024
189 extern unsigned char extlinux_bootsect[];
190 extern unsigned int extlinux_bootsect_len;
191 #define boot_block extlinux_bootsect
192 #define boot_block_len extlinux_bootsect_len
197 extern unsigned char extlinux_image[];
198 extern unsigned int extlinux_image_len;
199 #define boot_image extlinux_image
200 #define boot_image_len extlinux_image_len
203 * Common abort function
205 void __attribute__((noreturn)) die(const char *msg)
212 * read/write wrapper functions
214 ssize_t xpread(int fd, void *buf, size_t count, off_t offset)
216 char *bufp = (char *)buf;
221 rv = pread(fd, bufp, count, offset);
224 } else if ( rv == -1 ) {
225 if ( errno == EINTR ) {
228 die(strerror(errno));
241 ssize_t xpwrite(int fd, const void *buf, size_t count, off_t offset)
243 const char *bufp = (const char *)buf;
248 rv = pwrite(fd, bufp, count, offset);
251 } else if ( rv == -1 ) {
252 if ( errno == EINTR ) {
255 die(strerror(errno));
272 sectmap(int fd, uint32_t *sectors, int nsectors)
274 unsigned int blksize, blk, nblk;
278 if ( ioctl(fd, FIGETBSZ, &blksize) )
281 /* Number of sectors per block */
282 blksize >>= SECTOR_SHIFT;
288 dprintf("querying block %u\n", blk);
289 if ( ioctl(fd, FIBMAP, &blk) )
293 for ( i = 0 ; i < blksize ; i++ ) {
297 dprintf("Sector: %10u\n", blk);
307 * Get the size of a block device
309 uint64_t get_size(int devfd)
316 if ( !ioctl(devfd, BLKGETSIZE64, &bytes) )
319 if ( !ioctl(devfd, BLKGETSIZE, §s) )
320 return (uint64_t)sects << 9;
321 else if ( !fstat(devfd, &st) && st.st_size )
329 * Get device geometry and partition offset
331 struct geometry_table {
333 struct hd_geometry g;
336 /* Standard floppy disk geometries, plus LS-120. Zipdisk geometry
337 (x/64/32) is the final fallback. I don't know what LS-240 has
338 as its geometry, since I don't have one and don't know anyone that does,
339 and Google wasn't helpful... */
340 static const struct geometry_table standard_geometries[] = {
341 { 360*1024, { 2, 9, 40, 0 } },
342 { 720*1024, { 2, 9, 80, 0 } },
343 { 1200*1024, { 2, 15, 80, 0 } },
344 { 1440*1024, { 2, 18, 80, 0 } },
345 { 1680*1024, { 2, 21, 80, 0 } },
346 { 1722*1024, { 2, 21, 80, 0 } },
347 { 2880*1024, { 2, 36, 80, 0 } },
348 { 3840*1024, { 2, 48, 80, 0 } },
349 { 123264*1024, { 8, 32, 963, 0 } }, /* LS120 */
354 get_geometry(int devfd, uint64_t totalbytes, struct hd_geometry *geo)
356 struct floppy_struct fd_str;
357 const struct geometry_table *gp;
359 memset(geo, 0, sizeof *geo);
361 if ( !ioctl(devfd, HDIO_GETGEO, &geo) ) {
363 } else if ( !ioctl(devfd, FDGETPRM, &fd_str) ) {
364 geo->heads = fd_str.head;
365 geo->sectors = fd_str.sect;
366 geo->cylinders = fd_str.track;
371 /* Didn't work. Let's see if this is one of the standard geometries */
372 for ( gp = standard_geometries ; gp->bytes ; gp++ ) {
373 if ( gp->bytes == totalbytes ) {
374 memcpy(geo, &gp->g, sizeof *geo);
379 /* Didn't work either... assign a geometry of 64 heads, 32 sectors; this is
380 what zipdisks use, so this would help if someone has a USB key that
381 they're booting in USB-ZIP mode. */
383 geo->heads = opt.heads ?: 64;
384 geo->sectors = opt.sectors ?: 32;
385 geo->cylinders = totalbytes/(geo->heads*geo->sectors << SECTOR_SHIFT);
388 if ( !opt.sectors && !opt.heads )
389 fprintf(stderr, "Warning: unable to obtain device geometry (defaulting to %d heads, %d sectors)\n"
390 " (on hard disks, this is usually harmless.)\n",
391 geo->heads, geo->sectors);
397 * Query the device geometry and put it into the boot sector.
398 * Map the file and put the map in the boot sector and file.
399 * Stick the "current directory" inode number into the file.
402 patch_file_and_bootblock(int fd, int dirfd, int devfd)
405 struct hd_geometry geo;
407 uint64_t totalbytes, totalsectors;
409 unsigned char *p, *patcharea;
413 if ( fstat(dirfd, &dirst) ) {
414 perror("fstat dirfd");
415 exit(255); /* This should never happen */
418 totalbytes = get_size(devfd);
419 get_geometry(devfd, totalbytes, &geo);
422 geo.heads = opt.heads;
424 geo.sectors = opt.sectors;
426 /* Patch this into a fake FAT superblock. This isn't because
427 FAT is a good format in any way, it's because it lets the
428 early bootstrap share code with the FAT version. */
429 dprintf("heads = %u, sect = %u\n", geo.heads, geo.sectors);
431 totalsectors = totalbytes >> SECTOR_SHIFT;
432 if ( totalsectors >= 65536 ) {
433 set_16(boot_block+bsSectors, 0);
435 set_16(boot_block+bsSectors, totalsectors);
437 set_32(boot_block+bsHugeSectors, totalsectors);
439 set_16(boot_block+bsBytesPerSec, SECTOR_SIZE);
440 set_16(boot_block+bsSecPerTrack, geo.sectors);
441 set_16(boot_block+bsHeads, geo.heads);
442 set_32(boot_block+bsHiddenSecs, geo.start);
444 /* If we're in RAID mode then patch the appropriate instruction;
445 either way write the proper boot signature */
446 i = get_16(boot_block+0x1FE);
448 set_16(boot_block+i, 0x18CD); /* INT 18h */
450 set_16(boot_block+0x1FE, 0xAA55);
452 /* Construct the boot file */
454 dprintf("directory inode = %lu\n", (unsigned long) dirst.st_ino);
455 nsect = (boot_image_len+SECTOR_SIZE-1) >> SECTOR_SHIFT;
456 nsect += 2; /* Two sectors for the ADV */
457 sectp = alloca(sizeof(uint32_t)*nsect);
458 if ( sectmap(fd, sectp, nsect) ) {
463 /* First sector need pointer in boot sector */
464 set_32(boot_block+0x1F8, *sectp++);
467 /* Search for LDLINUX_MAGIC to find the patch area */
468 for ( p = boot_image ; get_32(p) != LDLINUX_MAGIC ; p += 4 );
471 /* Set up the totals */
472 dw = boot_image_len >> 2; /* COMPLETE dwords, excluding ADV */
473 set_16(patcharea, dw);
474 set_16(patcharea+2, nsect); /* Not including the first sector, but
476 set_32(patcharea+8, dirst.st_ino); /* "Current" directory */
478 /* Set the sector pointers */
487 /* Now produce a checksum */
488 set_32(patcharea+4, 0);
490 csum = LDLINUX_MAGIC;
491 for ( i = 0, p = boot_image ; i < dw ; i++, p += 4 )
492 csum -= get_32(p); /* Negative checksum */
494 set_32(patcharea+4, csum);
498 * Read the ADV from an existing instance, or initialize if invalid.
499 * Returns -1 on fatal errors, 0 if ADV is okay, and 1 if no valid
503 read_adv(const char *path)
510 asprintf(&file, "%s%sextlinux.sys",
512 path[0] && path[strlen(path)-1] == '/' ? "" : "/");
519 fd = open(file, O_RDONLY);
521 if ( errno != ENOENT ) {
524 syslinux_reset_adv(syslinux_adv);
526 } else if (fstat(fd, &st)) {
528 } else if (st.st_size < 2*ADV_SIZE) {
529 /* Too small to be useful */
530 syslinux_reset_adv(syslinux_adv);
531 err = 0; /* Nothing to read... */
532 } else if (xpread(fd, syslinux_adv, 2*ADV_SIZE,
533 st.st_size-2*ADV_SIZE) != 2*ADV_SIZE) {
536 /* We got it... maybe? */
537 err = syslinux_validate_adv(syslinux_adv) ? 1 : 0;
552 * Update the ADV in an existing installation.
555 write_adv(const char *path)
557 unsigned char advtmp[2*ADV_SIZE];
564 asprintf(&file, "%s%sextlinux.sys",
566 path[0] && path[strlen(path)-1] == '/' ? "" : "/");
573 fd = open(file, O_RDONLY);
576 } else if (fstat(fd, &st)) {
578 } else if (st.st_size < 2*ADV_SIZE) {
579 /* Too small to be useful */
581 } else if (xpread(fd, advtmp, 2*ADV_SIZE,
582 st.st_size-2*ADV_SIZE) != 2*ADV_SIZE) {
585 /* We got it... maybe? */
586 err = syslinux_validate_adv(advtmp) ? -2 : 0;
588 /* Got a good one, write our own ADV here */
589 if (!ioctl(fd, EXT2_IOC_GETFLAGS, &flags)) {
590 nflags = flags & ~EXT2_IMMUTABLE_FL;
592 ioctl(fd, EXT2_IOC_SETFLAGS, &nflags);
594 if (!(st.st_mode & S_IWUSR))
595 fchmod(fd, st.st_mode | S_IWUSR);
597 /* Need to re-open read-write */
599 fd = open(file, O_RDWR|O_SYNC);
602 } else if (fstat(fd, &xst) || xst.st_ino != st.st_ino ||
603 xst.st_dev != st.st_dev || xst.st_size != st.st_size) {
604 fprintf(stderr, "%s: race condition on write\n", file);
607 /* Write our own version ... */
608 if (xpwrite(fd, syslinux_adv, 2*ADV_SIZE,
609 st.st_size-2*ADV_SIZE) != 2*ADV_SIZE) {
615 if (!(st.st_mode & S_IWUSR))
616 fchmod(fd, st.st_mode);
619 ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
624 fprintf(stderr, "%s: cannot write auxilliary data (need --update)?\n",
638 * Make any user-specified ADV modifications
645 if (syslinux_setadv(ADV_BOOTONCE, strlen(opt.set_once), opt.set_once)) {
646 fprintf(stderr, "%s: not enough space for boot-once command\n", program);
655 * Install the boot block on the specified device.
656 * Must be run AFTER install_file()!
659 install_bootblock(int fd, const char *device)
661 struct ext2_super_block sb;
663 if ( xpread(fd, &sb, sizeof sb, EXT2_SUPER_OFFSET) != sizeof sb ) {
664 perror("reading superblock");
668 if ( sb.s_magic != EXT2_SUPER_MAGIC ) {
669 fprintf(stderr, "no ext2/ext3 superblock found on %s\n", device);
673 if ( xpwrite(fd, boot_block, boot_block_len, 0) != boot_block_len ) {
674 perror("writing bootblock");
682 install_file(const char *path, int devfd, struct stat *rst)
685 int fd = -1, dirfd = -1, flags;
688 asprintf(&file, "%s%sextlinux.sys",
690 path[0] && path[strlen(path)-1] == '/' ? "" : "/");
696 dirfd = open(path, O_RDONLY|O_DIRECTORY);
702 fd = open(file, O_RDONLY);
704 if ( errno != ENOENT ) {
709 /* If file exist, remove the immutable flag and set u+w mode */
710 if ( !ioctl(fd, EXT2_IOC_GETFLAGS, &flags) ) {
711 flags &= ~EXT2_IMMUTABLE_FL;
712 ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
714 if ( !fstat(fd, &st) ) {
715 fchmod(fd, st.st_mode | S_IWUSR);
720 fd = open(file, O_WRONLY|O_TRUNC|O_CREAT|O_SYNC, S_IRUSR|S_IRGRP|S_IROTH);
726 /* Write it the first time */
727 if ( xpwrite(fd, boot_image, boot_image_len, 0) != boot_image_len ||
728 xpwrite(fd, syslinux_adv, 2*ADV_SIZE, boot_image_len) != 2*ADV_SIZE ) {
729 fprintf(stderr, "%s: write failure on %s\n", program, file);
733 /* Map the file, and patch the initial sector accordingly */
734 patch_file_and_bootblock(fd, dirfd, devfd);
736 /* Write the first sector again - this relies on the file being
737 overwritten in place! */
738 if ( xpwrite(fd, boot_image, SECTOR_SIZE, 0) != SECTOR_SIZE ) {
739 fprintf(stderr, "%s: write failure on %s\n", program, file);
743 /* Attempt to set immutable flag and remove all write access */
744 /* Only set immutable flag if file is owned by root */
745 if ( !fstat(fd, &st) ) {
746 fchmod(fd, st.st_mode & (S_IRUSR|S_IRGRP|S_IROTH));
747 if ( st.st_uid == 0 && !ioctl(fd, EXT2_IOC_GETFLAGS, &flags) ) {
748 flags |= EXT2_IMMUTABLE_FL;
749 ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
753 if ( fstat(fd, rst) ) {
771 /* EXTLINUX installs the string 'EXTLINUX' at offset 3 in the boot
772 sector; this is consistent with FAT filesystems. */
774 already_installed(int devfd)
778 xpread(devfd, buffer, 8, 3);
779 return !memcmp(buffer, "EXTLINUX", 8);
784 static char devname_buf[64];
786 static void device_cleanup(void)
792 /* Verify that a device fd and a pathname agree.
793 Return 0 on valid, -1 on error. */
794 static int validate_device(const char *path, int devfd)
796 struct stat pst, dst;
798 if (stat(path, &pst) || fstat(devfd, &dst))
801 return (pst.st_dev == dst.st_rdev) ? 0 : -1;
805 static const char *find_device(const char *mtab_file, dev_t dev)
810 const char *devname = NULL;
812 mtab = setmntent(mtab_file, "r");
816 while ( (mnt = getmntent(mtab)) ) {
817 if ( (!strcmp(mnt->mnt_type, "ext2") ||
818 !strcmp(mnt->mnt_type, "ext3")) &&
819 !stat(mnt->mnt_fsname, &dst) && dst.st_rdev == dev ) {
820 devname = strdup(mnt->mnt_fsname);
831 install_loader(const char *path, int update_only)
835 const char *devname = NULL;
838 if ( stat(path, &st) || !S_ISDIR(st.st_mode) ) {
839 fprintf(stderr, "%s: Not a directory: %s\n", program, path);
843 if ( statfs(path, &sfs) ) {
844 fprintf(stderr, "%s: statfs %s: %s\n", program, path, strerror(errno));
848 if ( sfs.f_type != EXT2_SUPER_MAGIC ) {
849 fprintf(stderr, "%s: not an ext2/ext3 filesystem: %s\n", program, path);
857 /* klibc doesn't have getmntent and friends; instead, just create
858 a new device with the appropriate device type */
859 snprintf(devname_buf, sizeof devname_buf, "/tmp/dev-%u:%u",
860 major(st.st_dev), minor(st.st_dev));
862 if (mknod(devname_buf, S_IFBLK|0600, st.st_dev)) {
863 fprintf(stderr, "%s: cannot create device %s\n", program, devname);
867 atexit(device_cleanup); /* unlink the device node on exit */
868 devname = devname_buf;
872 devname = find_device("/proc/mounts", st.st_dev);
874 /* Didn't find it in /proc/mounts, try /etc/mtab */
875 devname = find_device("/etc/mtab", st.st_dev);
878 fprintf(stderr, "%s: cannot find device for path %s\n", program, path);
882 fprintf(stderr, "%s is device %s\n", path, devname);
885 if ( (devfd = open(devname, O_RDWR|O_SYNC)) < 0 ) {
886 fprintf(stderr, "%s: cannot open device %s\n", program, devname);
890 /* Verify that the device we opened is the device intended */
891 if (validate_device(path, devfd)) {
892 fprintf(stderr, "%s: path %s doesn't match device %s\n",
893 program, path, devname);
897 if ( update_only && !already_installed(devfd) ) {
898 fprintf(stderr, "%s: no previous extlinux boot sector found\n", program);
902 /* Read a pre-existing ADV, if already installed */
904 syslinux_reset_adv(syslinux_adv);
905 else if (read_adv(path) < 0)
908 if (modify_adv() < 0)
911 /* Install extlinux.sys */
912 if (install_file(path, devfd, &fst))
915 if ( fst.st_dev != st.st_dev ) {
916 fprintf(stderr, "%s: file system changed under us - aborting!\n",
922 rv = install_bootblock(devfd, devname);
930 * Modify the ADV of an existing installation
933 modify_existing_adv(const char *path)
936 syslinux_reset_adv(syslinux_adv);
937 else if (read_adv(path) < 0)
940 if (modify_adv() < 0)
943 if (write_adv(path) < 0)
950 main(int argc, char *argv[])
953 const char *directory;
954 int update_only = -1;
958 while ( (o = getopt_long(argc, argv, short_options,
959 long_options, NULL)) != EOF ) {
966 opt.sectors = strtoul(optarg, NULL, 0);
967 if ( opt.sectors < 1 || opt.sectors > 63 ) {
968 fprintf(stderr, "%s: invalid number of sectors: %u (must be 1-63)\n",
969 program, opt.sectors);
974 opt.heads = strtoul(optarg, NULL, 0);
975 if ( opt.heads < 1 || opt.heads > 256 ) {
976 fprintf(stderr, "%s: invalid number of heads: %u (must be 1-256)\n",
995 opt.set_once = optarg;
1004 fputs("extlinux " VERSION_STR
1005 " Copyright 1994-" YEAR_STR " H. Peter Anvin \n", stderr);
1012 directory = argv[optind];
1017 if ( update_only == -1 ) {
1018 if (opt.reset_adv || opt.set_once) {
1019 return modify_existing_adv(directory);
1025 return install_loader(directory, update_only);