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