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