1 /* $NetBSD: fdisk.c,v 1.161 2022/04/02 19:15:09 mlelstv Exp $ */
2
3 /*
4 * Mach Operating System
5 * Copyright (c) 1992 Carnegie Mellon University
6 * All Rights Reserved.
7 *
8 * Permission to use, copy, modify and distribute this software and its
9 * documentation is hereby granted, provided that both the copyright
10 * notice and this permission notice appear in all copies of the
11 * software, derivative works or modified versions, and any portions
12 * thereof, and that both notices appear in supporting documentation.
13 *
14 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
15 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
16 * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
17 *
18 * Carnegie Mellon requests users of this software to return to
19 *
20 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
21 * School of Computer Science
22 * Carnegie Mellon University
23 * Pittsburgh PA 15213-3890
24 *
25 * any improvements or extensions that they make and grant Carnegie Mellon
26 * the rights to redistribute these changes.
27 */
28
29 /*
30 * 14-Dec-89 Robert Baron (rvb) at Carnegie-Mellon University
31 * Copyright (c) 1989 Robert. V. Baron
32 * Created.
33 */
34
35 #if HAVE_NBTOOL_CONFIG_H
36 #include "nbtool_config.h"
37 #endif
38
39 #include <sys/cdefs.h>
40
41 #ifndef lint
42 __RCSID("$NetBSD: fdisk.c,v 1.161 2022/04/02 19:15:09 mlelstv Exp $");
43 #endif /* not lint */
44
45 #define MBRPTYPENAMES
46 #include <sys/types.h>
47 #include <sys/param.h>
48 #include <sys/stat.h>
49 #include <ctype.h>
50 #include <err.h>
51 #include <errno.h>
52 #include <fcntl.h>
53 #include <paths.h>
54 #include <stdarg.h>
55 #include <stddef.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <unistd.h>
60 #include <vis.h>
61 #include <zlib.h>
62
63 #if !HAVE_NBTOOL_CONFIG_H
64 #include <sys/disklabel.h>
65 #include <sys/disklabel_gpt.h>
66 #include <sys/bootblock.h>
67 #include <sys/ioctl.h>
68 #include <sys/sysctl.h>
69 #include <disktab.h>
70 #include <util.h>
71 #else
72 #include <nbinclude/sys/disklabel.h>
73 #include <nbinclude/sys/disklabel_gpt.h>
74 #include <nbinclude/sys/bootblock.h>
75 #include "../../include/disktab.h"
76 /* We enforce -F, so none of these possibly undefined items can be needed */
77 #define opendisk(path, fl, buf, buflen, cooked) (-1)
78 #endif /* HAVE_NBTOOL_CONFIG_H */
79
80 #ifndef DEFAULT_BOOTDIR
81 #define DEFAULT_BOOTDIR "/usr/mdec"
82 #endif
83
84 #define LE_MBR_MAGIC htole16(MBR_MAGIC)
85 #define LE_MBR_BS_MAGIC htole16(MBR_BS_MAGIC)
86
87 #ifdef BOOTSEL
88
89 #define DEFAULT_BOOTCODE "mbr"
90 #define DEFAULT_BOOTSELCODE "mbr_bootsel"
91 #define DEFAULT_BOOTEXTCODE "mbr_ext"
92
93 /* Scan values for the various keys we use, as returned by the BIOS */
94 #define SCAN_ENTER 0x1c
95 #define SCAN_F1 0x3b
96 #define SCAN_1 0x2
97
98
99 #define MAX_BIOS_DISKS 16 /* Going beyond F12 is hard though! */
100
101 /* We same the dflt 'boot partition' as a disk block, with some magic values. */
102 #define DEFAULT_ACTIVE (~(daddr_t)0)
103 #define DEFAULT_DISK(n) (DEFAULT_ACTIVE - MAX_BIOS_DISKS + (n))
104
105 #endif
106
107 #define GPT_TYPE(offs) ((offs) == GPT_HDR_BLKNO ? "primary" : "secondary")
108
109 #ifndef PRIdaddr
110 #define PRIdaddr PRId64
111 #endif
112
113 #ifndef _PATH_DEFDISK
114 #define _PATH_DEFDISK "/dev/rwd0d"
115 #endif
116
117 struct {
118 struct mbr_sector *ptn; /* array of pbrs */
119 daddr_t base; /* first sector of ext. ptn */
120 daddr_t limit; /* last sector of ext. ptn */
121 int num_ptn; /* number of contained partitions */
122 int ptn_id; /* entry in mbr */
123 int is_corrupt; /* 1 if extended chain illegal */
124 } ext;
125
126 #define LBUF 100
127 static char lbuf[LBUF];
128
129 static const char *disk = _PATH_DEFDISK;
130
131 static struct disklabel disklabel; /* disk parameters */
132
133 static struct mbr_sector mboot;
134
135 static const char *boot_dir = DEFAULT_BOOTDIR;
136 static char *boot_path = NULL; /* name of file we actually opened */
137
138 #ifdef BOOTSEL
139 #define BOOTSEL_OPTIONS "B"
140 #else
141 #define BOOTSEL_OPTIONS
142 #define change_part(e, p, id, st, sz, bm) change__part(e, p, id, st, sz)
143 #endif
144 #define OPTIONS BOOTSEL_OPTIONS "0123FSafgiIluvA:b:c:E:r:s:w:z:"
145
146 /*
147 * Disk geometry and partition alignment.
148 *
149 * Modern disks do not have a fixed geomery and will always give a 'faked'
150 * geometry that matches the ATA standard - max 16 heads and 256 sec/track.
151 * The ATA geometry allows access to 2^28 sectors (as does LBA mode).
152 *
153 * The BIOS calls originally used an 8bit register for cylinder, head and
154 * sector. Later 2 bits were stolen from the sector number and added to
155 * cylinder number. The BIOS will translate this faked geometry either to
156 * the geometry reported by the disk, or do LBA reads (possibly LBA48).
157 * BIOS CHS reads have all sorts of limits, but 2^24 is absolute.
158 * For historic reasons the BIOS geometry is the called the dos geometry!
159 *
160 * If you know the disks real geometry it is usually worth aligning
161 * disk partitions to cylinder boundaries (certainly traditional!).
162 * For 'mbr' disks this has always been done with the BIOS geometry.
163 * The first track (typically 63 sectors) is reserved because the first
164 * sector is used for boot code. Similarly the data partition in an
165 * extended partition will start one track in. If an extended partition
166 * starts at the beginning of the disk you lose 2 tracks.
167 *
168 * However non-magnetic media in particular has physical sectors that are
169 * not the same size as those reported, so has to do read modify write
170 * sequences for misaligned transfers. The alignment of partitions to
171 * cylinder boundaries makes this happen all the time.
172 *
173 * It is thus sensible to align partitions on a sensible sector boundary.
174 * For instance 1MB (2048 sectors).
175 * Common code can do this by using a geometry with 1 head and 2048
176 * sectors per track.
177 */
178
179 /* Disks reported geometry and overall size from device driver */
180 static unsigned int cylinders, sectors, heads;
181 static daddr_t disksectors;
182 #define cylindersectors (heads * sectors)
183
184 /* Geometry from the BIOS */
185 static unsigned int dos_cylinders;
186 static unsigned int dos_heads;
187 static unsigned int dos_sectors;
188 static daddr_t dos_disksectors;
189 #define dos_cylindersectors (dos_heads * dos_sectors)
190 #define dos_totalsectors (dos_heads * dos_sectors * dos_cylinders)
191
192 #define DOSSECT(s,c) (((s) & 0x3f) | (((c) >> 2) & 0xc0))
193 #define DOSCYL(c) ((c) & 0xff)
194 #define SEC_IN_1M (1024 * 1024 / secsize)
195 #define SEC_TO_MB(sec) ((unsigned int)(((sec) + SEC_IN_1M / 2) / SEC_IN_1M))
196 #define SEC_TO_CYL(sec) (((sec) + dos_cylindersectors/2) / dos_cylindersectors)
197
198 #define MAXCYL 1024 /* Usual limit is 1023 */
199 #define MAXHEAD 256 /* Usual limit is 255 */
200 #define MAXSECTOR 63
201 static int partition = -1;
202
203 /* Alignment of partition, and offset if first sector unusable */
204 static unsigned int ptn_alignment; /* default dos_cylindersectors */
205 static unsigned int ptn_0_offset; /* default dos_sectors */
206
207 static int fd = -1, wfd = -1, *rfd = &fd;
208 static char *disk_file = NULL;
209 static char *disk_type = NULL;
210
211 static int a_flag; /* set active partition */
212 static int i_flag; /* init bootcode */
213 static int I_flag; /* ignore errors */
214 static int u_flag; /* update partition data */
215 static int v_flag; /* more verbose */
216 static int sh_flag; /* Output data as shell defines */
217 static int f_flag; /* force --not interactive */
218 static int g_flag; /* preserve GPT headers */
219 static int s_flag; /* set id,offset,size */
220 static int b_flag; /* Set cyl, heads, secs (as c/h/s) */
221 static int B_flag; /* Edit/install bootselect code */
222 static int E_flag; /* extended partition number */
223 static int b_cyl, b_head, b_sec; /* b_flag values. */
224
225 #if !HAVE_NBTOOL_CONFIG_H
226 static int F_flag = 0;
227 #else
228 /* Tool - force 'file' mode to avoid unsupported functions and ioctls */
229 static int F_flag = 1;
230 #endif
231
232 static struct gpt_hdr gpt1, gpt2; /* GUID partition tables */
233
234 static struct mbr_sector bootcode[8192 / sizeof (struct mbr_sector)];
235 static ssize_t secsize = 512; /* sector size */
236 static char *iobuf; /* buffer for non 512 sector I/O */
237 static int bootsize; /* actual size of bootcode */
238 static int boot_installed; /* 1 if we've copied code into the mbr */
239
240 #if defined(USE_DISKLIST)
241 #include <machine/cpu.h>
242 static struct disklist *dl;
243 #endif
244
245
246 #define KNOWN_SYSIDS (sizeof(mbr_ptypes)/sizeof(mbr_ptypes[0]))
247
248 __dead static void usage(void);
249 static void print_s0(int);
250 static void print_part(struct mbr_sector *, int, daddr_t);
251 static void print_mbr_partition(struct mbr_sector *, int, daddr_t, daddr_t, int);
252 static void print_pbr(daddr_t, int, uint8_t);
253 static int is_all_zero(const unsigned char *, size_t);
254 static void printvis(int, const char *, const char *, size_t);
255 static int read_boot(const char *, void *, size_t, int);
256 static void init_sector0(int);
257 static void intuit_translated_geometry(void);
258 static void get_bios_geometry(void);
259 static void get_extended_ptn(void);
260 static void get_ptn_alignmemt(void);
261 #if defined(USE_DISKLIST)
262 static void get_diskname(const char *, char *, size_t);
263 #endif
264 static int change_part(int, int, int, daddr_t, daddr_t, char *);
265 static void print_geometry(void);
266 static int first_active(void);
267 static void change_active(int);
268 static void change_bios_geometry(void);
269 static void dos(int, unsigned char *, unsigned char *, unsigned char *);
270 static int open_disk(int);
271 static ssize_t read_disk(daddr_t, void *);
272 static ssize_t write_disk(daddr_t, void *);
273 static int get_params(void);
274 static int read_s0(daddr_t, struct mbr_sector *);
275 static int write_mbr(void);
276 static int read_gpt(daddr_t, struct gpt_hdr *);
277 static int delete_gpt(struct gpt_hdr *);
278 static int yesno(const char *, ...) __printflike(1, 2);
279 static int64_t decimal(const char *, int64_t, int, int64_t, int64_t);
280 #define DEC_SEC 1 /* asking for a sector number */
281 #define DEC_RND 2 /* round to end of first track */
282 #define DEC_RND_0 4 /* convert 0 to size of a track */
283 #define DEC_RND_DOWN 8 /* subtract 1 track */
284 #define DEC_RND_DOWN_2 16 /* subtract 2 tracks */
285 static int ptn_id(const char *, int *);
286 static int type_match(const void *, const void *);
287 static const char *get_type(int);
288 static int get_mapping(int, unsigned int *, unsigned int *, unsigned int *, unsigned long *);
289 #ifdef BOOTSEL
290 static daddr_t configure_bootsel(daddr_t);
291 static void install_bootsel(int);
292 static daddr_t get_default_boot(void);
293 static void set_default_boot(daddr_t);
294 static void string(const char *, int, char *);
295 #endif
296
297 static void
initvar_disk(const char ** diskp)298 initvar_disk(const char **diskp)
299 {
300 #if !HAVE_NBTOOL_CONFIG_H
301 int mib[2];
302 size_t len;
303 char *root_device;
304
305 mib[0] = CTL_KERN;
306 mib[1] = KERN_ROOT_DEVICE;
307 if (sysctl(mib, 2, NULL, &len, NULL, 0) == -1 ||
308 (root_device = malloc(len)) == NULL ||
309 sysctl(mib, 2, root_device, &len, NULL, 0) == -1)
310 return;
311
312 *diskp = root_device;
313 #endif /* HAVE_NBTOOL_CONFIG_H */
314 }
315
316 static int
getnum(const char * str,int * num)317 getnum(const char *str, int *num)
318 {
319 char *e;
320 long l;
321
322 errno = 0;
323 l = strtol(str, &e, 0);
324 if (str[0] == '\0' || *e != '\0')
325 return -1;
326 if (errno == ERANGE && (l == LONG_MAX || l == LONG_MIN))
327 return -1;
328 /* XXX: truncation */
329 *num = (int)l;
330 return 0;
331 }
332
333 /* [<sysid>][/[<start>][/[<size>][/[<bootmenu>]]]] */
334 static int
parse_s(char * arg,int * csysid,unsigned * cstart,unsigned * csize,char ** cbootmenu)335 parse_s(char *arg, int *csysid, unsigned *cstart, unsigned *csize,
336 char **cbootmenu)
337 {
338 char *ptr;
339 int num;
340
341 if ((ptr = strchr(arg, '/')) != NULL)
342 *ptr++ = '\0';
343
344 if (*arg) {
345 if (getnum(arg, &num) == -1)
346 return -1;
347 *csysid = num;
348 }
349 if (ptr == NULL)
350 return 0;
351
352 arg = ptr;
353 if ((ptr = strchr(arg, '/')) != NULL)
354 *ptr++ = '\0';
355 if (*arg) {
356 if (getnum(arg, &num) == -1)
357 return -1;
358 *cstart = num;
359 }
360 if (ptr == NULL)
361 return 0;
362
363 arg = ptr;
364 if ((ptr = strchr(arg, '/')) != NULL)
365 *ptr++ = '\0';
366 if (*arg) {
367 if (getnum(arg, &num) == -1)
368 return -1;
369 *csize = num;
370 }
371 if (ptr != NULL && *ptr)
372 *cbootmenu = ptr;
373 return 0;
374 }
375
376 int
main(int argc,char * argv[])377 main(int argc, char *argv[])
378 {
379 struct stat sb;
380 int ch;
381 size_t len;
382 char *cp;
383 int n;
384 #ifdef BOOTSEL
385 daddr_t default_ptn; /* start sector of default ptn */
386 #endif
387 char *cbootmenu = 0;
388
389 int csysid; /* For the s_flag. */
390 unsigned int cstart, csize;
391 a_flag = u_flag = sh_flag = f_flag = s_flag = b_flag = 0;
392 i_flag = B_flag = 0;
393 v_flag = 0;
394 E_flag = 0;
395 csysid = -1;
396 cstart = csize = ~0;
397 while ((ch = getopt(argc, argv, OPTIONS)) != -1) {
398 switch (ch) {
399 case '0':
400 partition = 0;
401 break;
402 case '1':
403 partition = 1;
404 break;
405 case '2':
406 partition = 2;
407 break;
408 case '3':
409 partition = 3;
410 break;
411 case 'E': /* Extended partition number */
412 E_flag = 1;
413 partition = strtoul(optarg, &cp, 0);
414 if (*cp || partition < 0)
415 errx(1, "Bad partition number -E %s.", optarg);
416 break;
417 #ifdef BOOTSEL
418 case 'B': /* Bootselect parameters */
419 B_flag = 1;
420 break;
421 #endif
422 case 'F': /* device argument is really a file */
423 F_flag = 1;
424 break;
425 case 'S': /* Output as shell variables */
426 sh_flag = 1;
427 break;
428 case 'a': /* Set active partition */
429 a_flag = 1;
430 break;
431 case 'f': /* Non interactive */
432 f_flag = 1;
433 break;
434 case 'g': /* Preserve GPT headers */
435 g_flag = 1;
436 break;
437 case 'i': /* Always update bootcode */
438 i_flag = 1;
439 break;
440 case 'I': /* Ignore errors */
441 I_flag = 1;
442 break;
443 case 'l': /* List known partition types */
444 for (len = 0; len < KNOWN_SYSIDS; len++)
445 printf("%03d %s\n", mbr_ptypes[len].id,
446 mbr_ptypes[len].name);
447 return 0;
448 case 'u': /* Update partition details */
449 u_flag = 1;
450 break;
451 case 'v': /* Be verbose */
452 v_flag++;
453 break;
454 case 's': /* Partition details */
455 s_flag = 1;
456
457 if (parse_s(optarg, &csysid, &cstart, &csize,
458 &cbootmenu) == -1)
459 errx(1, "Bad argument to the -s flag.");
460 break;
461 case 'b': /* BIOS geometry */
462 b_flag = 1;
463 if (sscanf(optarg, "%d/%d/%d%n", &b_cyl, &b_head,
464 &b_sec, &n) != 3 || optarg[n] != 0)
465 errx(1, "Bad argument to the -b flag.");
466 if (b_cyl > MAXCYL)
467 b_cyl = MAXCYL;
468 break;
469 case 'A': /* Partition alignment[/offset] */
470 if (sscanf(optarg, "%u%n/%u%n", &ptn_alignment,
471 &n, &ptn_0_offset, &n) < 1
472 || optarg[n] != 0
473 || ptn_0_offset > ptn_alignment)
474 errx(1, "Bad argument to the -A flag.");
475 if (ptn_0_offset == 0)
476 ptn_0_offset = ptn_alignment;
477 break;
478 case 'c': /* file/directory containing boot code */
479 if (strchr(optarg, '/') != NULL &&
480 stat(optarg, &sb) == 0 &&
481 (sb.st_mode & S_IFMT) == S_IFDIR) {
482 boot_dir = optarg;
483 break;
484 }
485 bootsize = read_boot(optarg, bootcode,
486 sizeof bootcode, 1);
487 i_flag = 1;
488 break;
489 case 'r': /* read data from disk_file (not raw disk) */
490 rfd = &wfd;
491 /* FALLTHROUGH */
492 case 'w': /* write data to disk_file */
493 disk_file = optarg;
494 break;
495 case 't':
496 if (setdisktab(optarg) == -1)
497 errx(EXIT_FAILURE, "bad disktab");
498 break;
499 case 'T':
500 disk_type = optarg;
501 break;
502 case 'z':
503 secsize = atoi(optarg);
504 if (secsize <= 512)
505 out: errx(EXIT_FAILURE, "Invalid sector size %zd",
506 secsize);
507 for (ch = secsize; (ch & 1) == 0; ch >>= 1)
508 continue;
509 if (ch != 1)
510 goto out;
511 break;
512 default:
513 usage();
514 }
515 }
516 argc -= optind;
517 argv += optind;
518
519 if (disk_type != NULL && getdiskbyname(disk_type) == NULL)
520 errx(EXIT_FAILURE, "bad disktype");
521
522 if (sh_flag && (a_flag || i_flag || u_flag || f_flag || s_flag))
523 usage();
524
525 if (B_flag && f_flag) {
526 warnx("Bootselector may only be configured interactively");
527 usage();
528 }
529
530 if (f_flag && u_flag && !s_flag) {
531 warnx("Partition data not specified");
532 usage();
533 }
534
535 if (s_flag && partition == -1) {
536 warnx("-s flag requires a partition selected.");
537 usage();
538 }
539
540 if (argc > 1)
541 usage();
542
543 if (argc > 0)
544 disk = argv[0];
545 else if (!F_flag) {
546 /* Default to boot device */
547 initvar_disk(&disk);
548 }
549
550 if (!F_flag && stat(disk, &sb) == 0 && S_ISREG(sb.st_mode))
551 F_flag = 1;
552
553 if (open_disk(B_flag || a_flag || i_flag || u_flag) < 0)
554 exit(1);
555
556 if (secsize > 512) {
557 if ((iobuf = malloc(secsize)) == NULL)
558 err(EXIT_FAILURE, "Cannot allocate %zd buffer",
559 secsize);
560 }
561
562 if (read_s0(0, &mboot))
563 /* must have been a blank disk */
564 init_sector0(1);
565
566 read_gpt(GPT_HDR_BLKNO, &gpt1);
567 read_gpt(disksectors - 1, &gpt2);
568
569 if (b_flag) {
570 dos_cylinders = b_cyl;
571 dos_heads = b_head;
572 dos_sectors = b_sec;
573 } else {
574 get_bios_geometry();
575 }
576
577 if (ptn_alignment == 0)
578 get_ptn_alignmemt();
579
580 get_extended_ptn();
581
582 #ifdef BOOTSEL
583 default_ptn = get_default_boot();
584 #endif
585
586 if (E_flag && !u_flag && partition >= ext.num_ptn)
587 errx(1, "Extended partition %d is not defined.", partition);
588
589 /* Do the update stuff! */
590 if (u_flag) {
591 if (!f_flag && !b_flag)
592 change_bios_geometry();
593
594 if (s_flag)
595 change_part(E_flag, partition, csysid, cstart, csize,
596 cbootmenu);
597 else {
598 int part = partition, chg_ext = E_flag, prompt = 1;
599 do {
600 if (prompt) {
601 printf("\n");
602 print_s0(partition);
603 }
604 if (partition == -1)
605 part = ptn_id(
606 "Which partition do you want to change?",
607 &chg_ext);
608 if (part < 0)
609 break;
610 prompt = change_part(chg_ext, part, 0, 0, 0, 0);
611 } while (partition == -1);
612 }
613 } else {
614 if (!i_flag && !B_flag) {
615 print_geometry();
616 print_s0(partition);
617 }
618 }
619
620 if (a_flag && !E_flag)
621 change_active(partition);
622
623 #ifdef BOOTSEL
624 if (B_flag || u_flag || i_flag)
625 /* Ensure the mbr code supports this configuration */
626 install_bootsel(0);
627 if (B_flag)
628 default_ptn = configure_bootsel(default_ptn);
629 set_default_boot(default_ptn);
630 #else
631 if (i_flag)
632 init_sector0(0);
633 #endif
634
635 if (u_flag || a_flag || i_flag || B_flag) {
636 if (!f_flag) {
637 printf("\nWe haven't written the MBR back to disk "
638 "yet. This is your last chance.\n");
639 if (u_flag)
640 print_s0(-1);
641 if (gpt1.hdr_size != 0 || gpt2.hdr_size != 0)
642 printf("\nWARNING: The disk is carrying "
643 "GUID Partition Tables.\n"
644 " If you continue, "
645 "GPT headers will be deleted.\n\n");
646 if (yesno("Should we write new partition table?")) {
647 delete_gpt(&gpt1);
648 delete_gpt(&gpt2);
649 write_mbr();
650 }
651 } else {
652 if (delete_gpt(&gpt1) > 0)
653 warnx("Primary GPT header was deleted");
654 if (delete_gpt(&gpt2) > 0)
655 warnx("Secondary GPT header was deleted");
656 write_mbr();
657 }
658 }
659
660 exit(0);
661 }
662
663 static void
usage(void)664 usage(void)
665 {
666 int indent = 7 + (int)strlen(getprogname()) + 1;
667
668 (void)fprintf(stderr, "usage: %s [-aBFfgIilSuv] "
669 "[-A ptn_alignment[/ptn_0_offset]] \\\n"
670 "%*s[-b cylinders/heads/sectors] \\\n"
671 "%*s[-0123 | -E num "
672 "[-s [id][/[start][/[size][/bootmenu]]]] \\\n"
673 "%*s[-t disktab] [-T disktype] \\\n"
674 "%*s[-c bootcode] "
675 "[-r|-w file] [-z sectorsize] [device]\n"
676 "\t-a change active partition\n"
677 "\t-f force - not interactive\n"
678 "\t-g preserve existing GPT headers\n"
679 "\t-i initialise MBR code\n"
680 "\t-I ignore errors about no space or overlapping partitions\n"
681 "\t-l list partition types\n"
682 "\t-u update partition data\n"
683 "\t-v verbose output, -v -v more verbose still\n"
684 "\t-B update bootselect options\n"
685 "\t-F treat device as a regular file\n"
686 "\t-S output as shell defines\n"
687 "\t-r and -w access 'file' for non-destructive testing\n",
688 getprogname(), indent, "", indent, "", indent, "", indent, "");
689 exit(1);
690 }
691
692 static daddr_t
ext_offset(int part)693 ext_offset(int part)
694 {
695 daddr_t offset = ext.base;
696
697 if (part != 0)
698 offset += le32toh(ext.ptn[part - 1].mbr_parts[1].mbrp_start);
699 return offset;
700 }
701
702 static void
print_s0(int which)703 print_s0(int which)
704 {
705 int part;
706
707 if (which == -1) {
708 if (!sh_flag)
709 printf("Partition table:\n");
710 for (part = 0; part < MBR_PART_COUNT; part++) {
711 if (!sh_flag)
712 printf("%d: ", part);
713 print_part(&mboot, part, 0);
714 }
715 if (!sh_flag) {
716 if (ext.is_corrupt)
717 printf("Extended partition table is corrupt\n");
718 else
719 if (ext.num_ptn != 0)
720 printf("Extended partition table:\n");
721 }
722 for (part = 0; part < ext.num_ptn; part++) {
723 if (!sh_flag)
724 printf("E%d: ", part);
725 print_part(&ext.ptn[part], 0, ext_offset(part));
726 if (!sh_flag && v_flag >= 2) {
727 printf("link: ");
728 print_mbr_partition(&ext.ptn[part], 1,
729 ext_offset(part), ext.base, 0);
730 }
731 }
732 #ifdef BOOTSEL
733 if (!sh_flag && mboot.mbr_bootsel_magic == LE_MBR_BS_MAGIC) {
734 int tmo;
735
736 printf("Bootselector ");
737 if (mboot.mbr_bootsel.mbrbs_flags & MBR_BS_ACTIVE) {
738 printf("enabled");
739 tmo = le16toh(mboot.mbr_bootsel.mbrbs_timeo);
740 if (tmo == 0xffff)
741 printf(", infinite timeout");
742 else
743 printf(", timeout %d seconds",
744 (10 * tmo + 9) / 182);
745 } else
746 printf("disabled");
747 printf(".\n");
748 }
749 #endif
750 if (!sh_flag) {
751 int active = first_active();
752 if (active == MBR_PART_COUNT)
753 printf("No active partition.\n");
754 else
755 printf("First active partition: %d\n", active);
756 }
757 if (!sh_flag)
758 printf("Drive serial number: %"PRIu32" (0x%08x)\n",
759 le32toh(mboot.mbr_dsn),
760 le32toh(mboot.mbr_dsn));
761 return;
762 }
763
764 if (E_flag) {
765 if (!sh_flag)
766 printf("Extended partition E%d:\n", which);
767 if (which > ext.num_ptn)
768 printf("Undefined\n");
769 else
770 print_part(&ext.ptn[which], 0, ext_offset(which));
771 } else {
772 if (!sh_flag)
773 printf("Partition %d:\n", which);
774 print_part(&mboot, which, 0);
775 }
776 }
777
778 static void
print_part(struct mbr_sector * boot,int part,daddr_t offset)779 print_part(struct mbr_sector *boot, int part, daddr_t offset)
780 {
781 struct mbr_partition *partp;
782 const char *e;
783
784 if (!sh_flag) {
785 print_mbr_partition(boot, part, offset, 0, 0);
786 return;
787 }
788
789 partp = &boot->mbr_parts[part];
790 if (boot != &mboot) {
791 part = boot - ext.ptn;
792 e = "E";
793 } else
794 e = "";
795
796 if (partp->mbrp_type == 0) {
797 printf("PART%s%dSIZE=0\n", e, part);
798 return;
799 }
800
801 printf("PART%s%dID=%d\n", e, part, partp->mbrp_type);
802 printf("PART%s%dSIZE=%u\n", e, part, le32toh(partp->mbrp_size));
803 printf("PART%s%dSTART=%"PRIdaddr"\n", e, part,
804 offset + le32toh(partp->mbrp_start));
805 printf("PART%s%dFLAG=0x%x\n", e, part, partp->mbrp_flag);
806 printf("PART%s%dBCYL=%d\n", e, part,
807 MBR_PCYL(partp->mbrp_scyl, partp->mbrp_ssect));
808 printf("PART%s%dBHEAD=%d\n", e, part, partp->mbrp_shd);
809 printf("PART%s%dBSEC=%d\n", e, part, MBR_PSECT(partp->mbrp_ssect));
810 printf("PART%s%dECYL=%d\n", e, part,
811 MBR_PCYL(partp->mbrp_ecyl, partp->mbrp_esect));
812 printf("PART%s%dEHEAD=%d\n", e, part, partp->mbrp_ehd);
813 printf("PART%s%dESEC=%d\n", e, part, MBR_PSECT(partp->mbrp_esect));
814 }
815
816 static void
pr_cyls(daddr_t sector,int is_end)817 pr_cyls(daddr_t sector, int is_end)
818 {
819 unsigned long cyl, head, sect;
820 cyl = sector / dos_cylindersectors;
821 sect = sector - cyl * dos_cylindersectors;
822 head = sect / dos_sectors;
823 sect -= head * dos_sectors;
824
825 printf("%lu", cyl);
826
827 if (is_end) {
828 if (head == dos_heads - 1 && sect == dos_sectors - 1)
829 return;
830 } else {
831 if (head == 0 && sect == 0)
832 return;
833 }
834
835 printf("/%lu/%lu", head, sect + 1);
836 }
837
838 static void
print_mbr_partition(struct mbr_sector * boot,int part,daddr_t offset,daddr_t exoffset,int indent)839 print_mbr_partition(struct mbr_sector *boot, int part,
840 daddr_t offset, daddr_t exoffset, int indent)
841 {
842 daddr_t start;
843 daddr_t size;
844 struct mbr_partition *partp = &boot->mbr_parts[part];
845 struct mbr_sector eboot;
846 int p;
847 static int dumped = 0;
848
849 if (partp->mbrp_type == 0 && v_flag < 2) {
850 printf("<UNUSED>\n");
851 return;
852 }
853
854 start = le32toh(partp->mbrp_start);
855 size = le32toh(partp->mbrp_size);
856 if (MBR_IS_EXTENDED(partp->mbrp_type))
857 start += exoffset;
858 else
859 start += offset;
860
861 printf("%s (sysid %d)\n", get_type(partp->mbrp_type), partp->mbrp_type);
862 #ifdef BOOTSEL
863 if (boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC &&
864 boot->mbr_bootsel.mbrbs_nametab[part][0])
865 printf("%*s bootmenu: %s\n", indent, "",
866 boot->mbr_bootsel.mbrbs_nametab[part]);
867 #endif
868
869 printf("%*s start %"PRIdaddr", size %"PRIdaddr,
870 indent, "", start, size);
871 if (size != 0) {
872 printf(" (%u MB, Cyls ", SEC_TO_MB(size));
873 if (v_flag == 0 && le32toh(partp->mbrp_start) == ptn_0_offset)
874 pr_cyls(start - ptn_0_offset, 0);
875 else
876 pr_cyls(start, 0);
877 printf("-");
878 pr_cyls(start + size - 1, 1);
879 printf(")");
880 }
881
882 switch (partp->mbrp_flag) {
883 case 0:
884 break;
885 case MBR_PFLAG_ACTIVE:
886 printf(", Active");
887 break;
888 default:
889 printf(", flag 0x%x", partp->mbrp_flag);
890 break;
891 }
892 printf("\n");
893
894 if (v_flag) {
895 printf("%*s beg: cylinder %4d, head %3d, sector %2d\n",
896 indent, "",
897 MBR_PCYL(partp->mbrp_scyl, partp->mbrp_ssect),
898 partp->mbrp_shd, MBR_PSECT(partp->mbrp_ssect));
899 printf("%*s end: cylinder %4d, head %3d, sector %2d\n",
900 indent, "",
901 MBR_PCYL(partp->mbrp_ecyl, partp->mbrp_esect),
902 partp->mbrp_ehd, MBR_PSECT(partp->mbrp_esect));
903 }
904
905 if (partp->mbrp_type == 0 && start == 0 && v_flag < 3)
906 return;
907
908 if (! MBR_IS_EXTENDED(partp->mbrp_type))
909 print_pbr(start, indent + 8, partp->mbrp_type);
910
911 if (!MBR_IS_EXTENDED(partp->mbrp_type) ||
912 (v_flag <= 2 && !ext.is_corrupt))
913 return;
914
915 /*
916 * Recursive dump extended table,
917 * This is read from the disk - so is wrong during editing.
918 * Just ensure we only show it once.
919 */
920 if (dumped)
921 return;
922
923 printf("%*s Extended partition table:\n", indent, "");
924 indent += 4;
925 if (read_s0(start, &eboot) == -1)
926 return;
927 for (p = 0; p < MBR_PART_COUNT; p++) {
928 printf("%*s%d: ", indent, "", p);
929 print_mbr_partition(&eboot, p, start,
930 exoffset ? exoffset : start, indent);
931 }
932
933 if (exoffset == 0)
934 dumped = 1;
935 }
936
937 /* Print a line with a label and a vis-encoded string */
938 static void
printvis(int indent,const char * label,const char * buf,size_t size)939 printvis(int indent, const char *label, const char *buf, size_t size)
940 {
941 char *visbuf;
942
943 if ((visbuf = malloc(size * 4 + 1)) == NULL)
944 err(1, "Malloc failed");
945 strsvisx(visbuf, buf, size, VIS_TAB|VIS_NL|VIS_OCTAL, "\"");
946 printf("%*s%s: \"%s\"\n",
947 indent, "",
948 label, visbuf);
949 free(visbuf);
950 }
951
952 /* Check whether a buffer contains all bytes zero */
953 static int
is_all_zero(const unsigned char * p,size_t size)954 is_all_zero(const unsigned char *p, size_t size)
955 {
956
957 while (size-- > 0) {
958 if (*p++ != 0)
959 return 0;
960 }
961 return 1;
962 }
963
964 /*
965 * Report on the contents of a PBR sector.
966 *
967 * We first perform several sanity checks. If vflag >= 2, we report all
968 * failing tests, but for smaller values of v_flag we stop after the
969 * first failing test. Tests are ordered in an attempt to get the most
970 * useful error message from the first failing test.
971 *
972 * If v_flag >= 2, we also report some decoded values from the PBR.
973 * These results may be meaningless, if the PBR doesn't follow common
974 * conventions.
975 *
976 * Trying to decode anything more than the magic number in the last
977 * two bytes is a layering violation, but it can be very useful in
978 * diagnosing boot failures.
979 */
980 static void
print_pbr(daddr_t sector,int indent,uint8_t part_type)981 print_pbr(daddr_t sector, int indent, uint8_t part_type)
982 {
983 struct mbr_sector pboot;
984 unsigned char *p, *endp;
985 unsigned char val;
986 int ok;
987 int errcount = 0;
988
989 #define PBR_ERROR(...) \
990 do { \
991 ++errcount; \
992 printf("%*s%s: ", indent, "", \
993 (v_flag < 2 ? "PBR is not bootable" : "Not bootable")); \
994 printf(__VA_ARGS__); \
995 if (v_flag < 2) \
996 return; \
997 } while (/*CONSTCOND*/ 0)
998
999 if (v_flag >= 2) {
1000 printf("%*sInformation from PBR:\n",
1001 indent, "");
1002 indent += 4;
1003 }
1004
1005 if (read_disk(sector, &pboot) == -1) {
1006 PBR_ERROR("Sector %"PRIdaddr" is unreadable (%s)\n",
1007 sector, strerror(errno));
1008 return;
1009 }
1010
1011 /* all bytes identical? */
1012 p = (unsigned char *)&pboot;
1013 endp = p + sizeof(pboot);
1014 val = *p;
1015 ok = 0;
1016 for (; p < endp; p++) {
1017 if (*p != val) {
1018 ok = 1;
1019 break;
1020 }
1021 }
1022 if (! ok)
1023 PBR_ERROR("All bytes are identical (0x%02x)\n", val);
1024
1025 if (pboot.mbr_magic != LE_MBR_MAGIC)
1026 PBR_ERROR("Bad magic number (0x%04x)\n",
1027 le16toh(pboot.mbr_magic));
1028
1029 #if 0
1030 /* Some i386 OS might fail this test. All non-i386 will fail. */
1031 if (pboot.mbr_jmpboot[0] != 0xE9
1032 && pboot.mbr_jmpboot[0] != 0xEB) {
1033 PBR_ERROR("Does not begin with i386 JMP instruction"
1034 " (0x%02x 0x%02x0 0x%02x)\n",
1035 pboot.mbr_jmpboot[0], pboot.mbr_jmpboot[1],
1036 pboot.mbr_jmpboot[2]);
1037 }
1038 #endif
1039
1040 if (v_flag > 0 && errcount == 0)
1041 printf("%*sPBR appears to be bootable\n",
1042 indent, "");
1043 if (v_flag < 2)
1044 return;
1045
1046 if (! is_all_zero(pboot.mbr_oemname, sizeof(pboot.mbr_oemname))) {
1047 printvis(indent, "OEM name", (char *)pboot.mbr_oemname,
1048 sizeof(pboot.mbr_oemname));
1049 }
1050
1051 if (pboot.mbr_bpb.bpb16.bsBootSig == 0x29)
1052 printf("%*sBPB FAT16 boot signature found\n",
1053 indent, "");
1054 if (pboot.mbr_bpb.bpb32.bsBootSig == 0x29)
1055 printf("%*sBPB FAT32 boot signature found\n",
1056 indent, "");
1057
1058 #undef PBR_ERROR
1059 }
1060
1061 static int
read_boot(const char * name,void * buf,size_t len,int err_exit)1062 read_boot(const char *name, void *buf, size_t len, int err_exit)
1063 {
1064 int bfd, ret;
1065 struct stat st;
1066
1067 if (boot_path != NULL)
1068 free(boot_path);
1069 if (strchr(name, '/') == 0)
1070 asprintf(&boot_path, "%s/%s", boot_dir, name);
1071 else
1072 boot_path = strdup(name);
1073 if (boot_path == NULL)
1074 err(1, "Malloc failed");
1075
1076 if ((bfd = open(boot_path, O_RDONLY)) < 0 || fstat(bfd, &st) == -1) {
1077 warn("%s", boot_path);
1078 goto fail;
1079 }
1080
1081 if (st.st_size > (off_t)len) {
1082 warnx("%s: bootcode too large", boot_path);
1083 goto fail;
1084 }
1085 ret = st.st_size;
1086 if (ret < 0x200) {
1087 warnx("%s: bootcode too small", boot_path);
1088 goto fail;
1089 }
1090 if (read(bfd, buf, len) != ret) {
1091 warn("%s", boot_path);
1092 goto fail;
1093 }
1094
1095 /*
1096 * Do some sanity checking here
1097 */
1098 if (((struct mbr_sector *)buf)->mbr_magic != LE_MBR_MAGIC) {
1099 warnx("%s: invalid magic", boot_path);
1100 goto fail;
1101 }
1102
1103 close(bfd);
1104 ret = (ret + 0x1ff) & ~0x1ff;
1105 return ret;
1106
1107 fail:
1108 if (bfd >= 0)
1109 close(bfd);
1110 if (err_exit)
1111 exit(1);
1112 return 0;
1113 }
1114
1115 static void
init_sector0(int zappart)1116 init_sector0(int zappart)
1117 {
1118 int i;
1119 int copy_size = offsetof(struct mbr_sector, mbr_dsn);
1120
1121 #ifdef DEFAULT_BOOTCODE
1122 if (bootsize == 0)
1123 bootsize = read_boot(DEFAULT_BOOTCODE, bootcode,
1124 sizeof bootcode, 0);
1125 #endif
1126 #ifdef BOOTSEL
1127 if (mboot.mbr_bootsel_magic == LE_MBR_BS_MAGIC
1128 && bootcode[0].mbr_bootsel_magic == LE_MBR_BS_MAGIC)
1129 copy_size = MBR_BS_OFFSET;
1130 #endif
1131
1132 if (bootsize != 0) {
1133 boot_installed = 1;
1134 memcpy(&mboot, bootcode, copy_size);
1135 mboot.mbr_bootsel_magic = bootcode[0].mbr_bootsel_magic;
1136 }
1137 mboot.mbr_magic = LE_MBR_MAGIC;
1138
1139 if (!zappart)
1140 return;
1141 for (i = 0; i < MBR_PART_COUNT; i++)
1142 memset(&mboot.mbr_parts[i], 0, sizeof(mboot.mbr_parts[i]));
1143 }
1144
1145 static void
get_extended_ptn(void)1146 get_extended_ptn(void)
1147 {
1148 struct mbr_partition *mp;
1149 struct mbr_sector *boot;
1150 daddr_t offset;
1151
1152 /* find first (there should only be one) extended partition */
1153 for (mp = mboot.mbr_parts; !MBR_IS_EXTENDED(mp->mbrp_type); mp++)
1154 if (mp >= &mboot.mbr_parts[MBR_PART_COUNT])
1155 return;
1156
1157 /*
1158 * The extended partition should be structured as a linked list
1159 * (even though it appears, at first glance, to be a tree).
1160 */
1161 ext.base = le32toh(mp->mbrp_start);
1162 ext.limit = ext.base + le32toh(mp->mbrp_size);
1163 ext.ptn_id = mp - mboot.mbr_parts;
1164 for (offset = 0;; offset = le32toh(boot->mbr_parts[1].mbrp_start)) {
1165 if (reallocarr(&ext.ptn,
1166 ext.num_ptn + 1, sizeof(*ext.ptn)) != 0)
1167 err(1, "Malloc failed");
1168 boot = ext.ptn + ext.num_ptn;
1169 if (read_s0(offset + ext.base, boot) == -1)
1170 break;
1171 /* expect p0 to be valid and p1 to be another extended ptn */
1172 if (MBR_IS_EXTENDED(boot->mbr_parts[0].mbrp_type))
1173 break;
1174 if (boot->mbr_parts[1].mbrp_type != 0 &&
1175 !MBR_IS_EXTENDED(boot->mbr_parts[1].mbrp_type))
1176 break;
1177 /* p2 and p3 should be unallocated */
1178 if (boot->mbr_parts[2].mbrp_type != 0 ||
1179 boot->mbr_parts[3].mbrp_type != 0)
1180 break;
1181 /* data ptn inside extended one */
1182 if (boot->mbr_parts[0].mbrp_type != 0 &&
1183 offset + le32toh(boot->mbr_parts[0].mbrp_start)
1184 + le32toh(boot->mbr_parts[0].mbrp_size) > ext.limit)
1185 break;
1186
1187 ext.num_ptn++;
1188
1189 if (boot->mbr_parts[1].mbrp_type == 0)
1190 /* end of extended partition chain */
1191 return;
1192 /* must be in sector order */
1193 if (offset >= le32toh(boot->mbr_parts[1].mbrp_start))
1194 break;
1195 }
1196
1197 warnx("Extended partition table is corrupt");
1198 ext.is_corrupt = 1;
1199 ext.num_ptn = 0;
1200 }
1201
1202 #if defined(USE_DISKLIST)
1203 static void
get_diskname(const char * fullname,char * diskname,size_t size)1204 get_diskname(const char *fullname, char *diskname, size_t size)
1205 {
1206 const char *p, *p2;
1207 size_t len;
1208
1209 p = strrchr(fullname, '/');
1210 if (p == NULL)
1211 p = fullname;
1212 else
1213 p++;
1214
1215 if (*p == 0) {
1216 strlcpy(diskname, fullname, size);
1217 return;
1218 }
1219
1220 if (*p == 'r')
1221 p++;
1222
1223 for (p2 = p; *p2 != 0; p2++)
1224 if (isdigit((unsigned char)*p2))
1225 break;
1226 if (*p2 == 0) {
1227 /* XXX invalid diskname? */
1228 strlcpy(diskname, fullname, size);
1229 return;
1230 }
1231 while (isdigit((unsigned char)*p2))
1232 p2++;
1233
1234 len = p2 - p;
1235 if (len > size) {
1236 /* XXX */
1237 strlcpy(diskname, fullname, size);
1238 return;
1239 }
1240
1241 memcpy(diskname, p, len);
1242 diskname[len] = 0;
1243 }
1244 #endif
1245
1246 static void
get_ptn_alignmemt(void)1247 get_ptn_alignmemt(void)
1248 {
1249 struct mbr_partition *partp = &mboot.mbr_parts[0];
1250 uint32_t ptn_0_base, ptn_0_limit;
1251
1252 /* Default to using 'traditional' cylinder alignment */
1253 ptn_alignment = dos_cylindersectors;
1254 ptn_0_offset = dos_sectors;
1255
1256 if (partp->mbrp_type != 0) {
1257 /* Try to copy alignment of first partition */
1258 ptn_0_base = le32toh(partp->mbrp_start);
1259 ptn_0_limit = ptn_0_base + le32toh(partp->mbrp_size);
1260 if (!(ptn_0_limit & 2047)) {
1261 /* Partition ends on a 1MB boundary, align to 1MB */
1262 ptn_alignment = 2048;
1263 if (ptn_0_base <= 2048
1264 && !(ptn_0_base & (ptn_0_base - 1))) {
1265 /* ptn_base is a power of 2, use it */
1266 ptn_0_offset = ptn_0_base;
1267 }
1268 }
1269 } else {
1270 /* Use 1MB alignment for large disks */
1271 if (disksectors > 2048 * 1024 * 128) {
1272 ptn_alignment = 2048;
1273 ptn_0_offset = 2048;
1274 }
1275 }
1276 }
1277
1278 static void
get_bios_geometry(void)1279 get_bios_geometry(void)
1280 {
1281 #if defined(USE_DISKLIST)
1282 int mib[2], i;
1283 size_t len;
1284 struct biosdisk_info *bip;
1285 struct nativedisk_info *nip;
1286 char diskname[8];
1287
1288 mib[0] = CTL_MACHDEP;
1289 mib[1] = CPU_DISKINFO;
1290 if (sysctl(mib, 2, NULL, &len, NULL, 0) < 0) {
1291 goto out;
1292 }
1293 dl = (struct disklist *) malloc(len);
1294 if (dl == NULL)
1295 err(1, "Malloc failed");
1296 if (sysctl(mib, 2, dl, &len, NULL, 0) < 0) {
1297 free(dl);
1298 dl = 0;
1299 goto out;
1300 }
1301
1302 get_diskname(disk, diskname, sizeof diskname);
1303
1304 for (i = 0; i < dl->dl_nnativedisks; i++) {
1305 nip = &dl->dl_nativedisks[i];
1306 if (strcmp(diskname, nip->ni_devname))
1307 continue;
1308 /*
1309 * XXX listing possible matches is better. This is ok for
1310 * now because the user has a chance to change it later.
1311 * Also, if all the disks have the same parameters then we can
1312 * just use them, we don't need to know which disk is which.
1313 */
1314 if (nip->ni_nmatches != 0) {
1315 bip = &dl->dl_biosdisks[nip->ni_biosmatches[0]];
1316 dos_cylinders = bip->bi_cyl;
1317 dos_heads = bip->bi_head;
1318 dos_sectors = bip->bi_sec;
1319 if (bip->bi_lbasecs)
1320 dos_disksectors = bip->bi_lbasecs;
1321 return;
1322 }
1323 }
1324 out:
1325 #endif
1326 /* Allright, allright, make a stupid guess.. */
1327 intuit_translated_geometry();
1328 }
1329
1330 #ifdef BOOTSEL
1331 static daddr_t
get_default_boot(void)1332 get_default_boot(void)
1333 {
1334 unsigned int id;
1335 int p;
1336
1337 if (mboot.mbr_bootsel_magic != LE_MBR_BS_MAGIC)
1338 /* default to first active partition */
1339 return DEFAULT_ACTIVE;
1340
1341 id = mboot.mbr_bootsel.mbrbs_defkey;
1342
1343 if (mboot.mbr_bootsel.mbrbs_flags & MBR_BS_ASCII) {
1344 /* Keycode is ascii */
1345 if (id == '\r')
1346 return DEFAULT_ACTIVE;
1347 /* '1'+ => allocated partition id, 'a'+ => disk 0+ */
1348 if (id >= 'a' && id < 'a' + MAX_BIOS_DISKS)
1349 return DEFAULT_DISK(id - 'a');
1350 id -= '1';
1351 } else {
1352 /* keycode is PS/2 keycode */
1353 if (id == SCAN_ENTER)
1354 return DEFAULT_ACTIVE;
1355 /* 1+ => allocated partition id, F1+ => disk 0+ */
1356 if (id >= SCAN_F1 && id < SCAN_F1 + MAX_BIOS_DISKS)
1357 return DEFAULT_DISK(id - SCAN_F1);
1358 id -= SCAN_1;
1359 }
1360
1361 /* Convert partition index to the invariant start sector number */
1362
1363 for (p = 0; p < MBR_PART_COUNT; p++) {
1364 if (mboot.mbr_parts[p].mbrp_type == 0)
1365 continue;
1366 if (mboot.mbr_bootsel.mbrbs_nametab[p][0] == 0)
1367 continue;
1368 if (id-- == 0)
1369 return le32toh(mboot.mbr_parts[p].mbrp_start);
1370 }
1371
1372 for (p = 0; p < ext.num_ptn; p++) {
1373 if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
1374 continue;
1375 if (ext.ptn[p].mbr_bootsel.mbrbs_nametab[0][0] == 0)
1376 continue;
1377 if (id-- == 0)
1378 return ext_offset(p)
1379 + le32toh(ext.ptn[p].mbr_parts[0].mbrp_start);
1380 }
1381
1382 return DEFAULT_ACTIVE;
1383 }
1384
1385 static void
set_default_boot(daddr_t default_ptn)1386 set_default_boot(daddr_t default_ptn)
1387 {
1388 int p;
1389 static const unsigned char key_list[] = { SCAN_ENTER, SCAN_F1, SCAN_1,
1390 '\r', 'a', '1' };
1391 const unsigned char *key = key_list;
1392
1393 if (mboot.mbr_bootsel_magic != LE_MBR_BS_MAGIC)
1394 /* sanity */
1395 return;
1396
1397 if (mboot.mbr_bootsel.mbrbs_flags & MBR_BS_ASCII)
1398 /* Use ascii values */
1399 key += 3;
1400
1401 if (default_ptn == DEFAULT_ACTIVE) {
1402 mboot.mbr_bootsel.mbrbs_defkey = key[0];
1403 return;
1404 }
1405
1406 if (default_ptn >= DEFAULT_DISK(0)
1407 && default_ptn < DEFAULT_DISK(MAX_BIOS_DISKS)) {
1408 mboot.mbr_bootsel.mbrbs_defkey = key[1]
1409 + default_ptn - DEFAULT_DISK(0);
1410 return;
1411 }
1412
1413 mboot.mbr_bootsel.mbrbs_defkey = key[2];
1414 for (p = 0; p < MBR_PART_COUNT; p++) {
1415 if (mboot.mbr_parts[p].mbrp_type == 0)
1416 continue;
1417 if (mboot.mbr_bootsel.mbrbs_nametab[p][0] == 0)
1418 continue;
1419 if (le32toh(mboot.mbr_parts[p].mbrp_start) == default_ptn)
1420 return;
1421 mboot.mbr_bootsel.mbrbs_defkey++;
1422 }
1423
1424 if (mboot.mbr_bootsel.mbrbs_flags & MBR_BS_EXTLBA) {
1425 for (p = 0; p < ext.num_ptn; p++) {
1426 if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
1427 continue;
1428 if (ext.ptn[p].mbr_bootsel.mbrbs_nametab[0][0] == 0)
1429 continue;
1430 if (le32toh(ext.ptn[p].mbr_parts[0].mbrp_start) +
1431 ext_offset(p) == default_ptn)
1432 return;
1433 mboot.mbr_bootsel.mbrbs_defkey++;
1434 }
1435 }
1436
1437 /* Default to first active partition */
1438 mboot.mbr_bootsel.mbrbs_defkey = key[0];
1439 }
1440
1441 static void
install_bootsel(int needed)1442 install_bootsel(int needed)
1443 {
1444 struct mbr_bootsel *mbs = &mboot.mbr_bootsel;
1445 int p;
1446 int ext13 = 0;
1447 const char *code;
1448
1449 needed |= MBR_BS_NEWMBR; /* need new bootsel code */
1450
1451 /* Work out which boot code we need for this configuration */
1452 for (p = 0; p < MBR_PART_COUNT; p++) {
1453 if (mboot.mbr_parts[p].mbrp_type == 0)
1454 continue;
1455 if (mboot.mbr_bootsel_magic != LE_MBR_BS_MAGIC)
1456 break;
1457 if (mbs->mbrbs_nametab[p][0] == 0)
1458 continue;
1459 needed |= MBR_BS_ACTIVE;
1460 if (le32toh(mboot.mbr_parts[p].mbrp_start) >= dos_totalsectors)
1461 ext13 = MBR_BS_EXTINT13;
1462 }
1463
1464 for (p = 0; p < ext.num_ptn; p++) {
1465 if (ext.ptn[p].mbr_bootsel_magic != LE_MBR_BS_MAGIC)
1466 continue;
1467 if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
1468 continue;
1469 if (ext.ptn[p].mbr_bootsel.mbrbs_nametab[p][0] == 0)
1470 continue;
1471 needed |= MBR_BS_EXTLBA | MBR_BS_ACTIVE;
1472 }
1473
1474 if (B_flag)
1475 needed |= MBR_BS_ACTIVE;
1476
1477 /* Is the installed code good enough ? */
1478 if (!i_flag && (needed == 0 ||
1479 (mboot.mbr_bootsel_magic == LE_MBR_BS_MAGIC
1480 && (mbs->mbrbs_flags & needed) == needed))) {
1481 /* yes - just set flags */
1482 mbs->mbrbs_flags |= ext13;
1483 return;
1484 }
1485
1486 /* ok - we need to replace the bootcode */
1487
1488 if (f_flag && !(i_flag || B_flag)) {
1489 warnx("Installed bootfile doesn't support required options.");
1490 return;
1491 }
1492
1493 if (!f_flag && bootsize == 0 && !i_flag)
1494 /* Output an explanation for the 'update bootcode' prompt. */
1495 printf("\n%s\n",
1496 "Installed bootfile doesn't support required options.");
1497
1498 /* Were we told a specific file ? (which we have already read) */
1499 /* If so check that it supports what we need. */
1500 if (bootsize != 0 && needed != 0
1501 && (bootcode[0].mbr_bootsel_magic != LE_MBR_BS_MAGIC
1502 || ((bootcode[0].mbr_bootsel.mbrbs_flags & needed) != needed))) {
1503 /* No it doesn't... */
1504 if (f_flag)
1505 warnx("Bootfile %s doesn't support "
1506 "required bootsel options", boot_path );
1507 /* But install it anyway */
1508 else
1509 if (yesno("Bootfile %s doesn't support the required "
1510 "options,\ninstall default bootfile instead?",
1511 boot_path))
1512 bootsize = 0;
1513 }
1514
1515 if (bootsize == 0) {
1516 /* Get name of bootfile that supports the required facilities */
1517 code = DEFAULT_BOOTCODE;
1518 if (needed & MBR_BS_ACTIVE)
1519 code = DEFAULT_BOOTSELCODE;
1520 #ifdef DEFAULT_BOOTEXTCODE
1521 if (needed & MBR_BS_EXTLBA)
1522 code = DEFAULT_BOOTEXTCODE;
1523 #endif
1524
1525 bootsize = read_boot(code, bootcode, sizeof bootcode, 0);
1526 if (bootsize == 0)
1527 /* The old bootcode is better than no bootcode at all */
1528 return;
1529 if ((bootcode[0].mbr_bootsel.mbrbs_flags & needed) != needed)
1530 warnx("Default bootfile %s doesn't support required "
1531 "options. Got flags 0x%x, wanted 0x%x\n",
1532 boot_path, bootcode[0].mbr_bootsel.mbrbs_flags,
1533 needed);
1534 }
1535
1536 if (!f_flag && !yesno("Update the bootcode from %s?", boot_path))
1537 return;
1538
1539 init_sector0(0);
1540
1541 if (mboot.mbr_bootsel_magic == LE_MBR_BS_MAGIC)
1542 mbs->mbrbs_flags = bootcode[0].mbr_bootsel.mbrbs_flags | ext13;
1543 }
1544
1545 static daddr_t
configure_bootsel(daddr_t default_ptn)1546 configure_bootsel(daddr_t default_ptn)
1547 {
1548 struct mbr_bootsel *mbs = &mboot.mbr_bootsel;
1549 int i, item, opt;
1550 int tmo;
1551 daddr_t *off;
1552 int num_bios_disks;
1553
1554 #if defined(USE_DISKLIST)
1555 if (dl != NULL) {
1556 num_bios_disks = dl->dl_nbiosdisks;
1557 if (num_bios_disks > MAX_BIOS_DISKS)
1558 num_bios_disks = MAX_BIOS_DISKS;
1559 } else
1560 #endif
1561 num_bios_disks = MAX_BIOS_DISKS;
1562
1563 printf("\nBoot selector configuration:\n");
1564
1565 /* The timeout value is in ticks, ~18.2 Hz. Avoid using floats.
1566 * Ticks are nearly 64k/3600 - so our long timers are sligtly out!
1567 * Newer bootcode always waits for 1 tick, so treats 0xffff
1568 * as wait forever.
1569 */
1570 tmo = le16toh(mbs->mbrbs_timeo);
1571 tmo = tmo == 0xffff ? -1 : (10 * tmo + 9) / 182;
1572 tmo = decimal("Timeout value (0 to 3600 seconds, -1 => never)",
1573 tmo, 0, -1, 3600);
1574 mbs->mbrbs_timeo = htole16(tmo == -1 ? 0xffff : (tmo * 182) / 10);
1575
1576 off = calloc(1 + MBR_PART_COUNT + ext.num_ptn + num_bios_disks, sizeof *off);
1577 if (off == NULL)
1578 err(1, "Malloc failed");
1579
1580 printf("Select the default boot option. Options are:\n\n");
1581 item = 0;
1582 opt = 0;
1583 off[opt] = DEFAULT_ACTIVE;
1584 printf("%d: The first active partition\n", opt);
1585 for (i = 0; i < MBR_PART_COUNT; i++) {
1586 if (mboot.mbr_parts[i].mbrp_type == 0)
1587 continue;
1588 if (mbs->mbrbs_nametab[i][0] == 0)
1589 continue;
1590 printf("%d: %s\n", ++opt, &mbs->mbrbs_nametab[i][0]);
1591 off[opt] = le32toh(mboot.mbr_parts[i].mbrp_start);
1592 if (off[opt] == default_ptn)
1593 item = opt;
1594 }
1595 if (mbs->mbrbs_flags & MBR_BS_EXTLBA) {
1596 for (i = 0; i < ext.num_ptn; i++) {
1597 if (ext.ptn[i].mbr_parts[0].mbrp_type == 0)
1598 continue;
1599 if (ext.ptn[i].mbr_bootsel.mbrbs_nametab[0][0] == 0)
1600 continue;
1601 printf("%d: %s\n",
1602 ++opt, ext.ptn[i].mbr_bootsel.mbrbs_nametab[0]);
1603 off[opt] = ext_offset(i) +
1604 le32toh(ext.ptn[i].mbr_parts[0].mbrp_start);
1605 if (off[opt] == default_ptn)
1606 item = opt;
1607 }
1608 }
1609 for (i = 0; i < num_bios_disks; i++) {
1610 printf("%d: Harddisk %d\n", ++opt, i);
1611 off[opt] = DEFAULT_DISK(i);
1612 if (DEFAULT_DISK(i) == default_ptn)
1613 item = opt;
1614 }
1615
1616 item = decimal("Default boot option", item, 0, 0, opt);
1617
1618 default_ptn = off[item];
1619 free(off);
1620 return default_ptn;
1621 }
1622 #endif /* BOOTSEL */
1623
1624
1625 /* Prerequisite: the disklabel parameters and master boot record must
1626 * have been read (i.e. dos_* and mboot are meaningful).
1627 * Specification: modifies dos_cylinders, dos_heads, dos_sectors, and
1628 * dos_cylindersectors to be consistent with what the
1629 * partition table is using, if we can find a geometry
1630 * which is consistent with all partition table entries.
1631 * We may get the number of cylinders slightly wrong (in
1632 * the conservative direction). The idea is to be able
1633 * to create a NetBSD partition on a disk we don't know
1634 * the translated geometry of.
1635 * This routine is only used for non-x86 systems or when we fail to
1636 * get the BIOS geometry from the kernel.
1637 */
1638 static void
intuit_translated_geometry(void)1639 intuit_translated_geometry(void)
1640 {
1641 uint32_t xcylinders;
1642 int xheads = -1, xsectors = -1, i, j;
1643 unsigned int c1, h1, s1, c2, h2, s2;
1644 unsigned long a1, a2;
1645 uint64_t num, denom;
1646
1647 /*
1648 * The physical parameters may be invalid as bios geometry.
1649 * If we cannot determine the actual bios geometry, we are
1650 * better off picking a likely 'faked' geometry than leaving
1651 * the invalid physical one.
1652 */
1653
1654 if (dos_cylinders > MAXCYL || dos_heads > MAXHEAD ||
1655 dos_sectors > MAXSECTOR) {
1656 h1 = MAXHEAD - 1;
1657 c1 = MAXCYL - 1;
1658 #if defined(USE_DISKLIST)
1659 if (dl != NULL) {
1660 /* BIOS may use 256 heads or 1024 cylinders */
1661 for (i = 0; i < dl->dl_nbiosdisks; i++) {
1662 if (h1 < (unsigned int)dl->dl_biosdisks[i].bi_head)
1663 h1 = dl->dl_biosdisks[i].bi_head;
1664 if (c1 < (unsigned int)dl->dl_biosdisks[i].bi_cyl)
1665 c1 = dl->dl_biosdisks[i].bi_cyl;
1666 }
1667 }
1668 #endif
1669 dos_sectors = MAXSECTOR;
1670 dos_heads = h1;
1671 dos_cylinders = disklabel.d_secperunit / (MAXSECTOR * h1);
1672 if (dos_cylinders > c1)
1673 dos_cylinders = c1;
1674 }
1675
1676 /* Try to deduce the number of heads from two different mappings. */
1677 for (i = 0; i < MBR_PART_COUNT * 2 - 1; i++) {
1678 if (get_mapping(i, &c1, &h1, &s1, &a1) < 0)
1679 continue;
1680 a1 -= s1;
1681 for (j = i + 1; j < MBR_PART_COUNT * 2; j++) {
1682 if (get_mapping(j, &c2, &h2, &s2, &a2) < 0)
1683 continue;
1684 a2 -= s2;
1685 num = (uint64_t)h1 * a2 - (uint64_t)h2 * a1;
1686 denom = (uint64_t)c2 * a1 - (uint64_t)c1 * a2;
1687 if (denom != 0 && num != 0 && num % denom == 0) {
1688 xheads = num / denom;
1689 xsectors = a1 / (c1 * xheads + h1);
1690 break;
1691 }
1692 }
1693 if (xheads != -1)
1694 break;
1695 }
1696
1697 if (xheads == -1) {
1698 if (F_flag)
1699 return;
1700 warnx("Cannot determine the number of heads");
1701 return;
1702 }
1703
1704 if (xsectors == -1) {
1705 warnx("Cannot determine the number of sectors");
1706 return;
1707 }
1708
1709 /* Estimate the number of cylinders. */
1710 xcylinders = disklabel.d_secperunit / xheads / xsectors;
1711 if (disklabel.d_secperunit > xcylinders * xheads * xsectors)
1712 xcylinders++;
1713
1714 /*
1715 * Now verify consistency with each of the partition table entries.
1716 * Be willing to shove cylinders up a little bit to make things work,
1717 * but translation mismatches are fatal.
1718 */
1719 for (i = 0; i < MBR_PART_COUNT * 2; i++) {
1720 if (get_mapping(i, &c1, &h1, &s1, &a1) < 0)
1721 continue;
1722 if (c1 >= MAXCYL - 2)
1723 continue;
1724 if (xsectors * (c1 * xheads + h1) + s1 != a1)
1725 return;
1726 }
1727
1728
1729 /* Everything checks out.
1730 * Reset the geometry to use for further calculations.
1731 * But cylinders cannot be > 1024.
1732 */
1733 if (xcylinders > MAXCYL)
1734 dos_cylinders = MAXCYL;
1735 else
1736 dos_cylinders = xcylinders;
1737 dos_heads = xheads;
1738 dos_sectors = xsectors;
1739 }
1740
1741 /*
1742 * For the purposes of intuit_translated_geometry(), treat the partition
1743 * table as a list of eight mapping between (cylinder, head, sector)
1744 * triplets and absolute sectors. Get the relevant geometry triplet and
1745 * absolute sectors for a given entry, or return -1 if it isn't present.
1746 * Note: for simplicity, the returned sector is 0-based.
1747 */
1748 static int
get_mapping(int i,unsigned int * cylinder,unsigned int * head,unsigned int * sector,unsigned long * absolute)1749 get_mapping(int i, unsigned int *cylinder, unsigned int *head, unsigned int *sector,
1750 unsigned long *absolute)
1751 {
1752 struct mbr_partition *part = &mboot.mbr_parts[i / 2];
1753
1754 if (part->mbrp_type == 0)
1755 return -1;
1756 if (i % 2 == 0) {
1757 *cylinder = MBR_PCYL(part->mbrp_scyl, part->mbrp_ssect);
1758 *head = part->mbrp_shd;
1759 *sector = MBR_PSECT(part->mbrp_ssect);
1760 *absolute = le32toh(part->mbrp_start);
1761 } else {
1762 *cylinder = MBR_PCYL(part->mbrp_ecyl, part->mbrp_esect);
1763 *head = part->mbrp_ehd;
1764 *sector = MBR_PSECT(part->mbrp_esect);
1765 *absolute = le32toh(part->mbrp_start)
1766 + le32toh(part->mbrp_size) - 1;
1767 }
1768 /* Sanity check the data against all zeroes */
1769 if ((*cylinder == 0) && (*sector == 0) && (*head == 0))
1770 return -1;
1771 /* sector numbers in the MBR partition table start at 1 */
1772 *sector = *sector - 1;
1773 /* Sanity check the data against max values */
1774 if ((((*cylinder * MAXHEAD) + *head) * MAXSECTOR + *sector) < *absolute)
1775 /* cannot be a CHS mapping */
1776 return -1;
1777 return 0;
1778 }
1779
1780 static void
delete_ptn(int part)1781 delete_ptn(int part)
1782 {
1783 if (part == ext.ptn_id) {
1784 /* forget all about the extended partition */
1785 free(ext.ptn);
1786 memset(&ext, 0, sizeof ext);
1787 }
1788
1789 mboot.mbr_parts[part].mbrp_type = 0;
1790 }
1791
1792 static void
delete_ext_ptn(int part)1793 delete_ext_ptn(int part)
1794 {
1795
1796 if (part == 0) {
1797 ext.ptn[0].mbr_parts[0].mbrp_type = 0;
1798 return;
1799 }
1800 ext.ptn[part - 1].mbr_parts[1] = ext.ptn[part].mbr_parts[1];
1801 memmove(&ext.ptn[part], &ext.ptn[part + 1],
1802 (ext.num_ptn - part - 1) * sizeof ext.ptn[0]);
1803 ext.num_ptn--;
1804 }
1805
1806 static int
add_ext_ptn(daddr_t start,daddr_t size)1807 add_ext_ptn(daddr_t start, daddr_t size)
1808 {
1809 int part;
1810 struct mbr_partition *partp;
1811
1812 if (reallocarr(&ext.ptn, ext.num_ptn + 1, sizeof(*ext.ptn)) != 0)
1813 err(1, "reallocarr");
1814 for (part = 0; part < ext.num_ptn; part++)
1815 if (ext_offset(part) > start)
1816 break;
1817 /* insert before 'part' - make space... */
1818 memmove(&ext.ptn[part + 1], &ext.ptn[part],
1819 (ext.num_ptn - part) * sizeof ext.ptn[0]);
1820 memset(&ext.ptn[part], 0, sizeof ext.ptn[0]);
1821 ext.ptn[part].mbr_magic = LE_MBR_MAGIC;
1822 /* we will be 'part' */
1823 if (part == 0) {
1824 /* link us to 'next' */
1825 partp = &ext.ptn[0].mbr_parts[1];
1826 /* offset will be fixed by caller */
1827 partp->mbrp_size = htole32(
1828 le32toh(ext.ptn[1].mbr_parts[0].mbrp_start) +
1829 le32toh(ext.ptn[1].mbr_parts[0].mbrp_size));
1830 } else {
1831 /* link us to prev's next */
1832 partp = &ext.ptn[part - 1].mbr_parts[1];
1833 ext.ptn[part].mbr_parts[1] = *partp;
1834 /* and prev onto us */
1835 partp->mbrp_start = htole32(start - ptn_0_offset - ext.base);
1836 partp->mbrp_size = htole32(size + ptn_0_offset);
1837 }
1838 partp->mbrp_type = 5; /* as used by win98 */
1839 partp->mbrp_flag = 0;
1840 /* wallop in some CHS values - win98 doesn't saturate them */
1841 dos(le32toh(partp->mbrp_start),
1842 &partp->mbrp_scyl, &partp->mbrp_shd, &partp->mbrp_ssect);
1843 dos(le32toh(partp->mbrp_start) + le32toh(partp->mbrp_size) - 1,
1844 &partp->mbrp_ecyl, &partp->mbrp_ehd, &partp->mbrp_esect);
1845 ext.num_ptn++;
1846
1847 return part;
1848 }
1849
1850 static const char *
check_overlap(int part,int sysid,daddr_t start,daddr_t size,int fix)1851 check_overlap(int part, int sysid, daddr_t start, daddr_t size, int fix)
1852 {
1853 int p;
1854 unsigned int p_s, p_e;
1855
1856 if (sysid != 0) {
1857 if (start == 0)
1858 return "Sector zero is reserved for the MBR";
1859 #if 0
1860 if (start < ptn_0_offset)
1861 /* This is just a convention, not a requirement */
1862 return "Track zero is reserved for the BIOS";
1863 #endif
1864 if (start + size > disksectors)
1865 return "Partition exceeds size of disk";
1866 for (p = 0; p < MBR_PART_COUNT; p++) {
1867 if (p == part || mboot.mbr_parts[p].mbrp_type == 0)
1868 continue;
1869 p_s = le32toh(mboot.mbr_parts[p].mbrp_start);
1870 p_e = p_s + le32toh(mboot.mbr_parts[p].mbrp_size);
1871 if (start + size <= p_s || start >= p_e)
1872 continue;
1873 if (f_flag) {
1874 if (fix)
1875 delete_ptn(p);
1876 return 0;
1877 }
1878 return "Overlaps another partition";
1879 }
1880 }
1881
1882 /* Are we trying to create an extended partition */
1883 if (!MBR_IS_EXTENDED(mboot.mbr_parts[part].mbrp_type)) {
1884 /* this wasn't the extended partition */
1885 if (!MBR_IS_EXTENDED(sysid))
1886 return 0;
1887 /* making an extended partition */
1888 if (ext.base != 0) {
1889 if (!f_flag)
1890 return "There cannot be 2 extended partitions";
1891 if (fix)
1892 delete_ptn(ext.ptn_id);
1893 }
1894 if (fix) {
1895 /* allocate a new extended partition */
1896 ext.ptn = calloc(1, sizeof ext.ptn[0]);
1897 if (ext.ptn == NULL)
1898 err(1, "Malloc failed");
1899 ext.ptn[0].mbr_magic = LE_MBR_MAGIC;
1900 ext.ptn_id = part;
1901 ext.base = start;
1902 ext.limit = start + size;
1903 ext.num_ptn = 1;
1904 }
1905 return 0;
1906 }
1907
1908 /* Check we haven't cut space allocated to an extended ptn */
1909
1910 if (!MBR_IS_EXTENDED(sysid)) {
1911 /* no longer an extended partition */
1912 if (fix) {
1913 /* Kill all memory of the extended partitions */
1914 delete_ptn(part);
1915 return 0;
1916 }
1917 if (ext.num_ptn == 0 ||
1918 (ext.num_ptn == 1 && ext.ptn[0].mbr_parts[0].mbrp_type == 0))
1919 /* nothing in extended partition */
1920 return 0;
1921 if (f_flag)
1922 return 0;
1923 if (yesno("Do you really want to delete all the extended partitions?"))
1924 return 0;
1925 return "Extended partition busy";
1926 }
1927
1928 if (le32toh(mboot.mbr_parts[part].mbrp_start) != ext.base)
1929 /* maybe impossible, but an extra sanity check */
1930 return 0;
1931
1932 for (p = ext.num_ptn; --p >= 0;) {
1933 if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
1934 continue;
1935 p_s = ext_offset(p);
1936 p_e = p_s + le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
1937 + le32toh(ext.ptn[p].mbr_parts[0].mbrp_size);
1938 if (p_s >= start && p_e <= start + size)
1939 continue;
1940 if (!f_flag)
1941 return "Extended partition outside main partition";
1942 if (fix)
1943 delete_ext_ptn(p);
1944 }
1945
1946 if (fix && start != ext.base) {
1947 /* The internal offsets need to be fixed up */
1948 for (p = 0; p < ext.num_ptn - 1; p++)
1949 ext.ptn[p].mbr_parts[1].mbrp_start = htole32(
1950 le32toh(ext.ptn[p].mbr_parts[1].mbrp_start)
1951 + ext.base - start);
1952 /* and maybe an empty partition at the start */
1953 if (ext.ptn[0].mbr_parts[0].mbrp_type == 0) {
1954 if (le32toh(ext.ptn[0].mbr_parts[1].mbrp_start) == 0) {
1955 /* don't need the empty slot */
1956 memmove(&ext.ptn[0], &ext.ptn[1],
1957 (ext.num_ptn - 1) * sizeof ext.ptn[0]);
1958 ext.num_ptn--;
1959 }
1960 } else {
1961 /* must create an empty slot */
1962 add_ext_ptn(start, ptn_0_offset);
1963 ext.ptn[0].mbr_parts[1].mbrp_start = htole32(ext.base
1964 - start);
1965 }
1966 }
1967 if (fix) {
1968 ext.base = start;
1969 ext.limit = start + size;
1970 }
1971 return 0;
1972 }
1973
1974 static const char *
check_ext_overlap(int part,int sysid,daddr_t start,daddr_t size,int fix)1975 check_ext_overlap(int part, int sysid, daddr_t start, daddr_t size, int fix)
1976 {
1977 int p;
1978 unsigned int p_s, p_e;
1979
1980 if (sysid == 0)
1981 return 0;
1982
1983 if (MBR_IS_EXTENDED(sysid))
1984 return "Nested extended partitions are not allowed";
1985
1986 /* allow one track at start for extended partition header */
1987 start -= ptn_0_offset;
1988 size += ptn_0_offset;
1989 if (start < ext.base || start + size > ext.limit)
1990 return "Outside bounds of extended partition";
1991
1992 if (f_flag && !fix)
1993 return 0;
1994
1995 for (p = ext.num_ptn; --p >= 0;) {
1996 if (p == part || ext.ptn[p].mbr_parts[0].mbrp_type == 0)
1997 continue;
1998 p_s = ext_offset(p);
1999 p_e = p_s + le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
2000 + le32toh(ext.ptn[p].mbr_parts[0].mbrp_size);
2001 if (p == 0)
2002 p_s += le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
2003 - ptn_0_offset;
2004 if (start < p_e && start + size > p_s) {
2005 if (!f_flag)
2006 return "Overlaps another extended partition";
2007 if (fix) {
2008 if (part == -1)
2009 delete_ext_ptn(p);
2010 else
2011 /* must not change numbering yet */
2012 ext.ptn[p].mbr_parts[0].mbrp_type = 0;
2013 }
2014 }
2015 }
2016 return 0;
2017 }
2018
2019 static int
change_part(int extended,int part,int sysid,daddr_t start,daddr_t size,char * bootmenu)2020 change_part(int extended, int part, int sysid, daddr_t start, daddr_t size,
2021 char *bootmenu)
2022 {
2023 struct mbr_partition *partp;
2024 struct mbr_sector *boot;
2025 daddr_t offset;
2026 const char *e;
2027 int upart = part;
2028 int p;
2029 int fl;
2030 daddr_t n_s, n_e;
2031 const char *errtext;
2032 #ifdef BOOTSEL
2033 char tmp_bootmenu[MBR_PART_COUNT * (MBR_BS_PARTNAMESIZE + 1)];
2034 int bootmenu_len = (extended ? MBR_PART_COUNT : 1) * (MBR_BS_PARTNAMESIZE + 1);
2035 #endif
2036
2037 if (extended) {
2038 if (part != -1 && part < ext.num_ptn) {
2039 boot = &ext.ptn[part];
2040 partp = &boot->mbr_parts[0];
2041 offset = ext_offset(part);
2042 } else {
2043 part = -1;
2044 boot = 0;
2045 partp = 0;
2046 offset = 0;
2047 }
2048 upart = 0;
2049 e = "E";
2050 } else {
2051 boot = &mboot;
2052 partp = &boot->mbr_parts[part];
2053 offset = 0;
2054 e = "";
2055 }
2056
2057 if (!f_flag && part != -1) {
2058 printf("The data for partition %s%d is:\n", e, part);
2059 print_part(boot, upart, offset);
2060 }
2061
2062 #ifdef BOOTSEL
2063 if (bootmenu != NULL)
2064 strlcpy(tmp_bootmenu, bootmenu, bootmenu_len);
2065 else
2066 if (boot != NULL && boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC)
2067 strlcpy(tmp_bootmenu,
2068 boot->mbr_bootsel.mbrbs_nametab[upart],
2069 bootmenu_len);
2070 else
2071 tmp_bootmenu[0] = 0;
2072 #endif
2073
2074 if (partp != NULL) {
2075 if (!s_flag) {
2076 /* values not specified, default to current ones */
2077 sysid = partp->mbrp_type;
2078 start = offset + le32toh(partp->mbrp_start);
2079 size = le32toh(partp->mbrp_size);
2080 } else {
2081 if (sysid == -1)
2082 sysid = partp->mbrp_type;
2083 if (start == (daddr_t)0xffffffff) {
2084 start = offset + le32toh(partp->mbrp_start);
2085 if (start == 0)
2086 start = offset = ptn_0_offset;
2087 }
2088 if (size == (daddr_t)0xffffffff) {
2089 size = le32toh(partp->mbrp_size);
2090 if (size == 0)
2091 size = disksectors - start;
2092 }
2093 }
2094 }
2095
2096 /* creating a new partition, default to free space */
2097 if (!s_flag && sysid == 0 && extended) {
2098 /* non-extended partition */
2099 start = ext.base;
2100 for (p = 0; p < ext.num_ptn; p++) {
2101 if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
2102 continue;
2103 n_s = ext_offset(p);
2104 if (n_s > start + ptn_0_offset)
2105 break;
2106 start = ext_offset(p)
2107 + le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
2108 + le32toh(ext.ptn[p].mbr_parts[0].mbrp_size);
2109 }
2110 if (ext.limit - start <= ptn_0_offset) {
2111 printf("No space in extended partition\n");
2112 return 0;
2113 }
2114 start += ptn_0_offset;
2115 }
2116
2117 if (!s_flag && sysid == 0 && !extended) {
2118 /* same for non-extended partition */
2119 /* first see if old start is free */
2120 if (start < ptn_0_offset)
2121 start = 0;
2122 for (p = 0; start != 0 && p < MBR_PART_COUNT; p++) {
2123 if (mboot.mbr_parts[p].mbrp_type == 0)
2124 continue;
2125 n_s = le32toh(mboot.mbr_parts[p].mbrp_start);
2126 if (start >= n_s &&
2127 start < n_s + le32toh(mboot.mbr_parts[p].mbrp_size))
2128 start = 0;
2129 }
2130 if (start == 0) {
2131 /* Look for first gap */
2132 start = ptn_0_offset;
2133 for (p = 0; p < MBR_PART_COUNT; p++) {
2134 if (mboot.mbr_parts[p].mbrp_type == 0)
2135 continue;
2136 n_s = le32toh(mboot.mbr_parts[p].mbrp_start);
2137 n_e = n_s + le32toh(mboot.mbr_parts[p].mbrp_size);
2138 if (start >= n_s && start < n_e) {
2139 start = n_e;
2140 p = -1;
2141 }
2142 }
2143 if (start >= disksectors && !I_flag) {
2144 printf("No free space\n");
2145 return 0;
2146 }
2147 }
2148 }
2149
2150 if (!f_flag) {
2151 /* request new values from user */
2152 if (sysid == 0)
2153 sysid = 169;
2154 sysid = decimal("sysid", sysid, 0, 0, 255);
2155 if (sysid == 0 && !v_flag) {
2156 start = 0;
2157 size = 0;
2158 #ifdef BOOTSEL
2159 tmp_bootmenu[0] = 0;
2160 #endif
2161 } else {
2162 daddr_t old = start;
2163 daddr_t lim = extended ? ext.limit : disksectors;
2164 start = decimal("start", start,
2165 DEC_SEC | DEC_RND_0 | (extended ? DEC_RND : 0),
2166 extended ? ext.base : 0, lim);
2167 /* Adjust 'size' so that end doesn't move when 'start'
2168 * is only changed slightly.
2169 */
2170 if (size > start - old)
2171 size -= start - old;
2172 else
2173 size = 0;
2174 /* Find end of available space from this start point */
2175 if (extended) {
2176 for (p = 0; p < ext.num_ptn; p++) {
2177 if (p == part)
2178 continue;
2179 if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
2180 continue;
2181 n_s = ext_offset(p);
2182 if (n_s > start && n_s < lim)
2183 lim = n_s;
2184 if (start >= n_s && start < n_s
2185 + le32toh(ext.ptn[p].mbr_parts[0].mbrp_start)
2186 + le32toh(ext.ptn[p].mbr_parts[0].mbrp_size)) {
2187 lim = start;
2188 break;
2189 }
2190 }
2191 } else {
2192 for (p = 0; p < MBR_PART_COUNT; p++) {
2193 if (p == part)
2194 continue;
2195 if (mboot.mbr_parts[p].mbrp_type == 0)
2196 continue;
2197 n_s = le32toh(mboot.mbr_parts[p].mbrp_start);
2198 if (n_s > start && n_s < lim)
2199 lim = n_s;
2200 if (start >= n_s && start < n_s
2201 + le32toh(mboot.mbr_parts[p].mbrp_size)) {
2202 lim = start;
2203 break;
2204 }
2205 }
2206 }
2207 lim -= start;
2208 if (lim == 0) {
2209 printf("Start sector already allocated\n");
2210 return 0;
2211 }
2212 if (size == 0 || size > lim)
2213 size = lim;
2214 fl = DEC_SEC;
2215 if (start % ptn_alignment == ptn_0_offset)
2216 fl |= DEC_RND_DOWN;
2217 if (start == 2 * ptn_0_offset)
2218 fl |= DEC_RND_DOWN | DEC_RND_DOWN_2;
2219 size = decimal("size", size, fl, 0, lim);
2220 #ifdef BOOTSEL
2221 #ifndef DEFAULT_BOOTEXTCODE
2222 if (!extended)
2223 #endif
2224 string("bootmenu", bootmenu_len, tmp_bootmenu);
2225 #endif
2226 }
2227 }
2228
2229 /*
2230 * Before we write these away, we must verify that nothing
2231 * untoward has been requested.
2232 */
2233
2234 if (extended)
2235 errtext = check_ext_overlap(part, sysid, start, size, 0);
2236 else
2237 errtext = check_overlap(part, sysid, start, size, 0);
2238 if (errtext != NULL && !I_flag) {
2239 if (f_flag)
2240 errx(2, "%s", errtext);
2241 printf("%s\n", errtext);
2242 return 0;
2243 }
2244
2245 /*
2246 * Before proceeding, delete any overlapped partitions.
2247 * This can only happen if '-f' was supplied on the command line.
2248 * Just hope the caller knows what they are doing.
2249 * This also fixes the base of each extended partition if the
2250 * partition itself has moved.
2251 */
2252 if (!I_flag) {
2253 if (extended)
2254 errtext = check_ext_overlap(part, sysid, start, size, 1);
2255 else
2256 errtext = check_overlap(part, sysid, start, size, 1);
2257 if (errtext)
2258 errx(1, "%s", errtext);
2259 }
2260
2261
2262 if (sysid == 0) {
2263 /* delete this partition - save info though */
2264 if (partp == NULL)
2265 /* must have been trying to create an extended ptn */
2266 return 0;
2267 if (start == 0 && size == 0)
2268 memset(partp, 0, sizeof *partp);
2269 #ifdef BOOTSEL
2270 if (boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC)
2271 memset(boot->mbr_bootsel.mbrbs_nametab[upart], 0,
2272 sizeof boot->mbr_bootsel.mbrbs_nametab[0]);
2273 #endif
2274 if (extended)
2275 delete_ext_ptn(part);
2276 else
2277 delete_ptn(part);
2278 return 1;
2279 }
2280
2281
2282 if (extended) {
2283 if (part != -1)
2284 delete_ext_ptn(part);
2285 if (start == ext.base + ptn_0_offset)
2286 /* First one must have been free */
2287 part = 0;
2288 else
2289 part = add_ext_ptn(start, size);
2290
2291 /* These must be re-calculated because of the realloc */
2292 boot = &ext.ptn[part];
2293 partp = &boot->mbr_parts[0];
2294 offset = ext_offset(part);
2295 }
2296
2297 partp->mbrp_type = sysid;
2298 partp->mbrp_start = htole32( start - offset);
2299 partp->mbrp_size = htole32( size);
2300 dos(start, &partp->mbrp_scyl, &partp->mbrp_shd, &partp->mbrp_ssect);
2301 dos(start + size - 1,
2302 &partp->mbrp_ecyl, &partp->mbrp_ehd, &partp->mbrp_esect);
2303 #ifdef BOOTSEL
2304 if (extended) {
2305 boot->mbr_bootsel_magic = LE_MBR_BS_MAGIC;
2306 strncpy(boot->mbr_bootsel.mbrbs_nametab[upart], tmp_bootmenu,
2307 bootmenu_len);
2308 } else {
2309 /* We need to bootselect code installed in order to have
2310 * somewhere to safely write the menu tag.
2311 */
2312 if (boot->mbr_bootsel_magic != LE_MBR_BS_MAGIC) {
2313 if (f_flag ||
2314 yesno("The bootselect code is not installed, "
2315 "do you want to install it now?"))
2316 install_bootsel(MBR_BS_ACTIVE);
2317 }
2318 if (boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC) {
2319 strncpy(boot->mbr_bootsel.mbrbs_nametab[upart],
2320 tmp_bootmenu, bootmenu_len);
2321 }
2322 }
2323 #endif
2324
2325 if (v_flag && !f_flag && yesno("Explicitly specify beg/end address?")) {
2326 /* this really isn't a good idea.... */
2327 int tsector, tcylinder, thead;
2328
2329 tcylinder = MBR_PCYL(partp->mbrp_scyl, partp->mbrp_ssect);
2330 thead = partp->mbrp_shd;
2331 tsector = MBR_PSECT(partp->mbrp_ssect);
2332 tcylinder = decimal("beginning cylinder",
2333 tcylinder, 0, 0, dos_cylinders - 1);
2334 thead = decimal("beginning head",
2335 thead, 0, 0, dos_heads - 1);
2336 tsector = decimal("beginning sector",
2337 tsector, 0, 1, dos_sectors);
2338 partp->mbrp_scyl = DOSCYL(tcylinder);
2339 partp->mbrp_shd = thead;
2340 partp->mbrp_ssect = DOSSECT(tsector, tcylinder);
2341
2342 tcylinder = MBR_PCYL(partp->mbrp_ecyl, partp->mbrp_esect);
2343 thead = partp->mbrp_ehd;
2344 tsector = MBR_PSECT(partp->mbrp_esect);
2345 tcylinder = decimal("ending cylinder",
2346 tcylinder, 0, 0, dos_cylinders - 1);
2347 thead = decimal("ending head",
2348 thead, 0, 0, dos_heads - 1);
2349 tsector = decimal("ending sector",
2350 tsector, 0, 1, dos_sectors);
2351 partp->mbrp_ecyl = DOSCYL(tcylinder);
2352 partp->mbrp_ehd = thead;
2353 partp->mbrp_esect = DOSSECT(tsector, tcylinder);
2354 }
2355
2356 /* If we had to mark an extended partition as deleted because
2357 * another request would have overlapped it, now is the time
2358 * to do the actual delete.
2359 */
2360 if (extended && f_flag) {
2361 for (p = ext.num_ptn; --p >= 0;)
2362 if (ext.ptn[p].mbr_parts[0].mbrp_type == 0)
2363 delete_ext_ptn(p);
2364 }
2365 return 1;
2366 }
2367
2368 static void
print_geometry(void)2369 print_geometry(void)
2370 {
2371
2372 if (sh_flag) {
2373 printf("DISK=%s\n", disk);
2374 printf("DLCYL=%d\nDLHEAD=%d\nDLSEC=%d\nDLSIZE=%"PRIdaddr"\n",
2375 cylinders, heads, sectors, disksectors);
2376 printf("BCYL=%d\nBHEAD=%d\nBSEC=%d\nBDLSIZE=%"PRIdaddr"\n",
2377 dos_cylinders, dos_heads, dos_sectors, dos_disksectors);
2378 printf("NUMEXTPTN=%d\n", ext.num_ptn);
2379 return;
2380 }
2381
2382 /* Not sh_flag */
2383 printf("Disk: %s\n", disk);
2384 printf("NetBSD disklabel disk geometry:\n");
2385 printf("cylinders: %d, heads: %d, sectors/track: %d "
2386 "(%d sectors/cylinder)\ntotal sectors: %"PRIdaddr", "
2387 "bytes/sector: %zd\n\n", cylinders, heads, sectors,
2388 cylindersectors, disksectors, secsize);
2389 printf("BIOS disk geometry:\n");
2390 printf("cylinders: %d, heads: %d, sectors/track: %d "
2391 "(%d sectors/cylinder)\ntotal sectors: %"PRIdaddr"\n\n",
2392 dos_cylinders, dos_heads, dos_sectors, dos_cylindersectors,
2393 dos_disksectors);
2394 printf("Partitions aligned to %d sector boundaries, offset %d\n\n",
2395 ptn_alignment, ptn_0_offset);
2396 }
2397
2398 /* Find the first active partition, else return MBR_PART_COUNT */
2399 static int
first_active(void)2400 first_active(void)
2401 {
2402 struct mbr_partition *partp = &mboot.mbr_parts[0];
2403 int part;
2404
2405 for (part = 0; part < MBR_PART_COUNT; part++)
2406 if (partp[part].mbrp_flag & MBR_PFLAG_ACTIVE)
2407 return part;
2408 return MBR_PART_COUNT;
2409 }
2410
2411 static void
change_active(int which)2412 change_active(int which)
2413 {
2414 struct mbr_partition *partp;
2415 int part;
2416 int active = MBR_PART_COUNT;
2417
2418 partp = &mboot.mbr_parts[0];
2419
2420 if (a_flag && which != -1)
2421 active = which;
2422 else
2423 active = first_active();
2424 if (!f_flag) {
2425 if (yesno("Do you want to change the active partition?")) {
2426 printf ("Choosing %d will make no partition active.\n",
2427 MBR_PART_COUNT);
2428 do {
2429 active = decimal("active partition",
2430 active, 0, 0, MBR_PART_COUNT);
2431 } while (!yesno("Are you happy with this choice?"));
2432 } else
2433 return;
2434 } else
2435 if (active != MBR_PART_COUNT)
2436 printf ("Making partition %d active.\n", active);
2437
2438 for (part = 0; part < MBR_PART_COUNT; part++)
2439 partp[part].mbrp_flag &= ~MBR_PFLAG_ACTIVE;
2440 if (active < MBR_PART_COUNT)
2441 partp[active].mbrp_flag |= MBR_PFLAG_ACTIVE;
2442 }
2443
2444 static void
change_bios_geometry(void)2445 change_bios_geometry(void)
2446 {
2447 print_geometry();
2448 if (!yesno("Do you want to change our idea of what BIOS thinks?"))
2449 return;
2450
2451 #if defined(USE_DISKLIST)
2452 if (dl != NULL) {
2453 struct biosdisk_info *bip;
2454 int i;
2455
2456 for (i = 0; i < dl->dl_nbiosdisks; i++) {
2457 if (i == 0)
2458 printf("\nGeometries of known disks:\n");
2459 bip = &dl->dl_biosdisks[i];
2460 printf("Disk %d: cylinders %u, heads %u, sectors %u"
2461 " (%"PRIdaddr" sectors, %dMB)\n",
2462 i, bip->bi_cyl, bip->bi_head, bip->bi_sec,
2463 bip->bi_lbasecs, SEC_TO_MB(bip->bi_lbasecs));
2464
2465 }
2466 printf("\n");
2467 }
2468 #endif
2469 do {
2470 dos_cylinders = decimal("BIOS's idea of #cylinders",
2471 dos_cylinders, 0, 0, MAXCYL);
2472 dos_heads = decimal("BIOS's idea of #heads",
2473 dos_heads, 0, 0, MAXHEAD);
2474 dos_sectors = decimal("BIOS's idea of #sectors",
2475 dos_sectors, 0, 1, MAXSECTOR);
2476 print_geometry();
2477 } while (!yesno("Are you happy with this choice?"));
2478 }
2479
2480
2481 /***********************************************\
2482 * Change real numbers into strange dos numbers *
2483 \***********************************************/
2484 static void
dos(int sector,unsigned char * cylinderp,unsigned char * headp,unsigned char * sectorp)2485 dos(int sector, unsigned char *cylinderp, unsigned char *headp,
2486 unsigned char *sectorp)
2487 {
2488 int cylinder, head;
2489
2490 cylinder = sector / dos_cylindersectors;
2491 sector -= cylinder * dos_cylindersectors;
2492
2493 head = sector / dos_sectors;
2494 sector -= head * dos_sectors;
2495 if (cylinder > 1023)
2496 cylinder = 1023;
2497
2498 *cylinderp = DOSCYL(cylinder);
2499 *headp = head;
2500 *sectorp = DOSSECT(sector + 1, cylinder);
2501 }
2502
2503 static int
open_disk(int update)2504 open_disk(int update)
2505 {
2506 static char namebuf[MAXPATHLEN + 1];
2507 int flags = update && disk_file == NULL ? O_RDWR : O_RDONLY;
2508
2509 if (!F_flag) {
2510 fd = opendisk(disk, flags, namebuf, sizeof(namebuf), 0);
2511 if (fd < 0) {
2512 if (errno == ENODEV)
2513 warnx("%s is not a character device", namebuf);
2514 else
2515 warn("cannot opendisk %s", namebuf);
2516 return (-1);
2517 }
2518 disk = namebuf;
2519 } else {
2520 fd = open(disk, flags, 0);
2521 if (fd == -1) {
2522 warn("cannot open %s", disk);
2523 return -1;
2524 }
2525 }
2526
2527 if (get_params() == -1) {
2528 close(fd);
2529 fd = -1;
2530 return (-1);
2531 }
2532 if (disk_file != NULL) {
2533 /* for testing: read/write data from a disk file */
2534 wfd = open(disk_file, update ? O_RDWR|O_CREAT : O_RDONLY, 0777);
2535 if (wfd == -1) {
2536 warn("%s", disk_file);
2537 close(fd);
2538 fd = -1;
2539 return -1;
2540 }
2541 } else
2542 wfd = fd;
2543 return (0);
2544 }
2545
2546 static ssize_t
read_disk(daddr_t sector,void * buf)2547 read_disk(daddr_t sector, void *buf)
2548 {
2549 ssize_t nr;
2550
2551 if (*rfd == -1)
2552 errx(1, "read_disk(); fd == -1");
2553
2554 if (secsize <= 0)
2555 errx(1, "read_disk(); secsize invalid");
2556
2557 off_t offs = sector * (off_t)secsize;
2558 off_t mod = offs & (secsize - 1);
2559 off_t rnd = offs & ~(secsize - 1);
2560
2561 if (lseek(*rfd, rnd, SEEK_SET) == (off_t)-1)
2562 return -1;
2563
2564 if (secsize <= 512)
2565 return read(*rfd, buf, secsize);
2566
2567 if ((nr = read(*rfd, iobuf, secsize)) != secsize)
2568 return nr;
2569
2570 memcpy(buf, &iobuf[mod], 512);
2571
2572 return 512;
2573 }
2574
2575 static ssize_t
write_disk(daddr_t sector,void * buf)2576 write_disk(daddr_t sector, void *buf)
2577 {
2578 ssize_t nr;
2579
2580 if (wfd == -1)
2581 errx(1, "write_disk(); wfd == -1");
2582
2583 off_t offs = sector * (off_t)secsize;
2584 off_t mod = offs & (secsize - 1);
2585 off_t rnd = offs & ~(secsize - 1);
2586
2587 if (lseek(wfd, rnd, SEEK_SET) == (off_t)-1)
2588 return -1;
2589
2590 if (secsize == 512)
2591 return write(wfd, buf, 512);
2592
2593 if ((nr = read(wfd, iobuf, secsize)) != secsize)
2594 return nr;
2595
2596 if (lseek(wfd, rnd, SEEK_SET) == (off_t)-1)
2597 return -1;
2598
2599 memcpy(&iobuf[mod], buf, 512);
2600
2601 if ((nr = write(wfd, iobuf, secsize)) != secsize)
2602 return nr;
2603
2604 return 512;
2605 }
2606
2607 static void
guess_geometry(daddr_t _sectors)2608 guess_geometry(daddr_t _sectors)
2609 {
2610 dos_sectors = MAXSECTOR;
2611 dos_heads = MAXHEAD - 1; /* some BIOS might use 256 */
2612 dos_cylinders = _sectors / (MAXSECTOR * (MAXHEAD - 1));
2613 if (dos_cylinders < 1)
2614 dos_cylinders = 1;
2615 else if (dos_cylinders > MAXCYL - 1)
2616 dos_cylinders = MAXCYL - 1;
2617 }
2618
2619 static int
get_params(void)2620 get_params(void)
2621 {
2622 if (disk_type != NULL) {
2623 struct disklabel *tmplabel;
2624
2625 if ((tmplabel = getdiskbyname(disk_type)) == NULL) {
2626 warn("%s: bad disktype", disk);
2627 return (-1);
2628 }
2629 disklabel = *tmplabel;
2630 } else if (F_flag) {
2631 struct stat st;
2632 if (fstat(fd, &st) == -1) {
2633 warn("%s: fstat", disk);
2634 return (-1);
2635 }
2636 if (st.st_size % 512 != 0) {
2637 warnx("%s size (%ju) is not divisible "
2638 "by sector size (%d)", disk, (uintmax_t)st.st_size,
2639 512);
2640 }
2641 disklabel.d_secperunit = st.st_size / 512;
2642 guess_geometry(disklabel.d_secperunit);
2643 disklabel.d_ncylinders = dos_cylinders;
2644 disklabel.d_ntracks = dos_heads;
2645 disklabel.d_secsize = 512;
2646 disklabel.d_nsectors = dos_sectors;
2647 }
2648 #if !HAVE_NBTOOL_CONFIG_H
2649 else if (ioctl(fd, DIOCGDEFLABEL, &disklabel) == -1) {
2650 warn("%s: DIOCGDEFLABEL", disk);
2651 if (ioctl(fd, DIOCGDINFO, &disklabel) == -1) {
2652 warn("%s: DIOCGDINFO", disk);
2653 return (-1);
2654 }
2655 }
2656 #endif
2657
2658 disksectors = disklabel.d_secperunit;
2659 cylinders = disklabel.d_ncylinders;
2660 heads = disklabel.d_ntracks;
2661 secsize = disklabel.d_secsize;
2662 sectors = disklabel.d_nsectors;
2663
2664 /* pick up some defaults for the BIOS sizes */
2665 if (sectors <= MAXSECTOR) {
2666 dos_cylinders = cylinders;
2667 dos_heads = heads;
2668 dos_sectors = sectors;
2669 } else {
2670 /* guess - has to better than the above */
2671 guess_geometry(disksectors);
2672 }
2673 dos_disksectors = disksectors;
2674
2675 return (0);
2676 }
2677
2678 #ifdef BOOTSEL
2679 /*
2680 * Rather unfortunately the bootsel 'magic' number is at the end of the
2681 * the structure, and there is no checksum. So when other operating
2682 * systems install mbr code by only writing the length of their code they
2683 * can overwrite part of the structure but keeping the magic number intact.
2684 * This code attempts to empirically detect this problem.
2685 */
2686 static int
validate_bootsel(struct mbr_bootsel * mbs)2687 validate_bootsel(struct mbr_bootsel *mbs)
2688 {
2689 unsigned int key = mbs->mbrbs_defkey;
2690 unsigned int tmo;
2691 size_t i, j;
2692
2693 if (v_flag)
2694 return 0;
2695
2696 /*
2697 * Check default key is sane
2698 * - this is the most likely field to be stuffed
2699 * 16 disks and 16 bootable partitions seems enough!
2700 * (the keymap decode starts falling apart at that point)
2701 */
2702 if (mbs->mbrbs_flags & MBR_BS_ASCII) {
2703 if (key != 0 && !(key == '\r'
2704 || (key >= '1' && key < '1' + MAX_BIOS_DISKS)
2705 || (key >= 'a' && key < 'a' + MAX_BIOS_DISKS)))
2706 return 1;
2707 } else {
2708 if (key != 0 && !(key == SCAN_ENTER
2709 || (key >= SCAN_1 && key < SCAN_1 + MAX_BIOS_DISKS)
2710 || (key >= SCAN_F1 && key < SCAN_F1 + MAX_BIOS_DISKS)))
2711 return 1;
2712 }
2713
2714 /* Checking the flags will lead to breakage... */
2715
2716 /* Timeout value is expected to be a multiple of a second */
2717 tmo = htole16(mbs->mbrbs_timeo);
2718 if (tmo != 0 && tmo != 0xffff && tmo != (10 * tmo + 9) / 182 * 182 / 10)
2719 return 2;
2720
2721 /* Check the menu strings are printable */
2722 /* Unfortunately they aren't zero filled... */
2723 for (j = 0; j < __arraycount(mbs->mbrbs_nametab); ++j)
2724 for (i = 0; i < sizeof(mbs->mbrbs_nametab[j]); i++) {
2725 int c = (uint8_t)mbs->mbrbs_nametab[j][i];
2726 if (c == 0 || isprint(c))
2727 continue;
2728 return 3;
2729 }
2730
2731 return 0;
2732 }
2733 #endif
2734
2735 static int
read_s0(daddr_t offset,struct mbr_sector * boot)2736 read_s0(daddr_t offset, struct mbr_sector *boot)
2737 {
2738 const char *tabletype = offset ? "extended" : "primary";
2739 #ifdef BOOTSEL
2740 static int reported;
2741 #endif
2742
2743 if (read_disk(offset, boot) == -1) {
2744 warn("Can't read %s partition table", tabletype);
2745 return -1;
2746 }
2747 if (boot->mbr_magic != LE_MBR_MAGIC) {
2748 if (F_flag && boot->mbr_magic == 0)
2749 return -1;
2750 warnx("%s partition table invalid, "
2751 "no magic in sector %"PRIdaddr, tabletype, offset);
2752 return -1;
2753
2754 }
2755 #ifdef BOOTSEL
2756 if (boot->mbr_bootsel_magic == LE_MBR_BS_MAGIC) {
2757 /* mbr_bootsel in new location */
2758 if (validate_bootsel(&boot->mbr_bootsel)) {
2759 warnx("removing corrupt bootsel information");
2760 boot->mbr_bootsel_magic = 0;
2761 }
2762 return 0;
2763 }
2764 if (boot->mbr_bootsel_magic != LE_MBR_MAGIC)
2765 return 0;
2766
2767 /* mbr_bootsel in old location */
2768 if (!reported)
2769 warnx("%s partition table: using old-style bootsel information",
2770 tabletype);
2771 reported = 1;
2772 if (validate_bootsel((void *)((uint8_t *)boot + MBR_BS_OFFSET + 4))) {
2773 warnx("%s bootsel information corrupt - ignoring", tabletype);
2774 return 0;
2775 }
2776 memmove((uint8_t *)boot + MBR_BS_OFFSET,
2777 (uint8_t *)boot + MBR_BS_OFFSET + 4,
2778 sizeof(struct mbr_bootsel));
2779 if ( ! (boot->mbr_bootsel.mbrbs_flags & MBR_BS_NEWMBR)) {
2780 /* old style default key */
2781 int id;
2782 /* F1..F4 => ptn 0..3, F5+ => disk 0+ */
2783 id = boot->mbr_bootsel.mbrbs_defkey;
2784 id -= SCAN_F1;
2785 if (id >= MBR_PART_COUNT)
2786 id -= MBR_PART_COUNT; /* Use number of disk */
2787 else if (mboot.mbr_parts[id].mbrp_type != 0)
2788 id = le32toh(boot->mbr_parts[id].mbrp_start);
2789 else
2790 id = DEFAULT_ACTIVE;
2791 boot->mbr_bootsel.mbrbs_defkey = id;
2792 }
2793 boot->mbr_bootsel_magic = LE_MBR_BS_MAGIC;
2794 /* highlight that new bootsel code is necessary */
2795 boot->mbr_bootsel.mbrbs_flags &= ~MBR_BS_NEWMBR;
2796 #endif /* BOOTSEL */
2797 return 0;
2798 }
2799
2800 static int
write_mbr(void)2801 write_mbr(void)
2802 {
2803 int flag, i;
2804 daddr_t offset;
2805 int rval = -1;
2806
2807 /*
2808 * write enable label sector before write (if necessary),
2809 * disable after writing.
2810 * needed if the disklabel protected area also protects
2811 * sector 0. (e.g. empty disk)
2812 */
2813 flag = 1;
2814 #if !HAVE_NBTOOL_CONFIG_H
2815 if (wfd == fd && F_flag == 0 && ioctl(wfd, DIOCWLABEL, &flag) < 0)
2816 warn("DIOCWLABEL");
2817 #endif
2818 if (write_disk(0, &mboot) == -1) {
2819 warn("Can't write fdisk partition table");
2820 goto protect_label;
2821 }
2822 if (boot_installed)
2823 for (i = bootsize; (i -= 0x200) > 0;)
2824 if (write_disk(i / 0x200, &bootcode[i / 0x200]) == -1) {
2825 warn("Can't write bootcode");
2826 goto protect_label;
2827 }
2828 for (offset = 0, i = 0; i < ext.num_ptn; i++) {
2829 if (write_disk(ext.base + offset, ext.ptn + i) == -1) {
2830 warn("Can't write %dth extended partition", i);
2831 goto protect_label;
2832 }
2833 offset = le32toh(ext.ptn[i].mbr_parts[1].mbrp_start);
2834 }
2835 rval = 0;
2836 protect_label:
2837 flag = 0;
2838 #if !HAVE_NBTOOL_CONFIG_H
2839 if (wfd == fd && F_flag == 0 && ioctl(wfd, DIOCWLABEL, &flag) < 0)
2840 warn("DIOCWLABEL");
2841 #endif
2842 return rval;
2843 }
2844
2845 static int
yesno(const char * str,...)2846 yesno(const char *str, ...)
2847 {
2848 int ch, first;
2849 va_list ap;
2850
2851 va_start(ap, str);
2852 vprintf(str, ap);
2853 va_end(ap);
2854 printf(" [n] ");
2855
2856 first = ch = getchar();
2857 while (ch != '\n' && ch != EOF)
2858 ch = getchar();
2859 if (ch == EOF)
2860 errx(1, "EOF");
2861 return (first == 'y' || first == 'Y');
2862 }
2863
2864 static int64_t
decimal(const char * prompt,int64_t dflt,int flags,int64_t minval,int64_t maxval)2865 decimal(const char *prompt, int64_t dflt, int flags, int64_t minval, int64_t maxval)
2866 {
2867 int64_t acc = 0;
2868 int valid;
2869 int len;
2870 char *cp;
2871
2872 for (;;) {
2873 if (flags & DEC_SEC) {
2874 printf("%s: [%" PRId64 "..%" PRId64 "cyl default: %" PRId64 ", %" PRId64 "cyl, %uMB] ",
2875 prompt, SEC_TO_CYL(minval), SEC_TO_CYL(maxval),
2876 dflt, SEC_TO_CYL(dflt), SEC_TO_MB(dflt));
2877 } else
2878 printf("%s: [%" PRId64 "..%" PRId64 " default: %" PRId64 "] ",
2879 prompt, minval, maxval, dflt);
2880
2881 if (!fgets(lbuf, LBUF, stdin))
2882 errx(1, "EOF");
2883 cp = lbuf;
2884
2885 cp += strspn(cp, " \t");
2886 if (*cp == '\n')
2887 return dflt;
2888
2889 if (cp[0] == '$' && cp[1] == '\n')
2890 return maxval;
2891
2892 if (isdigit((unsigned char)*cp) || *cp == '-') {
2893 acc = strtoll(lbuf, &cp, 10);
2894 len = strcspn(cp, " \t\n");
2895 valid = 0;
2896 if (len != 0 && (flags & DEC_SEC)) {
2897 if (!strncasecmp(cp, "gb", len)) {
2898 acc *= 1024;
2899 valid = 1;
2900 }
2901 if (valid || !strncasecmp(cp, "mb", len)) {
2902 acc *= SEC_IN_1M;
2903 /* round to whole number of cylinders */
2904 acc += ptn_alignment / 2;
2905 acc /= ptn_alignment;
2906 valid = 1;
2907 }
2908 if (valid || !strncasecmp(cp, "cyl", len)) {
2909 acc *= ptn_alignment;
2910 /* adjustments for cylinder boundary */
2911 if (acc == 0 && flags & DEC_RND_0)
2912 acc += ptn_0_offset;
2913 if (flags & DEC_RND)
2914 acc += ptn_0_offset;
2915 if (flags & DEC_RND_DOWN)
2916 acc -= ptn_0_offset;
2917 if (flags & DEC_RND_DOWN_2)
2918 acc -= ptn_0_offset;
2919 cp += len;
2920 }
2921 }
2922 }
2923
2924 cp += strspn(cp, " \t");
2925 if (*cp != '\n') {
2926 lbuf[strlen(lbuf) - 1] = 0;
2927 printf("%s is not a valid %s number.\n", lbuf,
2928 flags & DEC_SEC ? "sector" : "decimal");
2929 continue;
2930 }
2931
2932 if (acc >= minval && acc <= maxval)
2933 return acc;
2934 printf("%" PRId64 " is not between %" PRId64 " and %" PRId64 ".\n", acc, minval, maxval);
2935 }
2936 }
2937
2938 static int
ptn_id(const char * prompt,int * extended)2939 ptn_id(const char *prompt, int *extended)
2940 {
2941 unsigned int acc = 0;
2942 char *cp;
2943
2944 for (;; printf("%s is not a valid partition number.\n", lbuf)) {
2945 printf("%s: [none] ", prompt);
2946
2947 if (!fgets(lbuf, LBUF, stdin))
2948 errx(1, "EOF");
2949 lbuf[strlen(lbuf)-1] = '\0';
2950 cp = lbuf;
2951
2952 cp += strspn(cp, " \t");
2953 *extended = 0;
2954 if (*cp == 0)
2955 return -1;
2956
2957 if (*cp == 'E' || *cp == 'e') {
2958 cp++;
2959 *extended = 1;
2960 }
2961
2962 acc = strtoul(cp, &cp, 10);
2963
2964 cp += strspn(cp, " \t");
2965 if (*cp != '\0')
2966 continue;
2967
2968 if (*extended || acc < MBR_PART_COUNT)
2969 return acc;
2970 }
2971 }
2972
2973 #ifdef BOOTSEL
2974 static void
string(const char * prompt,int length,char * buf)2975 string(const char *prompt, int length, char *buf)
2976 {
2977 int len;
2978
2979 for (;;) {
2980 printf("%s: [%.*s] (space to clear)", prompt, length, buf);
2981
2982 if (!fgets(lbuf, LBUF, stdin))
2983 errx(1, "EOF");
2984 len = strlen(lbuf);
2985 if (len <= 1)
2986 /* unchanged if just <enter> */
2987 return;
2988 /* now strip trailing spaces, <space><enter> deletes string */
2989 do
2990 lbuf[--len] = 0;
2991 while (len != 0 && lbuf[len - 1] == ' ');
2992 if (len < length)
2993 break;
2994 printf("'%s' is longer than %d characters.\n",
2995 lbuf, length - 1);
2996 }
2997 strncpy(buf, lbuf, length);
2998 }
2999 #endif
3000
3001 static int
type_match(const void * key,const void * item)3002 type_match(const void *key, const void *item)
3003 {
3004 const int *idp = key;
3005 const struct mbr_ptype *ptr = item;
3006
3007 if (*idp < ptr->id)
3008 return (-1);
3009 if (*idp > ptr->id)
3010 return (1);
3011 return (0);
3012 }
3013
3014 static const char *
get_type(int type)3015 get_type(int type)
3016 {
3017 struct mbr_ptype *ptr;
3018
3019 ptr = bsearch(&type, mbr_ptypes, KNOWN_SYSIDS,
3020 sizeof(mbr_ptypes[0]), type_match);
3021 if (ptr == 0)
3022 return ("unknown");
3023 return (ptr->name);
3024 }
3025
3026 static int
read_gpt(daddr_t offset,struct gpt_hdr * gptp)3027 read_gpt(daddr_t offset, struct gpt_hdr *gptp)
3028 {
3029 char buf[512];
3030 struct gpt_hdr *hdr = (void *)buf;
3031 const char *tabletype = GPT_TYPE(offset);
3032
3033 if (read_disk(offset, buf) == -1) {
3034 warn("Can't read %s GPT header", tabletype);
3035 return -1;
3036 }
3037 (void)memcpy(gptp, buf, GPT_HDR_SIZE);
3038
3039 /* GPT CRC should be calculated with CRC field preset to zero */
3040 hdr->hdr_crc_self = 0;
3041
3042 if (memcmp(gptp->hdr_sig, GPT_HDR_SIG, sizeof(gptp->hdr_sig))
3043 || gptp->hdr_lba_self != (uint64_t)offset
3044 || crc32(0, (void *)hdr, gptp->hdr_size) != gptp->hdr_crc_self) {
3045 /* not a GPT */
3046 (void)memset(gptp, 0, GPT_HDR_SIZE);
3047 }
3048
3049 if (v_flag && gptp->hdr_size != 0) {
3050 printf("Found %s GPT header CRC %"PRIu32" "
3051 "at sector %"PRIdaddr", backup at %"PRIdaddr"\n",
3052 tabletype, gptp->hdr_crc_self, offset, gptp->hdr_lba_alt);
3053 }
3054 return gptp->hdr_size;
3055
3056 }
3057
3058 static int
delete_gpt(struct gpt_hdr * gptp)3059 delete_gpt(struct gpt_hdr *gptp)
3060 {
3061 char buf[512];
3062 struct gpt_hdr *hdr = (void *)buf;
3063
3064 if (g_flag)
3065 return 0; /* preserve existing GPT headers */
3066
3067 if (gptp->hdr_size == 0)
3068 return 0;
3069
3070 /* don't accidently overwrite something important */
3071 if (gptp->hdr_lba_self != GPT_HDR_BLKNO &&
3072 gptp->hdr_lba_self != (uint64_t)disksectors - 1) {
3073 warnx("given GPT header location doesn't seem correct");
3074 return -1;
3075 }
3076
3077 (void)memcpy(buf, gptp, GPT_HDR_SIZE);
3078 /*
3079 * Don't really delete GPT, just "disable" it, so it can
3080 * be recovered later in case of mistake or something
3081 */
3082 (void)memset(hdr->hdr_sig, 0, sizeof(gptp->hdr_sig));
3083 if (write_disk(gptp->hdr_lba_self, hdr) == -1) {
3084 warn("can't delete %s GPT header",
3085 GPT_TYPE(gptp->hdr_lba_self));
3086 return -1;
3087 }
3088 (void)memset(gptp, 0, GPT_HDR_SIZE);
3089 return 1;
3090 }
3091