xref: /illumos-gate/usr/src/cmd/fdisk/fdisk.c (revision 4c28a617e3922d92a58e813a5b955eb526b9c386)
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 (c) 1992, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright 2018 OmniOS Community Edition (OmniOSce) Association.
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 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <ctype.h>
48 #include <sys/stat.h>
49 #include <sys/types.h>
50 #include <limits.h>
51 #include <sys/param.h>
52 #include <sys/systeminfo.h>
53 #include <sys/efi_partition.h>
54 #include <sys/byteorder.h>
55 #include <sys/systeminfo.h>
56 
57 #include <sys/dktp/fdisk.h>
58 #include <sys/dkio.h>
59 #include <sys/vtoc.h>
60 #ifdef i386
61 #include <sys/tty.h>
62 #include <libfdisk.h>
63 #endif
64 
65 #define	CLR_SCR ""
66 #define	CLR_LIN ""
67 #define	HOME "" \
68 	""
69 #define	Q_LINE ""
70 
71 #ifdef i386
72 #define	W_LINE ""
73 #else
74 #define	W_LINE ""
75 #endif
76 
77 #define	E_LINE ""
78 
79 #ifdef i386
80 #define	M_LINE "" \
81 	""
82 #else
83 #define	M_LINE "" \
84 	""
85 #endif
86 
87 #define	T_LINE ""
88 
89 #define	DEFAULT_PATH	"/dev/rdsk/"
90 
91 #define	DK_MAX_2TB	UINT32_MAX	/* Max # of sectors in 2TB */
92 
93 /* for clear_vtoc() */
94 #define	OLD		0
95 #define	NEW		1
96 
97 /* readvtoc/writevtoc return codes */
98 #define	VTOC_OK		0	/* Good VTOC */
99 #define	VTOC_INVAL	1	/* invalid VTOC */
100 #define	VTOC_NOTSUP	2	/* operation not supported - EFI label */
101 #define	VTOC_RWERR	3	/* couldn't read or write VTOC */
102 
103 /*
104  * Support for fdisk(1M) on the SPARC platform
105  *	In order to convert little endian values to big endian for SPARC,
106  *	byte/short and long values must be swapped.
107  *	These swapping macros will be used to access information in the
108  *	mboot and ipart structures.
109  */
110 
111 #ifdef sparc
112 #define	les(val)	((((val)&0xFF)<<8)|(((val)>>8)&0xFF))
113 #define	lel(val)	(((unsigned)(les((val)&0x0000FFFF))<<16) | \
114 			    (les((unsigned)((val)&0xffff0000)>>16)))
115 #else
116 #define	les(val)	(val)
117 #define	lel(val)	(val)
118 #endif
119 
120 #if defined(_SUNOS_VTOC_16)
121 #define	VTOC_OFFSET	1
122 #elif defined(_SUNOS_VTOC_8)
123 #define	VTOC_OFFSET	0
124 #else
125 #error No VTOC format defined.
126 #endif
127 
128 #ifdef i386
129 #define	FDISK_KB	(1024)
130 #define	FDISK_MB	(FDISK_KB * 1024)
131 #define	FDISK_GB	(FDISK_MB * 1024)
132 #define	TRUE	1
133 
134 #define	FDISK_MAX_VALID_PART_ID	255
135 #define	FDISK_MAX_VALID_PART_NUM_DIGITS	2
136 #define	FDISK_MAX_VALID_PART_ID_DIGITS	3
137 
138 /* Maximum number of digits for a valid partition size */
139 #define	FDISK_MAX_VALID_CYL_NUM_DIGITS	10
140 
141 /* Minimum partition size in cylinders */
142 #define	FDISK_MIN_PART_SIZE	1
143 #endif
144 
145 static char Usage[] = "Usage: fdisk\n"
146 "[ -A id:act:bhead:bsect:bcyl:ehead:esect:ecyl:rsect:numsect ]\n"
147 "[ -b masterboot ]\n"
148 "[ -D id:act:bhead:bsect:bcyl:ehead:esect:ecyl:rsect:numsect ]\n"
149 "[ -E [slot:active] ]\n"
150 "[ -F fdisk_file ] [ -h ] [ -o offset ] [ -P fill_patt ] [ -s size ]\n"
151 "[ -S geom_file ] [ [ -v ] -W { creat_fdisk_file | - } ]\n"
152 "[ -w | r | d | n | I | B | g | G | R | t | T ] rdevice";
153 
154 static char Usage1[] = "    Partition options:\n"
155 "	-A id:act:bhead:bsect:bcyl:ehead:esect:ecyl:rsect:numsect\n"
156 "		Create a partition with specific attributes:\n"
157 "		id      = system id number (fdisk.h) for the partition type\n"
158 "		act     = active partition flag (0 is off and 128 is on)\n"
159 "		bhead   = beginning head for start of partition\n"
160 "		bsect   = beginning sector for start of partition\n"
161 "		bcyl    = beginning cylinder for start of partition\n"
162 "		ehead   = ending head for end of partition\n"
163 "		esect   = ending sector for end of partition\n"
164 "		ecyl    = ending cylinder for end of partition\n"
165 "		rsect   = sector number from start of disk for\n"
166 "			  start of partition\n"
167 "		numsect = partition size in sectors\n"
168 "	-b master_boot\n"
169 "		Use master_boot as the master boot file.\n"
170 "	-B	Create one Solaris partition that uses the entire disk.\n"
171 "	-D id:act:bhead:bsect:bcyl:ehead:esect:ecyl:rsect:numsect\n"
172 "		Delete a partition. See attribute definitions for -A.\n"
173 "	-E [slot:active]\n"
174 "		Create an EFI partition that uses the entire disk.\n"
175 "	-F fdisk_file\n"
176 "		Use fdisk_file to initialize on-line fdisk table.\n"
177 "	-I	Forego device checks. Generate a file image of what would go\n"
178 "		on a disk using the geometry specified with the -S option.\n"
179 "	-n	Do not run in interactive mode.\n"
180 "	-R	Open the disk device as read-only.\n"
181 "	-t	Check and adjust VTOC to be consistent with fdisk table.\n"
182 "		VTOC slices exceeding the partition size will be truncated.\n"
183 "	-T	Check and adjust VTOC to be consistent with fdisk table.\n"
184 "		VTOC slices exceeding the partition size will be removed.\n"
185 "	-W fdisk_file\n"
186 "		Write on-disk table to fdisk_file.\n"
187 "	-W -	Write on-disk table to standard output.\n"
188 "	-v	Display virtual geometry. Must be used with the -W option.\n"
189 "    Diagnostic options:\n"
190 "	-d	Activate debug information about progress.\n"
191 "	-g	Write label geometry to standard output:\n"
192 "		PCYL		number of physical cylinders\n"
193 "		NCYL		number of usable cylinders\n"
194 "		ACYL		number of alternate cylinders\n"
195 "		BCYL		cylinder offset\n"
196 "		NHEADS		number of heads\n"
197 "		NSECTORS	number of sectors per track\n"
198 "		SECTSIZ		size of a sector in bytes\n"
199 "	-G	Write physical geometry to standard output (see -g).\n"
200 "	-h	Issue this verbose help message.\n"
201 "	-o offset\n"
202 "		Block offset from start of disk (default 0). Ignored if\n"
203 "		-P # specified.\n"
204 "	-P fill_patt\n"
205 "		Fill disk with pattern fill_patt. fill_patt can be decimal or\n"
206 "		hexadecimal and is used as number for constant long word\n"
207 "		pattern. If fill_patt is \"#\" then pattern of block #\n"
208 "		for each block. Pattern is put in each block as long words\n"
209 "		and fills each block (see -o and -s).\n"
210 "	-r	Read from a disk to stdout (see -o and -s).\n"
211 "	-s size	Number of blocks on which to perform operation (see -o).\n"
212 "	-S geom_file\n"
213 "		Use geom_file to set the label geometry (see -g).\n"
214 "	-w	Write to a disk from stdin (see -o and -s).";
215 
216 static char Ostr[] = "Other OS";
217 static char Dstr[] = "DOS12";
218 static char D16str[] = "DOS16";
219 static char DDstr[] = "DOS-DATA";
220 static char EDstr[] = "EXT-DOS";
221 static char DBstr[] = "DOS-BIG";
222 static char PCstr[] = "PCIX";
223 static char Ustr[] = "UNIX System";
224 static char SUstr[] = "Solaris";
225 static char SU2str[] = "Solaris2";
226 static char X86str[] = "x86 Boot";
227 static char DIAGstr[] = "Diagnostic";
228 static char IFSstr[] = "IFS: NTFS";
229 static char AIXstr[] = "AIX Boot";
230 static char AIXDstr[] = "AIX Data";
231 static char OS2str[] = "OS/2 Boot";
232 static char WINstr[] = "Win95 FAT32";
233 static char EWINstr[] = "Ext Win95";
234 static char FAT95str[] = "FAT16 LBA";
235 static char EXTLstr[] = "EXT LBA";
236 static char LINUXstr[] = "Linux";
237 static char CPMstr[] = "CP/M";
238 static char NOV2str[] = "Netware 286";
239 static char NOVstr[] = "Netware 3.x+";
240 static char QNXstr[] = "QNX 4.x";
241 static char QNX2str[] = "QNX part 2";
242 static char QNX3str[] = "QNX part 3";
243 static char LINNATstr[] = "Linux native";
244 #ifdef i386
245 static char LINSWAPstr[] = "Linux swap";
246 #endif
247 static char NTFSVOL1str[] = "NT volset 1";
248 static char NTFSVOL2str[] = "NT volset 2";
249 static char BSDstr[] = "BSD OS";
250 static char NEXTSTEPstr[] = "NeXTSTEP";
251 static char BSDIFSstr[] = "BSDI FS";
252 static char BSDISWAPstr[] = "BSDI swap";
253 static char Actvstr[] = "Active";
254 static char EFIstr[] = "EFI";
255 static char NAstr[] = "      ";
256 
257 /* All the user options and flags */
258 static char *Dfltdev;			/* name of fixed disk drive */
259 
260 /* Diagnostic options */
261 static int	io_wrt = 0;		/* write stdin to disk (-w) */
262 static int	io_rd = 0;		/* read disk and write stdout (-r) */
263 static char	*io_fatt;		/* user supplied pattern (-P pattern) */
264 static int	io_patt = 0;		/* write pattern to disk (-P pattern) */
265 static int	io_lgeom = 0;		/* get label geometry (-g) */
266 static int	io_pgeom = 0;		/* get drive physical geometry (-G) */
267 static char	*io_sgeom = 0;		/* set label geometry (-S geom_file) */
268 static int	io_readonly = 0;	/* do not write to disk (-R) */
269 
270 /* The -o offset and -s size options specify the area of the disk on */
271 /* which to perform the particular operation; i.e., -P, -r, or -w. */
272 static off_t	io_offset = 0;		/* offset sector (-o offset) */
273 static off_t	io_size = 0;		/* size in sectors (-s size) */
274 
275 /* Partition table flags */
276 static int	v_flag = 0;		/* virtual geometry-HBA flag (-v) */
277 static int 	stdo_flag = 0;		/* stdout flag (-W -) */
278 static int	io_fdisk = 0;		/* do fdisk operation */
279 static int	io_ifdisk = 0;		/* interactive partition */
280 static int	io_nifdisk = 0;		/* non-interactive partition (-n) */
281 
282 static int	io_adjt = 0;		/* check/adjust VTOC (truncate (-t)) */
283 static int	io_ADJT = 0;		/* check/adjust VTOC (delete (-T)) */
284 static char	*io_ffdisk = 0;		/* input fdisk file name (-F file) */
285 static char	*io_Wfdisk = 0;		/* output fdisk file name (-W file) */
286 static char	*io_Afdisk = 0;		/* add entry to partition table (-A) */
287 static char	*io_Dfdisk = 0;		/* delete entry from part. table (-D) */
288 
289 static char	*io_mboot = 0;		/* master boot record (-b boot_file) */
290 
291 static struct mboot BootCod;		/* buffer for master boot record */
292 
293 static int	io_wholedisk = 0;	/* use whole disk for Solaris (-B) */
294 static int	io_EFIdisk = 0;		/* use whole disk for EFI (-E) */
295 static int	io_EFIslot = 0;		/* slot in which to place EFI entry */
296 static int	io_EFIactive = 0;	/* mark EFI entry as active */
297 static int	io_debug = 0;		/* activate verbose mode (-d) */
298 static int	io_image = 0;		/* create image using geometry (-I) */
299 
300 static struct mboot *Bootblk;		/* pointer to cut/paste sector zero */
301 static char	*Bootsect;		/* pointer to sector zero buffer */
302 static char	*Nullsect;
303 static struct extvtoc	disk_vtoc;	/* verify VTOC table */
304 static int	vt_inval = 0;
305 static int	no_virtgeom_ioctl = 0;	/* ioctl for virtual geometry failed */
306 static int	no_physgeom_ioctl = 0;	/* ioctl for physical geometry failed */
307 
308 static struct ipart	Table[FD_NUMPART];
309 static struct ipart	Old_Table[FD_NUMPART];
310 static int		skip_verify[FD_NUMPART]; /* special case skip sz chk */
311 
312 /* Disk geometry information */
313 static struct dk_minfo	minfo;
314 static struct dk_geom	disk_geom;
315 
316 static int Dev;			/* fd for open device */
317 
318 static diskaddr_t	dev_capacity;	/* number of blocks on device */
319 static diskaddr_t	chs_capacity;	/* Numcyl_usable * heads * sectors */
320 
321 static int		Numcyl_usable;	/* Number of usable cylinders */
322 					/*  used to limit fdisk to 2TB */
323 
324 /* Physical geometry for the drive */
325 static int	Numcyl;			/* number of cylinders */
326 static int	heads;			/* number of heads */
327 static int	sectors;		/* number of sectors per track */
328 static int	acyl;			/* number of alternate sectors */
329 
330 /* HBA (virtual) geometry for the drive */
331 static int	hba_Numcyl;		/* number of cylinders */
332 static int	hba_heads;		/* number of heads */
333 static int	hba_sectors;		/* number of sectors per track */
334 
335 static int	sectsiz;		/* sector size */
336 
337 /* Load functions for fdisk table modification */
338 #define	LOADFILE	0	/* load fdisk from file */
339 #define	LOADDEL		1	/* delete an fdisk entry */
340 #define	LOADADD		2	/* add an fdisk entry */
341 
342 #define	CBUFLEN 80
343 static char s[CBUFLEN];
344 
345 #ifdef i386
346 /*
347  * Complete list of all the 255 partition types. Some are unknown types
348  * and some entries are known to be unused.
349  *
350  * Courtesy of http://www.win.tue.nl/~aeb/partitions/partition_types-1.html
351  */
352 char *fdisk_part_types[] = {
353 	"Empty",				/* 0 */
354 	"FAT12",				/* 1 */
355 	"XENIX /",				/* 2 */
356 	"XENIX /usr",				/* 3 */
357 	"FAT16 (Upto 32M)",			/* 4 */
358 	"DOS Extended",				/* 5 */
359 	"FAT16 (>32M, HUGEDOS)",		/* 6 */
360 	"IFS: NTFS",				/* 7 */
361 	"AIX Boot/QNX(qny)",			/* 8 */
362 	"AIX Data/QNX(qnz)",			/* 9 */
363 	"OS/2 Boot/Coherent swap",		/* 10 */
364 	"WIN95 FAT32(Upto 2047GB)",		/* 11 */
365 	"WIN95 FAT32(LBA)",			/* 12 */
366 	"Unused",				/* 13 */
367 	"WIN95 FAT16(LBA)",			/* 14 */
368 	"WIN95 Extended(LBA)",			/* 15 */
369 	"OPUS",					/* 16 */
370 	"Hidden FAT12",				/* 17 */
371 	"Diagnostic",				/* 18 */
372 	"Unknown",				/* 19 */
373 	"Hidden FAT16(Upto 32M)",		/* 20 */
374 	"Unknown",				/* 21 */
375 	"Hidden FAT16(>=32M)",			/* 22 */
376 	"Hidden IFS: HPFS",			/* 23 */
377 	"AST SmartSleep Partition",		/* 24 */
378 	"Unused/Willowtech Photon",		/* 25 */
379 	"Unknown",				/* 26 */
380 	"Hidden FAT32",				/* 27 */
381 	"Hidden FAT32(LBA)",			/* 28 */
382 	"Unused",				/* 29 */
383 	"Hidden FAT16(LBA)",			/* 30 */
384 	"Unknown",				/* 31 */
385 	"Unused/OSF1",				/* 32 */
386 	"Reserved/FSo2(Oxygen FS)",		/* 33 */
387 	"Unused/(Oxygen EXT)",			/* 34 */
388 	"Reserved",				/* 35 */
389 	"NEC DOS 3.x",				/* 36 */
390 	"Unknown",				/* 37 */
391 	"Reserved",				/* 38 */
392 	"Unknown",				/* 39 */
393 	"Unknown",				/* 40 */
394 	"Unknown",				/* 41 */
395 	"AtheOS File System",			/* 42 */
396 	"SyllableSecure",			/* 43 */
397 	"Unknown",				/* 44 */
398 	"Unknown",				/* 45 */
399 	"Unknown",				/* 46 */
400 	"Unknown",				/* 47 */
401 	"Unknown",				/* 48 */
402 	"Reserved",				/* 49 */
403 	"NOS",					/* 50 */
404 	"Reserved",				/* 51 */
405 	"Reserved",				/* 52 */
406 	"JFS on OS/2",				/* 53 */
407 	"Reserved",				/* 54 */
408 	"Unknown",				/* 55 */
409 	"THEOS 3.2 2GB",			/* 56 */
410 	"Plan9/THEOS 4",			/* 57 */
411 	"THEOS 4 4GB",				/* 58 */
412 	"THEOS 4 Extended",			/* 59 */
413 	"PartitionMagic Recovery",		/* 60 */
414 	"Hidden NetWare",			/* 61 */
415 	"Unknown",				/* 62 */
416 	"Unknown",				/* 63 */
417 	"Venix 80286",				/* 64 */
418 	"MINIX/PPC PReP Boot",			/* 65 */
419 	"Win2K Dynamic Disk/SFS(DOS)",		/* 66 */
420 	"Linux+DRDOS shared",			/* 67 */
421 	"GoBack partition",			/* 68 */
422 	"Boot-US boot manager",			/* 69 */
423 	"EUMEL/Elan",				/* 70 */
424 	"EUMEL/Elan",				/* 71 */
425 	"EUMEL/Elan",				/* 72 */
426 	"Unknown",				/* 73 */
427 	"ALFS/THIN FS for DOS",			/* 74 */
428 	"Unknown",				/* 75 */
429 	"Oberon partition",			/* 76 */
430 	"QNX 4,x",				/* 77 */
431 	"QNX 4,x 2nd Part",			/* 78 */
432 	"QNX 4,x 3rd Part",			/* 79 */
433 	"OnTrack DM R/O, Lynx RTOS",		/* 80 */
434 	"OnTrack DM R/W, Novell",		/* 81 */
435 	"CP/M",					/* 82 */
436 	"Disk Manager 6.0 Aux3",		/* 83 */
437 	"Disk Manager 6.0 DDO",			/* 84 */
438 	"EZ-Drive",				/* 85 */
439 	"Golden Bow VFeature/AT&T MS-DOS",	/* 86 */
440 	"DrivePro",				/* 87 */
441 	"Unknown",				/* 88 */
442 	"Unknown",				/* 89 */
443 	"Unknown",				/* 90 */
444 	"Unknown",				/* 91 */
445 	"Priam EDisk",				/* 92 */
446 	"Unknown",				/* 93 */
447 	"Unknown",				/* 94 */
448 	"Unknown",				/* 95 */
449 	"Unknown",				/* 96 */
450 	"SpeedStor",				/* 97 */
451 	"Unknown",				/* 98 */
452 	"Unix SysV, Mach, GNU Hurd",		/* 99 */
453 	"PC-ARMOUR, Netware 286",		/* 100 */
454 	"Netware 386",				/* 101 */
455 	"Netware SMS",				/* 102 */
456 	"Novell",				/* 103 */
457 	"Novell",				/* 104 */
458 	"Netware NSS",				/* 105 */
459 	"Unknown",				/* 106 */
460 	"Unknown",				/* 107 */
461 	"Unknown",				/* 108 */
462 	"Unknown",				/* 109 */
463 	"Unknown",				/* 110 */
464 	"Unknown",				/* 111 */
465 	"DiskSecure Multi-Boot",		/* 112 */
466 	"Reserved",				/* 113 */
467 	"Unknown",				/* 114 */
468 	"Reserved",				/* 115 */
469 	"Scramdisk partition",			/* 116 */
470 	"IBM PC/IX",				/* 117 */
471 	"Reserved",				/* 118 */
472 	"M2FS/M2CS,Netware VNDI",		/* 119 */
473 	"XOSL FS",				/* 120 */
474 	"Unknown",				/* 121 */
475 	"Unknown",				/* 122 */
476 	"Unknown",				/* 123 */
477 	"Unknown",				/* 124 */
478 	"Unknown",				/* 125 */
479 	"Unused",				/* 126 */
480 	"Unused",				/* 127 */
481 	"MINIX until 1.4a",			/* 128 */
482 	"MINIX since 1.4b, early Linux",	/* 129 */
483 	"Solaris/Linux swap",			/* 130 */
484 	"Linux native",				/* 131 */
485 	"OS/2 hidden,Win Hibernation",		/* 132 */
486 	"Linux extended",			/* 133 */
487 	"Old Linux RAID,NT FAT16 RAID",		/* 134 */
488 	"NTFS volume set",			/* 135 */
489 	"Linux plaintext part table",		/* 136 */
490 	"Unknown",				/* 137 */
491 	"Linux Kernel Partition",		/* 138 */
492 	"Fault Tolerant FAT32 volume",		/* 139 */
493 	"Fault Tolerant FAT32 volume",		/* 140 */
494 	"Free FDISK hidden PDOS FAT12",		/* 141 */
495 	"Linux LVM partition",			/* 142 */
496 	"Unknown",				/* 143 */
497 	"Free FDISK hidden PDOS FAT16",		/* 144 */
498 	"Free FDISK hidden DOS EXT",		/* 145 */
499 	"Free FDISK hidden FAT16 Large",	/* 146 */
500 	"Hidden Linux native, Amoeba",		/* 147 */
501 	"Amoeba Bad Block Table",		/* 148 */
502 	"MIT EXOPC Native",			/* 149 */
503 	"Unknown",				/* 150 */
504 	"Free FDISK hidden PDOS FAT32",		/* 151 */
505 	"Free FDISK hidden FAT32 LBA",		/* 152 */
506 	"DCE376 logical drive",			/* 153 */
507 	"Free FDISK hidden FAT16 LBA",		/* 154 */
508 	"Free FDISK hidden DOS EXT",		/* 155 */
509 	"Unknown",				/* 156 */
510 	"Unknown",				/* 157 */
511 	"Unknown",				/* 158 */
512 	"BSD/OS",				/* 159 */
513 	"Laptop hibernation",			/* 160 */
514 	"Laptop hibernate,HP SpeedStor",	/* 161 */
515 	"Unknown",				/* 162 */
516 	"HP SpeedStor",				/* 163 */
517 	"HP SpeedStor",				/* 164 */
518 	"BSD/386,386BSD,NetBSD,FreeBSD",	/* 165 */
519 	"OpenBSD,HP SpeedStor",			/* 166 */
520 	"NeXTStep",				/* 167 */
521 	"Mac OS-X",				/* 168 */
522 	"NetBSD",				/* 169 */
523 	"Olivetti FAT12 1.44MB Service",	/* 170 */
524 	"Mac OS-X Boot",			/* 171 */
525 	"Unknown",				/* 172 */
526 	"Unknown",				/* 173 */
527 	"ShagOS filesystem",			/* 174 */
528 	"ShagOS swap",				/* 175 */
529 	"BootStar Dummy",			/* 176 */
530 	"HP SpeedStor",				/* 177 */
531 	"Unknown",				/* 178 */
532 	"HP SpeedStor",				/* 179 */
533 	"HP SpeedStor",				/* 180 */
534 	"Unknown",				/* 181 */
535 	"Corrupted FAT16 NT Mirror Set",	/* 182 */
536 	"Corrupted NTFS NT Mirror Set",		/* 183 */
537 	"Old BSDI BSD/386 swap",		/* 184 */
538 	"Unknown",				/* 185 */
539 	"Unknown",				/* 186 */
540 	"Boot Wizard hidden",			/* 187 */
541 	"Unknown",				/* 188 */
542 	"Unknown",				/* 189 */
543 	"Solaris x86 boot",			/* 190 */
544 	"Solaris2",				/* 191 */
545 	"REAL/32 or Novell DOS secured",	/* 192 */
546 	"DRDOS/secured(FAT12)",			/* 193 */
547 	"Hidden Linux",				/* 194 */
548 	"Hidden Linux swap",			/* 195 */
549 	"DRDOS/secured(FAT16,< 32M)",		/* 196 */
550 	"DRDOS/secured(Extended)",		/* 197 */
551 	"NT corrupted FAT16 volume",		/* 198 */
552 	"NT corrupted NTFS volume",		/* 199 */
553 	"DRDOS8.0+",				/* 200 */
554 	"DRDOS8.0+",				/* 201 */
555 	"DRDOS8.0+",				/* 202 */
556 	"DRDOS7.04+ secured FAT32(CHS)",	/* 203 */
557 	"DRDOS7.04+ secured FAT32(LBA)",	/* 204 */
558 	"CTOS Memdump",				/* 205 */
559 	"DRDOS7.04+ FAT16X(LBA)",		/* 206 */
560 	"DRDOS7.04+ secure EXT DOS(LBA)",	/* 207 */
561 	"REAL/32 secure big, MDOS",		/* 208 */
562 	"Old MDOS secure FAT12",		/* 209 */
563 	"Unknown",				/* 210 */
564 	"Unknown",				/* 211 */
565 	"Old MDOS secure FAT16 <32M",		/* 212 */
566 	"Old MDOS secure EXT",			/* 213 */
567 	"Old MDOS secure FAT16 >=32M",		/* 214 */
568 	"Unknown",				/* 215 */
569 	"CP/M-86",				/* 216 */
570 	"Unknown",				/* 217 */
571 	"Non-FS Data",				/* 218 */
572 	"CP/M,Concurrent DOS,CTOS",		/* 219 */
573 	"Unknown",				/* 220 */
574 	"Hidden CTOS memdump",			/* 221 */
575 	"Dell PowerEdge utilities(FAT)",	/* 222 */
576 	"DG/UX virtual disk manager",		/* 223 */
577 	"ST AVFS(STMicroelectronics)",		/* 224 */
578 	"SpeedStor 12-bit FAT EXT",		/* 225 */
579 	"Unknown",				/* 226 */
580 	"SpeedStor",				/* 227 */
581 	"SpeedStor 16-bit FAT EXT",		/* 228 */
582 	"Tandy MSDOS",				/* 229 */
583 	"Storage Dimensions SpeedStor",		/* 230 */
584 	"Unknown",				/* 231 */
585 	"Unknown",				/* 232 */
586 	"Unknown",				/* 233 */
587 	"Unknown",				/* 234 */
588 	"BeOS BFS",				/* 235 */
589 	"SkyOS SkyFS",				/* 236 */
590 	"Unused",				/* 237 */
591 	"EFI Header Indicator",			/* 238 */
592 	"EFI Filesystem",			/* 239 */
593 	"Linux/PA-RISC boot loader",		/* 240 */
594 	"SpeedStor",				/* 241 */
595 	"DOS 3.3+ secondary",			/* 242 */
596 	"SpeedStor Reserved",			/* 243 */
597 	"SpeedStor Large",			/* 244 */
598 	"Prologue multi-volume",		/* 245 */
599 	"SpeedStor",				/* 246 */
600 	"Unused",				/* 247 */
601 	"Unknown",				/* 248 */
602 	"pCache",				/* 249 */
603 	"Bochs",				/* 250 */
604 	"VMware File System",			/* 251 */
605 	"VMware swap",				/* 252 */
606 	"Linux raid autodetect",		/* 253 */
607 	"NT Disk Administrator hidden",		/* 254 */
608 	"Xenix Bad Block Table"			/* 255 */
609 };
610 
611 /* Allowed extended partition menu options */
612 static char ext_part_menu_opts[] = "adhipr";
613 
614 /*
615  * Structure holding all information about the extended partition
616  * NOTE : As of now, there will be just one instance of ext_part_t, since most
617  * known systems allow only one extended dos partition per disk.
618  */
619 static ext_part_t *epp;
620 #endif
621 
622 static void update_disk_and_exit(boolean_t table_changed);
623 int main(int argc, char *argv[]);
624 static int read_geom(char *sgeom);
625 static void dev_mboot_read(void);
626 static void dev_mboot_write(off_t sect, char *buff, int bootsiz);
627 static void mboot_read(void);
628 static void fill_patt(void);
629 static void abs_read(void);
630 static void abs_write(void);
631 static void load(int funct, char *file);
632 static void Set_Table_CHS_Values(int ti);
633 static int nopartdefined();
634 static int insert_tbl(int id, int act,
635     int bhead, int bsect, int bcyl,
636     int ehead, int esect, int ecyl,
637     uint32_t rsect, uint32_t numsect, int startindex);
638 static int entry_from_old_table(int id, int act,
639     int bhead, int bsect, int bcyl,
640     int ehead, int esect, int ecyl,
641     uint32_t rsect, uint32_t numsect, int startindex);
642 static int verify_tbl(void);
643 static int pars_fdisk(char *line,
644     int *id, int *act,
645     int *bhead, int *bsect, int *bcyl,
646     int *ehead, int *esect, int *ecyl,
647     uint32_t *rsect, uint32_t *numsect);
648 static int validate_part(int id, uint32_t rsect, uint32_t numsect);
649 static void stage0(void);
650 static int pcreate(void);
651 static int specify(uchar_t tsystid);
652 static void dispmenu(void);
653 static int pchange(void);
654 static int ppartid(void);
655 static char pdelete(void);
656 static void rm_blanks(char *s);
657 static int getcyl(void);
658 static void disptbl(void);
659 static void print_Table(void);
660 static void copy_Table_to_Old_Table(void);
661 static void nulltbl(void);
662 static void copy_Bootblk_to_Table(void);
663 static void fill_ipart(char *bootptr, struct ipart *partp);
664 #ifdef sparc
665 uchar_t getbyte(char **bp);
666 uint32_t getlong(char **bp);
667 #endif
668 static void copy_Table_to_Bootblk(void);
669 static int TableChanged(void);
670 static void ffile_write(char *file);
671 static void fix_slice(void);
672 static int yesno(void);
673 static int readvtoc(void);
674 static int writevtoc(void);
675 static int efi_ioctl(int fd, int cmd, dk_efi_t *dk_ioc);
676 static int clear_efi(void);
677 static void clear_vtoc(int table, int part);
678 static int lecture_and_query(char *warning, char *devname);
679 static void sanity_check_provided_device(char *devname, int fd);
680 static char *get_node(char *devname);
681 static int efi_create(void);
682 
683 #ifdef i386
684 static void id_to_name(uchar_t sysid, char *buffer);
685 static void ext_read_input(char *buf);
686 static int ext_read_options(char *buf);
687 static int ext_invalid_option(char ch);
688 static void ext_read_valid_part_num(int *pno);
689 static void ext_read_valid_part_id(uchar_t *partid);
690 static int ext_read_valid_partition_start(uint32_t *begsec);
691 static void ext_read_valid_partition_size(uint32_t begsec, uint32_t *endsec);
692 static void ext_part_menu();
693 static void add_logical_drive();
694 static void delete_logical_drive();
695 static void ext_print_help_menu();
696 static void ext_change_logical_drive_id();
697 static void ext_print_part_types();
698 static void ext_print_logical_drive_layout();
699 static void preach_and_continue();
700 #ifdef DEBUG
701 static void ext_print_logdrive_layout_debug();
702 #endif	/* DEBUG */
703 #endif	/* i386 */
704 
705 /*
706  * This function is called only during the non-interactive mode.
707  * It is touchy and does not tolerate any errors. If there are
708  * mounted logical drives, changes to the partition table
709  * are disallowed.
710  */
711 static void
712 update_disk_and_exit(boolean_t table_changed)
713 {
714 #ifdef i386
715 	int rval;
716 #endif
717 	if (table_changed) {
718 		/*
719 		 * Copy the new table back to the sector buffer
720 		 * and write it to disk
721 		 */
722 		copy_Table_to_Bootblk();
723 		dev_mboot_write(0, Bootsect, sectsiz);
724 	}
725 
726 	/* If the VTOC table is wrong fix it (truncation only) */
727 	if (io_adjt)
728 		fix_slice();
729 
730 #ifdef i386
731 	if (!io_readonly) {
732 		rval = fdisk_commit_ext_part(epp);
733 		switch (rval) {
734 			case FDISK_SUCCESS:
735 				/* Success */
736 				break;
737 			case FDISK_ENOEXTPART:
738 				/* Nothing to do */
739 				break;
740 			default:
741 				(void) fprintf(stderr, "Error in"
742 				    " fdisk_commit_ext_part\n");
743 				exit(rval);
744 		}
745 	}
746 	libfdisk_fini(&epp);
747 #endif
748 	exit(0);
749 }
750 
751 /*
752  * main
753  * Process command-line options.
754  */
755 int
756 main(int argc, char *argv[])
757 {
758 	int c, i;
759 	extern	int optind;
760 	extern	char *optarg;
761 	int	errflg = 0;
762 	int	diag_cnt = 0;
763 	int openmode;
764 #ifdef i386
765 	int rval;
766 	int lf_op_flag = 0;
767 #endif
768 
769 	setbuf(stderr, 0);	/* so all output gets out on exit */
770 	setbuf(stdout, 0);
771 
772 	/* Process the options. */
773 	while ((c = getopt(argc, argv, "o:s:P:F:b:A:D:W:S:tTIhwvrndgGRBE:"))
774 	    != EOF) {
775 		switch (c) {
776 
777 			case 'o':
778 				io_offset = (off_t)strtoull(optarg, 0, 0);
779 				continue;
780 			case 's':
781 				io_size = (off_t)strtoull(optarg, 0, 0);
782 				continue;
783 			case 'P':
784 				diag_cnt++;
785 				io_patt++;
786 				io_fatt = optarg;
787 				continue;
788 			case 'w':
789 				diag_cnt++;
790 				io_wrt++;
791 				continue;
792 			case 'r':
793 				diag_cnt++;
794 				io_rd++;
795 				continue;
796 			case 'd':
797 				io_debug++;
798 				continue;
799 			case 'I':
800 				io_image++;
801 				continue;
802 			case 'R':
803 				io_readonly++;
804 				continue;
805 			case 'S':
806 				diag_cnt++;
807 				io_sgeom = optarg;
808 				continue;
809 			case 'T':
810 				io_ADJT++;
811 				/* FALLTHROUGH */
812 			case 't':
813 				io_adjt++;
814 				continue;
815 			case 'B':
816 				io_wholedisk++;
817 				io_fdisk++;
818 				continue;
819 			case 'E':
820 				if (sscanf(optarg, "%d:%d",
821 				    &io_EFIslot, &io_EFIactive) != 2) {
822 					io_EFIslot = io_EFIactive = 0;
823 					optind--;
824 				}
825 				io_EFIdisk++;
826 				io_fdisk++;
827 				continue;
828 			case 'g':
829 				diag_cnt++;
830 				io_lgeom++;
831 				continue;
832 			case 'G':
833 				diag_cnt++;
834 				io_pgeom++;
835 				continue;
836 			case 'n':
837 				io_nifdisk++;
838 				io_fdisk++;
839 				continue;
840 			case 'F':
841 				io_fdisk++;
842 				io_ffdisk = optarg;
843 				continue;
844 			case 'b':
845 				io_mboot = optarg;
846 				continue;
847 			case 'W':
848 				/*
849 				 * If '-' is the -W argument, then write
850 				 * to standard output, otherwise write
851 				 * to the specified file.
852 				 */
853 				if (strncmp(optarg, "-", 1) == 0)
854 					stdo_flag = 1;
855 				else
856 					io_Wfdisk = optarg;
857 				io_fdisk++;
858 				continue;
859 			case 'A':
860 				io_fdisk++;
861 				io_Afdisk = optarg;
862 				continue;
863 			case 'D':
864 				io_fdisk++;
865 				io_Dfdisk = optarg;
866 				continue;
867 			case 'h':
868 				(void) fprintf(stderr, "%s\n", Usage);
869 				(void) fprintf(stderr, "%s\n", Usage1);
870 				exit(0);
871 				/* FALLTHROUGH */
872 			case 'v':
873 				v_flag = 1;
874 				continue;
875 			case '?':
876 				errflg++;
877 				break;
878 		}
879 		break;
880 	}
881 
882 	if (io_image && io_sgeom && diag_cnt == 1) {
883 		diag_cnt = 0;
884 	}
885 
886 	/* User option checking */
887 
888 	/* By default, run in interactive mode */
889 	if (!io_fdisk && !diag_cnt && !io_nifdisk) {
890 		io_ifdisk++;
891 		io_fdisk++;
892 	}
893 	if (((io_fdisk || io_adjt) && diag_cnt) || (diag_cnt > 1)) {
894 		errflg++;
895 	}
896 
897 	/* Was any error detected? */
898 	if (errflg || argc == optind) {
899 		(void) fprintf(stderr, "%s\n", Usage);
900 		(void) fprintf(stderr,
901 		    "\nDetailed help is available with the -h option.\n");
902 		exit(2);
903 	}
904 
905 	/* Figure out the correct device node to open */
906 	Dfltdev = get_node(argv[optind]);
907 
908 	if (io_readonly)
909 		openmode = O_RDONLY;
910 	else
911 		openmode = O_RDWR|O_CREAT;
912 
913 	if ((Dev = open(Dfltdev, openmode, 0666)) == -1) {
914 		(void) fprintf(stderr,
915 		    "fdisk: Cannot open device %s.\n",
916 		    Dfltdev);
917 		exit(1);
918 	}
919 	/*
920 	 * not all disk (or disklike) drivers support DKIOCGMEDIAINFO
921 	 * in that case leave the minfo structure zeroed
922 	 */
923 	if (ioctl(Dev, DKIOCGMEDIAINFO, &minfo)) {
924 		(void) memset(&minfo, 0, sizeof (minfo));
925 	}
926 
927 	/* Get the disk geometry */
928 	if (!io_image) {
929 		/* Get disk's HBA (virtual) geometry */
930 		errno = 0;
931 		if (ioctl(Dev, DKIOCG_VIRTGEOM, &disk_geom)) {
932 
933 			/*
934 			 * If ioctl isn't implemented on this platform, then
935 			 * turn off flag to print out virtual geometry (-v),
936 			 * otherwise use the virtual geometry.
937 			 */
938 
939 			if (errno == ENOTTY) {
940 				v_flag = 0;
941 				no_virtgeom_ioctl = 1;
942 			} else if (errno == EINVAL) {
943 				/*
944 				 * This means that the ioctl exists, but
945 				 * is invalid for this disk, meaning the
946 				 * disk doesn't have an HBA geometry
947 				 * (like, say, it's larger than 8GB).
948 				 */
949 				v_flag = 0;
950 				hba_Numcyl = hba_heads = hba_sectors = 0;
951 			} else {
952 				(void) fprintf(stderr,
953 				    "%s: Cannot get virtual disk geometry.\n",
954 				    argv[optind]);
955 				exit(1);
956 			}
957 		} else {
958 			/* save virtual geometry values obtained by ioctl */
959 			hba_Numcyl = disk_geom.dkg_ncyl;
960 			hba_heads = disk_geom.dkg_nhead;
961 			hba_sectors = disk_geom.dkg_nsect;
962 		}
963 
964 		errno = 0;
965 		if (ioctl(Dev, DKIOCG_PHYGEOM, &disk_geom)) {
966 			if (errno == ENOTTY) {
967 				no_physgeom_ioctl = 1;
968 			} else {
969 				(void) fprintf(stderr,
970 				    "%s: Cannot get physical disk geometry.\n",
971 				    argv[optind]);
972 				exit(1);
973 			}
974 
975 		}
976 		/*
977 		 * Call DKIOCGGEOM if the ioctls for physical and virtual
978 		 * geometry fail. Get both from this generic call.
979 		 */
980 		if (no_virtgeom_ioctl && no_physgeom_ioctl) {
981 			errno = 0;
982 			if (ioctl(Dev, DKIOCGGEOM, &disk_geom)) {
983 				(void) fprintf(stderr,
984 				    "%s: Cannot get disk label geometry.\n",
985 				    argv[optind]);
986 				exit(1);
987 			}
988 		}
989 
990 		Numcyl = disk_geom.dkg_ncyl;
991 		heads = disk_geom.dkg_nhead;
992 		sectors = disk_geom.dkg_nsect;
993 
994 		if (minfo.dki_lbsize != 0)
995 			sectsiz = minfo.dki_lbsize;
996 		else
997 			sectsiz = 512;
998 
999 		acyl = disk_geom.dkg_acyl;
1000 
1001 		/*
1002 		 * if hba geometry was not set by DKIOC_VIRTGEOM
1003 		 * or we got an invalid hba geometry
1004 		 * then set hba geometry based on max values
1005 		 */
1006 		if (no_virtgeom_ioctl ||
1007 		    disk_geom.dkg_ncyl == 0 ||
1008 		    disk_geom.dkg_nhead == 0 ||
1009 		    disk_geom.dkg_nsect == 0 ||
1010 		    disk_geom.dkg_ncyl > MAX_CYL ||
1011 		    disk_geom.dkg_nhead > MAX_HEAD + 1 ||
1012 		    disk_geom.dkg_nsect > MAX_SECT) {
1013 
1014 			/*
1015 			 * turn off flag to print out virtual geometry (-v)
1016 			 */
1017 			v_flag = 0;
1018 			hba_sectors	= MAX_SECT;
1019 			hba_heads	= MAX_HEAD + 1;
1020 			hba_Numcyl	= (Numcyl * heads * sectors) /
1021 			    (hba_sectors * hba_heads);
1022 		}
1023 
1024 		if (io_debug) {
1025 			(void) fprintf(stderr, "Physical Geometry:\n");
1026 			(void) fprintf(stderr,
1027 			    "  cylinders[%d] heads[%d] sectors[%d]\n"
1028 			    "  sector size[%d] blocks[%d] mbytes[%d]\n",
1029 			    Numcyl,
1030 			    heads,
1031 			    sectors,
1032 			    sectsiz,
1033 			    Numcyl * heads * sectors,
1034 			    (Numcyl * heads * sectors * sectsiz) / 1048576);
1035 			(void) fprintf(stderr, "Virtual (HBA) Geometry:\n");
1036 			(void) fprintf(stderr,
1037 			    "  cylinders[%d] heads[%d] sectors[%d]\n"
1038 			    "  sector size[%d] blocks[%d] mbytes[%d]\n",
1039 			    hba_Numcyl,
1040 			    hba_heads,
1041 			    hba_sectors,
1042 			    sectsiz,
1043 			    hba_Numcyl * hba_heads * hba_sectors,
1044 			    (hba_Numcyl * hba_heads * hba_sectors * sectsiz) /
1045 			    1048576);
1046 		}
1047 	}
1048 
1049 	/* If user has requested a geometry report just do it and exit */
1050 	if (io_lgeom) {
1051 		if (ioctl(Dev, DKIOCGGEOM, &disk_geom)) {
1052 			(void) fprintf(stderr,
1053 			    "%s: Cannot get disk label geometry.\n",
1054 			    argv[optind]);
1055 			exit(1);
1056 		}
1057 		Numcyl = disk_geom.dkg_ncyl;
1058 		heads = disk_geom.dkg_nhead;
1059 		sectors = disk_geom.dkg_nsect;
1060 		if (minfo.dki_lbsize != 0)
1061 			sectsiz = minfo.dki_lbsize;
1062 		else
1063 			sectsiz = 512;
1064 
1065 		acyl = disk_geom.dkg_acyl;
1066 		(void) printf("* Label geometry for device %s\n", Dfltdev);
1067 		(void) printf(
1068 		    "* PCYL     NCYL     ACYL     BCYL     NHEAD NSECT"
1069 		    " SECSIZ\n");
1070 		(void) printf("  %-8d %-8d %-8d %-8d %-5d %-5d %-6d\n",
1071 		    Numcyl,
1072 		    disk_geom.dkg_ncyl,
1073 		    disk_geom.dkg_acyl,
1074 		    disk_geom.dkg_bcyl,
1075 		    heads,
1076 		    sectors,
1077 		    sectsiz);
1078 		exit(0);
1079 	} else if (io_pgeom) {
1080 		if (ioctl(Dev, DKIOCG_PHYGEOM, &disk_geom)) {
1081 			(void) fprintf(stderr,
1082 			    "%s: Cannot get physical disk geometry.\n",
1083 			    argv[optind]);
1084 			exit(1);
1085 		}
1086 		(void) printf("* Physical geometry for device %s\n", Dfltdev);
1087 		(void) printf(
1088 		    "* PCYL     NCYL     ACYL     BCYL     NHEAD NSECT"
1089 		    " SECSIZ\n");
1090 		(void) printf("  %-8d %-8d %-8d %-8d %-5d %-5d %-6d\n",
1091 		    disk_geom.dkg_pcyl,
1092 		    disk_geom.dkg_ncyl,
1093 		    disk_geom.dkg_acyl,
1094 		    disk_geom.dkg_bcyl,
1095 		    disk_geom.dkg_nhead,
1096 		    disk_geom.dkg_nsect,
1097 		    sectsiz);
1098 		exit(0);
1099 	} else if (io_sgeom) {
1100 		if (read_geom(io_sgeom)) {
1101 			exit(1);
1102 		} else if (!io_image) {
1103 			exit(0);
1104 		}
1105 	}
1106 
1107 	/*
1108 	 * some drivers may not support DKIOCGMEDIAINFO
1109 	 * in that case use CHS
1110 	 */
1111 	chs_capacity = (diskaddr_t)Numcyl * heads * sectors;
1112 	dev_capacity = chs_capacity;
1113 	Numcyl_usable = Numcyl;
1114 
1115 	if (chs_capacity > DK_MAX_2TB) {
1116 		/* limit to 2TB */
1117 		Numcyl_usable = DK_MAX_2TB / (heads * sectors);
1118 		chs_capacity = (diskaddr_t)Numcyl_usable * heads * sectors;
1119 	}
1120 
1121 	if (minfo.dki_capacity > 0)
1122 		dev_capacity = minfo.dki_capacity;
1123 
1124 	/* Allocate memory to hold three complete sectors */
1125 	Bootsect = (char *)calloc(3 * sectsiz, 1);
1126 	if (Bootsect == NULL) {
1127 		(void) fprintf(stderr,
1128 		    "fdisk: Unable to obtain enough buffer memory"
1129 		    " (%d bytes).\n",
1130 		    3 * sectsiz);
1131 		exit(1);
1132 	}
1133 
1134 	Nullsect = Bootsect + sectsiz;
1135 	/* Zero out the "NULL" sector */
1136 	for (i = 0; i < sectsiz; i++) {
1137 		Nullsect[i] = 0;
1138 	}
1139 
1140 	/* Find out what the user wants done */
1141 	if (io_rd) {		/* abs disk read */
1142 		abs_read();	/* will not return */
1143 	} else if (io_wrt && !io_readonly) {
1144 		abs_write();	/* will not return */
1145 	} else if (io_patt && !io_readonly) {
1146 		fill_patt();	/* will not return */
1147 	}
1148 
1149 	/* This is the fdisk edit, the real reason for the program.	*/
1150 
1151 	sanity_check_provided_device(Dfltdev, Dev);
1152 
1153 	/* Get the new BOOT program in case we write a new fdisk table */
1154 	mboot_read();
1155 
1156 	/* Read from disk master boot */
1157 	dev_mboot_read();
1158 
1159 	/*
1160 	 * Verify and copy the device's fdisk table. This will be used
1161 	 * as the prototype mboot if the device's mboot looks invalid.
1162 	 */
1163 	Bootblk = (struct mboot *)Bootsect;
1164 	copy_Bootblk_to_Table();
1165 
1166 	/* save away a copy of Table in Old_Table for sensing changes */
1167 	copy_Table_to_Old_Table();
1168 
1169 #ifdef i386
1170 	/*
1171 	 * Read extended partition only when the fdisk table is not
1172 	 * supplied from a file
1173 	 */
1174 	if (!io_ffdisk) {
1175 		lf_op_flag |= FDISK_READ_DISK;
1176 	}
1177 	if ((rval = libfdisk_init(&epp, Dfltdev, &Table[0], lf_op_flag))
1178 	    != FDISK_SUCCESS) {
1179 		switch (rval) {
1180 			/*
1181 			 * FDISK_EBADLOGDRIVE, FDISK_ENOLOGDRIVE and
1182 			 * FDISK_EBADMAGIC can be considered as
1183 			 * soft errors and hence we do not exit
1184 			 */
1185 			case FDISK_EBADLOGDRIVE:
1186 				break;
1187 			case FDISK_ENOLOGDRIVE:
1188 				break;
1189 			case FDISK_EBADMAGIC:
1190 				break;
1191 			case FDISK_ENOVGEOM:
1192 				(void) fprintf(stderr, "Could not get virtual"
1193 				    " geometry for this device\n");
1194 				exit(1);
1195 				break;
1196 			case FDISK_ENOPGEOM:
1197 				(void) fprintf(stderr, "Could not get physical"
1198 				    " geometry for this device\n");
1199 				exit(1);
1200 				break;
1201 			case FDISK_ENOLGEOM:
1202 				(void) fprintf(stderr, "Could not get label"
1203 				    " geometry for this device\n");
1204 				exit(1);
1205 				break;
1206 			default:
1207 				perror("Failed to initialise libfdisk.\n");
1208 				exit(1);
1209 				break;
1210 		}
1211 	}
1212 #endif
1213 
1214 	/* Load fdisk table from specified file (-F fdisk_file) */
1215 	if (io_ffdisk) {
1216 		/* Load and verify user-specified table parameters */
1217 		load(LOADFILE, io_ffdisk);
1218 	}
1219 
1220 	/* Does user want to delete or add an entry? */
1221 	if (io_Dfdisk) {
1222 		load(LOADDEL, io_Dfdisk);
1223 	}
1224 	if (io_Afdisk) {
1225 		load(LOADADD, io_Afdisk);
1226 	}
1227 
1228 	if (!io_ffdisk && !io_Afdisk && !io_Dfdisk) {
1229 		/* Check if there is no fdisk table */
1230 		if (nopartdefined() || io_wholedisk || io_EFIdisk) {
1231 			if (io_ifdisk && !io_wholedisk && !io_EFIdisk) {
1232 				(void) printf(
1233 				    "No fdisk table exists. The default"
1234 				    " partition for the disk is:\n\n"
1235 				    "  a 100%% \"SOLARIS System\" "
1236 				    "partition\n\n"
1237 				    "Type \"y\" to accept the default "
1238 				    "partition,  otherwise type \"n\" to "
1239 				    "edit the\n partition table.\n");
1240 
1241 				if (Numcyl > Numcyl_usable)
1242 					(void) printf("WARNING: Disk is larger"
1243 					    " than 2TB. Solaris partition will"
1244 					    " be limited to 2 TB.\n");
1245 			}
1246 
1247 			/* Edit the partition table as directed */
1248 			if (io_wholedisk ||(io_ifdisk && yesno())) {
1249 
1250 				/* Default scenario */
1251 				nulltbl();
1252 				/* now set up UNIX System partition */
1253 				Table[0].bootid = ACTIVE;
1254 				Table[0].relsect = LE_32(heads * sectors);
1255 
1256 				Table[0].numsect =
1257 				    LE_32((ulong_t)((Numcyl_usable - 1) *
1258 				    heads * sectors));
1259 
1260 				Table[0].systid = SUNIXOS2;   /* Solaris */
1261 
1262 				/* calculate CHS values for table entry 0 */
1263 				Set_Table_CHS_Values(0);
1264 				update_disk_and_exit(B_TRUE);
1265 			} else if (io_EFIdisk) {
1266 				if (efi_create() == 0) {
1267 					(void) fprintf(stderr,
1268 					    "Error creating EFI partition\n");
1269 					exit(1);
1270 				}
1271 				(void) close(Dev);
1272 				exit(0);
1273 				/* NOTREACHED */
1274 			}
1275 		}
1276 	}
1277 
1278 	/* Display complete fdisk table entries for debugging purposes */
1279 	if (io_debug) {
1280 		(void) fprintf(stderr, "Partition Table Entry Values:\n");
1281 		print_Table();
1282 		if (io_ifdisk) {
1283 			(void) fprintf(stderr, "\n");
1284 			(void) fprintf(stderr, "Press Enter to continue.\n");
1285 			(void) fgets(s, sizeof (s), stdin);
1286 		}
1287 	}
1288 
1289 	/* Interactive fdisk mode */
1290 	if (io_ifdisk) {
1291 		(void) printf(CLR_SCR);
1292 		disptbl();
1293 		for (;;) {
1294 			stage0();
1295 			copy_Bootblk_to_Table();
1296 			disptbl();
1297 		}
1298 	}
1299 
1300 	/* If user wants to write the table to a file, do it */
1301 	if (io_Wfdisk)
1302 		ffile_write(io_Wfdisk);
1303 	else if (stdo_flag)
1304 		ffile_write((char *)stdout);
1305 
1306 	update_disk_and_exit(TableChanged() == 1);
1307 	return (0);
1308 }
1309 
1310 /*
1311  * read_geom
1312  * Read geometry from specified file (-S).
1313  */
1314 
1315 static int
1316 read_geom(char *sgeom)
1317 {
1318 	char	line[256];
1319 	FILE *fp;
1320 
1321 	/* open the prototype file */
1322 	if ((fp = fopen(sgeom, "r")) == NULL) {
1323 		(void) fprintf(stderr, "fdisk: Cannot open file %s.\n",
1324 		    io_sgeom);
1325 		return (1);
1326 	}
1327 
1328 	/* Read a line from the file */
1329 	while (fgets(line, sizeof (line) - 1, fp)) {
1330 		if (line[0] == '\0' || line[0] == '\n' || line[0] == '*')
1331 			continue;
1332 		else {
1333 			line[strlen(line)] = '\0';
1334 			if (sscanf(line, "%hu %hu %hu %hu %hu %hu %d",
1335 			    &disk_geom.dkg_pcyl,
1336 			    &disk_geom.dkg_ncyl,
1337 			    &disk_geom.dkg_acyl,
1338 			    &disk_geom.dkg_bcyl,
1339 			    &disk_geom.dkg_nhead,
1340 			    &disk_geom.dkg_nsect,
1341 			    &sectsiz) != 7) {
1342 				(void) fprintf(stderr,
1343 				    "Syntax error:\n	\"%s\".\n",
1344 				    line);
1345 				return (1);
1346 			}
1347 			break;
1348 		} /* else */
1349 	} /* while (fgets(line, sizeof (line) - 1, fp)) */
1350 
1351 	if (!io_image) {
1352 		if (ioctl(Dev, DKIOCSGEOM, &disk_geom)) {
1353 			(void) fprintf(stderr,
1354 			    "fdisk: Cannot set label geometry.\n");
1355 			return (1);
1356 		}
1357 	} else {
1358 		Numcyl = hba_Numcyl = disk_geom.dkg_ncyl;
1359 		heads = hba_heads = disk_geom.dkg_nhead;
1360 		sectors = hba_sectors = disk_geom.dkg_nsect;
1361 		acyl = disk_geom.dkg_acyl;
1362 	}
1363 
1364 	(void) fclose(fp);
1365 	return (0);
1366 }
1367 
1368 /*
1369  * dev_mboot_read
1370  * Read the master boot sector from the device.
1371  */
1372 static void
1373 dev_mboot_read(void)
1374 {
1375 	if ((ioctl(Dev, DKIOCGMBOOT, Bootsect) < 0) && (errno != ENOTTY)) {
1376 		perror("Error in ioctl DKIOCGMBOOT");
1377 	}
1378 	if (errno == 0)
1379 		return;
1380 	if (lseek(Dev, 0, SEEK_SET) == -1) {
1381 		(void) fprintf(stderr,
1382 		    "fdisk: Error seeking to partition table on %s.\n",
1383 		    Dfltdev);
1384 		if (!io_image)
1385 			exit(1);
1386 	}
1387 	if (read(Dev, Bootsect, sectsiz) != sectsiz) {
1388 		(void) fprintf(stderr,
1389 		    "fdisk: Error reading partition table from %s.\n",
1390 		    Dfltdev);
1391 		if (!io_image)
1392 			exit(1);
1393 	}
1394 }
1395 
1396 /*
1397  * dev_mboot_write
1398  * Write the master boot sector to the device.
1399  */
1400 static void
1401 dev_mboot_write(off_t sect, char *buff, int bootsiz)
1402 {
1403 	int 	new_pt, old_pt, error;
1404 	int	clr_efi = -1;
1405 
1406 	if (io_readonly)
1407 		return;
1408 
1409 	if (io_debug) {
1410 		(void) fprintf(stderr, "About to write fdisk table:\n");
1411 		print_Table();
1412 		if (io_ifdisk) {
1413 			(void) fprintf(stderr, "Press Enter to continue.\n");
1414 			(void) fgets(s, sizeof (s), stdin);
1415 		}
1416 	}
1417 
1418 	/*
1419 	 * If the new table has any Solaris partitions and the old
1420 	 * table does not have an entry that describes it
1421 	 * exactly then clear the old vtoc (if any).
1422 	 */
1423 	for (new_pt = 0; new_pt < FD_NUMPART; new_pt++) {
1424 
1425 		/* We only care about potential Solaris parts. */
1426 		if (Table[new_pt].systid != SUNIXOS &&
1427 		    Table[new_pt].systid != SUNIXOS2)
1428 			continue;
1429 
1430 		/* Does the old table have an exact entry for the new entry? */
1431 		for (old_pt = 0; old_pt < FD_NUMPART; old_pt++) {
1432 
1433 			/* We only care about old Solaris partitions. */
1434 			if ((Old_Table[old_pt].systid == SUNIXOS) ||
1435 			    (Old_Table[old_pt].systid == SUNIXOS2)) {
1436 
1437 				/* Is this old one the same as a new one? */
1438 				if ((Old_Table[old_pt].relsect ==
1439 				    Table[new_pt].relsect) &&
1440 				    (Old_Table[old_pt].numsect ==
1441 				    Table[new_pt].numsect))
1442 					break; /* Yes */
1443 			}
1444 		}
1445 
1446 		/* Did a solaris partition change location or size? */
1447 		if (old_pt >= FD_NUMPART) {
1448 			/* Yes clear old vtoc */
1449 			if (io_debug) {
1450 				(void) fprintf(stderr,
1451 				    "Clearing VTOC labels from NEW"
1452 				    " table\n");
1453 			}
1454 			clear_vtoc(NEW, new_pt);
1455 		}
1456 	}
1457 
1458 	/* see if the old table had EFI */
1459 	for (old_pt = 0; old_pt < FD_NUMPART; old_pt++) {
1460 		if (Old_Table[old_pt].systid == EFI_PMBR) {
1461 			clr_efi = old_pt;
1462 		}
1463 	}
1464 
1465 	/* look to see if a EFI partition changed in relsect/numsect */
1466 	for (new_pt = 0; new_pt < FD_NUMPART; new_pt++) {
1467 		if (Table[new_pt].systid != EFI_PMBR)
1468 			continue;
1469 		for (old_pt = 0; old_pt < FD_NUMPART; old_pt++) {
1470 			if ((Old_Table[old_pt].systid ==
1471 			    Table[new_pt].systid) &&
1472 			    (Old_Table[old_pt].relsect ==
1473 			    Table[new_pt].relsect) &&
1474 			    (Old_Table[old_pt].numsect ==
1475 			    Table[new_pt].numsect)) {
1476 				/*
1477 				 * New EFI guard partition matches old.
1478 				 * Do not clear EFI labels in this case.
1479 				 */
1480 				clr_efi = -1;
1481 				break;
1482 			}
1483 		}
1484 
1485 		/*
1486 		 * if EFI partition changed, set the flag to clear
1487 		 * the EFI GPT
1488 		 */
1489 		if (old_pt == FD_NUMPART && Table[new_pt].begcyl != 0) {
1490 			clr_efi = 0;
1491 		}
1492 		break;
1493 	}
1494 
1495 	/* clear labels if necessary */
1496 	if (clr_efi >= 0) {
1497 		if (io_debug) {
1498 			(void) fprintf(stderr, "Clearing EFI labels\n");
1499 		}
1500 		if ((error = clear_efi()) != 0) {
1501 			if (io_debug) {
1502 				(void) fprintf(stderr,
1503 				    "\tError %d clearing EFI labels"
1504 				    " (probably no EFI labels exist)\n",
1505 				    error);
1506 			}
1507 		}
1508 	}
1509 
1510 	if ((ioctl(Dev, DKIOCSMBOOT, buff) == -1) && (errno != ENOTTY)) {
1511 		(void) fprintf(stderr,
1512 		    "fdisk: Error in ioctl DKIOCSMBOOT on %s.\n",
1513 		    Dfltdev);
1514 	}
1515 	if (errno == 0)
1516 		return;
1517 
1518 	/* write to disk drive */
1519 	if (lseek(Dev, sect, SEEK_SET) == -1) {
1520 		(void) fprintf(stderr,
1521 		    "fdisk: Error seeking to master boot record on %s.\n",
1522 		    Dfltdev);
1523 		exit(1);
1524 	}
1525 	if (write(Dev, buff, bootsiz) != bootsiz) {
1526 		(void) fprintf(stderr,
1527 		    "fdisk: Error writing master boot record to %s.\n",
1528 		    Dfltdev);
1529 		exit(1);
1530 	}
1531 }
1532 
1533 /*
1534  * mboot_read
1535  * Read the prototype boot records from the files.
1536  */
1537 static void
1538 mboot_read(void)
1539 {
1540 	int mDev, i;
1541 	struct ipart *part;
1542 
1543 #if defined(i386) || defined(sparc)
1544 	/*
1545 	 * If the master boot file hasn't been specified, use the
1546 	 * implementation architecture name to generate the default one.
1547 	 */
1548 	if (io_mboot == (char *)0) {
1549 		/*
1550 		 * Bug ID 1249035:
1551 		 *	The mboot file must be delivered on all platforms
1552 		 *	and installed in a non-platform-dependent
1553 		 *	directory; i.e., /usr/lib/fs/ufs.
1554 		 */
1555 		io_mboot = "/usr/lib/fs/ufs/mboot";
1556 	}
1557 
1558 	/* First read in the master boot record */
1559 
1560 	/* Open the master boot proto file */
1561 	if ((mDev = open(io_mboot, O_RDONLY, 0666)) == -1) {
1562 		(void) fprintf(stderr,
1563 		    "fdisk: Cannot open master boot file %s.\n",
1564 		    io_mboot);
1565 		exit(1);
1566 	}
1567 
1568 	/* Read the master boot program */
1569 	if (read(mDev, &BootCod, sizeof (struct mboot)) != sizeof
1570 	    (struct mboot)) {
1571 		(void) fprintf(stderr,
1572 		    "fdisk: Cannot read master boot file %s.\n",
1573 		    io_mboot);
1574 		exit(1);
1575 	}
1576 
1577 	/* Is this really a master boot record? */
1578 	if (LE_16(BootCod.signature) != MBB_MAGIC) {
1579 		(void) fprintf(stderr,
1580 		    "fdisk: Invalid master boot file %s.\n", io_mboot);
1581 		(void) fprintf(stderr,
1582 		    "Bad magic number: is %x, but should be %x.\n",
1583 		    LE_16(BootCod.signature), MBB_MAGIC);
1584 		exit(1);
1585 	}
1586 
1587 	(void) close(mDev);
1588 #else
1589 #error	fdisk needs to be ported to new architecture
1590 #endif
1591 
1592 	/* Zero out the partitions part of this record */
1593 	part = (struct ipart *)BootCod.parts;
1594 	for (i = 0; i < FD_NUMPART; i++, part++) {
1595 		(void) memset(part, 0, sizeof (struct ipart));
1596 	}
1597 
1598 }
1599 
1600 /*
1601  * fill_patt
1602  * Fill the disk with user/sector number pattern.
1603  */
1604 static void
1605 fill_patt(void)
1606 {
1607 	int	*buff_ptr, i;
1608 	off_t	*off_ptr;
1609 	int	io_fpatt = 0;
1610 	int	io_ipatt = 0;
1611 
1612 	if (strncmp(io_fatt, "#", 1) != 0) {
1613 		io_fpatt++;
1614 		io_ipatt = strtoul(io_fatt, 0, 0);
1615 		buff_ptr = (int *)Bootsect;
1616 		for (i = 0; i < sectsiz; i += 4, buff_ptr++)
1617 			*buff_ptr = io_ipatt;
1618 	}
1619 
1620 	/*
1621 	 * Fill disk with pattern based on block number.
1622 	 * Write to the disk at absolute relative block io_offset
1623 	 * for io_size blocks.
1624 	 */
1625 	while (io_size--) {
1626 		off_ptr = (off_t *)Bootsect;
1627 		if (!io_fpatt) {
1628 			for (i = 0; i < sectsiz;
1629 			    i += sizeof (off_t), off_ptr++)
1630 				*off_ptr = io_offset;
1631 		}
1632 		/* Write the data to disk */
1633 		if (lseek(Dev, (off_t)(sectsiz * io_offset++),
1634 		    SEEK_SET) == -1) {
1635 			(void) fprintf(stderr, "fdisk: Error seeking on %s.\n",
1636 			    Dfltdev);
1637 			exit(1);
1638 		}
1639 		if (write(Dev, Bootsect, sectsiz) != sectsiz) {
1640 			(void) fprintf(stderr, "fdisk: Error writing %s.\n",
1641 			    Dfltdev);
1642 			exit(1);
1643 		}
1644 	} /* while (--io_size); */
1645 }
1646 
1647 /*
1648  * abs_read
1649  * Read from the disk at absolute relative block io_offset for
1650  * io_size blocks. Write the data to standard ouput (-r).
1651  */
1652 static void
1653 abs_read(void)
1654 {
1655 	int c;
1656 
1657 	while (io_size--) {
1658 		if (lseek(Dev, (off_t)(sectsiz * io_offset++),
1659 		    SEEK_SET) == -1) {
1660 			(void) fprintf(stderr, "fdisk: Error seeking on %s.\n",
1661 			    Dfltdev);
1662 			exit(1);
1663 		}
1664 		if (read(Dev, Bootsect, sectsiz) != sectsiz) {
1665 			(void) fprintf(stderr, "fdisk: Error reading %s.\n",
1666 			    Dfltdev);
1667 			exit(1);
1668 		}
1669 
1670 		/* Write to standard ouptut */
1671 		if ((c = write(1, Bootsect, (unsigned)sectsiz)) != sectsiz) {
1672 			if (c >= 0) {
1673 				if (io_debug)
1674 					(void) fprintf(stderr,
1675 					    "fdisk: Output warning: %d of %d"
1676 					    " characters written.\n",
1677 					    c, sectsiz);
1678 				exit(2);
1679 			} else {
1680 				perror("write error on output file.");
1681 				exit(2);
1682 			}
1683 		} /* if ((c = write(1, Bootsect, (unsigned)sectsiz)) */
1684 			/* != sectsiz) */
1685 	} /* while (--io_size); */
1686 	exit(0);
1687 }
1688 
1689 /*
1690  * abs_write
1691  * Read the data from standard input. Write to the disk at
1692  * absolute relative block io_offset for io_size blocks (-w).
1693  */
1694 static void
1695 abs_write(void)
1696 {
1697 	int c, i;
1698 
1699 	while (io_size--) {
1700 		int part_exit = 0;
1701 		/* Read from standard input */
1702 		if ((c = read(0, Bootsect, (unsigned)sectsiz)) != sectsiz) {
1703 			if (c >= 0) {
1704 				if (io_debug)
1705 				(void) fprintf(stderr,
1706 				    "fdisk: WARNING: Incomplete read (%d of"
1707 				    " %d characters read) on input file.\n",
1708 				    c, sectsiz);
1709 				/* Fill pattern to mark partial sector in buf */
1710 				for (i = c; i < sectsiz; ) {
1711 					Bootsect[i++] = 0x41;
1712 					Bootsect[i++] = 0x62;
1713 					Bootsect[i++] = 0x65;
1714 					Bootsect[i++] = 0;
1715 				}
1716 				part_exit++;
1717 			} else {
1718 				perror("read error on input file.");
1719 				exit(2);
1720 			}
1721 
1722 		}
1723 		/* Write to disk drive */
1724 		if (lseek(Dev, (off_t)(sectsiz * io_offset++),
1725 		    SEEK_SET) == -1) {
1726 			(void) fprintf(stderr, "fdisk: Error seeking on %s.\n",
1727 			    Dfltdev);
1728 			exit(1);
1729 		}
1730 		if (write(Dev, Bootsect, sectsiz) != sectsiz) {
1731 			(void) fprintf(stderr, "fdisk: Error writing %s.\n",
1732 			    Dfltdev);
1733 			exit(1);
1734 		}
1735 		if (part_exit)
1736 		exit(0);
1737 	} /* while (--io_size); */
1738 	exit(1);
1739 }
1740 
1741 
1742 /*
1743  * load
1744  * Load will either read the fdisk table from a file or add or
1745  * delete an entry (-A, -D, -F).
1746  */
1747 
1748 static void
1749 load(int funct, char *file)
1750 {
1751 	int	id;
1752 	int	act;
1753 	int	bhead;
1754 	int	bsect;
1755 	int	bcyl;
1756 	int	ehead;
1757 	int	esect;
1758 	int	ecyl;
1759 	uint32_t	rsect;
1760 	uint32_t	numsect;
1761 	char	line[256];
1762 	int	i = 0;
1763 	FILE *fp;
1764 	int	startindex = 0;
1765 	int	tmpindex = 0;
1766 #ifdef i386
1767 	int 	ext_part_present = 0;
1768 	uint32_t	begsec, endsec, relsect;
1769 	logical_drive_t *temp;
1770 	int part_count = 0, ldcnt = 0;
1771 	uint32_t ext_beg_sec;
1772 	uint32_t old_ext_beg_sec = 0, old_ext_num_sec = 0;
1773 	uint32_t new_ext_beg_sec = 0, new_ext_num_sec = 0;
1774 	int ext_part_inited = 0;
1775 	uchar_t	systid;
1776 #endif
1777 
1778 	switch (funct) {
1779 
1780 	case LOADFILE:
1781 
1782 		/*
1783 		 * Zero out the table before loading it, which will
1784 		 * force it to be updated on disk later (-F
1785 		 * fdisk_file).
1786 		 */
1787 		nulltbl();
1788 
1789 		/* Open the prototype file */
1790 		if ((fp = fopen(file, "r")) == NULL) {
1791 			(void) fprintf(stderr,
1792 			    "fdisk: Cannot open prototype partition file %s.\n",
1793 			    file);
1794 			exit(1);
1795 		}
1796 
1797 		/* Read a line from the file */
1798 		while (fgets(line, sizeof (line) - 1, fp)) {
1799 			if (pars_fdisk(line, &id, &act, &bhead, &bsect,
1800 			    &bcyl, &ehead, &esect, &ecyl, &rsect, &numsect)) {
1801 				continue;
1802 			}
1803 #ifdef i386
1804 			part_count++;
1805 
1806 			if (fdisk_is_dos_extended((uchar_t)id)) {
1807 				if (ext_part_present) {
1808 					(void) fprintf(stderr,
1809 					    "Extended partition"
1810 					    " already exists\n");
1811 					(void) fprintf(stderr, "fdisk: Error on"
1812 					    " entry \"%s\".\n", line);
1813 					exit(1);
1814 				}
1815 				ext_part_present = 1;
1816 				/*
1817 				 * If the existing extended partition's start
1818 				 * and size matches the new one, do not
1819 				 * initialize the extended partition EBR
1820 				 * (Extended Boot Record) because there could
1821 				 * be existing logical drives.
1822 				 */
1823 				for (i = 0; i < FD_NUMPART; i++) {
1824 					systid = Old_Table[i].systid;
1825 					if (fdisk_is_dos_extended(systid)) {
1826 						old_ext_beg_sec =
1827 						    Old_Table[i].relsect;
1828 						old_ext_num_sec =
1829 						    Old_Table[i].numsect;
1830 						break;
1831 					}
1832 				}
1833 				new_ext_beg_sec = rsect;
1834 				new_ext_num_sec = numsect;
1835 				if ((old_ext_beg_sec != new_ext_beg_sec) ||
1836 				    (old_ext_num_sec != new_ext_num_sec)) {
1837 					(void) fdisk_init_ext_part(epp,
1838 					    new_ext_beg_sec, new_ext_num_sec);
1839 					ext_part_inited = 1;
1840 				}
1841 			}
1842 
1843 			if (part_count > FD_NUMPART) {
1844 				/* This line should be logical drive info */
1845 				int offset = MAX_LOGDRIVE_OFFSET;
1846 				if (!ext_part_present) {
1847 					/* Erroneous input file */
1848 					(void) fprintf(stderr,
1849 					    "More than 4 primary"
1850 					    " partitions found in input\n");
1851 					(void) fprintf(stderr, "Exiting...\n");
1852 					exit(1);
1853 				}
1854 
1855 				if (numsect == 0) {
1856 					continue;
1857 				}
1858 
1859 				/*
1860 				 * If the start and size of the existing
1861 				 * extended partition matches the new one and
1862 				 * new logical drives are being defined via
1863 				 * the input file, initialize the EBR.
1864 				 */
1865 				if (!ext_part_inited) {
1866 					(void) fdisk_init_ext_part(epp,
1867 					    new_ext_beg_sec, new_ext_num_sec);
1868 					ext_part_inited = 1;
1869 				}
1870 
1871 				begsec = rsect - offset;
1872 				if ((ldcnt =
1873 				    fdisk_get_logical_drive_count(epp)) == 0) {
1874 					/* Adding the first logical drive */
1875 					/*
1876 					 * Make sure that begsec doesnt wrap
1877 					 * around. This can happen if rsect is
1878 					 * less than offset.
1879 					 */
1880 					if (rsect < offset) {
1881 						(void) fprintf(stderr,
1882 						    "Minimum of "
1883 						    "63 free sectors required "
1884 						    "before the beginning of "
1885 						    "a logical drive.");
1886 						exit(1);
1887 					}
1888 					/*
1889 					 * Check if the first logical drive
1890 					 * is out of order. In that case, do
1891 					 * not subtract MAX_LOGDRIVE_OFFSET
1892 					 * from the given start of partition.
1893 					 */
1894 					if (begsec != new_ext_beg_sec) {
1895 						begsec = rsect;
1896 						offset = 0;
1897 					}
1898 				}
1899 				if (ldcnt >= MAX_EXT_PARTS) {
1900 					(void) fprintf(stderr,
1901 					    "\nError : Number of "
1902 					    "logical drives exceeds limit of "
1903 					    "%d.\n", MAX_EXT_PARTS);
1904 					exit(1);
1905 				}
1906 
1907 				if (id > FDISK_MAX_VALID_PART_ID) {
1908 					(void) fprintf(stderr,
1909 					    "Invalid partition ID\n");
1910 					(void) fprintf(stderr, "fdisk: Error on"
1911 					    " entry \"%s\".\n", line);
1912 					exit(1);
1913 				}
1914 
1915 				endsec = rsect + numsect - 1;
1916 				if (fdisk_validate_logical_drive(epp,
1917 				    begsec, offset, numsect) == 0) {
1918 					if (id == EFI_PMBR) {
1919 						(void) fprintf(stderr, "EFI "
1920 						    "partitions not supported "
1921 						    "inside extended "
1922 						    "partition\n");
1923 						exit(1);
1924 					}
1925 					fdisk_add_logical_drive(epp, begsec,
1926 					    endsec, id);
1927 					continue;
1928 				} else {
1929 					(void) fprintf(stderr, "fdisk: Error on"
1930 					    " entry \"%s\".\n", line);
1931 					exit(1);
1932 				}
1933 			}
1934 #endif
1935 
1936 			/*
1937 			 * Validate the partition. It cannot start at sector
1938 			 * 0 unless it is UNUSED or already exists
1939 			 */
1940 			if (validate_part(id, rsect, numsect) < 0) {
1941 				(void) fprintf(stderr,
1942 				    "fdisk: Error on entry \"%s\".\n",
1943 				    line);
1944 				exit(1);
1945 			}
1946 
1947 			if ((tmpindex = entry_from_old_table(id, act, bhead,
1948 			    bsect, bcyl, ehead, esect, ecyl, rsect, numsect,
1949 			    startindex)) != -1) {
1950 				/*
1951 				 * If we got here it means we copied an
1952 				 * unmodified entry. So there is no need
1953 				 * to insert it in the table or do any
1954 				 * checks against disk size.
1955 				 *
1956 				 * This is a work around on the following
1957 				 * situation (for IDE disks, at least):
1958 				 * Different operation systems calculate
1959 				 * disk size different ways, of which there
1960 				 * are two main ways.
1961 				 *
1962 				 * The first, rounds the disk size to modulo
1963 				 * cylinder size (virtual made-up cylinder
1964 				 * usually based on maximum number of heads
1965 				 * and sectors in partition table fields).
1966 				 * Our OS's (for IDE) and most other "Unix"
1967 				 * type OS's do this.
1968 				 *
1969 				 * The second, uses every single block
1970 				 * on the disk (to maximize available space).
1971 				 * Since disk manufactures do not know about
1972 				 * "virtual cylinders", there are some number
1973 				 * of blocks that make up a partial cylinder
1974 				 * at the end of the disk.
1975 				 *
1976 				 * The difference between these two methods
1977 				 * is where the problem is. When one
1978 				 * tries to install Solaris/OpenSolaris on
1979 				 * a disk that has another OS using that
1980 				 * "partial cylinder", install fails. It fails
1981 				 * since fdisk thinks its asked to create a
1982 				 * partition with the -F option that contains
1983 				 * a partition that runs off the end of the
1984 				 * disk.
1985 				 */
1986 				startindex = tmpindex + 1;
1987 				continue;
1988 			}
1989 
1990 			/*
1991 			 * Find an unused entry to use and put the entry
1992 			 * in table
1993 			 */
1994 			if ((startindex = insert_tbl(id, act, bhead, bsect,
1995 			    bcyl, ehead, esect, ecyl, rsect, numsect,
1996 			    startindex)) < 0) {
1997 				(void) fprintf(stderr,
1998 				    "fdisk: Error on entry \"%s\".\n",
1999 				    line);
2000 				exit(1);
2001 			}
2002 			startindex++;
2003 		} /* while (fgets(line, sizeof (line) - 1, fp)) */
2004 
2005 		if (verify_tbl() < 0) {
2006 			(void) fprintf(stderr,
2007 			    "fdisk: Cannot create partition table\n");
2008 			exit(1);
2009 		}
2010 
2011 		(void) fclose(fp);
2012 		return;
2013 
2014 	case LOADDEL:
2015 
2016 		/* Parse the user-supplied deletion line (-D) */
2017 		if (pars_fdisk(file, &id, &act, &bhead, &bsect, &bcyl,
2018 		    &ehead, &esect, &ecyl, &rsect, &numsect)) {
2019 			(void) fprintf(stderr,
2020 			    "fdisk: Syntax error \"%s\"\n", file);
2021 			exit(1);
2022 		}
2023 
2024 		/* Find the exact entry in the table */
2025 		for (i = 0; i < FD_NUMPART; i++) {
2026 			if (Table[i].systid == id &&
2027 			    Table[i].bootid == act &&
2028 			    Table[i].beghead == bhead &&
2029 			    Table[i].begsect == ((bsect & 0x3f) |
2030 			    (uchar_t)((bcyl>>2) & 0xc0)) &&
2031 			    Table[i].begcyl == (uchar_t)(bcyl & 0xff) &&
2032 			    Table[i].endhead == ehead &&
2033 			    Table[i].endsect == ((esect & 0x3f) |
2034 			    (uchar_t)((ecyl>>2) & 0xc0)) &&
2035 			    Table[i].endcyl == (uchar_t)(ecyl & 0xff) &&
2036 			    Table[i].relsect == LE_32(rsect) &&
2037 			    Table[i].numsect == LE_32(numsect)) {
2038 
2039 				(void) memset(&Table[i], 0,
2040 				    sizeof (struct ipart));
2041 #ifdef i386
2042 				if (fdisk_is_dos_extended(id)) {
2043 					(void) fdisk_delete_ext_part(epp);
2044 				}
2045 #endif
2046 				return;
2047 			}
2048 		}
2049 
2050 #ifdef i386
2051 		ldcnt = FD_NUMPART + 1;
2052 		for (temp = fdisk_get_ld_head(epp); temp != NULL;
2053 		    temp = temp->next) {
2054 			relsect = temp->abs_secnum + temp->logdrive_offset;
2055 			if (temp->parts[0].systid == id &&
2056 			    temp->parts[0].bootid == act &&
2057 			    temp->parts[0].beghead == bhead &&
2058 			    temp->parts[0].begsect == ((bsect & 0x3f) |
2059 			    (uchar_t)((bcyl>>2) & 0xc0)) &&
2060 			    temp->parts[0].begcyl == (uchar_t)(bcyl & 0xff) &&
2061 			    temp->parts[0].endhead == ehead &&
2062 			    temp->parts[0].endsect == ((esect & 0x3f) |
2063 			    (uchar_t)((ecyl>>2) & 0xc0)) &&
2064 			    temp->parts[0].endcyl == (uchar_t)(ecyl & 0xff) &&
2065 			    relsect == LE_32(rsect) &&
2066 			    temp->parts[0].numsect == LE_32(numsect)) {
2067 				fdisk_delete_logical_drive(epp, ldcnt);
2068 				return;
2069 			}
2070 			ldcnt++;
2071 		}
2072 #endif
2073 
2074 		(void) fprintf(stderr,
2075 		    "fdisk: Entry does not match any existing partition:\n"
2076 		    "	\"%s\"\n",
2077 		    file);
2078 		exit(1);
2079 		/* FALLTHROUGH */
2080 
2081 	case LOADADD:
2082 
2083 		/* Parse the user-supplied addition line (-A) */
2084 		if (pars_fdisk(file, &id, &act, &bhead, &bsect, &bcyl, &ehead,
2085 		    &esect, &ecyl, &rsect, &numsect)) {
2086 			(void) fprintf(stderr,
2087 			    "fdisk: Syntax error \"%s\"\n", file);
2088 			exit(1);
2089 		}
2090 
2091 		/* Validate the partition. It cannot start at sector 0 */
2092 		if (rsect == 0) {
2093 			(void) fprintf(stderr,
2094 			    "fdisk: New partition cannot start at sector 0:\n"
2095 			    "   \"%s\".\n",
2096 			    file);
2097 			exit(1);
2098 		}
2099 
2100 		/*
2101 		 * if the user wishes to add an EFI partition, we need
2102 		 * more extensive validation.  rsect should be 1, and
2103 		 * numsect should equal the entire disk capacity - 1
2104 		 */
2105 
2106 		if (id == EFI_PMBR) {
2107 			if (rsect != 1) {
2108 				(void) fprintf(stderr,
2109 				    "fdisk: EFI partitions must start at sector"
2110 				    " 1 (input rsect = %d)\n", rsect);
2111 				exit(1);
2112 			}
2113 
2114 
2115 			if (dev_capacity > DK_MAX_2TB) {
2116 				if (numsect != DK_MAX_2TB) {
2117 					(void) fprintf(stderr,
2118 					    "fdisk: EFI partitions must "
2119 					    "encompass the entire maximum 2 TB "
2120 					    "(input numsect: %u - max: %llu)\n",
2121 					    numsect, (diskaddr_t)DK_MAX_2TB);
2122 				exit(1);
2123 				}
2124 			} else if (numsect != dev_capacity - 1) {
2125 				(void) fprintf(stderr,
2126 				    "fdisk: EFI partitions must encompass the "
2127 				    "entire disk\n"
2128 				    "(input numsect: %u - avail: %llu)\n",
2129 				    numsect,
2130 				    dev_capacity - 1);
2131 				exit(1);
2132 			}
2133 		}
2134 
2135 #ifdef i386
2136 		if (id > FDISK_MAX_VALID_PART_ID) {
2137 			(void) printf("Invalid partition ID\n");
2138 			exit(1);
2139 		}
2140 
2141 		if ((fdisk_ext_part_exists(epp)) &&
2142 		    (fdisk_is_dos_extended(id))) {
2143 			(void) fprintf(stderr,
2144 			    "Extended partition already exists.\n");
2145 			(void) fprintf(stderr,
2146 			    "fdisk: Invalid entry could not be "
2147 			    "inserted:\n        \"%s\"\n", file);
2148 			exit(1);
2149 		}
2150 
2151 		if (fdisk_ext_part_exists(epp) &&
2152 		    (rsect >= (ext_beg_sec = fdisk_get_ext_beg_sec(epp))) &&
2153 		    (rsect <= (fdisk_get_ext_end_sec(epp)))) {
2154 			int offset = MAX_LOGDRIVE_OFFSET;
2155 
2156 			/*
2157 			 * Make sure that begsec doesnt wrap around.
2158 			 * This can happen if rsect is less than offset
2159 			 */
2160 			if (rsect < offset) {
2161 				return;
2162 			}
2163 			begsec = rsect - offset;
2164 			if ((ldcnt = fdisk_get_logical_drive_count(epp)) == 0) {
2165 				/*
2166 				 * Adding the first logical drive
2167 				 * Check if the first logical drive
2168 				 * is out of order. In that case, do
2169 				 * not subtract MAX_LOGDRIVE_OFFSET
2170 				 * from the given start of partition.
2171 				 */
2172 				if (begsec != ext_beg_sec) {
2173 					begsec = rsect;
2174 					offset = 0;
2175 				}
2176 			}
2177 
2178 			if (ldcnt >= MAX_EXT_PARTS) {
2179 				(void) printf("\nNumber of logical drives "
2180 				    "exceeds limit of %d.\n", MAX_EXT_PARTS);
2181 				(void) printf("Failing further additions.\n");
2182 				exit(1);
2183 			}
2184 
2185 			if (numsect == 0) {
2186 				(void) fprintf(stderr,
2187 				    "fdisk: Partition size cannot be zero:\n"
2188 				    "   \"%s\".\n",
2189 				    file);
2190 				exit(1);
2191 			}
2192 			endsec = rsect + numsect - 1;
2193 			if (fdisk_validate_logical_drive(epp, begsec,
2194 			    offset, numsect) == 0) {
2195 				/* Valid logical drive */
2196 				fdisk_add_logical_drive(epp, begsec, endsec,
2197 				    id);
2198 				return;
2199 			} else {
2200 				(void) fprintf(stderr,
2201 				    "fdisk: Invalid entry could not be "
2202 				    "inserted:\n        \"%s\"\n", file);
2203 				exit(1);
2204 			}
2205 		}
2206 #endif
2207 
2208 		/* Find unused entry for use and put entry in table */
2209 		if (insert_tbl(id, act, bhead, bsect, bcyl, ehead, esect,
2210 		    ecyl, rsect, numsect, 0) < 0) {
2211 			(void) fprintf(stderr,
2212 			    "fdisk: Invalid entry could not be inserted:\n"
2213 			    "	\"%s\"\n",
2214 			    file);
2215 			exit(1);
2216 		}
2217 
2218 		/* Make sure new entry does not overlap existing entry */
2219 		if (verify_tbl() < 0) {
2220 			(void) fprintf(stderr,
2221 			    "fdisk: Cannot create partition \"%s\"\n", file);
2222 			exit(1);
2223 		}
2224 	} /* switch funct */
2225 }
2226 
2227 /*
2228  * Set_Table_CHS_Values
2229  *
2230  * This will calculate the CHS values for beginning and ending CHS
2231  * for a single partition table entry (ti) based on the relsect
2232  * and numsect values contained in the partion table entry.
2233  *
2234  * hba_heads and hba_sectors contain the number of heads and sectors.
2235  *
2236  * If the number of cylinders exceeds the MAX_CYL,
2237  * then maximum values will be placed in the corresponding chs entry.
2238  */
2239 static void
2240 Set_Table_CHS_Values(int ti)
2241 {
2242 	uint32_t	lba, cy, hd, sc;
2243 
2244 	lba = (uint32_t)Table[ti].relsect;
2245 	if (lba >= hba_heads * hba_sectors * MAX_CYL) {
2246 		/*
2247 		 * the lba address cannot be expressed in CHS value
2248 		 * so store the maximum CHS field values in the CHS fields.
2249 		 */
2250 		cy = MAX_CYL + 1;
2251 		hd = MAX_HEAD + 1;
2252 		sc = MAX_SECT;
2253 	} else {
2254 		cy = lba / hba_sectors / hba_heads;
2255 		hd = lba / hba_sectors % hba_heads;
2256 		sc = lba % hba_sectors + 1;
2257 	}
2258 	Table[ti].begcyl = cy & 0xff;
2259 	Table[ti].beghead = (uchar_t)hd;
2260 	Table[ti].begsect = (uchar_t)(((cy >> 2) & 0xc0) | sc);
2261 
2262 	/*
2263 	 * This code is identical to the code above
2264 	 * except that it works on ending CHS values
2265 	 */
2266 	lba = (uint32_t)(Table[ti].relsect + Table[ti].numsect - 1);
2267 	if (lba >= hba_heads * hba_sectors * MAX_CYL) {
2268 		cy = MAX_CYL + 1;
2269 		hd = MAX_HEAD + 1;
2270 		sc = MAX_SECT;
2271 	} else {
2272 		cy = lba / hba_sectors / hba_heads;
2273 		hd = lba / hba_sectors % hba_heads;
2274 		sc = lba % hba_sectors + 1;
2275 	}
2276 	Table[ti].endcyl = cy & 0xff;
2277 	Table[ti].endhead = (uchar_t)hd;
2278 	Table[ti].endsect = (uchar_t)(((cy >> 2) & 0xc0) | sc);
2279 }
2280 
2281 /*
2282  * insert_tbl
2283  * 	Insert entry into fdisk table. Check all user-supplied values
2284  *	for the entry, but not the validity relative to other table
2285  *	entries!
2286  */
2287 static int
2288 insert_tbl(
2289     int id, int act,
2290     int bhead, int bsect, int bcyl,
2291     int ehead, int esect, int ecyl,
2292     uint32_t rsect, uint32_t numsect, int startindex)
2293 {
2294 	int	i;
2295 
2296 	/* validate partition size */
2297 	if (((diskaddr_t)rsect + numsect) > dev_capacity) {
2298 		(void) fprintf(stderr,
2299 		    "fdisk: Partition table exceeds the size of the disk.\n");
2300 		return (-1);
2301 	}
2302 
2303 
2304 	/* find UNUSED partition table entry */
2305 	for (i = startindex; i < FD_NUMPART; i++) {
2306 		if (Table[i].systid == UNUSED) {
2307 			break;
2308 		}
2309 	}
2310 	if (i >= FD_NUMPART) {
2311 		(void) fprintf(stderr, "fdisk: Partition table is full.\n");
2312 		return (-1);
2313 	}
2314 
2315 	Table[i].systid = (uchar_t)id;
2316 	Table[i].bootid = (uchar_t)act;
2317 	Table[i].numsect = LE_32(numsect);
2318 	Table[i].relsect = LE_32(rsect);
2319 
2320 	if (id == UNUSED) {
2321 		(void) memset(&Table[i], 0, sizeof (struct ipart));
2322 	} else if (0 < bsect && bsect <= MAX_SECT &&
2323 	    0 <= bhead && bhead <= MAX_HEAD + 1 &&
2324 	    0 < esect && esect <= MAX_SECT &&
2325 	    0 <= ehead && ehead <= MAX_HEAD + 1) {
2326 
2327 		/*
2328 		 * If we have been called with a valid geometry, use it
2329 		 * valid means non-zero values that fit in the BIOS fields
2330 		 */
2331 		if (bcyl > MAX_CYL) {
2332 			/*
2333 			 * bcyl is set to the special fence value indicating
2334 			 * that the geometry is not representable for the
2335 			 * start LBA.
2336 			 * Set all fields to the maximum values.
2337 			 */
2338 			bcyl = MAX_CYL + 1;
2339 			bhead = MAX_HEAD + 1;
2340 			bsect = MAX_SECT;
2341 		}
2342 		if (ecyl > MAX_CYL) {
2343 			ecyl = MAX_CYL + 1;
2344 			ehead = MAX_HEAD + 1;
2345 			esect = MAX_SECT;
2346 		}
2347 		Table[i].begcyl = bcyl & 0xff;
2348 		Table[i].endcyl = ecyl & 0xff;
2349 		Table[i].beghead = (uchar_t)bhead;
2350 		Table[i].endhead = (uchar_t)ehead;
2351 		Table[i].begsect = (uchar_t)(((bcyl >> 2) & 0xc0) | bsect);
2352 		Table[i].endsect = ((ecyl >> 2) & 0xc0) | esect;
2353 	} else {
2354 
2355 		/*
2356 		 * The specified values are invalid,
2357 		 * so calculate the values based on hba_heads, hba_sectors
2358 		 */
2359 		Set_Table_CHS_Values(i);
2360 	}
2361 
2362 	/*
2363 	 * return partition index
2364 	 */
2365 	return (i);
2366 }
2367 
2368 /*
2369  * entry_from_old_table
2370  *	If the specified entry is in the old table and is not a Solaris entry
2371  *	then insert same entry into new fdisk table. If we do this then
2372  *	all checks are skipped for that entry!
2373  */
2374 static int
2375 entry_from_old_table(
2376     int id, int act,
2377     int bhead, int bsect, int bcyl,
2378     int ehead, int esect, int ecyl,
2379     uint32_t rsect, uint32_t numsect, int startindex)
2380 {
2381 	uint32_t	i, j;
2382 
2383 	if (id == SUNIXOS || id == SUNIXOS2 || id == UNUSED)
2384 		return (-1);
2385 	for (i = 0; i < FD_NUMPART; i++) {
2386 		if (Old_Table[i].systid == id &&
2387 		    Old_Table[i].bootid == act &&
2388 		    Old_Table[i].beghead == bhead &&
2389 		    Old_Table[i].begsect == ((bsect & 0x3f) |
2390 		    (uchar_t)((bcyl>>2) & 0xc0)) &&
2391 		    Old_Table[i].begcyl == (uchar_t)(bcyl & 0xff) &&
2392 		    Old_Table[i].endhead == ehead &&
2393 		    Old_Table[i].endsect == ((esect & 0x3f) |
2394 		    (uchar_t)((ecyl>>2) & 0xc0)) &&
2395 		    Old_Table[i].endcyl == (uchar_t)(ecyl & 0xff) &&
2396 		    Old_Table[i].relsect == lel(rsect) &&
2397 		    Old_Table[i].numsect == lel(numsect)) {
2398 			/* find UNUSED partition table entry */
2399 			for (j = startindex; j < FD_NUMPART; j++) {
2400 				if (Table[j].systid == UNUSED) {
2401 					(void) memcpy(&Table[j], &Old_Table[i],
2402 					    sizeof (Table[0]));
2403 					skip_verify[j] = 1;
2404 					return (j);
2405 
2406 				}
2407 			}
2408 			return (-1);
2409 		}
2410 
2411 	}
2412 	return (-1);
2413 }
2414 
2415 /*
2416  * verify_tbl
2417  * Verify that no partition entries overlap or exceed the size of
2418  * the disk.
2419  */
2420 static int
2421 verify_tbl(void)
2422 {
2423 	uint32_t	i, j, rsect, numsect;
2424 	int	noMoreParts = 0;
2425 	int	numParts = 0;
2426 
2427 	/* Make sure new entry does not overlap an existing entry */
2428 	for (i = 0; i < FD_NUMPART - 1; i++) {
2429 		if (Table[i].systid != UNUSED) {
2430 			numParts++;
2431 			/*
2432 			 * No valid partitions allowed after EFI_PMBR part
2433 			 */
2434 			if (noMoreParts) {
2435 				return (-1);
2436 			}
2437 
2438 			if (Table[i].systid == EFI_PMBR) {
2439 				/*
2440 				 * EFI_PMBR partition must be the only
2441 				 * partition
2442 				 */
2443 				noMoreParts = 1;
2444 
2445 				if (Table[i].relsect != 1) {
2446 					(void) fprintf(stderr, "ERROR: "
2447 					    "Invalid starting sector "
2448 					    "for EFI_PMBR partition:\n"
2449 					    "relsect %d "
2450 					    "(should be 1)\n",
2451 					    Table[i].relsect);
2452 
2453 					return (-1);
2454 				}
2455 
2456 				if (Table[i].numsect !=
2457 				    ((dev_capacity > DK_MAX_2TB) ? DK_MAX_2TB:
2458 				    (dev_capacity - 1))) {
2459 
2460 					(void) fprintf(stderr, "ERROR: "
2461 					    "EFI_PMBR partition must "
2462 					    "encompass the entire");
2463 
2464 					if (dev_capacity > DK_MAX_2TB)
2465 						(void) fprintf(stderr,
2466 						    "maximum 2 TB.\n "
2467 						    "numsect %u - "
2468 						    "actual %llu\n",
2469 						    Table[i].numsect,
2470 						    (diskaddr_t)DK_MAX_2TB);
2471 
2472 					else
2473 						(void) fprintf(stderr,
2474 						    "disk.\n numsect %u - "
2475 						    "actual %llu\n",
2476 						    Table[i].numsect,
2477 						    dev_capacity - 1);
2478 
2479 					return (-1);
2480 				}
2481 			}
2482 
2483 			/* make sure the partition isn't larger than the disk */
2484 			rsect = LE_32(Table[i].relsect);
2485 			numsect = LE_32(Table[i].numsect);
2486 
2487 			if ((((diskaddr_t)rsect + numsect) > dev_capacity) ||
2488 			    (((diskaddr_t)rsect + numsect) > DK_MAX_2TB)) {
2489 				if (!skip_verify[i])
2490 					return (-1);
2491 			}
2492 
2493 			for (j = i + 1; j < FD_NUMPART; j++) {
2494 				if (Table[j].systid != UNUSED) {
2495 					uint32_t t_relsect =
2496 					    LE_32(Table[j].relsect);
2497 					uint32_t t_numsect =
2498 					    LE_32(Table[j].numsect);
2499 
2500 					if (noMoreParts) {
2501 						(void) fprintf(stderr,
2502 						    "Cannot add partition to "
2503 						    "table; no more partitions "
2504 						    "allowed\n");
2505 
2506 						if (io_debug) {
2507 							(void) fprintf(stderr,
2508 							    "DEBUG: Current "
2509 							    "partition:\t"
2510 							    "%d:%d:%d:%d:%d:"
2511 							    "%d:%d:%d:%d:%d\n"
2512 							    "       Next "
2513 							    "partition:\t\t"
2514 							    "%d:%d:%d:%d:%d:"
2515 							    "%d:%d:%d:%d:%d\n",
2516 							    Table[i].systid,
2517 							    Table[i].bootid,
2518 							    Table[i].begcyl,
2519 							    Table[i].beghead,
2520 							    Table[i].begsect,
2521 							    Table[i].endcyl,
2522 							    Table[i].endhead,
2523 							    Table[i].endsect,
2524 							    Table[i].relsect,
2525 							    Table[i].numsect,
2526 							    Table[j].systid,
2527 							    Table[j].bootid,
2528 							    Table[j].begcyl,
2529 							    Table[j].beghead,
2530 							    Table[j].begsect,
2531 							    Table[j].endcyl,
2532 							    Table[j].endhead,
2533 							    Table[j].endsect,
2534 							    Table[j].relsect,
2535 							    Table[j].numsect);
2536 						}
2537 
2538 						return (-1);
2539 					}
2540 					if ((rsect >=
2541 					    (t_relsect + t_numsect)) ||
2542 					    ((rsect + numsect) <= t_relsect)) {
2543 						continue;
2544 					} else {
2545 						(void) fprintf(stderr, "ERROR: "
2546 						    "current partition overlaps"
2547 						    " following partition\n");
2548 
2549 						return (-1);
2550 					}
2551 				}
2552 			}
2553 		}
2554 	}
2555 	if (Table[i].systid != UNUSED) {
2556 		if (noMoreParts)
2557 			return (-1);
2558 		if (!skip_verify[i] &&
2559 		    ((((diskaddr_t)lel(Table[i].relsect) +
2560 		    lel(Table[i].numsect)) > dev_capacity) ||
2561 		    (((diskaddr_t)lel(Table[i].relsect) +
2562 		    lel(Table[i].numsect)) > DK_MAX_2TB))) {
2563 			return (-1);
2564 		}
2565 	}
2566 
2567 	return (numParts);
2568 }
2569 
2570 /*
2571  * pars_fdisk
2572  * Parse user-supplied data to set up fdisk partitions
2573  * (-A, -D, -F).
2574  */
2575 static int
2576 pars_fdisk(
2577     char *line,
2578     int *id, int *act,
2579     int *bhead, int *bsect, int *bcyl,
2580     int *ehead, int *esect, int *ecyl,
2581     uint32_t *rsect, uint32_t *numsect)
2582 {
2583 	int	i;
2584 	int64_t test;
2585 	char *tok, *p;
2586 	char buf[256];
2587 
2588 	if (line[0] == '\0' || line[0] == '\n' || line[0] == '*')
2589 		return (1);
2590 	line[strlen(line)] = '\0';
2591 	for (i = 0; i < strlen(line); i++) {
2592 		if (line[i] == '\0') {
2593 			break;
2594 		} else if (line[i] == ':') {
2595 			line[i] = ' ';
2596 		}
2597 	}
2598 	(void) strncpy(buf, line, 256);
2599 	errno = 0;
2600 	tok = strtok(buf, ": \t\n");
2601 	while (tok != NULL) {
2602 		for (p = tok; *p != '\0'; p++) {
2603 			if (!isdigit(*p)) {
2604 				(void) printf("Invalid input %s in line %s.\n",
2605 				    tok, line);
2606 				exit(1);
2607 			}
2608 		}
2609 
2610 		test = strtoll(tok, (char **)NULL, 10);
2611 		if ((test < 0) || (test > 0xFFFFFFFF) || (errno != 0)) {
2612 			(void) printf("Invalid input %s in line %s.\n", tok,
2613 			    line);
2614 			exit(1);
2615 		}
2616 		tok = strtok(NULL, ": \t\n");
2617 	}
2618 	if (sscanf(line, "%d %d %d %d %d %d %d %d %u %u",
2619 	    id, act, bhead, bsect, bcyl, ehead, esect, ecyl,
2620 	    rsect, numsect) != 10) {
2621 		(void) fprintf(stderr, "Syntax error:\n	\"%s\".\n", line);
2622 		exit(1);
2623 	}
2624 	return (0);
2625 }
2626 
2627 /*
2628  * validate_part
2629  * Validate that a new partition does not start at sector 0. Only UNUSED
2630  * partitions and previously existing partitions are allowed to start at 0.
2631  */
2632 static int
2633 validate_part(int id, uint32_t rsect, uint32_t numsect)
2634 {
2635 	int i;
2636 	if ((id != UNUSED) && (rsect == 0)) {
2637 		for (i = 0; i < FD_NUMPART; i++) {
2638 			if ((Old_Table[i].systid == id) &&
2639 			    (Old_Table[i].relsect == LE_32(rsect)) &&
2640 			    (Old_Table[i].numsect == LE_32(numsect)))
2641 				return (0);
2642 		}
2643 		(void) fprintf(stderr,
2644 		    "New partition cannot start at sector 0\n");
2645 		return (-1);
2646 	}
2647 #ifdef i386
2648 	if (id > FDISK_MAX_VALID_PART_ID) {
2649 		(void) fprintf(stderr, "Invalid partition ID\n");
2650 		return (-1);
2651 	}
2652 #endif
2653 	return (0);
2654 }
2655 
2656 /*
2657  * stage0
2658  * Print out interactive menu and process user input.
2659  */
2660 static void
2661 stage0(void)
2662 {
2663 #ifdef i386
2664 	int rval;
2665 #endif
2666 	dispmenu();
2667 	for (;;) {
2668 		(void) printf(Q_LINE);
2669 		(void) printf("Enter Selection: ");
2670 		(void) fgets(s, sizeof (s), stdin);
2671 		rm_blanks(s);
2672 #ifdef i386
2673 		while (!((s[0] > '0') && (s[0] < '8') &&
2674 		    ((s[1] == '\0') || (s[1] == '\n')))) {
2675 #else
2676 		while (!((s[0] > '0') && (s[0] < '7') &&
2677 		    ((s[1] == '\0') || (s[1] == '\n')))) {
2678 #endif
2679 			(void) printf(E_LINE); /* Clear any previous error */
2680 #ifdef i386
2681 			(void) printf(
2682 			    "Enter a one-digit number between 1 and 7.");
2683 #else
2684 			(void) printf(
2685 			    "Enter a one-digit number between 1 and 6.");
2686 #endif
2687 			(void) printf(Q_LINE);
2688 			(void) printf("Enter Selection: ");
2689 			(void) fgets(s, sizeof (s), stdin);
2690 			rm_blanks(s);
2691 		}
2692 		(void) printf(E_LINE);
2693 		switch (s[0]) {
2694 			case '1':
2695 				if (pcreate() == -1)
2696 					return;
2697 				break;
2698 			case '2':
2699 				if (pchange() == -1)
2700 					return;
2701 				break;
2702 			case '3':
2703 				if (pdelete() == -1)
2704 					return;
2705 				break;
2706 			case '4':
2707 				if (ppartid() == -1)
2708 					return;
2709 				break;
2710 #ifdef i386
2711 			case '5':
2712 				if (fdisk_ext_part_exists(epp)) {
2713 					ext_part_menu();
2714 				} else {
2715 					(void) printf(Q_LINE);
2716 					(void) printf("\nNo extended partition"
2717 					    " found\n");
2718 					(void) printf("Press enter to "
2719 					    "continue\n");
2720 					ext_read_input(s);
2721 				}
2722 				break;
2723 			case '6':
2724 				/* update disk partition table, if changed */
2725 				if (TableChanged() == 1) {
2726 					copy_Table_to_Bootblk();
2727 					dev_mboot_write(0, Bootsect, sectsiz);
2728 				}
2729 
2730 				/*
2731 				 * If the VTOC table is wrong fix it
2732 				 * (truncate only)
2733 				 */
2734 				if (io_adjt) {
2735 					fix_slice();
2736 				}
2737 				if (!io_readonly) {
2738 					rval = fdisk_commit_ext_part(epp);
2739 					switch (rval) {
2740 						case FDISK_SUCCESS:
2741 							/* Success */
2742 							/* Fallthrough */
2743 						case FDISK_ENOEXTPART:
2744 							/* Nothing to do */
2745 							break;
2746 						case FDISK_EMOUNTED:
2747 							(void) printf(Q_LINE);
2748 							preach_and_continue();
2749 							continue;
2750 						default:
2751 							perror("Commit failed");
2752 							exit(1);
2753 					}
2754 					libfdisk_fini(&epp);
2755 				}
2756 				(void) close(Dev);
2757 				exit(0);
2758 				/* NOTREACHED */
2759 #else
2760 			case '5':
2761 				/* update disk partition table, if changed */
2762 				if (TableChanged() == 1) {
2763 					copy_Table_to_Bootblk();
2764 					dev_mboot_write(0, Bootsect, sectsiz);
2765 				}
2766 				/*
2767 				 * If the VTOC table is wrong fix it
2768 				 * (truncate only)
2769 				 */
2770 				if (io_adjt) {
2771 					fix_slice();
2772 				}
2773 				(void) close(Dev);
2774 				exit(0);
2775 				/* FALLTHROUGH */
2776 #endif
2777 #ifdef i386
2778 			case '7':
2779 #else
2780 			case '6':
2781 #endif
2782 				/*
2783 				 * If the VTOC table is wrong fix it
2784 				 * (truncate only)
2785 				 */
2786 				if (io_adjt) {
2787 					fix_slice();
2788 				}
2789 				(void) close(Dev);
2790 				exit(0);
2791 				/* FALLTHROUGH */
2792 			default:
2793 				break;
2794 		}
2795 		copy_Table_to_Bootblk();
2796 		disptbl();
2797 		dispmenu();
2798 	}
2799 }
2800 
2801 /*
2802  * pcreate
2803  * Create partition entry in the table (interactive mode).
2804  */
2805 static int
2806 pcreate(void)
2807 {
2808 	uchar_t tsystid = 'z';
2809 	int i, j;
2810 	uint32_t numsect;
2811 	int retCode = 0;
2812 #ifdef i386
2813 	int ext_part_present = 0;
2814 #endif
2815 
2816 	i = 0;
2817 	for (;;) {
2818 		if (i == FD_NUMPART) {
2819 			(void) printf(E_LINE);
2820 			(void) printf(
2821 			    "The partition table is full!\n"
2822 			    "You must delete a partition before creating"
2823 			    " a new one.\n");
2824 			return (-1);
2825 		}
2826 		if (Table[i].systid == UNUSED) {
2827 			break;
2828 		}
2829 		i++;
2830 	}
2831 
2832 	numsect = 0;
2833 	for (i = 0; i < FD_NUMPART; i++) {
2834 		if (Table[i].systid != UNUSED) {
2835 			numsect += LE_32(Table[i].numsect);
2836 		}
2837 #ifdef i386
2838 		/* Check if an extended partition already exists */
2839 		if (fdisk_is_dos_extended(Table[i].systid)) {
2840 			ext_part_present = 1;
2841 		}
2842 #endif
2843 		if (numsect >= chs_capacity) {
2844 			(void) printf(E_LINE);
2845 			(void) printf("There is no more room on the disk for"
2846 			    " another partition.\n");
2847 			(void) printf(
2848 			    "You must delete a partition before creating"
2849 			    " a new one.\n");
2850 			return (-1);
2851 		}
2852 	}
2853 	while (tsystid == 'z') {
2854 
2855 		/*
2856 		 * The question here is expanding to more than what is
2857 		 * allocated for question lines (Q_LINE) which garbles
2858 		 * at least warning line. Clearing warning line as workaround
2859 		 * for now.
2860 		 */
2861 
2862 		(void) printf(W_LINE);
2863 		(void) printf(Q_LINE);
2864 		(void) printf(
2865 		    "Select the partition type to create:\n"
2866 		    "   1=SOLARIS2  2=UNIX        3=PCIXOS     4=Other\n"
2867 		    "   5=DOS12     6=DOS16       7=DOSEXT     8=DOSBIG\n"
2868 		    "   9=DOS16LBA  A=x86 Boot    B=Diagnostic C=FAT32\n"
2869 		    "   D=FAT32LBA  E=DOSEXTLBA   F=EFI        0=Exit? ");
2870 		(void) fgets(s, sizeof (s), stdin);
2871 		rm_blanks(s);
2872 		if ((s[1] != '\0') && (s[1] != '\n')) {
2873 			(void) printf(E_LINE);
2874 			(void) printf("Invalid selection, try again.");
2875 			continue;
2876 		}
2877 		switch (s[0]) {
2878 		case '0':		/* exit */
2879 			(void) printf(E_LINE);
2880 			return (-1);
2881 		case '1':		/* Solaris partition */
2882 			tsystid = SUNIXOS2;
2883 			break;
2884 		case '2':		/* UNIX partition */
2885 			tsystid = UNIXOS;
2886 			break;
2887 		case '3':		/* PCIXOS partition */
2888 			tsystid = PCIXOS;
2889 			break;
2890 		case '4':		/* OTHEROS System partition */
2891 			tsystid = OTHEROS;
2892 			break;
2893 		case '5':
2894 			tsystid = DOSOS12; /* DOS 12 bit fat */
2895 			break;
2896 		case '6':
2897 			tsystid = DOSOS16; /* DOS 16 bit fat */
2898 			break;
2899 		case '7':
2900 #ifdef i386
2901 			if (ext_part_present) {
2902 				(void) printf(Q_LINE);
2903 				(void) printf(E_LINE);
2904 				(void) fprintf(stderr,
2905 				    "Extended partition already exists\n");
2906 				(void) fprintf(stderr,
2907 				    "Press enter to continue\n");
2908 				ext_read_input(s);
2909 				continue;
2910 			}
2911 #endif
2912 			tsystid = EXTDOS;
2913 			break;
2914 		case '8':
2915 			tsystid = DOSHUGE;
2916 			break;
2917 		case '9':
2918 			tsystid = FDISK_FAT95;  /* FAT16, need extended int13 */
2919 			break;
2920 		case 'a':		/* x86 Boot partition */
2921 		case 'A':
2922 			tsystid = X86BOOT;
2923 			break;
2924 		case 'b':		/* Diagnostic boot partition */
2925 		case 'B':
2926 			tsystid = DIAGPART;
2927 			break;
2928 		case 'c':		/* FAT32 */
2929 		case 'C':
2930 			tsystid = FDISK_WINDOWS;
2931 			break;
2932 		case 'd':		/* FAT32 and need extended int13 */
2933 		case 'D':
2934 			tsystid = FDISK_EXT_WIN;
2935 			break;
2936 		case 'e':	/* Extended partition, need extended int13 */
2937 		case 'E':
2938 #ifdef i386
2939 			if (ext_part_present) {
2940 				(void) printf(Q_LINE);
2941 				(void) printf(E_LINE);
2942 				(void) fprintf(stderr,
2943 				    "Extended partition already exists\n");
2944 				(void) fprintf(stderr,
2945 				    "Press enter to continue\n");
2946 				ext_read_input(s);
2947 				continue;
2948 			}
2949 #endif
2950 			tsystid = FDISK_EXTLBA;
2951 			break;
2952 		case 'f':
2953 		case 'F':
2954 			tsystid = EFI_PMBR;
2955 			break;
2956 		default:
2957 			(void) printf(E_LINE);
2958 			(void) printf("Invalid selection, try again.");
2959 			continue;
2960 		}
2961 	}
2962 
2963 	(void) printf(E_LINE);
2964 
2965 	if (tsystid != EFI_PMBR) {
2966 		(void) printf(W_LINE);
2967 		if ((dev_capacity > DK_MAX_2TB))
2968 			(void) printf("WARNING: Disk is larger than 2 TB. "
2969 			    "Upper limit is 2 TB for non-EFI partition ID\n");
2970 
2971 		/* create the new partition */
2972 		i = specify(tsystid);
2973 
2974 		if (i != -1) {
2975 			/* see if it should be the active partition */
2976 			(void) printf(E_LINE);
2977 			(void) printf(Q_LINE);
2978 
2979 			(void) printf(
2980 			    "Should this become the active partition? If "
2981 			    "yes, it  will be activated\n"
2982 			    "each time the computer is reset or turned on.\n"
2983 			    "Please type \"y\" or \"n\". ");
2984 
2985 			if (yesno()) {
2986 				(void) printf(E_LINE);
2987 				for (j = 0; j < FD_NUMPART; j++) {
2988 					if (j == i) {
2989 						Table[j].bootid = ACTIVE;
2990 						(void) printf(E_LINE);
2991 						(void) printf(
2992 						    "Partition %d is now "
2993 						    "the active partition.",
2994 						    j + 1);
2995 					} else {
2996 						Table[j].bootid = 0;
2997 					}
2998 				}
2999 			} else {
3000 				Table[i].bootid = 0;
3001 			}
3002 
3003 #ifdef i386
3004 			/*
3005 			 * If partition created is an extended partition, null
3006 			 * out the first sector of the first cylinder of the
3007 			 * extended partition
3008 			 */
3009 			if (fdisk_is_dos_extended(Table[i].systid)) {
3010 				(void) fdisk_init_ext_part(epp,
3011 				    LE_32(Table[i].relsect),
3012 				    LE_32(Table[i].numsect));
3013 			}
3014 #endif
3015 			/* set up the return code */
3016 			i = 1;
3017 		}
3018 	} else {
3019 		/*
3020 		 * partitions of type EFI_PMBR must be the only partitions in
3021 		 * the table
3022 		 *
3023 		 * First, make sure there were no errors the table is
3024 		 * empty
3025 		 */
3026 		retCode = verify_tbl();
3027 
3028 		if (retCode < 0) {
3029 			(void) fprintf(stderr,
3030 			    "fdisk: Cannot create EFI partition table; \n"
3031 			    "current partition table is invalid.\n");
3032 			return (-1);
3033 		} else if (retCode > 0) {
3034 			(void) printf(
3035 			    "An EFI partition must be the only partition on "
3036 			    "disk.  You may manually delete existing\n"
3037 			    "partitions, or fdisk can do it.\n"
3038 			    "Do you want fdisk to destroy existing "
3039 			    "partitions?\n"
3040 			    "Please type \"y\" or \"n\". ");
3041 
3042 			if (yesno()) {
3043 				nulltbl();
3044 			} else {
3045 				return (-1);
3046 			}
3047 		}
3048 
3049 		/* create the table entry - i should be 0 */
3050 		i = insert_tbl(tsystid, 0, 0, 0, 0, 0, 0, 0, 1,
3051 		    (dev_capacity > DK_MAX_2TB) ? DK_MAX_2TB:
3052 		    (dev_capacity - 1), 0);
3053 
3054 		if (i != 0) {
3055 			(void) printf("Error creating EFI partition!!!\n");
3056 			i = -1;
3057 		} else {
3058 
3059 			/* EFI partitions are currently never active */
3060 			Table[i].bootid = 0;
3061 
3062 			/* set up the return code */
3063 			i = 1;
3064 		}
3065 	}
3066 
3067 	return (i);
3068 }
3069 
3070 /*
3071  * specify
3072  * Query the user to specify the size of the new partition in
3073  * terms of percentage of the disk or by specifying the starting
3074  * cylinder and length in cylinders.
3075  */
3076 static int
3077 specify(uchar_t tsystid)
3078 {
3079 	int	i, j, percent = -1;
3080 	int	cyl, cylen;
3081 	diskaddr_t first_free, size_free;
3082 	diskaddr_t max_free;
3083 	int	cyl_size;
3084 	struct ipart *partition[FD_NUMPART];
3085 	struct ipart localpart[FD_NUMPART];
3086 
3087 	cyl_size = heads * sectors;
3088 
3089 	/*
3090 	 * make a local copy of the partition table
3091 	 * and sort it into relsect order
3092 	 */
3093 
3094 
3095 	for (i = 0, j = 0; i < FD_NUMPART; i++) {
3096 		if (Table[i].systid != UNUSED) {
3097 			localpart[j] = Table[i];
3098 			j++;
3099 		}
3100 	}
3101 
3102 	while (j < FD_NUMPART) {
3103 		(void) memset(&localpart[j], 0, sizeof (struct ipart));
3104 		j++;
3105 	}
3106 
3107 	for (i = 0; i < FD_NUMPART; i++)
3108 		partition[i] = &localpart[i];
3109 
3110 	for (i = 0; i < FD_NUMPART - 1; i++) {
3111 		if (partition[i]->systid == UNUSED)
3112 			break;
3113 		for (j = i + 1; j < FD_NUMPART; j++) {
3114 			if (partition[j]->systid == UNUSED)
3115 				break;
3116 			if (LE_32(partition[j]->relsect) <
3117 			    LE_32(partition[i]->relsect)) {
3118 				struct ipart *temp = partition[i];
3119 				partition[i] = partition[j];
3120 				partition[j] = temp;
3121 			}
3122 		}
3123 	}
3124 
3125 
3126 	(void) printf(Q_LINE);
3127 	(void) printf(
3128 	    "Specify the percentage of disk to use for this partition\n"
3129 	    "(or type \"c\" to specify the size in cylinders). ");
3130 	(void) fgets(s, sizeof (s), stdin);
3131 	rm_blanks(s);
3132 	if (s[0] != 'c') {	/* Specify size in percentage of disk */
3133 		i = 0;
3134 		while ((s[i] != '\0') && (s[i] != '\n')) {
3135 			if (s[i] < '0' || s[i] > '9') {
3136 				(void) printf(E_LINE);
3137 				(void) printf("Invalid percentage value "
3138 				    "specified; retry the operation.");
3139 				return (-1);
3140 			}
3141 			i++;
3142 			if (i > 3) {
3143 				(void) printf(E_LINE);
3144 				(void) printf("Invalid percentage value "
3145 				    "specified; retry the operation.");
3146 				return (-1);
3147 			}
3148 		}
3149 		if ((percent = atoi(s)) > 100) {
3150 			(void) printf(E_LINE);
3151 			(void) printf(
3152 			    "Percentage value is too large. The value must be"
3153 			    " between 1 and 100;\nretry the operation.\n");
3154 			return (-1);
3155 		}
3156 		if (percent < 1) {
3157 			(void) printf(E_LINE);
3158 			(void) printf(
3159 			    "Percentage value is too small. The value must be"
3160 			    " between 1 and 100;\nretry the operation.\n");
3161 			return (-1);
3162 		}
3163 
3164 		if (percent == 100)
3165 			cylen = Numcyl_usable - 1;
3166 		else
3167 			cylen = (Numcyl_usable * percent) / 100;
3168 
3169 		/* Verify DOS12 partition doesn't exceed max size of 32MB. */
3170 		if ((tsystid == DOSOS12) &&
3171 		    ((long)((long)cylen * cyl_size) > MAXDOS)) {
3172 			int n;
3173 			n = MAXDOS * 100 / (int)(cyl_size) / Numcyl_usable;
3174 			(void) printf(E_LINE);
3175 			(void) printf("Maximum size for a DOS partition "
3176 			    "is %d%%; retry the operation.",
3177 			    n <= 100 ? n : 100);
3178 			return (-1);
3179 		}
3180 
3181 
3182 		max_free = 0;
3183 		for (i = 0; i < FD_NUMPART; i++) {
3184 
3185 			/*
3186 			 * check for free space before partition i
3187 			 * where i varies from 0 to 3
3188 			 *
3189 			 * freespace after partition 3 is unusable
3190 			 * because there are no free partitions
3191 			 *
3192 			 * freespace begins at the end of previous partition
3193 			 * or cylinder 1
3194 			 */
3195 			if (i) {
3196 				/* Not an empty table */
3197 				first_free = LE_32(partition[i - 1]->relsect) +
3198 				    LE_32(partition[i - 1]->numsect);
3199 			} else {
3200 				first_free = cyl_size;
3201 			}
3202 
3203 			/*
3204 			 * freespace ends before the current partition
3205 			 * or the end of the disk (chs end)
3206 			 */
3207 			if (partition[i]->systid == UNUSED) {
3208 				size_free = chs_capacity - first_free;
3209 			} else {
3210 				/*
3211 				 * Partition might start before cylinder 1.
3212 				 * Make sure free space is not negative.
3213 				 */
3214 				size_free =
3215 				    (LE_32(partition[i]->relsect > first_free))
3216 				    ? (LE_32(partition[i]->relsect) -
3217 				    first_free) : 0;
3218 			}
3219 
3220 			/* save largest free space */
3221 			if (max_free < size_free)
3222 				max_free = size_free;
3223 
3224 			if (((uint64_t)cylen * cyl_size) <= size_free) {
3225 				/* We found a place to use */
3226 				break;
3227 			}
3228 			if (partition[i]->systid == UNUSED) {
3229 				(void) printf(E_LINE);
3230 				max_free /= (cyl_size);
3231 				(void) fprintf(stderr, "fdisk: "
3232 				    "Maximum percentage available is %lld\n",
3233 				    100 * max_free / Numcyl_usable);
3234 				return (-1);
3235 			}
3236 		}
3237 
3238 		(void) printf(E_LINE);
3239 		if (i >= FD_NUMPART) {
3240 			(void) fprintf(stderr,
3241 			    "fdisk: Partition table is full.\n");
3242 			return (-1);
3243 		}
3244 
3245 		if ((i = insert_tbl(tsystid, 0, 0, 0, 0, 0, 0, 0,
3246 		    first_free, cylen * cyl_size, 0)) >= 0)  {
3247 			return (i);
3248 		}
3249 		return (-1);
3250 	} else {
3251 
3252 		/* Specifying size in cylinders */
3253 		(void) printf(E_LINE);
3254 		(void) printf(Q_LINE);
3255 		(void) printf("Enter starting cylinder number: ");
3256 		if ((cyl = getcyl()) == -1) {
3257 			(void) printf(E_LINE);
3258 			(void) printf("Invalid number; retry the operation.");
3259 			return (-1);
3260 		}
3261 		if (cyl == 0) {
3262 			(void) printf(E_LINE);
3263 			(void) printf(
3264 			    "New partition cannot start at cylinder 0.\n");
3265 			return (-1);
3266 		}
3267 
3268 
3269 		if (cyl >= Numcyl_usable) {
3270 			(void) printf(E_LINE);
3271 			(void) printf(
3272 			    "Cylinder %d is out of bounds, "
3273 			    "the maximum is %d.\n",
3274 			    cyl, Numcyl_usable - 1);
3275 			return (-1);
3276 		}
3277 
3278 		(void) printf(Q_LINE);
3279 		(void) printf("Enter partition size in cylinders: ");
3280 		if ((cylen = getcyl()) == -1) {
3281 			(void) printf(E_LINE);
3282 			(void) printf("Invalid number, retry the operation.");
3283 			return (-1);
3284 		}
3285 
3286 		for (i = 0; i < FD_NUMPART; i++) {
3287 			uint32_t	t_relsect, t_numsect;
3288 
3289 			if (partition[i]->systid == UNUSED)
3290 				break;
3291 			t_relsect = LE_32(partition[i]->relsect);
3292 			t_numsect = LE_32(partition[i]->numsect);
3293 
3294 			if (cyl * cyl_size >= t_relsect &&
3295 			    cyl * cyl_size < t_relsect + t_numsect) {
3296 				(void) printf(E_LINE);
3297 				(void) printf(
3298 				    "Cylinder %d is already allocated"
3299 				    "\nretry the operation.",
3300 				    cyl);
3301 				return (-1);
3302 			}
3303 
3304 			if (cyl * cyl_size < t_relsect &&
3305 			    (cyl + cylen - 1) * cyl_size > t_relsect) {
3306 				(void) printf(E_LINE);
3307 				(void) printf(
3308 				    "Maximum size for partition is %u cylinders"
3309 				    "\nretry the operation.",
3310 				    (t_relsect - cyl * cyl_size) / cyl_size);
3311 				return (-1);
3312 			}
3313 		}
3314 
3315 		/* Verify partition doesn't exceed disk size or 2 TB */
3316 		if (cyl + cylen > Numcyl_usable) {
3317 			(void) printf(E_LINE);
3318 			if (Numcyl > Numcyl_usable) {
3319 				(void) printf(
3320 				    "Maximum size for partition is %d "
3321 				    "cylinders; \nretry the operation.",
3322 				    Numcyl_usable - cyl);
3323 			} else {
3324 				(void) printf(
3325 				    "Maximum size for partition is %d "
3326 				    "cylinders; \nretry the operation.",
3327 				    Numcyl_usable - cyl);
3328 			}
3329 			return (-1);
3330 		}
3331 
3332 		/* Verify DOS12 partition doesn't exceed max size of 32MB. */
3333 		if ((tsystid == DOSOS12) &&
3334 		    ((long)((long)cylen * cyl_size) > MAXDOS)) {
3335 			(void) printf(E_LINE);
3336 			(void) printf(
3337 			    "Maximum size for a %s partition is %ld cylinders;"
3338 			    "\nretry the operation.",
3339 			    Dstr, MAXDOS / (int)(cyl_size));
3340 			return (-1);
3341 		}
3342 
3343 		(void) printf(E_LINE);
3344 		i = insert_tbl(tsystid, 0, 0, 0, 0, 0, 0, 0,
3345 		    cyl * cyl_size, cylen * cyl_size, 0);
3346 		if (i < 0)
3347 			return (-1);
3348 
3349 		if (verify_tbl() < 0) {
3350 			(void) printf(E_LINE);
3351 			(void) printf("fdisk: Cannot create partition table\n");
3352 			return (-1);
3353 		}
3354 
3355 		return (i);
3356 	}
3357 }
3358 
3359 /*
3360  * dispmenu
3361  * Display command menu (interactive mode).
3362  */
3363 static void
3364 dispmenu(void)
3365 {
3366 	(void) printf(M_LINE);
3367 #ifdef i386
3368 	(void) printf(
3369 	    "SELECT ONE OF THE FOLLOWING:\n"
3370 	    "   1. Create a partition\n"
3371 	    "   2. Specify the active partition\n"
3372 	    "   3. Delete a partition\n"
3373 	    "   4. Change between Solaris and Solaris2 Partition IDs\n"
3374 	    "   5. Edit/View extended partitions\n"
3375 	    "   6. Exit (update disk configuration and exit)\n"
3376 	    "   7. Cancel (exit without updating disk configuration)\n");
3377 #else
3378 	(void) printf(
3379 	    "SELECT ONE OF THE FOLLOWING:\n"
3380 	    "   1. Create a partition\n"
3381 	    "   2. Specify the active partition\n"
3382 	    "   3. Delete a partition\n"
3383 	    "   4. Change between Solaris and Solaris2 Partition IDs\n"
3384 	    "   5. Exit (update disk configuration and exit)\n"
3385 	    "   6. Cancel (exit without updating disk configuration)\n");
3386 #endif
3387 }
3388 
3389 /*
3390  * pchange
3391  * Change the ACTIVE designation of a partition.
3392  */
3393 static int
3394 pchange(void)
3395 {
3396 	char s[80];
3397 	int i, j;
3398 
3399 	for (;;) {
3400 		(void) printf(Q_LINE);
3401 			{
3402 			(void) printf(
3403 			    "Specify the partition number to boot from"
3404 			    " (or specify 0 for none): ");
3405 			}
3406 		(void) fgets(s, sizeof (s), stdin);
3407 		rm_blanks(s);
3408 		if (((s[1] != '\0') && (s[1] != '\n')) ||
3409 		    (s[0] < '0') || (s[0] > '4')) {
3410 			(void) printf(E_LINE);
3411 			(void) printf(
3412 			    "Invalid response, please specify a number"
3413 			    " between 0 and 4.\n");
3414 		} else {
3415 			break;
3416 		}
3417 	}
3418 	if (s[0] == '0') {	/* No active partitions */
3419 		for (i = 0; i < FD_NUMPART; i++) {
3420 			if (Table[i].systid != UNUSED &&
3421 			    Table[i].bootid == ACTIVE)
3422 				Table[i].bootid = 0;
3423 		}
3424 		(void) printf(E_LINE);
3425 			(void) printf(
3426 			    "No partition is currently marked as active.");
3427 		return (0);
3428 	} else {	/* User has selected a partition to be active */
3429 
3430 		i = s[0] - '1';
3431 
3432 		if (Table[i].systid == UNUSED) {
3433 			(void) printf(E_LINE);
3434 			(void) printf("Partition does not exist.");
3435 			return (-1);
3436 		}
3437 		/* a DOS-DATA or EXT-DOS partition cannot be active */
3438 		else if ((Table[i].systid == DOSDATA) ||
3439 		    (Table[i].systid == EXTDOS) ||
3440 		    (Table[i].systid == FDISK_EXTLBA)) {
3441 			(void) printf(E_LINE);
3442 			(void) printf(
3443 			    "DOS-DATA, EXT_DOS and EXT_DOS_LBA partitions "
3444 			    "cannot be made active.\n");
3445 			(void) printf("Select another partition.");
3446 			return (-1);
3447 		}
3448 		Table[i].bootid = ACTIVE;
3449 		for (j = 0; j < FD_NUMPART; j++) {
3450 			if (j != i)
3451 			Table[j].bootid = 0;
3452 		}
3453 	}
3454 	(void) printf(E_LINE);
3455 		{
3456 		(void) printf(
3457 		    "Partition %d is now active. The system will start up"
3458 		    " from this\n", i + 1);
3459 		(void) printf("partition after the next reboot.");
3460 		}
3461 	return (1);
3462 }
3463 
3464 /*
3465  * Change between SOLARIS and SOLARIS2 partition id
3466  */
3467 static int
3468 ppartid(void)
3469 {
3470 	char	*p, s[80];
3471 	int	i;
3472 
3473 	for (;;) {
3474 		(void) printf(Q_LINE);
3475 		(void) printf("Specify the partition number to change"
3476 		    " (or enter 0 to exit): ");
3477 		if (!fgets(s, sizeof (s), stdin))
3478 			return (1);
3479 		i = strtol(s, &p, 10);
3480 
3481 		if (*p != '\n' || i < 0 || i > FD_NUMPART) {
3482 			(void) printf(E_LINE);
3483 			(void) printf(
3484 			    "Invalid response, retry the operation.\n");
3485 			continue;
3486 		}
3487 
3488 		if (i == 0) {
3489 			/* exit delete command */
3490 			(void) printf(E_LINE); /* clear error message */
3491 			return (1);
3492 		}
3493 
3494 		i -= 1;
3495 
3496 		if (Table[i].systid == SUNIXOS) {
3497 			Table[i].systid = SUNIXOS2;
3498 		} else if (Table[i].systid == SUNIXOS2) {
3499 			Table[i].systid = SUNIXOS;
3500 		} else {
3501 			(void) printf(E_LINE);
3502 			(void) printf(
3503 			    "Partition %d is not a Solaris partition.",
3504 			    i + 1);
3505 			continue;
3506 		}
3507 
3508 		(void) printf(E_LINE);
3509 		(void) printf("Partition %d has been changed.", i + 1);
3510 		return (1);
3511 	}
3512 }
3513 
3514 /*
3515  * pdelete
3516  * Remove partition entry from the table (interactive mode).
3517  */
3518 static char
3519 pdelete(void)
3520 {
3521 	char s[80];
3522 	int i;
3523 	char pactive;
3524 
3525 DEL1:	(void) printf(Q_LINE);
3526 	(void) printf("Specify the partition number to delete"
3527 	    " (or enter 0 to exit): ");
3528 	(void) fgets(s, sizeof (s), stdin);
3529 	rm_blanks(s);
3530 	if ((s[0] == '0')) {	/* exit delete command */
3531 		(void) printf(E_LINE);	/* clear error message */
3532 		return (1);
3533 	}
3534 	/* Accept only a single digit between 1 and 4 */
3535 	if (((s[1] != '\0') && (s[1] != '\n')) ||
3536 	    (i = atoi(s)) < 1 || i > FD_NUMPART) {
3537 		(void) printf(E_LINE);
3538 		(void) printf("Invalid response, retry the operation.\n");
3539 		goto DEL1;
3540 	} else {		/* Found a digit between 1 and 4 */
3541 		--i;	/* Structure begins with element 0 */
3542 	}
3543 
3544 	if (Table[i].systid == UNUSED) {
3545 		(void) printf(E_LINE);
3546 		(void) printf("Partition %d does not exist.", i + 1);
3547 		return (-1);
3548 	}
3549 
3550 #ifdef i386
3551 	if (fdisk_is_dos_extended(Table[i].systid) &&
3552 	    (Table[i].relsect == fdisk_get_ext_beg_sec(epp)) &&
3553 	    fdisk_get_logical_drive_count(epp)) {
3554 		(void) printf(Q_LINE);
3555 		(void) printf("There are logical drives inside the"
3556 		    " extended partition\n");
3557 		(void) printf("Are you sure of proceeding with deletion ?"
3558 		    " (type \"y\" or \"n\") ");
3559 
3560 		(void) printf(E_LINE);
3561 		if (! yesno()) {
3562 			return (1);
3563 		}
3564 		if (fdisk_mounted_logical_drives(epp) == FDISK_EMOUNTED) {
3565 			(void) printf(Q_LINE);
3566 			(void) printf("There are mounted logical drives. "
3567 			    "Committing changes now can cause data loss or "
3568 			    "corruption. Unmount all logical drives and then "
3569 			    "try committing the changes again.\n");
3570 			(void) printf("Press enter to continue.\n");
3571 			ext_read_input(s);
3572 			return (1);
3573 		}
3574 		(void) fdisk_delete_ext_part(epp);
3575 	} else {
3576 #endif
3577 		(void) printf(Q_LINE);
3578 		(void) printf("Are you sure you want to delete partition %d?"
3579 		    " This will make all files and \n", i + 1);
3580 		(void) printf("programs in this partition inaccessible (type"
3581 		    " \"y\" or \"n\"). ");
3582 
3583 		(void) printf(E_LINE);
3584 		if (! yesno()) {
3585 			return (1);
3586 		}
3587 #ifdef i386
3588 	}
3589 #endif
3590 
3591 	if (Table[i].bootid == ACTIVE) {
3592 		pactive = 1;
3593 	} else {
3594 		pactive = 0;
3595 	}
3596 
3597 	(void) memset(&Table[i], 0, sizeof (struct ipart));
3598 
3599 	(void) printf(E_LINE);
3600 	(void) printf("Partition %d has been deleted.", i + 1);
3601 
3602 	if (pactive) {
3603 		(void) printf(" This was the active partition.");
3604 	}
3605 
3606 	return (1);
3607 }
3608 
3609 /*
3610  * rm_blanks
3611  * Remove blanks from strings of user responses.
3612  */
3613 static void
3614 rm_blanks(char *s)
3615 {
3616 	register int i, j;
3617 
3618 	for (i = 0; i < CBUFLEN; i++) {
3619 		if ((s[i] == ' ') || (s[i] == '\t'))
3620 			continue;
3621 		else
3622 			/* Found first non-blank character of the string */
3623 			break;
3624 	}
3625 	for (j = 0; i < CBUFLEN; j++, i++) {
3626 		if ((s[j] = s[i]) == '\0') {
3627 			/* Reached end of string */
3628 			return;
3629 		}
3630 	}
3631 }
3632 
3633 /*
3634  * getcyl
3635  * Take the user-specified cylinder number and convert it from a
3636  * string to a decimal value.
3637  */
3638 static int
3639 getcyl(void)
3640 {
3641 int slen, i, j;
3642 unsigned int cyl;
3643 	(void) fgets(s, sizeof (s), stdin);
3644 	rm_blanks(s);
3645 	slen = strlen(s);
3646 	if (s[slen - 1] == '\n')
3647 		slen--;
3648 	j = 1;
3649 	cyl = 0;
3650 	for (i = slen - 1; i >= 0; i--) {
3651 		if (s[i] < '0' || s[i] > '9') {
3652 			return (-1);
3653 		}
3654 		cyl += (j * (s[i] - '0'));
3655 		j *= 10;
3656 	}
3657 	return (cyl);
3658 }
3659 
3660 /*
3661  * disptbl
3662  * Display the current fdisk table; determine percentage
3663  * of the disk used for each partition.
3664  */
3665 static void
3666 disptbl(void)
3667 {
3668 	int i;
3669 	unsigned int startcyl, endcyl, length, percent, remainder;
3670 	char *stat, *type;
3671 	int is_pmbr = 0;
3672 
3673 	if ((heads == 0) || (sectors == 0)) {
3674 		(void) printf("WARNING: critical disk geometry information"
3675 		    " missing!\n");
3676 		(void) printf("\theads = %d, sectors = %d\n", heads, sectors);
3677 		exit(1);
3678 	}
3679 
3680 	(void) printf(HOME);
3681 	(void) printf(T_LINE);
3682 	(void) printf("             Total disk size is %d cylinders\n", Numcyl);
3683 	(void) printf("             Cylinder size is %d (%d byte) blocks\n\n",
3684 	    heads * sectors, sectsiz);
3685 	(void) printf(
3686 	    "                                               Cylinders\n");
3687 	(void) printf(
3688 	    "      Partition   Status    Type          Start   End   Length"
3689 	    "    %%\n");
3690 	(void) printf(
3691 	    "      =========   ======    ============  =====   ===   ======"
3692 	    "   ===");
3693 
3694 
3695 	for (i = 0; i < FD_NUMPART; i++) {
3696 
3697 		if (Table[i].systid == UNUSED) {
3698 			continue;
3699 		}
3700 
3701 		if (Table[i].bootid == ACTIVE)
3702 			stat = Actvstr;
3703 		else
3704 			stat = NAstr;
3705 		switch (Table[i].systid) {
3706 		case UNIXOS:
3707 			type = Ustr;
3708 			break;
3709 		case SUNIXOS:
3710 			type = SUstr;
3711 #ifdef i386
3712 			if (fdisk_is_linux_swap(epp, Table[i].relsect,
3713 			    NULL) == 0)
3714 				type = LINSWAPstr;
3715 #endif
3716 			break;
3717 		case SUNIXOS2:
3718 			type = SU2str;
3719 			break;
3720 		case X86BOOT:
3721 			type = X86str;
3722 			break;
3723 		case DOSOS12:
3724 			type = Dstr;
3725 			break;
3726 		case DOSOS16:
3727 			type = D16str;
3728 			break;
3729 		case EXTDOS:
3730 			type = EDstr;
3731 			break;
3732 		case DOSDATA:
3733 			type = DDstr;
3734 			break;
3735 		case DOSHUGE:
3736 			type = DBstr;
3737 			break;
3738 		case PCIXOS:
3739 			type = PCstr;
3740 			break;
3741 		case DIAGPART:
3742 			type = DIAGstr;
3743 			break;
3744 		case FDISK_IFS:
3745 			type = IFSstr;
3746 			break;
3747 		case FDISK_AIXBOOT:
3748 			type = AIXstr;
3749 			break;
3750 		case FDISK_AIXDATA:
3751 			type = AIXDstr;
3752 			break;
3753 		case FDISK_OS2BOOT:
3754 			type = OS2str;
3755 			break;
3756 		case FDISK_WINDOWS:
3757 			type = WINstr;
3758 			break;
3759 		case FDISK_EXT_WIN:
3760 			type = EWINstr;
3761 			break;
3762 		case FDISK_FAT95:
3763 			type = FAT95str;
3764 			break;
3765 		case FDISK_EXTLBA:
3766 			type = EXTLstr;
3767 			break;
3768 		case FDISK_LINUX:
3769 			type = LINUXstr;
3770 			break;
3771 		case FDISK_CPM:
3772 			type = CPMstr;
3773 			break;
3774 		case FDISK_NOVELL2:
3775 			type = NOV2str;
3776 			break;
3777 		case FDISK_NOVELL3:
3778 			type = NOVstr;
3779 			break;
3780 		case FDISK_QNX4:
3781 			type = QNXstr;
3782 			break;
3783 		case FDISK_QNX42:
3784 			type = QNX2str;
3785 			break;
3786 		case FDISK_QNX43:
3787 			type = QNX3str;
3788 			break;
3789 		case FDISK_LINUXNAT:
3790 			type = LINNATstr;
3791 			break;
3792 		case FDISK_NTFSVOL1:
3793 			type = NTFSVOL1str;
3794 			break;
3795 		case FDISK_NTFSVOL2:
3796 			type = NTFSVOL2str;
3797 			break;
3798 		case FDISK_BSD:
3799 			type = BSDstr;
3800 			break;
3801 		case FDISK_NEXTSTEP:
3802 			type = NEXTSTEPstr;
3803 			break;
3804 		case FDISK_BSDIFS:
3805 			type = BSDIFSstr;
3806 			break;
3807 		case FDISK_BSDISWAP:
3808 			type = BSDISWAPstr;
3809 			break;
3810 		case EFI_PMBR:
3811 			type = EFIstr;
3812 			if (LE_32(Table[i].numsect) == DK_MAX_2TB)
3813 				is_pmbr = 1;
3814 
3815 			break;
3816 		default:
3817 			type = Ostr;
3818 			break;
3819 		}
3820 		startcyl = LE_32(Table[i].relsect) /
3821 		    (unsigned long)(heads * sectors);
3822 
3823 		if (LE_32(Table[i].numsect) == DK_MAX_2TB) {
3824 			endcyl = Numcyl - 1;
3825 			length = endcyl - startcyl + 1;
3826 		} else {
3827 			length = LE_32(Table[i].numsect) /
3828 			    (unsigned long)(heads * sectors);
3829 			if (LE_32(Table[i].numsect) %
3830 			    (unsigned long)(heads * sectors))
3831 				length++;
3832 			endcyl = startcyl + length - 1;
3833 		}
3834 
3835 		percent = length * 100 / Numcyl_usable;
3836 		if ((remainder = (length * 100 % Numcyl_usable)) != 0) {
3837 			if ((remainder * 100 / Numcyl_usable) > 50) {
3838 				/* round up */
3839 				percent++;
3840 			}
3841 			/* Else leave the percent as is since it's already */
3842 			/* rounded down */
3843 		}
3844 		if (percent > 100)
3845 			percent = 100;
3846 		(void) printf(
3847 		    "\n          %d       %s    %-12.12s   %4d  %4d    %4d"
3848 		    "    %3d",
3849 		    i + 1, stat, type, startcyl, endcyl, length, percent);
3850 	}
3851 
3852 	/* Print warning message if table is empty */
3853 	if (nopartdefined()) {
3854 		(void) printf(W_LINE);
3855 		(void) printf("WARNING: no partitions are defined!");
3856 	} else {
3857 		/* Clear the warning line */
3858 		(void) printf(W_LINE);
3859 
3860 		/* Print warning if disk > 2TB and is not EFI PMBR */
3861 		if (!is_pmbr && (dev_capacity > DK_MAX_2TB))
3862 			(void) printf("WARNING: Disk is larger than 2 TB. "
3863 			    "Upper limit is 2 TB for non-EFI partition ID\n");
3864 	}
3865 }
3866 
3867 /*
3868  * print_Table
3869  * Write the detailed fdisk table to standard error for
3870  * the selected disk device.
3871  */
3872 static void
3873 print_Table(void)
3874 {
3875 	int i;
3876 
3877 	(void) fprintf(stderr,
3878 	    "  SYSID ACT BHEAD BSECT BEGCYL   EHEAD ESECT ENDCYL   RELSECT"
3879 	    "   NUMSECT\n");
3880 
3881 	for (i = 0; i < FD_NUMPART; i++) {
3882 		(void) fprintf(stderr, "  %-5d ", Table[i].systid);
3883 		(void) fprintf(stderr, "%-3d ", Table[i].bootid);
3884 		(void) fprintf(stderr, "%-5d ", Table[i].beghead);
3885 		(void) fprintf(stderr, "%-5d ", Table[i].begsect & 0x3f);
3886 		(void) fprintf(stderr, "%-8d ",
3887 		    (((uint_t)Table[i].begsect & 0xc0) << 2) + Table[i].begcyl);
3888 
3889 		(void) fprintf(stderr, "%-5d ", Table[i].endhead);
3890 		(void) fprintf(stderr, "%-5d ", Table[i].endsect & 0x3f);
3891 		(void) fprintf(stderr, "%-8d ",
3892 		    (((uint_t)Table[i].endsect & 0xc0) << 2) + Table[i].endcyl);
3893 		(void) fprintf(stderr, "%-10u ", LE_32(Table[i].relsect));
3894 		(void) fprintf(stderr, "%-10u\n", LE_32(Table[i].numsect));
3895 
3896 	}
3897 }
3898 
3899 /*
3900  * copy_Table_to_Old_Table
3901  * Copy Table into Old_Table. The function only copies the systid,
3902  * numsect, relsect, and bootid values because they are the only
3903  * ones compared when determining if Table has changed.
3904  */
3905 static void
3906 copy_Table_to_Old_Table(void)
3907 {
3908 	int i;
3909 	for (i = 0; i < FD_NUMPART; i++)  {
3910 		(void) memcpy(&Old_Table[i], &Table[i], sizeof (Table[0]));
3911 	}
3912 }
3913 
3914 /*
3915  * nulltbl
3916  * Zero out the systid, numsect, relsect, and bootid values in the
3917  * fdisk table.
3918  */
3919 static void
3920 nulltbl(void)
3921 {
3922 	int i;
3923 
3924 	for (i = 0; i < FD_NUMPART; i++)  {
3925 		Table[i].systid = UNUSED;
3926 		Table[i].numsect = LE_32(UNUSED);
3927 		Table[i].relsect = LE_32(UNUSED);
3928 		Table[i].bootid = 0;
3929 		skip_verify[i] = 0;
3930 	}
3931 }
3932 
3933 /*
3934  * copy_Bootblk_to_Table
3935  * Copy the bytes from the boot record to an internal "Table".
3936  * All unused are padded with zeros starting at offset 446.
3937  */
3938 static void
3939 copy_Bootblk_to_Table(void)
3940 {
3941 	int i;
3942 	char *bootptr;
3943 	struct ipart iparts[FD_NUMPART];
3944 
3945 	/* Get an aligned copy of the partition tables */
3946 	(void) memcpy(iparts, Bootblk->parts, sizeof (iparts));
3947 	bootptr = (char *)iparts;	/* Points to start of partition table */
3948 	if (LE_16(Bootblk->signature) != MBB_MAGIC)  {
3949 		/* Signature is missing */
3950 		nulltbl();
3951 		(void) memcpy(Bootblk->bootinst, &BootCod, BOOTSZ);
3952 		return;
3953 	}
3954 	/*
3955 	 * When the DOS fdisk command deletes a partition, it is not
3956 	 * recognized by the old algorithm.  The algorithm that
3957 	 * follows looks at each entry in the Bootrec and copies all
3958 	 * those that are valid.
3959 	 */
3960 	for (i = 0; i < FD_NUMPART; i++) {
3961 		if (iparts[i].systid == 0) {
3962 			/* Null entry */
3963 			(void) memset(&Table[i], 0, sizeof (struct ipart));
3964 		} else {
3965 			fill_ipart(bootptr, &Table[i]);
3966 		}
3967 		bootptr += sizeof (struct ipart);
3968 	}
3969 
3970 	/* For now, always replace the bootcode with ours */
3971 	(void) memcpy(Bootblk->bootinst, &BootCod, BOOTSZ);
3972 	copy_Table_to_Bootblk();
3973 }
3974 
3975 /*
3976  * fill_ipart
3977  * Initialize ipart structure values.
3978  */
3979 static void
3980 fill_ipart(char *bootptr, struct ipart *partp)
3981 {
3982 #ifdef sparc
3983 	/* Packing struct ipart for Sparc */
3984 	partp->bootid	= getbyte(&bootptr);
3985 	partp->beghead	= getbyte(&bootptr);
3986 	partp->begsect	= getbyte(&bootptr);
3987 	partp->begcyl	= getbyte(&bootptr);
3988 	partp->systid	= getbyte(&bootptr);
3989 	partp->endhead	= getbyte(&bootptr);
3990 	partp->endsect	= getbyte(&bootptr);
3991 	partp->endcyl	= getbyte(&bootptr);
3992 	partp->relsect	= (int32_t)getlong(&bootptr);
3993 	partp->numsect	= (int32_t)getlong(&bootptr);
3994 #else
3995 	*partp = *(struct ipart *)bootptr;
3996 #endif
3997 }
3998 
3999 /*
4000  * getbyte, getlong
4001  * 	Get a byte, a short, or a long (SPARC only).
4002  */
4003 #ifdef sparc
4004 uchar_t
4005 getbyte(char **bp)
4006 {
4007 	uchar_t	b;
4008 
4009 	b = (uchar_t)**bp;
4010 	*bp = *bp + 1;
4011 	return (b);
4012 }
4013 
4014 uint32_t
4015 getlong(char **bp)
4016 {
4017 	int32_t	b, bh, bl;
4018 
4019 	bh = ((**bp) << 8) | *(*bp + 1);
4020 	*bp += 2;
4021 	bl = ((**bp) << 8) | *(*bp + 1);
4022 	*bp += 2;
4023 
4024 	b = (bh << 16) | bl;
4025 	return ((uint32_t)b);
4026 }
4027 #endif
4028 
4029 /*
4030  * copy_Table_to_Bootblk
4031  * Copy the table into the boot record. Note that the unused
4032  * entries will always be the last ones in the table and they are
4033  * marked with 100 in sysind. The the unused portion of the table
4034  * is padded with zeros in the bytes after the used entries.
4035  */
4036 static void
4037 copy_Table_to_Bootblk(void)
4038 {
4039 	struct ipart *boot_ptr, *tbl_ptr;
4040 
4041 	boot_ptr = (struct ipart *)Bootblk->parts;
4042 	tbl_ptr = (struct ipart *)&Table[0].bootid;
4043 	for (; tbl_ptr < (struct ipart *)&Table[FD_NUMPART].bootid;
4044 	    tbl_ptr++, boot_ptr++) {
4045 		if (tbl_ptr->systid == UNUSED)
4046 			(void) memset(boot_ptr, 0, sizeof (struct ipart));
4047 		else
4048 			(void) memcpy(boot_ptr, tbl_ptr, sizeof (struct ipart));
4049 	}
4050 	Bootblk->signature = LE_16(MBB_MAGIC);
4051 }
4052 
4053 /*
4054  * TableChanged
4055  * 	Check for any changes in the partition table.
4056  */
4057 static int
4058 TableChanged(void)
4059 {
4060 	int i, changed;
4061 
4062 	changed = 0;
4063 	for (i = 0; i < FD_NUMPART; i++) {
4064 		if (memcmp(&Old_Table[i], &Table[i], sizeof (Table[0])) != 0) {
4065 			/* Partition table changed, write back to disk */
4066 			changed = 1;
4067 		}
4068 	}
4069 
4070 	return (changed);
4071 }
4072 
4073 /*
4074  * ffile_write
4075  * 	Display contents of partition table to standard output or
4076  *	another file name without writing it to the disk (-W file).
4077  */
4078 static void
4079 ffile_write(char *file)
4080 {
4081 	register int	i;
4082 	FILE *fp;
4083 
4084 	/*
4085 	 * If file isn't standard output, then it's a file name.
4086 	 * Open file and write it.
4087 	 */
4088 	if (file != (char *)stdout) {
4089 		if ((fp = fopen(file, "w")) == NULL) {
4090 			(void) fprintf(stderr,
4091 			    "fdisk: Cannot open output file %s.\n",
4092 			    file);
4093 			exit(1);
4094 		}
4095 	}
4096 	else
4097 		fp = stdout;
4098 
4099 	/*
4100 	 * Write the fdisk table information
4101 	 */
4102 	(void) fprintf(fp, "\n* %s default fdisk table\n", Dfltdev);
4103 	(void) fprintf(fp, "* Dimensions:\n");
4104 	(void) fprintf(fp, "*   %4d bytes/sector\n", sectsiz);
4105 	(void) fprintf(fp, "*   %4d sectors/track\n", sectors);
4106 	(void) fprintf(fp, "*   %4d tracks/cylinder\n", heads);
4107 	(void) fprintf(fp, "*   %4d cylinders\n", Numcyl);
4108 	(void) fprintf(fp, "*\n");
4109 	/* Write virtual (HBA) geometry, if required	*/
4110 	if (v_flag) {
4111 		(void) fprintf(fp, "* HBA Dimensions:\n");
4112 		(void) fprintf(fp, "*   %4d bytes/sector\n", sectsiz);
4113 		(void) fprintf(fp, "*   %4d sectors/track\n", hba_sectors);
4114 		(void) fprintf(fp, "*   %4d tracks/cylinder\n", hba_heads);
4115 		(void) fprintf(fp, "*   %4d cylinders\n", hba_Numcyl);
4116 		(void) fprintf(fp, "*\n");
4117 	}
4118 	(void) fprintf(fp, "* systid:\n");
4119 	(void) fprintf(fp, "*    1: DOSOS12\n");
4120 	(void) fprintf(fp, "*    2: PCIXOS\n");
4121 	(void) fprintf(fp, "*    4: DOSOS16\n");
4122 	(void) fprintf(fp, "*    5: EXTDOS\n");
4123 	(void) fprintf(fp, "*    6: DOSBIG\n");
4124 	(void) fprintf(fp, "*    7: FDISK_IFS\n");
4125 	(void) fprintf(fp, "*    8: FDISK_AIXBOOT\n");
4126 	(void) fprintf(fp, "*    9: FDISK_AIXDATA\n");
4127 	(void) fprintf(fp, "*   10: FDISK_0S2BOOT\n");
4128 	(void) fprintf(fp, "*   11: FDISK_WINDOWS\n");
4129 	(void) fprintf(fp, "*   12: FDISK_EXT_WIN\n");
4130 	(void) fprintf(fp, "*   14: FDISK_FAT95\n");
4131 	(void) fprintf(fp, "*   15: FDISK_EXTLBA\n");
4132 	(void) fprintf(fp, "*   18: DIAGPART\n");
4133 	(void) fprintf(fp, "*   65: FDISK_LINUX\n");
4134 	(void) fprintf(fp, "*   82: FDISK_CPM\n");
4135 	(void) fprintf(fp, "*   86: DOSDATA\n");
4136 	(void) fprintf(fp, "*   98: OTHEROS\n");
4137 	(void) fprintf(fp, "*   99: UNIXOS\n");
4138 	(void) fprintf(fp, "*  100: FDISK_NOVELL2\n");
4139 	(void) fprintf(fp, "*  101: FDISK_NOVELL3\n");
4140 	(void) fprintf(fp, "*  119: FDISK_QNX4\n");
4141 	(void) fprintf(fp, "*  120: FDISK_QNX42\n");
4142 	(void) fprintf(fp, "*  121: FDISK_QNX43\n");
4143 	(void) fprintf(fp, "*  130: SUNIXOS\n");
4144 	(void) fprintf(fp, "*  131: FDISK_LINUXNAT\n");
4145 	(void) fprintf(fp, "*  134: FDISK_NTFSVOL1\n");
4146 	(void) fprintf(fp, "*  135: FDISK_NTFSVOL2\n");
4147 	(void) fprintf(fp, "*  165: FDISK_BSD\n");
4148 	(void) fprintf(fp, "*  167: FDISK_NEXTSTEP\n");
4149 	(void) fprintf(fp, "*  183: FDISK_BSDIFS\n");
4150 	(void) fprintf(fp, "*  184: FDISK_BSDISWAP\n");
4151 	(void) fprintf(fp, "*  190: X86BOOT\n");
4152 	(void) fprintf(fp, "*  191: SUNIXOS2\n");
4153 	(void) fprintf(fp, "*  238: EFI_PMBR\n");
4154 	(void) fprintf(fp, "*  239: EFI_FS\n");
4155 	(void) fprintf(fp, "*\n");
4156 	(void) fprintf(fp,
4157 	    "\n* Id    Act  Bhead  Bsect  Bcyl    Ehead  Esect  Ecyl"
4158 	    "    Rsect      Numsect\n");
4159 
4160 	for (i = 0; i < FD_NUMPART; i++) {
4161 		(void) fprintf(fp,
4162 		    "  %-5d %-4d %-6d %-6d %-7d %-6d %-6d %-7d %-10u"
4163 		    " %-10u\n",
4164 		    Table[i].systid,
4165 		    Table[i].bootid,
4166 		    Table[i].beghead,
4167 		    Table[i].begsect & 0x3f,
4168 		    ((Table[i].begcyl & 0xff) | ((Table[i].begsect &
4169 		    0xc0) << 2)),
4170 		    Table[i].endhead,
4171 		    Table[i].endsect & 0x3f,
4172 		    ((Table[i].endcyl & 0xff) | ((Table[i].endsect &
4173 		    0xc0) << 2)),
4174 		    LE_32(Table[i].relsect),
4175 		    LE_32(Table[i].numsect));
4176 	}
4177 #ifdef i386
4178 	if (fdisk_ext_part_exists(epp)) {
4179 		struct ipart ext_tab;
4180 		logical_drive_t *temp;
4181 		uint32_t rsect, numsect, tempsect = 0;
4182 		for (temp = fdisk_get_ld_head(epp); temp != NULL;
4183 		    temp = temp->next) {
4184 			ext_tab = temp->parts[0];
4185 			rsect = tempsect + LE_32(ext_tab.relsect) +
4186 			    fdisk_get_ext_beg_sec(epp);
4187 			numsect = LE_32(ext_tab.numsect);
4188 			tempsect = LE_32(temp->parts[1].relsect);
4189 			(void) fprintf(fp,
4190 			    "  %-5d %-4d %-6d %-6d %-7d %-6d %-6d "
4191 			    "%-7d %-8u %-8u\n",
4192 			    ext_tab.systid,
4193 			    ext_tab.bootid,
4194 			    ext_tab.beghead,
4195 			    ext_tab.begsect & 0x3f,
4196 			    ((ext_tab.begcyl & 0xff) |
4197 			    ((ext_tab.begsect & 0xc0) << 2)),
4198 			    ext_tab.endhead,
4199 			    ext_tab.endsect & 0x3f,
4200 			    ((ext_tab.endcyl & 0xff) |
4201 			    ((ext_tab.endsect & 0xc0) << 2)),
4202 			    rsect,
4203 			    numsect);
4204 		}
4205 	}
4206 #endif
4207 
4208 	if (fp != stdout)
4209 		(void) fclose(fp);
4210 }
4211 
4212 /*
4213  * fix_slice
4214  * 	Read the VTOC table on the Solaris partition and check that no
4215  *	slices exist that extend past the end of the Solaris partition.
4216  *	If no Solaris partition exists, nothing is done.
4217  */
4218 static void
4219 fix_slice(void)
4220 {
4221 	int	i;
4222 	uint32_t	numsect;
4223 
4224 	if (io_image) {
4225 		return;
4226 	}
4227 
4228 	for (i = 0; i < FD_NUMPART; i++) {
4229 		if (Table[i].systid == SUNIXOS || Table[i].systid == SUNIXOS2) {
4230 			/*
4231 			 * Only the size matters (not starting point), since
4232 			 * VTOC entries are relative to the start of
4233 			 * the partition.
4234 			 */
4235 			numsect = LE_32(Table[i].numsect);
4236 			break;
4237 		}
4238 	}
4239 
4240 	if (i >= FD_NUMPART) {
4241 		if (!io_nifdisk) {
4242 			(void) fprintf(stderr,
4243 			    "fdisk: No Solaris partition found - VTOC not"
4244 			    " checked.\n");
4245 		}
4246 		return;
4247 	}
4248 
4249 	if (readvtoc() != VTOC_OK) {
4250 		exit(1);		/* Failed to read the VTOC */
4251 	}
4252 	for (i = 0; i < V_NUMPAR; i++) {
4253 		/* Special case for slice two (entire disk) */
4254 		if (i == 2) {
4255 			if (disk_vtoc.v_part[i].p_start != 0) {
4256 				(void) fprintf(stderr,
4257 				    "slice %d starts at %llu, is not at"
4258 				    " start of partition",
4259 				    i, disk_vtoc.v_part[i].p_start);
4260 				if (!io_nifdisk) {
4261 					(void) printf(" adjust ?:");
4262 					if (yesno())
4263 						disk_vtoc.v_part[i].p_start = 0;
4264 				} else {
4265 					disk_vtoc.v_part[i].p_start = 0;
4266 					(void) fprintf(stderr, " adjusted!\n");
4267 				}
4268 
4269 			}
4270 			if (disk_vtoc.v_part[i].p_size != numsect) {
4271 				(void) fprintf(stderr,
4272 				    "slice %d size %llu does not cover"
4273 				    " complete partition",
4274 				    i, disk_vtoc.v_part[i].p_size);
4275 				if (!io_nifdisk) {
4276 					(void) printf(" adjust ?:");
4277 					if (yesno())
4278 						disk_vtoc.v_part[i].p_size =
4279 						    numsect;
4280 				} else {
4281 					disk_vtoc.v_part[i].p_size = numsect;
4282 					(void) fprintf(stderr, " adjusted!\n");
4283 				}
4284 			}
4285 			if (disk_vtoc.v_part[i].p_tag != V_BACKUP) {
4286 				(void) fprintf(stderr,
4287 				    "slice %d tag was %d should be %d",
4288 				    i, disk_vtoc.v_part[i].p_tag,
4289 				    V_BACKUP);
4290 				if (!io_nifdisk) {
4291 					(void) printf(" fix ?:");
4292 					if (yesno())
4293 						disk_vtoc.v_part[i].p_tag =
4294 						    V_BACKUP;
4295 				} else {
4296 					disk_vtoc.v_part[i].p_tag = V_BACKUP;
4297 					(void) fprintf(stderr, " fixed!\n");
4298 				}
4299 			}
4300 			continue;
4301 		}
4302 		if (io_ADJT) {
4303 			if (disk_vtoc.v_part[i].p_start > numsect ||
4304 			    disk_vtoc.v_part[i].p_start +
4305 			    disk_vtoc.v_part[i].p_size > numsect) {
4306 				(void) fprintf(stderr,
4307 				    "slice %d (start %llu, end %llu)"
4308 				    " is larger than the partition",
4309 				    i, disk_vtoc.v_part[i].p_start,
4310 				    disk_vtoc.v_part[i].p_start +
4311 				    disk_vtoc.v_part[i].p_size);
4312 				if (!io_nifdisk) {
4313 					(void) printf(" remove ?:");
4314 					if (yesno()) {
4315 						disk_vtoc.v_part[i].p_size = 0;
4316 						disk_vtoc.v_part[i].p_start = 0;
4317 						disk_vtoc.v_part[i].p_tag = 0;
4318 						disk_vtoc.v_part[i].p_flag = 0;
4319 					}
4320 				} else {
4321 					disk_vtoc.v_part[i].p_size = 0;
4322 					disk_vtoc.v_part[i].p_start = 0;
4323 					disk_vtoc.v_part[i].p_tag = 0;
4324 					disk_vtoc.v_part[i].p_flag = 0;
4325 					(void) fprintf(stderr,
4326 					    " removed!\n");
4327 				}
4328 			}
4329 			continue;
4330 		}
4331 		if (disk_vtoc.v_part[i].p_start > numsect) {
4332 			(void) fprintf(stderr,
4333 			    "slice %d (start %llu) is larger than the "
4334 			    "partition", i, disk_vtoc.v_part[i].p_start);
4335 			if (!io_nifdisk) {
4336 				(void) printf(" remove ?:");
4337 				if (yesno()) {
4338 					disk_vtoc.v_part[i].p_size = 0;
4339 					disk_vtoc.v_part[i].p_start = 0;
4340 					disk_vtoc.v_part[i].p_tag = 0;
4341 					disk_vtoc.v_part[i].p_flag = 0;
4342 				}
4343 			} else {
4344 				disk_vtoc.v_part[i].p_size = 0;
4345 				disk_vtoc.v_part[i].p_start = 0;
4346 				disk_vtoc.v_part[i].p_tag = 0;
4347 				disk_vtoc.v_part[i].p_flag = 0;
4348 				(void) fprintf(stderr,
4349 				" removed!\n");
4350 			}
4351 		} else if (disk_vtoc.v_part[i].p_start
4352 		    + disk_vtoc.v_part[i].p_size > numsect) {
4353 			(void) fprintf(stderr,
4354 			    "slice %d (end %llu) is larger"
4355 			    " than the partition",
4356 			    i,
4357 			    disk_vtoc.v_part[i].p_start +
4358 			    disk_vtoc.v_part[i].p_size);
4359 			if (!io_nifdisk) {
4360 				(void) printf(" adjust ?:");
4361 				if (yesno()) {
4362 					disk_vtoc.v_part[i].p_size = numsect;
4363 				}
4364 			} else {
4365 				disk_vtoc.v_part[i].p_size = numsect;
4366 				(void) fprintf(stderr, " adjusted!\n");
4367 			}
4368 		}
4369 	}
4370 #if 1		/* bh for now */
4371 	/* Make the VTOC look sane - ha ha */
4372 	disk_vtoc.v_version = V_VERSION;
4373 	disk_vtoc.v_sanity = VTOC_SANE;
4374 	disk_vtoc.v_nparts = V_NUMPAR;
4375 	if (disk_vtoc.v_sectorsz == 0)
4376 		disk_vtoc.v_sectorsz = NBPSCTR;
4377 #endif
4378 
4379 	/* Write the VTOC back to the disk */
4380 	if (!io_readonly)
4381 		(void) writevtoc();
4382 }
4383 
4384 /*
4385  * yesno
4386  * Get yes or no answer. Return 1 for yes and 0 for no.
4387  */
4388 
4389 static int
4390 yesno(void)
4391 {
4392 	char	s[80];
4393 
4394 	for (;;) {
4395 		(void) fgets(s, sizeof (s), stdin);
4396 		rm_blanks(s);
4397 		if (((s[1] != '\0') && (s[1] != '\n')) ||
4398 		    ((s[0] != 'y') && (s[0] != 'n'))) {
4399 			(void) printf(E_LINE);
4400 			(void) printf("Please answer with \"y\" or \"n\": ");
4401 			continue;
4402 		}
4403 		if (s[0] == 'y')
4404 			return (1);
4405 		else
4406 			return (0);
4407 	}
4408 }
4409 
4410 /*
4411  * readvtoc
4412  * 	Read the VTOC from the Solaris partition of the device.
4413  */
4414 static int
4415 readvtoc(void)
4416 {
4417 	int	i;
4418 	int	retval = VTOC_OK;
4419 
4420 	if ((i = read_extvtoc(Dev, &disk_vtoc)) < VTOC_OK) {
4421 		if (i == VT_EINVAL) {
4422 			(void) fprintf(stderr, "fdisk: Invalid VTOC.\n");
4423 			vt_inval++;
4424 			retval = VTOC_INVAL;
4425 		} else if (i == VT_ENOTSUP) {
4426 			(void) fprintf(stderr, "fdisk: partition may have EFI "
4427 			    "GPT\n");
4428 			retval = VTOC_NOTSUP;
4429 		} else {
4430 			(void) fprintf(stderr, "fdisk: Cannot read VTOC.\n");
4431 			retval = VTOC_RWERR;
4432 		}
4433 	}
4434 	return (retval);
4435 }
4436 
4437 /*
4438  * writevtoc
4439  * 	Write the VTOC to the Solaris partition on the device.
4440  */
4441 static int
4442 writevtoc(void)
4443 {
4444 	int	i;
4445 	int	retval = 0;
4446 
4447 	if ((i = write_extvtoc(Dev, &disk_vtoc)) != 0) {
4448 		if (i == VT_EINVAL) {
4449 			(void) fprintf(stderr,
4450 			    "fdisk: Invalid entry exists in VTOC.\n");
4451 			retval = VTOC_INVAL;
4452 		} else if (i == VT_ENOTSUP) {
4453 			(void) fprintf(stderr, "fdisk: partition may have EFI "
4454 			    "GPT\n");
4455 			retval = VTOC_NOTSUP;
4456 		} else {
4457 			(void) fprintf(stderr, "fdisk: Cannot write VTOC.\n");
4458 			retval = VTOC_RWERR;
4459 		}
4460 	}
4461 	return (retval);
4462 }
4463 
4464 /*
4465  * efi_ioctl
4466  * issues DKIOCSETEFI IOCTL
4467  * (duplicate of private efi_ioctl() in rdwr_efi.c
4468  */
4469 static int
4470 efi_ioctl(int fd, int cmd, dk_efi_t *dk_ioc)
4471 {
4472 	void *data = dk_ioc->dki_data;
4473 	int error;
4474 
4475 	dk_ioc->dki_data_64 = (uintptr_t)data;
4476 	error = ioctl(fd, cmd, (void *)dk_ioc);
4477 
4478 	return (error);
4479 }
4480 
4481 /*
4482  * clear_efi
4483  * Clear EFI labels from the EFI_PMBR partition on the device
4484  * This function is modeled on the libefi(3LIB) call efi_write()
4485  */
4486 static int
4487 clear_efi(void)
4488 {
4489 	struct dk_gpt	*efi_vtoc;
4490 	dk_efi_t	dk_ioc;
4491 
4492 	/*
4493 	 * see if we can read the EFI label
4494 	 */
4495 	if (efi_alloc_and_read(Dev, &efi_vtoc) < 0) {
4496 		return (VT_ERROR);
4497 	}
4498 
4499 	/*
4500 	 * set up the dk_ioc structure for writing
4501 	 */
4502 	dk_ioc.dki_lba = 1;
4503 	dk_ioc.dki_length = EFI_MIN_ARRAY_SIZE + efi_vtoc->efi_lbasize;
4504 
4505 	if ((dk_ioc.dki_data = calloc(dk_ioc.dki_length, 1)) == NULL) {
4506 		return (VT_ERROR);
4507 	}
4508 
4509 	/*
4510 	 * clear the primary label
4511 	 */
4512 	if (io_debug) {
4513 		(void) fprintf(stderr,
4514 		    "\tClearing primary EFI label at block %lld\n",
4515 		    dk_ioc.dki_lba);
4516 	}
4517 
4518 	if (efi_ioctl(Dev, DKIOCSETEFI, &dk_ioc) == -1) {
4519 		free(dk_ioc.dki_data);
4520 		switch (errno) {
4521 			case EIO:
4522 				return (VT_EIO);
4523 			case EINVAL:
4524 				return (VT_EINVAL);
4525 			default:
4526 				return (VT_ERROR);
4527 		}
4528 	}
4529 
4530 	/*
4531 	 * clear the backup partition table
4532 	 */
4533 	dk_ioc.dki_lba = efi_vtoc->efi_last_u_lba + 1;
4534 	dk_ioc.dki_length -= efi_vtoc->efi_lbasize;
4535 	dk_ioc.dki_data = (efi_gpt_t *)((char *)dk_ioc.dki_data +
4536 	    efi_vtoc->efi_lbasize);
4537 	if (io_debug) {
4538 		(void) fprintf(stderr,
4539 		    "\tClearing backup partition table at block %lld\n",
4540 		    dk_ioc.dki_lba);
4541 	}
4542 
4543 	if (efi_ioctl(Dev, DKIOCSETEFI, &dk_ioc) == -1) {
4544 		(void) fprintf(stderr, "\tUnable to clear backup EFI label at "
4545 		    "block %llu; errno %d\n", efi_vtoc->efi_last_u_lba + 1,
4546 		    errno);
4547 	}
4548 
4549 	/*
4550 	 * clear the backup label
4551 	 */
4552 	dk_ioc.dki_lba = efi_vtoc->efi_last_lba;
4553 	dk_ioc.dki_length = efi_vtoc->efi_lbasize;
4554 	dk_ioc.dki_data = (efi_gpt_t *)((char *)dk_ioc.dki_data -
4555 	    efi_vtoc->efi_lbasize);
4556 	if (io_debug) {
4557 		(void) fprintf(stderr, "\tClearing backup label at block "
4558 		    "%lld\n", dk_ioc.dki_lba);
4559 	}
4560 
4561 	if (efi_ioctl(Dev, DKIOCSETEFI, &dk_ioc) == -1) {
4562 		(void) fprintf(stderr,
4563 		    "\tUnable to clear backup EFI label at "
4564 		    "block %llu; errno %d\n",
4565 		    efi_vtoc->efi_last_lba,
4566 		    errno);
4567 	}
4568 
4569 	free(dk_ioc.dki_data);
4570 	efi_free(efi_vtoc);
4571 
4572 	return (0);
4573 }
4574 
4575 /*
4576  * clear_vtoc
4577  * 	Clear the VTOC from the current or previous Solaris partition on the
4578  *      device.
4579  */
4580 static void
4581 clear_vtoc(int table, int part)
4582 {
4583 	struct ipart *clr_table;
4584 	char *disk_label;
4585 	uint32_t pcyl, ncyl, count;
4586 	diskaddr_t backup_block, solaris_offset;
4587 	ssize_t bytes;
4588 	off_t seek_byte;
4589 
4590 #ifdef DEBUG
4591 	char *read_label;
4592 #endif /* DEBUG */
4593 
4594 	if (table == OLD) {
4595 		clr_table = &Old_Table[part];
4596 	} else {
4597 		clr_table = &Table[part];
4598 	}
4599 
4600 	disk_label = (char *)calloc(sectsiz, 1);
4601 	if (disk_label == NULL) {
4602 		return;
4603 	}
4604 
4605 	seek_byte = (off_t)(LE_32(clr_table->relsect) + VTOC_OFFSET) * sectsiz;
4606 
4607 	if (io_debug) {
4608 		(void) fprintf(stderr,
4609 		    "\tClearing primary VTOC at byte %llu (block %llu)\n",
4610 		    (uint64_t)seek_byte,
4611 		    (uint64_t)(LE_32(clr_table->relsect) + VTOC_OFFSET));
4612 	}
4613 
4614 	if (lseek(Dev, seek_byte, SEEK_SET) == -1) {
4615 		(void) fprintf(stderr,
4616 		    "\tError seeking to primary label at byte %llu\n",
4617 		    (uint64_t)seek_byte);
4618 		free(disk_label);
4619 		return;
4620 	}
4621 
4622 	bytes = write(Dev, disk_label, sectsiz);
4623 
4624 	if (bytes != sectsiz) {
4625 		(void) fprintf(stderr,
4626 		    "\tWarning: only %d bytes written to clear primary"
4627 		    " VTOC!\n", bytes);
4628 	}
4629 
4630 #ifdef DEBUG
4631 	if (lseek(Dev, seek_byte, SEEK_SET) == -1) {
4632 		(void) fprintf(stderr,
4633 		    "DEBUG: Error seeking to primary label at byte %llu\n",
4634 		    (uint64_t)seek_byte);
4635 		free(disk_label);
4636 		return;
4637 	} else {
4638 		(void) fprintf(stderr,
4639 		    "DEBUG: Successful lseek() to byte %llu\n",
4640 		    (uint64_t)seek_byte);
4641 	}
4642 
4643 	read_label = (char *)calloc(sectsiz, 1);
4644 	if (read_label == NULL) {
4645 		free(disk_label);
4646 		return;
4647 	}
4648 
4649 	bytes = read(Dev, read_label, sectsiz);
4650 
4651 	if (bytes != sectsiz) {
4652 		(void) fprintf(stderr,
4653 		    "DEBUG: Warning: only %d bytes read of label\n",
4654 		    bytes);
4655 	}
4656 
4657 	if (memcmp(disk_label, read_label, sectsiz) != 0) {
4658 		(void) fprintf(stderr,
4659 		    "DEBUG: Warning: disk_label and read_label differ!!!\n");
4660 	} else {
4661 		(void) fprintf(stderr, "DEBUG Good compare of disk_label and "
4662 		    "read_label\n");
4663 	}
4664 #endif /* DEBUG */
4665 
4666 	/* Clear backup label */
4667 	pcyl = LE_32(clr_table->numsect) / (heads * sectors);
4668 	solaris_offset = LE_32(clr_table->relsect);
4669 	ncyl = pcyl - acyl;
4670 
4671 	backup_block = ((ncyl + acyl - 1) *
4672 	    (heads * sectors)) + ((heads - 1) * sectors) + 1;
4673 
4674 	for (count = 1; count < 6; count++) {
4675 		seek_byte = (off_t)(solaris_offset + backup_block) * sectsiz;
4676 
4677 		if (lseek(Dev, seek_byte, SEEK_SET) == -1) {
4678 			(void) fprintf(stderr,
4679 			    "\tError seeking to backup label at byte %llu on "
4680 			    "%s.\n", (uint64_t)seek_byte, Dfltdev);
4681 			free(disk_label);
4682 #ifdef DEBUG
4683 			free(read_label);
4684 #endif /* DEBUG */
4685 			return;
4686 		}
4687 
4688 		if (io_debug) {
4689 			(void) fprintf(stderr, "\tClearing backup VTOC at"
4690 			    " byte %llu (block %llu)\n",
4691 			    (uint64_t)seek_byte,
4692 			    (uint64_t)(solaris_offset + backup_block));
4693 		}
4694 
4695 		bytes = write(Dev, disk_label, sectsiz);
4696 
4697 		if (bytes != sectsiz) {
4698 			(void) fprintf(stderr,
4699 			    "\t\tWarning: only %d bytes written to "
4700 			    "clear backup VTOC at block %llu!\n", bytes,
4701 			    (uint64_t)(solaris_offset + backup_block));
4702 		}
4703 
4704 #ifdef DEBUG
4705 	if (lseek(Dev, seek_byte, SEEK_SET) == -1) {
4706 		(void) fprintf(stderr,
4707 		    "DEBUG: Error seeking to backup label at byte %llu\n",
4708 		    (uint64_t)seek_byte);
4709 		free(disk_label);
4710 		free(read_label);
4711 		return;
4712 	} else {
4713 		(void) fprintf(stderr,
4714 		    "DEBUG: Successful lseek() to byte %llu\n",
4715 		    (uint64_t)seek_byte);
4716 	}
4717 
4718 	bytes = read(Dev, read_label, sectsiz);
4719 
4720 	if (bytes != sectsiz) {
4721 		(void) fprintf(stderr,
4722 		    "DEBUG: Warning: only %d bytes read of backup label\n",
4723 		    bytes);
4724 	}
4725 
4726 	if (memcmp(disk_label, read_label, sectsiz) != 0) {
4727 		(void) fprintf(stderr,
4728 		    "DEBUG: Warning: disk_label and read_label differ!!!\n");
4729 	} else {
4730 		(void) fprintf(stderr,
4731 		    "DEBUG: Good compare of disk_label and backup "
4732 		    "read_label\n");
4733 	}
4734 
4735 #endif /* DEBUG */
4736 
4737 		backup_block += 2;
4738 	}
4739 
4740 #ifdef DEBUG
4741 	free(read_label);
4742 #endif /* DEBUG */
4743 	free(disk_label);
4744 }
4745 
4746 #define	FDISK_STANDARD_LECTURE \
4747 	"Fdisk is normally used with the device that " \
4748 	"represents the entire fixed disk.\n" \
4749 	"(For example, /dev/rdsk/c0d0p0 on x86 or " \
4750 	"/dev/rdsk/c0t5d0s2 on sparc).\n"
4751 
4752 #define	FDISK_LECTURE_NOT_SECTOR_ZERO \
4753 	"The device does not appear to include absolute\n" \
4754 	"sector 0 of the PHYSICAL disk " \
4755 	"(the normal location for an fdisk table).\n"
4756 
4757 #define	FDISK_LECTURE_NOT_FULL \
4758 	"The device does not appear to encompass the entire PHYSICAL disk.\n"
4759 
4760 #define	FDISK_LECTURE_NO_VTOC \
4761 	"Unable to find a volume table of contents.\n" \
4762 	"Cannot verify the device encompasses the full PHYSICAL disk.\n"
4763 
4764 #define	FDISK_LECTURE_NO_GEOM \
4765 	"Unable to get geometry from device.\n" \
4766 	"Cannot verify the device encompasses the full PHYSICAL disk.\n"
4767 
4768 #define	FDISK_SHALL_I_CONTINUE \
4769 	"Are you sure you want to continue? (y/n) "
4770 
4771 /*
4772  *  lecture_and_query
4773  *	Called when a sanity check fails.  This routine gives a warning
4774  *	specific to the check that fails, followed by a generic lecture
4775  *	about the "right" device to supply as input.  Then, if appropriate,
4776  *	it will prompt the user on whether or not they want to continue.
4777  *	Inappropriate times for prompting are when the user has selected
4778  *	non-interactive mode or read-only mode.
4779  */
4780 static int
4781 lecture_and_query(char *warning, char *devname)
4782 {
4783 	if (io_nifdisk)
4784 		return (0);
4785 
4786 	(void) fprintf(stderr, "WARNING: Device %s: \n", devname);
4787 	(void) fprintf(stderr, "%s", warning);
4788 	(void) fprintf(stderr, FDISK_STANDARD_LECTURE);
4789 	(void) fprintf(stderr, FDISK_SHALL_I_CONTINUE);
4790 
4791 	return (yesno());
4792 }
4793 
4794 static void
4795 sanity_check_provided_device(char *devname, int fd)
4796 {
4797 	struct extvtoc v;
4798 	struct dk_geom d;
4799 	struct part_info pi;
4800 	struct extpart_info extpi;
4801 	diskaddr_t totsize;
4802 	int idx = -1;
4803 
4804 	/*
4805 	 *  First try the PARTINFO ioctl.  If it works, we will be able
4806 	 *  to tell if they've specified the full disk partition by checking
4807 	 *  to see if they've specified a partition that starts at sector 0.
4808 	 */
4809 	if (ioctl(fd, DKIOCEXTPARTINFO, &extpi) != -1) {
4810 		if (extpi.p_start != 0) {
4811 			if (!lecture_and_query(FDISK_LECTURE_NOT_SECTOR_ZERO,
4812 			    devname)) {
4813 				(void) close(fd);
4814 				exit(1);
4815 			}
4816 		}
4817 	} else if (ioctl(fd, DKIOCPARTINFO, &pi) != -1) {
4818 		if (pi.p_start != 0) {
4819 			if (!lecture_and_query(FDISK_LECTURE_NOT_SECTOR_ZERO,
4820 			    devname)) {
4821 				(void) close(fd);
4822 				exit(1);
4823 			}
4824 		}
4825 	} else {
4826 		if ((idx = read_extvtoc(fd, &v)) < 0) {
4827 			if (!lecture_and_query(FDISK_LECTURE_NO_VTOC,
4828 			    devname)) {
4829 				(void) close(fd);
4830 				exit(1);
4831 			}
4832 			return;
4833 		}
4834 		if (ioctl(fd, DKIOCGGEOM, &d) == -1) {
4835 			perror(devname);
4836 			if (!lecture_and_query(FDISK_LECTURE_NO_GEOM,
4837 			    devname)) {
4838 				(void) close(fd);
4839 				exit(1);
4840 			}
4841 			return;
4842 		}
4843 		totsize = (diskaddr_t)d.dkg_ncyl * d.dkg_nhead * d.dkg_nsect;
4844 		if (v.v_part[idx].p_size != totsize) {
4845 			if (!lecture_and_query(FDISK_LECTURE_NOT_FULL,
4846 			    devname)) {
4847 				(void) close(fd);
4848 				exit(1);
4849 			}
4850 		}
4851 	}
4852 }
4853 
4854 
4855 /*
4856  * get_node
4857  * Called from main to construct the name of the device node to open.
4858  * Initially tries to stat the node exactly as provided, if that fails
4859  * we prepend the default path (/dev/rdsk/).
4860  */
4861 static char *
4862 get_node(char *devname)
4863 {
4864 	char *node;
4865 	struct stat statbuf;
4866 	size_t space;
4867 
4868 	/* Don't do anything if we are skipping device checks */
4869 	if (io_image)
4870 		return (devname);
4871 
4872 	node = devname;
4873 
4874 	/* Try the node as provided first */
4875 	if (stat(node, (struct stat *)&statbuf) == -1) {
4876 		/*
4877 		 * Copy the passed in string to a new buffer, prepend the
4878 		 * default path and try again.
4879 		 */
4880 		space = strlen(DEFAULT_PATH) + strlen(devname) + 1;
4881 
4882 		if ((node = malloc(space)) == NULL) {
4883 			(void) fprintf(stderr, "fdisk: Unable to obtain memory "
4884 			    "for device node.\n");
4885 			exit(1);
4886 		}
4887 
4888 		/* Copy over the default path and the provided node */
4889 		(void) strncpy(node, DEFAULT_PATH, strlen(DEFAULT_PATH));
4890 		space -= strlen(DEFAULT_PATH);
4891 		(void) strlcpy(node + strlen(DEFAULT_PATH), devname, space);
4892 
4893 		/* Try to stat it again */
4894 		if (stat(node, (struct stat *)&statbuf) == -1) {
4895 			/* Failed all options, give up */
4896 			(void) fprintf(stderr,
4897 			    "fdisk: Cannot stat device %s.\n",
4898 			    devname);
4899 			exit(1);
4900 		}
4901 	}
4902 
4903 	/* Make sure the device specified is the raw device */
4904 	if ((statbuf.st_mode & S_IFMT) != S_IFCHR) {
4905 		(void) fprintf(stderr,
4906 		    "fdisk: %s must be a raw device.\n", node);
4907 		exit(1);
4908 	}
4909 
4910 	return (node);
4911 }
4912 
4913 #ifdef i386
4914 static void
4915 preach_and_continue()
4916 {
4917 	(void) fprintf(stderr, "There are mounted logical drives. Committing "
4918 	    "changes now can lead to inconsistancy in internal system state "
4919 	    "which can eventually cause data loss or corruption. Unmount all "
4920 	    "logical drives and try committing the changes again.\n");
4921 	ext_read_input(s);
4922 }
4923 
4924 /*
4925  * Convert a given partition ID to an descriptive string.
4926  * Just an index into the partition types table.
4927  */
4928 void
4929 id_to_name(uchar_t sysid, char *buffer)
4930 {
4931 	(void) strcpy(buffer, fdisk_part_types[sysid]);
4932 }
4933 
4934 /*
4935  * Procedure to check the validity of the extended partition menu option
4936  * entered by the user
4937  */
4938 static int
4939 ext_invalid_option(char ch)
4940 {
4941 	char *p;
4942 
4943 	p = strchr(ext_part_menu_opts, tolower(ch));
4944 
4945 	if (p == NULL) {
4946 		return (1);
4947 	}
4948 	return (0);
4949 }
4950 
4951 /*
4952  * Read 16 bytes of the input (assuming that no valid user input spans more
4953  * than that). Flush the input stream, so that the next read does not reap
4954  * stale data from the previous input that was not processed.
4955  * Note that fgets also reads the trailing '\n'
4956  */
4957 static void
4958 ext_read_input(char *buf)
4959 {
4960 	(void) fgets(buf, 16, stdin);
4961 	(void) fflush(stdin);
4962 }
4963 
4964 /*
4965  * Procedure to read and validate the user option at the extended partition menu
4966  */
4967 static int
4968 ext_read_options(char *buf)
4969 {
4970 	ext_read_input(buf);
4971 	if ((strlen(buf) != 2) || (ext_invalid_option(buf[0]))) {
4972 		(void) printf("\nUnknown Command\n");
4973 		return (-1);
4974 	}
4975 	return (0);
4976 }
4977 
4978 /*
4979  * Procedure to print the list of known partition types and their IDs
4980  */
4981 static void
4982 ext_print_part_types()
4983 {
4984 	int i, rowmax, rowcount = 1;
4985 	struct winsize ws;
4986 	char buf[80];
4987 
4988 	/* Get the current window dimensions */
4989 	if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) < 0) {
4990 		perror("ioctl");
4991 		rowmax = 20;
4992 	} else {
4993 		/*
4994 		 * Accommodate the initial headings by reducing the number of
4995 		 * partition IDs being printed.
4996 		 */
4997 		rowmax = ws.ws_row - 5;
4998 	}
4999 
5000 	if (rowmax < 3) {
5001 		(void) fprintf(stderr, "Window size too small."
5002 		    " Try resizing the window\n");
5003 		return;
5004 	}
5005 
5006 	(void) printf("List of known partition types : \n");
5007 	(void) printf("PartID          Partition Type\n");
5008 	(void) printf("======          ==============\n");
5009 	for (i = 0; i <= FDISK_MAX_VALID_PART_ID; i++) {
5010 		(void) printf("%-3d          %s\n", i, fdisk_part_types[i]);
5011 		rowcount++;
5012 		if (rowcount == rowmax) {
5013 			/*
5014 			 * After the initial screen, use all the rows for
5015 			 * printing the partition IDs, but one.
5016 			 */
5017 			rowmax = ws.ws_row - 1;
5018 			(void) fprintf(stderr, "\nPress enter to see next "
5019 			    "page or 'q' to quit : ");
5020 			ext_read_input(buf);
5021 			if ((strlen(buf) == 2) && (tolower(buf[0]) == 'q')) {
5022 				return;
5023 			}
5024 			rowcount = 1;
5025 		}
5026 	}
5027 }
5028 
5029 static void
5030 ext_read_valid_part_num(int *pno)
5031 {
5032 	char buf[80];
5033 	int len, i;
5034 
5035 	for (;;) {
5036 		(void) printf("Enter the partition number : ");
5037 		ext_read_input(buf);
5038 
5039 		len = strlen(buf);
5040 
5041 		/* Check length of the input */
5042 		if ((len < 2) || (len > (FDISK_MAX_VALID_PART_NUM_DIGITS+1))) {
5043 			goto print_error_and_continue;
5044 		}
5045 
5046 		/* Check if there is a non-digit in the input */
5047 		for (i = 0; i < len-1; i++) {
5048 			if (!isdigit(buf[i])) {
5049 				goto print_error_and_continue;
5050 			}
5051 		}
5052 
5053 		*pno = atoi(buf);
5054 
5055 		if ((*pno <= FD_NUMPART) ||
5056 		    *pno > (fdisk_get_logical_drive_count(epp) + FD_NUMPART)) {
5057 			goto print_error_and_continue;
5058 		}
5059 
5060 		break;
5061 print_error_and_continue:
5062 		(void) printf("Invalid partition number\n");
5063 		continue;
5064 	}
5065 }
5066 
5067 static void
5068 ext_read_valid_part_id(uchar_t *partid)
5069 {
5070 	char buf[80];
5071 	int len, i, id;
5072 
5073 	for (;;) {
5074 		(void) printf("Enter the ID ( Type I for list of "
5075 		    "partition IDs ) : ");
5076 		ext_read_input(buf);
5077 		len = strlen(buf);
5078 
5079 		if ((len < 2) || (len > (FDISK_MAX_VALID_PART_ID_DIGITS + 1))) {
5080 			(void) printf("Invalid partition ID\n");
5081 			continue;
5082 		}
5083 
5084 		if ((len == 2) && (toupper(buf[0]) == 'I')) {
5085 			ext_print_part_types();
5086 			continue;
5087 		}
5088 
5089 		/* Check if there is a non-digit in the input */
5090 		for (i = 0; i < len-1; i++) {
5091 			if (!isdigit(buf[i])) {
5092 				(void) printf("Invalid partition ID\n");
5093 				break;
5094 			}
5095 		}
5096 
5097 		if (i < len - 1) {
5098 			continue;
5099 		}
5100 
5101 		/* Check if the (now) valid number is greater than the limit */
5102 		if ((id = atoi(buf)) > FDISK_MAX_VALID_PART_ID) {
5103 			(void) printf("Invalid partition ID\n");
5104 			continue;
5105 		}
5106 
5107 		*partid = (uchar_t)id;
5108 
5109 		/* Disallow multiple extended partitions */
5110 		if (fdisk_is_dos_extended(*partid)) {
5111 			(void) printf("Multiple extended partitions not "
5112 			    "allowed\n");
5113 			continue;
5114 		}
5115 
5116 		/* Disallow EFI partitions within extended partition */
5117 		if (*partid == EFI_PMBR) {
5118 			(void) printf("EFI partitions within an extended "
5119 			    "partition is not allowed\n");
5120 			continue;
5121 		}
5122 
5123 		return; /* Valid partition ID is in partid */
5124 	}
5125 }
5126 
5127 static void
5128 delete_logical_drive()
5129 {
5130 	int pno;
5131 
5132 	if (!fdisk_get_logical_drive_count(epp)) {
5133 		(void) printf("\nNo logical drives defined.\n");
5134 		return;
5135 	}
5136 
5137 	(void) printf("\n");
5138 	ext_read_valid_part_num(&pno);
5139 	fdisk_delete_logical_drive(epp, pno);
5140 	(void) printf("Partition %d deleted\n", pno);
5141 }
5142 
5143 static int
5144 ext_read_valid_partition_start(uint32_t *begsec)
5145 {
5146 	char buf[80];
5147 	int ret, len, i;
5148 	uint32_t begcyl;
5149 	uint32_t first_free_cyl;
5150 	uint32_t first_free_sec;
5151 
5152 	ret = fdisk_ext_find_first_free_sec(epp, &first_free_sec);
5153 	if (ret != FDISK_SUCCESS) {
5154 		return (ret);
5155 	}
5156 
5157 	first_free_cyl = FDISK_SECT_TO_CYL(epp, first_free_sec);
5158 	for (;;) {
5159 		(void) printf("Enter the beginning cylinder (Default - %d) : ",
5160 		    first_free_cyl);
5161 		ext_read_input(buf);
5162 		len = strlen(buf);
5163 		if (len == 1) { /* User accepted the default value */
5164 			*begsec = first_free_sec;
5165 			return (FDISK_SUCCESS);
5166 		}
5167 
5168 		if (len > (FDISK_MAX_VALID_CYL_NUM_DIGITS + 1)) {
5169 			(void) printf("Input too long\n");
5170 			(void) printf("Invalid beginning cylinder number\n");
5171 			continue;
5172 		}
5173 		/* Check if there is a non-digit in the input */
5174 		for (i = 0; i < len - 1; i++) {
5175 			if (!isdigit(buf[i])) {
5176 				(void) printf("Invalid beginning cylinder "
5177 				    "number\n");
5178 				break;
5179 			}
5180 		}
5181 		if (i < len - 1) {
5182 			continue;
5183 		}
5184 
5185 		begcyl = atoi(buf);
5186 		ret = fdisk_ext_validate_part_start(epp, begcyl, begsec);
5187 		switch (ret) {
5188 			case FDISK_SUCCESS:
5189 				/*
5190 				 * Success.
5191 				 * Valid beginning sector is in begsec
5192 				 */
5193 				break;
5194 
5195 			case FDISK_EOVERLAP:
5196 				(void) printf("Partition boundary overlaps "
5197 				    "with ");
5198 				(void) printf("existing partitions\n");
5199 				(void) printf("Invalid beginning cylinder "
5200 				    "number\n");
5201 				continue;
5202 
5203 			case FDISK_EOOBOUND:
5204 				(void) printf("Cylinder boundary beyond the "
5205 				    "limits\n");
5206 				(void) printf("Invalid beginning cylinder "
5207 				    "number\n");
5208 				continue;
5209 		}
5210 		return (FDISK_SUCCESS);
5211 	}
5212 }
5213 
5214 /*
5215  * Algorithm :
5216  * 1. Check if the first character is a +
5217  *	a) If yes, check if the last character is 'k', 'm' or 'g'
5218  * 2. If not, check if there are any non-digits
5219  * 3. Check for the length of the numeral string
5220  * 4. atoi the numeral string
5221  * 5. In case of data entered in KB, MB or GB, convert it to number of cylinders
5222  *	a) Adjust size to be cylinder boundary aligned
5223  * 6. If size specifies is zero, flag error
5224  * 7. Check if the size is less than 1 cylinder
5225  *	a) If yes, default the size FDISK_MIN_PART_SIZE
5226  * 	b) If no, Check if the size is within endcyl - begcyl
5227  */
5228 static void
5229 ext_read_valid_partition_size(uint32_t begsec, uint32_t *endsec)
5230 {
5231 	char buf[80];
5232 	uint32_t last_free_sec;
5233 	uint32_t last_free_cyl;
5234 	int i, len, ch, mbgb = 0, scale = FDISK_SECTS_PER_CYL(epp);
5235 	uint64_t size = 0;
5236 	int copy_len;
5237 	char numbuf[FDISK_MAX_VALID_CYL_NUM_DIGITS + 1];
5238 	int sectsize = fdisk_get_disk_geom(epp, PHYSGEOM, SSIZE);
5239 	uint32_t remdr, spc, poss_end;
5240 
5241 	if (sectsize == EINVAL) {
5242 		(void) fprintf(stderr, "Unsupported geometry statistics.\n");
5243 		exit(1);
5244 	}
5245 
5246 	last_free_sec = fdisk_ext_find_last_free_sec(epp, begsec);
5247 	last_free_cyl = FDISK_SECT_TO_CYL(epp, last_free_sec);
5248 
5249 	for (;;) {
5250 		(void) printf("Enter the size in cylinders (Default End "
5251 		    "Cylinder -");
5252 		(void) printf(" %u)\n", last_free_cyl);
5253 		(void) printf("Type +<size>K, +<size>M or +<size>G to enter "
5254 		    "size in");
5255 		(void) printf("KB, MB or GB : ");
5256 		ext_read_input(buf);
5257 		len = strlen(buf);
5258 		mbgb = 0;
5259 		scale = FDISK_SECTS_PER_CYL(epp);
5260 
5261 		if (len == 1) { /* User accepted the default value */
5262 			*endsec = last_free_sec;
5263 			return;
5264 		}
5265 
5266 		copy_len = len - 1;
5267 
5268 		if ((buf[0] == '+') && (isdigit(buf[1]))) {
5269 			copy_len--;
5270 			if ((ch = toupper(buf[len - 2])) == 'B') {
5271 				ch = toupper(buf[len - 3]);
5272 				copy_len--;
5273 			}
5274 
5275 			if (!((ch == 'K') || (ch == 'M') || (ch == 'G'))) {
5276 				(void) printf("Invalid partition size\n");
5277 				continue;
5278 			}
5279 
5280 			copy_len--;
5281 			mbgb = 1;
5282 			scale = ((ch == 'K') ? FDISK_KB :
5283 			    ((ch == 'M') ? FDISK_MB : FDISK_GB));
5284 		}
5285 
5286 		if (copy_len > FDISK_MAX_VALID_CYL_NUM_DIGITS) {
5287 			(void) printf("Input too long\n");
5288 			(void) printf("Invalid partition size\n");
5289 			continue;
5290 		}
5291 
5292 		(void) strncpy(numbuf, &buf[mbgb], copy_len);
5293 		numbuf[copy_len] = '\0';
5294 
5295 		for (i = mbgb; i < copy_len + mbgb; i++) {
5296 			if (!isdigit(buf[i])) {
5297 				break;
5298 			}
5299 		}
5300 
5301 		if (i < copy_len + mbgb) {
5302 			(void) printf("Invalid partition size\n");
5303 			continue;
5304 		}
5305 
5306 		size = (atoll(numbuf) * (scale));
5307 
5308 		if (size == 0) {
5309 			(void) printf("Zero size is invalid\n");
5310 			(void) printf("Invalid partition size\n");
5311 			continue;
5312 		}
5313 
5314 		if (mbgb) {
5315 			size /= sectsize;
5316 		}
5317 
5318 		if (size > (last_free_sec - begsec + 1)) {
5319 			(void) printf("Cylinder boundary beyond the limits");
5320 			(void) printf(" or overlaps with existing");
5321 			(void) printf(" partitions\n");
5322 			(void) printf("Invalid partition size\n");
5323 			continue;
5324 		}
5325 
5326 		/*
5327 		 * Adjust the ending sector such that there are no partial
5328 		 * cylinders allocated. But at the same time, make sure it
5329 		 * doesn't over shoot boundaries.
5330 		 */
5331 		spc = FDISK_SECTS_PER_CYL(epp);
5332 		poss_end = begsec + size - 1;
5333 		if ((remdr = (poss_end % spc)) != 0) {
5334 			poss_end += spc - remdr - 1;
5335 		}
5336 		*endsec = (poss_end > last_free_sec) ? last_free_sec :
5337 		    poss_end;
5338 
5339 		return;
5340 	}
5341 }
5342 
5343 /*
5344  * ALGORITHM:
5345  * 1. Get the starting and ending sectors/cylinder of the extended partition.
5346  * 2. Keep track of the first free sector/cylinder
5347  * 3. Allow the user to specify the beginning cylinder of the new partition
5348  * 4. Check for the validity of the entered data
5349  *	a) If it is non-numeric
5350  *	b) If it is beyond the extended partition limits
5351  *	c) If it overlaps with the current logical drives
5352  * 5. Allow the user to specify the size in cylinders/ human readable form
5353  * 6. Check for the validity of the entered data
5354  *	a) If it is non-numeric
5355  *	b) If it is beyond the extended partition limits
5356  *	c) If it overlaps with the current logical drives
5357  *	d) If it is a number lesser than the starting cylinder
5358  * 7. Request partition ID for the new partition.
5359  * 8. Update the first free cylinder available
5360  * 9. Display Success message
5361  */
5362 
5363 static void
5364 add_logical_drive()
5365 {
5366 	uint32_t begsec, endsec;
5367 	uchar_t partid;
5368 	char buf[80];
5369 	int rval;
5370 
5371 	if (fdisk_get_logical_drive_count(epp) >= MAX_EXT_PARTS) {
5372 		(void) printf("\nNumber of logical drives exceeds limit of "
5373 		    "%d.\n", MAX_EXT_PARTS);
5374 		(void) printf("Command did not succeed. Press enter to "
5375 		    "continue\n");
5376 		ext_read_input(buf);
5377 		return;
5378 	}
5379 
5380 	(void) printf("\n");
5381 	rval = ext_read_valid_partition_start(&begsec);
5382 	switch (rval) {
5383 		case FDISK_SUCCESS:
5384 			break;
5385 
5386 		case FDISK_EOOBOUND:
5387 			(void) printf("\nNo space left in the extended "
5388 			    "partition\n");
5389 			(void) printf("Press enter to continue\n");
5390 			ext_read_input(buf);
5391 			return;
5392 	}
5393 
5394 	ext_read_valid_partition_size(begsec, &endsec);
5395 	ext_read_valid_part_id(&partid);
5396 	fdisk_add_logical_drive(epp, begsec, endsec, partid);
5397 
5398 	(void) printf("New partition with ID %d added\n", partid);
5399 }
5400 
5401 static void
5402 ext_change_logical_drive_id()
5403 {
5404 	int pno;
5405 	uchar_t partid;
5406 
5407 	if (!fdisk_get_logical_drive_count(epp)) {
5408 		(void) printf("\nNo logical drives defined.\n");
5409 		return;
5410 	}
5411 
5412 	(void) printf("\n");
5413 	ext_read_valid_part_num(&pno);
5414 	ext_read_valid_part_id(&partid);
5415 	fdisk_change_logical_drive_id(epp, pno, partid);
5416 
5417 	(void) printf("Partition ID of partition %d changed to %d\n", pno,
5418 	    partid);
5419 }
5420 
5421 #ifdef DEBUG
5422 static void
5423 ext_print_logdrive_layout_debug()
5424 {
5425 	int pno;
5426 	char namebuff[255];
5427 	logical_drive_t *head = fdisk_get_ld_head(epp);
5428 	logical_drive_t *temp;
5429 
5430 	if (!fdisk_get_logical_drive_count(epp)) {
5431 		(void) printf("\nNo logical drives defined.\n");
5432 		return;
5433 	}
5434 
5435 	(void) printf("\n\n");
5436 	puts("#  start block  end block    abs start    abs end      OSType");
5437 	for (temp = head, pno = 5; temp != NULL; temp = temp->next, pno++) {
5438 		/* Print the logical drive details */
5439 		id_to_name(temp->parts[0].systid, namebuff);
5440 		(void) printf("%d: %.10u   %.10u   %.10u   %.10u",
5441 		    pno,
5442 		    LE_32(temp->parts[0].relsect),
5443 		    LE_32(temp->parts[0].numsect),
5444 		    temp->abs_secnum,
5445 		    temp->abs_secnum + temp->numsect - 1 +
5446 		    MAX_LOGDRIVE_OFFSET);
5447 		(void) printf("   %s\n", namebuff);
5448 		/*
5449 		 * Print the second entry in the EBR which is information
5450 		 * about the location and the size of the next extended
5451 		 * partition.
5452 		 */
5453 		id_to_name(temp->parts[1].systid, namebuff);
5454 		(void) printf("%d: %.10u   %.10u   %.10s   %.10s",
5455 		    pno,
5456 		    LE_32(temp->parts[1].relsect),
5457 		    LE_32(temp->parts[1].numsect),
5458 		    "          ", "          ");
5459 		(void) printf("   %s\n", namebuff);
5460 	}
5461 }
5462 #endif
5463 
5464 static void
5465 ext_print_logical_drive_layout()
5466 {
5467 	int sysid;
5468 	unsigned int startcyl, endcyl, length, percent, remainder;
5469 	logical_drive_t *temp;
5470 	uint32_t part_start;
5471 	struct ipart *fpart;
5472 	char namebuff[255];
5473 	int numcyl = fdisk_get_disk_geom(epp, PHYSGEOM, NCYL);
5474 	int pno;
5475 
5476 	if (numcyl == EINVAL) {
5477 		(void) fprintf(stderr, "Unsupported geometry statistics.\n");
5478 		exit(1);
5479 	}
5480 
5481 	if (!fdisk_get_logical_drive_count(epp)) {
5482 		(void) printf("\nNo logical drives defined.\n");
5483 		return;
5484 	}
5485 
5486 	(void) printf("\n");
5487 	(void) printf("Number of cylinders in disk              : %u\n",
5488 	    numcyl);
5489 	(void) printf("Beginning cylinder of extended partition : %u\n",
5490 	    fdisk_get_ext_beg_cyl(epp));
5491 	(void) printf("Ending cylinder of extended partition    : %u\n",
5492 	    fdisk_get_ext_end_cyl(epp));
5493 	(void) printf("\n");
5494 	(void) printf("Part#   StartCyl   EndCyl     Length    %%     "
5495 	"Part ID (Type)\n");
5496 	(void) printf("=====   ========   ========   =======   ==="
5497 	"   ==============\n");
5498 	for (temp = fdisk_get_ld_head(epp), pno = 5; temp != NULL;
5499 	    temp = temp->next, pno++) {
5500 		/* Print the logical drive details */
5501 		fpart = &temp->parts[0];
5502 		sysid = fpart->systid;
5503 		/*
5504 		 * Check if partition id 0x82 is Solaris
5505 		 * or a Linux swap. Print the string
5506 		 * accordingly.
5507 		 */
5508 		if (sysid == SUNIXOS) {
5509 			part_start = temp->abs_secnum +
5510 			    temp->logdrive_offset;
5511 			if (fdisk_is_linux_swap(epp, part_start,
5512 			    NULL) == 0)
5513 				(void) strcpy(namebuff, LINSWAPstr);
5514 			else
5515 				(void) strcpy(namebuff, SUstr);
5516 		} else {
5517 			id_to_name(sysid, namebuff);
5518 		}
5519 		startcyl = temp->begcyl;
5520 		endcyl = temp->endcyl;
5521 		if (startcyl == endcyl) {
5522 			length = 1;
5523 		} else {
5524 			length = endcyl - startcyl + 1;
5525 		}
5526 		percent = length * 100 / numcyl;
5527 		if ((remainder = (length * 100 % numcyl)) != 0) {
5528 			if ((remainder * 100 / numcyl) > 50) {
5529 				/* round up */
5530 				percent++;
5531 			}
5532 			/* Else leave the percent as is since it's already */
5533 			/* rounded down */
5534 		}
5535 		if (percent > 100) {
5536 			percent = 100;
5537 		}
5538 		(void) printf("%-5d   %-8u   %-8u   %-7u   %-3d   "
5539 		    "%-3d (%-.28s)\n",
5540 		    pno, startcyl, endcyl, length, percent, sysid, namebuff);
5541 	}
5542 #ifdef DEBUG
5543 	ext_print_logdrive_layout_debug();
5544 #endif
5545 	(void) printf("\n");
5546 }
5547 
5548 static void
5549 ext_print_help_menu()
5550 {
5551 	(void) printf("\n");
5552 	(void) printf("a	Add a logical drive\n");
5553 	(void) printf("d	Delete a logical drive\n");
5554 	(void) printf("h	Print this help menu\n");
5555 	(void) printf("i	Change the id of the logical drive\n");
5556 	(void) printf("p	Print the logical drive layout\n");
5557 	(void) printf("r	Return to the main fdisk menu\n");
5558 	(void) printf("        (To commit or cancel the changes)\n");
5559 	(void) printf("\n");
5560 }
5561 
5562 static void
5563 ext_part_menu()
5564 {
5565 	char buf[80];
5566 	uchar_t *bbsigp;
5567 	static int bbsig_disp_flag = 1;
5568 
5569 	int i;
5570 
5571 	(void) printf(CLR_SCR);
5572 
5573 	if (fdisk_corrupt_logical_drives(epp)) {
5574 		(void) printf("One or more logical drives seem to be "
5575 		    "corrupt.\n");
5576 		(void) printf("Displaying only sane logical drives.\n");
5577 	}
5578 
5579 	if (bbsig_disp_flag && fdisk_invalid_bb_sig(epp, &bbsigp)) {
5580 		(void) printf("The following logical drives have a wrong "
5581 		    "boot block signature :\n\n");
5582 		for (i = 0; bbsigp[i]; i++) {
5583 			(void) printf("%d ", bbsigp[i]);
5584 		}
5585 		(void) printf("\n\n");
5586 		(void) printf("They will be corrected when you choose to "
5587 		    "commit\n");
5588 		bbsig_disp_flag = 0;
5589 	}
5590 
5591 	(void) printf("Extended partition menu\n");
5592 
5593 	for (;;) {
5594 		(void) printf("\nEnter Command (Type h for help) : ");
5595 		if ((ext_read_options(buf)) < 0) {
5596 			(void) printf("\nCommand Options : \n");
5597 			ext_print_help_menu();
5598 			continue;
5599 		}
5600 		switch (buf[0]) {
5601 			case 'a':
5602 				add_logical_drive();
5603 				break;
5604 			case 'd':
5605 				delete_logical_drive();
5606 				break;
5607 			case 'h':
5608 				ext_print_help_menu();
5609 				break;
5610 			case 'i':
5611 				ext_change_logical_drive_id();
5612 				break;
5613 			case 'p':
5614 				ext_print_logical_drive_layout();
5615 				break;
5616 			case 'r':
5617 				(void) printf(CLR_SCR);
5618 				return;
5619 			default : /* NOTREACHED */
5620 				break;
5621 		}
5622 	}
5623 }
5624 #endif /* i386 */
5625 
5626 static int
5627 nopartdefined()
5628 {
5629 	int i;
5630 
5631 	for (i = 0; i < FD_NUMPART; i++)
5632 		if (Table[i].systid != UNUSED)
5633 			return (0);
5634 	return (1);
5635 }
5636 
5637 /* create an EFI partition for the whole disk */
5638 static int
5639 efi_create()
5640 {
5641 	if (io_EFIslot < 0 || io_EFIslot > 3) {
5642 		(void) fprintf(stderr,
5643 		    "EFI partition slot must be between 0 and 3 inclusive.\n");
5644 		return (0);
5645 	}
5646 	if (io_EFIactive != 0 && io_EFIactive != 1) {
5647 		(void) fprintf(stderr,
5648 		    "EFI partition active flag must be 0 or 1.\n");
5649 		return (0);
5650 	}
5651 
5652 	nulltbl();
5653 	/*
5654 	 * In the following call, start and end cylinder values are set to one
5655 	 * above the maximum number of cylinders. This is a special fence
5656 	 * value which indicates that the geometry for the corresponding LBA
5657 	 * is not representable. This results in a protective MBR which
5658 	 * is the same as that created by libefi.
5659 	 */
5660 	if (insert_tbl(EFI_PMBR,
5661 	    io_EFIactive ? ACTIVE : NOTACTIVE,
5662 	    MAX_HEAD + 1, MAX_SECT, MAX_CYL + 1,
5663 	    MAX_HEAD + 1, MAX_SECT, MAX_CYL + 1,
5664 	    1,
5665 	    (dev_capacity > DK_MAX_2TB) ? DK_MAX_2TB : (dev_capacity - 1),
5666 	    io_EFIslot) != io_EFIslot)
5667 		return (0);
5668 	copy_Table_to_Bootblk();
5669 	dev_mboot_write(0, Bootsect, sectsiz);
5670 	return (1);
5671 }
5672