xref: /illumos-gate/usr/src/cmd/fdisk/fdisk.c (revision 50981ffc7e4c5048d14890df805afee6ec113991)
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 				/*
2292 				 * Partition might start before cylinder 1.
2293 				 * Make sure free space is not negative.
2294 				 */
2295 				size_free =
2296 				    (lel(partition[i]->relsect > first_free)) ?
2297 				    (lel(partition[i]->relsect) - first_free) :
2298 				    0;
2299 			}
2300 
2301 			/* save largest free space */
2302 			if (max_free < size_free)
2303 				max_free = size_free;
2304 
2305 			if (((uint64_t)cylen * cyl_size) <= size_free) {
2306 				/* We found a place to use */
2307 				break;
2308 			}
2309 			if (partition[i]->systid == UNUSED) {
2310 				(void) printf(E_LINE);
2311 				max_free /= (cyl_size);
2312 				(void) fprintf(stderr, "fdisk: "
2313 				    "Maximum percentage available is %lld\n",
2314 				    100 * max_free / Numcyl_usable);
2315 				return (-1);
2316 			}
2317 		}
2318 
2319 		(void) printf(E_LINE);
2320 		if (i >= FD_NUMPART) {
2321 			(void) fprintf(stderr,
2322 			    "fdisk: Partition table is full.\n");
2323 			return (-1);
2324 		}
2325 
2326 		if ((i = insert_tbl(tsystid, 0, 0, 0, 0, 0, 0, 0,
2327 		    first_free, cylen * cyl_size)) >= 0)  {
2328 			return (i);
2329 		}
2330 		return (-1);
2331 	} else {
2332 
2333 		/* Specifying size in cylinders */
2334 		(void) printf(E_LINE);
2335 		(void) printf(Q_LINE);
2336 		(void) printf("Enter starting cylinder number: ");
2337 		if ((cyl = getcyl()) == -1) {
2338 			(void) printf(E_LINE);
2339 			(void) printf("Invalid number; retry the operation.");
2340 			return (-1);
2341 		}
2342 		if (cyl == 0) {
2343 			(void) printf(E_LINE);
2344 			(void) printf(
2345 			    "New partition cannot start at cylinder 0.\n");
2346 			return (-1);
2347 		}
2348 
2349 
2350 		if (cyl >= Numcyl_usable) {
2351 			(void) printf(E_LINE);
2352 			(void) printf(
2353 			    "Cylinder %d is out of bounds, "
2354 			    "the maximum is %d.\n",
2355 			    cyl, Numcyl_usable - 1);
2356 			return (-1);
2357 		}
2358 
2359 		(void) printf(Q_LINE);
2360 		(void) printf("Enter partition size in cylinders: ");
2361 		if ((cylen = getcyl()) == -1) {
2362 			(void) printf(E_LINE);
2363 			(void) printf("Invalid number, retry the operation.");
2364 			return (-1);
2365 		}
2366 
2367 		for (i = 0; i < FD_NUMPART; i++) {
2368 			uint32_t	t_relsect, t_numsect;
2369 
2370 			if (partition[i]->systid == UNUSED)
2371 				break;
2372 			t_relsect = lel(partition[i]->relsect);
2373 			t_numsect = lel(partition[i]->numsect);
2374 
2375 			if (cyl * cyl_size >= t_relsect &&
2376 			    cyl * cyl_size < t_relsect + t_numsect) {
2377 				(void) printf(E_LINE);
2378 				(void) printf(
2379 				    "Cylinder %d is already allocated"
2380 				    "\nretry the operation.",
2381 				    cyl);
2382 				return (-1);
2383 			}
2384 
2385 			if (cyl * cyl_size < t_relsect &&
2386 			    (cyl + cylen - 1) * cyl_size > t_relsect) {
2387 				(void) printf(E_LINE);
2388 				(void) printf(
2389 				    "Maximum size for partition is %u cylinders"
2390 				    "\nretry the operation.",
2391 				    (t_relsect - cyl * cyl_size) / cyl_size);
2392 				return (-1);
2393 			}
2394 		}
2395 
2396 		/* Verify partition doesn't exceed disk size or 2 TB */
2397 		if (cyl + cylen > Numcyl_usable) {
2398 			(void) printf(E_LINE);
2399 			if (Numcyl > Numcyl_usable) {
2400 				(void) printf(
2401 				    "Maximum size for partition is %d "
2402 				    "cylinders; \nretry the operation.",
2403 				    Numcyl_usable - cyl);
2404 			} else {
2405 				(void) printf(
2406 				    "Maximum size for partition is %d "
2407 				    "cylinders; \nretry the operation.",
2408 				    Numcyl_usable - cyl);
2409 			}
2410 			return (-1);
2411 		}
2412 
2413 		/* Verify DOS12 partition doesn't exceed max size of 32MB. */
2414 		if ((tsystid == DOSOS12) &&
2415 		    ((long)((long)cylen * cyl_size) > MAXDOS)) {
2416 			(void) printf(E_LINE);
2417 			(void) printf(
2418 			    "Maximum size for a %s partition is %ld cylinders;"
2419 			    "\nretry the operation.",
2420 			    Dstr, MAXDOS / (int)(cyl_size));
2421 			return (-1);
2422 		}
2423 
2424 		(void) printf(E_LINE);
2425 		i = insert_tbl(tsystid, 0, 0, 0, 0, 0, 0, 0,
2426 		    cyl * cyl_size, cylen * cyl_size);
2427 		if (i < 0)
2428 			return (-1);
2429 
2430 		if (verify_tbl() < 0) {
2431 			(void) printf(E_LINE);
2432 			(void) printf("fdisk: Cannot create partition table\n");
2433 			return (-1);
2434 		}
2435 
2436 		return (i);
2437 	}
2438 }
2439 
2440 /*
2441  * dispmenu
2442  * Display command menu (interactive mode).
2443  */
2444 static void
2445 dispmenu(void)
2446 {
2447 	(void) printf(M_LINE);
2448 	(void) printf(
2449 	    "SELECT ONE OF THE FOLLOWING:\n"
2450 	    "   1. Create a partition\n"
2451 	    "   2. Specify the active partition\n"
2452 	    "   3. Delete a partition\n"
2453 	    "   4. Change between Solaris and Solaris2 Partition IDs\n"
2454 	    "   5. Exit (update disk configuration and exit)\n"
2455 	    "   6. Cancel (exit without updating disk configuration)\n");
2456 }
2457 
2458 /*
2459  * pchange
2460  * Change the ACTIVE designation of a partition.
2461  */
2462 static int
2463 pchange(void)
2464 {
2465 	char s[80];
2466 	int i, j;
2467 
2468 	for (;;) {
2469 		(void) printf(Q_LINE);
2470 			{
2471 			(void) printf(
2472 			    "Specify the partition number to boot from"
2473 			    " (or specify 0 for none): ");
2474 			}
2475 		(void) gets(s);
2476 		rm_blanks(s);
2477 		if ((s[1] != 0) || (s[0] < '0') || (s[0] > '4')) {
2478 			(void) printf(E_LINE);
2479 			(void) printf(
2480 			    "Invalid response, please specify a number"
2481 			    " between 0 and 4.\n");
2482 		} else {
2483 			break;
2484 		}
2485 	}
2486 	if (s[0] == '0') {	/* No active partitions */
2487 		for (i = 0; i < FD_NUMPART; i++) {
2488 			if (Table[i].systid != UNUSED &&
2489 			    Table[i].bootid == ACTIVE)
2490 				Table[i].bootid = 0;
2491 		}
2492 		(void) printf(E_LINE);
2493 			(void) printf(
2494 			    "No partition is currently marked as active.");
2495 		return (0);
2496 	} else {	/* User has selected a partition to be active */
2497 		i = s[0] - '1';
2498 		if (Table[i].systid == UNUSED) {
2499 			(void) printf(E_LINE);
2500 			(void) printf("Partition does not exist.");
2501 			return (-1);
2502 		}
2503 		/* a DOS-DATA or EXT-DOS partition cannot be active */
2504 		else if ((Table[i].systid == DOSDATA) ||
2505 		    (Table[i].systid == EXTDOS) ||
2506 		    (Table[i].systid == FDISK_EXTLBA)) {
2507 			(void) printf(E_LINE);
2508 			(void) printf(
2509 			    "DOS-DATA, EXT_DOS and EXT_DOS_LBA partitions "
2510 			    "cannot be made active.\n");
2511 			(void) printf("Select another partition.");
2512 			return (-1);
2513 		}
2514 		Table[i].bootid = ACTIVE;
2515 		for (j = 0; j < FD_NUMPART; j++) {
2516 			if (j != i)
2517 			Table[j].bootid = 0;
2518 		}
2519 	}
2520 	(void) printf(E_LINE);
2521 		{
2522 		(void) printf(
2523 		    "Partition %d is now active. The system will start up"
2524 		    " from this\n", i + 1);
2525 		(void) printf("partition after the next reboot.");
2526 		}
2527 	return (1);
2528 }
2529 
2530 /*
2531  * Change between SOLARIS and SOLARIS2 partition id
2532  */
2533 static int
2534 ppartid(void)
2535 {
2536 	char	*p, s[80];
2537 	int	i;
2538 
2539 	for (;;) {
2540 		(void) printf(Q_LINE);
2541 		(void) printf("Specify the partition number to change"
2542 		    " (or enter 0 to exit): ");
2543 		if (!fgets(s, sizeof (s), stdin))
2544 			return (1);
2545 		i = strtol(s, &p, 10);
2546 
2547 		if (*p != '\n' || i < 0 || i > FD_NUMPART) {
2548 			(void) printf(E_LINE);
2549 			(void) printf(
2550 			    "Invalid response, retry the operation.\n");
2551 			continue;
2552 		}
2553 
2554 		if (i == 0) {
2555 			/* exit delete command */
2556 			(void) printf(E_LINE); /* clear error message */
2557 			return (1);
2558 		}
2559 
2560 		i -= 1;
2561 		if (Table[i].systid == SUNIXOS) {
2562 			Table[i].systid = SUNIXOS2;
2563 		} else if (Table[i].systid == SUNIXOS2) {
2564 			Table[i].systid = SUNIXOS;
2565 		} else {
2566 			(void) printf(E_LINE);
2567 			(void) printf(
2568 			    "Partition %d is not a Solaris partition.",
2569 			    i + 1);
2570 			continue;
2571 		}
2572 
2573 		(void) printf(E_LINE);
2574 		(void) printf("Partition %d has been changed.", i + 1);
2575 		return (1);
2576 	}
2577 }
2578 
2579 /*
2580  * pdelete
2581  * Remove partition entry from the table (interactive mode).
2582  */
2583 static char
2584 pdelete(void)
2585 {
2586 	char s[80];
2587 	int i, j;
2588 	char pactive;
2589 
2590 DEL1:	(void) printf(Q_LINE);
2591 	(void) printf("Specify the partition number to delete"
2592 	    " (or enter 0 to exit): ");
2593 	(void) gets(s);
2594 	rm_blanks(s);
2595 	if ((s[0] == '0')) {	/* exit delete command */
2596 		(void) printf(E_LINE);	/* clear error message */
2597 		return (1);
2598 	}
2599 	/* Accept only a single digit between 1 and 4 */
2600 	if (s[1] != 0 || (i = atoi(s)) < 1 || i > FD_NUMPART) {
2601 		(void) printf(E_LINE);
2602 		(void) printf("Invalid response, retry the operation.\n");
2603 		goto DEL1;
2604 	} else {		/* Found a digit between 1 and 4 */
2605 		--i;	/* Structure begins with element 0 */
2606 	}
2607 
2608 	if (Table[i].systid == UNUSED) {
2609 		(void) printf(E_LINE);
2610 		(void) printf("Partition %d does not exist.", i + 1);
2611 		return (-1);
2612 	}
2613 
2614 	(void) printf(Q_LINE);
2615 	(void) printf("Are you sure you want to delete partition %d?"
2616 	    " This will make all files and \n", i + 1);
2617 	(void) printf("programs in this partition inaccessible (type"
2618 	    " \"y\" or \"n\"). ");
2619 
2620 	(void) printf(E_LINE);
2621 	if (! yesno()) {
2622 		return (1);
2623 	}
2624 
2625 	if (Table[i].bootid == ACTIVE) {
2626 		pactive = 1;
2627 	} else {
2628 		pactive = 0;
2629 	}
2630 
2631 	for (j = i; j < FD_NUMPART - 1; j++) {
2632 		Table[j] = Table[j + 1];
2633 	}
2634 
2635 	Table[j].systid = UNUSED;
2636 	Table[j].numsect = 0;
2637 	Table[j].relsect = 0;
2638 	Table[j].bootid = 0;
2639 	(void) printf(E_LINE);
2640 	(void) printf("Partition %d has been deleted.", i + 1);
2641 
2642 	if (pactive) {
2643 		(void) printf(" This was the active partition.");
2644 	}
2645 
2646 	return (1);
2647 }
2648 
2649 /*
2650  * rm_blanks
2651  * Remove blanks from strings of user responses.
2652  */
2653 static void
2654 rm_blanks(char *s)
2655 {
2656 	register int i, j;
2657 
2658 	for (i = 0; i < CBUFLEN; i++) {
2659 		if ((s[i] == ' ') || (s[i] == '\t'))
2660 			continue;
2661 		else
2662 			/* Found first non-blank character of the string */
2663 			break;
2664 	}
2665 	for (j = 0; i < CBUFLEN; j++, i++) {
2666 		if ((s[j] = s[i]) == '\0') {
2667 			/* Reached end of string */
2668 			return;
2669 		}
2670 	}
2671 }
2672 
2673 /*
2674  * getcyl
2675  * Take the user-specified cylinder number and convert it from a
2676  * string to a decimal value.
2677  */
2678 static int
2679 getcyl(void)
2680 {
2681 int slen, i, j;
2682 unsigned int cyl;
2683 	(void) gets(s);
2684 	rm_blanks(s);
2685 	slen = strlen(s);
2686 	j = 1;
2687 	cyl = 0;
2688 	for (i = slen - 1; i >= 0; i--) {
2689 		if (s[i] < '0' || s[i] > '9') {
2690 			return (-1);
2691 		}
2692 		cyl += (j * (s[i] - '0'));
2693 		j *= 10;
2694 	}
2695 	return (cyl);
2696 }
2697 
2698 /*
2699  * disptbl
2700  * Display the current fdisk table; determine percentage
2701  * of the disk used for each partition.
2702  */
2703 static void
2704 disptbl(void)
2705 {
2706 	int i;
2707 	unsigned int startcyl, endcyl, length, percent, remainder;
2708 	char *stat, *type;
2709 	int is_pmbr = 0;
2710 
2711 	if ((heads == 0) || (sectors == 0)) {
2712 		(void) printf("WARNING: critical disk geometry information"
2713 		    " missing!\n");
2714 		(void) printf("\theads = %d, sectors = %d\n", heads, sectors);
2715 		exit(1);
2716 	}
2717 
2718 	(void) printf(HOME);
2719 	(void) printf(T_LINE);
2720 	(void) printf("             Total disk size is %d cylinders\n", Numcyl);
2721 	(void) printf("             Cylinder size is %d (512 byte) blocks\n\n",
2722 	    heads * sectors);
2723 	(void) printf(
2724 	    "                                               Cylinders\n");
2725 	(void) printf(
2726 	    "      Partition   Status    Type          Start   End   Length"
2727 	    "    %%\n");
2728 	(void) printf(
2729 	    "      =========   ======    ============  =====   ===   ======"
2730 	    "   ===");
2731 	for (i = 0; i < FD_NUMPART; i++) {
2732 		if (Table[i].systid == UNUSED) {
2733 			(void) printf("\n");
2734 			(void) printf(CLR_LIN);
2735 			continue;
2736 		}
2737 		if (Table[i].bootid == ACTIVE)
2738 			stat = Actvstr;
2739 		else
2740 			stat = NAstr;
2741 		switch (Table[i].systid) {
2742 		case UNIXOS:
2743 			type = Ustr;
2744 			break;
2745 		case SUNIXOS:
2746 			type = SUstr;
2747 			break;
2748 		case SUNIXOS2:
2749 			type = SU2str;
2750 			break;
2751 		case X86BOOT:
2752 			type = X86str;
2753 			break;
2754 		case DOSOS12:
2755 			type = Dstr;
2756 			break;
2757 		case DOSOS16:
2758 			type = D16str;
2759 			break;
2760 		case EXTDOS:
2761 			type = EDstr;
2762 			break;
2763 		case DOSDATA:
2764 			type = DDstr;
2765 			break;
2766 		case DOSHUGE:
2767 			type = DBstr;
2768 			break;
2769 		case PCIXOS:
2770 			type = PCstr;
2771 			break;
2772 		case DIAGPART:
2773 			type = DIAGstr;
2774 			break;
2775 		case FDISK_IFS:
2776 			type = IFSstr;
2777 			break;
2778 		case FDISK_AIXBOOT:
2779 			type = AIXstr;
2780 			break;
2781 		case FDISK_AIXDATA:
2782 			type = AIXDstr;
2783 			break;
2784 		case FDISK_OS2BOOT:
2785 			type = OS2str;
2786 			break;
2787 		case FDISK_WINDOWS:
2788 			type = WINstr;
2789 			break;
2790 		case FDISK_EXT_WIN:
2791 			type = EWINstr;
2792 			break;
2793 		case FDISK_FAT95:
2794 			type = FAT95str;
2795 			break;
2796 		case FDISK_EXTLBA:
2797 			type = EXTLstr;
2798 			break;
2799 		case FDISK_LINUX:
2800 			type = LINUXstr;
2801 			break;
2802 		case FDISK_CPM:
2803 			type = CPMstr;
2804 			break;
2805 		case FDISK_NOVELL3:
2806 			type = NOVstr;
2807 			break;
2808 		case FDISK_QNX4:
2809 			type = QNXstr;
2810 			break;
2811 		case FDISK_QNX42:
2812 			type = QNX2str;
2813 			break;
2814 		case FDISK_QNX43:
2815 			type = QNX3str;
2816 			break;
2817 		case FDISK_LINUXNAT:
2818 			type = LINNATstr;
2819 			break;
2820 		case FDISK_NTFSVOL1:
2821 			type = NTFSVOL1str;
2822 			break;
2823 		case FDISK_NTFSVOL2:
2824 			type = NTFSVOL2str;
2825 			break;
2826 		case FDISK_BSD:
2827 			type = BSDstr;
2828 			break;
2829 		case FDISK_NEXTSTEP:
2830 			type = NEXTSTEPstr;
2831 			break;
2832 		case FDISK_BSDIFS:
2833 			type = BSDIFSstr;
2834 			break;
2835 		case FDISK_BSDISWAP:
2836 			type = BSDISWAPstr;
2837 			break;
2838 		case EFI_PMBR:
2839 			type = EFIstr;
2840 			if (lel(Table[i].numsect) == DK_MAX_2TB)
2841 				is_pmbr = 1;
2842 
2843 			break;
2844 		default:
2845 			type = Ostr;
2846 			break;
2847 		}
2848 		startcyl = lel(Table[i].relsect) /
2849 		    (unsigned long)(heads * sectors);
2850 
2851 		if (lel(Table[i].numsect) == DK_MAX_2TB) {
2852 			endcyl = Numcyl - 1;
2853 			length = endcyl - startcyl + 1;
2854 		} else {
2855 			length = lel(Table[i].numsect) /
2856 			    (unsigned long)(heads * sectors);
2857 			if (lel(Table[i].numsect) %
2858 			    (unsigned long)(heads * sectors))
2859 				length++;
2860 			endcyl = startcyl + length - 1;
2861 		}
2862 
2863 		percent = length * 100 / Numcyl_usable;
2864 		if ((remainder = (length * 100 % Numcyl_usable)) != 0) {
2865 			if ((remainder * 100 / Numcyl_usable) > 50) {
2866 				/* round up */
2867 				percent++;
2868 			}
2869 			/* Else leave the percent as is since it's already */
2870 			/* rounded down */
2871 		}
2872 		if (percent > 100)
2873 			percent = 100;
2874 		(void) printf(
2875 		    "\n          %d       %s    %-12.12s   %4d  %4d    %4d"
2876 		    "    %3d",
2877 		    i + 1, stat, type, startcyl, endcyl, length, percent);
2878 	}
2879 
2880 	/* Print warning message if table is empty */
2881 	if (Table[0].systid == UNUSED) {
2882 		(void) printf(W_LINE);
2883 		(void) printf("WARNING: no partitions are defined!");
2884 	} else {
2885 		/* Clear the warning line */
2886 		(void) printf(W_LINE);
2887 
2888 		/* Print warning if disk > 2TB and is not EFI PMBR */
2889 		if (!is_pmbr && (dev_capacity > DK_MAX_2TB))
2890 			(void) printf("WARNING: Disk is larger than 2 TB. "
2891 			    "Upper limit is 2 TB for non-EFI partition ID\n");
2892 	}
2893 }
2894 
2895 /*
2896  * print_Table
2897  * Write the detailed fdisk table to standard error for
2898  * the selected disk device.
2899  */
2900 static void
2901 print_Table(void)
2902 {
2903 	int i;
2904 
2905 	(void) fprintf(stderr,
2906 	    "  SYSID ACT BHEAD BSECT BEGCYL   EHEAD ESECT ENDCYL   RELSECT"
2907 	    "   NUMSECT\n");
2908 
2909 	for (i = 0; i < FD_NUMPART; i++) {
2910 		(void) fprintf(stderr, "  %-5d ", Table[i].systid);
2911 		(void) fprintf(stderr, "%-3d ", Table[i].bootid);
2912 		(void) fprintf(stderr, "%-5d ", Table[i].beghead);
2913 		(void) fprintf(stderr, "%-5d ", Table[i].begsect & 0x3f);
2914 		(void) fprintf(stderr, "%-8d ",
2915 		    (((uint_t)Table[i].begsect & 0xc0) << 2) + Table[i].begcyl);
2916 
2917 		(void) fprintf(stderr, "%-5d ", Table[i].endhead);
2918 		(void) fprintf(stderr, "%-5d ", Table[i].endsect & 0x3f);
2919 		(void) fprintf(stderr, "%-8d ",
2920 		    (((uint_t)Table[i].endsect & 0xc0) << 2) + Table[i].endcyl);
2921 		(void) fprintf(stderr, "%-10u ", lel(Table[i].relsect));
2922 		(void) fprintf(stderr, "%-10u\n", lel(Table[i].numsect));
2923 
2924 	}
2925 }
2926 
2927 /*
2928  * copy_Table_to_Old_Table
2929  * Copy Table into Old_Table. The function only copies the systid,
2930  * numsect, relsect, and bootid values because they are the only
2931  * ones compared when determining if Table has changed.
2932  */
2933 static void
2934 copy_Table_to_Old_Table(void)
2935 {
2936 	int i;
2937 	for (i = 0; i < FD_NUMPART; i++)  {
2938 		(void) memcpy(&Old_Table[i], &Table[i], sizeof (Table[0]));
2939 	}
2940 }
2941 
2942 /*
2943  * nulltbl
2944  * Zero out the systid, numsect, relsect, and bootid values in the
2945  * fdisk table.
2946  */
2947 static void
2948 nulltbl(void)
2949 {
2950 	int i;
2951 
2952 	for (i = 0; i < FD_NUMPART; i++)  {
2953 		Table[i].systid = UNUSED;
2954 		Table[i].numsect = lel(UNUSED);
2955 		Table[i].relsect = lel(UNUSED);
2956 		Table[i].bootid = 0;
2957 	}
2958 }
2959 
2960 /*
2961  * copy_Bootblk_to_Table
2962  * Copy the bytes from the boot record to an internal "Table".
2963  * All unused are padded with zeros starting at offset 446.
2964  */
2965 static void
2966 copy_Bootblk_to_Table(void)
2967 {
2968 	int i, j;
2969 	char *bootptr;
2970 	struct ipart iparts[FD_NUMPART];
2971 
2972 	/* Get an aligned copy of the partition tables */
2973 	(void) memcpy(iparts, Bootblk->parts, sizeof (iparts));
2974 	bootptr = (char *)iparts;	/* Points to start of partition table */
2975 	if (les(Bootblk->signature) != MBB_MAGIC)  {
2976 		/* Signature is missing */
2977 		nulltbl();
2978 		(void) memcpy(Bootblk->bootinst, &BootCod, BOOTSZ);
2979 		return;
2980 	}
2981 	/*
2982 	 * When the DOS fdisk command deletes a partition, it is not
2983 	 * recognized by the old algorithm.  The algorithm that
2984 	 * follows looks at each entry in the Bootrec and copies all
2985 	 * those that are valid.
2986 	 */
2987 	j = 0;
2988 	for (i = 0; i < FD_NUMPART; i++) {
2989 		if (iparts[i].systid == 0) {
2990 			/* Null entry */
2991 			bootptr += sizeof (struct ipart);
2992 		} else {
2993 			fill_ipart(bootptr, &Table[j]);
2994 			j++;
2995 			bootptr += sizeof (struct ipart);
2996 		}
2997 	}
2998 	for (i = j; i < FD_NUMPART; i++) {
2999 		Table[i].systid = UNUSED;
3000 		Table[i].numsect = lel(UNUSED);
3001 		Table[i].relsect = lel(UNUSED);
3002 		Table[i].bootid = 0;
3003 
3004 	}
3005 	/* For now, always replace the bootcode with ours */
3006 	(void) memcpy(Bootblk->bootinst, &BootCod, BOOTSZ);
3007 	copy_Table_to_Bootblk();
3008 }
3009 
3010 /*
3011  * fill_ipart
3012  * Initialize ipart structure values.
3013  */
3014 static void
3015 fill_ipart(char *bootptr, struct ipart *partp)
3016 {
3017 #ifdef sparc
3018 	/* Packing struct ipart for Sparc */
3019 	partp->bootid	= getbyte(&bootptr);
3020 	partp->beghead	= getbyte(&bootptr);
3021 	partp->begsect	= getbyte(&bootptr);
3022 	partp->begcyl	= getbyte(&bootptr);
3023 	partp->systid	= getbyte(&bootptr);
3024 	partp->endhead	= getbyte(&bootptr);
3025 	partp->endsect	= getbyte(&bootptr);
3026 	partp->endcyl	= getbyte(&bootptr);
3027 	partp->relsect	= (int32_t)getlong(&bootptr);
3028 	partp->numsect	= (int32_t)getlong(&bootptr);
3029 #else
3030 	*partp = *(struct ipart *)bootptr;
3031 #endif
3032 }
3033 
3034 /*
3035  * getbyte, getlong
3036  * 	Get a byte, a short, or a long (SPARC only).
3037  */
3038 #ifdef sparc
3039 uchar_t
3040 getbyte(char **bp)
3041 {
3042 	uchar_t	b;
3043 
3044 	b = (uchar_t)**bp;
3045 	*bp = *bp + 1;
3046 	return (b);
3047 }
3048 
3049 uint32_t
3050 getlong(char **bp)
3051 {
3052 	int32_t	b, bh, bl;
3053 
3054 	bh = ((**bp) << 8) | *(*bp + 1);
3055 	*bp += 2;
3056 	bl = ((**bp) << 8) | *(*bp + 1);
3057 	*bp += 2;
3058 
3059 	b = (bh << 16) | bl;
3060 	return ((uint32_t)b);
3061 }
3062 #endif
3063 
3064 /*
3065  * copy_Table_to_Bootblk
3066  * Copy the table into the 512 boot record. Note that the unused
3067  * entries will always be the last ones in the table and they are
3068  * marked with 100 in sysind. The the unused portion of the table
3069  * is padded with zeros in the bytes after the used entries.
3070  */
3071 static void
3072 copy_Table_to_Bootblk(void)
3073 {
3074 	struct ipart *boot_ptr, *tbl_ptr;
3075 
3076 	boot_ptr = (struct ipart *)Bootblk->parts;
3077 	tbl_ptr = (struct ipart *)&Table[0].bootid;
3078 	for (; tbl_ptr < (struct ipart *)&Table[FD_NUMPART].bootid;
3079 	    tbl_ptr++, boot_ptr++) {
3080 		if (tbl_ptr->systid == UNUSED)
3081 			(void) memset(boot_ptr, 0, sizeof (struct ipart));
3082 		else
3083 			(void) memcpy(boot_ptr, tbl_ptr, sizeof (struct ipart));
3084 	}
3085 	Bootblk->signature = les(MBB_MAGIC);
3086 }
3087 
3088 /*
3089  * TableChanged
3090  * 	Check for any changes in the partition table.
3091  */
3092 static int
3093 TableChanged(void)
3094 {
3095 	int i, changed;
3096 
3097 	changed = 0;
3098 	for (i = 0; i < FD_NUMPART; i++) {
3099 		if (memcmp(&Old_Table[i], &Table[i], sizeof (Table[0])) != 0) {
3100 			/* Partition table changed, write back to disk */
3101 			changed = 1;
3102 		}
3103 	}
3104 
3105 	return (changed);
3106 }
3107 
3108 /*
3109  * ffile_write
3110  * 	Display contents of partition table to standard output or
3111  *	another file name without writing it to the disk (-W file).
3112  */
3113 static void
3114 ffile_write(char *file)
3115 {
3116 	register int	i;
3117 	FILE *fp;
3118 
3119 	/*
3120 	 * If file isn't standard output, then it's a file name.
3121 	 * Open file and write it.
3122 	 */
3123 	if (file != (char *)stdout) {
3124 		if ((fp = fopen(file, "w")) == NULL) {
3125 			(void) fprintf(stderr,
3126 			    "fdisk: Cannot open output file %s.\n",
3127 			    file);
3128 			exit(1);
3129 		}
3130 	}
3131 	else
3132 		fp = stdout;
3133 
3134 	/*
3135 	 * Write the fdisk table information
3136 	 */
3137 	(void) fprintf(fp, "\n* %s default fdisk table\n", Dfltdev);
3138 	(void) fprintf(fp, "* Dimensions:\n");
3139 	(void) fprintf(fp, "*   %4d bytes/sector\n", sectsiz);
3140 	(void) fprintf(fp, "*   %4d sectors/track\n", sectors);
3141 	(void) fprintf(fp, "*   %4d tracks/cylinder\n", heads);
3142 	(void) fprintf(fp, "*   %4d cylinders\n", Numcyl);
3143 	(void) fprintf(fp, "*\n");
3144 	/* Write virtual (HBA) geometry, if required	*/
3145 	if (v_flag) {
3146 		(void) fprintf(fp, "* HBA Dimensions:\n");
3147 		(void) fprintf(fp, "*   %4d bytes/sector\n", sectsiz);
3148 		(void) fprintf(fp, "*   %4d sectors/track\n", hba_sectors);
3149 		(void) fprintf(fp, "*   %4d tracks/cylinder\n", hba_heads);
3150 		(void) fprintf(fp, "*   %4d cylinders\n", hba_Numcyl);
3151 		(void) fprintf(fp, "*\n");
3152 	}
3153 	(void) fprintf(fp, "* systid:\n");
3154 	(void) fprintf(fp, "*    1: DOSOS12\n");
3155 	(void) fprintf(fp, "*    2: PCIXOS\n");
3156 	(void) fprintf(fp, "*    4: DOSOS16\n");
3157 	(void) fprintf(fp, "*    5: EXTDOS\n");
3158 	(void) fprintf(fp, "*    6: DOSBIG\n");
3159 	(void) fprintf(fp, "*    7: FDISK_IFS\n");
3160 	(void) fprintf(fp, "*    8: FDISK_AIXBOOT\n");
3161 	(void) fprintf(fp, "*    9: FDISK_AIXDATA\n");
3162 	(void) fprintf(fp, "*   10: FDISK_0S2BOOT\n");
3163 	(void) fprintf(fp, "*   11: FDISK_WINDOWS\n");
3164 	(void) fprintf(fp, "*   12: FDISK_EXT_WIN\n");
3165 	(void) fprintf(fp, "*   14: FDISK_FAT95\n");
3166 	(void) fprintf(fp, "*   15: FDISK_EXTLBA\n");
3167 	(void) fprintf(fp, "*   18: DIAGPART\n");
3168 	(void) fprintf(fp, "*   65: FDISK_LINUX\n");
3169 	(void) fprintf(fp, "*   82: FDISK_CPM\n");
3170 	(void) fprintf(fp, "*   86: DOSDATA\n");
3171 	(void) fprintf(fp, "*   98: OTHEROS\n");
3172 	(void) fprintf(fp, "*   99: UNIXOS\n");
3173 	(void) fprintf(fp, "*  101: FDISK_NOVELL3\n");
3174 	(void) fprintf(fp, "*  119: FDISK_QNX4\n");
3175 	(void) fprintf(fp, "*  120: FDISK_QNX42\n");
3176 	(void) fprintf(fp, "*  121: FDISK_QNX43\n");
3177 	(void) fprintf(fp, "*  130: SUNIXOS\n");
3178 	(void) fprintf(fp, "*  131: FDISK_LINUXNAT\n");
3179 	(void) fprintf(fp, "*  134: FDISK_NTFSVOL1\n");
3180 	(void) fprintf(fp, "*  135: FDISK_NTFSVOL2\n");
3181 	(void) fprintf(fp, "*  165: FDISK_BSD\n");
3182 	(void) fprintf(fp, "*  167: FDISK_NEXTSTEP\n");
3183 	(void) fprintf(fp, "*  183: FDISK_BSDIFS\n");
3184 	(void) fprintf(fp, "*  184: FDISK_BSDISWAP\n");
3185 	(void) fprintf(fp, "*  190: X86BOOT\n");
3186 	(void) fprintf(fp, "*  191: SUNIXOS2\n");
3187 	(void) fprintf(fp, "*  238: EFI_PMBR\n");
3188 	(void) fprintf(fp, "*  239: EFI_FS\n");
3189 	(void) fprintf(fp, "*\n");
3190 	(void) fprintf(fp,
3191 	    "\n* Id    Act  Bhead  Bsect  Bcyl    Ehead  Esect  Ecyl"
3192 	    "    Rsect      Numsect\n");
3193 
3194 	for (i = 0; i < FD_NUMPART; i++) {
3195 		if (Table[i].systid != UNUSED)
3196 			(void) fprintf(fp,
3197 			    "  %-5d %-4d %-6d %-6d %-7d %-6d %-6d %-7d %-10u"
3198 			    " %-10u\n",
3199 			    Table[i].systid,
3200 			    Table[i].bootid,
3201 			    Table[i].beghead,
3202 			    Table[i].begsect & 0x3f,
3203 			    ((Table[i].begcyl & 0xff) | ((Table[i].begsect &
3204 			    0xc0) << 2)),
3205 			    Table[i].endhead,
3206 			    Table[i].endsect & 0x3f,
3207 			    ((Table[i].endcyl & 0xff) | ((Table[i].endsect &
3208 			    0xc0) << 2)),
3209 			    lel(Table[i].relsect),
3210 			    lel(Table[i].numsect));
3211 	}
3212 	if (fp != stdout)
3213 		(void) fclose(fp);
3214 }
3215 
3216 /*
3217  * fix_slice
3218  * 	Read the VTOC table on the Solaris partition and check that no
3219  *	slices exist that extend past the end of the Solaris partition.
3220  *	If no Solaris partition exists, nothing is done.
3221  */
3222 static void
3223 fix_slice(void)
3224 {
3225 	int	i;
3226 	uint32_t	numsect;
3227 
3228 	if (io_image) {
3229 		return;
3230 	}
3231 
3232 	for (i = 0; i < FD_NUMPART; i++) {
3233 		if (Table[i].systid == SUNIXOS || Table[i].systid == SUNIXOS2) {
3234 			/*
3235 			 * Only the size matters (not starting point), since
3236 			 * VTOC entries are relative to the start of
3237 			 * the partition.
3238 			 */
3239 			numsect = lel(Table[i].numsect);
3240 			break;
3241 		}
3242 	}
3243 
3244 	if (i >= FD_NUMPART) {
3245 		if (!io_nifdisk) {
3246 			(void) fprintf(stderr,
3247 			    "fdisk: No Solaris partition found - VTOC not"
3248 			    " checked.\n");
3249 		}
3250 		return;
3251 	}
3252 
3253 	if (readvtoc() != VTOC_OK) {
3254 		exit(1);		/* Failed to read the VTOC */
3255 	}
3256 	for (i = 0; i < V_NUMPAR; i++) {
3257 		/* Special case for slice two (entire disk) */
3258 		if (i == 2) {
3259 			if (disk_vtoc.v_part[i].p_start != 0) {
3260 				(void) fprintf(stderr,
3261 				    "slice %d starts at %llu, is not at"
3262 				    " start of partition",
3263 				    i, disk_vtoc.v_part[i].p_start);
3264 				if (!io_nifdisk) {
3265 					(void) printf(" adjust ?:");
3266 					if (yesno())
3267 						disk_vtoc.v_part[i].p_start = 0;
3268 				} else {
3269 					disk_vtoc.v_part[i].p_start = 0;
3270 					(void) fprintf(stderr, " adjusted!\n");
3271 				}
3272 
3273 			}
3274 			if (disk_vtoc.v_part[i].p_size != numsect) {
3275 				(void) fprintf(stderr,
3276 				    "slice %d size %llu does not cover"
3277 				    " complete partition",
3278 				    i, disk_vtoc.v_part[i].p_size);
3279 				if (!io_nifdisk) {
3280 					(void) printf(" adjust ?:");
3281 					if (yesno())
3282 						disk_vtoc.v_part[i].p_size =
3283 						    numsect;
3284 				} else {
3285 					disk_vtoc.v_part[i].p_size = numsect;
3286 					(void) fprintf(stderr, " adjusted!\n");
3287 				}
3288 			}
3289 			if (disk_vtoc.v_part[i].p_tag != V_BACKUP) {
3290 				(void) fprintf(stderr,
3291 				    "slice %d tag was %d should be %d",
3292 				    i, disk_vtoc.v_part[i].p_tag,
3293 				    V_BACKUP);
3294 				if (!io_nifdisk) {
3295 					(void) printf(" fix ?:");
3296 					if (yesno())
3297 						disk_vtoc.v_part[i].p_tag =
3298 						    V_BACKUP;
3299 				} else {
3300 					disk_vtoc.v_part[i].p_tag = V_BACKUP;
3301 					(void) fprintf(stderr, " fixed!\n");
3302 				}
3303 			}
3304 			continue;
3305 		}
3306 		if (io_ADJT) {
3307 			if (disk_vtoc.v_part[i].p_start > numsect ||
3308 			    disk_vtoc.v_part[i].p_start +
3309 			    disk_vtoc.v_part[i].p_size > numsect) {
3310 				(void) fprintf(stderr,
3311 				    "slice %d (start %llu, end %llu)"
3312 				    " is larger than the partition",
3313 				    i, disk_vtoc.v_part[i].p_start,
3314 				    disk_vtoc.v_part[i].p_start +
3315 				    disk_vtoc.v_part[i].p_size);
3316 				if (!io_nifdisk) {
3317 					(void) printf(" remove ?:");
3318 					if (yesno()) {
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 					}
3324 				} else {
3325 					disk_vtoc.v_part[i].p_size = 0;
3326 					disk_vtoc.v_part[i].p_start = 0;
3327 					disk_vtoc.v_part[i].p_tag = 0;
3328 					disk_vtoc.v_part[i].p_flag = 0;
3329 					(void) fprintf(stderr,
3330 					    " removed!\n");
3331 				}
3332 			}
3333 			continue;
3334 		}
3335 		if (disk_vtoc.v_part[i].p_start > numsect) {
3336 			(void) fprintf(stderr,
3337 			    "slice %d (start %llu) is larger than the "
3338 			    "partition", i, disk_vtoc.v_part[i].p_start);
3339 			if (!io_nifdisk) {
3340 				(void) printf(" remove ?:");
3341 				if (yesno()) {
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 				}
3347 			} else {
3348 				disk_vtoc.v_part[i].p_size = 0;
3349 				disk_vtoc.v_part[i].p_start = 0;
3350 				disk_vtoc.v_part[i].p_tag = 0;
3351 				disk_vtoc.v_part[i].p_flag = 0;
3352 				(void) fprintf(stderr,
3353 				" removed!\n");
3354 			}
3355 		} else if (disk_vtoc.v_part[i].p_start
3356 		    + disk_vtoc.v_part[i].p_size > numsect) {
3357 			(void) fprintf(stderr,
3358 			    "slice %d (end %llu) is larger"
3359 			    " than the partition",
3360 			    i,
3361 			    disk_vtoc.v_part[i].p_start +
3362 			    disk_vtoc.v_part[i].p_size);
3363 			if (!io_nifdisk) {
3364 				(void) printf(" adjust ?:");
3365 				if (yesno()) {
3366 					disk_vtoc.v_part[i].p_size = numsect;
3367 				}
3368 			} else {
3369 				disk_vtoc.v_part[i].p_size = numsect;
3370 				(void) fprintf(stderr, " adjusted!\n");
3371 			}
3372 		}
3373 	}
3374 #if 1		/* bh for now */
3375 	/* Make the VTOC look sane - ha ha */
3376 	disk_vtoc.v_version = V_VERSION;
3377 	disk_vtoc.v_sanity = VTOC_SANE;
3378 	disk_vtoc.v_nparts = V_NUMPAR;
3379 	if (disk_vtoc.v_sectorsz == 0)
3380 		disk_vtoc.v_sectorsz = NBPSCTR;
3381 #endif
3382 
3383 	/* Write the VTOC back to the disk */
3384 	if (!io_readonly)
3385 		(void) writevtoc();
3386 }
3387 
3388 /*
3389  * yesno
3390  * Get yes or no answer. Return 1 for yes and 0 for no.
3391  */
3392 
3393 static int
3394 yesno(void)
3395 {
3396 	char	s[80];
3397 
3398 	for (;;) {
3399 		(void) gets(s);
3400 		rm_blanks(s);
3401 		if ((s[1] != 0) || ((s[0] != 'y') && (s[0] != 'n'))) {
3402 			(void) printf(E_LINE);
3403 			(void) printf("Please answer with \"y\" or \"n\": ");
3404 			continue;
3405 		}
3406 		if (s[0] == 'y')
3407 			return (1);
3408 		else
3409 			return (0);
3410 	}
3411 }
3412 
3413 /*
3414  * readvtoc
3415  * 	Read the VTOC from the Solaris partition of the device.
3416  */
3417 static int
3418 readvtoc(void)
3419 {
3420 	int	i;
3421 	int	retval = VTOC_OK;
3422 
3423 	if ((i = read_extvtoc(Dev, &disk_vtoc)) < VTOC_OK) {
3424 		if (i == VT_EINVAL) {
3425 			(void) fprintf(stderr, "fdisk: Invalid VTOC.\n");
3426 			vt_inval++;
3427 			retval = VTOC_INVAL;
3428 		} else if (i == VT_ENOTSUP) {
3429 			(void) fprintf(stderr, "fdisk: partition may have EFI "
3430 			    "GPT\n");
3431 			retval = VTOC_NOTSUP;
3432 		} else {
3433 			(void) fprintf(stderr, "fdisk: Cannot read VTOC.\n");
3434 			retval = VTOC_RWERR;
3435 		}
3436 	}
3437 	return (retval);
3438 }
3439 
3440 /*
3441  * writevtoc
3442  * 	Write the VTOC to the Solaris partition on the device.
3443  */
3444 static int
3445 writevtoc(void)
3446 {
3447 	int	i;
3448 	int	retval = 0;
3449 
3450 	if ((i = write_extvtoc(Dev, &disk_vtoc)) != 0) {
3451 		if (i == VT_EINVAL) {
3452 			(void) fprintf(stderr,
3453 			    "fdisk: Invalid entry exists in VTOC.\n");
3454 			retval = VTOC_INVAL;
3455 		} else if (i == VT_ENOTSUP) {
3456 			(void) fprintf(stderr, "fdisk: partition may have EFI "
3457 			    "GPT\n");
3458 			retval = VTOC_NOTSUP;
3459 		} else {
3460 			(void) fprintf(stderr, "fdisk: Cannot write VTOC.\n");
3461 			retval = VTOC_RWERR;
3462 		}
3463 	}
3464 	return (retval);
3465 }
3466 
3467 /*
3468  * efi_ioctl
3469  * issues DKIOCSETEFI IOCTL
3470  * (duplicate of private efi_ioctl() in rdwr_efi.c
3471  */
3472 static int
3473 efi_ioctl(int fd, int cmd, dk_efi_t *dk_ioc)
3474 {
3475 	void *data = dk_ioc->dki_data;
3476 	int error;
3477 
3478 	dk_ioc->dki_data_64 = (uintptr_t)data;
3479 	error = ioctl(fd, cmd, (void *)dk_ioc);
3480 
3481 	return (error);
3482 }
3483 
3484 /*
3485  * clear_efi
3486  * Clear EFI labels from the EFI_PMBR partition on the device
3487  * This function is modeled on the libefi(3LIB) call efi_write()
3488  */
3489 static int
3490 clear_efi(void)
3491 {
3492 	struct dk_gpt	*efi_vtoc;
3493 	dk_efi_t	dk_ioc;
3494 
3495 	/*
3496 	 * see if we can read the EFI label
3497 	 */
3498 	if (efi_alloc_and_read(Dev, &efi_vtoc) < 0) {
3499 		return (VT_ERROR);
3500 	}
3501 
3502 	/*
3503 	 * set up the dk_ioc structure for writing
3504 	 */
3505 	dk_ioc.dki_lba = 1;
3506 	dk_ioc.dki_length = EFI_MIN_ARRAY_SIZE + efi_vtoc->efi_lbasize;
3507 
3508 	if ((dk_ioc.dki_data = calloc(dk_ioc.dki_length, 1)) == NULL) {
3509 		return (VT_ERROR);
3510 	}
3511 
3512 	/*
3513 	 * clear the primary label
3514 	 */
3515 	if (io_debug) {
3516 		(void) fprintf(stderr,
3517 		    "\tClearing primary EFI label at block %lld\n",
3518 		    dk_ioc.dki_lba);
3519 	}
3520 
3521 	if (efi_ioctl(Dev, DKIOCSETEFI, &dk_ioc) == -1) {
3522 		free(dk_ioc.dki_data);
3523 		switch (errno) {
3524 			case EIO:
3525 				return (VT_EIO);
3526 			case EINVAL:
3527 				return (VT_EINVAL);
3528 			default:
3529 				return (VT_ERROR);
3530 		}
3531 	}
3532 
3533 	/*
3534 	 * clear the backup partition table
3535 	 */
3536 	dk_ioc.dki_lba = efi_vtoc->efi_last_u_lba + 1;
3537 	dk_ioc.dki_length -= efi_vtoc->efi_lbasize;
3538 	dk_ioc.dki_data++;
3539 	if (io_debug) {
3540 		(void) fprintf(stderr,
3541 		    "\tClearing backup partition table at block %lld\n",
3542 		    dk_ioc.dki_lba);
3543 	}
3544 
3545 	if (efi_ioctl(Dev, DKIOCSETEFI, &dk_ioc) == -1) {
3546 		(void) fprintf(stderr, "\tUnable to clear backup EFI label at "
3547 		    "block %llu; errno %d\n", efi_vtoc->efi_last_u_lba + 1,
3548 		    errno);
3549 	}
3550 
3551 	/*
3552 	 * clear the backup label
3553 	 */
3554 	dk_ioc.dki_lba = efi_vtoc->efi_last_lba;
3555 	dk_ioc.dki_length = efi_vtoc->efi_lbasize;
3556 	dk_ioc.dki_data--;
3557 	if (io_debug) {
3558 		(void) fprintf(stderr, "\tClearing backup label at block "
3559 		    "%lld\n", dk_ioc.dki_lba);
3560 	}
3561 
3562 	if (efi_ioctl(Dev, DKIOCSETEFI, &dk_ioc) == -1) {
3563 		(void) fprintf(stderr,
3564 		    "\tUnable to clear backup EFI label at "
3565 		    "block %llu; errno %d\n",
3566 		    efi_vtoc->efi_last_lba,
3567 		    errno);
3568 	}
3569 
3570 	free(dk_ioc.dki_data);
3571 	efi_free(efi_vtoc);
3572 
3573 	return (0);
3574 }
3575 
3576 /*
3577  * clear_vtoc
3578  * 	Clear the VTOC from the current or previous Solaris partition on the
3579  *      device.
3580  */
3581 static void
3582 clear_vtoc(int table, int part)
3583 {
3584 	struct ipart *clr_table;
3585 	struct dk_label disk_label;
3586 	uint32_t pcyl, ncyl, count;
3587 	diskaddr_t backup_block, solaris_offset;
3588 	ssize_t bytes;
3589 	off_t seek_byte;
3590 
3591 #ifdef DEBUG
3592 	struct dk_label	read_label;
3593 #endif /* DEBUG */
3594 
3595 	if (table == OLD) {
3596 		clr_table = &Old_Table[part];
3597 	} else {
3598 		clr_table = &Table[part];
3599 	}
3600 
3601 	(void) memset(&disk_label, 0, sizeof (struct dk_label));
3602 
3603 	seek_byte = (off_t)(lel(clr_table->relsect) + VTOC_OFFSET) * sectsiz;
3604 
3605 	if (io_debug) {
3606 		(void) fprintf(stderr,
3607 		    "\tClearing primary VTOC at byte %llu (block %llu)\n",
3608 		    (uint64_t)seek_byte,
3609 		    (uint64_t)(lel(clr_table->relsect) + VTOC_OFFSET));
3610 	}
3611 
3612 	if (lseek(Dev, seek_byte, SEEK_SET) == -1) {
3613 		(void) fprintf(stderr,
3614 		    "\tError seeking to primary label at byte %llu\n",
3615 		    (uint64_t)seek_byte);
3616 		return;
3617 	}
3618 
3619 	bytes = write(Dev, &disk_label, sizeof (struct dk_label));
3620 
3621 	if (bytes != sizeof (struct dk_label)) {
3622 		(void) fprintf(stderr,
3623 		    "\tWarning: only %d bytes written to clear primary"
3624 		    " VTOC!\n", bytes);
3625 	}
3626 
3627 #ifdef DEBUG
3628 	if (lseek(Dev, seek_byte, SEEK_SET) == -1) {
3629 		(void) fprintf(stderr,
3630 		    "DEBUG: Error seeking to primary label at byte %llu\n",
3631 		    (uint64_t)seek_byte);
3632 		return;
3633 	} else {
3634 		(void) fprintf(stderr,
3635 		    "DEBUG: Successful lseek() to byte %llu\n",
3636 		    (uint64_t)seek_byte);
3637 	}
3638 
3639 	bytes = read(Dev, &read_label, sizeof (struct dk_label));
3640 
3641 	if (bytes != sizeof (struct dk_label)) {
3642 		(void) fprintf(stderr,
3643 		    "DEBUG: Warning: only %d bytes read of label\n",
3644 		    bytes);
3645 	}
3646 
3647 	if (memcmp(&disk_label, &read_label, sizeof (struct dk_label)) != 0) {
3648 		(void) fprintf(stderr,
3649 		    "DEBUG: Warning: disk_label and read_label differ!!!\n");
3650 	} else {
3651 		(void) fprintf(stderr, "DEBUG Good compare of disk_label and "
3652 		    "read_label\n");
3653 	}
3654 #endif /* DEBUG */
3655 
3656 	/* Clear backup label */
3657 	pcyl = lel(clr_table->numsect) / (heads * sectors);
3658 	solaris_offset = lel(clr_table->relsect);
3659 	ncyl = pcyl - acyl;
3660 
3661 	backup_block = ((ncyl + acyl - 1) *
3662 	    (heads * sectors)) + ((heads - 1) * sectors) + 1;
3663 
3664 	for (count = 1; count < 6; count++) {
3665 		seek_byte = (off_t)(solaris_offset + backup_block) * 512;
3666 
3667 		if (lseek(Dev, seek_byte, SEEK_SET) == -1) {
3668 			(void) fprintf(stderr,
3669 			    "\tError seeking to backup label at byte %llu on "
3670 			    "%s.\n", (uint64_t)seek_byte, Dfltdev);
3671 			return;
3672 		}
3673 
3674 		if (io_debug) {
3675 			(void) fprintf(stderr, "\tClearing backup VTOC at"
3676 			    " byte %llu (block %llu)\n",
3677 			    (uint64_t)seek_byte,
3678 			    (uint64_t)(solaris_offset + backup_block));
3679 		}
3680 
3681 		bytes = write(Dev, &disk_label, sizeof (struct dk_label));
3682 
3683 		if (bytes != sizeof (struct dk_label)) {
3684 			(void) fprintf(stderr,
3685 			    "\t\tWarning: only %d bytes written to "
3686 			    "clear backup VTOC at block %llu!\n", bytes,
3687 			    (uint64_t)(solaris_offset + backup_block));
3688 		}
3689 
3690 #ifdef DEBUG
3691 	if (lseek(Dev, seek_byte, SEEK_SET) == -1) {
3692 		(void) fprintf(stderr,
3693 		    "DEBUG: Error seeking to backup label at byte %llu\n",
3694 		    (uint64_t)seek_byte);
3695 		return;
3696 	} else {
3697 		(void) fprintf(stderr,
3698 		    "DEBUG: Successful lseek() to byte %llu\n",
3699 		    (uint64_t)seek_byte);
3700 	}
3701 
3702 	bytes = read(Dev, &read_label, sizeof (struct dk_label));
3703 
3704 	if (bytes != sizeof (struct dk_label)) {
3705 		(void) fprintf(stderr,
3706 		    "DEBUG: Warning: only %d bytes read of backup label\n",
3707 		    bytes);
3708 	}
3709 
3710 	if (memcmp(&disk_label, &read_label, sizeof (struct dk_label)) != 0) {
3711 		(void) fprintf(stderr,
3712 		    "DEBUG: Warning: disk_label and read_label differ!!!\n");
3713 	} else {
3714 		(void) fprintf(stderr,
3715 		    "DEBUG: Good compare of disk_label and backup "
3716 		    "read_label\n");
3717 	}
3718 #endif /* DEBUG */
3719 
3720 		backup_block += 2;
3721 	}
3722 }
3723 
3724 #define	FDISK_STANDARD_LECTURE \
3725 	"Fdisk is normally used with the device that " \
3726 	"represents the entire fixed disk.\n" \
3727 	"(For example, /dev/rdsk/c0d0p0 on x86 or " \
3728 	"/dev/rdsk/c0t5d0s2 on sparc).\n"
3729 
3730 #define	FDISK_LECTURE_NOT_SECTOR_ZERO \
3731 	"The device does not appear to include absolute\n" \
3732 	"sector 0 of the PHYSICAL disk " \
3733 	"(the normal location for an fdisk table).\n"
3734 
3735 #define	FDISK_LECTURE_NOT_FULL \
3736 	"The device does not appear to encompass the entire PHYSICAL disk.\n"
3737 
3738 #define	FDISK_LECTURE_NO_VTOC \
3739 	"Unable to find a volume table of contents.\n" \
3740 	"Cannot verify the device encompasses the full PHYSICAL disk.\n"
3741 
3742 #define	FDISK_LECTURE_NO_GEOM \
3743 	"Unable to get geometry from device.\n" \
3744 	"Cannot verify the device encompasses the full PHYSICAL disk.\n"
3745 
3746 #define	FDISK_SHALL_I_CONTINUE \
3747 	"Are you sure you want to continue? (y/n) "
3748 
3749 /*
3750  *  lecture_and_query
3751  *	Called when a sanity check fails.  This routine gives a warning
3752  *	specific to the check that fails, followed by a generic lecture
3753  *	about the "right" device to supply as input.  Then, if appropriate,
3754  *	it will prompt the user on whether or not they want to continue.
3755  *	Inappropriate times for prompting are when the user has selected
3756  *	non-interactive mode or read-only mode.
3757  */
3758 static int
3759 lecture_and_query(char *warning, char *devname)
3760 {
3761 	if (io_nifdisk)
3762 		return (0);
3763 
3764 	(void) fprintf(stderr, "WARNING: Device %s: \n", devname);
3765 	(void) fprintf(stderr, "%s", warning);
3766 	(void) fprintf(stderr, FDISK_STANDARD_LECTURE);
3767 	(void) fprintf(stderr, FDISK_SHALL_I_CONTINUE);
3768 
3769 	return (yesno());
3770 }
3771 
3772 static void
3773 sanity_check_provided_device(char *devname, int fd)
3774 {
3775 	struct extvtoc v;
3776 	struct dk_geom d;
3777 	struct part_info pi;
3778 	struct extpart_info extpi;
3779 	diskaddr_t totsize;
3780 	int idx = -1;
3781 
3782 	/*
3783 	 *  First try the PARTINFO ioctl.  If it works, we will be able
3784 	 *  to tell if they've specified the full disk partition by checking
3785 	 *  to see if they've specified a partition that starts at sector 0.
3786 	 */
3787 	if (ioctl(fd, DKIOCEXTPARTINFO, &extpi) != -1) {
3788 		if (extpi.p_start != 0) {
3789 			if (!lecture_and_query(FDISK_LECTURE_NOT_SECTOR_ZERO,
3790 			    devname)) {
3791 				(void) close(fd);
3792 				exit(1);
3793 			}
3794 		}
3795 	} else if (ioctl(fd, DKIOCPARTINFO, &pi) != -1) {
3796 		if (pi.p_start != 0) {
3797 			if (!lecture_and_query(FDISK_LECTURE_NOT_SECTOR_ZERO,
3798 			    devname)) {
3799 				(void) close(fd);
3800 				exit(1);
3801 			}
3802 		}
3803 	} else {
3804 		if ((idx = read_extvtoc(fd, &v)) < 0) {
3805 			if (!lecture_and_query(FDISK_LECTURE_NO_VTOC,
3806 			    devname)) {
3807 				(void) close(fd);
3808 				exit(1);
3809 			}
3810 			return;
3811 		}
3812 		if (ioctl(fd, DKIOCGGEOM, &d) == -1) {
3813 			perror(devname);
3814 			if (!lecture_and_query(FDISK_LECTURE_NO_GEOM,
3815 			    devname)) {
3816 				(void) close(fd);
3817 				exit(1);
3818 			}
3819 			return;
3820 		}
3821 		totsize = (diskaddr_t)d.dkg_ncyl * d.dkg_nhead * d.dkg_nsect;
3822 		if (v.v_part[idx].p_size != totsize) {
3823 			if (!lecture_and_query(FDISK_LECTURE_NOT_FULL,
3824 			    devname)) {
3825 				(void) close(fd);
3826 				exit(1);
3827 			}
3828 		}
3829 	}
3830 }
3831 
3832 
3833 /*
3834  * get_node
3835  * Called from main to construct the name of the device node to open.
3836  * Initially tries to stat the node exactly as provided, if that fails
3837  * we prepend the default path (/dev/rdsk/).
3838  */
3839 static char *
3840 get_node(char *devname)
3841 {
3842 	char *node;
3843 	struct stat statbuf;
3844 	size_t space;
3845 
3846 	/* Don't do anything if we are skipping device checks */
3847 	if (io_image)
3848 		return (devname);
3849 
3850 	node = devname;
3851 
3852 	/* Try the node as provided first */
3853 	if (stat(node, (struct stat *)&statbuf) == -1) {
3854 		/*
3855 		 * Copy the passed in string to a new buffer, prepend the
3856 		 * default path and try again.
3857 		 */
3858 		space = strlen(DEFAULT_PATH) + strlen(devname) + 1;
3859 
3860 		if ((node = malloc(space)) == NULL) {
3861 			(void) fprintf(stderr, "fdisk: Unable to obtain memory "
3862 			    "for device node.\n");
3863 			exit(1);
3864 		}
3865 
3866 		/* Copy over the default path and the provided node */
3867 		(void) strncpy(node, DEFAULT_PATH, strlen(DEFAULT_PATH));
3868 		space -= strlen(DEFAULT_PATH);
3869 		(void) strlcpy(node + strlen(DEFAULT_PATH), devname, space);
3870 
3871 		/* Try to stat it again */
3872 		if (stat(node, (struct stat *)&statbuf) == -1) {
3873 			/* Failed all options, give up */
3874 			(void) fprintf(stderr,
3875 			    "fdisk: Cannot stat device %s.\n",
3876 			    devname);
3877 			exit(1);
3878 		}
3879 	}
3880 
3881 	/* Make sure the device specified is the raw device */
3882 	if ((statbuf.st_mode & S_IFMT) != S_IFCHR) {
3883 		(void) fprintf(stderr,
3884 		    "fdisk: %s must be a raw device.\n", node);
3885 		exit(1);
3886 	}
3887 
3888 	return (node);
3889 }
3890