xref: /illumos-gate/usr/src/cmd/fdisk/fdisk.c (revision cc1a9a89a73172cc2db053635fab3b1b91691657)
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 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*	Copyright (c) 1990, 1991 UNIX System Laboratories, Inc.	*/
28 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989, 1990 AT&T	*/
29 /*	  All Rights Reserved	*/
30 
31 /*	Copyright (c) 1987, 1988 Microsoft Corporation	*/
32 /*	  All Rights Reserved	*/
33 
34 /*
35  * PROGRAM: fdisk(1M)
36  * This program reads the partition table on the specified device and
37  * also reads the drive parameters. The user can perform various
38  * operations from a supplied menu or from the command line. Diagnostic
39  * options are also available.
40  */
41 
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <unistd.h>
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <ctype.h>
49 #include <sys/stat.h>
50 #include <sys/types.h>
51 #include <limits.h>
52 #include <sys/param.h>
53 #include <sys/systeminfo.h>
54 #include <sys/efi_partition.h>
55 #include <sys/byteorder.h>
56 #include <sys/systeminfo.h>
57 
58 #include <sys/dktp/fdisk.h>
59 #include <sys/dkio.h>
60 #include <sys/vtoc.h>
61 
62 #define	CLR_SCR ""
63 #define	CLR_LIN ""
64 #define	HOME "" \
65 	""
66 #define	Q_LINE ""
67 #define	W_LINE ""
68 #define	E_LINE ""
69 #define	M_LINE "" \
70 	""
71 #define	T_LINE ""
72 
73 #define	DEFAULT_PATH	"/dev/rdsk/"
74 
75 /* XXX - should be in fdisk.h, used by sd as well */
76 
77 /*
78  * the MAX values are the maximum usable values for BIOS chs values
79  * The MAX_CYL value of 1022 is the maximum usable value
80  *   the value of 1023 is a fence value,
81  *   indicating no CHS geometry exists for the corresponding LBA value.
82  * HEAD range [ 0 .. MAX_HEAD ], so number of heads is (MAX_HEAD + 1)
83  * SECT range [ 1 .. MAX_SECT ], so number of sectors is (MAX_SECT)
84  */
85 #define	MAX_SECT	(63)
86 #define	MAX_CYL		(1022)
87 #define	MAX_HEAD	(254)
88 
89 #define	DK_MAX_2TB	UINT32_MAX	/* Max # of sectors in 2TB */
90 
91 /* for clear_vtoc() */
92 #define	OLD		0
93 #define	NEW		1
94 
95 /* readvtoc/writevtoc return codes */
96 #define	VTOC_OK		0	/* Good VTOC */
97 #define	VTOC_INVAL	1	/* invalid VTOC */
98 #define	VTOC_NOTSUP	2	/* operation not supported - EFI label */
99 #define	VTOC_RWERR	3	/* couldn't read or write VTOC */
100 
101 /*
102  * Support for fdisk(1M) on the SPARC platform
103  *	In order to convert little endian values to big endian for SPARC,
104  *	byte/short and long values must be swapped.
105  *	These swapping macros will be used to access information in the
106  *	mboot and ipart structures.
107  */
108 
109 #ifdef sparc
110 #define	les(val)	((((val)&0xFF)<<8)|(((val)>>8)&0xFF))
111 #define	lel(val)	(((unsigned)(les((val)&0x0000FFFF))<<16) | \
112 			    (les((unsigned)((val)&0xffff0000)>>16)))
113 #else
114 #define	les(val)	(val)
115 #define	lel(val)	(val)
116 #endif
117 
118 #if defined(_SUNOS_VTOC_16)
119 #define	VTOC_OFFSET	1
120 #elif defined(_SUNOS_VTOC_8)
121 #define	VTOC_OFFSET	0
122 #else
123 #error No VTOC format defined.
124 #endif
125 
126 static char Usage[] = "Usage: fdisk\n"
127 "[ -A id:act:bhead:bsect:bcyl:ehead:esect:ecyl:rsect:numsect ]\n"
128 "[ -b masterboot ]\n"
129 "[ -D id:act:bhead:bsect:bcyl:ehead:esect:ecyl:rsect:numsect ]\n"
130 "[ -F fdisk_file ] [ -h ] [ -o offset ] [ -P fill_patt ] [ -s size ]\n"
131 "[ -S geom_file ] [ [ -v ] -W { creat_fdisk_file | - } ]\n"
132 "[ -w | r | d | n | I | B | E | g | G | R | t | T ] rdevice";
133 
134 static char Usage1[] = "    Partition options:\n"
135 "	-A id:act:bhead:bsect:bcyl:ehead:esect:ecyl:rsect:numsect\n"
136 "		Create a partition with specific attributes:\n"
137 "		id      = system id number (fdisk.h) for the partition type\n"
138 "		act     = active partition flag (0 is off and 128 is on)\n"
139 "		bhead   = beginning head for start of partition\n"
140 "		bsect   = beginning sector for start of partition\n"
141 "		bcyl    = beginning cylinder for start of partition\n"
142 "		ehead   = ending head for end of partition\n"
143 "		esect   = ending sector for end of partition\n"
144 "		ecyl    = ending cylinder for end of partition\n"
145 "		rsect   = sector number from start of disk for\n"
146 "			  start of partition\n"
147 "		numsect = partition size in sectors\n"
148 "	-b master_boot\n"
149 "		Use master_boot as the master boot file.\n"
150 "	-B	Create one Solaris partition that uses the entire disk.\n"
151 "	-E	Create one EFI partition that uses the entire disk.\n"
152 "	-D id:act:bhead:bsect:bcyl:ehead:esect:ecyl:rsect:numsect\n"
153 "		Delete a partition. See attribute definitions for -A.\n"
154 "	-F fdisk_file\n"
155 "		Use fdisk_file to initialize on-line fdisk table.\n"
156 "	-I	Forego device checks. Generate a file image of what would go\n"
157 "		on a disk using the geometry specified with the -S option.\n"
158 "	-n	Do not run in interactive mode.\n"
159 "	-R	Open the disk device as read-only.\n"
160 "	-t	Check and adjust VTOC to be consistent with fdisk table.\n"
161 "		VTOC slices exceeding the partition size will be truncated.\n"
162 "	-T	Check and adjust VTOC to be consistent with fdisk table.\n"
163 "		VTOC slices exceeding the partition size will be removed.\n"
164 "	-W fdisk_file\n"
165 "		Write on-disk table to fdisk_file.\n"
166 "	-W -	Write on-disk table to standard output.\n"
167 "	-v	Display virtual geometry. Must be used with the -W option.\n"
168 "    Diagnostic options:\n"
169 "	-d	Activate debug information about progress.\n"
170 "	-g	Write label geometry to standard output:\n"
171 "		PCYL		number of physical cylinders\n"
172 "		NCYL		number of usable cylinders\n"
173 "		ACYL		number of alternate cylinders\n"
174 "		BCYL		cylinder offset\n"
175 "		NHEADS		number of heads\n"
176 "		NSECTORS	number of sectors per track\n"
177 "		SECTSIZ		size of a sector in bytes\n"
178 "	-G	Write physical geometry to standard output (see -g).\n"
179 "	-h	Issue this verbose help message.\n"
180 "	-o offset\n"
181 "		Block offset from start of disk (default 0). Ignored if\n"
182 "		-P # specified.\n"
183 "	-P fill_patt\n"
184 "		Fill disk with pattern fill_patt. fill_patt can be decimal or\n"
185 "		hexadecimal and is used as number for constant long word\n"
186 "		pattern. If fill_patt is \"#\" then pattern of block #\n"
187 "		for each block. Pattern is put in each block as long words\n"
188 "		and fills each block (see -o and -s).\n"
189 "	-r	Read from a disk to stdout (see -o and -s).\n"
190 "	-s size	Number of blocks on which to perform operation (see -o).\n"
191 "	-S geom_file\n"
192 "		Use geom_file to set the label geometry (see -g).\n"
193 "	-w	Write to a disk from stdin (see -o and -s).";
194 
195 static char Ostr[] = "Other OS";
196 static char Dstr[] = "DOS12";
197 static char D16str[] = "DOS16";
198 static char DDstr[] = "DOS-DATA";
199 static char EDstr[] = "EXT-DOS";
200 static char DBstr[] = "DOS-BIG";
201 static char PCstr[] = "PCIX";
202 static char Ustr[] = "UNIX System";
203 static char SUstr[] = "Solaris";
204 static char SU2str[] = "Solaris2";
205 static char X86str[] = "x86 Boot";
206 static char DIAGstr[] = "Diagnostic";
207 static char IFSstr[] = "IFS: NTFS";
208 static char AIXstr[] = "AIX Boot";
209 static char AIXDstr[] = "AIX Data";
210 static char OS2str[] = "OS/2 Boot";
211 static char WINstr[] = "Win95 FAT32";
212 static char EWINstr[] = "Ext Win95";
213 static char FAT95str[] = "FAT16 LBA";
214 static char EXTLstr[] = "EXT LBA";
215 static char LINUXstr[] = "Linux";
216 static char CPMstr[] = "CP/M";
217 static char NOVstr[] = "Netware 3.x+";
218 static char QNXstr[] = "QNX 4.x";
219 static char QNX2str[] = "QNX part 2";
220 static char QNX3str[] = "QNX part 3";
221 static char LINNATstr[] = "Linux native";
222 static char NTFSVOL1str[] = "NT volset 1";
223 static char NTFSVOL2str[] = "NT volset 2";
224 static char BSDstr[] = "BSD OS";
225 static char NEXTSTEPstr[] = "NeXTSTEP";
226 static char BSDIFSstr[] = "BSDI FS";
227 static char BSDISWAPstr[] = "BSDI swap";
228 static char Actvstr[] = "Active";
229 static char EFIstr[] = "EFI";
230 static char NAstr[] = "      ";
231 
232 /* All the user options and flags */
233 static char *Dfltdev;			/* name of fixed disk drive */
234 
235 /* Diagnostic options */
236 static int	io_wrt = 0;		/* write stdin to disk (-w) */
237 static int	io_rd = 0;		/* read disk and write stdout (-r) */
238 static char	*io_fatt;		/* user supplied pattern (-P pattern) */
239 static int	io_patt = 0;		/* write pattern to disk (-P pattern) */
240 static int	io_lgeom = 0;		/* get label geometry (-g) */
241 static int	io_pgeom = 0;		/* get drive physical geometry (-G) */
242 static char	*io_sgeom = 0;		/* set label geometry (-S geom_file) */
243 static int	io_readonly = 0;	/* do not write to disk (-R) */
244 
245 /* The -o offset and -s size options specify the area of the disk on */
246 /* which to perform the particular operation; i.e., -P, -r, or -w. */
247 static off_t	io_offset = 0;		/* offset sector (-o offset) */
248 static off_t	io_size = 0;		/* size in sectors (-s size) */
249 
250 /* Partition table flags */
251 static int	v_flag = 0;		/* virtual geometry-HBA flag (-v) */
252 static int 	stdo_flag = 0;		/* stdout flag (-W -) */
253 static int	io_fdisk = 0;		/* do fdisk operation */
254 static int	io_ifdisk = 0;		/* interactive partition */
255 static int	io_nifdisk = 0;		/* non-interactive partition (-n) */
256 
257 static int	io_adjt = 0;		/* check/adjust VTOC (truncate (-t)) */
258 static int	io_ADJT = 0;		/* check/adjust VTOC (delete (-T)) */
259 static char	*io_ffdisk = 0;		/* input fdisk file name (-F file) */
260 static char	*io_Wfdisk = 0;		/* output fdisk file name (-W file) */
261 static char	*io_Afdisk = 0;		/* add entry to partition table (-A) */
262 static char	*io_Dfdisk = 0;		/* delete entry from part. table (-D) */
263 
264 static char	*io_mboot = 0;		/* master boot record (-b boot_file) */
265 
266 static struct mboot BootCod;		/* buffer for master boot record */
267 
268 static int	io_wholedisk = 0;	/* use whole disk for Solaris (-B) */
269 static int	io_EFIdisk = 0;		/* use whole disk for EFI (-E) */
270 static int	io_debug = 0;		/* activate verbose mode (-d) */
271 static int	io_image = 0;		/* create image using geometry (-I) */
272 
273 static struct mboot *Bootblk;		/* pointer to cut/paste sector zero */
274 static char	*Bootsect;		/* pointer to sector zero buffer */
275 static char	*Nullsect;
276 static struct extvtoc	disk_vtoc;	/* verify VTOC table */
277 static int	vt_inval = 0;
278 static int	no_virtgeom_ioctl = 0;	/* ioctl for virtual geometry failed */
279 static int	no_physgeom_ioctl = 0;	/* ioctl for physical geometry failed */
280 
281 static struct ipart	Table[FD_NUMPART];
282 static struct ipart	Old_Table[FD_NUMPART];
283 
284 /* Disk geometry information */
285 static struct dk_minfo	minfo;
286 static struct dk_geom	disk_geom;
287 
288 static int Dev;			/* fd for open device */
289 
290 static diskaddr_t	dev_capacity;	/* number of blocks on device */
291 static diskaddr_t	chs_capacity;	/* Numcyl_usable * heads * sectors */
292 
293 static int		Numcyl_usable;	/* Number of usable cylinders */
294 					/*  used to limit fdisk to 2TB */
295 
296 /* Physical geometry for the drive */
297 static int	Numcyl;			/* number of cylinders */
298 static int	heads;			/* number of heads */
299 static int	sectors;		/* number of sectors per track */
300 static int	acyl;			/* number of alternate sectors */
301 
302 /* HBA (virtual) geometry for the drive */
303 static int	hba_Numcyl;		/* number of cylinders */
304 static int	hba_heads;		/* number of heads */
305 static int	hba_sectors;		/* number of sectors per track */
306 
307 static int	sectsiz;		/* sector size */
308 
309 /* Load functions for fdisk table modification */
310 #define	LOADFILE	0	/* load fdisk from file */
311 #define	LOADDEL		1	/* delete an fdisk entry */
312 #define	LOADADD		2	/* add an fdisk entry */
313 
314 #define	CBUFLEN 80
315 static char s[CBUFLEN];
316 
317 static void update_disk_and_exit(boolean_t table_changed);
318 int main(int argc, char *argv[]);
319 static int read_geom(char *sgeom);
320 static void dev_mboot_read(void);
321 static void dev_mboot_write(off_t sect, char *buff, int bootsiz);
322 static void mboot_read(void);
323 static void fill_patt(void);
324 static void abs_read(void);
325 static void abs_write(void);
326 static void load(int funct, char *file);
327 static void Set_Table_CHS_Values(int ti);
328 static int insert_tbl(int id, int act,
329     int bhead, int bsect, int bcyl,
330     int ehead, int esect, int ecyl,
331     uint32_t rsect, uint32_t numsect);
332 static int verify_tbl(void);
333 static int pars_fdisk(char *line,
334     int *id, int *act,
335     int *bhead, int *bsect, int *bcyl,
336     int *ehead, int *esect, int *ecyl,
337     uint32_t *rsect, uint32_t *numsect);
338 static int validate_part(int id, uint32_t rsect, uint32_t numsect);
339 static void stage0(void);
340 static int pcreate(void);
341 static int specify(uchar_t tsystid);
342 static void dispmenu(void);
343 static int pchange(void);
344 static int ppartid(void);
345 static char pdelete(void);
346 static void rm_blanks(char *s);
347 static int getcyl(void);
348 static void disptbl(void);
349 static void print_Table(void);
350 static void copy_Table_to_Old_Table(void);
351 static void nulltbl(void);
352 static void copy_Bootblk_to_Table(void);
353 static void fill_ipart(char *bootptr, struct ipart *partp);
354 #ifdef sparc
355 uchar_t getbyte(char **bp);
356 uint32_t getlong(char **bp);
357 #endif
358 static void copy_Table_to_Bootblk(void);
359 static int TableChanged(void);
360 static void ffile_write(char *file);
361 static void fix_slice(void);
362 static int yesno(void);
363 static int readvtoc(void);
364 static int writevtoc(void);
365 static int efi_ioctl(int fd, int cmd, dk_efi_t *dk_ioc);
366 static int clear_efi(void);
367 static void clear_vtoc(int table, int part);
368 static int lecture_and_query(char *warning, char *devname);
369 static void sanity_check_provided_device(char *devname, int fd);
370 static char *get_node(char *devname);
371 
372 static void
373 update_disk_and_exit(boolean_t table_changed)
374 {
375 	if (table_changed) {
376 		/*
377 		 * Copy the new table back to the sector buffer
378 		 * and write it to disk
379 		 */
380 		copy_Table_to_Bootblk();
381 		dev_mboot_write(0, Bootsect, sectsiz);
382 	}
383 
384 	/* If the VTOC table is wrong fix it (truncation only) */
385 	if (io_adjt)
386 		fix_slice();
387 
388 	exit(0);
389 }
390 
391 
392 
393 /*
394  * main
395  * Process command-line options.
396  */
397 int
398 main(int argc, char *argv[])
399 {
400 	int c, i;
401 	extern	int optind;
402 	extern	char *optarg;
403 	int	errflg = 0;
404 	int	diag_cnt = 0;
405 	int openmode;
406 
407 	setbuf(stderr, 0);	/* so all output gets out on exit */
408 	setbuf(stdout, 0);
409 
410 	/* Process the options. */
411 	while ((c = getopt(argc, argv, "o:s:P:F:b:A:D:W:S:tTIhwvrndgGRBE"))
412 	    != EOF) {
413 		switch (c) {
414 
415 			case 'o':
416 				io_offset = (off_t)strtoull(optarg, 0, 0);
417 				continue;
418 			case 's':
419 				io_size = (off_t)strtoull(optarg, 0, 0);
420 				continue;
421 			case 'P':
422 				diag_cnt++;
423 				io_patt++;
424 				io_fatt = optarg;
425 				continue;
426 			case 'w':
427 				diag_cnt++;
428 				io_wrt++;
429 				continue;
430 			case 'r':
431 				diag_cnt++;
432 				io_rd++;
433 				continue;
434 			case 'd':
435 				io_debug++;
436 				continue;
437 			case 'I':
438 				io_image++;
439 				continue;
440 			case 'R':
441 				io_readonly++;
442 				continue;
443 			case 'S':
444 				diag_cnt++;
445 				io_sgeom = optarg;
446 				continue;
447 			case 'T':
448 				io_ADJT++;
449 				/* FALLTHRU */
450 			case 't':
451 				io_adjt++;
452 				continue;
453 			case 'B':
454 				io_wholedisk++;
455 				io_fdisk++;
456 				continue;
457 			case 'E':
458 				io_EFIdisk++;
459 				io_fdisk++;
460 				continue;
461 			case 'g':
462 				diag_cnt++;
463 				io_lgeom++;
464 				continue;
465 			case 'G':
466 				diag_cnt++;
467 				io_pgeom++;
468 				continue;
469 			case 'n':
470 				io_nifdisk++;
471 				io_fdisk++;
472 				continue;
473 			case 'F':
474 				io_fdisk++;
475 				io_ffdisk = optarg;
476 				continue;
477 			case 'b':
478 				io_mboot = optarg;
479 				continue;
480 			case 'W':
481 				/*
482 				 * If '-' is the -W argument, then write
483 				 * to standard output, otherwise write
484 				 * to the specified file.
485 				 */
486 				if (strncmp(optarg, "-", 1) == 0)
487 					stdo_flag = 1;
488 				else
489 					io_Wfdisk = optarg;
490 				io_fdisk++;
491 				continue;
492 			case 'A':
493 				io_fdisk++;
494 				io_Afdisk = optarg;
495 				continue;
496 			case 'D':
497 				io_fdisk++;
498 				io_Dfdisk = optarg;
499 				continue;
500 			case 'h':
501 				(void) fprintf(stderr, "%s\n", Usage);
502 				(void) fprintf(stderr, "%s\n", Usage1);
503 				exit(0);
504 				/* FALLTHRU */
505 			case 'v':
506 				v_flag = 1;
507 				continue;
508 			case '?':
509 				errflg++;
510 				break;
511 		}
512 		break;
513 	}
514 
515 	if (io_image && io_sgeom && diag_cnt == 1) {
516 		diag_cnt = 0;
517 	}
518 
519 	/* User option checking */
520 
521 	/* By default, run in interactive mode */
522 	if (!io_fdisk && !diag_cnt && !io_nifdisk) {
523 		io_ifdisk++;
524 		io_fdisk++;
525 	}
526 	if (((io_fdisk || io_adjt) && diag_cnt) || (diag_cnt > 1)) {
527 		errflg++;
528 	}
529 
530 	/* Was any error detected? */
531 	if (errflg || argc == optind) {
532 		(void) fprintf(stderr, "%s\n", Usage);
533 		(void) fprintf(stderr,
534 		    "\nDetailed help is available with the -h option.\n");
535 		exit(2);
536 	}
537 
538 
539 	/* Figure out the correct device node to open */
540 	Dfltdev = get_node(argv[optind]);
541 
542 	if (io_readonly)
543 		openmode = O_RDONLY;
544 	else
545 		openmode = O_RDWR|O_CREAT;
546 
547 	if ((Dev = open(Dfltdev, openmode, 0666)) == -1) {
548 		(void) fprintf(stderr,
549 		    "fdisk: Cannot open device %s.\n",
550 		    Dfltdev);
551 		exit(1);
552 	}
553 	/*
554 	 * not all disk (or disklike) drivers support DKIOCGMEDIAINFO
555 	 * in that case leave the minfo structure zeroed
556 	 */
557 	if (ioctl(Dev, DKIOCGMEDIAINFO, &minfo)) {
558 		memset(&minfo, 0, sizeof (minfo));
559 	}
560 
561 	/* Get the disk geometry */
562 	if (!io_image) {
563 		/* Get disk's HBA (virtual) geometry */
564 		errno = 0;
565 		if (ioctl(Dev, DKIOCG_VIRTGEOM, &disk_geom)) {
566 
567 			/*
568 			 * If ioctl isn't implemented on this platform, then
569 			 * turn off flag to print out virtual geometry (-v),
570 			 * otherwise use the virtual geometry.
571 			 */
572 
573 			if (errno == ENOTTY) {
574 				v_flag = 0;
575 				no_virtgeom_ioctl = 1;
576 			} else if (errno == EINVAL) {
577 				/*
578 				 * This means that the ioctl exists, but
579 				 * is invalid for this disk, meaning the
580 				 * disk doesn't have an HBA geometry
581 				 * (like, say, it's larger than 8GB).
582 				 */
583 				v_flag = 0;
584 				hba_Numcyl = hba_heads = hba_sectors = 0;
585 			} else {
586 				(void) fprintf(stderr,
587 				    "%s: Cannot get virtual disk geometry.\n",
588 				    argv[optind]);
589 				exit(1);
590 			}
591 		} else {
592 			/* save virtual geometry values obtained by ioctl */
593 			hba_Numcyl = disk_geom.dkg_ncyl;
594 			hba_heads = disk_geom.dkg_nhead;
595 			hba_sectors = disk_geom.dkg_nsect;
596 		}
597 
598 		errno = 0;
599 		if (ioctl(Dev, DKIOCG_PHYGEOM, &disk_geom)) {
600 			if (errno == ENOTTY) {
601 				no_physgeom_ioctl = 1;
602 			} else {
603 				(void) fprintf(stderr,
604 				    "%s: Cannot get physical disk geometry.\n",
605 				    argv[optind]);
606 				exit(1);
607 			}
608 
609 		}
610 		/*
611 		 * Call DKIOCGGEOM if the ioctls for physical and virtual
612 		 * geometry fail. Get both from this generic call.
613 		 */
614 		if (no_virtgeom_ioctl && no_physgeom_ioctl) {
615 			errno = 0;
616 			if (ioctl(Dev, DKIOCGGEOM, &disk_geom)) {
617 				(void) fprintf(stderr,
618 				    "%s: Cannot get disk label geometry.\n",
619 				    argv[optind]);
620 				exit(1);
621 			}
622 		}
623 
624 		Numcyl = disk_geom.dkg_ncyl;
625 		heads = disk_geom.dkg_nhead;
626 		sectors = disk_geom.dkg_nsect;
627 		sectsiz = 512;
628 		acyl = disk_geom.dkg_acyl;
629 
630 		/*
631 		 * if hba geometry was not set by DKIOC_VIRTGEOM
632 		 * or we got an invalid hba geometry
633 		 * then set hba geometry based on max values
634 		 */
635 		if (no_virtgeom_ioctl ||
636 		    disk_geom.dkg_ncyl == 0 ||
637 		    disk_geom.dkg_nhead == 0 ||
638 		    disk_geom.dkg_nsect == 0 ||
639 		    disk_geom.dkg_ncyl > MAX_CYL ||
640 		    disk_geom.dkg_nhead > MAX_HEAD ||
641 		    disk_geom.dkg_nsect > MAX_SECT) {
642 
643 			/*
644 			 * turn off flag to print out virtual geometry (-v)
645 			 */
646 			v_flag = 0;
647 			hba_sectors	= MAX_SECT;
648 			hba_heads	= MAX_HEAD + 1;
649 			hba_Numcyl	= (Numcyl * heads * sectors) /
650 			    (hba_sectors * hba_heads);
651 		}
652 
653 		if (io_debug) {
654 			(void) fprintf(stderr, "Physical Geometry:\n");
655 			(void) fprintf(stderr,
656 			    "  cylinders[%d] heads[%d] sectors[%d]\n"
657 			    "  sector size[%d] blocks[%d] mbytes[%d]\n",
658 			    Numcyl,
659 			    heads,
660 			    sectors,
661 			    sectsiz,
662 			    Numcyl * heads * sectors,
663 			    (Numcyl * heads * sectors * sectsiz) / 1048576);
664 			(void) fprintf(stderr, "Virtual (HBA) Geometry:\n");
665 			(void) fprintf(stderr,
666 			    "  cylinders[%d] heads[%d] sectors[%d]\n"
667 			    "  sector size[%d] blocks[%d] mbytes[%d]\n",
668 			    hba_Numcyl,
669 			    hba_heads,
670 			    hba_sectors,
671 			    sectsiz,
672 			    hba_Numcyl * hba_heads * hba_sectors,
673 			    (hba_Numcyl * hba_heads * hba_sectors * sectsiz) /
674 			    1048576);
675 		}
676 	}
677 
678 	/* If user has requested a geometry report just do it and exit */
679 	if (io_lgeom) {
680 		if (ioctl(Dev, DKIOCGGEOM, &disk_geom)) {
681 			(void) fprintf(stderr,
682 			    "%s: Cannot get disk label geometry.\n",
683 			    argv[optind]);
684 			exit(1);
685 		}
686 		Numcyl = disk_geom.dkg_ncyl;
687 		heads = disk_geom.dkg_nhead;
688 		sectors = disk_geom.dkg_nsect;
689 		sectsiz = 512;
690 		acyl = disk_geom.dkg_acyl;
691 		(void) printf("* Label geometry for device %s\n", Dfltdev);
692 		(void) printf(
693 		    "* PCYL     NCYL     ACYL     BCYL     NHEAD NSECT"
694 		    " SECSIZ\n");
695 		(void) printf("  %-8d %-8d %-8d %-8d %-5d %-5d %-6d\n",
696 		    Numcyl,
697 		    disk_geom.dkg_ncyl,
698 		    disk_geom.dkg_acyl,
699 		    disk_geom.dkg_bcyl,
700 		    heads,
701 		    sectors,
702 		    sectsiz);
703 		exit(0);
704 	} else if (io_pgeom) {
705 		if (ioctl(Dev, DKIOCG_PHYGEOM, &disk_geom)) {
706 			(void) fprintf(stderr,
707 			    "%s: Cannot get physical disk geometry.\n",
708 			    argv[optind]);
709 			exit(1);
710 		}
711 		(void) printf("* Physical geometry for device %s\n", Dfltdev);
712 		(void) printf(
713 		    "* PCYL     NCYL     ACYL     BCYL     NHEAD NSECT"
714 		    " SECSIZ\n");
715 		(void) printf("  %-8d %-8d %-8d %-8d %-5d %-5d %-6d\n",
716 		    disk_geom.dkg_pcyl,
717 		    disk_geom.dkg_ncyl,
718 		    disk_geom.dkg_acyl,
719 		    disk_geom.dkg_bcyl,
720 		    disk_geom.dkg_nhead,
721 		    disk_geom.dkg_nsect,
722 		    sectsiz);
723 		exit(0);
724 	} else if (io_sgeom) {
725 		if (read_geom(io_sgeom)) {
726 			exit(1);
727 		} else if (!io_image) {
728 			exit(0);
729 		}
730 	}
731 
732 	/*
733 	 * some drivers may not support DKIOCGMEDIAINFO
734 	 * in that case use CHS
735 	 */
736 	chs_capacity = (diskaddr_t)Numcyl * heads * sectors;
737 	dev_capacity = chs_capacity;
738 	Numcyl_usable = Numcyl;
739 
740 	if (chs_capacity > DK_MAX_2TB) {
741 		/* limit to 2TB */
742 		Numcyl_usable = DK_MAX_2TB / (heads * sectors);
743 		chs_capacity = (diskaddr_t)Numcyl_usable * heads * sectors;
744 	}
745 
746 	if (minfo.dki_capacity > 0)
747 		dev_capacity = minfo.dki_capacity;
748 
749 	/* Allocate memory to hold three complete sectors */
750 	Bootsect = (char *)malloc(3 * sectsiz);
751 	if (Bootsect == NULL) {
752 		(void) fprintf(stderr,
753 		    "fdisk: Unable to obtain enough buffer memory"
754 		    " (%d bytes).\n",
755 		    3 * sectsiz);
756 		exit(1);
757 	}
758 
759 	Nullsect = Bootsect + sectsiz;
760 	/* Zero out the "NULL" sector */
761 	for (i = 0; i < sectsiz; i++) {
762 		Nullsect[i] = 0;
763 	}
764 
765 	/* Find out what the user wants done */
766 	if (io_rd) {		/* abs disk read */
767 		abs_read();	/* will not return */
768 	} else if (io_wrt && !io_readonly) {
769 		abs_write();	/* will not return */
770 	} else if (io_patt && !io_readonly) {
771 		fill_patt();	/* will not return */
772 	}
773 
774 
775 	/* This is the fdisk edit, the real reason for the program.	*/
776 
777 	sanity_check_provided_device(Dfltdev, Dev);
778 
779 	/* Get the new BOOT program in case we write a new fdisk table */
780 	mboot_read();
781 
782 	/* Read from disk master boot */
783 	dev_mboot_read();
784 
785 	/*
786 	 * Verify and copy the device's fdisk table. This will be used
787 	 * as the prototype mboot if the device's mboot looks invalid.
788 	 */
789 	Bootblk = (struct mboot *)Bootsect;
790 	copy_Bootblk_to_Table();
791 
792 	/* save away a copy of Table in Old_Table for sensing changes */
793 	copy_Table_to_Old_Table();
794 
795 	/* Load fdisk table from specified file (-F fdisk_file) */
796 	if (io_ffdisk) {
797 		/* Load and verify user-specified table parameters */
798 		load(LOADFILE, io_ffdisk);
799 	}
800 
801 	/* Does user want to delete or add an entry? */
802 	if (io_Dfdisk) {
803 		load(LOADDEL, io_Dfdisk);
804 	}
805 	if (io_Afdisk) {
806 		load(LOADADD, io_Afdisk);
807 	}
808 
809 	if (!io_ffdisk && !io_Afdisk && !io_Dfdisk) {
810 		/* Check if there is no fdisk table */
811 		if (Table[0].systid == UNUSED || io_wholedisk || io_EFIdisk) {
812 			if (io_ifdisk && !io_wholedisk && !io_EFIdisk) {
813 				(void) printf(
814 				    "No fdisk table exists. The default"
815 				    " partition for the disk is:\n\n"
816 				    "  a 100%% \"SOLARIS System\" "
817 				    "partition\n\n"
818 				    "Type \"y\" to accept the default "
819 				    "partition,  otherwise type \"n\" to "
820 				    "edit the\n partition table.\n");
821 
822 				if (Numcyl > Numcyl_usable)
823 					(void) printf("WARNING: Disk is larger"
824 					    " than 2TB. Solaris partition will"
825 					    " be limited to 2 TB.\n");
826 			}
827 
828 			/* Edit the partition table as directed */
829 			if (io_wholedisk ||(io_ifdisk && yesno())) {
830 
831 				/* Default scenario */
832 				nulltbl();
833 				/* now set up UNIX System partition */
834 				Table[0].bootid = ACTIVE;
835 				Table[0].relsect = lel(heads * sectors);
836 
837 				Table[0].numsect =
838 				    lel((ulong_t)((Numcyl_usable - 1) *
839 				    heads * sectors));
840 
841 				Table[0].systid = SUNIXOS2;   /* Solaris */
842 
843 				/* calculate CHS values for table entry 0 */
844 				Set_Table_CHS_Values(0);
845 				update_disk_and_exit(B_TRUE);
846 			} else if (io_EFIdisk) {
847 				/* create an EFI partition for the whole disk */
848 				nulltbl();
849 				i = insert_tbl(EFI_PMBR, 0, 0, 0, 0, 0, 0, 0, 1,
850 				    (dev_capacity > DK_MAX_2TB) ? DK_MAX_2TB :
851 				    (dev_capacity - 1));
852 				if (i != 0) {
853 					(void) fprintf(stderr,
854 					    "Error creating EFI partition\n");
855 					exit(1);
856 				}
857 				update_disk_and_exit(B_TRUE);
858 			}
859 		}
860 	}
861 
862 	/* Display complete fdisk table entries for debugging purposes */
863 	if (io_debug) {
864 		(void) fprintf(stderr, "Partition Table Entry Values:\n");
865 		print_Table();
866 		if (io_ifdisk) {
867 			(void) fprintf(stderr, "\n");
868 			(void) fprintf(stderr, "Press Enter to continue.\n");
869 			(void) gets(s);
870 		}
871 	}
872 
873 	/* Interactive fdisk mode */
874 	if (io_ifdisk) {
875 		(void) printf(CLR_SCR);
876 		disptbl();
877 		for (;;) {
878 			stage0();
879 			copy_Bootblk_to_Table();
880 			disptbl();
881 		}
882 	}
883 
884 	/* If user wants to write the table to a file, do it */
885 	if (io_Wfdisk)
886 		ffile_write(io_Wfdisk);
887 	else if (stdo_flag)
888 		ffile_write((char *)stdout);
889 
890 	update_disk_and_exit(TableChanged() == 1);
891 	return (0);
892 }
893 
894 /*
895  * read_geom
896  * Read geometry from specified file (-S).
897  */
898 
899 static int
900 read_geom(char *sgeom)
901 {
902 	char	line[256];
903 	FILE *fp;
904 
905 	/* open the prototype file */
906 	if ((fp = fopen(sgeom, "r")) == NULL) {
907 		(void) fprintf(stderr, "fdisk: Cannot open file %s.\n",
908 		    io_sgeom);
909 		return (1);
910 	}
911 
912 	/* Read a line from the file */
913 	while (fgets(line, sizeof (line) - 1, fp)) {
914 		if (line[0] == '\0' || line[0] == '\n' || line[0] == '*')
915 			continue;
916 		else {
917 			line[strlen(line)] = '\0';
918 			if (sscanf(line, "%hu %hu %hu %hu %hu %hu %d",
919 			    &disk_geom.dkg_pcyl,
920 			    &disk_geom.dkg_ncyl,
921 			    &disk_geom.dkg_acyl,
922 			    &disk_geom.dkg_bcyl,
923 			    &disk_geom.dkg_nhead,
924 			    &disk_geom.dkg_nsect,
925 			    &sectsiz) != 7) {
926 				(void) fprintf(stderr,
927 				    "Syntax error:\n	\"%s\".\n",
928 				    line);
929 				return (1);
930 			}
931 			break;
932 		} /* else */
933 	} /* while (fgets(line, sizeof (line) - 1, fp)) */
934 
935 	if (!io_image) {
936 		if (ioctl(Dev, DKIOCSGEOM, &disk_geom)) {
937 			(void) fprintf(stderr,
938 			    "fdisk: Cannot set label geometry.\n");
939 			return (1);
940 		}
941 	} else {
942 		Numcyl = hba_Numcyl = disk_geom.dkg_ncyl;
943 		heads = hba_heads = disk_geom.dkg_nhead;
944 		sectors = hba_sectors = disk_geom.dkg_nsect;
945 		acyl = disk_geom.dkg_acyl;
946 	}
947 
948 	(void) fclose(fp);
949 	return (0);
950 }
951 
952 /*
953  * dev_mboot_read
954  * Read the master boot sector from the device.
955  */
956 static void
957 dev_mboot_read(void)
958 {
959 	if ((ioctl(Dev, DKIOCGMBOOT, Bootsect) < 0) && (errno != ENOTTY)) {
960 		perror("Error in ioctl DKIOCGMBOOT");
961 	}
962 	if (errno == 0)
963 		return;
964 	if (lseek(Dev, 0, SEEK_SET) == -1) {
965 		(void) fprintf(stderr,
966 		    "fdisk: Error seeking to partition table on %s.\n",
967 		    Dfltdev);
968 		if (!io_image)
969 			exit(1);
970 	}
971 	if (read(Dev, Bootsect, sectsiz) != sectsiz) {
972 		(void) fprintf(stderr,
973 		    "fdisk: Error reading partition table from %s.\n",
974 		    Dfltdev);
975 		if (!io_image)
976 			exit(1);
977 	}
978 }
979 
980 /*
981  * dev_mboot_write
982  * Write the master boot sector to the device.
983  */
984 static void
985 dev_mboot_write(off_t sect, char *buff, int bootsiz)
986 {
987 	int 	new_pt, old_pt, error;
988 	int	clr_efi = -1;
989 
990 	if (io_readonly)
991 		return;
992 
993 	if (io_debug) {
994 		(void) fprintf(stderr, "About to write fdisk table:\n");
995 		print_Table();
996 		if (io_ifdisk) {
997 			(void) fprintf(stderr, "Press Enter to continue.\n");
998 			(void) gets(s);
999 		}
1000 	}
1001 
1002 	/*
1003 	 * If the new table has any Solaris partitions and the old
1004 	 * table does not have an entry that describes it
1005 	 * exactly then clear the old vtoc (if any).
1006 	 */
1007 	for (new_pt = 0; new_pt < FD_NUMPART; new_pt++) {
1008 
1009 		/* We only care about potential Solaris parts. */
1010 		if (Table[new_pt].systid != SUNIXOS &&
1011 		    Table[new_pt].systid != SUNIXOS2)
1012 			continue;
1013 
1014 		/* Does the old table have an exact entry for the new entry? */
1015 		for (old_pt = 0; old_pt < FD_NUMPART; old_pt++) {
1016 
1017 			/* We only care about old Solaris partitions. */
1018 			if ((Old_Table[old_pt].systid == SUNIXOS) ||
1019 			    (Old_Table[old_pt].systid == SUNIXOS2)) {
1020 
1021 				/* Is this old one the same as a new one? */
1022 				if ((Old_Table[old_pt].relsect ==
1023 				    Table[new_pt].relsect) &&
1024 				    (Old_Table[old_pt].numsect ==
1025 				    Table[new_pt].numsect))
1026 					break; /* Yes */
1027 			}
1028 		}
1029 
1030 		/* Did a solaris partition change location or size? */
1031 		if (old_pt >= FD_NUMPART) {
1032 			/* Yes clear old vtoc */
1033 			if (io_debug) {
1034 				(void) fprintf(stderr,
1035 				    "Clearing VTOC labels from NEW"
1036 				    " table\n");
1037 			}
1038 			clear_vtoc(NEW, new_pt);
1039 		}
1040 	}
1041 
1042 
1043 	/* see if the old table had EFI */
1044 	for (old_pt = 0; old_pt < FD_NUMPART; old_pt++) {
1045 		if (Old_Table[old_pt].systid == EFI_PMBR) {
1046 			clr_efi = old_pt;
1047 		}
1048 	}
1049 
1050 	/* look to see if a EFI partition changed in relsect/numsect */
1051 	for (new_pt = 0; new_pt < FD_NUMPART; new_pt++) {
1052 		if (Table[new_pt].systid != EFI_PMBR)
1053 			continue;
1054 		for (old_pt = 0; old_pt < FD_NUMPART; old_pt++) {
1055 			if ((Old_Table[old_pt].systid ==
1056 			    Table[new_pt].systid) &&
1057 			    (Old_Table[old_pt].relsect ==
1058 			    Table[new_pt].relsect) &&
1059 			    (Old_Table[old_pt].numsect ==
1060 			    Table[new_pt].numsect))
1061 				break;
1062 		}
1063 
1064 		/*
1065 		 * if EFI partition changed, set the flag to clear
1066 		 * the EFI GPT
1067 		 */
1068 		if (old_pt == FD_NUMPART && Table[new_pt].begcyl != 0) {
1069 			clr_efi = 0;
1070 		}
1071 		break;
1072 	}
1073 
1074 	/* clear labels if necessary */
1075 	if (clr_efi >= 0) {
1076 		if (io_debug) {
1077 			(void) fprintf(stderr, "Clearing EFI labels\n");
1078 		}
1079 		if ((error = clear_efi()) != 0) {
1080 			if (io_debug) {
1081 				(void) fprintf(stderr,
1082 				    "\tError %d clearing EFI labels"
1083 				    " (probably no EFI labels exist)\n",
1084 				    error);
1085 			}
1086 		}
1087 	}
1088 
1089 	if ((ioctl(Dev, DKIOCSMBOOT, buff) == -1) && (errno != ENOTTY)) {
1090 		(void) fprintf(stderr,
1091 		    "fdisk: Error in ioctl DKIOCSMBOOT on %s.\n",
1092 		    Dfltdev);
1093 	}
1094 	if (errno == 0)
1095 		return;
1096 
1097 	/* write to disk drive */
1098 	if (lseek(Dev, sect, SEEK_SET) == -1) {
1099 		(void) fprintf(stderr,
1100 		    "fdisk: Error seeking to master boot record on %s.\n",
1101 		    Dfltdev);
1102 		exit(1);
1103 	}
1104 	if (write(Dev, buff, bootsiz) != bootsiz) {
1105 		(void) fprintf(stderr,
1106 		    "fdisk: Error writing master boot record to %s.\n",
1107 		    Dfltdev);
1108 		exit(1);
1109 	}
1110 }
1111 
1112 /*
1113  * mboot_read
1114  * Read the prototype boot records from the files.
1115  */
1116 static void
1117 mboot_read(void)
1118 {
1119 	int mDev, i;
1120 	struct ipart *part;
1121 
1122 #if defined(i386) || defined(sparc)
1123 	/*
1124 	 * If the master boot file hasn't been specified, use the
1125 	 * implementation architecture name to generate the default one.
1126 	 */
1127 	if (io_mboot == (char *)0) {
1128 		/*
1129 		 * Bug ID 1249035:
1130 		 *	The mboot file must be delivered on all platforms
1131 		 *	and installed in a non-platform-dependent
1132 		 *	directory; i.e., /usr/lib/fs/ufs.
1133 		 */
1134 		io_mboot = "/usr/lib/fs/ufs/mboot";
1135 	}
1136 
1137 	/* First read in the master boot record */
1138 
1139 	/* Open the master boot proto file */
1140 	if ((mDev = open(io_mboot, O_RDONLY, 0666)) == -1) {
1141 		(void) fprintf(stderr,
1142 		    "fdisk: Cannot open master boot file %s.\n",
1143 		    io_mboot);
1144 		exit(1);
1145 	}
1146 
1147 	/* Read the master boot program */
1148 	if (read(mDev, &BootCod, sizeof (struct mboot)) != sizeof
1149 	    (struct mboot)) {
1150 		(void) fprintf(stderr,
1151 		    "fdisk: Cannot read master boot file %s.\n",
1152 		    io_mboot);
1153 		exit(1);
1154 	}
1155 
1156 	/* Is this really a master boot record? */
1157 	if (les(BootCod.signature) != MBB_MAGIC) {
1158 		(void) fprintf(stderr,
1159 		    "fdisk: Invalid master boot file %s.\n", io_mboot);
1160 		(void) fprintf(stderr,
1161 		    "Bad magic number: is %x, but should be %x.\n",
1162 		    les(BootCod.signature), MBB_MAGIC);
1163 		exit(1);
1164 	}
1165 
1166 	(void) close(mDev);
1167 #else
1168 #error	fdisk needs to be ported to new architecture
1169 #endif
1170 
1171 	/* Zero out the partitions part of this record */
1172 	part = (struct ipart *)BootCod.parts;
1173 	for (i = 0; i < FD_NUMPART; i++, part++) {
1174 		(void) memset(part, 0, sizeof (struct ipart));
1175 	}
1176 
1177 }
1178 
1179 /*
1180  * fill_patt
1181  * Fill the disk with user/sector number pattern.
1182  */
1183 static void
1184 fill_patt(void)
1185 {
1186 	int	*buff_ptr, i;
1187 	off_t	*off_ptr;
1188 	int	io_fpatt = 0;
1189 	int	io_ipatt = 0;
1190 
1191 	if (strncmp(io_fatt, "#", 1) != 0) {
1192 		io_fpatt++;
1193 		io_ipatt = strtoul(io_fatt, 0, 0);
1194 		buff_ptr = (int *)Bootsect;
1195 		for (i = 0; i < sectsiz; i += 4, buff_ptr++)
1196 			*buff_ptr = io_ipatt;
1197 	}
1198 
1199 	/*
1200 	 * Fill disk with pattern based on block number.
1201 	 * Write to the disk at absolute relative block io_offset
1202 	 * for io_size blocks.
1203 	 */
1204 	while (io_size--) {
1205 		off_ptr = (off_t *)Bootsect;
1206 		if (!io_fpatt) {
1207 			for (i = 0; i < sectsiz;
1208 			    i += sizeof (off_t), off_ptr++)
1209 				*off_ptr = io_offset;
1210 		}
1211 		/* Write the data to disk */
1212 		if (lseek(Dev, (off_t)(sectsiz * io_offset++),
1213 		    SEEK_SET) == -1) {
1214 			(void) fprintf(stderr, "fdisk: Error seeking on %s.\n",
1215 			    Dfltdev);
1216 			exit(1);
1217 		}
1218 		if (write(Dev, Bootsect, sectsiz) != sectsiz) {
1219 			(void) fprintf(stderr, "fdisk: Error writing %s.\n",
1220 			    Dfltdev);
1221 			exit(1);
1222 		}
1223 	} /* while (--io_size); */
1224 }
1225 
1226 /*
1227  * abs_read
1228  * Read from the disk at absolute relative block io_offset for
1229  * io_size blocks. Write the data to standard ouput (-r).
1230  */
1231 static void
1232 abs_read(void)
1233 {
1234 	int c;
1235 
1236 	while (io_size--) {
1237 		if (lseek(Dev, (off_t)(sectsiz * io_offset++),
1238 		    SEEK_SET) == -1) {
1239 			(void) fprintf(stderr, "fdisk: Error seeking on %s.\n",
1240 			    Dfltdev);
1241 			exit(1);
1242 		}
1243 		if (read(Dev, Bootsect, sectsiz) != sectsiz) {
1244 			(void) fprintf(stderr, "fdisk: Error reading %s.\n",
1245 			    Dfltdev);
1246 			exit(1);
1247 		}
1248 
1249 		/* Write to standard ouptut */
1250 		if ((c = write(1, Bootsect, (unsigned)sectsiz)) != sectsiz) {
1251 			if (c >= 0) {
1252 				if (io_debug)
1253 					(void) fprintf(stderr,
1254 					    "fdisk: Output warning: %d of %d"
1255 					    " characters written.\n",
1256 					    c, sectsiz);
1257 				exit(2);
1258 			} else {
1259 				perror("write error on output file.");
1260 				exit(2);
1261 			}
1262 		} /* if ((c = write(1, Bootsect, (unsigned)sectsiz)) */
1263 			/* != sectsiz) */
1264 	} /* while (--io_size); */
1265 	exit(0);
1266 }
1267 
1268 /*
1269  * abs_write
1270  * Read the data from standard input. Write to the disk at
1271  * absolute relative block io_offset for io_size blocks (-w).
1272  */
1273 static void
1274 abs_write(void)
1275 {
1276 	int c, i;
1277 
1278 	while (io_size--) {
1279 		int part_exit = 0;
1280 		/* Read from standard input */
1281 		if ((c = read(0, Bootsect, (unsigned)sectsiz)) != sectsiz) {
1282 			if (c >= 0) {
1283 				if (io_debug)
1284 				(void) fprintf(stderr,
1285 				    "fdisk: WARNING: Incomplete read (%d of"
1286 				    " %d characters read) on input file.\n",
1287 				    c, sectsiz);
1288 				/* Fill pattern to mark partial sector in buf */
1289 				for (i = c; i < sectsiz; ) {
1290 					Bootsect[i++] = 0x41;
1291 					Bootsect[i++] = 0x62;
1292 					Bootsect[i++] = 0x65;
1293 					Bootsect[i++] = 0;
1294 				}
1295 				part_exit++;
1296 			} else {
1297 				perror("read error on input file.");
1298 				exit(2);
1299 			}
1300 
1301 		}
1302 		/* Write to disk drive */
1303 		if (lseek(Dev, (off_t)(sectsiz * io_offset++),
1304 		    SEEK_SET) == -1) {
1305 			(void) fprintf(stderr, "fdisk: Error seeking on %s.\n",
1306 			    Dfltdev);
1307 			exit(1);
1308 		}
1309 		if (write(Dev, Bootsect, sectsiz) != sectsiz) {
1310 			(void) fprintf(stderr, "fdisk: Error writing %s.\n",
1311 			    Dfltdev);
1312 			exit(1);
1313 		}
1314 		if (part_exit)
1315 		exit(0);
1316 	} /* while (--io_size); */
1317 	exit(1);
1318 }
1319 
1320 
1321 /*
1322  * load
1323  * Load will either read the fdisk table from a file or add or
1324  * delete an entry (-A, -D, -F).
1325  */
1326 
1327 static void
1328 load(int funct, char *file)
1329 {
1330 	int	id;
1331 	int	act;
1332 	int	bhead;
1333 	int	bsect;
1334 	int	bcyl;
1335 	int	ehead;
1336 	int	esect;
1337 	int	ecyl;
1338 	uint32_t	rsect;
1339 	uint32_t	numsect;
1340 	char	line[256];
1341 	int	i = 0;
1342 	int	j;
1343 	FILE *fp;
1344 
1345 	switch (funct) {
1346 
1347 	case LOADFILE:
1348 
1349 		/*
1350 		 * Zero out the table before loading it, which will
1351 		 * force it to be updated on disk later (-F
1352 		 * fdisk_file).
1353 		 */
1354 		nulltbl();
1355 
1356 		/* Open the prototype file */
1357 		if ((fp = fopen(file, "r")) == NULL) {
1358 			(void) fprintf(stderr,
1359 			    "fdisk: Cannot open prototype partition file %s.\n",
1360 			    file);
1361 			exit(1);
1362 		}
1363 
1364 		/* Read a line from the file */
1365 		while (fgets(line, sizeof (line) - 1, fp)) {
1366 			if (pars_fdisk(line, &id, &act, &bhead, &bsect,
1367 			    &bcyl, &ehead, &esect, &ecyl, &rsect, &numsect)) {
1368 				continue;
1369 			}
1370 
1371 			/*
1372 			 * Validate the partition. It cannot start at sector
1373 			 * 0 unless it is UNUSED or already exists
1374 			 */
1375 			if (validate_part(id, rsect, numsect) < 0) {
1376 				(void) fprintf(stderr,
1377 				    "fdisk: Error on entry \"%s\".\n",
1378 				    line);
1379 				exit(1);
1380 			}
1381 			/*
1382 			 * Find an unused entry to use and put the entry
1383 			 * in table
1384 			 */
1385 			if (insert_tbl(id, act, bhead, bsect, bcyl, ehead,
1386 			    esect, ecyl, rsect, numsect) < 0) {
1387 				(void) fprintf(stderr,
1388 				    "fdisk: Error on entry \"%s\".\n",
1389 				    line);
1390 				exit(1);
1391 			}
1392 		} /* while (fgets(line, sizeof (line) - 1, fp)) */
1393 
1394 		if (verify_tbl() < 0) {
1395 			(void) fprintf(stderr,
1396 			    "fdisk: Cannot create partition table\n");
1397 			exit(1);
1398 		}
1399 
1400 		(void) fclose(fp);
1401 		return;
1402 
1403 	case LOADDEL:
1404 
1405 		/* Parse the user-supplied deletion line (-D) */
1406 		if (pars_fdisk(file, &id, &act, &bhead, &bsect, &bcyl,
1407 		    &ehead, &esect, &ecyl, &rsect, &numsect)) {
1408 			(void) fprintf(stderr,
1409 			    "fdisk: Syntax error \"%s\"\n", file);
1410 			exit(1);
1411 		}
1412 
1413 		/* Find the exact entry in the table */
1414 		for (i = 0; i < FD_NUMPART; i++) {
1415 			if (Table[i].systid == id &&
1416 			    Table[i].bootid == act &&
1417 			    Table[i].beghead == bhead &&
1418 			    Table[i].begsect == ((bsect & 0x3f) |
1419 			    (uchar_t)((bcyl>>2) & 0xc0)) &&
1420 			    Table[i].begcyl == (uchar_t)(bcyl & 0xff) &&
1421 			    Table[i].endhead == ehead &&
1422 			    Table[i].endsect == ((esect & 0x3f) |
1423 			    (uchar_t)((ecyl>>2) & 0xc0)) &&
1424 			    Table[i].endcyl == (uchar_t)(ecyl & 0xff) &&
1425 			    Table[i].relsect == lel(rsect) &&
1426 			    Table[i].numsect == lel(numsect)) {
1427 
1428 				/*
1429 				 * Found the entry. Now move rest of
1430 				 * entries up toward the top of the
1431 				 * table, leaving available entries at
1432 				 * the end of the fdisk table.
1433 				 */
1434 				for (j = i; j < FD_NUMPART - 1; j++) {
1435 					Table[j].systid = Table[j + 1].systid;
1436 					Table[j].bootid = Table[j + 1].bootid;
1437 					Table[j].beghead = Table[j + 1].beghead;
1438 					Table[j].begsect = Table[j + 1].begsect;
1439 					Table[j].begcyl = Table[j + 1].begcyl;
1440 					Table[j].endhead = Table[j + 1].endhead;
1441 					Table[j].endsect = Table[j + 1].endsect;
1442 					Table[j].endcyl = Table[j + 1].endcyl;
1443 					Table[j].relsect = Table[j + 1].relsect;
1444 					Table[j].numsect = Table[j + 1].numsect;
1445 				}
1446 
1447 				/*
1448 				 * Mark the last entry as unused in case
1449 				 * all table entries were in use prior
1450 				 * to the deletion.
1451 				 */
1452 
1453 				Table[FD_NUMPART - 1].systid = UNUSED;
1454 				Table[FD_NUMPART - 1].bootid = 0;
1455 				return;
1456 			}
1457 		}
1458 		(void) fprintf(stderr,
1459 		    "fdisk: Entry does not match any existing partition:\n"
1460 		    "	\"%s\"\n",
1461 		    file);
1462 		exit(1);
1463 		/* FALLTHRU */
1464 
1465 	case LOADADD:
1466 
1467 		/* Parse the user-supplied addition line (-A) */
1468 		if (pars_fdisk(file, &id, &act, &bhead, &bsect, &bcyl, &ehead,
1469 		    &esect, &ecyl, &rsect, &numsect)) {
1470 			(void) fprintf(stderr,
1471 			    "fdisk: Syntax error \"%s\"\n", file);
1472 			exit(1);
1473 		}
1474 
1475 		/* Validate the partition. It cannot start at sector 0 */
1476 		if (rsect == 0) {
1477 			(void) fprintf(stderr,
1478 			    "fdisk: New partition cannot start at sector 0:\n"
1479 			    "   \"%s\".\n",
1480 			    file);
1481 			exit(1);
1482 		}
1483 
1484 		/*
1485 		 * if the user wishes to add an EFI partition, we need
1486 		 * more extensive validation.  rsect should be 1, and
1487 		 * numsect should equal the entire disk capacity - 1
1488 		 */
1489 
1490 		if (id == EFI_PMBR) {
1491 			if (rsect != 1) {
1492 				(void) fprintf(stderr,
1493 				    "fdisk: EFI partitions must start at sector"
1494 				    " 1 (input rsect = %d)\n", rsect);
1495 				exit(1);
1496 			}
1497 
1498 
1499 			if (dev_capacity > DK_MAX_2TB) {
1500 				if (numsect != DK_MAX_2TB) {
1501 					(void) fprintf(stderr,
1502 					    "fdisk: EFI partitions must "
1503 					    "encompass the entire maximum 2 TB "
1504 					    "(input numsect: %u - max: %llu)\n",
1505 					    numsect, (diskaddr_t)DK_MAX_2TB);
1506 				exit(1);
1507 				}
1508 			} else if (numsect != dev_capacity - 1) {
1509 				(void) fprintf(stderr,
1510 				    "fdisk: EFI partitions must encompass the "
1511 				    "entire disk\n"
1512 				    "(input numsect: %u - avail: %llu)\n",
1513 				    numsect,
1514 				    dev_capacity - 1);
1515 				exit(1);
1516 			}
1517 		}
1518 
1519 		/* Find unused entry for use and put entry in table */
1520 		if (insert_tbl(id, act, bhead, bsect, bcyl, ehead, esect,
1521 		    ecyl, rsect, numsect) < 0) {
1522 			(void) fprintf(stderr,
1523 			    "fdisk: Invalid entry could not be inserted:\n"
1524 			    "	\"%s\"\n",
1525 			    file);
1526 			exit(1);
1527 		}
1528 
1529 		/* Make sure new entry does not overlap existing entry */
1530 		if (verify_tbl() < 0) {
1531 			(void) fprintf(stderr,
1532 			    "fdisk: Cannot create partition \"%s\"\n", file);
1533 			exit(1);
1534 		}
1535 	} /* switch funct */
1536 }
1537 
1538 /*
1539  * Set_Table_CHS_Values
1540  *
1541  * This will calculate the CHS values for beginning and ending CHS
1542  * for a single partition table entry (ti) based on the relsect
1543  * and numsect values contained in the partion table entry.
1544  *
1545  * hba_heads and hba_sectors contain the number of heads and sectors.
1546  *
1547  * If the number of cylinders exceeds the MAX_CYL,
1548  * then maximum values will be placed in the corresponding chs entry.
1549  */
1550 static void
1551 Set_Table_CHS_Values(int ti)
1552 {
1553 	uint32_t	lba, cy, hd, sc;
1554 
1555 	lba = (uint32_t)Table[ti].relsect;
1556 	if (lba >= hba_heads * hba_sectors * MAX_CYL) {
1557 		/*
1558 		 * the lba address cannot be expressed in CHS value
1559 		 * so store the maximum CHS field values in the CHS fields.
1560 		 */
1561 		cy = MAX_CYL + 1;
1562 		hd = MAX_HEAD;
1563 		sc = MAX_SECT;
1564 	} else {
1565 		cy = lba / hba_sectors / hba_heads;
1566 		hd = lba / hba_sectors % hba_heads;
1567 		sc = lba % hba_sectors + 1;
1568 	}
1569 	Table[ti].begcyl = cy & 0xff;
1570 	Table[ti].beghead = (uchar_t)hd;
1571 	Table[ti].begsect = (uchar_t)(((cy >> 2) & 0xc0) | sc);
1572 
1573 	/*
1574 	 * This code is identical to the code above
1575 	 * except that it works on ending CHS values
1576 	 */
1577 	lba = (uint32_t)(Table[ti].relsect + Table[ti].numsect - 1);
1578 	if (lba >= hba_heads * hba_sectors * MAX_CYL) {
1579 		cy = MAX_CYL + 1;
1580 		hd = MAX_HEAD;
1581 		sc = MAX_SECT;
1582 	} else {
1583 		cy = lba / hba_sectors / hba_heads;
1584 		hd = lba / hba_sectors % hba_heads;
1585 		sc = lba % hba_sectors + 1;
1586 	}
1587 	Table[ti].endcyl = cy & 0xff;
1588 	Table[ti].endhead = (uchar_t)hd;
1589 	Table[ti].endsect = (uchar_t)(((cy >> 2) & 0xc0) | sc);
1590 }
1591 
1592 /*
1593  * insert_tbl
1594  * 	Insert entry into fdisk table. Check all user-supplied values
1595  *	for the entry, but not the validity relative to other table
1596  *	entries!
1597  */
1598 static int
1599 insert_tbl(
1600     int id, int act,
1601     int bhead, int bsect, int bcyl,
1602     int ehead, int esect, int ecyl,
1603     uint32_t rsect, uint32_t numsect)
1604 {
1605 	int	i;
1606 
1607 	/* validate partition size */
1608 	if (((diskaddr_t)rsect + numsect) > dev_capacity) {
1609 		(void) fprintf(stderr,
1610 		    "fdisk: Partition table exceeds the size of the disk.\n");
1611 		return (-1);
1612 	}
1613 
1614 
1615 	/* find UNUSED partition table entry */
1616 	for (i = 0; i < FD_NUMPART; i++) {
1617 		if (Table[i].systid == UNUSED) {
1618 			break;
1619 		}
1620 	}
1621 	if (i >= FD_NUMPART) {
1622 		(void) fprintf(stderr, "fdisk: Partition table is full.\n");
1623 		return (-1);
1624 	}
1625 
1626 
1627 	Table[i].systid = (uchar_t)id;
1628 	Table[i].bootid = (uchar_t)act;
1629 	Table[i].numsect = lel(numsect);
1630 	Table[i].relsect = lel(rsect);
1631 
1632 	/*
1633 	 * If we have been called with a valid geometry, use it
1634 	 * valid means non-zero values that fit in the BIOS fields
1635 	 */
1636 	if (0 < bsect && bsect <= MAX_SECT &&
1637 	    0 <= bhead && bhead <= MAX_HEAD &&
1638 	    0 < esect && esect <= MAX_SECT &&
1639 	    0 <= ehead && ehead <= MAX_HEAD) {
1640 		if (bcyl > MAX_CYL)
1641 			bcyl = MAX_CYL + 1;
1642 		if (ecyl > MAX_CYL)
1643 			ecyl = MAX_CYL + 1;
1644 		Table[i].begcyl = bcyl & 0xff;
1645 		Table[i].endcyl = ecyl & 0xff;
1646 		Table[i].beghead = (uchar_t)bhead;
1647 		Table[i].endhead = (uchar_t)ehead;
1648 		Table[i].begsect = (uchar_t)(((bcyl >> 2) & 0xc0) | bsect);
1649 		Table[i].endsect = ((ecyl >> 2) & 0xc0) | esect;
1650 	} else {
1651 
1652 		/*
1653 		 * The specified values are invalid,
1654 		 * so calculate the values based on hba_heads, hba_sectors
1655 		 */
1656 		Set_Table_CHS_Values(i);
1657 	}
1658 
1659 	/*
1660 	 * return partition index
1661 	 */
1662 	return (i);
1663 }
1664 
1665 /*
1666  * verify_tbl
1667  * Verify that no partition entries overlap or exceed the size of
1668  * the disk.
1669  */
1670 static int
1671 verify_tbl(void)
1672 {
1673 	uint32_t	i, j, rsect, numsect;
1674 	int	noMoreParts = 0;
1675 	int	numParts = 0;
1676 
1677 	/* Make sure new entry does not overlap an existing entry */
1678 	for (i = 0; i < FD_NUMPART - 1; i++) {
1679 		if (Table[i].systid != UNUSED) {
1680 			numParts++;
1681 			/*
1682 			 * No valid partitions allowed after an UNUSED  or
1683 			 * EFI_PMBR part
1684 			 */
1685 			if (noMoreParts) {
1686 				return (-1);
1687 			}
1688 
1689 			/*
1690 			 * EFI_PMBR partitions must be the only partition
1691 			 * and must be Table entry 0
1692 			 */
1693 			if (Table[i].systid == EFI_PMBR) {
1694 				if (i == 0) {
1695 					noMoreParts = 1;
1696 				} else {
1697 					return (-1);
1698 				}
1699 
1700 				if (Table[i].relsect != 1) {
1701 					(void) fprintf(stderr, "ERROR: "
1702 					    "Invalid starting sector "
1703 					    "for EFI_PMBR partition:\n"
1704 					    "relsect %d "
1705 					    "(should be 1)\n",
1706 					    Table[i].relsect);
1707 
1708 					return (-1);
1709 				}
1710 
1711 				if (Table[i].numsect != dev_capacity - 1) {
1712 					(void) fprintf(stderr, "ERROR: "
1713 					    "EFI_PMBR partition must "
1714 					    "encompass the entire "
1715 					    "disk.\n numsect %d - "
1716 					    "actual %llu\n",
1717 					    Table[i].numsect,
1718 					    dev_capacity - 1);
1719 
1720 					return (-1);
1721 				}
1722 			}
1723 
1724 			/* make sure the partition isn't larger than the disk */
1725 			rsect = lel(Table[i].relsect);
1726 			numsect = lel(Table[i].numsect);
1727 
1728 			if ((((diskaddr_t)rsect + numsect) > dev_capacity) ||
1729 			    (((diskaddr_t)rsect + numsect) > DK_MAX_2TB)) {
1730 				return (-1);
1731 			}
1732 
1733 			for (j = i + 1; j < FD_NUMPART; j++) {
1734 				if (Table[j].systid != UNUSED) {
1735 					uint32_t t_relsect =
1736 					    lel(Table[j].relsect);
1737 					uint32_t t_numsect =
1738 					    lel(Table[j].numsect);
1739 
1740 					if (noMoreParts) {
1741 						(void) fprintf(stderr,
1742 						    "Cannot add partition to "
1743 						    "table; no more partitions "
1744 						    "allowed\n");
1745 
1746 						if (io_debug) {
1747 							(void) fprintf(stderr,
1748 							    "DEBUG: Current "
1749 							    "partition:\t"
1750 							    "%d:%d:%d:%d:%d:"
1751 							    "%d:%d:%d:%d:%d\n"
1752 							    "       Next "
1753 							    "partition:\t\t"
1754 							    "%d:%d:%d:%d:%d:"
1755 							    "%d:%d:%d:%d:%d\n",
1756 							    Table[i].systid,
1757 							    Table[i].bootid,
1758 							    Table[i].begcyl,
1759 							    Table[i].beghead,
1760 							    Table[i].begsect,
1761 							    Table[i].endcyl,
1762 							    Table[i].endhead,
1763 							    Table[i].endsect,
1764 							    Table[i].relsect,
1765 							    Table[i].numsect,
1766 							    Table[j].systid,
1767 							    Table[j].bootid,
1768 							    Table[j].begcyl,
1769 							    Table[j].beghead,
1770 							    Table[j].begsect,
1771 							    Table[j].endcyl,
1772 							    Table[j].endhead,
1773 							    Table[j].endsect,
1774 							    Table[j].relsect,
1775 							    Table[j].numsect);
1776 						}
1777 
1778 						return (-1);
1779 					}
1780 					if ((rsect >=
1781 					    (t_relsect + t_numsect)) ||
1782 					    ((rsect + numsect) <= t_relsect)) {
1783 						continue;
1784 					} else {
1785 						(void) fprintf(stderr, "ERROR: "
1786 						    "current partition overlaps"
1787 						    " following partition\n");
1788 
1789 						return (-1);
1790 					}
1791 				}
1792 			}
1793 		} else {
1794 			noMoreParts = 1;
1795 		}
1796 	}
1797 	if (Table[i].systid != UNUSED) {
1798 		if (noMoreParts ||
1799 		    (((diskaddr_t)lel(Table[i].relsect) +
1800 		    lel(Table[i].numsect)) > dev_capacity) ||
1801 		    (((diskaddr_t)lel(Table[i].relsect) +
1802 		    lel(Table[i].numsect)) > DK_MAX_2TB)) {
1803 			return (-1);
1804 		}
1805 	}
1806 
1807 	return (numParts);
1808 }
1809 
1810 /*
1811  * pars_fdisk
1812  * Parse user-supplied data to set up fdisk partitions
1813  * (-A, -D, -F).
1814  */
1815 static int
1816 pars_fdisk(
1817     char *line,
1818     int *id, int *act,
1819     int *bhead, int *bsect, int *bcyl,
1820     int *ehead, int *esect, int *ecyl,
1821     uint32_t *rsect, uint32_t *numsect)
1822 {
1823 	int	i;
1824 	if (line[0] == '\0' || line[0] == '\n' || line[0] == '*')
1825 		return (1);
1826 	line[strlen(line)] = '\0';
1827 	for (i = 0; i < strlen(line); i++) {
1828 		if (line[i] == '\0') {
1829 			break;
1830 		} else if (line[i] == ':') {
1831 			line[i] = ' ';
1832 		}
1833 	}
1834 	if (sscanf(line, "%d %d %d %d %d %d %d %d %u %u",
1835 	    id, act, bhead, bsect, bcyl, ehead, esect, ecyl,
1836 	    rsect, numsect) != 10) {
1837 		(void) fprintf(stderr, "Syntax error:\n	\"%s\".\n", line);
1838 		exit(1);
1839 	}
1840 	return (0);
1841 }
1842 
1843 /*
1844  * validate_part
1845  * Validate that a new partition does not start at sector 0. Only UNUSED
1846  * partitions and previously existing partitions are allowed to start at 0.
1847  */
1848 static int
1849 validate_part(int id, uint32_t rsect, uint32_t numsect)
1850 {
1851 	int i;
1852 	if ((id != UNUSED) && (rsect == 0)) {
1853 		for (i = 0; i < FD_NUMPART; i++) {
1854 			if ((Old_Table[i].systid == id) &&
1855 			    (Old_Table[i].relsect == lel(rsect)) &&
1856 			    (Old_Table[i].numsect == lel(numsect)))
1857 				return (0);
1858 		}
1859 		(void) fprintf(stderr,
1860 		    "New partition cannot start at sector 0\n");
1861 		return (-1);
1862 	}
1863 	return (0);
1864 }
1865 
1866 /*
1867  * stage0
1868  * Print out interactive menu and process user input.
1869  */
1870 static void
1871 stage0(void)
1872 {
1873 	dispmenu();
1874 	for (;;) {
1875 		(void) printf(Q_LINE);
1876 		(void) printf("Enter Selection: ");
1877 		(void) gets(s);
1878 		rm_blanks(s);
1879 		while (!((s[0] > '0') && (s[0] < '7') && (s[1] == 0))) {
1880 			(void) printf(E_LINE); /* Clear any previous error */
1881 			(void) printf(
1882 			    "Enter a one-digit number between 1 and 6.");
1883 			(void) printf(Q_LINE);
1884 			(void) printf("Enter Selection: ");
1885 			(void) gets(s);
1886 			rm_blanks(s);
1887 		}
1888 		(void) printf(E_LINE);
1889 		switch (s[0]) {
1890 			case '1':
1891 				if (pcreate() == -1)
1892 					return;
1893 				break;
1894 			case '2':
1895 				if (pchange() == -1)
1896 					return;
1897 				break;
1898 			case '3':
1899 				if (pdelete() == -1)
1900 					return;
1901 				break;
1902 			case '4':
1903 				if (ppartid() == -1)
1904 					return;
1905 				break;
1906 			case '5':
1907 				/* update disk partition table, if changed */
1908 				if (TableChanged() == 1) {
1909 					copy_Table_to_Bootblk();
1910 					dev_mboot_write(0, Bootsect, sectsiz);
1911 				}
1912 				/*
1913 				 * If the VTOC table is wrong fix it
1914 				 * (truncate only)
1915 				 */
1916 				if (io_adjt) {
1917 					fix_slice();
1918 				}
1919 				(void) close(Dev);
1920 				exit(0);
1921 				/* FALLTHRU */
1922 			case '6':
1923 				/*
1924 				 * If the VTOC table is wrong fix it
1925 				 * (truncate only)
1926 				 */
1927 				if (io_adjt) {
1928 					fix_slice();
1929 				}
1930 				(void) close(Dev);
1931 				exit(0);
1932 				/* FALLTHRU */
1933 			default:
1934 				break;
1935 		}
1936 		copy_Table_to_Bootblk();
1937 		disptbl();
1938 		dispmenu();
1939 	}
1940 }
1941 
1942 /*
1943  * pcreate
1944  * Create partition entry in the table (interactive mode).
1945  */
1946 static int
1947 pcreate(void)
1948 {
1949 	uchar_t tsystid = 'z';
1950 	int i, j;
1951 	uint32_t numsect;
1952 	int retCode = 0;
1953 
1954 	i = 0;
1955 	for (;;) {
1956 		if (i == FD_NUMPART) {
1957 			(void) printf(E_LINE);
1958 			(void) printf(
1959 			    "The partition table is full!\n"
1960 			    "You must delete a partition before creating"
1961 			    " a new one.\n");
1962 			return (-1);
1963 		}
1964 		if (Table[i].systid == UNUSED) {
1965 			break;
1966 		}
1967 		i++;
1968 	}
1969 
1970 	numsect = 0;
1971 	for (i = 0; i < FD_NUMPART; i++) {
1972 		if (Table[i].systid != UNUSED) {
1973 			numsect += lel(Table[i].numsect);
1974 		}
1975 		if (numsect >= chs_capacity) {
1976 			(void) printf(E_LINE);
1977 			(void) printf("There is no more room on the disk for"
1978 			    " another partition.\n");
1979 			(void) printf(
1980 			    "You must delete a partition before creating"
1981 			    " a new one.\n");
1982 			return (-1);
1983 		}
1984 	}
1985 	while (tsystid == 'z') {
1986 
1987 		/*
1988 		 * The question here is expanding to more than what is
1989 		 * allocated for question lines (Q_LINE) which garbles
1990 		 * at least warning line. Clearing warning line as workaround
1991 		 * for now.
1992 		 */
1993 
1994 		(void) printf(W_LINE);
1995 		(void) printf(Q_LINE);
1996 		(void) printf(
1997 		    "Select the partition type to create:\n"
1998 		    "   1=SOLARIS2  2=UNIX        3=PCIXOS     4=Other\n"
1999 		    "   5=DOS12     6=DOS16       7=DOSEXT     8=DOSBIG\n"
2000 		    "   9=DOS16LBA  A=x86 Boot    B=Diagnostic C=FAT32\n"
2001 		    "   D=FAT32LBA  E=DOSEXTLBA   F=EFI        0=Exit? ");
2002 		(void) gets(s);
2003 		rm_blanks(s);
2004 		if (s[1] != 0) {
2005 			(void) printf(E_LINE);
2006 			(void) printf("Invalid selection, try again.");
2007 			continue;
2008 		}
2009 		switch (s[0]) {
2010 		case '0':		/* exit */
2011 			(void) printf(E_LINE);
2012 			return (-1);
2013 		case '1':		/* Solaris partition */
2014 			tsystid = SUNIXOS2;
2015 			break;
2016 		case '2':		/* UNIX partition */
2017 			tsystid = UNIXOS;
2018 			break;
2019 		case '3':		/* PCIXOS partition */
2020 			tsystid = PCIXOS;
2021 			break;
2022 		case '4':		/* OTHEROS System partition */
2023 			tsystid = OTHEROS;
2024 			break;
2025 		case '5':
2026 			tsystid = DOSOS12; /* DOS 12 bit fat */
2027 			break;
2028 		case '6':
2029 			tsystid = DOSOS16; /* DOS 16 bit fat */
2030 			break;
2031 		case '7':
2032 			tsystid = EXTDOS;
2033 			break;
2034 		case '8':
2035 			tsystid = DOSHUGE;
2036 			break;
2037 		case '9':
2038 			tsystid = FDISK_FAT95;  /* FAT16, need extended int13 */
2039 			break;
2040 		case 'a':		/* x86 Boot partition */
2041 		case 'A':
2042 			tsystid = X86BOOT;
2043 			break;
2044 		case 'b':		/* Diagnostic boot partition */
2045 		case 'B':
2046 			tsystid = DIAGPART;
2047 			break;
2048 		case 'c':		/* FAT32 */
2049 		case 'C':
2050 			tsystid = FDISK_WINDOWS;
2051 			break;
2052 		case 'd':		/* FAT32 and need extended int13 */
2053 		case 'D':
2054 			tsystid = FDISK_EXT_WIN;
2055 			break;
2056 		case 'e':	/* Extended partition, need extended int13 */
2057 		case 'E':
2058 			tsystid = FDISK_EXTLBA;
2059 			break;
2060 		case 'f':
2061 		case 'F':
2062 			tsystid = EFI_PMBR;
2063 			break;
2064 		default:
2065 			(void) printf(E_LINE);
2066 			(void) printf("Invalid selection, try again.");
2067 			continue;
2068 		}
2069 	}
2070 
2071 	(void) printf(E_LINE);
2072 
2073 	if (tsystid != EFI_PMBR) {
2074 		(void) printf(W_LINE);
2075 		if ((dev_capacity > DK_MAX_2TB))
2076 			(void) printf("WARNING: Disk is larger than 2 TB. "
2077 			    "Upper limit is 2 TB for non-EFI partition ID\n");
2078 
2079 		/* create the new partition */
2080 		i = specify(tsystid);
2081 
2082 		if (i != -1) {
2083 			/* see if it should be the active partition */
2084 			(void) printf(E_LINE);
2085 			(void) printf(Q_LINE);
2086 
2087 			(void) printf(
2088 			    "Should this become the active partition? If "
2089 			    "yes, it  will be activated\n"
2090 			    "each time the computer is reset or turned on.\n"
2091 			    "Please type \"y\" or \"n\". ");
2092 
2093 			if (yesno()) {
2094 				(void) printf(E_LINE);
2095 				for (j = 0; j < FD_NUMPART; j++) {
2096 					if (j == i) {
2097 						Table[j].bootid = ACTIVE;
2098 						(void) printf(E_LINE);
2099 						(void) printf(
2100 						    "Partition %d is now "
2101 						    "the active partition.",
2102 						    j + 1);
2103 					} else {
2104 						Table[j].bootid = 0;
2105 					}
2106 				}
2107 			} else {
2108 				Table[i].bootid = 0;
2109 			}
2110 
2111 			/* set up the return code */
2112 			i = 1;
2113 		}
2114 	} else {
2115 		/*
2116 		 * partitions of type EFI_PMBR must be the only partitions in
2117 		 * the table
2118 		 *
2119 		 * First, make sure there were no errors the table is
2120 		 * empty
2121 		 */
2122 		retCode = verify_tbl();
2123 
2124 		if (retCode < 0) {
2125 			(void) fprintf(stderr,
2126 			    "fdisk: Cannot create EFI partition table; \n"
2127 			    "current partition table is invalid.\n");
2128 			return (-1);
2129 		} else if (retCode > 0) {
2130 			(void) printf(
2131 			    "An EFI partition must be the only partition on "
2132 			    "disk.  You may manually delete existing\n"
2133 			    "partitions, or fdisk can do it.\n"
2134 			    "Do you want fdisk to destroy existing "
2135 			    "partitions?\n"
2136 			    "Please type \"y\" or \"n\". ");
2137 
2138 			if (yesno()) {
2139 				nulltbl();
2140 			} else {
2141 				return (-1);
2142 			}
2143 		}
2144 
2145 		/* create the table entry - i should be 0 */
2146 		i = insert_tbl(tsystid, 0, 0, 0, 0, 0, 0, 0, 1,
2147 		    (dev_capacity > DK_MAX_2TB) ? DK_MAX_2TB:
2148 		    (dev_capacity - 1));
2149 
2150 		if (i != 0) {
2151 			(void) printf("Error creating EFI partition!!!\n");
2152 			i = -1;
2153 		} else {
2154 
2155 			/* EFI partitions are currently never active */
2156 			Table[i].bootid = 0;
2157 
2158 			/* set up the return code */
2159 			i = 1;
2160 		}
2161 	}
2162 
2163 	return (i);
2164 }
2165 
2166 /*
2167  * specify
2168  * Query the user to specify the size of the new partition in
2169  * terms of percentage of the disk or by specifying the starting
2170  * cylinder and length in cylinders.
2171  */
2172 static int
2173 specify(uchar_t tsystid)
2174 {
2175 	int	i, j, percent = -1;
2176 	int	cyl, cylen;
2177 	diskaddr_t first_free, size_free;
2178 	diskaddr_t max_free;
2179 	int	cyl_size;
2180 	struct ipart *partition[FD_NUMPART];
2181 
2182 	cyl_size = heads * sectors;
2183 
2184 	/*
2185 	 * make a local copy of the partition table
2186 	 * and sort it into relsect order
2187 	 */
2188 	for (i = 0; i < FD_NUMPART; i++)
2189 		partition[i] = &Table[i];
2190 
2191 	for (i = 0; i < FD_NUMPART - 1; i++) {
2192 		if (partition[i]->systid == UNUSED)
2193 			break;
2194 		for (j = i + 1; j < FD_NUMPART; j++) {
2195 			if (partition[j]->systid == UNUSED)
2196 				break;
2197 			if (lel(partition[j]->relsect) <
2198 			    lel(partition[i]->relsect)) {
2199 				struct ipart *temp = partition[i];
2200 				partition[i] = partition[j];
2201 				partition[j] = temp;
2202 			}
2203 		}
2204 	}
2205 
2206 
2207 	(void) printf(Q_LINE);
2208 	(void) printf(
2209 	    "Specify the percentage of disk to use for this partition\n"
2210 	    "(or type \"c\" to specify the size in cylinders). ");
2211 	(void) gets(s);
2212 	rm_blanks(s);
2213 	if (s[0] != 'c') {	/* Specify size in percentage of disk */
2214 		i = 0;
2215 		while (s[i] != '\0') {
2216 			if (s[i] < '0' || s[i] > '9') {
2217 				(void) printf(E_LINE);
2218 				(void) printf("Invalid percentage value "
2219 				    "specified; retry the operation.");
2220 				return (-1);
2221 			}
2222 			i++;
2223 			if (i > 3) {
2224 				(void) printf(E_LINE);
2225 				(void) printf("Invalid percentage value "
2226 				    "specified; retry the operation.");
2227 				return (-1);
2228 			}
2229 		}
2230 		if ((percent = atoi(s)) > 100) {
2231 			(void) printf(E_LINE);
2232 			(void) printf(
2233 			    "Percentage value is too large. The value must be"
2234 			    " between 1 and 100;\nretry the operation.\n");
2235 			return (-1);
2236 		}
2237 		if (percent < 1) {
2238 			(void) printf(E_LINE);
2239 			(void) printf(
2240 			    "Percentage value is too small. The value must be"
2241 			    " between 1 and 100;\nretry the operation.\n");
2242 			return (-1);
2243 		}
2244 
2245 		if (percent == 100)
2246 			cylen = Numcyl_usable - 1;
2247 		else
2248 			cylen = (Numcyl_usable * percent) / 100;
2249 
2250 		/* Verify DOS12 partition doesn't exceed max size of 32MB. */
2251 		if ((tsystid == DOSOS12) &&
2252 		    ((long)((long)cylen * cyl_size) > MAXDOS)) {
2253 			int n;
2254 			n = MAXDOS * 100 / (int)(cyl_size) / Numcyl_usable;
2255 			(void) printf(E_LINE);
2256 			(void) printf("Maximum size for a DOS partition "
2257 			    "is %d%%; retry the operation.",
2258 			    n <= 100 ? n : 100);
2259 			return (-1);
2260 		}
2261 
2262 
2263 		max_free = 0;
2264 		for (i = 0; i < FD_NUMPART; i++) {
2265 
2266 			/*
2267 			 * check for free space before partition i
2268 			 * where i varies from 0 to 3
2269 			 *
2270 			 * freespace after partition 3 is unusable
2271 			 * because there are no free partitions
2272 			 *
2273 			 * freespace begins at the end of previous partition
2274 			 * or cylinder 1
2275 			 */
2276 			if (i) {
2277 				/* Not an empty table */
2278 				first_free = lel(partition[i - 1]->relsect) +
2279 				    lel(partition[i - 1]->numsect);
2280 			} else {
2281 				first_free = cyl_size;
2282 			}
2283 
2284 			/*
2285 			 * freespace ends before the current partition
2286 			 * or the end of the disk (chs end)
2287 			 */
2288 			if (partition[i]->systid == UNUSED) {
2289 				size_free = chs_capacity - first_free;
2290 			} else {
2291 				size_free =
2292 				    lel(partition[i]->relsect) - first_free;
2293 			}
2294 
2295 			/* save largest free space */
2296 			if (max_free < size_free)
2297 				max_free = size_free;
2298 
2299 			if (((uint64_t)cylen * cyl_size) <= size_free) {
2300 				/* We found a place to use */
2301 				break;
2302 			}
2303 			if (partition[i]->systid == UNUSED) {
2304 				(void) printf(E_LINE);
2305 				max_free /= (cyl_size);
2306 				(void) fprintf(stderr, "fdisk: "
2307 				    "Maximum percentage available is %lld\n",
2308 				    100 * max_free / Numcyl_usable);
2309 				return (-1);
2310 			}
2311 		}
2312 
2313 		(void) printf(E_LINE);
2314 		if (i >= FD_NUMPART) {
2315 			(void) fprintf(stderr,
2316 			    "fdisk: Partition table is full.\n");
2317 			return (-1);
2318 		}
2319 
2320 		if ((i = insert_tbl(tsystid, 0, 0, 0, 0, 0, 0, 0,
2321 		    first_free, cylen * cyl_size)) >= 0)  {
2322 			return (i);
2323 		}
2324 		return (-1);
2325 	} else {
2326 
2327 		/* Specifying size in cylinders */
2328 		(void) printf(E_LINE);
2329 		(void) printf(Q_LINE);
2330 		(void) printf("Enter starting cylinder number: ");
2331 		if ((cyl = getcyl()) == -1) {
2332 			(void) printf(E_LINE);
2333 			(void) printf("Invalid number; retry the operation.");
2334 			return (-1);
2335 		}
2336 		if (cyl == 0) {
2337 			(void) printf(E_LINE);
2338 			(void) printf(
2339 			    "New partition cannot start at cylinder 0.\n");
2340 			return (-1);
2341 		}
2342 
2343 
2344 		if (cyl >= Numcyl_usable) {
2345 			(void) printf(E_LINE);
2346 			(void) printf(
2347 			    "Cylinder %d is out of bounds, "
2348 			    "the maximum is %d.\n",
2349 			    cyl, Numcyl_usable - 1);
2350 			return (-1);
2351 		}
2352 
2353 		(void) printf(Q_LINE);
2354 		(void) printf("Enter partition size in cylinders: ");
2355 		if ((cylen = getcyl()) == -1) {
2356 			(void) printf(E_LINE);
2357 			(void) printf("Invalid number, retry the operation.");
2358 			return (-1);
2359 		}
2360 
2361 		for (i = 0; i < FD_NUMPART; i++) {
2362 			uint32_t	t_relsect, t_numsect;
2363 
2364 			if (partition[i]->systid == UNUSED)
2365 				break;
2366 			t_relsect = lel(partition[i]->relsect);
2367 			t_numsect = lel(partition[i]->numsect);
2368 
2369 			if (cyl * cyl_size >= t_relsect &&
2370 			    cyl * cyl_size < t_relsect + t_numsect) {
2371 				(void) printf(E_LINE);
2372 				(void) printf(
2373 				    "Cylinder %d is already allocated"
2374 				    "\nretry the operation.",
2375 				    cyl);
2376 				return (-1);
2377 			}
2378 
2379 			if (cyl * cyl_size < t_relsect &&
2380 			    (cyl + cylen - 1) * cyl_size > t_relsect) {
2381 				(void) printf(E_LINE);
2382 				(void) printf(
2383 				    "Maximum size for partition is %u cylinders"
2384 				    "\nretry the operation.",
2385 				    (t_relsect - cyl * cyl_size) / cyl_size);
2386 				return (-1);
2387 			}
2388 		}
2389 
2390 		/* Verify partition doesn't exceed disk size or 2 TB */
2391 		if (cyl + cylen > Numcyl_usable) {
2392 			(void) printf(E_LINE);
2393 			if (Numcyl > Numcyl_usable) {
2394 				(void) printf(
2395 				    "Maximum size for partition is %d "
2396 				    "cylinders; \nretry the operation.",
2397 				    Numcyl_usable - cyl);
2398 			} else {
2399 				(void) printf(
2400 				    "Maximum size for partition is %d "
2401 				    "cylinders; \nretry the operation.",
2402 				    Numcyl_usable - cyl);
2403 			}
2404 			return (-1);
2405 		}
2406 
2407 		/* Verify DOS12 partition doesn't exceed max size of 32MB. */
2408 		if ((tsystid == DOSOS12) &&
2409 		    ((long)((long)cylen * cyl_size) > MAXDOS)) {
2410 			(void) printf(E_LINE);
2411 			(void) printf(
2412 			    "Maximum size for a %s partition is %ld cylinders;"
2413 			    "\nretry the operation.",
2414 			    Dstr, MAXDOS / (int)(cyl_size));
2415 			return (-1);
2416 		}
2417 
2418 		(void) printf(E_LINE);
2419 		i = insert_tbl(tsystid, 0, 0, 0, 0, 0, 0, 0,
2420 		    cyl * cyl_size, cylen * cyl_size);
2421 		if (i < 0)
2422 			return (-1);
2423 
2424 		if (verify_tbl() < 0) {
2425 			(void) printf(E_LINE);
2426 			(void) printf("fdisk: Cannot create partition table\n");
2427 			return (-1);
2428 		}
2429 
2430 		return (i);
2431 	}
2432 }
2433 
2434 /*
2435  * dispmenu
2436  * Display command menu (interactive mode).
2437  */
2438 static void
2439 dispmenu(void)
2440 {
2441 	(void) printf(M_LINE);
2442 	(void) printf(
2443 	    "SELECT ONE OF THE FOLLOWING:\n"
2444 	    "   1. Create a partition\n"
2445 	    "   2. Specify the active partition\n"
2446 	    "   3. Delete a partition\n"
2447 	    "   4. Change between Solaris and Solaris2 Partition IDs\n"
2448 	    "   5. Exit (update disk configuration and exit)\n"
2449 	    "   6. Cancel (exit without updating disk configuration)\n");
2450 }
2451 
2452 /*
2453  * pchange
2454  * Change the ACTIVE designation of a partition.
2455  */
2456 static int
2457 pchange(void)
2458 {
2459 	char s[80];
2460 	int i, j;
2461 
2462 	for (;;) {
2463 		(void) printf(Q_LINE);
2464 			{
2465 			(void) printf(
2466 			    "Specify the partition number to boot from"
2467 			    " (or specify 0 for none): ");
2468 			}
2469 		(void) gets(s);
2470 		rm_blanks(s);
2471 		if ((s[1] != 0) || (s[0] < '0') || (s[0] > '4')) {
2472 			(void) printf(E_LINE);
2473 			(void) printf(
2474 			    "Invalid response, please specify a number"
2475 			    " between 0 and 4.\n");
2476 		} else {
2477 			break;
2478 		}
2479 	}
2480 	if (s[0] == '0') {	/* No active partitions */
2481 		for (i = 0; i < FD_NUMPART; i++) {
2482 			if (Table[i].systid != UNUSED &&
2483 			    Table[i].bootid == ACTIVE)
2484 				Table[i].bootid = 0;
2485 		}
2486 		(void) printf(E_LINE);
2487 			(void) printf(
2488 			    "No partition is currently marked as active.");
2489 		return (0);
2490 	} else {	/* User has selected a partition to be active */
2491 		i = s[0] - '1';
2492 		if (Table[i].systid == UNUSED) {
2493 			(void) printf(E_LINE);
2494 			(void) printf("Partition does not exist.");
2495 			return (-1);
2496 		}
2497 		/* a DOS-DATA or EXT-DOS partition cannot be active */
2498 		else if ((Table[i].systid == DOSDATA) ||
2499 		    (Table[i].systid == EXTDOS) ||
2500 		    (Table[i].systid == FDISK_EXTLBA)) {
2501 			(void) printf(E_LINE);
2502 			(void) printf(
2503 			    "DOS-DATA, EXT_DOS and EXT_DOS_LBA partitions "
2504 			    "cannot be made active.\n");
2505 			(void) printf("Select another partition.");
2506 			return (-1);
2507 		}
2508 		Table[i].bootid = ACTIVE;
2509 		for (j = 0; j < FD_NUMPART; j++) {
2510 			if (j != i)
2511 			Table[j].bootid = 0;
2512 		}
2513 	}
2514 	(void) printf(E_LINE);
2515 		{
2516 		(void) printf(
2517 		    "Partition %d is now active. The system will start up"
2518 		    " from this\n", i + 1);
2519 		(void) printf("partition after the next reboot.");
2520 		}
2521 	return (1);
2522 }
2523 
2524 /*
2525  * Change between SOLARIS and SOLARIS2 partition id
2526  */
2527 static int
2528 ppartid(void)
2529 {
2530 	char	*p, s[80];
2531 	int	i;
2532 
2533 	for (;;) {
2534 		(void) printf(Q_LINE);
2535 		(void) printf("Specify the partition number to change"
2536 		    " (or enter 0 to exit): ");
2537 		if (!fgets(s, sizeof (s), stdin))
2538 			return (1);
2539 		i = strtol(s, &p, 10);
2540 
2541 		if (*p != '\n' || i < 0 || i > FD_NUMPART) {
2542 			(void) printf(E_LINE);
2543 			(void) printf(
2544 			    "Invalid response, retry the operation.\n");
2545 			continue;
2546 		}
2547 
2548 		if (i == 0) {
2549 			/* exit delete command */
2550 			(void) printf(E_LINE); /* clear error message */
2551 			return (1);
2552 		}
2553 
2554 		i -= 1;
2555 		if (Table[i].systid == SUNIXOS) {
2556 			Table[i].systid = SUNIXOS2;
2557 		} else if (Table[i].systid == SUNIXOS2) {
2558 			Table[i].systid = SUNIXOS;
2559 		} else {
2560 			(void) printf(E_LINE);
2561 			(void) printf(
2562 			    "Partition %d is not a Solaris partition.",
2563 			    i + 1);
2564 			continue;
2565 		}
2566 
2567 		(void) printf(E_LINE);
2568 		(void) printf("Partition %d has been changed.", i + 1);
2569 		return (1);
2570 	}
2571 }
2572 
2573 /*
2574  * pdelete
2575  * Remove partition entry from the table (interactive mode).
2576  */
2577 static char
2578 pdelete(void)
2579 {
2580 	char s[80];
2581 	int i, j;
2582 	char pactive;
2583 
2584 DEL1:	(void) printf(Q_LINE);
2585 	(void) printf("Specify the partition number to delete"
2586 	    " (or enter 0 to exit): ");
2587 	(void) gets(s);
2588 	rm_blanks(s);
2589 	if ((s[0] == '0')) {	/* exit delete command */
2590 		(void) printf(E_LINE);	/* clear error message */
2591 		return (1);
2592 	}
2593 	/* Accept only a single digit between 1 and 4 */
2594 	if (s[1] != 0 || (i = atoi(s)) < 1 || i > FD_NUMPART) {
2595 		(void) printf(E_LINE);
2596 		(void) printf("Invalid response, retry the operation.\n");
2597 		goto DEL1;
2598 	} else {		/* Found a digit between 1 and 4 */
2599 		--i;	/* Structure begins with element 0 */
2600 	}
2601 
2602 	if (Table[i].systid == UNUSED) {
2603 		(void) printf(E_LINE);
2604 		(void) printf("Partition %d does not exist.", i + 1);
2605 		return (-1);
2606 	}
2607 
2608 	(void) printf(Q_LINE);
2609 	(void) printf("Are you sure you want to delete partition %d?"
2610 	    " This will make all files and \n", i + 1);
2611 	(void) printf("programs in this partition inaccessible (type"
2612 	    " \"y\" or \"n\"). ");
2613 
2614 	(void) printf(E_LINE);
2615 	if (! yesno()) {
2616 		return (1);
2617 	}
2618 
2619 	if (Table[i].bootid == ACTIVE) {
2620 		pactive = 1;
2621 	} else {
2622 		pactive = 0;
2623 	}
2624 
2625 	for (j = i; j < FD_NUMPART - 1; j++) {
2626 		Table[j] = Table[j + 1];
2627 	}
2628 
2629 	Table[j].systid = UNUSED;
2630 	Table[j].numsect = 0;
2631 	Table[j].relsect = 0;
2632 	Table[j].bootid = 0;
2633 	(void) printf(E_LINE);
2634 	(void) printf("Partition %d has been deleted.", i + 1);
2635 
2636 	if (pactive) {
2637 		(void) printf(" This was the active partition.");
2638 	}
2639 
2640 	return (1);
2641 }
2642 
2643 /*
2644  * rm_blanks
2645  * Remove blanks from strings of user responses.
2646  */
2647 static void
2648 rm_blanks(char *s)
2649 {
2650 	register int i, j;
2651 
2652 	for (i = 0; i < CBUFLEN; i++) {
2653 		if ((s[i] == ' ') || (s[i] == '\t'))
2654 			continue;
2655 		else
2656 			/* Found first non-blank character of the string */
2657 			break;
2658 	}
2659 	for (j = 0; i < CBUFLEN; j++, i++) {
2660 		if ((s[j] = s[i]) == '\0') {
2661 			/* Reached end of string */
2662 			return;
2663 		}
2664 	}
2665 }
2666 
2667 /*
2668  * getcyl
2669  * Take the user-specified cylinder number and convert it from a
2670  * string to a decimal value.
2671  */
2672 static int
2673 getcyl(void)
2674 {
2675 int slen, i, j;
2676 unsigned int cyl;
2677 	(void) gets(s);
2678 	rm_blanks(s);
2679 	slen = strlen(s);
2680 	j = 1;
2681 	cyl = 0;
2682 	for (i = slen - 1; i >= 0; i--) {
2683 		if (s[i] < '0' || s[i] > '9') {
2684 			return (-1);
2685 		}
2686 		cyl += (j * (s[i] - '0'));
2687 		j *= 10;
2688 	}
2689 	return (cyl);
2690 }
2691 
2692 /*
2693  * disptbl
2694  * Display the current fdisk table; determine percentage
2695  * of the disk used for each partition.
2696  */
2697 static void
2698 disptbl(void)
2699 {
2700 	int i;
2701 	unsigned int startcyl, endcyl, length, percent, remainder;
2702 	char *stat, *type;
2703 	int is_pmbr = 0;
2704 
2705 	if ((heads == 0) || (sectors == 0)) {
2706 		(void) printf("WARNING: critical disk geometry information"
2707 		    " missing!\n");
2708 		(void) printf("\theads = %d, sectors = %d\n", heads, sectors);
2709 		exit(1);
2710 	}
2711 
2712 	(void) printf(HOME);
2713 	(void) printf(T_LINE);
2714 	(void) printf("             Total disk size is %d cylinders\n", Numcyl);
2715 	(void) printf("             Cylinder size is %d (512 byte) blocks\n\n",
2716 	    heads * sectors);
2717 	(void) printf(
2718 	    "                                               Cylinders\n");
2719 	(void) printf(
2720 	    "      Partition   Status    Type          Start   End   Length"
2721 	    "    %%\n");
2722 	(void) printf(
2723 	    "      =========   ======    ============  =====   ===   ======"
2724 	    "   ===");
2725 	for (i = 0; i < FD_NUMPART; i++) {
2726 		if (Table[i].systid == UNUSED) {
2727 			(void) printf("\n");
2728 			(void) printf(CLR_LIN);
2729 			continue;
2730 		}
2731 		if (Table[i].bootid == ACTIVE)
2732 			stat = Actvstr;
2733 		else
2734 			stat = NAstr;
2735 		switch (Table[i].systid) {
2736 		case UNIXOS:
2737 			type = Ustr;
2738 			break;
2739 		case SUNIXOS:
2740 			type = SUstr;
2741 			break;
2742 		case SUNIXOS2:
2743 			type = SU2str;
2744 			break;
2745 		case X86BOOT:
2746 			type = X86str;
2747 			break;
2748 		case DOSOS12:
2749 			type = Dstr;
2750 			break;
2751 		case DOSOS16:
2752 			type = D16str;
2753 			break;
2754 		case EXTDOS:
2755 			type = EDstr;
2756 			break;
2757 		case DOSDATA:
2758 			type = DDstr;
2759 			break;
2760 		case DOSHUGE:
2761 			type = DBstr;
2762 			break;
2763 		case PCIXOS:
2764 			type = PCstr;
2765 			break;
2766 		case DIAGPART:
2767 			type = DIAGstr;
2768 			break;
2769 		case FDISK_IFS:
2770 			type = IFSstr;
2771 			break;
2772 		case FDISK_AIXBOOT:
2773 			type = AIXstr;
2774 			break;
2775 		case FDISK_AIXDATA:
2776 			type = AIXDstr;
2777 			break;
2778 		case FDISK_OS2BOOT:
2779 			type = OS2str;
2780 			break;
2781 		case FDISK_WINDOWS:
2782 			type = WINstr;
2783 			break;
2784 		case FDISK_EXT_WIN:
2785 			type = EWINstr;
2786 			break;
2787 		case FDISK_FAT95:
2788 			type = FAT95str;
2789 			break;
2790 		case FDISK_EXTLBA:
2791 			type = EXTLstr;
2792 			break;
2793 		case FDISK_LINUX:
2794 			type = LINUXstr;
2795 			break;
2796 		case FDISK_CPM:
2797 			type = CPMstr;
2798 			break;
2799 		case FDISK_NOVELL3:
2800 			type = NOVstr;
2801 			break;
2802 		case FDISK_QNX4:
2803 			type = QNXstr;
2804 			break;
2805 		case FDISK_QNX42:
2806 			type = QNX2str;
2807 			break;
2808 		case FDISK_QNX43:
2809 			type = QNX3str;
2810 			break;
2811 		case FDISK_LINUXNAT:
2812 			type = LINNATstr;
2813 			break;
2814 		case FDISK_NTFSVOL1:
2815 			type = NTFSVOL1str;
2816 			break;
2817 		case FDISK_NTFSVOL2:
2818 			type = NTFSVOL2str;
2819 			break;
2820 		case FDISK_BSD:
2821 			type = BSDstr;
2822 			break;
2823 		case FDISK_NEXTSTEP:
2824 			type = NEXTSTEPstr;
2825 			break;
2826 		case FDISK_BSDIFS:
2827 			type = BSDIFSstr;
2828 			break;
2829 		case FDISK_BSDISWAP:
2830 			type = BSDISWAPstr;
2831 			break;
2832 		case EFI_PMBR:
2833 			type = EFIstr;
2834 			if (lel(Table[i].numsect) == DK_MAX_2TB)
2835 				is_pmbr = 1;
2836 
2837 			break;
2838 		default:
2839 			type = Ostr;
2840 			break;
2841 		}
2842 		startcyl = lel(Table[i].relsect) /
2843 		    (unsigned long)(heads * sectors);
2844 
2845 		if (lel(Table[i].numsect) == DK_MAX_2TB) {
2846 			endcyl = Numcyl - 1;
2847 			length = endcyl - startcyl + 1;
2848 		} else {
2849 			length = lel(Table[i].numsect) /
2850 			    (unsigned long)(heads * sectors);
2851 			if (lel(Table[i].numsect) %
2852 			    (unsigned long)(heads * sectors))
2853 				length++;
2854 			endcyl = startcyl + length - 1;
2855 		}
2856 
2857 		percent = length * 100 / Numcyl_usable;
2858 		if ((remainder = (length * 100 % Numcyl_usable)) != 0) {
2859 			if ((remainder * 100 / Numcyl_usable) > 50) {
2860 				/* round up */
2861 				percent++;
2862 			}
2863 			/* Else leave the percent as is since it's already */
2864 			/* rounded down */
2865 		}
2866 		if (percent > 100)
2867 			percent = 100;
2868 		(void) printf(
2869 		    "\n          %d       %s    %-12.12s   %4d  %4d    %4d"
2870 		    "    %3d",
2871 		    i + 1, stat, type, startcyl, endcyl, length, percent);
2872 	}
2873 
2874 	/* Print warning message if table is empty */
2875 	if (Table[0].systid == UNUSED) {
2876 		(void) printf(W_LINE);
2877 		(void) printf("WARNING: no partitions are defined!");
2878 	} else {
2879 		/* Clear the warning line */
2880 		(void) printf(W_LINE);
2881 
2882 		/* Print warning if disk > 2TB and is not EFI PMBR */
2883 		if (!is_pmbr && (dev_capacity > DK_MAX_2TB))
2884 			(void) printf("WARNING: Disk is larger than 2 TB. "
2885 			    "Upper limit is 2 TB for non-EFI partition ID\n");
2886 	}
2887 }
2888 
2889 /*
2890  * print_Table
2891  * Write the detailed fdisk table to standard error for
2892  * the selected disk device.
2893  */
2894 static void
2895 print_Table(void)
2896 {
2897 	int i;
2898 
2899 	(void) fprintf(stderr,
2900 	    "  SYSID ACT BHEAD BSECT BEGCYL   EHEAD ESECT ENDCYL   RELSECT"
2901 	    "   NUMSECT\n");
2902 
2903 	for (i = 0; i < FD_NUMPART; i++) {
2904 		(void) fprintf(stderr, "  %-5d ", Table[i].systid);
2905 		(void) fprintf(stderr, "%-3d ", Table[i].bootid);
2906 		(void) fprintf(stderr, "%-5d ", Table[i].beghead);
2907 		(void) fprintf(stderr, "%-5d ", Table[i].begsect & 0x3f);
2908 		(void) fprintf(stderr, "%-8d ",
2909 		    (((uint_t)Table[i].begsect & 0xc0) << 2) + Table[i].begcyl);
2910 
2911 		(void) fprintf(stderr, "%-5d ", Table[i].endhead);
2912 		(void) fprintf(stderr, "%-5d ", Table[i].endsect & 0x3f);
2913 		(void) fprintf(stderr, "%-8d ",
2914 		    (((uint_t)Table[i].endsect & 0xc0) << 2) + Table[i].endcyl);
2915 		(void) fprintf(stderr, "%-10u ", lel(Table[i].relsect));
2916 		(void) fprintf(stderr, "%-10u\n", lel(Table[i].numsect));
2917 
2918 	}
2919 }
2920 
2921 /*
2922  * copy_Table_to_Old_Table
2923  * Copy Table into Old_Table. The function only copies the systid,
2924  * numsect, relsect, and bootid values because they are the only
2925  * ones compared when determining if Table has changed.
2926  */
2927 static void
2928 copy_Table_to_Old_Table(void)
2929 {
2930 	int i;
2931 	for (i = 0; i < FD_NUMPART; i++)  {
2932 		(void) memcpy(&Old_Table[i], &Table[i], sizeof (Table[0]));
2933 	}
2934 }
2935 
2936 /*
2937  * nulltbl
2938  * Zero out the systid, numsect, relsect, and bootid values in the
2939  * fdisk table.
2940  */
2941 static void
2942 nulltbl(void)
2943 {
2944 	int i;
2945 
2946 	for (i = 0; i < FD_NUMPART; i++)  {
2947 		Table[i].systid = UNUSED;
2948 		Table[i].numsect = lel(UNUSED);
2949 		Table[i].relsect = lel(UNUSED);
2950 		Table[i].bootid = 0;
2951 	}
2952 }
2953 
2954 /*
2955  * copy_Bootblk_to_Table
2956  * Copy the bytes from the boot record to an internal "Table".
2957  * All unused are padded with zeros starting at offset 446.
2958  */
2959 static void
2960 copy_Bootblk_to_Table(void)
2961 {
2962 	int i, j;
2963 	char *bootptr;
2964 	struct ipart iparts[FD_NUMPART];
2965 
2966 	/* Get an aligned copy of the partition tables */
2967 	(void) memcpy(iparts, Bootblk->parts, sizeof (iparts));
2968 	bootptr = (char *)iparts;	/* Points to start of partition table */
2969 	if (les(Bootblk->signature) != MBB_MAGIC)  {
2970 		/* Signature is missing */
2971 		nulltbl();
2972 		(void) memcpy(Bootblk->bootinst, &BootCod, BOOTSZ);
2973 		return;
2974 	}
2975 	/*
2976 	 * When the DOS fdisk command deletes a partition, it is not
2977 	 * recognized by the old algorithm.  The algorithm that
2978 	 * follows looks at each entry in the Bootrec and copies all
2979 	 * those that are valid.
2980 	 */
2981 	j = 0;
2982 	for (i = 0; i < FD_NUMPART; i++) {
2983 		if (iparts[i].systid == 0) {
2984 			/* Null entry */
2985 			bootptr += sizeof (struct ipart);
2986 		} else {
2987 			fill_ipart(bootptr, &Table[j]);
2988 			j++;
2989 			bootptr += sizeof (struct ipart);
2990 		}
2991 	}
2992 	for (i = j; i < FD_NUMPART; i++) {
2993 		Table[i].systid = UNUSED;
2994 		Table[i].numsect = lel(UNUSED);
2995 		Table[i].relsect = lel(UNUSED);
2996 		Table[i].bootid = 0;
2997 
2998 	}
2999 	/* For now, always replace the bootcode with ours */
3000 	(void) memcpy(Bootblk->bootinst, &BootCod, BOOTSZ);
3001 	copy_Table_to_Bootblk();
3002 }
3003 
3004 /*
3005  * fill_ipart
3006  * Initialize ipart structure values.
3007  */
3008 static void
3009 fill_ipart(char *bootptr, struct ipart *partp)
3010 {
3011 #ifdef sparc
3012 	/* Packing struct ipart for Sparc */
3013 	partp->bootid	= getbyte(&bootptr);
3014 	partp->beghead	= getbyte(&bootptr);
3015 	partp->begsect	= getbyte(&bootptr);
3016 	partp->begcyl	= getbyte(&bootptr);
3017 	partp->systid	= getbyte(&bootptr);
3018 	partp->endhead	= getbyte(&bootptr);
3019 	partp->endsect	= getbyte(&bootptr);
3020 	partp->endcyl	= getbyte(&bootptr);
3021 	partp->relsect	= (int32_t)getlong(&bootptr);
3022 	partp->numsect	= (int32_t)getlong(&bootptr);
3023 #else
3024 	*partp = *(struct ipart *)bootptr;
3025 #endif
3026 }
3027 
3028 /*
3029  * getbyte, getlong
3030  * 	Get a byte, a short, or a long (SPARC only).
3031  */
3032 #ifdef sparc
3033 uchar_t
3034 getbyte(char **bp)
3035 {
3036 	uchar_t	b;
3037 
3038 	b = (uchar_t)**bp;
3039 	*bp = *bp + 1;
3040 	return (b);
3041 }
3042 
3043 uint32_t
3044 getlong(char **bp)
3045 {
3046 	int32_t	b, bh, bl;
3047 
3048 	bh = ((**bp) << 8) | *(*bp + 1);
3049 	*bp += 2;
3050 	bl = ((**bp) << 8) | *(*bp + 1);
3051 	*bp += 2;
3052 
3053 	b = (bh << 16) | bl;
3054 	return ((uint32_t)b);
3055 }
3056 #endif
3057 
3058 /*
3059  * copy_Table_to_Bootblk
3060  * Copy the table into the 512 boot record. Note that the unused
3061  * entries will always be the last ones in the table and they are
3062  * marked with 100 in sysind. The the unused portion of the table
3063  * is padded with zeros in the bytes after the used entries.
3064  */
3065 static void
3066 copy_Table_to_Bootblk(void)
3067 {
3068 	struct ipart *boot_ptr, *tbl_ptr;
3069 
3070 	boot_ptr = (struct ipart *)Bootblk->parts;
3071 	tbl_ptr = (struct ipart *)&Table[0].bootid;
3072 	for (; tbl_ptr < (struct ipart *)&Table[FD_NUMPART].bootid;
3073 	    tbl_ptr++, boot_ptr++) {
3074 		if (tbl_ptr->systid == UNUSED)
3075 			(void) memset(boot_ptr, 0, sizeof (struct ipart));
3076 		else
3077 			(void) memcpy(boot_ptr, tbl_ptr, sizeof (struct ipart));
3078 	}
3079 	Bootblk->signature = les(MBB_MAGIC);
3080 }
3081 
3082 /*
3083  * TableChanged
3084  * 	Check for any changes in the partition table.
3085  */
3086 static int
3087 TableChanged(void)
3088 {
3089 	int i, changed;
3090 
3091 	changed = 0;
3092 	for (i = 0; i < FD_NUMPART; i++) {
3093 		if (memcmp(&Old_Table[i], &Table[i], sizeof (Table[0])) != 0) {
3094 			/* Partition table changed, write back to disk */
3095 			changed = 1;
3096 		}
3097 	}
3098 
3099 	return (changed);
3100 }
3101 
3102 /*
3103  * ffile_write
3104  * 	Display contents of partition table to standard output or
3105  *	another file name without writing it to the disk (-W file).
3106  */
3107 static void
3108 ffile_write(char *file)
3109 {
3110 	register int	i;
3111 	FILE *fp;
3112 
3113 	/*
3114 	 * If file isn't standard output, then it's a file name.
3115 	 * Open file and write it.
3116 	 */
3117 	if (file != (char *)stdout) {
3118 		if ((fp = fopen(file, "w")) == NULL) {
3119 			(void) fprintf(stderr,
3120 			    "fdisk: Cannot open output file %s.\n",
3121 			    file);
3122 			exit(1);
3123 		}
3124 	}
3125 	else
3126 		fp = stdout;
3127 
3128 	/*
3129 	 * Write the fdisk table information
3130 	 */
3131 	(void) fprintf(fp, "\n* %s default fdisk table\n", Dfltdev);
3132 	(void) fprintf(fp, "* Dimensions:\n");
3133 	(void) fprintf(fp, "*   %4d bytes/sector\n", sectsiz);
3134 	(void) fprintf(fp, "*   %4d sectors/track\n", sectors);
3135 	(void) fprintf(fp, "*   %4d tracks/cylinder\n", heads);
3136 	(void) fprintf(fp, "*   %4d cylinders\n", Numcyl);
3137 	(void) fprintf(fp, "*\n");
3138 	/* Write virtual (HBA) geometry, if required	*/
3139 	if (v_flag) {
3140 		(void) fprintf(fp, "* HBA Dimensions:\n");
3141 		(void) fprintf(fp, "*   %4d bytes/sector\n", sectsiz);
3142 		(void) fprintf(fp, "*   %4d sectors/track\n", hba_sectors);
3143 		(void) fprintf(fp, "*   %4d tracks/cylinder\n", hba_heads);
3144 		(void) fprintf(fp, "*   %4d cylinders\n", hba_Numcyl);
3145 		(void) fprintf(fp, "*\n");
3146 	}
3147 	(void) fprintf(fp, "* systid:\n");
3148 	(void) fprintf(fp, "*    1: DOSOS12\n");
3149 	(void) fprintf(fp, "*    2: PCIXOS\n");
3150 	(void) fprintf(fp, "*    4: DOSOS16\n");
3151 	(void) fprintf(fp, "*    5: EXTDOS\n");
3152 	(void) fprintf(fp, "*    6: DOSBIG\n");
3153 	(void) fprintf(fp, "*    7: FDISK_IFS\n");
3154 	(void) fprintf(fp, "*    8: FDISK_AIXBOOT\n");
3155 	(void) fprintf(fp, "*    9: FDISK_AIXDATA\n");
3156 	(void) fprintf(fp, "*   10: FDISK_0S2BOOT\n");
3157 	(void) fprintf(fp, "*   11: FDISK_WINDOWS\n");
3158 	(void) fprintf(fp, "*   12: FDISK_EXT_WIN\n");
3159 	(void) fprintf(fp, "*   14: FDISK_FAT95\n");
3160 	(void) fprintf(fp, "*   15: FDISK_EXTLBA\n");
3161 	(void) fprintf(fp, "*   18: DIAGPART\n");
3162 	(void) fprintf(fp, "*   65: FDISK_LINUX\n");
3163 	(void) fprintf(fp, "*   82: FDISK_CPM\n");
3164 	(void) fprintf(fp, "*   86: DOSDATA\n");
3165 	(void) fprintf(fp, "*   98: OTHEROS\n");
3166 	(void) fprintf(fp, "*   99: UNIXOS\n");
3167 	(void) fprintf(fp, "*  101: FDISK_NOVELL3\n");
3168 	(void) fprintf(fp, "*  119: FDISK_QNX4\n");
3169 	(void) fprintf(fp, "*  120: FDISK_QNX42\n");
3170 	(void) fprintf(fp, "*  121: FDISK_QNX43\n");
3171 	(void) fprintf(fp, "*  130: SUNIXOS\n");
3172 	(void) fprintf(fp, "*  131: FDISK_LINUXNAT\n");
3173 	(void) fprintf(fp, "*  134: FDISK_NTFSVOL1\n");
3174 	(void) fprintf(fp, "*  135: FDISK_NTFSVOL2\n");
3175 	(void) fprintf(fp, "*  165: FDISK_BSD\n");
3176 	(void) fprintf(fp, "*  167: FDISK_NEXTSTEP\n");
3177 	(void) fprintf(fp, "*  183: FDISK_BSDIFS\n");
3178 	(void) fprintf(fp, "*  184: FDISK_BSDISWAP\n");
3179 	(void) fprintf(fp, "*  190: X86BOOT\n");
3180 	(void) fprintf(fp, "*  191: SUNIXOS2\n");
3181 	(void) fprintf(fp, "*  238: EFI_PMBR\n");
3182 	(void) fprintf(fp, "*  239: EFI_FS\n");
3183 	(void) fprintf(fp, "*\n");
3184 	(void) fprintf(fp,
3185 	    "\n* Id    Act  Bhead  Bsect  Bcyl    Ehead  Esect  Ecyl"
3186 	    "    Rsect      Numsect\n");
3187 
3188 	for (i = 0; i < FD_NUMPART; i++) {
3189 		if (Table[i].systid != UNUSED)
3190 			(void) fprintf(fp,
3191 			    "  %-5d %-4d %-6d %-6d %-7d %-6d %-6d %-7d %-10u"
3192 			    " %-10u\n",
3193 			    Table[i].systid,
3194 			    Table[i].bootid,
3195 			    Table[i].beghead,
3196 			    Table[i].begsect & 0x3f,
3197 			    ((Table[i].begcyl & 0xff) | ((Table[i].begsect &
3198 			    0xc0) << 2)),
3199 			    Table[i].endhead,
3200 			    Table[i].endsect & 0x3f,
3201 			    ((Table[i].endcyl & 0xff) | ((Table[i].endsect &
3202 			    0xc0) << 2)),
3203 			    lel(Table[i].relsect),
3204 			    lel(Table[i].numsect));
3205 	}
3206 	if (fp != stdout)
3207 		(void) fclose(fp);
3208 }
3209 
3210 /*
3211  * fix_slice
3212  * 	Read the VTOC table on the Solaris partition and check that no
3213  *	slices exist that extend past the end of the Solaris partition.
3214  *	If no Solaris partition exists, nothing is done.
3215  */
3216 static void
3217 fix_slice(void)
3218 {
3219 	int	i;
3220 	uint32_t	numsect;
3221 
3222 	if (io_image) {
3223 		return;
3224 	}
3225 
3226 	for (i = 0; i < FD_NUMPART; i++) {
3227 		if (Table[i].systid == SUNIXOS || Table[i].systid == SUNIXOS2) {
3228 			/*
3229 			 * Only the size matters (not starting point), since
3230 			 * VTOC entries are relative to the start of
3231 			 * the partition.
3232 			 */
3233 			numsect = lel(Table[i].numsect);
3234 			break;
3235 		}
3236 	}
3237 
3238 	if (i >= FD_NUMPART) {
3239 		if (!io_nifdisk) {
3240 			(void) fprintf(stderr,
3241 			    "fdisk: No Solaris partition found - VTOC not"
3242 			    " checked.\n");
3243 		}
3244 		return;
3245 	}
3246 
3247 	if (readvtoc() != VTOC_OK) {
3248 		exit(1);		/* Failed to read the VTOC */
3249 	}
3250 	for (i = 0; i < V_NUMPAR; i++) {
3251 		/* Special case for slice two (entire disk) */
3252 		if (i == 2) {
3253 			if (disk_vtoc.v_part[i].p_start != 0) {
3254 				(void) fprintf(stderr,
3255 				    "slice %d starts at %llu, is not at"
3256 				    " start of partition",
3257 				    i, disk_vtoc.v_part[i].p_start);
3258 				if (!io_nifdisk) {
3259 					(void) printf(" adjust ?:");
3260 					if (yesno())
3261 						disk_vtoc.v_part[i].p_start = 0;
3262 				} else {
3263 					disk_vtoc.v_part[i].p_start = 0;
3264 					(void) fprintf(stderr, " adjusted!\n");
3265 				}
3266 
3267 			}
3268 			if (disk_vtoc.v_part[i].p_size != numsect) {
3269 				(void) fprintf(stderr,
3270 				    "slice %d size %llu does not cover"
3271 				    " complete partition",
3272 				    i, disk_vtoc.v_part[i].p_size);
3273 				if (!io_nifdisk) {
3274 					(void) printf(" adjust ?:");
3275 					if (yesno())
3276 						disk_vtoc.v_part[i].p_size =
3277 						    numsect;
3278 				} else {
3279 					disk_vtoc.v_part[i].p_size = numsect;
3280 					(void) fprintf(stderr, " adjusted!\n");
3281 				}
3282 			}
3283 			if (disk_vtoc.v_part[i].p_tag != V_BACKUP) {
3284 				(void) fprintf(stderr,
3285 				    "slice %d tag was %d should be %d",
3286 				    i, disk_vtoc.v_part[i].p_tag,
3287 				    V_BACKUP);
3288 				if (!io_nifdisk) {
3289 					(void) printf(" fix ?:");
3290 					if (yesno())
3291 						disk_vtoc.v_part[i].p_tag =
3292 						    V_BACKUP;
3293 				} else {
3294 					disk_vtoc.v_part[i].p_tag = V_BACKUP;
3295 					(void) fprintf(stderr, " fixed!\n");
3296 				}
3297 			}
3298 			continue;
3299 		}
3300 		if (io_ADJT) {
3301 			if (disk_vtoc.v_part[i].p_start > numsect ||
3302 			    disk_vtoc.v_part[i].p_start +
3303 			    disk_vtoc.v_part[i].p_size > numsect) {
3304 				(void) fprintf(stderr,
3305 				    "slice %d (start %llu, end %llu)"
3306 				    " is larger than the partition",
3307 				    i, disk_vtoc.v_part[i].p_start,
3308 				    disk_vtoc.v_part[i].p_start +
3309 				    disk_vtoc.v_part[i].p_size);
3310 				if (!io_nifdisk) {
3311 					(void) printf(" remove ?:");
3312 					if (yesno()) {
3313 						disk_vtoc.v_part[i].p_size = 0;
3314 						disk_vtoc.v_part[i].p_start = 0;
3315 						disk_vtoc.v_part[i].p_tag = 0;
3316 						disk_vtoc.v_part[i].p_flag = 0;
3317 					}
3318 				} else {
3319 					disk_vtoc.v_part[i].p_size = 0;
3320 					disk_vtoc.v_part[i].p_start = 0;
3321 					disk_vtoc.v_part[i].p_tag = 0;
3322 					disk_vtoc.v_part[i].p_flag = 0;
3323 					(void) fprintf(stderr,
3324 					    " removed!\n");
3325 				}
3326 			}
3327 			continue;
3328 		}
3329 		if (disk_vtoc.v_part[i].p_start > numsect) {
3330 			(void) fprintf(stderr,
3331 			    "slice %d (start %llu) is larger than the "
3332 			    "partition", i, disk_vtoc.v_part[i].p_start);
3333 			if (!io_nifdisk) {
3334 				(void) printf(" remove ?:");
3335 				if (yesno()) {
3336 					disk_vtoc.v_part[i].p_size = 0;
3337 					disk_vtoc.v_part[i].p_start = 0;
3338 					disk_vtoc.v_part[i].p_tag = 0;
3339 					disk_vtoc.v_part[i].p_flag = 0;
3340 				}
3341 			} else {
3342 				disk_vtoc.v_part[i].p_size = 0;
3343 				disk_vtoc.v_part[i].p_start = 0;
3344 				disk_vtoc.v_part[i].p_tag = 0;
3345 				disk_vtoc.v_part[i].p_flag = 0;
3346 				(void) fprintf(stderr,
3347 				" removed!\n");
3348 			}
3349 		} else if (disk_vtoc.v_part[i].p_start
3350 		    + disk_vtoc.v_part[i].p_size > numsect) {
3351 			(void) fprintf(stderr,
3352 			    "slice %d (end %llu) is larger"
3353 			    " than the partition",
3354 			    i,
3355 			    disk_vtoc.v_part[i].p_start +
3356 			    disk_vtoc.v_part[i].p_size);
3357 			if (!io_nifdisk) {
3358 				(void) printf(" adjust ?:");
3359 				if (yesno()) {
3360 					disk_vtoc.v_part[i].p_size = numsect;
3361 				}
3362 			} else {
3363 				disk_vtoc.v_part[i].p_size = numsect;
3364 				(void) fprintf(stderr, " adjusted!\n");
3365 			}
3366 		}
3367 	}
3368 #if 1		/* bh for now */
3369 	/* Make the VTOC look sane - ha ha */
3370 	disk_vtoc.v_version = V_VERSION;
3371 	disk_vtoc.v_sanity = VTOC_SANE;
3372 	disk_vtoc.v_nparts = V_NUMPAR;
3373 	if (disk_vtoc.v_sectorsz == 0)
3374 		disk_vtoc.v_sectorsz = NBPSCTR;
3375 #endif
3376 
3377 	/* Write the VTOC back to the disk */
3378 	if (!io_readonly)
3379 		(void) writevtoc();
3380 }
3381 
3382 /*
3383  * yesno
3384  * Get yes or no answer. Return 1 for yes and 0 for no.
3385  */
3386 
3387 static int
3388 yesno(void)
3389 {
3390 	char	s[80];
3391 
3392 	for (;;) {
3393 		(void) gets(s);
3394 		rm_blanks(s);
3395 		if ((s[1] != 0) || ((s[0] != 'y') && (s[0] != 'n'))) {
3396 			(void) printf(E_LINE);
3397 			(void) printf("Please answer with \"y\" or \"n\": ");
3398 			continue;
3399 		}
3400 		if (s[0] == 'y')
3401 			return (1);
3402 		else
3403 			return (0);
3404 	}
3405 }
3406 
3407 /*
3408  * readvtoc
3409  * 	Read the VTOC from the Solaris partition of the device.
3410  */
3411 static int
3412 readvtoc(void)
3413 {
3414 	int	i;
3415 	int	retval = VTOC_OK;
3416 
3417 	if ((i = read_extvtoc(Dev, &disk_vtoc)) < VTOC_OK) {
3418 		if (i == VT_EINVAL) {
3419 			(void) fprintf(stderr, "fdisk: Invalid VTOC.\n");
3420 			vt_inval++;
3421 			retval = VTOC_INVAL;
3422 		} else if (i == VT_ENOTSUP) {
3423 			(void) fprintf(stderr, "fdisk: partition may have EFI "
3424 			    "GPT\n");
3425 			retval = VTOC_NOTSUP;
3426 		} else {
3427 			(void) fprintf(stderr, "fdisk: Cannot read VTOC.\n");
3428 			retval = VTOC_RWERR;
3429 		}
3430 	}
3431 	return (retval);
3432 }
3433 
3434 /*
3435  * writevtoc
3436  * 	Write the VTOC to the Solaris partition on the device.
3437  */
3438 static int
3439 writevtoc(void)
3440 {
3441 	int	i;
3442 	int	retval = 0;
3443 
3444 	if ((i = write_extvtoc(Dev, &disk_vtoc)) != 0) {
3445 		if (i == VT_EINVAL) {
3446 			(void) fprintf(stderr,
3447 			    "fdisk: Invalid entry exists in VTOC.\n");
3448 			retval = VTOC_INVAL;
3449 		} else if (i == VT_ENOTSUP) {
3450 			(void) fprintf(stderr, "fdisk: partition may have EFI "
3451 			    "GPT\n");
3452 			retval = VTOC_NOTSUP;
3453 		} else {
3454 			(void) fprintf(stderr, "fdisk: Cannot write VTOC.\n");
3455 			retval = VTOC_RWERR;
3456 		}
3457 	}
3458 	return (retval);
3459 }
3460 
3461 /*
3462  * efi_ioctl
3463  * issues DKIOCSETEFI IOCTL
3464  * (duplicate of private efi_ioctl() in rdwr_efi.c
3465  */
3466 static int
3467 efi_ioctl(int fd, int cmd, dk_efi_t *dk_ioc)
3468 {
3469 	void *data = dk_ioc->dki_data;
3470 	int error;
3471 
3472 	dk_ioc->dki_data_64 = (uintptr_t)data;
3473 	error = ioctl(fd, cmd, (void *)dk_ioc);
3474 
3475 	return (error);
3476 }
3477 
3478 /*
3479  * clear_efi
3480  * Clear EFI labels from the EFI_PMBR partition on the device
3481  * This function is modeled on the libefi(3LIB) call efi_write()
3482  */
3483 static int
3484 clear_efi(void)
3485 {
3486 	struct dk_gpt	*efi_vtoc;
3487 	dk_efi_t	dk_ioc;
3488 
3489 	/*
3490 	 * see if we can read the EFI label
3491 	 */
3492 	if (efi_alloc_and_read(Dev, &efi_vtoc) < 0) {
3493 		return (VT_ERROR);
3494 	}
3495 
3496 	/*
3497 	 * set up the dk_ioc structure for writing
3498 	 */
3499 	dk_ioc.dki_lba = 1;
3500 	dk_ioc.dki_length = EFI_MIN_ARRAY_SIZE + efi_vtoc->efi_lbasize;
3501 
3502 	if ((dk_ioc.dki_data = calloc(dk_ioc.dki_length, 1)) == NULL) {
3503 		return (VT_ERROR);
3504 	}
3505 
3506 	/*
3507 	 * clear the primary label
3508 	 */
3509 	if (io_debug) {
3510 		(void) fprintf(stderr,
3511 		    "\tClearing primary EFI label at block %lld\n",
3512 		    dk_ioc.dki_lba);
3513 	}
3514 
3515 	if (efi_ioctl(Dev, DKIOCSETEFI, &dk_ioc) == -1) {
3516 		free(dk_ioc.dki_data);
3517 		switch (errno) {
3518 			case EIO:
3519 				return (VT_EIO);
3520 			case EINVAL:
3521 				return (VT_EINVAL);
3522 			default:
3523 				return (VT_ERROR);
3524 		}
3525 	}
3526 
3527 	/*
3528 	 * clear the backup partition table
3529 	 */
3530 	dk_ioc.dki_lba = efi_vtoc->efi_last_u_lba + 1;
3531 	dk_ioc.dki_length -= efi_vtoc->efi_lbasize;
3532 	dk_ioc.dki_data++;
3533 	if (io_debug) {
3534 		(void) fprintf(stderr,
3535 		    "\tClearing backup partition table at block %lld\n",
3536 		    dk_ioc.dki_lba);
3537 	}
3538 
3539 	if (efi_ioctl(Dev, DKIOCSETEFI, &dk_ioc) == -1) {
3540 		(void) fprintf(stderr, "\tUnable to clear backup EFI label at "
3541 		    "block %llu; errno %d\n", efi_vtoc->efi_last_u_lba + 1,
3542 		    errno);
3543 	}
3544 
3545 	/*
3546 	 * clear the backup label
3547 	 */
3548 	dk_ioc.dki_lba = efi_vtoc->efi_last_lba;
3549 	dk_ioc.dki_length = efi_vtoc->efi_lbasize;
3550 	dk_ioc.dki_data--;
3551 	if (io_debug) {
3552 		(void) fprintf(stderr, "\tClearing backup label at block "
3553 		    "%lld\n", dk_ioc.dki_lba);
3554 	}
3555 
3556 	if (efi_ioctl(Dev, DKIOCSETEFI, &dk_ioc) == -1) {
3557 		(void) fprintf(stderr,
3558 		    "\tUnable to clear backup EFI label at "
3559 		    "block %llu; errno %d\n",
3560 		    efi_vtoc->efi_last_lba,
3561 		    errno);
3562 	}
3563 
3564 	free(dk_ioc.dki_data);
3565 	efi_free(efi_vtoc);
3566 
3567 	return (0);
3568 }
3569 
3570 /*
3571  * clear_vtoc
3572  * 	Clear the VTOC from the current or previous Solaris partition on the
3573  *      device.
3574  */
3575 static void
3576 clear_vtoc(int table, int part)
3577 {
3578 	struct ipart *clr_table;
3579 	struct dk_label disk_label;
3580 	uint32_t pcyl, ncyl, count;
3581 	diskaddr_t backup_block, solaris_offset;
3582 	ssize_t bytes;
3583 	off_t seek_byte;
3584 
3585 #ifdef DEBUG
3586 	struct dk_label	read_label;
3587 #endif /* DEBUG */
3588 
3589 	if (table == OLD) {
3590 		clr_table = &Old_Table[part];
3591 	} else {
3592 		clr_table = &Table[part];
3593 	}
3594 
3595 	(void) memset(&disk_label, 0, sizeof (struct dk_label));
3596 
3597 	seek_byte = (off_t)(lel(clr_table->relsect) + VTOC_OFFSET) * sectsiz;
3598 
3599 	if (io_debug) {
3600 		(void) fprintf(stderr,
3601 		    "\tClearing primary VTOC at byte %llu (block %llu)\n",
3602 		    (uint64_t)seek_byte,
3603 		    (uint64_t)(lel(clr_table->relsect) + VTOC_OFFSET));
3604 	}
3605 
3606 	if (lseek(Dev, seek_byte, SEEK_SET) == -1) {
3607 		(void) fprintf(stderr,
3608 		    "\tError seeking to primary label at byte %llu\n",
3609 		    (uint64_t)seek_byte);
3610 		return;
3611 	}
3612 
3613 	bytes = write(Dev, &disk_label, sizeof (struct dk_label));
3614 
3615 	if (bytes != sizeof (struct dk_label)) {
3616 		(void) fprintf(stderr,
3617 		    "\tWarning: only %d bytes written to clear primary"
3618 		    " VTOC!\n", bytes);
3619 	}
3620 
3621 #ifdef DEBUG
3622 	if (lseek(Dev, seek_byte, SEEK_SET) == -1) {
3623 		(void) fprintf(stderr,
3624 		    "DEBUG: Error seeking to primary label at byte %llu\n",
3625 		    (uint64_t)seek_byte);
3626 		return;
3627 	} else {
3628 		(void) fprintf(stderr,
3629 		    "DEBUG: Successful lseek() to byte %llu\n",
3630 		    (uint64_t)seek_byte);
3631 	}
3632 
3633 	bytes = read(Dev, &read_label, sizeof (struct dk_label));
3634 
3635 	if (bytes != sizeof (struct dk_label)) {
3636 		(void) fprintf(stderr,
3637 		    "DEBUG: Warning: only %d bytes read of label\n",
3638 		    bytes);
3639 	}
3640 
3641 	if (memcmp(&disk_label, &read_label, sizeof (struct dk_label)) != 0) {
3642 		(void) fprintf(stderr,
3643 		    "DEBUG: Warning: disk_label and read_label differ!!!\n");
3644 	} else {
3645 		(void) fprintf(stderr, "DEBUG Good compare of disk_label and "
3646 		    "read_label\n");
3647 	}
3648 #endif /* DEBUG */
3649 
3650 	/* Clear backup label */
3651 	pcyl = lel(clr_table->numsect) / (heads * sectors);
3652 	solaris_offset = lel(clr_table->relsect);
3653 	ncyl = pcyl - acyl;
3654 
3655 	backup_block = ((ncyl + acyl - 1) *
3656 	    (heads * sectors)) + ((heads - 1) * sectors) + 1;
3657 
3658 	for (count = 1; count < 6; count++) {
3659 		seek_byte = (off_t)(solaris_offset + backup_block) * 512;
3660 
3661 		if (lseek(Dev, seek_byte, SEEK_SET) == -1) {
3662 			(void) fprintf(stderr,
3663 			    "\tError seeking to backup label at byte %llu on "
3664 			    "%s.\n", (uint64_t)seek_byte, Dfltdev);
3665 			return;
3666 		}
3667 
3668 		if (io_debug) {
3669 			(void) fprintf(stderr, "\tClearing backup VTOC at"
3670 			    " byte %llu (block %llu)\n",
3671 			    (uint64_t)seek_byte,
3672 			    (uint64_t)(solaris_offset + backup_block));
3673 		}
3674 
3675 		bytes = write(Dev, &disk_label, sizeof (struct dk_label));
3676 
3677 		if (bytes != sizeof (struct dk_label)) {
3678 			(void) fprintf(stderr,
3679 			    "\t\tWarning: only %d bytes written to "
3680 			    "clear backup VTOC at block %llu!\n", bytes,
3681 			    (uint64_t)(solaris_offset + backup_block));
3682 		}
3683 
3684 #ifdef DEBUG
3685 	if (lseek(Dev, seek_byte, SEEK_SET) == -1) {
3686 		(void) fprintf(stderr,
3687 		    "DEBUG: Error seeking to backup label at byte %llu\n",
3688 		    (uint64_t)seek_byte);
3689 		return;
3690 	} else {
3691 		(void) fprintf(stderr,
3692 		    "DEBUG: Successful lseek() to byte %llu\n",
3693 		    (uint64_t)seek_byte);
3694 	}
3695 
3696 	bytes = read(Dev, &read_label, sizeof (struct dk_label));
3697 
3698 	if (bytes != sizeof (struct dk_label)) {
3699 		(void) fprintf(stderr,
3700 		    "DEBUG: Warning: only %d bytes read of backup label\n",
3701 		    bytes);
3702 	}
3703 
3704 	if (memcmp(&disk_label, &read_label, sizeof (struct dk_label)) != 0) {
3705 		(void) fprintf(stderr,
3706 		    "DEBUG: Warning: disk_label and read_label differ!!!\n");
3707 	} else {
3708 		(void) fprintf(stderr,
3709 		    "DEBUG: Good compare of disk_label and backup "
3710 		    "read_label\n");
3711 	}
3712 #endif /* DEBUG */
3713 
3714 		backup_block += 2;
3715 	}
3716 }
3717 
3718 #define	FDISK_STANDARD_LECTURE \
3719 	"Fdisk is normally used with the device that " \
3720 	"represents the entire fixed disk.\n" \
3721 	"(For example, /dev/rdsk/c0d0p0 on x86 or " \
3722 	"/dev/rdsk/c0t5d0s2 on sparc).\n"
3723 
3724 #define	FDISK_LECTURE_NOT_SECTOR_ZERO \
3725 	"The device does not appear to include absolute\n" \
3726 	"sector 0 of the PHYSICAL disk " \
3727 	"(the normal location for an fdisk table).\n"
3728 
3729 #define	FDISK_LECTURE_NOT_FULL \
3730 	"The device does not appear to encompass the entire PHYSICAL disk.\n"
3731 
3732 #define	FDISK_LECTURE_NO_VTOC \
3733 	"Unable to find a volume table of contents.\n" \
3734 	"Cannot verify the device encompasses the full PHYSICAL disk.\n"
3735 
3736 #define	FDISK_LECTURE_NO_GEOM \
3737 	"Unable to get geometry from device.\n" \
3738 	"Cannot verify the device encompasses the full PHYSICAL disk.\n"
3739 
3740 #define	FDISK_SHALL_I_CONTINUE \
3741 	"Are you sure you want to continue? (y/n) "
3742 
3743 /*
3744  *  lecture_and_query
3745  *	Called when a sanity check fails.  This routine gives a warning
3746  *	specific to the check that fails, followed by a generic lecture
3747  *	about the "right" device to supply as input.  Then, if appropriate,
3748  *	it will prompt the user on whether or not they want to continue.
3749  *	Inappropriate times for prompting are when the user has selected
3750  *	non-interactive mode or read-only mode.
3751  */
3752 static int
3753 lecture_and_query(char *warning, char *devname)
3754 {
3755 	if (io_nifdisk)
3756 		return (0);
3757 
3758 	(void) fprintf(stderr, "WARNING: Device %s: \n", devname);
3759 	(void) fprintf(stderr, "%s", warning);
3760 	(void) fprintf(stderr, FDISK_STANDARD_LECTURE);
3761 	(void) fprintf(stderr, FDISK_SHALL_I_CONTINUE);
3762 
3763 	return (yesno());
3764 }
3765 
3766 static void
3767 sanity_check_provided_device(char *devname, int fd)
3768 {
3769 	struct extvtoc v;
3770 	struct dk_geom d;
3771 	struct part_info pi;
3772 	struct extpart_info extpi;
3773 	diskaddr_t totsize;
3774 	int idx = -1;
3775 
3776 	/*
3777 	 *  First try the PARTINFO ioctl.  If it works, we will be able
3778 	 *  to tell if they've specified the full disk partition by checking
3779 	 *  to see if they've specified a partition that starts at sector 0.
3780 	 */
3781 	if (ioctl(fd, DKIOCEXTPARTINFO, &extpi) != -1) {
3782 		if (extpi.p_start != 0) {
3783 			if (!lecture_and_query(FDISK_LECTURE_NOT_SECTOR_ZERO,
3784 			    devname)) {
3785 				(void) close(fd);
3786 				exit(1);
3787 			}
3788 		}
3789 	} else if (ioctl(fd, DKIOCPARTINFO, &pi) != -1) {
3790 		if (pi.p_start != 0) {
3791 			if (!lecture_and_query(FDISK_LECTURE_NOT_SECTOR_ZERO,
3792 			    devname)) {
3793 				(void) close(fd);
3794 				exit(1);
3795 			}
3796 		}
3797 	} else {
3798 		if ((idx = read_extvtoc(fd, &v)) < 0) {
3799 			if (!lecture_and_query(FDISK_LECTURE_NO_VTOC,
3800 			    devname)) {
3801 				(void) close(fd);
3802 				exit(1);
3803 			}
3804 			return;
3805 		}
3806 		if (ioctl(fd, DKIOCGGEOM, &d) == -1) {
3807 			perror(devname);
3808 			if (!lecture_and_query(FDISK_LECTURE_NO_GEOM,
3809 			    devname)) {
3810 				(void) close(fd);
3811 				exit(1);
3812 			}
3813 			return;
3814 		}
3815 		totsize = (diskaddr_t)d.dkg_ncyl * d.dkg_nhead * d.dkg_nsect;
3816 		if (v.v_part[idx].p_size != totsize) {
3817 			if (!lecture_and_query(FDISK_LECTURE_NOT_FULL,
3818 			    devname)) {
3819 				(void) close(fd);
3820 				exit(1);
3821 			}
3822 		}
3823 	}
3824 }
3825 
3826 
3827 /*
3828  * get_node
3829  * Called from main to construct the name of the device node to open.
3830  * Initially tries to stat the node exactly as provided, if that fails
3831  * we prepend the default path (/dev/rdsk/).
3832  */
3833 static char *
3834 get_node(char *devname)
3835 {
3836 	char *node;
3837 	struct stat statbuf;
3838 	size_t space;
3839 
3840 	/* Don't do anything if we are skipping device checks */
3841 	if (io_image)
3842 		return (devname);
3843 
3844 	node = devname;
3845 
3846 	/* Try the node as provided first */
3847 	if (stat(node, (struct stat *)&statbuf) == -1) {
3848 		/*
3849 		 * Copy the passed in string to a new buffer, prepend the
3850 		 * default path and try again.
3851 		 */
3852 		space = strlen(DEFAULT_PATH) + strlen(devname) + 1;
3853 
3854 		if ((node = malloc(space)) == NULL) {
3855 			(void) fprintf(stderr, "fdisk: Unable to obtain memory "
3856 			    "for device node.\n");
3857 			exit(1);
3858 		}
3859 
3860 		/* Copy over the default path and the provided node */
3861 		(void) strncpy(node, DEFAULT_PATH, strlen(DEFAULT_PATH));
3862 		space -= strlen(DEFAULT_PATH);
3863 		(void) strlcpy(node + strlen(DEFAULT_PATH), devname, space);
3864 
3865 		/* Try to stat it again */
3866 		if (stat(node, (struct stat *)&statbuf) == -1) {
3867 			/* Failed all options, give up */
3868 			(void) fprintf(stderr,
3869 			    "fdisk: Cannot stat device %s.\n",
3870 			    devname);
3871 			exit(1);
3872 		}
3873 	}
3874 
3875 	/* Make sure the device specified is the raw device */
3876 	if ((statbuf.st_mode & S_IFMT) != S_IFCHR) {
3877 		(void) fprintf(stderr,
3878 		    "fdisk: %s must be a raw device.\n", node);
3879 		exit(1);
3880 	}
3881 
3882 	return (node);
3883 }
3884