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