1 #ident "$Id: extlinux.c,v 1.15 2005/04/03 00:00:36 hpa Exp $"
2 /* ----------------------------------------------------------------------- *
4 * Copyright 1998-2005 H. Peter Anvin - All Rights Reserved
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. */
34 #include <sys/ioctl.h>
36 #include <sys/types.h>
37 #include <sys/mount.h>
39 #include <linux/fd.h> /* Floppy geometry */
40 #include <linux/hdreg.h> /* Hard disk geometry */
41 #include <linux/fs.h> /* FIGETBSZ, FIBMAP */
44 #include "../version.h"
47 # define dprintf printf
49 # define dprintf(...) ((void)0)
52 /* Global option handling */
56 /* These are the options we can set and their values */
65 static void __attribute__((noreturn)) usage(int rv)
68 "Usage: %s [options] directory\n"
69 " --zip -z Force zipdrive geometry (-H 64 -S 32)\n"
70 " --sectors=# -S Force the number of sectors per track\n"
71 " --heads=# -H Force number of heads\n"
73 " Note: geometry is determined at boot time for devices which\n"
74 " are considered hard disks by the BIOS. Unfortunately, this is\n"
75 " not possible for devices which are considered floppy disks,\n"
76 " which includes zipdisks and LS-120 superfloppies.\n"
78 " The -z option is useful for USB devices which are considered\n"
79 " hard disks by some BIOSes and zipdrives by other BIOSes.\n",
85 static const struct option long_options[] = {
86 { "zipdrive", 0, NULL, 'z' },
87 { "sectors", 1, NULL, 'S' },
88 { "heads", 1, NULL, 'H' },
89 { "version", 0, NULL, 'v' },
90 { "help", 0, NULL, 'h' },
94 static const char short_options[] = "zS:H:vh";
98 #if defined(__linux__) && !defined(BLKGETSIZE64)
99 /* This takes a u64, but the size field says size_t. Someone screwed big. */
100 # define BLKGETSIZE64 _IOR(0x12,114,size_t)
103 #define LDLINUX_MAGIC 0x3eb202fe
108 bsBytesPerSec = 0x0b,
109 bsSecPerClust = 0x0d,
112 bsRootDirEnts = 0x11,
116 bsSecPerTrack = 0x18,
119 bsHugeSectors = 0x20,
122 bs16DriveNumber = 0x24,
123 bs16Reserved1 = 0x25,
124 bs16BootSignature = 0x26,
126 bs16VolumeLabel = 0x2b,
127 bs16FileSysType = 0x36,
138 bs32DriveNumber = 64,
140 bs32BootSignature = 66,
142 bs32VolumeLabel = 71,
143 bs32FileSysType = 82,
149 #define bsHead bsJump
150 #define bsHeadLen (bsOemName-bsHead)
151 #define bsCode bs32Code /* The common safe choice */
152 #define bsCodeLen (bsSignature-bs32Code)
155 * Access functions for littleendian numbers, possibly misaligned.
157 static inline uint8_t get_8(const unsigned char *p)
159 return *(const uint8_t *)p;
162 static inline uint16_t get_16(const unsigned char *p)
164 #if defined(__i386__) || defined(__x86_64__)
165 /* Littleendian and unaligned-capable */
166 return *(const uint16_t *)p;
168 return (uint16_t)p[0] + ((uint16_t)p[1] << 8);
172 static inline uint32_t get_32(const unsigned char *p)
174 #if defined(__i386__) || defined(__x86_64__)
175 /* Littleendian and unaligned-capable */
176 return *(const uint32_t *)p;
178 return (uint32_t)p[0] + ((uint32_t)p[1] << 8) +
179 ((uint32_t)p[2] << 16) + ((uint32_t)p[3] << 24);
183 static inline void set_16(unsigned char *p, uint16_t v)
185 #if defined(__i386__) || defined(__x86_64__)
186 /* Littleendian and unaligned-capable */
190 p[1] = ((v >> 8) & 0xff);
194 static inline void set_32(unsigned char *p, uint32_t v)
196 #if defined(__i386__) || defined(__x86_64__)
197 /* Littleendian and unaligned-capable */
201 p[1] = ((v >> 8) & 0xff);
202 p[2] = ((v >> 16) & 0xff);
203 p[3] = ((v >> 24) & 0xff);
207 #ifndef EXT2_SUPER_OFFSET
208 #define EXT2_SUPER_OFFSET 1024
211 #define SECTOR_SHIFT 9 /* 512-byte sectors */
212 #define SECTOR_SIZE (1 << SECTOR_SHIFT)
219 extern unsigned char extlinux_bootsect[];
220 extern unsigned int extlinux_bootsect_len;
221 #define boot_block extlinux_bootsect
222 #define boot_block_len extlinux_bootsect_len
227 extern unsigned char extlinux_image[];
228 extern unsigned int extlinux_image_len;
229 #define boot_image extlinux_image
230 #define boot_image_len extlinux_image_len
233 * Common abort function
235 void __attribute__((noreturn)) die(const char *msg)
242 * read/write wrapper functions
244 ssize_t xpread(int fd, void *buf, size_t count, off_t offset)
246 char *bufp = (char *)buf;
251 rv = pread(fd, bufp, count, offset);
254 } else if ( rv == -1 ) {
255 if ( errno == EINTR ) {
258 die(strerror(errno));
271 ssize_t xpwrite(int fd, const void *buf, size_t count, off_t offset)
273 const char *bufp = (const char *)buf;
278 rv = pwrite(fd, bufp, count, offset);
281 } else if ( rv == -1 ) {
282 if ( errno == EINTR ) {
285 die(strerror(errno));
302 sectmap(int fd, uint32_t *sectors, int nsectors)
304 unsigned int blksize, blk, nblk;
308 if ( ioctl(fd, FIGETBSZ, &blksize) )
311 /* Number of sectors per block */
312 blksize >>= SECTOR_SHIFT;
318 dprintf("querying block %u\n", blk);
319 if ( ioctl(fd, FIBMAP, &blk) )
323 for ( i = 0 ; i < blksize ; i++ ) {
327 dprintf("Sector: %10u\n", blk);
337 * Get the size of a block device
339 uint64_t get_size(int devfd)
346 if ( !ioctl(devfd, BLKGETSIZE64, &bytes) )
349 if ( !ioctl(devfd, BLKGETSIZE, §s) )
350 return (uint64_t)sects << 9;
351 else if ( !fstat(devfd, &st) && st.st_size )
359 * Get device geometry and partition offset
361 struct geometry_table {
363 struct hd_geometry g;
366 /* Standard floppy disk geometries, plus LS-120. Zipdisk geometry
367 (x/64/32) is the final fallback. I don't know what LS-240 has
368 as its geometry, since I don't have one and don't know anyone that does,
369 and Google wasn't helpful... */
370 static const struct geometry_table standard_geometries[] = {
371 { 360*1024, { 2, 9, 40, 0 } },
372 { 720*1024, { 2, 9, 80, 0 } },
373 { 1200*1024, { 2, 15, 80, 0 } },
374 { 1440*1024, { 2, 18, 80, 0 } },
375 { 1680*1024, { 2, 21, 80, 0 } },
376 { 1722*1024, { 2, 21, 80, 0 } },
377 { 2880*1024, { 2, 36, 80, 0 } },
378 { 3840*1024, { 2, 48, 80, 0 } },
379 { 123264*1024, { 8, 32, 963, 0 } }, /* LS120 */
384 get_geometry(int devfd, uint64_t totalbytes, struct hd_geometry *geo)
386 struct floppy_struct fd_str;
387 const struct geometry_table *gp;
389 memset(geo, 0, sizeof *geo);
391 if ( !ioctl(devfd, HDIO_GETGEO, &geo) ) {
393 } else if ( !ioctl(devfd, FDGETPRM, &fd_str) ) {
394 geo->heads = fd_str.head;
395 geo->sectors = fd_str.sect;
396 geo->cylinders = fd_str.track;
401 /* Didn't work. Let's see if this is one of the standard geometries */
402 for ( gp = standard_geometries ; gp->bytes ; gp++ ) {
403 if ( gp->bytes == totalbytes ) {
404 memcpy(geo, &gp->g, sizeof *geo);
409 /* Didn't work either... assign a geometry of 64 heads, 32 sectors; this is
410 what zipdisks use, so this would help if someone has a USB key that
411 they're booting in USB-ZIP mode. */
413 geo->heads = opt.heads ?: 64;
414 geo->sectors = opt.sectors ?: 32;
415 geo->cylinders = totalbytes/(geo->heads*geo->sectors << SECTOR_SHIFT);
418 if ( !opt.sectors && !opt.heads )
419 fprintf(stderr, "Warning: unable to obtain device geometry (defaulting to %d heads, %d sectors)\n"
420 " (on hard disks, this is usually harmless.)\n",
421 geo->heads, geo->sectors);
427 * Query the device geometry and put it into the boot sector.
428 * Map the file and put the map in the boot sector and file.
429 * Stick the "current directory" inode number into the file.
432 patch_file_and_bootblock(int fd, int dirfd, int devfd)
435 struct hd_geometry geo;
437 uint64_t totalbytes, totalsectors;
439 unsigned char *p, *patcharea;
443 if ( fstat(dirfd, &dirst) ) {
444 perror("fstat dirfd");
445 exit(255); /* This should never happen */
448 totalbytes = get_size(devfd);
449 get_geometry(devfd, totalbytes, &geo);
452 geo.heads = opt.heads;
454 geo.sectors = opt.sectors;
456 /* Patch this into a fake FAT superblock. This isn't because
457 FAT is a good format in any way, it's because it lets the
458 early bootstrap share code with the FAT version. */
459 dprintf("heads = %u, sect = %u\n", geo.heads, geo.sectors);
461 totalsectors = totalbytes >> SECTOR_SHIFT;
462 if ( totalsectors >= 65536 ) {
463 set_16(boot_block+bsSectors, 0);
465 set_16(boot_block+bsSectors, totalsectors);
467 set_32(boot_block+bsHugeSectors, totalsectors);
469 set_16(boot_block+bsBytesPerSec, SECTOR_SIZE);
470 set_16(boot_block+bsSecPerTrack, geo.sectors);
471 set_16(boot_block+bsHeads, geo.heads);
472 set_32(boot_block+bsHiddenSecs, geo.start);
474 /* Construct the boot file */
476 dprintf("directory inode = %lu\n", (unsigned long) dirst.st_ino);
477 nsect = (boot_image_len+SECTOR_SIZE-1) >> SECTOR_SHIFT;
478 sectp = alloca(sizeof(uint32_t)*nsect);
479 if ( sectmap(fd, sectp, nsect) ) {
484 /* First sector need pointer in boot sector */
485 set_32(boot_block+0x1F8, *sectp++);
488 /* Search for LDLINUX_MAGIC to find the patch area */
489 for ( p = boot_image ; get_32(p) != LDLINUX_MAGIC ; p += 4 );
492 /* Set up the totals */
493 dw = boot_image_len >> 2; /* COMPLETE dwords! */
494 set_16(patcharea, dw);
495 set_16(patcharea+2, nsect); /* Does not include the first sector! */
496 set_32(patcharea+8, dirst.st_ino); /* "Current" directory */
498 /* Set the sector pointers */
507 /* Now produce a checksum */
508 set_32(patcharea+4, 0);
510 csum = LDLINUX_MAGIC;
511 for ( i = 0, p = boot_image ; i < dw ; i++, p += 4 )
512 csum -= get_32(p); /* Negative checksum */
514 set_32(patcharea+4, csum);
518 * Install the boot block on the specified device.
519 * Must be run AFTER install_file()!
522 install_bootblock(int fd, const char *device)
524 struct ext2_super_block sb;
526 if ( xpread(fd, &sb, sizeof sb, EXT2_SUPER_OFFSET) != sizeof sb ) {
527 perror("reading superblock");
531 if ( sb.s_magic != EXT2_SUPER_MAGIC ) {
532 fprintf(stderr, "no ext2/ext3 superblock found on %s\n", device);
536 if ( xpwrite(fd, boot_block, boot_block_len, 0) != boot_block_len ) {
537 perror("writing bootblock");
545 install_file(const char *path, int devfd, struct stat *rst)
548 int fd = -1, dirfd = -1, flags;
551 asprintf(&file, "%s%sextlinux.sys",
553 path[0] && path[strlen(path)-1] == '/' ? "" : "/");
559 dirfd = open(path, O_RDONLY|O_DIRECTORY);
565 fd = open(file, O_RDONLY);
567 if ( errno != ENOENT ) {
572 /* If file exist, remove the immutable flag and set u+w mode */
573 if ( !ioctl(fd, EXT2_IOC_GETFLAGS, &flags) ) {
574 flags &= ~EXT2_IMMUTABLE_FL;
575 ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
577 if ( !fstat(fd, &st) ) {
578 fchmod(fd, st.st_mode | S_IWUSR);
583 fd = open(file, O_WRONLY|O_TRUNC|O_CREAT, S_IRUSR|S_IRGRP|S_IROTH);
589 /* Write it the first time */
590 if ( xpwrite(fd, boot_image, boot_image_len, 0) != boot_image_len ) {
591 fprintf(stderr, "%s: write failure on %s\n", program, file);
595 /* Map the file, and patch the initial sector accordingly */
596 patch_file_and_bootblock(fd, dirfd, devfd);
598 /* Write it again - this relies on the file being overwritten in place! */
599 if ( xpwrite(fd, boot_image, boot_image_len, 0) != boot_image_len ) {
600 fprintf(stderr, "%s: write failure on %s\n", program, file);
604 /* Attempt to set immutable flag and remove all write access */
605 /* Only set immutable flag if file is owned by root */
606 if ( !fstat(fd, &st) ) {
607 fchmod(fd, st.st_mode & (S_IRUSR|S_IRGRP|S_IROTH));
608 if ( st.st_uid == 0 && !ioctl(fd, EXT2_IOC_GETFLAGS, &flags) ) {
609 flags |= EXT2_IMMUTABLE_FL;
610 ioctl(fd, EXT2_IOC_SETFLAGS, &flags);
614 if ( fstat(fd, rst) ) {
633 install_loader(const char *path)
635 struct stat st, dst, fst;
636 struct mntent *mnt = NULL;
640 if ( stat(path, &st) || !S_ISDIR(st.st_mode) ) {
641 fprintf(stderr, "%s: Not a directory: %s\n", program, path);
647 if ( (mtab = setmntent("/proc/mounts", "r")) ) {
648 while ( (mnt = getmntent(mtab)) ) {
649 if ( (!strcmp(mnt->mnt_type, "ext2") ||
650 !strcmp(mnt->mnt_type, "ext3")) &&
651 !stat(mnt->mnt_fsname, &dst) &&
652 dst.st_rdev == st.st_dev ) {
653 fprintf(stderr, "%s is device %s\n", path, mnt->mnt_fsname);
654 if ( (devfd = open(mnt->mnt_fsname, O_RDWR|O_SYNC)) < 0 ) {
655 fprintf(stderr, "%s: cannot open device %s\n", program, mnt->mnt_fsname);
664 /* Didn't find it in /proc/mounts, try /etc/mtab */
665 if ( (mtab = setmntent("/etc/mtab", "r")) ) {
666 while ( (mnt = getmntent(mtab)) ) {
667 if ( (!strcmp(mnt->mnt_type, "ext2") ||
668 !strcmp(mnt->mnt_type, "ext3")) &&
669 !stat(mnt->mnt_fsname, &dst) &&
670 dst.st_rdev == st.st_dev ) {
671 fprintf(stderr, "%s is device %s\n", path, mnt->mnt_fsname);
672 if ( (devfd = open(mnt->mnt_fsname, O_RDWR|O_SYNC)) < 0 ) {
673 fprintf(stderr, "%s: cannot open device %s\n", program, mnt->mnt_fsname);
683 fprintf(stderr, "%s: cannot find device for path %s\n", program, path);
687 install_file(path, devfd, &fst);
689 if ( fst.st_dev != st.st_dev ) {
690 fprintf(stderr, "%s: file system changed under us - aborting!\n",
696 rv = install_bootblock(devfd, mnt->mnt_fsname);
708 main(int argc, char *argv[])
711 const char *directory;
715 while ( (o = getopt_long(argc, argv, short_options,
716 long_options, NULL)) != EOF ) {
723 opt.sectors = strtoul(optarg, NULL, 0);
724 if ( opt.sectors < 1 || opt.sectors > 63 ) {
725 fprintf(stderr, "%s: invalid number of sectors: %u (must be 1-63)\n",
726 program, opt.sectors);
731 opt.heads = strtoul(optarg, NULL, 0);
732 if ( opt.heads < 1 || opt.heads > 256 ) {
733 fprintf(stderr, "%s: invalid number of heads: %u (must be 1-256)\n",
742 fputs("extlinux " VERSION "\n", stderr);
745 fprintf(stderr, "%s: Unknown option: %c\n", program, optopt);
750 directory = argv[optind];
755 return install_loader(directory);