xref: /titanic_41/usr/src/cmd/fdisk/fdisk.c (revision 07d06da50d310a325b457d6330165aebab1e0064)
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, FDISK_ENOLOGDRIVE and
1185 			 * FDISK_EBADMAGIC can be considered as
1186 			 * soft errors and hence we do not exit
1187 			 */
1188 			case FDISK_EBADLOGDRIVE:
1189 				break;
1190 			case FDISK_ENOLOGDRIVE:
1191 				break;
1192 			case FDISK_EBADMAGIC:
1193 				break;
1194 			case FDISK_ENOVGEOM:
1195 				fprintf(stderr, "Could not get virtual"
1196 				    " geometry for this device\n");
1197 				libfdisk_fini(&epp);
1198 				exit(1);
1199 				break;
1200 			case FDISK_ENOPGEOM:
1201 				fprintf(stderr, "Could not get physical"
1202 				    " geometry for this device\n");
1203 				libfdisk_fini(&epp);
1204 				exit(1);
1205 				break;
1206 			case FDISK_ENOLGEOM:
1207 				fprintf(stderr, "Could not get label"
1208 				    " geometry for this device\n");
1209 				libfdisk_fini(&epp);
1210 				exit(1);
1211 				break;
1212 			default:
1213 				perror("Failed to initialise libfdisk.\n");
1214 				libfdisk_fini(&epp);
1215 				exit(1);
1216 				break;
1217 		}
1218 	}
1219 #endif
1220 
1221 	/* Load fdisk table from specified file (-F fdisk_file) */
1222 	if (io_ffdisk) {
1223 		/* Load and verify user-specified table parameters */
1224 		load(LOADFILE, io_ffdisk);
1225 	}
1226 
1227 	/* Does user want to delete or add an entry? */
1228 	if (io_Dfdisk) {
1229 		load(LOADDEL, io_Dfdisk);
1230 	}
1231 	if (io_Afdisk) {
1232 		load(LOADADD, io_Afdisk);
1233 	}
1234 
1235 	if (!io_ffdisk && !io_Afdisk && !io_Dfdisk) {
1236 		/* Check if there is no fdisk table */
1237 		if (Table[0].systid == UNUSED || io_wholedisk || io_EFIdisk) {
1238 			if (io_ifdisk && !io_wholedisk && !io_EFIdisk) {
1239 				(void) printf(
1240 				    "No fdisk table exists. The default"
1241 				    " partition for the disk is:\n\n"
1242 				    "  a 100%% \"SOLARIS System\" "
1243 				    "partition\n\n"
1244 				    "Type \"y\" to accept the default "
1245 				    "partition,  otherwise type \"n\" to "
1246 				    "edit the\n partition table.\n");
1247 
1248 				if (Numcyl > Numcyl_usable)
1249 					(void) printf("WARNING: Disk is larger"
1250 					    " than 2TB. Solaris partition will"
1251 					    " be limited to 2 TB.\n");
1252 			}
1253 
1254 			/* Edit the partition table as directed */
1255 			if (io_wholedisk ||(io_ifdisk && yesno())) {
1256 
1257 				/* Default scenario */
1258 				nulltbl();
1259 				/* now set up UNIX System partition */
1260 				Table[0].bootid = ACTIVE;
1261 				Table[0].relsect = LE_32(heads * sectors);
1262 
1263 				Table[0].numsect =
1264 				    LE_32((ulong_t)((Numcyl_usable - 1) *
1265 				    heads * sectors));
1266 
1267 				Table[0].systid = SUNIXOS2;   /* Solaris */
1268 
1269 				/* calculate CHS values for table entry 0 */
1270 				Set_Table_CHS_Values(0);
1271 				update_disk_and_exit(B_TRUE);
1272 			} else if (io_EFIdisk) {
1273 				/* create an EFI partition for the whole disk */
1274 				nulltbl();
1275 				i = insert_tbl(EFI_PMBR, 0, 0, 0, 0, 0, 0, 0, 1,
1276 				    (dev_capacity > DK_MAX_2TB) ? DK_MAX_2TB :
1277 				    (dev_capacity - 1));
1278 				if (i != 0) {
1279 					(void) fprintf(stderr,
1280 					    "Error creating EFI partition\n");
1281 					exit(1);
1282 				}
1283 				update_disk_and_exit(B_TRUE);
1284 			}
1285 		}
1286 	}
1287 
1288 	/* Display complete fdisk table entries for debugging purposes */
1289 	if (io_debug) {
1290 		(void) fprintf(stderr, "Partition Table Entry Values:\n");
1291 		print_Table();
1292 		if (io_ifdisk) {
1293 			(void) fprintf(stderr, "\n");
1294 			(void) fprintf(stderr, "Press Enter to continue.\n");
1295 			(void) fgets(s, sizeof (s), stdin);
1296 		}
1297 	}
1298 
1299 	/* Interactive fdisk mode */
1300 	if (io_ifdisk) {
1301 		(void) printf(CLR_SCR);
1302 		disptbl();
1303 		for (;;) {
1304 			stage0();
1305 			copy_Bootblk_to_Table();
1306 			disptbl();
1307 		}
1308 	}
1309 
1310 	/* If user wants to write the table to a file, do it */
1311 	if (io_Wfdisk)
1312 		ffile_write(io_Wfdisk);
1313 	else if (stdo_flag)
1314 		ffile_write((char *)stdout);
1315 
1316 	update_disk_and_exit(TableChanged() == 1);
1317 	return (0);
1318 }
1319 
1320 /*
1321  * read_geom
1322  * Read geometry from specified file (-S).
1323  */
1324 
1325 static int
1326 read_geom(char *sgeom)
1327 {
1328 	char	line[256];
1329 	FILE *fp;
1330 
1331 	/* open the prototype file */
1332 	if ((fp = fopen(sgeom, "r")) == NULL) {
1333 		(void) fprintf(stderr, "fdisk: Cannot open file %s.\n",
1334 		    io_sgeom);
1335 		return (1);
1336 	}
1337 
1338 	/* Read a line from the file */
1339 	while (fgets(line, sizeof (line) - 1, fp)) {
1340 		if (line[0] == '\0' || line[0] == '\n' || line[0] == '*')
1341 			continue;
1342 		else {
1343 			line[strlen(line)] = '\0';
1344 			if (sscanf(line, "%hu %hu %hu %hu %hu %hu %d",
1345 			    &disk_geom.dkg_pcyl,
1346 			    &disk_geom.dkg_ncyl,
1347 			    &disk_geom.dkg_acyl,
1348 			    &disk_geom.dkg_bcyl,
1349 			    &disk_geom.dkg_nhead,
1350 			    &disk_geom.dkg_nsect,
1351 			    &sectsiz) != 7) {
1352 				(void) fprintf(stderr,
1353 				    "Syntax error:\n	\"%s\".\n",
1354 				    line);
1355 				return (1);
1356 			}
1357 			break;
1358 		} /* else */
1359 	} /* while (fgets(line, sizeof (line) - 1, fp)) */
1360 
1361 	if (!io_image) {
1362 		if (ioctl(Dev, DKIOCSGEOM, &disk_geom)) {
1363 			(void) fprintf(stderr,
1364 			    "fdisk: Cannot set label geometry.\n");
1365 			return (1);
1366 		}
1367 	} else {
1368 		Numcyl = hba_Numcyl = disk_geom.dkg_ncyl;
1369 		heads = hba_heads = disk_geom.dkg_nhead;
1370 		sectors = hba_sectors = disk_geom.dkg_nsect;
1371 		acyl = disk_geom.dkg_acyl;
1372 	}
1373 
1374 	(void) fclose(fp);
1375 	return (0);
1376 }
1377 
1378 /*
1379  * dev_mboot_read
1380  * Read the master boot sector from the device.
1381  */
1382 static void
1383 dev_mboot_read(void)
1384 {
1385 	if ((ioctl(Dev, DKIOCGMBOOT, Bootsect) < 0) && (errno != ENOTTY)) {
1386 		perror("Error in ioctl DKIOCGMBOOT");
1387 	}
1388 	if (errno == 0)
1389 		return;
1390 	if (lseek(Dev, 0, SEEK_SET) == -1) {
1391 		(void) fprintf(stderr,
1392 		    "fdisk: Error seeking to partition table on %s.\n",
1393 		    Dfltdev);
1394 		if (!io_image)
1395 			exit(1);
1396 	}
1397 	if (read(Dev, Bootsect, sectsiz) != sectsiz) {
1398 		(void) fprintf(stderr,
1399 		    "fdisk: Error reading partition table from %s.\n",
1400 		    Dfltdev);
1401 		if (!io_image)
1402 			exit(1);
1403 	}
1404 }
1405 
1406 /*
1407  * dev_mboot_write
1408  * Write the master boot sector to the device.
1409  */
1410 static void
1411 dev_mboot_write(off_t sect, char *buff, int bootsiz)
1412 {
1413 	int 	new_pt, old_pt, error;
1414 	int	clr_efi = -1;
1415 
1416 	if (io_readonly)
1417 		return;
1418 
1419 	if (io_debug) {
1420 		(void) fprintf(stderr, "About to write fdisk table:\n");
1421 		print_Table();
1422 		if (io_ifdisk) {
1423 			(void) fprintf(stderr, "Press Enter to continue.\n");
1424 			(void) fgets(s, sizeof (s), stdin);
1425 		}
1426 	}
1427 
1428 	/*
1429 	 * If the new table has any Solaris partitions and the old
1430 	 * table does not have an entry that describes it
1431 	 * exactly then clear the old vtoc (if any).
1432 	 */
1433 	for (new_pt = 0; new_pt < FD_NUMPART; new_pt++) {
1434 
1435 		/* We only care about potential Solaris parts. */
1436 		if (Table[new_pt].systid != SUNIXOS &&
1437 		    Table[new_pt].systid != SUNIXOS2)
1438 			continue;
1439 
1440 		/* Does the old table have an exact entry for the new entry? */
1441 		for (old_pt = 0; old_pt < FD_NUMPART; old_pt++) {
1442 
1443 			/* We only care about old Solaris partitions. */
1444 			if ((Old_Table[old_pt].systid == SUNIXOS) ||
1445 			    (Old_Table[old_pt].systid == SUNIXOS2)) {
1446 
1447 				/* Is this old one the same as a new one? */
1448 				if ((Old_Table[old_pt].relsect ==
1449 				    Table[new_pt].relsect) &&
1450 				    (Old_Table[old_pt].numsect ==
1451 				    Table[new_pt].numsect))
1452 					break; /* Yes */
1453 			}
1454 		}
1455 
1456 		/* Did a solaris partition change location or size? */
1457 		if (old_pt >= FD_NUMPART) {
1458 			/* Yes clear old vtoc */
1459 			if (io_debug) {
1460 				(void) fprintf(stderr,
1461 				    "Clearing VTOC labels from NEW"
1462 				    " table\n");
1463 			}
1464 			clear_vtoc(NEW, new_pt);
1465 		}
1466 	}
1467 
1468 
1469 	/* see if the old table had EFI */
1470 	for (old_pt = 0; old_pt < FD_NUMPART; old_pt++) {
1471 		if (Old_Table[old_pt].systid == EFI_PMBR) {
1472 			clr_efi = old_pt;
1473 		}
1474 	}
1475 
1476 	/* look to see if a EFI partition changed in relsect/numsect */
1477 	for (new_pt = 0; new_pt < FD_NUMPART; new_pt++) {
1478 		if (Table[new_pt].systid != EFI_PMBR)
1479 			continue;
1480 		for (old_pt = 0; old_pt < FD_NUMPART; old_pt++) {
1481 			if ((Old_Table[old_pt].systid ==
1482 			    Table[new_pt].systid) &&
1483 			    (Old_Table[old_pt].relsect ==
1484 			    Table[new_pt].relsect) &&
1485 			    (Old_Table[old_pt].numsect ==
1486 			    Table[new_pt].numsect))
1487 				break;
1488 		}
1489 
1490 		/*
1491 		 * if EFI partition changed, set the flag to clear
1492 		 * the EFI GPT
1493 		 */
1494 		if (old_pt == FD_NUMPART && Table[new_pt].begcyl != 0) {
1495 			clr_efi = 0;
1496 		}
1497 		break;
1498 	}
1499 
1500 	/* clear labels if necessary */
1501 	if (clr_efi >= 0) {
1502 		if (io_debug) {
1503 			(void) fprintf(stderr, "Clearing EFI labels\n");
1504 		}
1505 		if ((error = clear_efi()) != 0) {
1506 			if (io_debug) {
1507 				(void) fprintf(stderr,
1508 				    "\tError %d clearing EFI labels"
1509 				    " (probably no EFI labels exist)\n",
1510 				    error);
1511 			}
1512 		}
1513 	}
1514 
1515 	if ((ioctl(Dev, DKIOCSMBOOT, buff) == -1) && (errno != ENOTTY)) {
1516 		(void) fprintf(stderr,
1517 		    "fdisk: Error in ioctl DKIOCSMBOOT on %s.\n",
1518 		    Dfltdev);
1519 	}
1520 	if (errno == 0)
1521 		return;
1522 
1523 	/* write to disk drive */
1524 	if (lseek(Dev, sect, SEEK_SET) == -1) {
1525 		(void) fprintf(stderr,
1526 		    "fdisk: Error seeking to master boot record on %s.\n",
1527 		    Dfltdev);
1528 		exit(1);
1529 	}
1530 	if (write(Dev, buff, bootsiz) != bootsiz) {
1531 		(void) fprintf(stderr,
1532 		    "fdisk: Error writing master boot record to %s.\n",
1533 		    Dfltdev);
1534 		exit(1);
1535 	}
1536 }
1537 
1538 /*
1539  * mboot_read
1540  * Read the prototype boot records from the files.
1541  */
1542 static void
1543 mboot_read(void)
1544 {
1545 	int mDev, i;
1546 	struct ipart *part;
1547 
1548 #if defined(i386) || defined(sparc)
1549 	/*
1550 	 * If the master boot file hasn't been specified, use the
1551 	 * implementation architecture name to generate the default one.
1552 	 */
1553 	if (io_mboot == (char *)0) {
1554 		/*
1555 		 * Bug ID 1249035:
1556 		 *	The mboot file must be delivered on all platforms
1557 		 *	and installed in a non-platform-dependent
1558 		 *	directory; i.e., /usr/lib/fs/ufs.
1559 		 */
1560 		io_mboot = "/usr/lib/fs/ufs/mboot";
1561 	}
1562 
1563 	/* First read in the master boot record */
1564 
1565 	/* Open the master boot proto file */
1566 	if ((mDev = open(io_mboot, O_RDONLY, 0666)) == -1) {
1567 		(void) fprintf(stderr,
1568 		    "fdisk: Cannot open master boot file %s.\n",
1569 		    io_mboot);
1570 		exit(1);
1571 	}
1572 
1573 	/* Read the master boot program */
1574 	if (read(mDev, &BootCod, sizeof (struct mboot)) != sizeof
1575 	    (struct mboot)) {
1576 		(void) fprintf(stderr,
1577 		    "fdisk: Cannot read master boot file %s.\n",
1578 		    io_mboot);
1579 		exit(1);
1580 	}
1581 
1582 	/* Is this really a master boot record? */
1583 	if (LE_16(BootCod.signature) != MBB_MAGIC) {
1584 		(void) fprintf(stderr,
1585 		    "fdisk: Invalid master boot file %s.\n", io_mboot);
1586 		(void) fprintf(stderr,
1587 		    "Bad magic number: is %x, but should be %x.\n",
1588 		    LE_16(BootCod.signature), MBB_MAGIC);
1589 		exit(1);
1590 	}
1591 
1592 	(void) close(mDev);
1593 #else
1594 #error	fdisk needs to be ported to new architecture
1595 #endif
1596 
1597 	/* Zero out the partitions part of this record */
1598 	part = (struct ipart *)BootCod.parts;
1599 	for (i = 0; i < FD_NUMPART; i++, part++) {
1600 		(void) memset(part, 0, sizeof (struct ipart));
1601 	}
1602 
1603 }
1604 
1605 /*
1606  * fill_patt
1607  * Fill the disk with user/sector number pattern.
1608  */
1609 static void
1610 fill_patt(void)
1611 {
1612 	int	*buff_ptr, i;
1613 	off_t	*off_ptr;
1614 	int	io_fpatt = 0;
1615 	int	io_ipatt = 0;
1616 
1617 	if (strncmp(io_fatt, "#", 1) != 0) {
1618 		io_fpatt++;
1619 		io_ipatt = strtoul(io_fatt, 0, 0);
1620 		buff_ptr = (int *)Bootsect;
1621 		for (i = 0; i < sectsiz; i += 4, buff_ptr++)
1622 			*buff_ptr = io_ipatt;
1623 	}
1624 
1625 	/*
1626 	 * Fill disk with pattern based on block number.
1627 	 * Write to the disk at absolute relative block io_offset
1628 	 * for io_size blocks.
1629 	 */
1630 	while (io_size--) {
1631 		off_ptr = (off_t *)Bootsect;
1632 		if (!io_fpatt) {
1633 			for (i = 0; i < sectsiz;
1634 			    i += sizeof (off_t), off_ptr++)
1635 				*off_ptr = io_offset;
1636 		}
1637 		/* Write the data to disk */
1638 		if (lseek(Dev, (off_t)(sectsiz * io_offset++),
1639 		    SEEK_SET) == -1) {
1640 			(void) fprintf(stderr, "fdisk: Error seeking on %s.\n",
1641 			    Dfltdev);
1642 			exit(1);
1643 		}
1644 		if (write(Dev, Bootsect, sectsiz) != sectsiz) {
1645 			(void) fprintf(stderr, "fdisk: Error writing %s.\n",
1646 			    Dfltdev);
1647 			exit(1);
1648 		}
1649 	} /* while (--io_size); */
1650 }
1651 
1652 /*
1653  * abs_read
1654  * Read from the disk at absolute relative block io_offset for
1655  * io_size blocks. Write the data to standard ouput (-r).
1656  */
1657 static void
1658 abs_read(void)
1659 {
1660 	int c;
1661 
1662 	while (io_size--) {
1663 		if (lseek(Dev, (off_t)(sectsiz * io_offset++),
1664 		    SEEK_SET) == -1) {
1665 			(void) fprintf(stderr, "fdisk: Error seeking on %s.\n",
1666 			    Dfltdev);
1667 			exit(1);
1668 		}
1669 		if (read(Dev, Bootsect, sectsiz) != sectsiz) {
1670 			(void) fprintf(stderr, "fdisk: Error reading %s.\n",
1671 			    Dfltdev);
1672 			exit(1);
1673 		}
1674 
1675 		/* Write to standard ouptut */
1676 		if ((c = write(1, Bootsect, (unsigned)sectsiz)) != sectsiz) {
1677 			if (c >= 0) {
1678 				if (io_debug)
1679 					(void) fprintf(stderr,
1680 					    "fdisk: Output warning: %d of %d"
1681 					    " characters written.\n",
1682 					    c, sectsiz);
1683 				exit(2);
1684 			} else {
1685 				perror("write error on output file.");
1686 				exit(2);
1687 			}
1688 		} /* if ((c = write(1, Bootsect, (unsigned)sectsiz)) */
1689 			/* != sectsiz) */
1690 	} /* while (--io_size); */
1691 	exit(0);
1692 }
1693 
1694 /*
1695  * abs_write
1696  * Read the data from standard input. Write to the disk at
1697  * absolute relative block io_offset for io_size blocks (-w).
1698  */
1699 static void
1700 abs_write(void)
1701 {
1702 	int c, i;
1703 
1704 	while (io_size--) {
1705 		int part_exit = 0;
1706 		/* Read from standard input */
1707 		if ((c = read(0, Bootsect, (unsigned)sectsiz)) != sectsiz) {
1708 			if (c >= 0) {
1709 				if (io_debug)
1710 				(void) fprintf(stderr,
1711 				    "fdisk: WARNING: Incomplete read (%d of"
1712 				    " %d characters read) on input file.\n",
1713 				    c, sectsiz);
1714 				/* Fill pattern to mark partial sector in buf */
1715 				for (i = c; i < sectsiz; ) {
1716 					Bootsect[i++] = 0x41;
1717 					Bootsect[i++] = 0x62;
1718 					Bootsect[i++] = 0x65;
1719 					Bootsect[i++] = 0;
1720 				}
1721 				part_exit++;
1722 			} else {
1723 				perror("read error on input file.");
1724 				exit(2);
1725 			}
1726 
1727 		}
1728 		/* Write to disk drive */
1729 		if (lseek(Dev, (off_t)(sectsiz * io_offset++),
1730 		    SEEK_SET) == -1) {
1731 			(void) fprintf(stderr, "fdisk: Error seeking on %s.\n",
1732 			    Dfltdev);
1733 			exit(1);
1734 		}
1735 		if (write(Dev, Bootsect, sectsiz) != sectsiz) {
1736 			(void) fprintf(stderr, "fdisk: Error writing %s.\n",
1737 			    Dfltdev);
1738 			exit(1);
1739 		}
1740 		if (part_exit)
1741 		exit(0);
1742 	} /* while (--io_size); */
1743 	exit(1);
1744 }
1745 
1746 
1747 /*
1748  * load
1749  * Load will either read the fdisk table from a file or add or
1750  * delete an entry (-A, -D, -F).
1751  */
1752 
1753 static void
1754 load(int funct, char *file)
1755 {
1756 	int	id;
1757 	int	act;
1758 	int	bhead;
1759 	int	bsect;
1760 	int	bcyl;
1761 	int	ehead;
1762 	int	esect;
1763 	int	ecyl;
1764 	uint32_t	rsect;
1765 	uint32_t	numsect;
1766 	char	line[256];
1767 	int	i = 0;
1768 	int	j;
1769 	FILE *fp;
1770 #ifdef i386
1771 	int 	ext_part_present = 0;
1772 	uint32_t	begsec, endsec, relsect;
1773 	logical_drive_t *temp;
1774 	int part_count = 0, ldcnt = 0;
1775 	uint32_t ext_beg_sec, ext_end_sec;
1776 	uint32_t old_ext_beg_sec = 0, old_ext_num_sec = 0;
1777 	uint32_t new_ext_beg_sec = 0, new_ext_num_sec = 0;
1778 	int ext_part_inited = 0;
1779 	uchar_t	systid;
1780 #endif
1781 
1782 	switch (funct) {
1783 
1784 	case LOADFILE:
1785 
1786 		/*
1787 		 * Zero out the table before loading it, which will
1788 		 * force it to be updated on disk later (-F
1789 		 * fdisk_file).
1790 		 */
1791 		nulltbl();
1792 
1793 		/* Open the prototype file */
1794 		if ((fp = fopen(file, "r")) == NULL) {
1795 			(void) fprintf(stderr,
1796 			    "fdisk: Cannot open prototype partition file %s.\n",
1797 			    file);
1798 			exit(1);
1799 		}
1800 
1801 		/* Read a line from the file */
1802 		while (fgets(line, sizeof (line) - 1, fp)) {
1803 			if (pars_fdisk(line, &id, &act, &bhead, &bsect,
1804 			    &bcyl, &ehead, &esect, &ecyl, &rsect, &numsect)) {
1805 				continue;
1806 			}
1807 #ifdef i386
1808 			part_count++;
1809 
1810 			if (fdisk_is_dos_extended((uchar_t)id)) {
1811 				if (ext_part_present) {
1812 					fprintf(stderr, "Extended partition"
1813 					    " already exists\n");
1814 					fprintf(stderr, "fdisk: Error on"
1815 					    " entry \"%s\".\n", line);
1816 					exit(1);
1817 				}
1818 				ext_part_present = 1;
1819 				/*
1820 				 * If the existing extended partition's start
1821 				 * and size matches the new one, do not
1822 				 * initialize the extended partition EBR
1823 				 * (Extended Boot Record) because there could
1824 				 * be existing logical drives.
1825 				 */
1826 				for (i = 0; i < FD_NUMPART; i++) {
1827 					systid = Old_Table[i].systid;
1828 					if (fdisk_is_dos_extended(systid)) {
1829 						old_ext_beg_sec =
1830 						    Old_Table[i].relsect;
1831 						old_ext_num_sec =
1832 						    Old_Table[i].numsect;
1833 						break;
1834 					}
1835 				}
1836 				new_ext_beg_sec = rsect;
1837 				new_ext_num_sec = numsect;
1838 				if ((old_ext_beg_sec != new_ext_beg_sec) ||
1839 				    (old_ext_num_sec != new_ext_num_sec)) {
1840 					fdisk_init_ext_part(epp,
1841 					    new_ext_beg_sec, new_ext_num_sec);
1842 					ext_part_inited = 1;
1843 				}
1844 			}
1845 
1846 			if (part_count > FD_NUMPART) {
1847 				/* This line should be logical drive info */
1848 				int offset = MAX_LOGDRIVE_OFFSET;
1849 				if (!ext_part_present) {
1850 					/* Erroneous input file */
1851 					fprintf(stderr, "More than 4 primary"
1852 					    " partitions found in input\n");
1853 					fprintf(stderr, "Exiting...\n");
1854 					exit(1);
1855 				}
1856 
1857 				if (numsect == 0) {
1858 					continue;
1859 				}
1860 
1861 				/*
1862 				 * If the start and size of the existing
1863 				 * extended partition matches the new one and
1864 				 * new logical drives are being defined via
1865 				 * the input file, initialize the EBR.
1866 				 */
1867 				if (!ext_part_inited) {
1868 					fdisk_init_ext_part(epp,
1869 					    new_ext_beg_sec, new_ext_num_sec);
1870 					ext_part_inited = 1;
1871 				}
1872 
1873 				begsec = rsect - offset;
1874 				if ((ldcnt =
1875 				    fdisk_get_logical_drive_count(epp)) == 0) {
1876 					/* Adding the first logical drive */
1877 					/*
1878 					 * Make sure that begsec doesnt wrap
1879 					 * around. This can happen if rsect is
1880 					 * less than offset.
1881 					 */
1882 					if (rsect < offset) {
1883 						fprintf(stderr, "Minimum of "
1884 						    "63 free sectors required "
1885 						    "before the beginning of "
1886 						    "a logical drive.");
1887 						exit(1);
1888 					}
1889 					/*
1890 					 * Check if the first logical drive
1891 					 * is out of order. In that case, do
1892 					 * not subtract MAX_LOGDRIVE_OFFSET
1893 					 * from the given start of partition.
1894 					 */
1895 					if (begsec != new_ext_beg_sec) {
1896 						begsec = rsect;
1897 						offset = 0;
1898 					}
1899 				}
1900 				if (ldcnt >= MAX_EXT_PARTS) {
1901 					fprintf(stderr, "\nError : Number of "
1902 					    "logical drives exceeds limit of "
1903 					    "%d.\n", MAX_EXT_PARTS);
1904 					exit(1);
1905 				}
1906 
1907 				if (id > FDISK_MAX_VALID_PART_ID) {
1908 					fprintf(stderr, "Invalid partition "
1909 					    "ID\n");
1910 					fprintf(stderr, "fdisk: Error on"
1911 					    " entry \"%s\".\n", line);
1912 					exit(1);
1913 				}
1914 
1915 				endsec = rsect + numsect - 1;
1916 				if (fdisk_validate_logical_drive(epp,
1917 				    begsec, offset, numsect) == 0) {
1918 					if (id == EFI_PMBR) {
1919 						fprintf(stderr, "EFI "
1920 						    "partitions not supported "
1921 						    "inside extended "
1922 						    "partition\n");
1923 						exit(1);
1924 					}
1925 					fdisk_add_logical_drive(epp, begsec,
1926 					    endsec, id);
1927 					continue;
1928 				} else {
1929 					fprintf(stderr, "fdisk: Error on"
1930 					    " entry \"%s\".\n", line);
1931 					exit(1);
1932 				}
1933 			}
1934 #endif
1935 
1936 			/*
1937 			 * Validate the partition. It cannot start at sector
1938 			 * 0 unless it is UNUSED or already exists
1939 			 */
1940 			if (validate_part(id, rsect, numsect) < 0) {
1941 				(void) fprintf(stderr,
1942 				    "fdisk: Error on entry \"%s\".\n",
1943 				    line);
1944 				exit(1);
1945 			}
1946 
1947 			if (entry_from_old_table(id, act, bhead, bsect,
1948 			    bcyl, ehead, esect, ecyl, rsect, numsect)) {
1949 				/*
1950 				 * If we got here it means we copied an
1951 				 * unmodified entry. So there is no need
1952 				 * to insert it in the table or do any
1953 				 * checks against disk size.
1954 				 *
1955 				 * This is a work around on the following
1956 				 * situation (for IDE disks, at least):
1957 				 * Different operation systems calculate
1958 				 * disk size different ways, of which there
1959 				 * are two main ways.
1960 				 *
1961 				 * The first, rounds the disk size to modulo
1962 				 * cylinder size (virtual made-up cylinder
1963 				 * usually based on maximum number of heads
1964 				 * and sectors in partition table fields).
1965 				 * Our OS's (for IDE) and most other "Unix"
1966 				 * type OS's do this.
1967 				 *
1968 				 * The second, uses every single block
1969 				 * on the disk (to maximize available space).
1970 				 * Since disk manufactures do not know about
1971 				 * "virtual cylinders", there are some number
1972 				 * of blocks that make up a partial cylinder
1973 				 * at the end of the disk.
1974 				 *
1975 				 * The difference between these two methods
1976 				 * is where the problem is. When one
1977 				 * tries to install Solaris/OpenSolaris on
1978 				 * a disk that has another OS using that
1979 				 * "partial cylinder", install fails. It fails
1980 				 * since fdisk thinks its asked to create a
1981 				 * partition with the -F option that contains
1982 				 * a partition that runs off the end of the
1983 				 * disk.
1984 				 */
1985 				continue;
1986 			}
1987 
1988 			/*
1989 			 * Find an unused entry to use and put the entry
1990 			 * in table
1991 			 */
1992 			if (insert_tbl(id, act, bhead, bsect, bcyl, ehead,
1993 			    esect, ecyl, rsect, numsect) < 0) {
1994 				(void) fprintf(stderr,
1995 				    "fdisk: Error on entry \"%s\".\n",
1996 				    line);
1997 				exit(1);
1998 			}
1999 		} /* while (fgets(line, sizeof (line) - 1, fp)) */
2000 
2001 		if (verify_tbl() < 0) {
2002 			(void) fprintf(stderr,
2003 			    "fdisk: Cannot create partition table\n");
2004 			exit(1);
2005 		}
2006 
2007 		(void) fclose(fp);
2008 		return;
2009 
2010 	case LOADDEL:
2011 
2012 		/* Parse the user-supplied deletion line (-D) */
2013 		if (pars_fdisk(file, &id, &act, &bhead, &bsect, &bcyl,
2014 		    &ehead, &esect, &ecyl, &rsect, &numsect)) {
2015 			(void) fprintf(stderr,
2016 			    "fdisk: Syntax error \"%s\"\n", file);
2017 			exit(1);
2018 		}
2019 
2020 		/* Find the exact entry in the table */
2021 		for (i = 0; i < FD_NUMPART; i++) {
2022 			if (Table[i].systid == id &&
2023 			    Table[i].bootid == act &&
2024 			    Table[i].beghead == bhead &&
2025 			    Table[i].begsect == ((bsect & 0x3f) |
2026 			    (uchar_t)((bcyl>>2) & 0xc0)) &&
2027 			    Table[i].begcyl == (uchar_t)(bcyl & 0xff) &&
2028 			    Table[i].endhead == ehead &&
2029 			    Table[i].endsect == ((esect & 0x3f) |
2030 			    (uchar_t)((ecyl>>2) & 0xc0)) &&
2031 			    Table[i].endcyl == (uchar_t)(ecyl & 0xff) &&
2032 			    Table[i].relsect == LE_32(rsect) &&
2033 			    Table[i].numsect == LE_32(numsect)) {
2034 
2035 				/*
2036 				 * Found the entry. Now move rest of
2037 				 * entries up toward the top of the
2038 				 * table, leaving available entries at
2039 				 * the end of the fdisk table.
2040 				 */
2041 				for (j = i; j < FD_NUMPART - 1; j++) {
2042 					Table[j].systid = Table[j + 1].systid;
2043 					Table[j].bootid = Table[j + 1].bootid;
2044 					Table[j].beghead = Table[j + 1].beghead;
2045 					Table[j].begsect = Table[j + 1].begsect;
2046 					Table[j].begcyl = Table[j + 1].begcyl;
2047 					Table[j].endhead = Table[j + 1].endhead;
2048 					Table[j].endsect = Table[j + 1].endsect;
2049 					Table[j].endcyl = Table[j + 1].endcyl;
2050 					Table[j].relsect = Table[j + 1].relsect;
2051 					Table[j].numsect = Table[j + 1].numsect;
2052 				}
2053 
2054 				/*
2055 				 * Mark the last entry as unused in case
2056 				 * all table entries were in use prior
2057 				 * to the deletion.
2058 				 */
2059 
2060 				Table[FD_NUMPART - 1].systid = UNUSED;
2061 				Table[FD_NUMPART - 1].bootid = 0;
2062 #ifdef i386
2063 				if (fdisk_is_dos_extended(id)) {
2064 					fdisk_delete_ext_part(epp);
2065 				}
2066 #endif
2067 				return;
2068 			}
2069 		}
2070 
2071 #ifdef i386
2072 		ldcnt = FD_NUMPART + 1;
2073 		for (temp = fdisk_get_ld_head(epp); temp != NULL;
2074 		    temp = temp->next) {
2075 			relsect = temp->abs_secnum + temp->logdrive_offset;
2076 			if (temp->parts[0].systid == id &&
2077 			    temp->parts[0].bootid == act &&
2078 			    temp->parts[0].beghead == bhead &&
2079 			    temp->parts[0].begsect == ((bsect & 0x3f) |
2080 			    (uchar_t)((bcyl>>2) & 0xc0)) &&
2081 			    temp->parts[0].begcyl == (uchar_t)(bcyl & 0xff) &&
2082 			    temp->parts[0].endhead == ehead &&
2083 			    temp->parts[0].endsect == ((esect & 0x3f) |
2084 			    (uchar_t)((ecyl>>2) & 0xc0)) &&
2085 			    temp->parts[0].endcyl == (uchar_t)(ecyl & 0xff) &&
2086 			    relsect == LE_32(rsect) &&
2087 			    temp->parts[0].numsect == LE_32(numsect)) {
2088 				fdisk_delete_logical_drive(epp, ldcnt);
2089 				return;
2090 			}
2091 			ldcnt++;
2092 		}
2093 #endif
2094 
2095 		(void) fprintf(stderr,
2096 		    "fdisk: Entry does not match any existing partition:\n"
2097 		    "	\"%s\"\n",
2098 		    file);
2099 		exit(1);
2100 		/* FALLTHRU */
2101 
2102 	case LOADADD:
2103 
2104 		/* Parse the user-supplied addition line (-A) */
2105 		if (pars_fdisk(file, &id, &act, &bhead, &bsect, &bcyl, &ehead,
2106 		    &esect, &ecyl, &rsect, &numsect)) {
2107 			(void) fprintf(stderr,
2108 			    "fdisk: Syntax error \"%s\"\n", file);
2109 			exit(1);
2110 		}
2111 
2112 		/* Validate the partition. It cannot start at sector 0 */
2113 		if (rsect == 0) {
2114 			(void) fprintf(stderr,
2115 			    "fdisk: New partition cannot start at sector 0:\n"
2116 			    "   \"%s\".\n",
2117 			    file);
2118 			exit(1);
2119 		}
2120 
2121 		/*
2122 		 * if the user wishes to add an EFI partition, we need
2123 		 * more extensive validation.  rsect should be 1, and
2124 		 * numsect should equal the entire disk capacity - 1
2125 		 */
2126 
2127 		if (id == EFI_PMBR) {
2128 			if (rsect != 1) {
2129 				(void) fprintf(stderr,
2130 				    "fdisk: EFI partitions must start at sector"
2131 				    " 1 (input rsect = %d)\n", rsect);
2132 				exit(1);
2133 			}
2134 
2135 
2136 			if (dev_capacity > DK_MAX_2TB) {
2137 				if (numsect != DK_MAX_2TB) {
2138 					(void) fprintf(stderr,
2139 					    "fdisk: EFI partitions must "
2140 					    "encompass the entire maximum 2 TB "
2141 					    "(input numsect: %u - max: %llu)\n",
2142 					    numsect, (diskaddr_t)DK_MAX_2TB);
2143 				exit(1);
2144 				}
2145 			} else if (numsect != dev_capacity - 1) {
2146 				(void) fprintf(stderr,
2147 				    "fdisk: EFI partitions must encompass the "
2148 				    "entire disk\n"
2149 				    "(input numsect: %u - avail: %llu)\n",
2150 				    numsect,
2151 				    dev_capacity - 1);
2152 				exit(1);
2153 			}
2154 		}
2155 
2156 #ifdef i386
2157 		if (id > FDISK_MAX_VALID_PART_ID) {
2158 			printf("Invalid partition ID\n");
2159 			exit(1);
2160 		}
2161 
2162 		if ((fdisk_ext_part_exists(epp)) &&
2163 		    (fdisk_is_dos_extended(id))) {
2164 			(void) fprintf(stderr,
2165 			    "Extended partition already exists.\n");
2166 			(void) fprintf(stderr,
2167 			    "fdisk: Invalid entry could not be "
2168 			    "inserted:\n        \"%s\"\n", file);
2169 			exit(1);
2170 		}
2171 
2172 		if (fdisk_ext_part_exists(epp) &&
2173 		    (rsect >= (ext_beg_sec = fdisk_get_ext_beg_sec(epp))) &&
2174 		    (rsect <= (ext_end_sec = fdisk_get_ext_end_sec(epp)))) {
2175 			int offset = MAX_LOGDRIVE_OFFSET;
2176 
2177 			/*
2178 			 * Make sure that begsec doesnt wrap around.
2179 			 * This can happen if rsect is less than offset
2180 			 */
2181 			if (rsect < offset) {
2182 				return;
2183 			}
2184 			begsec = rsect - offset;
2185 			if ((ldcnt = fdisk_get_logical_drive_count(epp)) == 0) {
2186 				/*
2187 				 * Adding the first logical drive
2188 				 * Check if the first logical drive
2189 				 * is out of order. In that case, do
2190 				 * not subtract MAX_LOGDRIVE_OFFSET
2191 				 * from the given start of partition.
2192 				 */
2193 				if (begsec != ext_beg_sec) {
2194 					begsec = rsect;
2195 					offset = 0;
2196 				}
2197 			}
2198 
2199 			if (ldcnt >= MAX_EXT_PARTS) {
2200 				printf("\nNumber of logical drives exceeds "
2201 				    "limit of %d.\n", MAX_EXT_PARTS);
2202 				printf("Failing further additions.\n");
2203 				exit(1);
2204 			}
2205 
2206 			if (numsect == 0) {
2207 				(void) fprintf(stderr,
2208 				    "fdisk: Partition size cannot be zero:\n"
2209 				    "   \"%s\".\n",
2210 				    file);
2211 				exit(1);
2212 			}
2213 			endsec = rsect + numsect - 1;
2214 			if (fdisk_validate_logical_drive(epp, begsec,
2215 			    offset, numsect) == 0) {
2216 				/* Valid logical drive */
2217 				fdisk_add_logical_drive(epp, begsec, endsec,
2218 				    id);
2219 				return;
2220 			} else {
2221 				(void) fprintf(stderr,
2222 				    "fdisk: Invalid entry could not be "
2223 				    "inserted:\n        \"%s\"\n", file);
2224 				exit(1);
2225 			}
2226 		}
2227 #endif
2228 
2229 		/* Find unused entry for use and put entry in table */
2230 		if (insert_tbl(id, act, bhead, bsect, bcyl, ehead, esect,
2231 		    ecyl, rsect, numsect) < 0) {
2232 			(void) fprintf(stderr,
2233 			    "fdisk: Invalid entry could not be inserted:\n"
2234 			    "	\"%s\"\n",
2235 			    file);
2236 			exit(1);
2237 		}
2238 
2239 		/* Make sure new entry does not overlap existing entry */
2240 		if (verify_tbl() < 0) {
2241 			(void) fprintf(stderr,
2242 			    "fdisk: Cannot create partition \"%s\"\n", file);
2243 			exit(1);
2244 		}
2245 	} /* switch funct */
2246 }
2247 
2248 /*
2249  * Set_Table_CHS_Values
2250  *
2251  * This will calculate the CHS values for beginning and ending CHS
2252  * for a single partition table entry (ti) based on the relsect
2253  * and numsect values contained in the partion table entry.
2254  *
2255  * hba_heads and hba_sectors contain the number of heads and sectors.
2256  *
2257  * If the number of cylinders exceeds the MAX_CYL,
2258  * then maximum values will be placed in the corresponding chs entry.
2259  */
2260 static void
2261 Set_Table_CHS_Values(int ti)
2262 {
2263 	uint32_t	lba, cy, hd, sc;
2264 
2265 	lba = (uint32_t)Table[ti].relsect;
2266 	if (lba >= hba_heads * hba_sectors * MAX_CYL) {
2267 		/*
2268 		 * the lba address cannot be expressed in CHS value
2269 		 * so store the maximum CHS field values in the CHS fields.
2270 		 */
2271 		cy = MAX_CYL + 1;
2272 		hd = MAX_HEAD;
2273 		sc = MAX_SECT;
2274 	} else {
2275 		cy = lba / hba_sectors / hba_heads;
2276 		hd = lba / hba_sectors % hba_heads;
2277 		sc = lba % hba_sectors + 1;
2278 	}
2279 	Table[ti].begcyl = cy & 0xff;
2280 	Table[ti].beghead = (uchar_t)hd;
2281 	Table[ti].begsect = (uchar_t)(((cy >> 2) & 0xc0) | sc);
2282 
2283 	/*
2284 	 * This code is identical to the code above
2285 	 * except that it works on ending CHS values
2286 	 */
2287 	lba = (uint32_t)(Table[ti].relsect + Table[ti].numsect - 1);
2288 	if (lba >= hba_heads * hba_sectors * MAX_CYL) {
2289 		cy = MAX_CYL + 1;
2290 		hd = MAX_HEAD;
2291 		sc = MAX_SECT;
2292 	} else {
2293 		cy = lba / hba_sectors / hba_heads;
2294 		hd = lba / hba_sectors % hba_heads;
2295 		sc = lba % hba_sectors + 1;
2296 	}
2297 	Table[ti].endcyl = cy & 0xff;
2298 	Table[ti].endhead = (uchar_t)hd;
2299 	Table[ti].endsect = (uchar_t)(((cy >> 2) & 0xc0) | sc);
2300 }
2301 
2302 /*
2303  * insert_tbl
2304  * 	Insert entry into fdisk table. Check all user-supplied values
2305  *	for the entry, but not the validity relative to other table
2306  *	entries!
2307  */
2308 static int
2309 insert_tbl(
2310     int id, int act,
2311     int bhead, int bsect, int bcyl,
2312     int ehead, int esect, int ecyl,
2313     uint32_t rsect, uint32_t numsect)
2314 {
2315 	int	i;
2316 
2317 	/* validate partition size */
2318 	if (((diskaddr_t)rsect + numsect) > dev_capacity) {
2319 		(void) fprintf(stderr,
2320 		    "fdisk: Partition table exceeds the size of the disk.\n");
2321 		return (-1);
2322 	}
2323 
2324 
2325 	/* find UNUSED partition table entry */
2326 	for (i = 0; i < FD_NUMPART; i++) {
2327 		if (Table[i].systid == UNUSED) {
2328 			break;
2329 		}
2330 	}
2331 	if (i >= FD_NUMPART) {
2332 		(void) fprintf(stderr, "fdisk: Partition table is full.\n");
2333 		return (-1);
2334 	}
2335 
2336 
2337 	Table[i].systid = (uchar_t)id;
2338 	Table[i].bootid = (uchar_t)act;
2339 	Table[i].numsect = LE_32(numsect);
2340 	Table[i].relsect = LE_32(rsect);
2341 
2342 	/*
2343 	 * If we have been called with a valid geometry, use it
2344 	 * valid means non-zero values that fit in the BIOS fields
2345 	 */
2346 	if (0 < bsect && bsect <= MAX_SECT &&
2347 	    0 <= bhead && bhead <= MAX_HEAD &&
2348 	    0 < esect && esect <= MAX_SECT &&
2349 	    0 <= ehead && ehead <= MAX_HEAD) {
2350 		if (bcyl > MAX_CYL)
2351 			bcyl = MAX_CYL + 1;
2352 		if (ecyl > MAX_CYL)
2353 			ecyl = MAX_CYL + 1;
2354 		Table[i].begcyl = bcyl & 0xff;
2355 		Table[i].endcyl = ecyl & 0xff;
2356 		Table[i].beghead = (uchar_t)bhead;
2357 		Table[i].endhead = (uchar_t)ehead;
2358 		Table[i].begsect = (uchar_t)(((bcyl >> 2) & 0xc0) | bsect);
2359 		Table[i].endsect = ((ecyl >> 2) & 0xc0) | esect;
2360 	} else {
2361 
2362 		/*
2363 		 * The specified values are invalid,
2364 		 * so calculate the values based on hba_heads, hba_sectors
2365 		 */
2366 		Set_Table_CHS_Values(i);
2367 	}
2368 
2369 	/*
2370 	 * return partition index
2371 	 */
2372 	return (i);
2373 }
2374 
2375 /*
2376  * entry_from_old_table
2377  *	If the specified entry is in the old table and is not a Solaris entry
2378  *	then insert same entry into new fdisk table. If we do this then
2379  *	all checks are skipped for that entry!
2380  */
2381 static int
2382 entry_from_old_table(
2383     int id, int act,
2384     int bhead, int bsect, int bcyl,
2385     int ehead, int esect, int ecyl,
2386     uint32_t rsect, uint32_t numsect)
2387 {
2388 	uint32_t	i, j;
2389 
2390 	if (id == SUNIXOS || id == SUNIXOS2)
2391 		return (0);
2392 	for (i = 0; i < FD_NUMPART; i++) {
2393 		if (Old_Table[i].systid == id &&
2394 		    Old_Table[i].bootid == act &&
2395 		    Old_Table[i].beghead == bhead &&
2396 		    Old_Table[i].begsect == ((bsect & 0x3f) |
2397 		    (uchar_t)((bcyl>>2) & 0xc0)) &&
2398 		    Old_Table[i].begcyl == (uchar_t)(bcyl & 0xff) &&
2399 		    Old_Table[i].endhead == ehead &&
2400 		    Old_Table[i].endsect == ((esect & 0x3f) |
2401 		    (uchar_t)((ecyl>>2) & 0xc0)) &&
2402 		    Old_Table[i].endcyl == (uchar_t)(ecyl & 0xff) &&
2403 		    Old_Table[i].relsect == lel(rsect) &&
2404 		    Old_Table[i].numsect == lel(numsect)) {
2405 			/* find UNUSED partition table entry */
2406 			for (j = 0; j < FD_NUMPART; j++) {
2407 				if (Table[j].systid == UNUSED) {
2408 					(void) memcpy(&Table[j], &Old_Table[i],
2409 					    sizeof (Table[0]));
2410 					skip_verify[j] = 1;
2411 					return (1);
2412 
2413 				}
2414 			}
2415 			return (0);
2416 		}
2417 
2418 	}
2419 	return (0);
2420 }
2421 
2422 /*
2423  * verify_tbl
2424  * Verify that no partition entries overlap or exceed the size of
2425  * the disk.
2426  */
2427 static int
2428 verify_tbl(void)
2429 {
2430 	uint32_t	i, j, rsect, numsect;
2431 	int	noMoreParts = 0;
2432 	int	numParts = 0;
2433 
2434 	/* Make sure new entry does not overlap an existing entry */
2435 	for (i = 0; i < FD_NUMPART - 1; i++) {
2436 		if (Table[i].systid != UNUSED) {
2437 			numParts++;
2438 			/*
2439 			 * No valid partitions allowed after an UNUSED  or
2440 			 * EFI_PMBR part
2441 			 */
2442 			if (noMoreParts) {
2443 				return (-1);
2444 			}
2445 
2446 			/*
2447 			 * EFI_PMBR partitions must be the only partition
2448 			 * and must be Table entry 0
2449 			 */
2450 			if (Table[i].systid == EFI_PMBR) {
2451 				if (i == 0) {
2452 					noMoreParts = 1;
2453 				} else {
2454 					return (-1);
2455 				}
2456 
2457 				if (Table[i].relsect != 1) {
2458 					(void) fprintf(stderr, "ERROR: "
2459 					    "Invalid starting sector "
2460 					    "for EFI_PMBR partition:\n"
2461 					    "relsect %d "
2462 					    "(should be 1)\n",
2463 					    Table[i].relsect);
2464 
2465 					return (-1);
2466 				}
2467 
2468 				if (Table[i].numsect != dev_capacity - 1) {
2469 					(void) fprintf(stderr, "ERROR: "
2470 					    "EFI_PMBR partition must "
2471 					    "encompass the entire "
2472 					    "disk.\n numsect %d - "
2473 					    "actual %llu\n",
2474 					    Table[i].numsect,
2475 					    dev_capacity - 1);
2476 
2477 					return (-1);
2478 				}
2479 			}
2480 
2481 			/* make sure the partition isn't larger than the disk */
2482 			rsect = LE_32(Table[i].relsect);
2483 			numsect = LE_32(Table[i].numsect);
2484 
2485 			if ((((diskaddr_t)rsect + numsect) > dev_capacity) ||
2486 			    (((diskaddr_t)rsect + numsect) > DK_MAX_2TB)) {
2487 				if (!skip_verify[i])
2488 					return (-1);
2489 			}
2490 
2491 			for (j = i + 1; j < FD_NUMPART; j++) {
2492 				if (Table[j].systid != UNUSED) {
2493 					uint32_t t_relsect =
2494 					    LE_32(Table[j].relsect);
2495 					uint32_t t_numsect =
2496 					    LE_32(Table[j].numsect);
2497 
2498 					if (noMoreParts) {
2499 						(void) fprintf(stderr,
2500 						    "Cannot add partition to "
2501 						    "table; no more partitions "
2502 						    "allowed\n");
2503 
2504 						if (io_debug) {
2505 							(void) fprintf(stderr,
2506 							    "DEBUG: Current "
2507 							    "partition:\t"
2508 							    "%d:%d:%d:%d:%d:"
2509 							    "%d:%d:%d:%d:%d\n"
2510 							    "       Next "
2511 							    "partition:\t\t"
2512 							    "%d:%d:%d:%d:%d:"
2513 							    "%d:%d:%d:%d:%d\n",
2514 							    Table[i].systid,
2515 							    Table[i].bootid,
2516 							    Table[i].begcyl,
2517 							    Table[i].beghead,
2518 							    Table[i].begsect,
2519 							    Table[i].endcyl,
2520 							    Table[i].endhead,
2521 							    Table[i].endsect,
2522 							    Table[i].relsect,
2523 							    Table[i].numsect,
2524 							    Table[j].systid,
2525 							    Table[j].bootid,
2526 							    Table[j].begcyl,
2527 							    Table[j].beghead,
2528 							    Table[j].begsect,
2529 							    Table[j].endcyl,
2530 							    Table[j].endhead,
2531 							    Table[j].endsect,
2532 							    Table[j].relsect,
2533 							    Table[j].numsect);
2534 						}
2535 
2536 						return (-1);
2537 					}
2538 					if ((rsect >=
2539 					    (t_relsect + t_numsect)) ||
2540 					    ((rsect + numsect) <= t_relsect)) {
2541 						continue;
2542 					} else {
2543 						(void) fprintf(stderr, "ERROR: "
2544 						    "current partition overlaps"
2545 						    " following partition\n");
2546 
2547 						return (-1);
2548 					}
2549 				}
2550 			}
2551 		} else {
2552 			noMoreParts = 1;
2553 		}
2554 	}
2555 	if (Table[i].systid != UNUSED) {
2556 		if (noMoreParts)
2557 			return (-1);
2558 		if (!skip_verify[i] &&
2559 		    ((((diskaddr_t)lel(Table[i].relsect) +
2560 		    lel(Table[i].numsect)) > dev_capacity) ||
2561 		    (((diskaddr_t)lel(Table[i].relsect) +
2562 		    lel(Table[i].numsect)) > DK_MAX_2TB))) {
2563 			return (-1);
2564 		}
2565 	}
2566 
2567 	return (numParts);
2568 }
2569 
2570 /*
2571  * pars_fdisk
2572  * Parse user-supplied data to set up fdisk partitions
2573  * (-A, -D, -F).
2574  */
2575 static int
2576 pars_fdisk(
2577     char *line,
2578     int *id, int *act,
2579     int *bhead, int *bsect, int *bcyl,
2580     int *ehead, int *esect, int *ecyl,
2581     uint32_t *rsect, uint32_t *numsect)
2582 {
2583 	int	i;
2584 	int64_t test;
2585 	char *tok, *p;
2586 	char buf[256];
2587 
2588 	if (line[0] == '\0' || line[0] == '\n' || line[0] == '*')
2589 		return (1);
2590 	line[strlen(line)] = '\0';
2591 	for (i = 0; i < strlen(line); i++) {
2592 		if (line[i] == '\0') {
2593 			break;
2594 		} else if (line[i] == ':') {
2595 			line[i] = ' ';
2596 		}
2597 	}
2598 	strncpy(buf, line, 256);
2599 	errno = 0;
2600 	tok = strtok(buf, ": \t\n");
2601 	while (tok != NULL) {
2602 		for (p = tok; *p != '\0'; p++) {
2603 			if (!isdigit(*p)) {
2604 				printf("Invalid input %s in line %s.\n",
2605 				    tok, line);
2606 				exit(1);
2607 			}
2608 		}
2609 
2610 		test = strtoll(tok, (char **)NULL, 10);
2611 		if ((test < 0) || (test > 0xFFFFFFFF) || (errno != 0)) {
2612 			printf("Invalid input %s in line %s.\n", tok, line);
2613 			exit(1);
2614 		}
2615 		tok = strtok(NULL, ": \t\n");
2616 	}
2617 	if (sscanf(line, "%d %d %d %d %d %d %d %d %u %u",
2618 	    id, act, bhead, bsect, bcyl, ehead, esect, ecyl,
2619 	    rsect, numsect) != 10) {
2620 		(void) fprintf(stderr, "Syntax error:\n	\"%s\".\n", line);
2621 		exit(1);
2622 	}
2623 	return (0);
2624 }
2625 
2626 /*
2627  * validate_part
2628  * Validate that a new partition does not start at sector 0. Only UNUSED
2629  * partitions and previously existing partitions are allowed to start at 0.
2630  */
2631 static int
2632 validate_part(int id, uint32_t rsect, uint32_t numsect)
2633 {
2634 	int i;
2635 	if ((id != UNUSED) && (rsect == 0)) {
2636 		for (i = 0; i < FD_NUMPART; i++) {
2637 			if ((Old_Table[i].systid == id) &&
2638 			    (Old_Table[i].relsect == LE_32(rsect)) &&
2639 			    (Old_Table[i].numsect == LE_32(numsect)))
2640 				return (0);
2641 		}
2642 		(void) fprintf(stderr,
2643 		    "New partition cannot start at sector 0\n");
2644 		return (-1);
2645 	}
2646 #ifdef i386
2647 	if (id > FDISK_MAX_VALID_PART_ID) {
2648 		fprintf(stderr, "Invalid partition ID\n");
2649 		return (-1);
2650 	}
2651 #endif
2652 	return (0);
2653 }
2654 
2655 /*
2656  * stage0
2657  * Print out interactive menu and process user input.
2658  */
2659 static void
2660 stage0(void)
2661 {
2662 #ifdef i386
2663 	int rval;
2664 #endif
2665 	dispmenu();
2666 	for (;;) {
2667 		(void) printf(Q_LINE);
2668 		(void) printf("Enter Selection: ");
2669 		(void) fgets(s, sizeof (s), stdin);
2670 		rm_blanks(s);
2671 #ifdef i386
2672 		while (!((s[0] > '0') && (s[0] < '8') &&
2673 		    ((s[1] == '\0') || (s[1] == '\n')))) {
2674 #else
2675 		while (!((s[0] > '0') && (s[0] < '7') &&
2676 		    ((s[1] == '\0') || (s[1] == '\n')))) {
2677 #endif
2678 			(void) printf(E_LINE); /* Clear any previous error */
2679 #ifdef i386
2680 			(void) printf(
2681 			    "Enter a one-digit number between 1 and 7.");
2682 #else
2683 			(void) printf(
2684 			    "Enter a one-digit number between 1 and 6.");
2685 #endif
2686 			(void) printf(Q_LINE);
2687 			(void) printf("Enter Selection: ");
2688 			(void) fgets(s, sizeof (s), stdin);
2689 			rm_blanks(s);
2690 		}
2691 		(void) printf(E_LINE);
2692 		switch (s[0]) {
2693 			case '1':
2694 				if (pcreate() == -1)
2695 					return;
2696 				break;
2697 			case '2':
2698 				if (pchange() == -1)
2699 					return;
2700 				break;
2701 			case '3':
2702 				if (pdelete() == -1)
2703 					return;
2704 				break;
2705 			case '4':
2706 				if (ppartid() == -1)
2707 					return;
2708 				break;
2709 #ifdef i386
2710 			case '5':
2711 				if (fdisk_ext_part_exists(epp)) {
2712 					ext_part_menu();
2713 				} else {
2714 					printf(Q_LINE);
2715 					printf("\nNo extended partition found"
2716 					    "\n");
2717 					printf("Press enter to continue\n");
2718 					ext_read_input(s);
2719 				}
2720 				break;
2721 			case '6':
2722 				/* update disk partition table, if changed */
2723 				if (TableChanged() == 1) {
2724 					copy_Table_to_Bootblk();
2725 					dev_mboot_write(0, Bootsect, sectsiz);
2726 				}
2727 
2728 				/*
2729 				 * If the VTOC table is wrong fix it
2730 				 * (truncate only)
2731 				 */
2732 				if (io_adjt) {
2733 					fix_slice();
2734 				}
2735 				if (!io_readonly) {
2736 					rval = fdisk_commit_ext_part(epp);
2737 					switch (rval) {
2738 						case FDISK_SUCCESS:
2739 							/* Success */
2740 							/* Fallthrough */
2741 						case FDISK_ENOEXTPART:
2742 							/* Nothing to do */
2743 							break;
2744 						case FDISK_EMOUNTED:
2745 							printf(Q_LINE);
2746 							preach_and_continue();
2747 							continue;
2748 						default:
2749 							perror("Commit failed");
2750 							exit(1);
2751 					}
2752 					libfdisk_fini(&epp);
2753 				}
2754 				(void) close(Dev);
2755 				exit(0);
2756 #else
2757 			case '5':
2758 				/* update disk partition table, if changed */
2759 				if (TableChanged() == 1) {
2760 					copy_Table_to_Bootblk();
2761 					dev_mboot_write(0, Bootsect, sectsiz);
2762 				}
2763 				/*
2764 				 * If the VTOC table is wrong fix it
2765 				 * (truncate only)
2766 				 */
2767 				if (io_adjt) {
2768 					fix_slice();
2769 				}
2770 				(void) close(Dev);
2771 				exit(0);
2772 				/* FALLTHRU */
2773 #endif
2774 #ifdef i386
2775 			case '7':
2776 #else
2777 			case '6':
2778 #endif
2779 				/*
2780 				 * If the VTOC table is wrong fix it
2781 				 * (truncate only)
2782 				 */
2783 				if (io_adjt) {
2784 					fix_slice();
2785 				}
2786 				(void) close(Dev);
2787 				exit(0);
2788 				/* FALLTHRU */
2789 			default:
2790 				break;
2791 		}
2792 		copy_Table_to_Bootblk();
2793 		disptbl();
2794 		dispmenu();
2795 	}
2796 }
2797 
2798 /*
2799  * pcreate
2800  * Create partition entry in the table (interactive mode).
2801  */
2802 static int
2803 pcreate(void)
2804 {
2805 	uchar_t tsystid = 'z';
2806 	int i, j;
2807 	uint32_t numsect;
2808 	int retCode = 0;
2809 #ifdef i386
2810 	int ext_part_present = 0;
2811 #endif
2812 
2813 	i = 0;
2814 	for (;;) {
2815 		if (i == FD_NUMPART) {
2816 			(void) printf(E_LINE);
2817 			(void) printf(
2818 			    "The partition table is full!\n"
2819 			    "You must delete a partition before creating"
2820 			    " a new one.\n");
2821 			return (-1);
2822 		}
2823 		if (Table[i].systid == UNUSED) {
2824 			break;
2825 		}
2826 		i++;
2827 	}
2828 
2829 	numsect = 0;
2830 	for (i = 0; i < FD_NUMPART; i++) {
2831 		if (Table[i].systid != UNUSED) {
2832 			numsect += LE_32(Table[i].numsect);
2833 		}
2834 #ifdef i386
2835 		/* Check if an extended partition already exists */
2836 		if (fdisk_is_dos_extended(Table[i].systid)) {
2837 			ext_part_present = 1;
2838 		}
2839 #endif
2840 		if (numsect >= chs_capacity) {
2841 			(void) printf(E_LINE);
2842 			(void) printf("There is no more room on the disk for"
2843 			    " another partition.\n");
2844 			(void) printf(
2845 			    "You must delete a partition before creating"
2846 			    " a new one.\n");
2847 			return (-1);
2848 		}
2849 	}
2850 	while (tsystid == 'z') {
2851 
2852 		/*
2853 		 * The question here is expanding to more than what is
2854 		 * allocated for question lines (Q_LINE) which garbles
2855 		 * at least warning line. Clearing warning line as workaround
2856 		 * for now.
2857 		 */
2858 
2859 		(void) printf(W_LINE);
2860 		(void) printf(Q_LINE);
2861 		(void) printf(
2862 		    "Select the partition type to create:\n"
2863 		    "   1=SOLARIS2  2=UNIX        3=PCIXOS     4=Other\n"
2864 		    "   5=DOS12     6=DOS16       7=DOSEXT     8=DOSBIG\n"
2865 		    "   9=DOS16LBA  A=x86 Boot    B=Diagnostic C=FAT32\n"
2866 		    "   D=FAT32LBA  E=DOSEXTLBA   F=EFI        0=Exit? ");
2867 		(void) fgets(s, sizeof (s), stdin);
2868 		rm_blanks(s);
2869 		if ((s[1] != '\0') && (s[1] != '\n')) {
2870 			(void) printf(E_LINE);
2871 			(void) printf("Invalid selection, try again.");
2872 			continue;
2873 		}
2874 		switch (s[0]) {
2875 		case '0':		/* exit */
2876 			(void) printf(E_LINE);
2877 			return (-1);
2878 		case '1':		/* Solaris partition */
2879 			tsystid = SUNIXOS2;
2880 			break;
2881 		case '2':		/* UNIX partition */
2882 			tsystid = UNIXOS;
2883 			break;
2884 		case '3':		/* PCIXOS partition */
2885 			tsystid = PCIXOS;
2886 			break;
2887 		case '4':		/* OTHEROS System partition */
2888 			tsystid = OTHEROS;
2889 			break;
2890 		case '5':
2891 			tsystid = DOSOS12; /* DOS 12 bit fat */
2892 			break;
2893 		case '6':
2894 			tsystid = DOSOS16; /* DOS 16 bit fat */
2895 			break;
2896 		case '7':
2897 #ifdef i386
2898 			if (ext_part_present) {
2899 				printf(Q_LINE);
2900 				printf(E_LINE);
2901 				fprintf(stderr,
2902 				    "Extended partition already exists\n");
2903 				fprintf(stderr, "Press enter to continue\n");
2904 				ext_read_input(s);
2905 				continue;
2906 			}
2907 #endif
2908 			tsystid = EXTDOS;
2909 			break;
2910 		case '8':
2911 			tsystid = DOSHUGE;
2912 			break;
2913 		case '9':
2914 			tsystid = FDISK_FAT95;  /* FAT16, need extended int13 */
2915 			break;
2916 		case 'a':		/* x86 Boot partition */
2917 		case 'A':
2918 			tsystid = X86BOOT;
2919 			break;
2920 		case 'b':		/* Diagnostic boot partition */
2921 		case 'B':
2922 			tsystid = DIAGPART;
2923 			break;
2924 		case 'c':		/* FAT32 */
2925 		case 'C':
2926 			tsystid = FDISK_WINDOWS;
2927 			break;
2928 		case 'd':		/* FAT32 and need extended int13 */
2929 		case 'D':
2930 			tsystid = FDISK_EXT_WIN;
2931 			break;
2932 		case 'e':	/* Extended partition, need extended int13 */
2933 		case 'E':
2934 #ifdef i386
2935 			if (ext_part_present) {
2936 				printf(Q_LINE);
2937 				printf(E_LINE);
2938 				fprintf(stderr,
2939 				    "Extended partition already exists\n");
2940 				fprintf(stderr, "Press enter to continue\n");
2941 				ext_read_input(s);
2942 				continue;
2943 			}
2944 #endif
2945 			tsystid = FDISK_EXTLBA;
2946 			break;
2947 		case 'f':
2948 		case 'F':
2949 			tsystid = EFI_PMBR;
2950 			break;
2951 		default:
2952 			(void) printf(E_LINE);
2953 			(void) printf("Invalid selection, try again.");
2954 			continue;
2955 		}
2956 	}
2957 
2958 	(void) printf(E_LINE);
2959 
2960 	if (tsystid != EFI_PMBR) {
2961 		(void) printf(W_LINE);
2962 		if ((dev_capacity > DK_MAX_2TB))
2963 			(void) printf("WARNING: Disk is larger than 2 TB. "
2964 			    "Upper limit is 2 TB for non-EFI partition ID\n");
2965 
2966 		/* create the new partition */
2967 		i = specify(tsystid);
2968 
2969 		if (i != -1) {
2970 			/* see if it should be the active partition */
2971 			(void) printf(E_LINE);
2972 			(void) printf(Q_LINE);
2973 
2974 			(void) printf(
2975 			    "Should this become the active partition? If "
2976 			    "yes, it  will be activated\n"
2977 			    "each time the computer is reset or turned on.\n"
2978 			    "Please type \"y\" or \"n\". ");
2979 
2980 			if (yesno()) {
2981 				(void) printf(E_LINE);
2982 				for (j = 0; j < FD_NUMPART; j++) {
2983 					if (j == i) {
2984 						Table[j].bootid = ACTIVE;
2985 						(void) printf(E_LINE);
2986 						(void) printf(
2987 						    "Partition %d is now "
2988 						    "the active partition.",
2989 						    j + 1);
2990 					} else {
2991 						Table[j].bootid = 0;
2992 					}
2993 				}
2994 			} else {
2995 				Table[i].bootid = 0;
2996 			}
2997 
2998 #ifdef i386
2999 			/*
3000 			 * If partition created is an extended partition, null
3001 			 * out the first sector of the first cylinder of the
3002 			 * extended partition
3003 			 */
3004 			if (fdisk_is_dos_extended(Table[i].systid)) {
3005 				fdisk_init_ext_part(epp,
3006 				    LE_32(Table[i].relsect),
3007 				    LE_32(Table[i].numsect));
3008 			}
3009 #endif
3010 			/* set up the return code */
3011 			i = 1;
3012 		}
3013 	} else {
3014 		/*
3015 		 * partitions of type EFI_PMBR must be the only partitions in
3016 		 * the table
3017 		 *
3018 		 * First, make sure there were no errors the table is
3019 		 * empty
3020 		 */
3021 		retCode = verify_tbl();
3022 
3023 		if (retCode < 0) {
3024 			(void) fprintf(stderr,
3025 			    "fdisk: Cannot create EFI partition table; \n"
3026 			    "current partition table is invalid.\n");
3027 			return (-1);
3028 		} else if (retCode > 0) {
3029 			(void) printf(
3030 			    "An EFI partition must be the only partition on "
3031 			    "disk.  You may manually delete existing\n"
3032 			    "partitions, or fdisk can do it.\n"
3033 			    "Do you want fdisk to destroy existing "
3034 			    "partitions?\n"
3035 			    "Please type \"y\" or \"n\". ");
3036 
3037 			if (yesno()) {
3038 				nulltbl();
3039 			} else {
3040 				return (-1);
3041 			}
3042 		}
3043 
3044 		/* create the table entry - i should be 0 */
3045 		i = insert_tbl(tsystid, 0, 0, 0, 0, 0, 0, 0, 1,
3046 		    (dev_capacity > DK_MAX_2TB) ? DK_MAX_2TB:
3047 		    (dev_capacity - 1));
3048 
3049 		if (i != 0) {
3050 			(void) printf("Error creating EFI partition!!!\n");
3051 			i = -1;
3052 		} else {
3053 
3054 			/* EFI partitions are currently never active */
3055 			Table[i].bootid = 0;
3056 
3057 			/* set up the return code */
3058 			i = 1;
3059 		}
3060 	}
3061 
3062 	return (i);
3063 }
3064 
3065 /*
3066  * specify
3067  * Query the user to specify the size of the new partition in
3068  * terms of percentage of the disk or by specifying the starting
3069  * cylinder and length in cylinders.
3070  */
3071 static int
3072 specify(uchar_t tsystid)
3073 {
3074 	int	i, j, percent = -1;
3075 	int	cyl, cylen;
3076 	diskaddr_t first_free, size_free;
3077 	diskaddr_t max_free;
3078 	int	cyl_size;
3079 	struct ipart *partition[FD_NUMPART];
3080 
3081 	cyl_size = heads * sectors;
3082 
3083 	/*
3084 	 * make a local copy of the partition table
3085 	 * and sort it into relsect order
3086 	 */
3087 	for (i = 0; i < FD_NUMPART; i++)
3088 		partition[i] = &Table[i];
3089 
3090 	for (i = 0; i < FD_NUMPART - 1; i++) {
3091 		if (partition[i]->systid == UNUSED)
3092 			break;
3093 		for (j = i + 1; j < FD_NUMPART; j++) {
3094 			if (partition[j]->systid == UNUSED)
3095 				break;
3096 			if (LE_32(partition[j]->relsect) <
3097 			    LE_32(partition[i]->relsect)) {
3098 				struct ipart *temp = partition[i];
3099 				partition[i] = partition[j];
3100 				partition[j] = temp;
3101 			}
3102 		}
3103 	}
3104 
3105 
3106 	(void) printf(Q_LINE);
3107 	(void) printf(
3108 	    "Specify the percentage of disk to use for this partition\n"
3109 	    "(or type \"c\" to specify the size in cylinders). ");
3110 	(void) fgets(s, sizeof (s), stdin);
3111 	rm_blanks(s);
3112 	if (s[0] != 'c') {	/* Specify size in percentage of disk */
3113 		i = 0;
3114 		while ((s[i] != '\0') && (s[i] != '\n')) {
3115 			if (s[i] < '0' || s[i] > '9') {
3116 				(void) printf(E_LINE);
3117 				(void) printf("Invalid percentage value "
3118 				    "specified; retry the operation.");
3119 				return (-1);
3120 			}
3121 			i++;
3122 			if (i > 3) {
3123 				(void) printf(E_LINE);
3124 				(void) printf("Invalid percentage value "
3125 				    "specified; retry the operation.");
3126 				return (-1);
3127 			}
3128 		}
3129 		if ((percent = atoi(s)) > 100) {
3130 			(void) printf(E_LINE);
3131 			(void) printf(
3132 			    "Percentage value is too large. The value must be"
3133 			    " between 1 and 100;\nretry the operation.\n");
3134 			return (-1);
3135 		}
3136 		if (percent < 1) {
3137 			(void) printf(E_LINE);
3138 			(void) printf(
3139 			    "Percentage value is too small. The value must be"
3140 			    " between 1 and 100;\nretry the operation.\n");
3141 			return (-1);
3142 		}
3143 
3144 		if (percent == 100)
3145 			cylen = Numcyl_usable - 1;
3146 		else
3147 			cylen = (Numcyl_usable * percent) / 100;
3148 
3149 		/* Verify DOS12 partition doesn't exceed max size of 32MB. */
3150 		if ((tsystid == DOSOS12) &&
3151 		    ((long)((long)cylen * cyl_size) > MAXDOS)) {
3152 			int n;
3153 			n = MAXDOS * 100 / (int)(cyl_size) / Numcyl_usable;
3154 			(void) printf(E_LINE);
3155 			(void) printf("Maximum size for a DOS partition "
3156 			    "is %d%%; retry the operation.",
3157 			    n <= 100 ? n : 100);
3158 			return (-1);
3159 		}
3160 
3161 
3162 		max_free = 0;
3163 		for (i = 0; i < FD_NUMPART; i++) {
3164 
3165 			/*
3166 			 * check for free space before partition i
3167 			 * where i varies from 0 to 3
3168 			 *
3169 			 * freespace after partition 3 is unusable
3170 			 * because there are no free partitions
3171 			 *
3172 			 * freespace begins at the end of previous partition
3173 			 * or cylinder 1
3174 			 */
3175 			if (i) {
3176 				/* Not an empty table */
3177 				first_free = LE_32(partition[i - 1]->relsect) +
3178 				    LE_32(partition[i - 1]->numsect);
3179 			} else {
3180 				first_free = cyl_size;
3181 			}
3182 
3183 			/*
3184 			 * freespace ends before the current partition
3185 			 * or the end of the disk (chs end)
3186 			 */
3187 			if (partition[i]->systid == UNUSED) {
3188 				size_free = chs_capacity - first_free;
3189 			} else {
3190 				/*
3191 				 * Partition might start before cylinder 1.
3192 				 * Make sure free space is not negative.
3193 				 */
3194 				size_free =
3195 				    (LE_32(partition[i]->relsect > first_free))
3196 				    ? (LE_32(partition[i]->relsect) -
3197 				    first_free) : 0;
3198 			}
3199 
3200 			/* save largest free space */
3201 			if (max_free < size_free)
3202 				max_free = size_free;
3203 
3204 			if (((uint64_t)cylen * cyl_size) <= size_free) {
3205 				/* We found a place to use */
3206 				break;
3207 			}
3208 			if (partition[i]->systid == UNUSED) {
3209 				(void) printf(E_LINE);
3210 				max_free /= (cyl_size);
3211 				(void) fprintf(stderr, "fdisk: "
3212 				    "Maximum percentage available is %lld\n",
3213 				    100 * max_free / Numcyl_usable);
3214 				return (-1);
3215 			}
3216 		}
3217 
3218 		(void) printf(E_LINE);
3219 		if (i >= FD_NUMPART) {
3220 			(void) fprintf(stderr,
3221 			    "fdisk: Partition table is full.\n");
3222 			return (-1);
3223 		}
3224 
3225 		if ((i = insert_tbl(tsystid, 0, 0, 0, 0, 0, 0, 0,
3226 		    first_free, cylen * cyl_size)) >= 0)  {
3227 			return (i);
3228 		}
3229 		return (-1);
3230 	} else {
3231 
3232 		/* Specifying size in cylinders */
3233 		(void) printf(E_LINE);
3234 		(void) printf(Q_LINE);
3235 		(void) printf("Enter starting cylinder number: ");
3236 		if ((cyl = getcyl()) == -1) {
3237 			(void) printf(E_LINE);
3238 			(void) printf("Invalid number; retry the operation.");
3239 			return (-1);
3240 		}
3241 		if (cyl == 0) {
3242 			(void) printf(E_LINE);
3243 			(void) printf(
3244 			    "New partition cannot start at cylinder 0.\n");
3245 			return (-1);
3246 		}
3247 
3248 
3249 		if (cyl >= Numcyl_usable) {
3250 			(void) printf(E_LINE);
3251 			(void) printf(
3252 			    "Cylinder %d is out of bounds, "
3253 			    "the maximum is %d.\n",
3254 			    cyl, Numcyl_usable - 1);
3255 			return (-1);
3256 		}
3257 
3258 		(void) printf(Q_LINE);
3259 		(void) printf("Enter partition size in cylinders: ");
3260 		if ((cylen = getcyl()) == -1) {
3261 			(void) printf(E_LINE);
3262 			(void) printf("Invalid number, retry the operation.");
3263 			return (-1);
3264 		}
3265 
3266 		for (i = 0; i < FD_NUMPART; i++) {
3267 			uint32_t	t_relsect, t_numsect;
3268 
3269 			if (partition[i]->systid == UNUSED)
3270 				break;
3271 			t_relsect = LE_32(partition[i]->relsect);
3272 			t_numsect = LE_32(partition[i]->numsect);
3273 
3274 			if (cyl * cyl_size >= t_relsect &&
3275 			    cyl * cyl_size < t_relsect + t_numsect) {
3276 				(void) printf(E_LINE);
3277 				(void) printf(
3278 				    "Cylinder %d is already allocated"
3279 				    "\nretry the operation.",
3280 				    cyl);
3281 				return (-1);
3282 			}
3283 
3284 			if (cyl * cyl_size < t_relsect &&
3285 			    (cyl + cylen - 1) * cyl_size > t_relsect) {
3286 				(void) printf(E_LINE);
3287 				(void) printf(
3288 				    "Maximum size for partition is %u cylinders"
3289 				    "\nretry the operation.",
3290 				    (t_relsect - cyl * cyl_size) / cyl_size);
3291 				return (-1);
3292 			}
3293 		}
3294 
3295 		/* Verify partition doesn't exceed disk size or 2 TB */
3296 		if (cyl + cylen > Numcyl_usable) {
3297 			(void) printf(E_LINE);
3298 			if (Numcyl > Numcyl_usable) {
3299 				(void) printf(
3300 				    "Maximum size for partition is %d "
3301 				    "cylinders; \nretry the operation.",
3302 				    Numcyl_usable - cyl);
3303 			} else {
3304 				(void) printf(
3305 				    "Maximum size for partition is %d "
3306 				    "cylinders; \nretry the operation.",
3307 				    Numcyl_usable - cyl);
3308 			}
3309 			return (-1);
3310 		}
3311 
3312 		/* Verify DOS12 partition doesn't exceed max size of 32MB. */
3313 		if ((tsystid == DOSOS12) &&
3314 		    ((long)((long)cylen * cyl_size) > MAXDOS)) {
3315 			(void) printf(E_LINE);
3316 			(void) printf(
3317 			    "Maximum size for a %s partition is %ld cylinders;"
3318 			    "\nretry the operation.",
3319 			    Dstr, MAXDOS / (int)(cyl_size));
3320 			return (-1);
3321 		}
3322 
3323 		(void) printf(E_LINE);
3324 		i = insert_tbl(tsystid, 0, 0, 0, 0, 0, 0, 0,
3325 		    cyl * cyl_size, cylen * cyl_size);
3326 		if (i < 0)
3327 			return (-1);
3328 
3329 		if (verify_tbl() < 0) {
3330 			(void) printf(E_LINE);
3331 			(void) printf("fdisk: Cannot create partition table\n");
3332 			return (-1);
3333 		}
3334 
3335 		return (i);
3336 	}
3337 }
3338 
3339 /*
3340  * dispmenu
3341  * Display command menu (interactive mode).
3342  */
3343 static void
3344 dispmenu(void)
3345 {
3346 	(void) printf(M_LINE);
3347 #ifdef i386
3348 	(void) printf(
3349 	    "SELECT ONE OF THE FOLLOWING:\n"
3350 	    "   1. Create a partition\n"
3351 	    "   2. Specify the active partition\n"
3352 	    "   3. Delete a partition\n"
3353 	    "   4. Change between Solaris and Solaris2 Partition IDs\n"
3354 	    "   5. Edit/View extended partitions\n"
3355 	    "   6. Exit (update disk configuration and exit)\n"
3356 	    "   7. Cancel (exit without updating disk configuration)\n");
3357 #else
3358 	(void) printf(
3359 	    "SELECT ONE OF THE FOLLOWING:\n"
3360 	    "   1. Create a partition\n"
3361 	    "   2. Specify the active partition\n"
3362 	    "   3. Delete a partition\n"
3363 	    "   4. Change between Solaris and Solaris2 Partition IDs\n"
3364 	    "   5. Exit (update disk configuration and exit)\n"
3365 	    "   6. Cancel (exit without updating disk configuration)\n");
3366 #endif
3367 }
3368 
3369 /*
3370  * pchange
3371  * Change the ACTIVE designation of a partition.
3372  */
3373 static int
3374 pchange(void)
3375 {
3376 	char s[80];
3377 	int i, j;
3378 
3379 	for (;;) {
3380 		(void) printf(Q_LINE);
3381 			{
3382 			(void) printf(
3383 			    "Specify the partition number to boot from"
3384 			    " (or specify 0 for none): ");
3385 			}
3386 		(void) fgets(s, sizeof (s), stdin);
3387 		rm_blanks(s);
3388 		if (((s[1] != '\0') && (s[1] != '\n')) ||
3389 		    (s[0] < '0') || (s[0] > '4')) {
3390 			(void) printf(E_LINE);
3391 			(void) printf(
3392 			    "Invalid response, please specify a number"
3393 			    " between 0 and 4.\n");
3394 		} else {
3395 			break;
3396 		}
3397 	}
3398 	if (s[0] == '0') {	/* No active partitions */
3399 		for (i = 0; i < FD_NUMPART; i++) {
3400 			if (Table[i].systid != UNUSED &&
3401 			    Table[i].bootid == ACTIVE)
3402 				Table[i].bootid = 0;
3403 		}
3404 		(void) printf(E_LINE);
3405 			(void) printf(
3406 			    "No partition is currently marked as active.");
3407 		return (0);
3408 	} else {	/* User has selected a partition to be active */
3409 		i = s[0] - '1';
3410 		if (Table[i].systid == UNUSED) {
3411 			(void) printf(E_LINE);
3412 			(void) printf("Partition does not exist.");
3413 			return (-1);
3414 		}
3415 		/* a DOS-DATA or EXT-DOS partition cannot be active */
3416 		else if ((Table[i].systid == DOSDATA) ||
3417 		    (Table[i].systid == EXTDOS) ||
3418 		    (Table[i].systid == FDISK_EXTLBA)) {
3419 			(void) printf(E_LINE);
3420 			(void) printf(
3421 			    "DOS-DATA, EXT_DOS and EXT_DOS_LBA partitions "
3422 			    "cannot be made active.\n");
3423 			(void) printf("Select another partition.");
3424 			return (-1);
3425 		}
3426 		Table[i].bootid = ACTIVE;
3427 		for (j = 0; j < FD_NUMPART; j++) {
3428 			if (j != i)
3429 			Table[j].bootid = 0;
3430 		}
3431 	}
3432 	(void) printf(E_LINE);
3433 		{
3434 		(void) printf(
3435 		    "Partition %d is now active. The system will start up"
3436 		    " from this\n", i + 1);
3437 		(void) printf("partition after the next reboot.");
3438 		}
3439 	return (1);
3440 }
3441 
3442 /*
3443  * Change between SOLARIS and SOLARIS2 partition id
3444  */
3445 static int
3446 ppartid(void)
3447 {
3448 	char	*p, s[80];
3449 	int	i;
3450 
3451 	for (;;) {
3452 		(void) printf(Q_LINE);
3453 		(void) printf("Specify the partition number to change"
3454 		    " (or enter 0 to exit): ");
3455 		if (!fgets(s, sizeof (s), stdin))
3456 			return (1);
3457 		i = strtol(s, &p, 10);
3458 
3459 		if (*p != '\n' || i < 0 || i > FD_NUMPART) {
3460 			(void) printf(E_LINE);
3461 			(void) printf(
3462 			    "Invalid response, retry the operation.\n");
3463 			continue;
3464 		}
3465 
3466 		if (i == 0) {
3467 			/* exit delete command */
3468 			(void) printf(E_LINE); /* clear error message */
3469 			return (1);
3470 		}
3471 
3472 		i -= 1;
3473 		if (Table[i].systid == SUNIXOS) {
3474 			Table[i].systid = SUNIXOS2;
3475 		} else if (Table[i].systid == SUNIXOS2) {
3476 			Table[i].systid = SUNIXOS;
3477 		} else {
3478 			(void) printf(E_LINE);
3479 			(void) printf(
3480 			    "Partition %d is not a Solaris partition.",
3481 			    i + 1);
3482 			continue;
3483 		}
3484 
3485 		(void) printf(E_LINE);
3486 		(void) printf("Partition %d has been changed.", i + 1);
3487 		return (1);
3488 	}
3489 }
3490 
3491 /*
3492  * pdelete
3493  * Remove partition entry from the table (interactive mode).
3494  */
3495 static char
3496 pdelete(void)
3497 {
3498 	char s[80];
3499 	int i, j;
3500 	char pactive;
3501 
3502 DEL1:	(void) printf(Q_LINE);
3503 	(void) printf("Specify the partition number to delete"
3504 	    " (or enter 0 to exit): ");
3505 	(void) fgets(s, sizeof (s), stdin);
3506 	rm_blanks(s);
3507 	if ((s[0] == '0')) {	/* exit delete command */
3508 		(void) printf(E_LINE);	/* clear error message */
3509 		return (1);
3510 	}
3511 	/* Accept only a single digit between 1 and 4 */
3512 	if (((s[1] != '\0') && (s[1] != '\n')) ||
3513 	    (i = atoi(s)) < 1 || i > FD_NUMPART) {
3514 		(void) printf(E_LINE);
3515 		(void) printf("Invalid response, retry the operation.\n");
3516 		goto DEL1;
3517 	} else {		/* Found a digit between 1 and 4 */
3518 		--i;	/* Structure begins with element 0 */
3519 	}
3520 
3521 	if (Table[i].systid == UNUSED) {
3522 		(void) printf(E_LINE);
3523 		(void) printf("Partition %d does not exist.", i + 1);
3524 		return (-1);
3525 	}
3526 
3527 #ifdef i386
3528 	if (fdisk_is_dos_extended(Table[i].systid) &&
3529 	    (Table[i].relsect == fdisk_get_ext_beg_sec(epp)) &&
3530 	    fdisk_get_logical_drive_count(epp)) {
3531 		(void) printf(Q_LINE);
3532 		(void) printf("There are logical drives inside the"
3533 		    " extended partition\n");
3534 		(void) printf("Are you sure of proceeding with deletion ?"
3535 		    " (type \"y\" or \"n\") ");
3536 
3537 		(void) printf(E_LINE);
3538 		if (! yesno()) {
3539 			return (1);
3540 		}
3541 		if (fdisk_mounted_logical_drives(epp) == FDISK_EMOUNTED) {
3542 			(void) printf(Q_LINE);
3543 			(void) printf("There are mounted logical drives. "
3544 			    "Committing changes now can cause data loss or "
3545 			    "corruption. Unmount all logical drives and then "
3546 			    "try committing the changes again.\n");
3547 			(void) printf("Press enter to continue.\n");
3548 			ext_read_input(s);
3549 			return (1);
3550 		}
3551 		fdisk_delete_ext_part(epp);
3552 	} else {
3553 #endif
3554 		(void) printf(Q_LINE);
3555 		(void) printf("Are you sure you want to delete partition %d?"
3556 		    " This will make all files and \n", i + 1);
3557 		(void) printf("programs in this partition inaccessible (type"
3558 		    " \"y\" or \"n\"). ");
3559 
3560 		(void) printf(E_LINE);
3561 		if (! yesno()) {
3562 			return (1);
3563 		}
3564 #ifdef i386
3565 	}
3566 #endif
3567 
3568 	if (Table[i].bootid == ACTIVE) {
3569 		pactive = 1;
3570 	} else {
3571 		pactive = 0;
3572 	}
3573 
3574 	for (j = i; j < FD_NUMPART - 1; j++) {
3575 		Table[j] = Table[j + 1];
3576 	}
3577 
3578 	Table[j].systid = UNUSED;
3579 	Table[j].numsect = 0;
3580 	Table[j].relsect = 0;
3581 	Table[j].bootid = 0;
3582 	(void) printf(E_LINE);
3583 	(void) printf("Partition %d has been deleted.", i + 1);
3584 
3585 	if (pactive) {
3586 		(void) printf(" This was the active partition.");
3587 	}
3588 
3589 	return (1);
3590 }
3591 
3592 /*
3593  * rm_blanks
3594  * Remove blanks from strings of user responses.
3595  */
3596 static void
3597 rm_blanks(char *s)
3598 {
3599 	register int i, j;
3600 
3601 	for (i = 0; i < CBUFLEN; i++) {
3602 		if ((s[i] == ' ') || (s[i] == '\t'))
3603 			continue;
3604 		else
3605 			/* Found first non-blank character of the string */
3606 			break;
3607 	}
3608 	for (j = 0; i < CBUFLEN; j++, i++) {
3609 		if ((s[j] = s[i]) == '\0') {
3610 			/* Reached end of string */
3611 			return;
3612 		}
3613 	}
3614 }
3615 
3616 /*
3617  * getcyl
3618  * Take the user-specified cylinder number and convert it from a
3619  * string to a decimal value.
3620  */
3621 static int
3622 getcyl(void)
3623 {
3624 int slen, i, j;
3625 unsigned int cyl;
3626 	(void) fgets(s, sizeof (s), stdin);
3627 	rm_blanks(s);
3628 	slen = strlen(s);
3629 	if (s[slen - 1] == '\n')
3630 		slen--;
3631 	j = 1;
3632 	cyl = 0;
3633 	for (i = slen - 1; i >= 0; i--) {
3634 		if (s[i] < '0' || s[i] > '9') {
3635 			return (-1);
3636 		}
3637 		cyl += (j * (s[i] - '0'));
3638 		j *= 10;
3639 	}
3640 	return (cyl);
3641 }
3642 
3643 /*
3644  * disptbl
3645  * Display the current fdisk table; determine percentage
3646  * of the disk used for each partition.
3647  */
3648 static void
3649 disptbl(void)
3650 {
3651 	int i;
3652 	unsigned int startcyl, endcyl, length, percent, remainder;
3653 	char *stat, *type;
3654 	int is_pmbr = 0;
3655 
3656 	if ((heads == 0) || (sectors == 0)) {
3657 		(void) printf("WARNING: critical disk geometry information"
3658 		    " missing!\n");
3659 		(void) printf("\theads = %d, sectors = %d\n", heads, sectors);
3660 		exit(1);
3661 	}
3662 
3663 	(void) printf(HOME);
3664 	(void) printf(T_LINE);
3665 	(void) printf("             Total disk size is %d cylinders\n", Numcyl);
3666 	(void) printf("             Cylinder size is %d (%d byte) blocks\n\n",
3667 	    heads * sectors, sectsiz);
3668 	(void) printf(
3669 	    "                                               Cylinders\n");
3670 	(void) printf(
3671 	    "      Partition   Status    Type          Start   End   Length"
3672 	    "    %%\n");
3673 	(void) printf(
3674 	    "      =========   ======    ============  =====   ===   ======"
3675 	    "   ===");
3676 	for (i = 0; i < FD_NUMPART; i++) {
3677 		if (Table[i].systid == UNUSED) {
3678 			(void) printf("\n");
3679 			(void) printf(CLR_LIN);
3680 			continue;
3681 		}
3682 		if (Table[i].bootid == ACTIVE)
3683 			stat = Actvstr;
3684 		else
3685 			stat = NAstr;
3686 		switch (Table[i].systid) {
3687 		case UNIXOS:
3688 			type = Ustr;
3689 			break;
3690 		case SUNIXOS:
3691 			type = SUstr;
3692 #ifdef i386
3693 			if (fdisk_is_linux_swap(epp, Table[i].relsect,
3694 			    NULL) == 0)
3695 				type = LINSWAPstr;
3696 #endif
3697 			break;
3698 		case SUNIXOS2:
3699 			type = SU2str;
3700 			break;
3701 		case X86BOOT:
3702 			type = X86str;
3703 			break;
3704 		case DOSOS12:
3705 			type = Dstr;
3706 			break;
3707 		case DOSOS16:
3708 			type = D16str;
3709 			break;
3710 		case EXTDOS:
3711 			type = EDstr;
3712 			break;
3713 		case DOSDATA:
3714 			type = DDstr;
3715 			break;
3716 		case DOSHUGE:
3717 			type = DBstr;
3718 			break;
3719 		case PCIXOS:
3720 			type = PCstr;
3721 			break;
3722 		case DIAGPART:
3723 			type = DIAGstr;
3724 			break;
3725 		case FDISK_IFS:
3726 			type = IFSstr;
3727 			break;
3728 		case FDISK_AIXBOOT:
3729 			type = AIXstr;
3730 			break;
3731 		case FDISK_AIXDATA:
3732 			type = AIXDstr;
3733 			break;
3734 		case FDISK_OS2BOOT:
3735 			type = OS2str;
3736 			break;
3737 		case FDISK_WINDOWS:
3738 			type = WINstr;
3739 			break;
3740 		case FDISK_EXT_WIN:
3741 			type = EWINstr;
3742 			break;
3743 		case FDISK_FAT95:
3744 			type = FAT95str;
3745 			break;
3746 		case FDISK_EXTLBA:
3747 			type = EXTLstr;
3748 			break;
3749 		case FDISK_LINUX:
3750 			type = LINUXstr;
3751 			break;
3752 		case FDISK_CPM:
3753 			type = CPMstr;
3754 			break;
3755 		case FDISK_NOVELL2:
3756 			type = NOV2str;
3757 			break;
3758 		case FDISK_NOVELL3:
3759 			type = NOVstr;
3760 			break;
3761 		case FDISK_QNX4:
3762 			type = QNXstr;
3763 			break;
3764 		case FDISK_QNX42:
3765 			type = QNX2str;
3766 			break;
3767 		case FDISK_QNX43:
3768 			type = QNX3str;
3769 			break;
3770 		case FDISK_LINUXNAT:
3771 			type = LINNATstr;
3772 			break;
3773 		case FDISK_NTFSVOL1:
3774 			type = NTFSVOL1str;
3775 			break;
3776 		case FDISK_NTFSVOL2:
3777 			type = NTFSVOL2str;
3778 			break;
3779 		case FDISK_BSD:
3780 			type = BSDstr;
3781 			break;
3782 		case FDISK_NEXTSTEP:
3783 			type = NEXTSTEPstr;
3784 			break;
3785 		case FDISK_BSDIFS:
3786 			type = BSDIFSstr;
3787 			break;
3788 		case FDISK_BSDISWAP:
3789 			type = BSDISWAPstr;
3790 			break;
3791 		case EFI_PMBR:
3792 			type = EFIstr;
3793 			if (LE_32(Table[i].numsect) == DK_MAX_2TB)
3794 				is_pmbr = 1;
3795 
3796 			break;
3797 		default:
3798 			type = Ostr;
3799 			break;
3800 		}
3801 		startcyl = LE_32(Table[i].relsect) /
3802 		    (unsigned long)(heads * sectors);
3803 
3804 		if (LE_32(Table[i].numsect) == DK_MAX_2TB) {
3805 			endcyl = Numcyl - 1;
3806 			length = endcyl - startcyl + 1;
3807 		} else {
3808 			length = LE_32(Table[i].numsect) /
3809 			    (unsigned long)(heads * sectors);
3810 			if (LE_32(Table[i].numsect) %
3811 			    (unsigned long)(heads * sectors))
3812 				length++;
3813 			endcyl = startcyl + length - 1;
3814 		}
3815 
3816 		percent = length * 100 / Numcyl_usable;
3817 		if ((remainder = (length * 100 % Numcyl_usable)) != 0) {
3818 			if ((remainder * 100 / Numcyl_usable) > 50) {
3819 				/* round up */
3820 				percent++;
3821 			}
3822 			/* Else leave the percent as is since it's already */
3823 			/* rounded down */
3824 		}
3825 		if (percent > 100)
3826 			percent = 100;
3827 		(void) printf(
3828 		    "\n          %d       %s    %-12.12s   %4d  %4d    %4d"
3829 		    "    %3d",
3830 		    i + 1, stat, type, startcyl, endcyl, length, percent);
3831 	}
3832 
3833 	/* Print warning message if table is empty */
3834 	if (Table[0].systid == UNUSED) {
3835 		(void) printf(W_LINE);
3836 		(void) printf("WARNING: no partitions are defined!");
3837 	} else {
3838 		/* Clear the warning line */
3839 		(void) printf(W_LINE);
3840 
3841 		/* Print warning if disk > 2TB and is not EFI PMBR */
3842 		if (!is_pmbr && (dev_capacity > DK_MAX_2TB))
3843 			(void) printf("WARNING: Disk is larger than 2 TB. "
3844 			    "Upper limit is 2 TB for non-EFI partition ID\n");
3845 	}
3846 }
3847 
3848 /*
3849  * print_Table
3850  * Write the detailed fdisk table to standard error for
3851  * the selected disk device.
3852  */
3853 static void
3854 print_Table(void)
3855 {
3856 	int i;
3857 
3858 	(void) fprintf(stderr,
3859 	    "  SYSID ACT BHEAD BSECT BEGCYL   EHEAD ESECT ENDCYL   RELSECT"
3860 	    "   NUMSECT\n");
3861 
3862 	for (i = 0; i < FD_NUMPART; i++) {
3863 		(void) fprintf(stderr, "  %-5d ", Table[i].systid);
3864 		(void) fprintf(stderr, "%-3d ", Table[i].bootid);
3865 		(void) fprintf(stderr, "%-5d ", Table[i].beghead);
3866 		(void) fprintf(stderr, "%-5d ", Table[i].begsect & 0x3f);
3867 		(void) fprintf(stderr, "%-8d ",
3868 		    (((uint_t)Table[i].begsect & 0xc0) << 2) + Table[i].begcyl);
3869 
3870 		(void) fprintf(stderr, "%-5d ", Table[i].endhead);
3871 		(void) fprintf(stderr, "%-5d ", Table[i].endsect & 0x3f);
3872 		(void) fprintf(stderr, "%-8d ",
3873 		    (((uint_t)Table[i].endsect & 0xc0) << 2) + Table[i].endcyl);
3874 		(void) fprintf(stderr, "%-10u ", LE_32(Table[i].relsect));
3875 		(void) fprintf(stderr, "%-10u\n", LE_32(Table[i].numsect));
3876 
3877 	}
3878 }
3879 
3880 /*
3881  * copy_Table_to_Old_Table
3882  * Copy Table into Old_Table. The function only copies the systid,
3883  * numsect, relsect, and bootid values because they are the only
3884  * ones compared when determining if Table has changed.
3885  */
3886 static void
3887 copy_Table_to_Old_Table(void)
3888 {
3889 	int i;
3890 	for (i = 0; i < FD_NUMPART; i++)  {
3891 		(void) memcpy(&Old_Table[i], &Table[i], sizeof (Table[0]));
3892 	}
3893 }
3894 
3895 /*
3896  * nulltbl
3897  * Zero out the systid, numsect, relsect, and bootid values in the
3898  * fdisk table.
3899  */
3900 static void
3901 nulltbl(void)
3902 {
3903 	int i;
3904 
3905 	for (i = 0; i < FD_NUMPART; i++)  {
3906 		Table[i].systid = UNUSED;
3907 		Table[i].numsect = LE_32(UNUSED);
3908 		Table[i].relsect = LE_32(UNUSED);
3909 		Table[i].bootid = 0;
3910 		skip_verify[i] = 0;
3911 	}
3912 }
3913 
3914 /*
3915  * copy_Bootblk_to_Table
3916  * Copy the bytes from the boot record to an internal "Table".
3917  * All unused are padded with zeros starting at offset 446.
3918  */
3919 static void
3920 copy_Bootblk_to_Table(void)
3921 {
3922 	int i, j;
3923 	char *bootptr;
3924 	struct ipart iparts[FD_NUMPART];
3925 
3926 	/* Get an aligned copy of the partition tables */
3927 	(void) memcpy(iparts, Bootblk->parts, sizeof (iparts));
3928 	bootptr = (char *)iparts;	/* Points to start of partition table */
3929 	if (LE_16(Bootblk->signature) != MBB_MAGIC)  {
3930 		/* Signature is missing */
3931 		nulltbl();
3932 		(void) memcpy(Bootblk->bootinst, &BootCod, BOOTSZ);
3933 		return;
3934 	}
3935 	/*
3936 	 * When the DOS fdisk command deletes a partition, it is not
3937 	 * recognized by the old algorithm.  The algorithm that
3938 	 * follows looks at each entry in the Bootrec and copies all
3939 	 * those that are valid.
3940 	 */
3941 	j = 0;
3942 	for (i = 0; i < FD_NUMPART; i++) {
3943 		if (iparts[i].systid == 0) {
3944 			/* Null entry */
3945 			bootptr += sizeof (struct ipart);
3946 		} else {
3947 			fill_ipart(bootptr, &Table[j]);
3948 			j++;
3949 			bootptr += sizeof (struct ipart);
3950 		}
3951 	}
3952 	for (i = j; i < FD_NUMPART; i++) {
3953 		Table[i].systid = UNUSED;
3954 		Table[i].numsect = LE_32(UNUSED);
3955 		Table[i].relsect = LE_32(UNUSED);
3956 		Table[i].bootid = 0;
3957 
3958 	}
3959 	/* For now, always replace the bootcode with ours */
3960 	(void) memcpy(Bootblk->bootinst, &BootCod, BOOTSZ);
3961 	copy_Table_to_Bootblk();
3962 }
3963 
3964 /*
3965  * fill_ipart
3966  * Initialize ipart structure values.
3967  */
3968 static void
3969 fill_ipart(char *bootptr, struct ipart *partp)
3970 {
3971 #ifdef sparc
3972 	/* Packing struct ipart for Sparc */
3973 	partp->bootid	= getbyte(&bootptr);
3974 	partp->beghead	= getbyte(&bootptr);
3975 	partp->begsect	= getbyte(&bootptr);
3976 	partp->begcyl	= getbyte(&bootptr);
3977 	partp->systid	= getbyte(&bootptr);
3978 	partp->endhead	= getbyte(&bootptr);
3979 	partp->endsect	= getbyte(&bootptr);
3980 	partp->endcyl	= getbyte(&bootptr);
3981 	partp->relsect	= (int32_t)getlong(&bootptr);
3982 	partp->numsect	= (int32_t)getlong(&bootptr);
3983 #else
3984 	*partp = *(struct ipart *)bootptr;
3985 #endif
3986 }
3987 
3988 /*
3989  * getbyte, getlong
3990  * 	Get a byte, a short, or a long (SPARC only).
3991  */
3992 #ifdef sparc
3993 uchar_t
3994 getbyte(char **bp)
3995 {
3996 	uchar_t	b;
3997 
3998 	b = (uchar_t)**bp;
3999 	*bp = *bp + 1;
4000 	return (b);
4001 }
4002 
4003 uint32_t
4004 getlong(char **bp)
4005 {
4006 	int32_t	b, bh, bl;
4007 
4008 	bh = ((**bp) << 8) | *(*bp + 1);
4009 	*bp += 2;
4010 	bl = ((**bp) << 8) | *(*bp + 1);
4011 	*bp += 2;
4012 
4013 	b = (bh << 16) | bl;
4014 	return ((uint32_t)b);
4015 }
4016 #endif
4017 
4018 /*
4019  * copy_Table_to_Bootblk
4020  * Copy the table into the boot record. Note that the unused
4021  * entries will always be the last ones in the table and they are
4022  * marked with 100 in sysind. The the unused portion of the table
4023  * is padded with zeros in the bytes after the used entries.
4024  */
4025 static void
4026 copy_Table_to_Bootblk(void)
4027 {
4028 	struct ipart *boot_ptr, *tbl_ptr;
4029 
4030 	boot_ptr = (struct ipart *)Bootblk->parts;
4031 	tbl_ptr = (struct ipart *)&Table[0].bootid;
4032 	for (; tbl_ptr < (struct ipart *)&Table[FD_NUMPART].bootid;
4033 	    tbl_ptr++, boot_ptr++) {
4034 		if (tbl_ptr->systid == UNUSED)
4035 			(void) memset(boot_ptr, 0, sizeof (struct ipart));
4036 		else
4037 			(void) memcpy(boot_ptr, tbl_ptr, sizeof (struct ipart));
4038 	}
4039 	Bootblk->signature = LE_16(MBB_MAGIC);
4040 }
4041 
4042 /*
4043  * TableChanged
4044  * 	Check for any changes in the partition table.
4045  */
4046 static int
4047 TableChanged(void)
4048 {
4049 	int i, changed;
4050 
4051 	changed = 0;
4052 	for (i = 0; i < FD_NUMPART; i++) {
4053 		if (memcmp(&Old_Table[i], &Table[i], sizeof (Table[0])) != 0) {
4054 			/* Partition table changed, write back to disk */
4055 			changed = 1;
4056 		}
4057 	}
4058 
4059 	return (changed);
4060 }
4061 
4062 /*
4063  * ffile_write
4064  * 	Display contents of partition table to standard output or
4065  *	another file name without writing it to the disk (-W file).
4066  */
4067 static void
4068 ffile_write(char *file)
4069 {
4070 	register int	i;
4071 	FILE *fp;
4072 
4073 	/*
4074 	 * If file isn't standard output, then it's a file name.
4075 	 * Open file and write it.
4076 	 */
4077 	if (file != (char *)stdout) {
4078 		if ((fp = fopen(file, "w")) == NULL) {
4079 			(void) fprintf(stderr,
4080 			    "fdisk: Cannot open output file %s.\n",
4081 			    file);
4082 			exit(1);
4083 		}
4084 	}
4085 	else
4086 		fp = stdout;
4087 
4088 	/*
4089 	 * Write the fdisk table information
4090 	 */
4091 	(void) fprintf(fp, "\n* %s default fdisk table\n", Dfltdev);
4092 	(void) fprintf(fp, "* Dimensions:\n");
4093 	(void) fprintf(fp, "*   %4d bytes/sector\n", sectsiz);
4094 	(void) fprintf(fp, "*   %4d sectors/track\n", sectors);
4095 	(void) fprintf(fp, "*   %4d tracks/cylinder\n", heads);
4096 	(void) fprintf(fp, "*   %4d cylinders\n", Numcyl);
4097 	(void) fprintf(fp, "*\n");
4098 	/* Write virtual (HBA) geometry, if required	*/
4099 	if (v_flag) {
4100 		(void) fprintf(fp, "* HBA Dimensions:\n");
4101 		(void) fprintf(fp, "*   %4d bytes/sector\n", sectsiz);
4102 		(void) fprintf(fp, "*   %4d sectors/track\n", hba_sectors);
4103 		(void) fprintf(fp, "*   %4d tracks/cylinder\n", hba_heads);
4104 		(void) fprintf(fp, "*   %4d cylinders\n", hba_Numcyl);
4105 		(void) fprintf(fp, "*\n");
4106 	}
4107 	(void) fprintf(fp, "* systid:\n");
4108 	(void) fprintf(fp, "*    1: DOSOS12\n");
4109 	(void) fprintf(fp, "*    2: PCIXOS\n");
4110 	(void) fprintf(fp, "*    4: DOSOS16\n");
4111 	(void) fprintf(fp, "*    5: EXTDOS\n");
4112 	(void) fprintf(fp, "*    6: DOSBIG\n");
4113 	(void) fprintf(fp, "*    7: FDISK_IFS\n");
4114 	(void) fprintf(fp, "*    8: FDISK_AIXBOOT\n");
4115 	(void) fprintf(fp, "*    9: FDISK_AIXDATA\n");
4116 	(void) fprintf(fp, "*   10: FDISK_0S2BOOT\n");
4117 	(void) fprintf(fp, "*   11: FDISK_WINDOWS\n");
4118 	(void) fprintf(fp, "*   12: FDISK_EXT_WIN\n");
4119 	(void) fprintf(fp, "*   14: FDISK_FAT95\n");
4120 	(void) fprintf(fp, "*   15: FDISK_EXTLBA\n");
4121 	(void) fprintf(fp, "*   18: DIAGPART\n");
4122 	(void) fprintf(fp, "*   65: FDISK_LINUX\n");
4123 	(void) fprintf(fp, "*   82: FDISK_CPM\n");
4124 	(void) fprintf(fp, "*   86: DOSDATA\n");
4125 	(void) fprintf(fp, "*   98: OTHEROS\n");
4126 	(void) fprintf(fp, "*   99: UNIXOS\n");
4127 	(void) fprintf(fp, "*  100: FDISK_NOVELL2\n");
4128 	(void) fprintf(fp, "*  101: FDISK_NOVELL3\n");
4129 	(void) fprintf(fp, "*  119: FDISK_QNX4\n");
4130 	(void) fprintf(fp, "*  120: FDISK_QNX42\n");
4131 	(void) fprintf(fp, "*  121: FDISK_QNX43\n");
4132 	(void) fprintf(fp, "*  130: SUNIXOS\n");
4133 	(void) fprintf(fp, "*  131: FDISK_LINUXNAT\n");
4134 	(void) fprintf(fp, "*  134: FDISK_NTFSVOL1\n");
4135 	(void) fprintf(fp, "*  135: FDISK_NTFSVOL2\n");
4136 	(void) fprintf(fp, "*  165: FDISK_BSD\n");
4137 	(void) fprintf(fp, "*  167: FDISK_NEXTSTEP\n");
4138 	(void) fprintf(fp, "*  183: FDISK_BSDIFS\n");
4139 	(void) fprintf(fp, "*  184: FDISK_BSDISWAP\n");
4140 	(void) fprintf(fp, "*  190: X86BOOT\n");
4141 	(void) fprintf(fp, "*  191: SUNIXOS2\n");
4142 	(void) fprintf(fp, "*  238: EFI_PMBR\n");
4143 	(void) fprintf(fp, "*  239: EFI_FS\n");
4144 	(void) fprintf(fp, "*\n");
4145 	(void) fprintf(fp,
4146 	    "\n* Id    Act  Bhead  Bsect  Bcyl    Ehead  Esect  Ecyl"
4147 	    "    Rsect      Numsect\n");
4148 
4149 	for (i = 0; i < FD_NUMPART; i++) {
4150 		(void) fprintf(fp,
4151 		    "  %-5d %-4d %-6d %-6d %-7d %-6d %-6d %-7d %-10u"
4152 		    " %-10u\n",
4153 		    Table[i].systid,
4154 		    Table[i].bootid,
4155 		    Table[i].beghead,
4156 		    Table[i].begsect & 0x3f,
4157 		    ((Table[i].begcyl & 0xff) | ((Table[i].begsect &
4158 		    0xc0) << 2)),
4159 		    Table[i].endhead,
4160 		    Table[i].endsect & 0x3f,
4161 		    ((Table[i].endcyl & 0xff) | ((Table[i].endsect &
4162 		    0xc0) << 2)),
4163 		    LE_32(Table[i].relsect),
4164 		    LE_32(Table[i].numsect));
4165 	}
4166 #ifdef i386
4167 	if (fdisk_ext_part_exists(epp)) {
4168 		struct ipart ext_tab;
4169 		logical_drive_t *temp;
4170 		uint32_t rsect, numsect, tempsect = 0;
4171 		for (temp = fdisk_get_ld_head(epp); temp != NULL;
4172 		    temp = temp->next) {
4173 			ext_tab = temp->parts[0];
4174 			rsect = tempsect + LE_32(ext_tab.relsect) +
4175 			    fdisk_get_ext_beg_sec(epp);
4176 			numsect = LE_32(ext_tab.numsect);
4177 			tempsect = LE_32(temp->parts[1].relsect);
4178 			(void) fprintf(fp,
4179 			    "  %-5d %-4d %-6d %-6d %-7d %-6d %-6d "
4180 			    "%-7d %-8u %-8u\n",
4181 			    ext_tab.systid,
4182 			    ext_tab.bootid,
4183 			    ext_tab.beghead,
4184 			    ext_tab.begsect & 0x3f,
4185 			    ((ext_tab.begcyl & 0xff) |
4186 			    ((ext_tab.begsect & 0xc0) << 2)),
4187 			    ext_tab.endhead,
4188 			    ext_tab.endsect & 0x3f,
4189 			    ((ext_tab.endcyl & 0xff) |
4190 			    ((ext_tab.endsect & 0xc0) << 2)),
4191 			    rsect,
4192 			    numsect);
4193 		}
4194 	}
4195 #endif
4196 
4197 	if (fp != stdout)
4198 		(void) fclose(fp);
4199 }
4200 
4201 /*
4202  * fix_slice
4203  * 	Read the VTOC table on the Solaris partition and check that no
4204  *	slices exist that extend past the end of the Solaris partition.
4205  *	If no Solaris partition exists, nothing is done.
4206  */
4207 static void
4208 fix_slice(void)
4209 {
4210 	int	i;
4211 	uint32_t	numsect;
4212 
4213 	if (io_image) {
4214 		return;
4215 	}
4216 
4217 	for (i = 0; i < FD_NUMPART; i++) {
4218 		if (Table[i].systid == SUNIXOS || Table[i].systid == SUNIXOS2) {
4219 			/*
4220 			 * Only the size matters (not starting point), since
4221 			 * VTOC entries are relative to the start of
4222 			 * the partition.
4223 			 */
4224 			numsect = LE_32(Table[i].numsect);
4225 			break;
4226 		}
4227 	}
4228 
4229 	if (i >= FD_NUMPART) {
4230 		if (!io_nifdisk) {
4231 			(void) fprintf(stderr,
4232 			    "fdisk: No Solaris partition found - VTOC not"
4233 			    " checked.\n");
4234 		}
4235 		return;
4236 	}
4237 
4238 	if (readvtoc() != VTOC_OK) {
4239 		exit(1);		/* Failed to read the VTOC */
4240 	}
4241 	for (i = 0; i < V_NUMPAR; i++) {
4242 		/* Special case for slice two (entire disk) */
4243 		if (i == 2) {
4244 			if (disk_vtoc.v_part[i].p_start != 0) {
4245 				(void) fprintf(stderr,
4246 				    "slice %d starts at %llu, is not at"
4247 				    " start of partition",
4248 				    i, disk_vtoc.v_part[i].p_start);
4249 				if (!io_nifdisk) {
4250 					(void) printf(" adjust ?:");
4251 					if (yesno())
4252 						disk_vtoc.v_part[i].p_start = 0;
4253 				} else {
4254 					disk_vtoc.v_part[i].p_start = 0;
4255 					(void) fprintf(stderr, " adjusted!\n");
4256 				}
4257 
4258 			}
4259 			if (disk_vtoc.v_part[i].p_size != numsect) {
4260 				(void) fprintf(stderr,
4261 				    "slice %d size %llu does not cover"
4262 				    " complete partition",
4263 				    i, disk_vtoc.v_part[i].p_size);
4264 				if (!io_nifdisk) {
4265 					(void) printf(" adjust ?:");
4266 					if (yesno())
4267 						disk_vtoc.v_part[i].p_size =
4268 						    numsect;
4269 				} else {
4270 					disk_vtoc.v_part[i].p_size = numsect;
4271 					(void) fprintf(stderr, " adjusted!\n");
4272 				}
4273 			}
4274 			if (disk_vtoc.v_part[i].p_tag != V_BACKUP) {
4275 				(void) fprintf(stderr,
4276 				    "slice %d tag was %d should be %d",
4277 				    i, disk_vtoc.v_part[i].p_tag,
4278 				    V_BACKUP);
4279 				if (!io_nifdisk) {
4280 					(void) printf(" fix ?:");
4281 					if (yesno())
4282 						disk_vtoc.v_part[i].p_tag =
4283 						    V_BACKUP;
4284 				} else {
4285 					disk_vtoc.v_part[i].p_tag = V_BACKUP;
4286 					(void) fprintf(stderr, " fixed!\n");
4287 				}
4288 			}
4289 			continue;
4290 		}
4291 		if (io_ADJT) {
4292 			if (disk_vtoc.v_part[i].p_start > numsect ||
4293 			    disk_vtoc.v_part[i].p_start +
4294 			    disk_vtoc.v_part[i].p_size > numsect) {
4295 				(void) fprintf(stderr,
4296 				    "slice %d (start %llu, end %llu)"
4297 				    " is larger than the partition",
4298 				    i, disk_vtoc.v_part[i].p_start,
4299 				    disk_vtoc.v_part[i].p_start +
4300 				    disk_vtoc.v_part[i].p_size);
4301 				if (!io_nifdisk) {
4302 					(void) printf(" remove ?:");
4303 					if (yesno()) {
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 					}
4309 				} else {
4310 					disk_vtoc.v_part[i].p_size = 0;
4311 					disk_vtoc.v_part[i].p_start = 0;
4312 					disk_vtoc.v_part[i].p_tag = 0;
4313 					disk_vtoc.v_part[i].p_flag = 0;
4314 					(void) fprintf(stderr,
4315 					    " removed!\n");
4316 				}
4317 			}
4318 			continue;
4319 		}
4320 		if (disk_vtoc.v_part[i].p_start > numsect) {
4321 			(void) fprintf(stderr,
4322 			    "slice %d (start %llu) is larger than the "
4323 			    "partition", i, disk_vtoc.v_part[i].p_start);
4324 			if (!io_nifdisk) {
4325 				(void) printf(" remove ?:");
4326 				if (yesno()) {
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 				}
4332 			} else {
4333 				disk_vtoc.v_part[i].p_size = 0;
4334 				disk_vtoc.v_part[i].p_start = 0;
4335 				disk_vtoc.v_part[i].p_tag = 0;
4336 				disk_vtoc.v_part[i].p_flag = 0;
4337 				(void) fprintf(stderr,
4338 				" removed!\n");
4339 			}
4340 		} else if (disk_vtoc.v_part[i].p_start
4341 		    + disk_vtoc.v_part[i].p_size > numsect) {
4342 			(void) fprintf(stderr,
4343 			    "slice %d (end %llu) is larger"
4344 			    " than the partition",
4345 			    i,
4346 			    disk_vtoc.v_part[i].p_start +
4347 			    disk_vtoc.v_part[i].p_size);
4348 			if (!io_nifdisk) {
4349 				(void) printf(" adjust ?:");
4350 				if (yesno()) {
4351 					disk_vtoc.v_part[i].p_size = numsect;
4352 				}
4353 			} else {
4354 				disk_vtoc.v_part[i].p_size = numsect;
4355 				(void) fprintf(stderr, " adjusted!\n");
4356 			}
4357 		}
4358 	}
4359 #if 1		/* bh for now */
4360 	/* Make the VTOC look sane - ha ha */
4361 	disk_vtoc.v_version = V_VERSION;
4362 	disk_vtoc.v_sanity = VTOC_SANE;
4363 	disk_vtoc.v_nparts = V_NUMPAR;
4364 	if (disk_vtoc.v_sectorsz == 0)
4365 		disk_vtoc.v_sectorsz = NBPSCTR;
4366 #endif
4367 
4368 	/* Write the VTOC back to the disk */
4369 	if (!io_readonly)
4370 		(void) writevtoc();
4371 }
4372 
4373 /*
4374  * yesno
4375  * Get yes or no answer. Return 1 for yes and 0 for no.
4376  */
4377 
4378 static int
4379 yesno(void)
4380 {
4381 	char	s[80];
4382 
4383 	for (;;) {
4384 		(void) fgets(s, sizeof (s), stdin);
4385 		rm_blanks(s);
4386 		if (((s[1] != '\0') && (s[1] != '\n')) ||
4387 		    ((s[0] != 'y') && (s[0] != 'n'))) {
4388 			(void) printf(E_LINE);
4389 			(void) printf("Please answer with \"y\" or \"n\": ");
4390 			continue;
4391 		}
4392 		if (s[0] == 'y')
4393 			return (1);
4394 		else
4395 			return (0);
4396 	}
4397 }
4398 
4399 /*
4400  * readvtoc
4401  * 	Read the VTOC from the Solaris partition of the device.
4402  */
4403 static int
4404 readvtoc(void)
4405 {
4406 	int	i;
4407 	int	retval = VTOC_OK;
4408 
4409 	if ((i = read_extvtoc(Dev, &disk_vtoc)) < VTOC_OK) {
4410 		if (i == VT_EINVAL) {
4411 			(void) fprintf(stderr, "fdisk: Invalid VTOC.\n");
4412 			vt_inval++;
4413 			retval = VTOC_INVAL;
4414 		} else if (i == VT_ENOTSUP) {
4415 			(void) fprintf(stderr, "fdisk: partition may have EFI "
4416 			    "GPT\n");
4417 			retval = VTOC_NOTSUP;
4418 		} else {
4419 			(void) fprintf(stderr, "fdisk: Cannot read VTOC.\n");
4420 			retval = VTOC_RWERR;
4421 		}
4422 	}
4423 	return (retval);
4424 }
4425 
4426 /*
4427  * writevtoc
4428  * 	Write the VTOC to the Solaris partition on the device.
4429  */
4430 static int
4431 writevtoc(void)
4432 {
4433 	int	i;
4434 	int	retval = 0;
4435 
4436 	if ((i = write_extvtoc(Dev, &disk_vtoc)) != 0) {
4437 		if (i == VT_EINVAL) {
4438 			(void) fprintf(stderr,
4439 			    "fdisk: Invalid entry exists in VTOC.\n");
4440 			retval = VTOC_INVAL;
4441 		} else if (i == VT_ENOTSUP) {
4442 			(void) fprintf(stderr, "fdisk: partition may have EFI "
4443 			    "GPT\n");
4444 			retval = VTOC_NOTSUP;
4445 		} else {
4446 			(void) fprintf(stderr, "fdisk: Cannot write VTOC.\n");
4447 			retval = VTOC_RWERR;
4448 		}
4449 	}
4450 	return (retval);
4451 }
4452 
4453 /*
4454  * efi_ioctl
4455  * issues DKIOCSETEFI IOCTL
4456  * (duplicate of private efi_ioctl() in rdwr_efi.c
4457  */
4458 static int
4459 efi_ioctl(int fd, int cmd, dk_efi_t *dk_ioc)
4460 {
4461 	void *data = dk_ioc->dki_data;
4462 	int error;
4463 
4464 	dk_ioc->dki_data_64 = (uintptr_t)data;
4465 	error = ioctl(fd, cmd, (void *)dk_ioc);
4466 
4467 	return (error);
4468 }
4469 
4470 /*
4471  * clear_efi
4472  * Clear EFI labels from the EFI_PMBR partition on the device
4473  * This function is modeled on the libefi(3LIB) call efi_write()
4474  */
4475 static int
4476 clear_efi(void)
4477 {
4478 	struct dk_gpt	*efi_vtoc;
4479 	dk_efi_t	dk_ioc;
4480 
4481 	/*
4482 	 * see if we can read the EFI label
4483 	 */
4484 	if (efi_alloc_and_read(Dev, &efi_vtoc) < 0) {
4485 		return (VT_ERROR);
4486 	}
4487 
4488 	/*
4489 	 * set up the dk_ioc structure for writing
4490 	 */
4491 	dk_ioc.dki_lba = 1;
4492 	dk_ioc.dki_length = EFI_MIN_ARRAY_SIZE + efi_vtoc->efi_lbasize;
4493 
4494 	if ((dk_ioc.dki_data = calloc(dk_ioc.dki_length, 1)) == NULL) {
4495 		return (VT_ERROR);
4496 	}
4497 
4498 	/*
4499 	 * clear the primary label
4500 	 */
4501 	if (io_debug) {
4502 		(void) fprintf(stderr,
4503 		    "\tClearing primary EFI label at block %lld\n",
4504 		    dk_ioc.dki_lba);
4505 	}
4506 
4507 	if (efi_ioctl(Dev, DKIOCSETEFI, &dk_ioc) == -1) {
4508 		free(dk_ioc.dki_data);
4509 		switch (errno) {
4510 			case EIO:
4511 				return (VT_EIO);
4512 			case EINVAL:
4513 				return (VT_EINVAL);
4514 			default:
4515 				return (VT_ERROR);
4516 		}
4517 	}
4518 
4519 	/*
4520 	 * clear the backup partition table
4521 	 */
4522 	dk_ioc.dki_lba = efi_vtoc->efi_last_u_lba + 1;
4523 	dk_ioc.dki_length -= efi_vtoc->efi_lbasize;
4524 	dk_ioc.dki_data = (efi_gpt_t *)((char *)dk_ioc.dki_data +
4525 	    efi_vtoc->efi_lbasize);
4526 	if (io_debug) {
4527 		(void) fprintf(stderr,
4528 		    "\tClearing backup partition table at block %lld\n",
4529 		    dk_ioc.dki_lba);
4530 	}
4531 
4532 	if (efi_ioctl(Dev, DKIOCSETEFI, &dk_ioc) == -1) {
4533 		(void) fprintf(stderr, "\tUnable to clear backup EFI label at "
4534 		    "block %llu; errno %d\n", efi_vtoc->efi_last_u_lba + 1,
4535 		    errno);
4536 	}
4537 
4538 	/*
4539 	 * clear the backup label
4540 	 */
4541 	dk_ioc.dki_lba = efi_vtoc->efi_last_lba;
4542 	dk_ioc.dki_length = efi_vtoc->efi_lbasize;
4543 	dk_ioc.dki_data = (efi_gpt_t *)((char *)dk_ioc.dki_data -
4544 	    efi_vtoc->efi_lbasize);
4545 	if (io_debug) {
4546 		(void) fprintf(stderr, "\tClearing backup label at block "
4547 		    "%lld\n", dk_ioc.dki_lba);
4548 	}
4549 
4550 	if (efi_ioctl(Dev, DKIOCSETEFI, &dk_ioc) == -1) {
4551 		(void) fprintf(stderr,
4552 		    "\tUnable to clear backup EFI label at "
4553 		    "block %llu; errno %d\n",
4554 		    efi_vtoc->efi_last_lba,
4555 		    errno);
4556 	}
4557 
4558 	free(dk_ioc.dki_data);
4559 	efi_free(efi_vtoc);
4560 
4561 	return (0);
4562 }
4563 
4564 /*
4565  * clear_vtoc
4566  * 	Clear the VTOC from the current or previous Solaris partition on the
4567  *      device.
4568  */
4569 static void
4570 clear_vtoc(int table, int part)
4571 {
4572 	struct ipart *clr_table;
4573 	char *disk_label;
4574 	uint32_t pcyl, ncyl, count;
4575 	diskaddr_t backup_block, solaris_offset;
4576 	ssize_t bytes;
4577 	off_t seek_byte;
4578 
4579 #ifdef DEBUG
4580 	char *read_label;
4581 #endif /* DEBUG */
4582 
4583 	if (table == OLD) {
4584 		clr_table = &Old_Table[part];
4585 	} else {
4586 		clr_table = &Table[part];
4587 	}
4588 
4589 	disk_label = (char *)calloc(sectsiz, 1);
4590 	if (disk_label == NULL) {
4591 		return;
4592 	}
4593 
4594 	seek_byte = (off_t)(LE_32(clr_table->relsect) + VTOC_OFFSET) * sectsiz;
4595 
4596 	if (io_debug) {
4597 		(void) fprintf(stderr,
4598 		    "\tClearing primary VTOC at byte %llu (block %llu)\n",
4599 		    (uint64_t)seek_byte,
4600 		    (uint64_t)(LE_32(clr_table->relsect) + VTOC_OFFSET));
4601 	}
4602 
4603 	if (lseek(Dev, seek_byte, SEEK_SET) == -1) {
4604 		(void) fprintf(stderr,
4605 		    "\tError seeking to primary label at byte %llu\n",
4606 		    (uint64_t)seek_byte);
4607 		free(disk_label);
4608 		return;
4609 	}
4610 
4611 	bytes = write(Dev, disk_label, sectsiz);
4612 
4613 	if (bytes != sectsiz) {
4614 		(void) fprintf(stderr,
4615 		    "\tWarning: only %d bytes written to clear primary"
4616 		    " VTOC!\n", bytes);
4617 	}
4618 
4619 #ifdef DEBUG
4620 	if (lseek(Dev, seek_byte, SEEK_SET) == -1) {
4621 		(void) fprintf(stderr,
4622 		    "DEBUG: Error seeking to primary label at byte %llu\n",
4623 		    (uint64_t)seek_byte);
4624 		free(disk_label);
4625 		return;
4626 	} else {
4627 		(void) fprintf(stderr,
4628 		    "DEBUG: Successful lseek() to byte %llu\n",
4629 		    (uint64_t)seek_byte);
4630 	}
4631 
4632 	read_label = (char *)calloc(sectsiz, 1);
4633 	if (read_label == NULL) {
4634 		free(disk_label);
4635 		return;
4636 	}
4637 
4638 	bytes = read(Dev, read_label, sectsiz);
4639 
4640 	if (bytes != sectsiz) {
4641 		(void) fprintf(stderr,
4642 		    "DEBUG: Warning: only %d bytes read of label\n",
4643 		    bytes);
4644 	}
4645 
4646 	if (memcmp(disk_label, read_label, sectsiz) != 0) {
4647 		(void) fprintf(stderr,
4648 		    "DEBUG: Warning: disk_label and read_label differ!!!\n");
4649 	} else {
4650 		(void) fprintf(stderr, "DEBUG Good compare of disk_label and "
4651 		    "read_label\n");
4652 	}
4653 #endif /* DEBUG */
4654 
4655 	/* Clear backup label */
4656 	pcyl = LE_32(clr_table->numsect) / (heads * sectors);
4657 	solaris_offset = LE_32(clr_table->relsect);
4658 	ncyl = pcyl - acyl;
4659 
4660 	backup_block = ((ncyl + acyl - 1) *
4661 	    (heads * sectors)) + ((heads - 1) * sectors) + 1;
4662 
4663 	for (count = 1; count < 6; count++) {
4664 		seek_byte = (off_t)(solaris_offset + backup_block) * sectsiz;
4665 
4666 		if (lseek(Dev, seek_byte, SEEK_SET) == -1) {
4667 			(void) fprintf(stderr,
4668 			    "\tError seeking to backup label at byte %llu on "
4669 			    "%s.\n", (uint64_t)seek_byte, Dfltdev);
4670 			free(disk_label);
4671 #ifdef DEBUG
4672 			free(read_label);
4673 #endif /* DEBUG */
4674 			return;
4675 		}
4676 
4677 		if (io_debug) {
4678 			(void) fprintf(stderr, "\tClearing backup VTOC at"
4679 			    " byte %llu (block %llu)\n",
4680 			    (uint64_t)seek_byte,
4681 			    (uint64_t)(solaris_offset + backup_block));
4682 		}
4683 
4684 		bytes = write(Dev, disk_label, sectsiz);
4685 
4686 		if (bytes != sectsiz) {
4687 			(void) fprintf(stderr,
4688 			    "\t\tWarning: only %d bytes written to "
4689 			    "clear backup VTOC at block %llu!\n", bytes,
4690 			    (uint64_t)(solaris_offset + backup_block));
4691 		}
4692 
4693 #ifdef DEBUG
4694 	if (lseek(Dev, seek_byte, SEEK_SET) == -1) {
4695 		(void) fprintf(stderr,
4696 		    "DEBUG: Error seeking to backup label at byte %llu\n",
4697 		    (uint64_t)seek_byte);
4698 		free(disk_label);
4699 		free(read_label);
4700 		return;
4701 	} else {
4702 		(void) fprintf(stderr,
4703 		    "DEBUG: Successful lseek() to byte %llu\n",
4704 		    (uint64_t)seek_byte);
4705 	}
4706 
4707 	bytes = read(Dev, read_label, sectsiz);
4708 
4709 	if (bytes != sectsiz) {
4710 		(void) fprintf(stderr,
4711 		    "DEBUG: Warning: only %d bytes read of backup label\n",
4712 		    bytes);
4713 	}
4714 
4715 	if (memcmp(disk_label, read_label, sectsiz) != 0) {
4716 		(void) fprintf(stderr,
4717 		    "DEBUG: Warning: disk_label and read_label differ!!!\n");
4718 	} else {
4719 		(void) fprintf(stderr,
4720 		    "DEBUG: Good compare of disk_label and backup "
4721 		    "read_label\n");
4722 	}
4723 
4724 #endif /* DEBUG */
4725 
4726 		backup_block += 2;
4727 	}
4728 
4729 #ifdef DEBUG
4730 	free(read_label);
4731 #endif /* DEBUG */
4732 	free(disk_label);
4733 }
4734 
4735 #define	FDISK_STANDARD_LECTURE \
4736 	"Fdisk is normally used with the device that " \
4737 	"represents the entire fixed disk.\n" \
4738 	"(For example, /dev/rdsk/c0d0p0 on x86 or " \
4739 	"/dev/rdsk/c0t5d0s2 on sparc).\n"
4740 
4741 #define	FDISK_LECTURE_NOT_SECTOR_ZERO \
4742 	"The device does not appear to include absolute\n" \
4743 	"sector 0 of the PHYSICAL disk " \
4744 	"(the normal location for an fdisk table).\n"
4745 
4746 #define	FDISK_LECTURE_NOT_FULL \
4747 	"The device does not appear to encompass the entire PHYSICAL disk.\n"
4748 
4749 #define	FDISK_LECTURE_NO_VTOC \
4750 	"Unable to find a volume table of contents.\n" \
4751 	"Cannot verify the device encompasses the full PHYSICAL disk.\n"
4752 
4753 #define	FDISK_LECTURE_NO_GEOM \
4754 	"Unable to get geometry from device.\n" \
4755 	"Cannot verify the device encompasses the full PHYSICAL disk.\n"
4756 
4757 #define	FDISK_SHALL_I_CONTINUE \
4758 	"Are you sure you want to continue? (y/n) "
4759 
4760 /*
4761  *  lecture_and_query
4762  *	Called when a sanity check fails.  This routine gives a warning
4763  *	specific to the check that fails, followed by a generic lecture
4764  *	about the "right" device to supply as input.  Then, if appropriate,
4765  *	it will prompt the user on whether or not they want to continue.
4766  *	Inappropriate times for prompting are when the user has selected
4767  *	non-interactive mode or read-only mode.
4768  */
4769 static int
4770 lecture_and_query(char *warning, char *devname)
4771 {
4772 	if (io_nifdisk)
4773 		return (0);
4774 
4775 	(void) fprintf(stderr, "WARNING: Device %s: \n", devname);
4776 	(void) fprintf(stderr, "%s", warning);
4777 	(void) fprintf(stderr, FDISK_STANDARD_LECTURE);
4778 	(void) fprintf(stderr, FDISK_SHALL_I_CONTINUE);
4779 
4780 	return (yesno());
4781 }
4782 
4783 static void
4784 sanity_check_provided_device(char *devname, int fd)
4785 {
4786 	struct extvtoc v;
4787 	struct dk_geom d;
4788 	struct part_info pi;
4789 	struct extpart_info extpi;
4790 	diskaddr_t totsize;
4791 	int idx = -1;
4792 
4793 	/*
4794 	 *  First try the PARTINFO ioctl.  If it works, we will be able
4795 	 *  to tell if they've specified the full disk partition by checking
4796 	 *  to see if they've specified a partition that starts at sector 0.
4797 	 */
4798 	if (ioctl(fd, DKIOCEXTPARTINFO, &extpi) != -1) {
4799 		if (extpi.p_start != 0) {
4800 			if (!lecture_and_query(FDISK_LECTURE_NOT_SECTOR_ZERO,
4801 			    devname)) {
4802 				(void) close(fd);
4803 				exit(1);
4804 			}
4805 		}
4806 	} else if (ioctl(fd, DKIOCPARTINFO, &pi) != -1) {
4807 		if (pi.p_start != 0) {
4808 			if (!lecture_and_query(FDISK_LECTURE_NOT_SECTOR_ZERO,
4809 			    devname)) {
4810 				(void) close(fd);
4811 				exit(1);
4812 			}
4813 		}
4814 	} else {
4815 		if ((idx = read_extvtoc(fd, &v)) < 0) {
4816 			if (!lecture_and_query(FDISK_LECTURE_NO_VTOC,
4817 			    devname)) {
4818 				(void) close(fd);
4819 				exit(1);
4820 			}
4821 			return;
4822 		}
4823 		if (ioctl(fd, DKIOCGGEOM, &d) == -1) {
4824 			perror(devname);
4825 			if (!lecture_and_query(FDISK_LECTURE_NO_GEOM,
4826 			    devname)) {
4827 				(void) close(fd);
4828 				exit(1);
4829 			}
4830 			return;
4831 		}
4832 		totsize = (diskaddr_t)d.dkg_ncyl * d.dkg_nhead * d.dkg_nsect;
4833 		if (v.v_part[idx].p_size != totsize) {
4834 			if (!lecture_and_query(FDISK_LECTURE_NOT_FULL,
4835 			    devname)) {
4836 				(void) close(fd);
4837 				exit(1);
4838 			}
4839 		}
4840 	}
4841 }
4842 
4843 
4844 /*
4845  * get_node
4846  * Called from main to construct the name of the device node to open.
4847  * Initially tries to stat the node exactly as provided, if that fails
4848  * we prepend the default path (/dev/rdsk/).
4849  */
4850 static char *
4851 get_node(char *devname)
4852 {
4853 	char *node;
4854 	struct stat statbuf;
4855 	size_t space;
4856 
4857 	/* Don't do anything if we are skipping device checks */
4858 	if (io_image)
4859 		return (devname);
4860 
4861 	node = devname;
4862 
4863 	/* Try the node as provided first */
4864 	if (stat(node, (struct stat *)&statbuf) == -1) {
4865 		/*
4866 		 * Copy the passed in string to a new buffer, prepend the
4867 		 * default path and try again.
4868 		 */
4869 		space = strlen(DEFAULT_PATH) + strlen(devname) + 1;
4870 
4871 		if ((node = malloc(space)) == NULL) {
4872 			(void) fprintf(stderr, "fdisk: Unable to obtain memory "
4873 			    "for device node.\n");
4874 			exit(1);
4875 		}
4876 
4877 		/* Copy over the default path and the provided node */
4878 		(void) strncpy(node, DEFAULT_PATH, strlen(DEFAULT_PATH));
4879 		space -= strlen(DEFAULT_PATH);
4880 		(void) strlcpy(node + strlen(DEFAULT_PATH), devname, space);
4881 
4882 		/* Try to stat it again */
4883 		if (stat(node, (struct stat *)&statbuf) == -1) {
4884 			/* Failed all options, give up */
4885 			(void) fprintf(stderr,
4886 			    "fdisk: Cannot stat device %s.\n",
4887 			    devname);
4888 			exit(1);
4889 		}
4890 	}
4891 
4892 	/* Make sure the device specified is the raw device */
4893 	if ((statbuf.st_mode & S_IFMT) != S_IFCHR) {
4894 		(void) fprintf(stderr,
4895 		    "fdisk: %s must be a raw device.\n", node);
4896 		exit(1);
4897 	}
4898 
4899 	return (node);
4900 }
4901 
4902 #ifdef i386
4903 static void
4904 preach_and_continue()
4905 {
4906 	(void) fprintf(stderr, "There are mounted logical drives. Committing "
4907 	    "changes now can lead to inconsistancy in internal system state "
4908 	    "which can eventually cause data loss or corruption. Unmount all "
4909 	    "logical drives and try committing the changes again.\n");
4910 	ext_read_input(s);
4911 }
4912 
4913 /*
4914  * Convert a given partition ID to an descriptive string.
4915  * Just an index into the partition types table.
4916  */
4917 void
4918 id_to_name(uchar_t sysid, char *buffer)
4919 {
4920 	strcpy(buffer, fdisk_part_types[sysid]);
4921 }
4922 
4923 /*
4924  * Procedure to check the validity of the extended partition menu option
4925  * entered by the user
4926  */
4927 static int
4928 ext_invalid_option(char ch)
4929 {
4930 	char *p;
4931 
4932 	p = strchr(ext_part_menu_opts, tolower(ch));
4933 
4934 	if (p == NULL) {
4935 		return (1);
4936 	}
4937 	return (0);
4938 }
4939 
4940 /*
4941  * Read 16 bytes of the input (assuming that no valid user input spans more
4942  * than that). Flush the input stream, so that the next read does not reap
4943  * stale data from the previous input that was not processed.
4944  * Note that fgets also reads the trailing '\n'
4945  */
4946 static void
4947 ext_read_input(char *buf)
4948 {
4949 	fgets(buf, 16, stdin);
4950 	fflush(stdin);
4951 }
4952 
4953 /*
4954  * Procedure to read and validate the user option at the extended partition menu
4955  */
4956 static int
4957 ext_read_options(char *buf)
4958 {
4959 	ext_read_input(buf);
4960 	if ((strlen(buf) != 2) || (ext_invalid_option(buf[0]))) {
4961 		printf("\nUnknown Command\n");
4962 		return (-1);
4963 	}
4964 	return (0);
4965 }
4966 
4967 /*
4968  * Procedure to print the list of known partition types and their IDs
4969  */
4970 static void
4971 ext_print_part_types()
4972 {
4973 	int i, rowmax, rowcount = 1;
4974 	struct winsize ws;
4975 	char buf[80];
4976 
4977 	/* Get the current window dimensions */
4978 	if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) < 0) {
4979 		perror("ioctl");
4980 		rowmax = 20;
4981 	} else {
4982 		/*
4983 		 * Accommodate the initial headings by reducing the number of
4984 		 * partition IDs being printed.
4985 		 */
4986 		rowmax = ws.ws_row - 5;
4987 	}
4988 
4989 	if (rowmax < 3) {
4990 		fprintf(stderr, "Window size too small."
4991 		    " Try resizing the window\n");
4992 		return;
4993 	}
4994 
4995 	printf("List of known partition types : \n");
4996 	printf("PartID          Partition Type\n");
4997 	printf("======          ==============\n");
4998 	for (i = 0; i <= FDISK_MAX_VALID_PART_ID; i++) {
4999 		printf("%-3d          %s\n", i, fdisk_part_types[i]);
5000 		rowcount++;
5001 		if (rowcount == rowmax) {
5002 			/*
5003 			 * After the initial screen, use all the rows for
5004 			 * printing the partition IDs, but one.
5005 			 */
5006 			rowmax = ws.ws_row - 1;
5007 			fprintf(stderr, "\nPress enter to see next page or 'q'"
5008 			    " to quit : ");
5009 			ext_read_input(buf);
5010 			if ((strlen(buf) == 2) && (tolower(buf[0]) == 'q')) {
5011 				return;
5012 			}
5013 			rowcount = 1;
5014 		}
5015 	}
5016 }
5017 
5018 static void
5019 ext_read_valid_part_num(int *pno)
5020 {
5021 	char buf[80];
5022 	int len, i;
5023 
5024 	for (;;) {
5025 		printf("Enter the partition number : ");
5026 		ext_read_input(buf);
5027 
5028 		len = strlen(buf);
5029 
5030 		/* Check length of the input */
5031 		if ((len < 2) || (len > (FDISK_MAX_VALID_PART_NUM_DIGITS+1))) {
5032 			goto print_error_and_continue;
5033 		}
5034 
5035 		/* Check if there is a non-digit in the input */
5036 		for (i = 0; i < len-1; i++) {
5037 			if (!isdigit(buf[i])) {
5038 				goto print_error_and_continue;
5039 			}
5040 		}
5041 
5042 		*pno = atoi(buf);
5043 
5044 		if ((*pno <= FD_NUMPART) ||
5045 		    *pno > (fdisk_get_logical_drive_count(epp) + FD_NUMPART)) {
5046 			goto print_error_and_continue;
5047 		}
5048 
5049 		break;
5050 print_error_and_continue:
5051 		printf("Invalid partition number\n");
5052 		continue;
5053 	}
5054 }
5055 
5056 static void
5057 ext_read_valid_part_id(uchar_t *partid)
5058 {
5059 	char buf[80];
5060 	int len, i, id;
5061 
5062 	for (;;) {
5063 		printf("Enter the ID ( Type I for list of partition IDs ) : ");
5064 		ext_read_input(buf);
5065 		len = strlen(buf);
5066 
5067 		if ((len < 2) || (len > (FDISK_MAX_VALID_PART_ID_DIGITS + 1))) {
5068 			printf("Invalid partition ID\n");
5069 			continue;
5070 		}
5071 
5072 		if ((len == 2) && (toupper(buf[0]) == 'I')) {
5073 			ext_print_part_types();
5074 			continue;
5075 		}
5076 
5077 		/* Check if there is a non-digit in the input */
5078 		for (i = 0; i < len-1; i++) {
5079 			if (!isdigit(buf[i])) {
5080 				printf("Invalid partition ID\n");
5081 				break;
5082 			}
5083 		}
5084 
5085 		if (i < len - 1) {
5086 			continue;
5087 		}
5088 
5089 		/* Check if the (now) valid number is greater than the limit */
5090 		if ((id = atoi(buf)) > FDISK_MAX_VALID_PART_ID) {
5091 			printf("Invalid partition ID\n");
5092 			continue;
5093 		}
5094 
5095 		*partid = (uchar_t)id;
5096 
5097 		/* Disallow multiple extended partitions */
5098 		if (fdisk_is_dos_extended(*partid)) {
5099 			printf("Multiple extended partitions not allowed\n");
5100 			continue;
5101 		}
5102 
5103 		/* Disallow EFI partitions within extended partition */
5104 		if (*partid == EFI_PMBR) {
5105 			printf("EFI partitions within an extended partition"
5106 			    " is not allowed\n");
5107 			continue;
5108 		}
5109 
5110 		return; /* Valid partition ID is in partid */
5111 	}
5112 }
5113 
5114 static void
5115 delete_logical_drive()
5116 {
5117 	int pno;
5118 
5119 	if (!fdisk_get_logical_drive_count(epp)) {
5120 		printf("\nNo logical drives defined.\n");
5121 		return;
5122 	}
5123 
5124 	printf("\n");
5125 	ext_read_valid_part_num(&pno);
5126 	fdisk_delete_logical_drive(epp, pno);
5127 	printf("Partition %d deleted\n", pno);
5128 }
5129 
5130 static int
5131 ext_read_valid_partition_start(uint32_t *begsec)
5132 {
5133 	char buf[80];
5134 	int ret, len, i;
5135 	uint32_t begcyl;
5136 	uint32_t first_free_cyl;
5137 	uint32_t first_free_sec;
5138 
5139 	ret = fdisk_ext_find_first_free_sec(epp, &first_free_sec);
5140 	if (ret != FDISK_SUCCESS) {
5141 		return (ret);
5142 	}
5143 
5144 	first_free_cyl = FDISK_SECT_TO_CYL(epp, first_free_sec);
5145 	for (;;) {
5146 		printf("Enter the beginning cylinder (Default - %d) : ",
5147 		    first_free_cyl);
5148 		ext_read_input(buf);
5149 		len = strlen(buf);
5150 		if (len == 1) { /* User accepted the default value */
5151 			*begsec = first_free_sec;
5152 			return (FDISK_SUCCESS);
5153 		}
5154 
5155 		if (len > (FDISK_MAX_VALID_CYL_NUM_DIGITS + 1)) {
5156 			printf("Input too long\n");
5157 			printf("Invalid beginning cylinder number\n");
5158 			continue;
5159 		}
5160 		/* Check if there is a non-digit in the input */
5161 		for (i = 0; i < len - 1; i++) {
5162 			if (!isdigit(buf[i])) {
5163 				printf("Invalid beginning cylinder number\n");
5164 				break;
5165 			}
5166 		}
5167 		if (i < len - 1) {
5168 			continue;
5169 		}
5170 
5171 		begcyl = atoi(buf);
5172 		ret = fdisk_ext_validate_part_start(epp, begcyl, begsec);
5173 		switch (ret) {
5174 			case FDISK_SUCCESS:
5175 				/*
5176 				 * Success.
5177 				 * Valid beginning sector is in begsec
5178 				 */
5179 				break;
5180 
5181 			case FDISK_EOVERLAP:
5182 				printf("Partition boundary overlaps with ");
5183 				printf("existing partitions\n");
5184 				printf("Invalid beginning cylinder number\n");
5185 				continue;
5186 
5187 			case FDISK_EOOBOUND:
5188 				printf("Cylinder boundary beyond the limits\n");
5189 				printf("Invalid beginning cylinder number\n");
5190 				continue;
5191 		}
5192 		return (FDISK_SUCCESS);
5193 	}
5194 }
5195 
5196 /*
5197  * Algorithm :
5198  * 1. Check if the first character is a +
5199  *	a) If yes, check if the last character is 'k', 'm' or 'g'
5200  * 2. If not, check if there are any non-digits
5201  * 3. Check for the length of the numeral string
5202  * 4. atoi the numeral string
5203  * 5. In case of data entered in KB, MB or GB, convert it to number of cylinders
5204  *	a) Adjust size to be cylinder boundary aligned
5205  * 6. If size specifies is zero, flag error
5206  * 7. Check if the size is less than 1 cylinder
5207  *	a) If yes, default the size FDISK_MIN_PART_SIZE
5208  * 	b) If no, Check if the size is within endcyl - begcyl
5209  */
5210 static void
5211 ext_read_valid_partition_size(uint32_t begsec, uint32_t *endsec)
5212 {
5213 	char buf[80];
5214 	uint32_t tempcyl;
5215 	uint32_t last_free_sec;
5216 	uint32_t last_free_cyl;
5217 	int i, len, ch, mbgb = 0, scale = FDISK_SECTS_PER_CYL(epp);
5218 	uint64_t size = 0;
5219 	int copy_len;
5220 	char numbuf[FDISK_MAX_VALID_CYL_NUM_DIGITS + 1];
5221 	int sectsize = fdisk_get_disk_geom(epp, PHYSGEOM, SSIZE);
5222 	uint32_t remdr, spc, poss_end;
5223 
5224 	if (sectsize == EINVAL) {
5225 		fprintf(stderr, "Unsupported geometry statistics.\n");
5226 		exit(1);
5227 	}
5228 
5229 	last_free_sec = fdisk_ext_find_last_free_sec(epp, begsec);
5230 	last_free_cyl = FDISK_SECT_TO_CYL(epp, last_free_sec);
5231 
5232 	for (;;) {
5233 		printf("Enter the size in cylinders (Default End Cylinder -");
5234 		printf(" %u)\n", last_free_cyl);
5235 		printf("Type +<size>K, +<size>M or +<size>G to enter size in");
5236 		printf("KB, MB or GB : ");
5237 		ext_read_input(buf);
5238 		len = strlen(buf);
5239 		mbgb = 0;
5240 		scale = FDISK_SECTS_PER_CYL(epp);
5241 
5242 		if (len == 1) { /* User accepted the default value */
5243 			*endsec = last_free_sec;
5244 			return;
5245 		}
5246 
5247 		copy_len = len - 1;
5248 
5249 		if ((buf[0] == '+') && (isdigit(buf[1]))) {
5250 			copy_len--;
5251 			if ((ch = toupper(buf[len - 2])) == 'B') {
5252 				ch = toupper(buf[len - 3]);
5253 				copy_len--;
5254 			}
5255 
5256 			if (!((ch == 'K') || (ch == 'M') || (ch == 'G'))) {
5257 				printf("Invalid partition size\n");
5258 				continue;
5259 			}
5260 
5261 			copy_len--;
5262 			mbgb = 1;
5263 			scale = ((ch == 'K') ? FDISK_KB :
5264 			    ((ch == 'M') ? FDISK_MB : FDISK_GB));
5265 		}
5266 
5267 		if (copy_len > FDISK_MAX_VALID_CYL_NUM_DIGITS) {
5268 			printf("Input too long\n");
5269 			printf("Invalid partition size\n");
5270 			continue;
5271 		}
5272 
5273 		strncpy(numbuf, &buf[mbgb], copy_len);
5274 		numbuf[copy_len] = '\0';
5275 
5276 		for (i = mbgb; i < copy_len + mbgb; i++) {
5277 			if (!isdigit(buf[i])) {
5278 				break;
5279 			}
5280 		}
5281 
5282 		if (i < copy_len + mbgb) {
5283 			printf("Invalid partition size\n");
5284 			continue;
5285 		}
5286 
5287 		size = (atoll(numbuf) * (scale));
5288 
5289 		if (size == 0) {
5290 			printf("Zero size is invalid\n");
5291 			printf("Invalid partition size\n");
5292 			continue;
5293 		}
5294 
5295 		if (mbgb) {
5296 			size /= sectsize;
5297 		}
5298 
5299 		if (size > (last_free_sec - begsec + 1)) {
5300 			printf("Cylinder boundary beyond the limits");
5301 			printf(" or overlaps with existing");
5302 			printf(" partitions\n");
5303 			printf("Invalid partition size\n");
5304 			continue;
5305 		}
5306 
5307 		/*
5308 		 * Adjust the ending sector such that there are no partial
5309 		 * cylinders allocated. But at the same time, make sure it
5310 		 * doesn't over shoot boundaries.
5311 		 */
5312 		spc = FDISK_SECTS_PER_CYL(epp);
5313 		poss_end = begsec + size - 1;
5314 		if (remdr = (poss_end % spc)) {
5315 			poss_end += spc - remdr - 1;
5316 		}
5317 		*endsec = (poss_end > last_free_sec) ? last_free_sec :
5318 		    poss_end;
5319 
5320 		return;
5321 	}
5322 }
5323 
5324 /*
5325  * ALGORITHM:
5326  * 1. Get the starting and ending sectors/cylinder of the extended partition.
5327  * 2. Keep track of the first free sector/cylinder
5328  * 3. Allow the user to specify the beginning cylinder of the new partition
5329  * 4. Check for the validity of the entered data
5330  *	a) If it is non-numeric
5331  *	b) If it is beyond the extended partition limits
5332  *	c) If it overlaps with the current logical drives
5333  * 5. Allow the user to specify the size in cylinders/ human readable form
5334  * 6. Check for the validity of the entered data
5335  *	a) If it is non-numeric
5336  *	b) If it is beyond the extended partition limits
5337  *	c) If it overlaps with the current logical drives
5338  *	d) If it is a number lesser than the starting cylinder
5339  * 7. Request partition ID for the new partition.
5340  * 8. Update the first free cylinder available
5341  * 9. Display Success message
5342  */
5343 
5344 static void
5345 add_logical_drive()
5346 {
5347 	uint32_t begsec, endsec;
5348 	uchar_t partid;
5349 	char buf[80];
5350 	int rval;
5351 
5352 	if (fdisk_get_logical_drive_count(epp) >= MAX_EXT_PARTS) {
5353 		printf("\nNumber of logical drives exceeds limit of %d.\n",
5354 		    MAX_EXT_PARTS);
5355 		printf("Command did not succeed. Press enter to continue\n");
5356 		ext_read_input(buf);
5357 		return;
5358 	}
5359 
5360 	printf("\n");
5361 	rval = ext_read_valid_partition_start(&begsec);
5362 	switch (rval) {
5363 		case FDISK_SUCCESS:
5364 			break;
5365 
5366 		case FDISK_EOOBOUND:
5367 			printf("\nNo space left in the extended partition\n");
5368 			printf("Press enter to continue\n");
5369 			ext_read_input(buf);
5370 			return;
5371 	}
5372 
5373 	ext_read_valid_partition_size(begsec, &endsec);
5374 	ext_read_valid_part_id(&partid);
5375 	fdisk_add_logical_drive(epp, begsec, endsec, partid);
5376 
5377 	printf("New partition with ID %d added\n", partid);
5378 }
5379 
5380 static void
5381 ext_change_logical_drive_id()
5382 {
5383 	int pno;
5384 	uchar_t partid;
5385 
5386 	if (!fdisk_get_logical_drive_count(epp)) {
5387 		printf("\nNo logical drives defined.\n");
5388 		return;
5389 	}
5390 
5391 	printf("\n");
5392 	ext_read_valid_part_num(&pno);
5393 	ext_read_valid_part_id(&partid);
5394 	fdisk_change_logical_drive_id(epp, pno, partid);
5395 
5396 	printf("Partition ID of partition %d changed to %d\n", pno, partid);
5397 }
5398 
5399 #ifdef DEBUG
5400 static void
5401 ext_print_logdrive_layout_debug()
5402 {
5403 	int pno;
5404 	char namebuff[255];
5405 	logical_drive_t *head = fdisk_get_ld_head(epp);
5406 	logical_drive_t *temp;
5407 
5408 	if (!fdisk_get_logical_drive_count(epp)) {
5409 		printf("\nNo logical drives defined.\n");
5410 		return;
5411 	}
5412 
5413 	printf("\n\n");
5414 	puts("#  start block  end block    abs start    abs end      OSType");
5415 	for (temp = head, pno = 5; temp != NULL; temp = temp->next, pno++) {
5416 		/* Print the logical drive details */
5417 		id_to_name(temp->parts[0].systid, namebuff);
5418 		printf("%d: %.10u   %.10u   %.10u   %.10u",
5419 		    pno,
5420 		    LE_32(temp->parts[0].relsect),
5421 		    LE_32(temp->parts[0].numsect),
5422 		    temp->abs_secnum,
5423 		    temp->abs_secnum + temp->numsect - 1 +
5424 		    MAX_LOGDRIVE_OFFSET);
5425 		printf("   %s\n", namebuff);
5426 		/*
5427 		 * Print the second entry in the EBR which is information
5428 		 * about the location and the size of the next extended
5429 		 * partition.
5430 		 */
5431 		id_to_name(temp->parts[1].systid, namebuff);
5432 		printf("%d: %.10u   %.10u   %.10s   %.10s",
5433 		    pno,
5434 		    LE_32(temp->parts[1].relsect),
5435 		    LE_32(temp->parts[1].numsect),
5436 		    "          ", "          ");
5437 		printf("   %s\n", namebuff);
5438 	}
5439 }
5440 #endif
5441 
5442 static void
5443 ext_print_logical_drive_layout()
5444 {
5445 	int sysid;
5446 	unsigned int startcyl, endcyl, length, percent, remainder;
5447 	logical_drive_t *temp;
5448 	uint32_t part_start;
5449 	struct ipart *fpart;
5450 	char namebuff[255];
5451 	int numcyl = fdisk_get_disk_geom(epp, PHYSGEOM, NCYL);
5452 	int pno;
5453 
5454 	if (numcyl == EINVAL) {
5455 		fprintf(stderr, "Unsupported geometry statistics.\n");
5456 		exit(1);
5457 	}
5458 
5459 	if (!fdisk_get_logical_drive_count(epp)) {
5460 		printf("\nNo logical drives defined.\n");
5461 		return;
5462 	}
5463 
5464 	printf("\n");
5465 	printf("Number of cylinders in disk              : %u\n", numcyl);
5466 	printf("Beginning cylinder of extended partition : %u\n",
5467 	    fdisk_get_ext_beg_cyl(epp));
5468 	printf("Ending cylinder of extended partition    : %u\n",
5469 	    fdisk_get_ext_end_cyl(epp));
5470 	printf("\n");
5471 	printf("Part#   StartCyl   EndCyl     Length    %%     "
5472 	"Part ID (Type)\n");
5473 	printf("=====   ========   ========   =======   ==="
5474 	"   ==============\n");
5475 	for (temp = fdisk_get_ld_head(epp), pno = 5; temp != NULL;
5476 	    temp = temp->next, pno++) {
5477 		/* Print the logical drive details */
5478 		fpart = &temp->parts[0];
5479 		sysid = fpart->systid;
5480 		/*
5481 		 * Check if partition id 0x82 is Solaris
5482 		 * or a Linux swap. Print the string
5483 		 * accordingly.
5484 		 */
5485 		if (sysid == SUNIXOS) {
5486 			part_start = temp->abs_secnum +
5487 			    temp->logdrive_offset;
5488 			if (fdisk_is_linux_swap(epp, part_start,
5489 			    NULL) == 0)
5490 				strcpy(namebuff, LINSWAPstr);
5491 			else
5492 				strcpy(namebuff, SUstr);
5493 		} else {
5494 			id_to_name(sysid, namebuff);
5495 		}
5496 		startcyl = temp->begcyl;
5497 		endcyl = temp->endcyl;
5498 		if (startcyl == endcyl) {
5499 			length = 1;
5500 		} else {
5501 			length = endcyl - startcyl + 1;
5502 		}
5503 		percent = length * 100 / numcyl;
5504 		if ((remainder = (length * 100 % numcyl)) != 0) {
5505 			if ((remainder * 100 / numcyl) > 50) {
5506 				/* round up */
5507 				percent++;
5508 			}
5509 			/* Else leave the percent as is since it's already */
5510 			/* rounded down */
5511 		}
5512 		if (percent > 100) {
5513 			percent = 100;
5514 		}
5515 		printf("%-5d   %-8u   %-8u   %-7u   %-3d   %-3d (%-.28s)\n",
5516 		    pno, startcyl, endcyl, length, percent, sysid, namebuff);
5517 	}
5518 #ifdef DEBUG
5519 	ext_print_logdrive_layout_debug();
5520 #endif
5521 	printf("\n");
5522 }
5523 
5524 static void
5525 ext_print_help_menu()
5526 {
5527 	printf("\n");
5528 	printf("a	Add a logical drive\n");
5529 	printf("d	Delete a logical drive\n");
5530 	printf("h	Print this help menu\n");
5531 	printf("i	Change the id of the logical drive\n");
5532 	printf("p	Print the logical drive layout\n");
5533 	printf("r	Return to the main fdisk menu\n");
5534 	printf("        (To commit or cancel the changes)\n");
5535 	printf("\n");
5536 }
5537 
5538 static void
5539 ext_part_menu()
5540 {
5541 	char buf[80];
5542 	uchar_t *bbsigp;
5543 	static int bbsig_disp_flag = 1;
5544 
5545 	int i;
5546 
5547 	printf(CLR_SCR);
5548 
5549 	if (fdisk_corrupt_logical_drives(epp)) {
5550 		printf("One or more logical drives seem to be corrupt.\n");
5551 		printf("Displaying only sane logical drives.\n");
5552 	}
5553 
5554 	if (bbsig_disp_flag && fdisk_invalid_bb_sig(epp, &bbsigp)) {
5555 		printf("The following logical drives have a wrong boot block"
5556 		    " signature :\n\n");
5557 		for (i = 0; bbsigp[i]; i++) {
5558 			printf("%d ", bbsigp[i]);
5559 		}
5560 		printf("\n\n");
5561 		printf("They will be corrected when you choose to commit\n");
5562 		bbsig_disp_flag = 0;
5563 	}
5564 
5565 	printf("Extended partition menu\n");
5566 
5567 	for (;;) {
5568 		printf("\nEnter Command (Type h for help) : ");
5569 		if ((ext_read_options(buf)) < 0) {
5570 			printf("\nCommand Options : \n");
5571 			ext_print_help_menu();
5572 			continue;
5573 		}
5574 		switch (buf[0]) {
5575 			case 'a':
5576 				add_logical_drive();
5577 				break;
5578 			case 'd':
5579 				delete_logical_drive();
5580 				break;
5581 			case 'h':
5582 				ext_print_help_menu();
5583 				break;
5584 			case 'i':
5585 				ext_change_logical_drive_id();
5586 				break;
5587 			case 'p':
5588 				ext_print_logical_drive_layout();
5589 				break;
5590 			case 'r':
5591 				printf(CLR_SCR);
5592 				return;
5593 			default : /* NOTREACHED */
5594 				break;
5595 		}
5596 	}
5597 }
5598 #endif
5599