1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <libgen.h>
29 #include <malloc.h>
30 #include <string.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <fcntl.h>
34 #include <unistd.h>
35 #include <strings.h>
36 #include <sys/mount.h>
37 #include <sys/mnttab.h>
38 #include <sys/dktp/fdisk.h>
39 #include <sys/dkio.h>
40 #include <sys/vtoc.h>
41 
42 #include <libintl.h>
43 #include <locale.h>
44 #include "message.h"
45 #include <errno.h>
46 #include <libfdisk.h>
47 #include <md5.h>
48 
49 #ifndef	TEXT_DOMAIN
50 #define	TEXT_DOMAIN	"SUNW_OST_OSCMD"
51 #endif
52 
53 #define	SECTOR_SIZE	0x200
54 #define	HASH_SIZE	0x10
55 #define	VERSION_SIZE	0x50
56 #define	STAGE2_MEMADDR	0x8000	/* loading addr of stage2 */
57 
58 #define	STAGE1_BPB_OFFSET	0x3
59 #define	STAGE1_BPB_SIZE		0x3B
60 #define	STAGE1_BOOT_DRIVE	0x40
61 #define	STAGE1_FORCE_LBA	0x41
62 #define	STAGE1_STAGE2_ADDRESS	0x42
63 #define	STAGE1_STAGE2_SECTOR	0x44
64 #define	STAGE1_STAGE2_SEGMENT	0x48
65 
66 #define	STAGE2_BLOCKLIST	(SECTOR_SIZE - 0x8)
67 #define	STAGE2_INSTALLPART	(SECTOR_SIZE + 0x8)
68 #define	STAGE2_FORCE_LBA	(SECTOR_SIZE + 0x11)
69 #define	STAGE2_VER_STRING	(SECTOR_SIZE + 0x12)
70 #define	STAGE2_SIGN_OFFSET	(SECTOR_SIZE + 0x60)
71 #define	STAGE2_PKG_VERSION	(SECTOR_SIZE + 0x70)
72 #define	STAGE2_BLKOFF		50	/* offset from start of fdisk part */
73 
74 static char extended_sig[] = "\xCC\xCC\xCC\xCC\xAA\xAA\xAA\xAA\xBB\xBB\xBB\xBB"
75 "\xBB\xBB\xBB\xBB";
76 
77 static int nowrite = 0;
78 static int write_mboot = 0;
79 static int force_mboot = 0;
80 static int getinfo = 0;
81 static int do_version = 0;
82 static int is_floppy = 0;
83 static int is_bootpar = 0;
84 static int strip = 0;
85 static int stage2_fd;
86 static int partition, slice = 0xff;
87 static char *device_p0;
88 static uint32_t stage2_first_sector, stage2_second_sector;
89 
90 
91 static char bpb_sect[SECTOR_SIZE];
92 static char boot_sect[SECTOR_SIZE];
93 static char stage1_buffer[SECTOR_SIZE];
94 static char stage2_buffer[2 * SECTOR_SIZE];
95 static char signature[HASH_SIZE];
96 static char verstring[VERSION_SIZE];
97 static unsigned int blocklist[SECTOR_SIZE / sizeof (unsigned int)];
98 
99 static int open_device(char *);
100 static void read_bpb_sect(int);
101 static void read_boot_sect(char *);
102 static void write_boot_sect(char *);
103 static void read_stage1_stage2(char *, char *);
104 static void modify_and_write_stage1(int);
105 static void modify_and_write_stage2(int);
106 static unsigned int get_start_sector(int);
107 static void copy_stage2(int, char *);
108 static char *get_raw_partition(char *);
109 static void usage(char *);
110 static void print_info();
111 static int read_stage2_info(int);
112 static void check_extended_support();
113 
114 extern int read_stage2_blocklist(int, unsigned int *);
115 
116 int
117 main(int argc, char *argv[])
118 {
119 	int dev_fd, opt, params = 3;
120 	char *stage1, *stage2, *device;
121 
122 	(void) setlocale(LC_ALL, "");
123 	(void) textdomain(TEXT_DOMAIN);
124 
125 	while ((opt = getopt(argc, argv, "fmneis:")) != EOF) {
126 		switch (opt) {
127 		case 'm':
128 			write_mboot = 1;
129 			break;
130 		case 'n':
131 			nowrite = 1;
132 			break;
133 		case 'f':
134 			force_mboot = 1;
135 			break;
136 		case 'i':
137 			getinfo = 1;
138 			params = 1;
139 			break;
140 		case 'e':
141 			strip = 1;
142 			break;
143 		case 's':
144 			do_version = 1;
145 			(void) snprintf(verstring, sizeof (verstring), "%s",
146 			    optarg);
147 			break;
148 		default:
149 			/* fall through to process non-optional args */
150 			break;
151 		}
152 	}
153 
154 	/* check arguments */
155 	if (argc != optind + params) {
156 		usage(argv[0]);
157 	}
158 
159 	if (nowrite) {
160 		(void) fprintf(stdout, DRY_RUN);
161 	}
162 
163 	if (params == 1) {
164 		device = strdup(argv[optind]);
165 		if (!device) {
166 			usage(argv[0]);
167 		}
168 	} else if (params == 3) {
169 		stage1 = strdup(argv[optind]);
170 		stage2 = strdup(argv[optind + 1]);
171 		device = strdup(argv[optind + 2]);
172 
173 		if (!stage1 || !stage2 || !device) {
174 			usage(argv[0]);
175 		}
176 	}
177 
178 	/* open and check device type */
179 	dev_fd = open_device(device);
180 
181 	if (getinfo) {
182 		if (read_stage2_info(dev_fd) != 0) {
183 			fprintf(stderr, "Unable to read extended information"
184 			    " from %s\n", device);
185 			exit(1);
186 		}
187 		print_info();
188 		(void) free(device);
189 		(void) close(dev_fd);
190 		return (0);
191 	}
192 
193 	/* read in stage1 and stage2 into buffer */
194 	read_stage1_stage2(stage1, stage2);
195 
196 	/* check if stage2 supports extended versioning */
197 	if (do_version)
198 		check_extended_support(stage2);
199 
200 	/* In the pcfs case, write a fresh stage2 */
201 	if (is_floppy || is_bootpar) {
202 		copy_stage2(dev_fd, device);
203 		read_bpb_sect(dev_fd);
204 	}
205 
206 	/* read in boot sector */
207 	if (!is_floppy)
208 		read_boot_sect(device);
209 
210 	/* modify stage1 based on grub needs */
211 	modify_and_write_stage1(dev_fd);
212 
213 	/* modify stage2 and write to media */
214 	modify_and_write_stage2(dev_fd);
215 
216 	if (!is_floppy && write_mboot)
217 		write_boot_sect(device);
218 
219 	(void) close(dev_fd);
220 	free(device);
221 	free(stage1);
222 	free(stage2);
223 
224 	return (0);
225 }
226 
227 static unsigned int
228 get_start_sector(int fd)
229 {
230 	static unsigned int start_sect = 0;
231 	uint32_t secnum = 0, numsec = 0;
232 	int i, pno, rval, log_part = 0;
233 	struct mboot *mboot;
234 	struct ipart *part;
235 	ext_part_t *epp;
236 	struct part_info dkpi;
237 	struct extpart_info edkpi;
238 
239 	if (start_sect)
240 		return (start_sect);
241 
242 	mboot = (struct mboot *)boot_sect;
243 	for (i = 0; i < FD_NUMPART; i++) {
244 		part = (struct ipart *)mboot->parts + i;
245 		if (is_bootpar) {
246 			if (part->systid == 0xbe) {
247 				start_sect = part->relsect;
248 				partition = i;
249 				goto found_part;
250 			}
251 		}
252 	}
253 
254 	/*
255 	 * We will not support x86 boot partition on extended partitions
256 	 */
257 	if (is_bootpar) {
258 		(void) fprintf(stderr, NOBOOTPAR);
259 		exit(-1);
260 	}
261 
262 	/*
263 	 * Not an x86 boot partition. Search for Solaris fdisk partition
264 	 * Get the solaris partition information from the device
265 	 * and compare the offset of S2 with offset of solaris partition
266 	 * from fdisk partition table.
267 	 */
268 	if (ioctl(fd, DKIOCEXTPARTINFO, &edkpi) < 0) {
269 		if (ioctl(fd, DKIOCPARTINFO, &dkpi) < 0) {
270 			(void) fprintf(stderr, PART_FAIL);
271 			exit(-1);
272 		} else {
273 			edkpi.p_start = dkpi.p_start;
274 		}
275 	}
276 
277 	for (i = 0; i < FD_NUMPART; i++) {
278 		part = (struct ipart *)mboot->parts + i;
279 
280 		if (part->relsect == 0) {
281 			(void) fprintf(stderr, BAD_PART, i);
282 			exit(-1);
283 		}
284 
285 		if (edkpi.p_start >= part->relsect &&
286 		    edkpi.p_start < (part->relsect + part->numsect)) {
287 			/* Found the partition */
288 			break;
289 		}
290 	}
291 
292 	if (i == FD_NUMPART) {
293 		/* No solaris fdisk partitions (primary or logical) */
294 		(void) fprintf(stderr, NOSOLPAR);
295 		exit(-1);
296 	}
297 
298 	/*
299 	 * We have found a Solaris fdisk partition (primary or extended)
300 	 * Handle the simple case first: Solaris in a primary partition
301 	 */
302 	if (!fdisk_is_dos_extended(part->systid)) {
303 		start_sect = part->relsect;
304 		partition = i;
305 		goto found_part;
306 	}
307 
308 	/*
309 	 * Solaris in a logical partition. Find that partition in the
310 	 * extended part.
311 	 */
312 	if ((rval = libfdisk_init(&epp, device_p0, NULL, FDISK_READ_DISK))
313 	    != FDISK_SUCCESS) {
314 		switch (rval) {
315 			/*
316 			 * The first 2 cases are not an error per-se, just that
317 			 * there is no Solaris logical partition
318 			 */
319 			case FDISK_EBADLOGDRIVE:
320 			case FDISK_ENOLOGDRIVE:
321 				(void) fprintf(stderr, NOSOLPAR);
322 				exit(-1);
323 				/*NOTREACHED*/
324 			case FDISK_ENOVGEOM:
325 				(void) fprintf(stderr, NO_VIRT_GEOM);
326 				exit(1);
327 				break;
328 			case FDISK_ENOPGEOM:
329 				(void) fprintf(stderr, NO_PHYS_GEOM);
330 				exit(1);
331 				break;
332 			case FDISK_ENOLGEOM:
333 				(void) fprintf(stderr, NO_LABEL_GEOM);
334 				exit(1);
335 				break;
336 			default:
337 				(void) fprintf(stderr, LIBFDISK_INIT_FAIL);
338 				exit(1);
339 				break;
340 		}
341 	}
342 
343 	rval = fdisk_get_solaris_part(epp, &pno, &secnum, &numsec);
344 	if (rval != FDISK_SUCCESS) {
345 		/* No solaris logical partition */
346 		(void) fprintf(stderr, NOSOLPAR);
347 		exit(-1);
348 	}
349 	libfdisk_fini(&epp);
350 
351 	start_sect = secnum;
352 	partition = pno - 1;
353 	log_part = 1;
354 
355 found_part:
356 	/* get confirmation for -m */
357 	if (write_mboot && !force_mboot) {
358 		(void) fprintf(stdout, MBOOT_PROMPT);
359 		if (getchar() != 'y') {
360 			write_mboot = 0;
361 			(void) fprintf(stdout, MBOOT_NOT_UPDATED);
362 		}
363 	}
364 
365 	/*
366 	 * Currently if Solaris is in an extended partition we need to
367 	 * write GRUB to the MBR. Check for this.
368 	 */
369 	if (log_part && !write_mboot) {
370 		(void) fprintf(stderr, EXTSOLPAR);
371 		exit(-1);
372 	}
373 
374 	/*
375 	 * warn, if Solaris in primary partition and GRUB not in MBR and
376 	 * partition is not active
377 	 */
378 	if (!log_part && part->bootid != 128 && !write_mboot) {
379 		(void) fprintf(stdout, SOLPAR_INACTIVE, partition + 1);
380 	}
381 
382 	return (start_sect);
383 }
384 
385 static void
386 usage(char *progname)
387 {
388 	(void) fprintf(stderr, USAGE, basename(progname));
389 	exit(-1);
390 }
391 
392 static int
393 open_device(char *device)
394 {
395 	int dev_fd;
396 	struct stat stat;
397 	char *raw_part;
398 
399 	is_floppy = strncmp(device, "/dev/rdsk", strlen("/dev/rdsk")) &&
400 	    strncmp(device, "/dev/dsk", strlen("/dev/dsk"));
401 
402 	/* handle boot partition specification */
403 	if (!is_floppy && strstr(device, "p0:boot")) {
404 		is_bootpar = 1;
405 	}
406 
407 	raw_part = get_raw_partition(device);
408 
409 	if (nowrite)
410 		dev_fd = open(raw_part, O_RDONLY);
411 	else
412 		dev_fd = open(raw_part, O_RDWR);
413 
414 	if (dev_fd == -1 || fstat(dev_fd, &stat) != 0) {
415 		(void) fprintf(stderr, OPEN_FAIL, raw_part);
416 		exit(-1);
417 	}
418 	if (S_ISCHR(stat.st_mode) == 0) {
419 		(void) fprintf(stderr, NOT_RAW_DEVICE, raw_part);
420 		exit(-1);
421 	}
422 
423 	return (dev_fd);
424 }
425 
426 static void
427 read_stage1_stage2(char *stage1, char *stage2)
428 {
429 	int fd;
430 
431 	/* read the stage1 file from filesystem */
432 	fd = open(stage1, O_RDONLY);
433 	if (fd == -1 || read(fd, stage1_buffer, SECTOR_SIZE) != SECTOR_SIZE) {
434 		(void) fprintf(stderr, READ_FAIL_STAGE1, stage1);
435 		exit(-1);
436 	}
437 	(void) close(fd);
438 
439 	/* read first two blocks of stage 2 from filesystem */
440 	stage2_fd = open(stage2, O_RDONLY);
441 	if (stage2_fd == -1 ||
442 	    read(stage2_fd, stage2_buffer, 2 * SECTOR_SIZE)
443 	    != 2 * SECTOR_SIZE) {
444 		(void) fprintf(stderr, READ_FAIL_STAGE2, stage2);
445 		exit(-1);
446 	}
447 	/* leave the stage2 file open for later */
448 }
449 
450 static void
451 read_bpb_sect(int dev_fd)
452 {
453 	if (pread(dev_fd, bpb_sect, SECTOR_SIZE, 0) != SECTOR_SIZE) {
454 		(void) fprintf(stderr, READ_FAIL_BPB);
455 		exit(-1);
456 	}
457 }
458 
459 static void
460 read_boot_sect(char *device)
461 {
462 	static int read_mbr = 0;
463 	int i, fd;
464 	char save[2];
465 
466 	if (read_mbr)
467 		return;
468 	read_mbr = 1;
469 
470 	/* get the whole disk (p0) */
471 	i = strlen(device);
472 	save[0] = device[i - 2];
473 	save[1] = device[i - 1];
474 	device[i - 2] = 'p';
475 	device[i - 1] = '0';
476 
477 	device_p0 = strdup(device);
478 	fd = open(device, O_RDONLY);
479 	if (fd == -1 || read(fd, boot_sect, SECTOR_SIZE) != SECTOR_SIZE) {
480 		(void) fprintf(stderr, READ_FAIL_MBR, device);
481 		if (fd == -1)
482 			perror("open");
483 		else
484 			perror("read");
485 		exit(-1);
486 	}
487 	(void) close(fd);
488 	device[i - 2] = save[0];
489 	device[i - 1] = save[1];
490 }
491 
492 static void
493 write_boot_sect(char *device)
494 {
495 	int fd, len;
496 	char *raw, *end;
497 	struct stat stat;
498 
499 	/* make a copy and chop off ":boot" */
500 	raw = strdup(device);
501 	end = strstr(raw, "p0:boot");
502 	if (end)
503 		end[2] = 0;
504 
505 	/* open p0 (whole disk) */
506 	len = strlen(raw);
507 	raw[len - 2] = 'p';
508 	raw[len - 1] = '0';
509 	fd = open(raw, O_WRONLY);
510 	if (fd == -1 || fstat(fd, &stat) != 0) {
511 		(void) fprintf(stderr, OPEN_FAIL, raw);
512 		exit(-1);
513 	}
514 	if (!nowrite &&
515 	    pwrite(fd, stage1_buffer, SECTOR_SIZE, 0) != SECTOR_SIZE) {
516 		(void) fprintf(stderr, WRITE_FAIL_BOOTSEC);
517 		exit(-1);
518 	}
519 	(void) fprintf(stdout, WRITE_MBOOT);
520 	(void) close(fd);
521 }
522 
523 static void
524 modify_and_write_stage1(int dev_fd)
525 {
526 	if (is_floppy) {
527 		stage2_first_sector = blocklist[0];
528 		/* copy bios parameter block (for fat fs) */
529 		bcopy(bpb_sect + STAGE1_BPB_OFFSET,
530 		    stage1_buffer + STAGE1_BPB_OFFSET, STAGE1_BPB_SIZE);
531 	} else if (is_bootpar) {
532 		stage2_first_sector = get_start_sector(dev_fd) + blocklist[0];
533 		/* copy bios parameter block (for fat fs) and MBR */
534 		bcopy(bpb_sect + STAGE1_BPB_OFFSET,
535 		    stage1_buffer + STAGE1_BPB_OFFSET, STAGE1_BPB_SIZE);
536 		bcopy(boot_sect + BOOTSZ, stage1_buffer + BOOTSZ, 512 - BOOTSZ);
537 		*((unsigned char *)(stage1_buffer + STAGE1_FORCE_LBA)) = 1;
538 	} else {
539 		stage2_first_sector = get_start_sector(dev_fd) + STAGE2_BLKOFF;
540 		/* copy MBR to stage1 in case of overwriting MBR sector */
541 		bcopy(boot_sect + BOOTSZ, stage1_buffer + BOOTSZ, 512 - BOOTSZ);
542 		*((unsigned char *)(stage1_buffer + STAGE1_FORCE_LBA)) = 1;
543 	}
544 
545 	/* modify default stage1 file generated by GRUB */
546 	*((ulong_t *)(stage1_buffer + STAGE1_STAGE2_SECTOR))
547 	    = stage2_first_sector;
548 	*((ushort_t *)(stage1_buffer + STAGE1_STAGE2_ADDRESS))
549 	    = STAGE2_MEMADDR;
550 	*((ushort_t *)(stage1_buffer + STAGE1_STAGE2_SEGMENT))
551 	    = STAGE2_MEMADDR >> 4;
552 
553 	/*
554 	 * XXX the default grub distribution also:
555 	 * - Copy the possible MBR/extended part table
556 	 * - Set the boot drive of stage1
557 	 */
558 
559 	/* write stage1/pboot to 1st sector */
560 	if (!nowrite &&
561 	    pwrite(dev_fd, stage1_buffer, SECTOR_SIZE, 0) != SECTOR_SIZE) {
562 		(void) fprintf(stderr, WRITE_FAIL_PBOOT);
563 		exit(-1);
564 	}
565 
566 	if (is_floppy) {
567 		(void) fprintf(stdout, WRITE_BOOTSEC_FLOPPY);
568 	} else {
569 		(void) fprintf(stdout, WRITE_PBOOT,
570 		    partition, get_start_sector(dev_fd));
571 	}
572 }
573 
574 static void check_extended_support(char *stage2)
575 {
576 	char	*cmp = stage2_buffer + STAGE2_SIGN_OFFSET - 1;
577 
578 	if ((*cmp++ != '\xEE') && memcmp(cmp, extended_sig, HASH_SIZE) != 0) {
579 		fprintf(stderr, "%s does not support extended versioning\n",
580 		    stage2);
581 		do_version = 0;
582 	}
583 }
584 
585 
586 static void print_info()
587 {
588 	int	i;
589 
590 	if (strip) {
591 		fprintf(stdout, "%s\n", verstring);
592 	} else {
593 		fprintf(stdout, "Grub extended version information : %s\n",
594 		    verstring);
595 		fprintf(stdout, "Grub stage2 (MD5) signature : ");
596 	}
597 
598 	for (i = 0; i < HASH_SIZE; i++)
599 		fprintf(stdout, "%02x", (unsigned char)signature[i]);
600 
601 	fprintf(stdout, "\n");
602 }
603 
604 static int
605 read_stage2_info(int dev_fd)
606 {
607 	int 	ret;
608 	int	first_offset, second_offset;
609 	char	*sign;
610 
611 	if (is_floppy || is_bootpar) {
612 
613 		ret = pread(dev_fd, stage1_buffer, SECTOR_SIZE, 0);
614 		if (ret != SECTOR_SIZE) {
615 			perror("Error reading stage1 sector");
616 			return (1);
617 		}
618 
619 		first_offset = *((ulong_t *)(stage1_buffer +
620 		    STAGE1_STAGE2_SECTOR));
621 
622 		/* Start reading in the first sector of stage 2 */
623 
624 		ret = pread(dev_fd, stage2_buffer, SECTOR_SIZE, first_offset *
625 		    SECTOR_SIZE);
626 		if (ret != SECTOR_SIZE) {
627 			perror("Error reading stage2 first sector");
628 			return (1);
629 		}
630 
631 		/* From the block list section grab stage2 second sector */
632 
633 		second_offset = *((ulong_t *)(stage2_buffer +
634 		    STAGE2_BLOCKLIST));
635 
636 		ret = pread(dev_fd, stage2_buffer + SECTOR_SIZE, SECTOR_SIZE,
637 		    second_offset * SECTOR_SIZE);
638 		if (ret != SECTOR_SIZE) {
639 			perror("Error reading stage2 second sector");
640 			return (1);
641 		}
642 	} else {
643 		ret = pread(dev_fd, stage2_buffer, 2 * SECTOR_SIZE,
644 		    STAGE2_BLKOFF * SECTOR_SIZE);
645 		if (ret != 2 * SECTOR_SIZE) {
646 			perror("Error reading stage2 sectors");
647 			return (1);
648 		}
649 	}
650 
651 	sign = stage2_buffer + STAGE2_SIGN_OFFSET - 1;
652 	if (*sign++ != '\xEE')
653 		return (1);
654 	(void) memcpy(signature, sign, HASH_SIZE);
655 	sign = stage2_buffer + STAGE2_PKG_VERSION;
656 	(void) strncpy(verstring, sign, VERSION_SIZE);
657 	return (0);
658 }
659 
660 
661 static int
662 compute_and_write_md5hash(char *dest)
663 {
664 	struct stat	sb;
665 	char		*buffer;
666 
667 	if (fstat(stage2_fd, &sb) == -1)
668 		return (-1);
669 
670 	buffer = malloc(sb.st_size);
671 	if (buffer == NULL)
672 		return (-1);
673 
674 	if (lseek(stage2_fd, 0, SEEK_SET) == -1)
675 		return (-1);
676 	if (read(stage2_fd, buffer, sb.st_size) < 0)
677 		return (-1);
678 
679 	md5_calc(dest, buffer, sb.st_size);
680 	free(buffer);
681 	return (0);
682 }
683 
684 
685 #define	START_BLOCK(pos)	(*(ulong_t *)(pos))
686 #define	NUM_BLOCK(pos)		(*(ushort_t *)((pos) + 4))
687 #define	START_SEG(pos)		(*(ushort_t *)((pos) + 6))
688 
689 static void
690 modify_and_write_stage2(int dev_fd)
691 {
692 	int 	nrecord;
693 	off_t 	offset;
694 	char	*dest;
695 
696 	if (do_version) {
697 		dest = stage2_buffer + STAGE2_SIGN_OFFSET;
698 		if (compute_and_write_md5hash(dest) < 0)
699 			perror("MD5 operation");
700 		dest = stage2_buffer + STAGE2_PKG_VERSION;
701 		(void) strncpy(dest, verstring, VERSION_SIZE);
702 	}
703 
704 	if (is_floppy || is_bootpar) {
705 		int i = 0;
706 		uint32_t partition_offset;
707 		uint32_t install_addr = 0x8200;
708 		uchar_t *pos = (uchar_t *)stage2_buffer + STAGE2_BLOCKLIST;
709 
710 		stage2_first_sector = blocklist[0];
711 
712 		/* figure out the second sector */
713 		if (blocklist[1] > 1) {
714 			blocklist[0]++;
715 			blocklist[1]--;
716 		} else {
717 			i += 2;
718 		}
719 		stage2_second_sector = blocklist[i];
720 
721 		if (is_floppy)
722 			partition_offset = 0;
723 		else	/* solaris boot partition */
724 			partition_offset = get_start_sector(dev_fd);
725 
726 		/* install the blocklist at the end of stage2_buffer */
727 		while (blocklist[i]) {
728 			if (START_BLOCK(pos - 8) != 0 &&
729 			    START_BLOCK(pos - 8) != blocklist[i + 2]) {
730 				(void) fprintf(stderr, PCFS_FRAGMENTED);
731 				exit(-1);
732 			}
733 			START_BLOCK(pos) = blocklist[i] + partition_offset;
734 			START_SEG(pos) = (ushort_t)(install_addr >> 4);
735 			NUM_BLOCK(pos) = blocklist[i + 1];
736 			install_addr += blocklist[i + 1] * SECTOR_SIZE;
737 			pos -= 8;
738 			i += 2;
739 		}
740 
741 	} else {
742 		/*
743 		 * In a solaris partition, stage2 is written to contiguous
744 		 * blocks. So we update the starting block only.
745 		 */
746 		*((ulong_t *)(stage2_buffer + STAGE2_BLOCKLIST)) =
747 		    stage2_first_sector + 1;
748 	}
749 
750 	if (is_floppy) {
751 		/* modify the config file to add (fd0) */
752 		char *config_file = stage2_buffer + STAGE2_VER_STRING;
753 		while (*config_file++)
754 			;
755 		strcpy(config_file, "(fd0)/boot/grub/menu.lst");
756 	} else {
757 		/* force lba and set disk partition */
758 		*((unsigned char *) (stage2_buffer + STAGE2_FORCE_LBA)) = 1;
759 		*((long *)(stage2_buffer + STAGE2_INSTALLPART))
760 		    = (partition << 16) | (slice << 8) | 0xff;
761 	}
762 
763 	/* modification done, now do the writing */
764 	if (is_floppy || is_bootpar) {
765 		/* we rewrite block 0 and 1 and that's it */
766 		if (!nowrite &&
767 		    (pwrite(dev_fd, stage2_buffer, SECTOR_SIZE,
768 		    stage2_first_sector * SECTOR_SIZE) != SECTOR_SIZE ||
769 		    pwrite(dev_fd, stage2_buffer + SECTOR_SIZE, SECTOR_SIZE,
770 		    stage2_second_sector * SECTOR_SIZE) != SECTOR_SIZE)) {
771 			(void) fprintf(stderr, WRITE_FAIL_STAGE2);
772 			exit(-1);
773 		}
774 		(void) fprintf(stdout, WRITE_STAGE2_PCFS);
775 		return;
776 	}
777 
778 	/* for disk, write stage2 starting at STAGE2_BLKOFF sector */
779 	offset = STAGE2_BLKOFF;
780 
781 	/* write the modified first two sectors */
782 	if (!nowrite && pwrite(dev_fd, stage2_buffer, 2 * SECTOR_SIZE,
783 	    offset * SECTOR_SIZE) != 2 * SECTOR_SIZE) {
784 		(void) fprintf(stderr, WRITE_FAIL_STAGE2);
785 		exit(-1);
786 	}
787 
788 	/* write the remaining sectors */
789 	nrecord = 2;
790 	offset += 2;
791 	for (;;) {
792 		int nread, nwrite;
793 		nread = pread(stage2_fd, stage2_buffer, SECTOR_SIZE,
794 		    nrecord * SECTOR_SIZE);
795 		if (nread > 0 && !nowrite)
796 			nwrite = pwrite(dev_fd, stage2_buffer, SECTOR_SIZE,
797 			    offset * SECTOR_SIZE);
798 		else
799 			nwrite = SECTOR_SIZE;
800 		if (nread < 0 || nwrite != SECTOR_SIZE) {
801 			(void) fprintf(stderr, WRITE_FAIL_STAGE2_BLOCKS,
802 			    nread, nwrite);
803 			break;
804 		}
805 		if (nread > 0) {
806 			nrecord ++;
807 			offset ++;
808 		}
809 		if (nread < SECTOR_SIZE)
810 			break;	/* end of file */
811 	}
812 	(void) fprintf(stdout, WRITE_STAGE2_DISK,
813 	    partition, nrecord, STAGE2_BLKOFF, stage2_first_sector);
814 }
815 
816 static char *
817 get_raw_partition(char *device)
818 {
819 	int len;
820 	struct mboot *mboot;
821 	static char *raw = NULL;
822 
823 	if (raw)
824 		return (raw);
825 	raw = strdup(device);
826 
827 	if (is_floppy)
828 		return (raw);
829 
830 	if (is_bootpar) {
831 		int i;
832 		char *end = strstr(raw, "p0:boot");
833 
834 		end[2] = 0;		/* chop off :boot */
835 		read_boot_sect(raw);
836 		mboot = (struct mboot *)boot_sect;
837 		for (i = 0; i < FD_NUMPART; i++) {
838 			struct ipart *part = (struct ipart *)mboot->parts + i;
839 			if (part->systid == 0xbe)	/* solaris boot part */
840 				break;
841 		}
842 
843 		if (i == FD_NUMPART) {
844 			(void) fprintf(stderr, BOOTPAR_NOTFOUND, device);
845 			exit(-1);
846 		}
847 		end[1] = '1' + i;	/* set partition name */
848 		return (raw);
849 	}
850 
851 	/* For disk, remember slice and return whole fdisk partition  */
852 	len = strlen(raw);
853 	if (raw[len - 2] != 's' || raw[len - 1] == '2') {
854 		(void) fprintf(stderr, NOT_ROOT_SLICE);
855 		exit(-1);
856 	}
857 	slice = atoi(&raw[len - 1]);
858 
859 	raw[len - 2] = 's';
860 	raw[len - 1] = '2';
861 	return (raw);
862 }
863 
864 #define	TMP_MNTPT	"/tmp/installgrub_pcfs"
865 static void
866 copy_stage2(int dev_fd, char *device)
867 {
868 	FILE *mntfp;
869 	int i, pcfs_fp;
870 	char buf[SECTOR_SIZE];
871 	char *cp;
872 	struct mnttab mp = {0}, mpref = {0};
873 
874 	/* convert raw to block device name by removing the first 'r' */
875 	(void) strncpy(buf, device, sizeof (buf));
876 	buf[sizeof (buf) - 1] = 0;
877 	cp = strchr(buf, 'r');
878 	if (cp == NULL) {
879 		(void) fprintf(stderr, CONVERT_FAIL, device);
880 		exit(-1);
881 	}
882 	do {
883 		*cp = *(cp + 1);
884 	} while (*(++cp));
885 
886 	/* get the mount point, if any */
887 	mntfp = fopen("/etc/mnttab", "r");
888 	if (mntfp == NULL) {
889 		(void) fprintf(stderr, OPEN_FAIL_FILE, "/etc/mnttab");
890 		exit(-1);
891 	}
892 
893 	mpref.mnt_special = buf;
894 	if (getmntany(mntfp, &mp, &mpref) != 0) {
895 		char cmd[128];
896 
897 		/* not mounted, try remount */
898 		(void) mkdir(TMP_MNTPT, S_IRWXU);
899 		(void) snprintf(cmd, sizeof (cmd), "mount -F pcfs %s %s",
900 		    buf, TMP_MNTPT);
901 		(void) system(cmd);
902 		rewind(mntfp);
903 		bzero(&mp, sizeof (mp));
904 		if (getmntany(mntfp, &mp, &mpref) != 0) {
905 			(void) fprintf(stderr, MOUNT_FAIL, buf);
906 			exit(-1);
907 		}
908 	}
909 
910 	(void) snprintf(buf, sizeof (buf),
911 	    "%s/boot", mp.mnt_mountp);
912 	(void) mkdir(buf, S_IRWXU);
913 	(void) strcat(buf, "/grub");
914 	(void) mkdir(buf, S_IRWXU);
915 
916 	(void) strcat(buf, "/stage2");
917 	pcfs_fp = open(buf, O_WRONLY | O_CREAT, S_IRWXU);
918 	if (pcfs_fp == -1) {
919 		(void) fprintf(stderr, OPEN_FAIL_FILE, buf);
920 		perror("open:");
921 		(void) umount(TMP_MNTPT);
922 		exit(-1);
923 	}
924 
925 	/* write stage2 to pcfs */
926 	for (i = 0; ; i++) {
927 		int nread, nwrite;
928 		nread = pread(stage2_fd, buf, SECTOR_SIZE, i * SECTOR_SIZE);
929 		if (nowrite)
930 			nwrite = nread;
931 		else
932 			nwrite = pwrite(pcfs_fp, buf, nread, i * SECTOR_SIZE);
933 		if (nread < 0 || nwrite != nread) {
934 			(void) fprintf(stderr, WRITE_FAIL_STAGE2_BLOCKS,
935 			    nread, nwrite);
936 			break;
937 		}
938 		if (nread < SECTOR_SIZE)
939 			break;	/* end of file */
940 	}
941 	(void) close(pcfs_fp);
942 	(void) umount(TMP_MNTPT);
943 
944 	/*
945 	 * Now, get the blocklist from the device.
946 	 */
947 	bzero(blocklist, sizeof (blocklist));
948 	if (read_stage2_blocklist(dev_fd, blocklist) != 0)
949 		exit(-1);
950 }
951