xref: /illumos-gate/usr/src/cmd/fdisk/fdisk.c (revision 13b70267)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 1992, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright 2018 OmniOS Community Edition (OmniOSce) Association.
25  */
26 
27 /*	Copyright (c) 1990, 1991 UNIX System Laboratories, Inc.	*/
28 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989, 1990 AT&T	*/
29 /*	  All Rights Reserved	*/
30 
31 /*	Copyright (c) 1987, 1988 Microsoft Corporation	*/
32 /*	  All Rights Reserved	*/
33 
34 /*
35  * PROGRAM: fdisk(1M)
36  * This program reads the partition table on the specified device and
37  * also reads the drive parameters. The user can perform various
38  * operations from a supplied menu or from the command line. Diagnostic
39  * options are also available.
40  */
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <ctype.h>
48 #include <sys/stat.h>
49 #include <sys/types.h>
50 #include <limits.h>
51 #include <sys/param.h>
52 #include <sys/systeminfo.h>
53 #include <sys/efi_partition.h>
54 #include <sys/byteorder.h>
55 #include <sys/systeminfo.h>
56 
57 #include <sys/dktp/fdisk.h>
58 #include <sys/dkio.h>
59 #include <sys/vtoc.h>
60 #ifdef i386
61 #include <sys/tty.h>
62 #include <libfdisk.h>
63 #endif
64 
65 #define	CLR_SCR ""
66 #define	CLR_LIN ""
67 #define	HOME "" \
68 	""
69 #define	Q_LINE ""
70 
71 #ifdef i386
72 #define	W_LINE ""
73 #else
74 #define	W_LINE ""
75 #endif
76 
77 #define	E_LINE ""
78 
79 #ifdef i386
80 #define	M_LINE "" \
81 	""
82 #else
83 #define	M_LINE "" \
84 	""
85 #endif
86 
87 #define	T_LINE ""
88 
89 #define	DEFAULT_PATH			"/dev/rdsk/"
90 #define	DEFAULT_MASTER_BOOT_FILE	"/boot/pmbr"
91 
92 #define	DK_MAX_2TB	UINT32_MAX	/* Max # of sectors in 2TB */
93 
94 /* for clear_vtoc() */
95 #define	OLD		0
96 #define	NEW		1
97 
98 /* readvtoc/writevtoc return codes */
99 #define	VTOC_OK		0	/* Good VTOC */
100 #define	VTOC_INVAL	1	/* invalid VTOC */
101 #define	VTOC_NOTSUP	2	/* operation not supported - EFI label */
102 #define	VTOC_RWERR	3	/* couldn't read or write VTOC */
103 
104 /*
105  * Support for fdisk(1M) on the SPARC platform
106  *	In order to convert little endian values to big endian for SPARC,
107  *	byte/short and long values must be swapped.
108  *	These swapping macros will be used to access information in the
109  *	mboot and ipart structures.
110  */
111 
112 #ifdef sparc
113 #define	les(val)	((((val)&0xFF)<<8)|(((val)>>8)&0xFF))
114 #define	lel(val)	(((unsigned)(les((val)&0x0000FFFF))<<16) | \
115 			    (les((unsigned)((val)&0xffff0000)>>16)))
116 #else
117 #define	les(val)	(val)
118 #define	lel(val)	(val)
119 #endif
120 
121 #if defined(_SUNOS_VTOC_16)
122 #define	VTOC_OFFSET	1
123 #elif defined(_SUNOS_VTOC_8)
124 #define	VTOC_OFFSET	0
125 #else
126 #error No VTOC format defined.
127 #endif
128 
129 #ifdef i386
130 #define	FDISK_KB	(1024)
131 #define	FDISK_MB	(FDISK_KB * 1024)
132 #define	FDISK_GB	(FDISK_MB * 1024)
133 #define	TRUE	1
134 
135 #define	FDISK_MAX_VALID_PART_ID	255
136 #define	FDISK_MAX_VALID_PART_NUM_DIGITS	2
137 #define	FDISK_MAX_VALID_PART_ID_DIGITS	3
138 
139 /* Maximum number of digits for a valid partition size */
140 #define	FDISK_MAX_VALID_CYL_NUM_DIGITS	10
141 
142 /* Minimum partition size in cylinders */
143 #define	FDISK_MIN_PART_SIZE	1
144 #endif
145 
146 static char Usage[] = "Usage: fdisk\n"
147 "[ -A id:act:bhead:bsect:bcyl:ehead:esect:ecyl:rsect:numsect ]\n"
148 "[ -b masterboot ]\n"
149 "[ -D id:act:bhead:bsect:bcyl:ehead:esect:ecyl:rsect:numsect ]\n"
150 "[ -E [slot:active] ]\n"
151 "[ -F fdisk_file ] [ -h ] [ -o offset ] [ -P fill_patt ] [ -s size ]\n"
152 "[ -S geom_file ] [ [ -v ] -W { creat_fdisk_file | - } ]\n"
153 "[ -w | r | d | n | I | B | g | G | R | t | T ] rdevice";
154 
155 static char Usage1[] = "    Partition options:\n"
156 "	-A id:act:bhead:bsect:bcyl:ehead:esect:ecyl:rsect:numsect\n"
157 "		Create a partition with specific attributes:\n"
158 "		id      = system id number (fdisk.h) for the partition type\n"
159 "		act     = active partition flag (0 is off and 128 is on)\n"
160 "		bhead   = beginning head for start of partition\n"
161 "		bsect   = beginning sector for start of partition\n"
162 "		bcyl    = beginning cylinder for start of partition\n"
163 "		ehead   = ending head for end of partition\n"
164 "		esect   = ending sector for end of partition\n"
165 "		ecyl    = ending cylinder for end of partition\n"
166 "		rsect   = sector number from start of disk for\n"
167 "			  start of partition\n"
168 "		numsect = partition size in sectors\n"
169 "	-b master_boot\n"
170 "		Use master_boot as the master boot file.\n"
171 "	-B	Create one Solaris partition that uses the entire disk.\n"
172 "	-D id:act:bhead:bsect:bcyl:ehead:esect:ecyl:rsect:numsect\n"
173 "		Delete a partition. See attribute definitions for -A.\n"
174 "	-E [slot:active]\n"
175 "		Create an EFI partition that uses the entire disk.\n"
176 "	-F fdisk_file\n"
177 "		Use fdisk_file to initialize on-line fdisk table.\n"
178 "	-I	Forego device checks. Generate a file image of what would go\n"
179 "		on a disk using the geometry specified with the -S option.\n"
180 "	-n	Do not run in interactive mode.\n"
181 "	-R	Open the disk device as read-only.\n"
182 "	-t	Check and adjust VTOC to be consistent with fdisk table.\n"
183 "		VTOC slices exceeding the partition size will be truncated.\n"
184 "	-T	Check and adjust VTOC to be consistent with fdisk table.\n"
185 "		VTOC slices exceeding the partition size will be removed.\n"
186 "	-W fdisk_file\n"
187 "		Write on-disk table to fdisk_file.\n"
188 "	-W -	Write on-disk table to standard output.\n"
189 "	-v	Display virtual geometry. Must be used with the -W option.\n"
190 "    Diagnostic options:\n"
191 "	-d	Activate debug information about progress.\n"
192 "	-g	Write label geometry to standard output:\n"
193 "		PCYL		number of physical cylinders\n"
194 "		NCYL		number of usable cylinders\n"
195 "		ACYL		number of alternate cylinders\n"
196 "		BCYL		cylinder offset\n"
197 "		NHEADS		number of heads\n"
198 "		NSECTORS	number of sectors per track\n"
199 "		SECTSIZ		size of a sector in bytes\n"
200 "	-G	Write physical geometry to standard output (see -g).\n"
201 "	-h	Issue this verbose help message.\n"
202 "	-o offset\n"
203 "		Block offset from start of disk (default 0). Ignored if\n"
204 "		-P # specified.\n"
205 "	-P fill_patt\n"
206 "		Fill disk with pattern fill_patt. fill_patt can be decimal or\n"
207 "		hexadecimal and is used as number for constant long word\n"
208 "		pattern. If fill_patt is \"#\" then pattern of block #\n"
209 "		for each block. Pattern is put in each block as long words\n"
210 "		and fills each block (see -o and -s).\n"
211 "	-r	Read from a disk to stdout (see -o and -s).\n"
212 "	-s size	Number of blocks on which to perform operation (see -o).\n"
213 "	-S geom_file\n"
214 "		Use geom_file to set the label geometry (see -g).\n"
215 "	-w	Write to a disk from stdin (see -o and -s).";
216 
217 static char Ostr[] = "Other OS";
218 static char Dstr[] = "DOS12";
219 static char D16str[] = "DOS16";
220 static char DDstr[] = "DOS-DATA";
221 static char EDstr[] = "EXT-DOS";
222 static char DBstr[] = "DOS-BIG";
223 static char PCstr[] = "PCIX";
224 static char Ustr[] = "UNIX System";
225 static char SUstr[] = "Solaris";
226 static char SU2str[] = "Solaris2";
227 static char X86str[] = "x86 Boot";
228 static char DIAGstr[] = "Diagnostic";
229 static char IFSstr[] = "IFS: NTFS";
230 static char AIXstr[] = "AIX Boot";
231 static char AIXDstr[] = "AIX Data";
232 static char OS2str[] = "OS/2 Boot";
233 static char WINstr[] = "Win95 FAT32";
234 static char EWINstr[] = "Ext Win95";
235 static char FAT95str[] = "FAT16 LBA";
236 static char EXTLstr[] = "EXT LBA";
237 static char LINUXstr[] = "Linux";
238 static char CPMstr[] = "CP/M";
239 static char NOV2str[] = "Netware 286";
240 static char NOVstr[] = "Netware 3.x+";
241 static char QNXstr[] = "QNX 4.x";
242 static char QNX2str[] = "QNX part 2";
243 static char QNX3str[] = "QNX part 3";
244 static char LINNATstr[] = "Linux native";
245 #ifdef i386
246 static char LINSWAPstr[] = "Linux swap";
247 #endif
248 static char NTFSVOL1str[] = "NT volset 1";
249 static char NTFSVOL2str[] = "NT volset 2";
250 static char BSDstr[] = "BSD OS";
251 static char NEXTSTEPstr[] = "NeXTSTEP";
252 static char BSDIFSstr[] = "BSDI FS";
253 static char BSDISWAPstr[] = "BSDI swap";
254 static char Actvstr[] = "Active";
255 static char EFIstr[] = "EFI";
256 static char NAstr[] = "      ";
257 
258 /* All the user options and flags */
259 static char *Dfltdev;			/* name of fixed disk drive */
260 
261 /* Diagnostic options */
262 static int	io_wrt = 0;		/* write stdin to disk (-w) */
263 static int	io_rd = 0;		/* read disk and write stdout (-r) */
264 static char	*io_fatt;		/* user supplied pattern (-P pattern) */
265 static int	io_patt = 0;		/* write pattern to disk (-P pattern) */
266 static int	io_lgeom = 0;		/* get label geometry (-g) */
267 static int	io_pgeom = 0;		/* get drive physical geometry (-G) */
268 static char	*io_sgeom = 0;		/* set label geometry (-S geom_file) */
269 static int	io_readonly = 0;	/* do not write to disk (-R) */
270 
271 /* The -o offset and -s size options specify the area of the disk on */
272 /* which to perform the particular operation; i.e., -P, -r, or -w. */
273 static off_t	io_offset = 0;		/* offset sector (-o offset) */
274 static off_t	io_size = 0;		/* size in sectors (-s size) */
275 
276 /* Partition table flags */
277 static int	v_flag = 0;		/* virtual geometry-HBA flag (-v) */
278 static int	stdo_flag = 0;		/* stdout flag (-W -) */
279 static int	io_fdisk = 0;		/* do fdisk operation */
280 static int	io_ifdisk = 0;		/* interactive partition */
281 static int	io_nifdisk = 0;		/* non-interactive partition (-n) */
282 
283 static int	io_adjt = 0;		/* check/adjust VTOC (truncate (-t)) */
284 static int	io_ADJT = 0;		/* check/adjust VTOC (delete (-T)) */
285 static char	*io_ffdisk = 0;		/* input fdisk file name (-F file) */
286 static char	*io_Wfdisk = 0;		/* output fdisk file name (-W file) */
287 static char	*io_Afdisk = 0;		/* add entry to partition table (-A) */
288 static char	*io_Dfdisk = 0;		/* delete entry from part. table (-D) */
289 
290 static char	*io_mboot = 0;		/* master boot record (-b boot_file) */
291 
292 static struct mboot BootCod;		/* buffer for master boot record */
293 
294 static int	io_wholedisk = 0;	/* use whole disk for Solaris (-B) */
295 static int	io_EFIdisk = 0;		/* use whole disk for EFI (-E) */
296 static int	io_EFIslot = 0;		/* slot in which to place EFI entry */
297 static int	io_EFIactive = 0;	/* mark EFI entry as active */
298 static int	io_debug = 0;		/* activate verbose mode (-d) */
299 static int	io_image = 0;		/* create image using geometry (-I) */
300 
301 static struct mboot *Bootblk;		/* pointer to cut/paste sector zero */
302 static char	*Bootsect;		/* pointer to sector zero buffer */
303 static char	*Nullsect;
304 static struct extvtoc	disk_vtoc;	/* verify VTOC table */
305 static int	vt_inval = 0;
306 static int	no_virtgeom_ioctl = 0;	/* ioctl for virtual geometry failed */
307 static int	no_physgeom_ioctl = 0;	/* ioctl for physical geometry failed */
308 
309 static struct ipart	Table[FD_NUMPART];
310 static struct ipart	Old_Table[FD_NUMPART];
311 static int		skip_verify[FD_NUMPART]; /* special case skip sz chk */
312 
313 /* Disk geometry information */
314 static struct dk_minfo	minfo;
315 static struct dk_geom	disk_geom;
316 
317 static int Dev;			/* fd for open device */
318 
319 static diskaddr_t	dev_capacity;	/* number of blocks on device */
320 static diskaddr_t	chs_capacity;	/* Numcyl_usable * heads * sectors */
321 
322 static int		Numcyl_usable;	/* Number of usable cylinders */
323 					/*  used to limit fdisk to 2TB */
324 
325 /* Physical geometry for the drive */
326 static int	Numcyl;			/* number of cylinders */
327 static int	heads;			/* number of heads */
328 static int	sectors;		/* number of sectors per track */
329 static int	acyl;			/* number of alternate sectors */
330 
331 /* HBA (virtual) geometry for the drive */
332 static int	hba_Numcyl;		/* number of cylinders */
333 static int	hba_heads;		/* number of heads */
334 static int	hba_sectors;		/* number of sectors per track */
335 
336 static int	sectsiz;		/* sector size */
337 
338 /* Load functions for fdisk table modification */
339 #define	LOADFILE	0	/* load fdisk from file */
340 #define	LOADDEL		1	/* delete an fdisk entry */
341 #define	LOADADD		2	/* add an fdisk entry */
342 
343 #define	CBUFLEN 80
344 static char s[CBUFLEN];
345 
346 #ifdef i386
347 /*
348  * Complete list of all the 255 partition types. Some are unknown types
349  * and some entries are known to be unused.
350  *
351  * Courtesy of http://www.win.tue.nl/~aeb/partitions/partition_types-1.html
352  */
353 char *fdisk_part_types[] = {
354 	"Empty",				/* 0 */
355 	"FAT12",				/* 1 */
356 	"XENIX /",				/* 2 */
357 	"XENIX /usr",				/* 3 */
358 	"FAT16 (Upto 32M)",			/* 4 */
359 	"DOS Extended",				/* 5 */
360 	"FAT16 (>32M, HUGEDOS)",		/* 6 */
361 	"IFS: NTFS",				/* 7 */
362 	"AIX Boot/QNX(qny)",			/* 8 */
363 	"AIX Data/QNX(qnz)",			/* 9 */
364 	"OS/2 Boot/Coherent swap",		/* 10 */
365 	"WIN95 FAT32(Upto 2047GB)",		/* 11 */
366 	"WIN95 FAT32(LBA)",			/* 12 */
367 	"Unused",				/* 13 */
368 	"WIN95 FAT16(LBA)",			/* 14 */
369 	"WIN95 Extended(LBA)",			/* 15 */
370 	"OPUS",					/* 16 */
371 	"Hidden FAT12",				/* 17 */
372 	"Diagnostic",				/* 18 */
373 	"Unknown",				/* 19 */
374 	"Hidden FAT16(Upto 32M)",		/* 20 */
375 	"Unknown",				/* 21 */
376 	"Hidden FAT16(>=32M)",			/* 22 */
377 	"Hidden IFS: HPFS",			/* 23 */
378 	"AST SmartSleep Partition",		/* 24 */
379 	"Unused/Willowtech Photon",		/* 25 */
380 	"Unknown",				/* 26 */
381 	"Hidden FAT32",				/* 27 */
382 	"Hidden FAT32(LBA)",			/* 28 */
383 	"Unused",				/* 29 */
384 	"Hidden FAT16(LBA)",			/* 30 */
385 	"Unknown",				/* 31 */
386 	"Unused/OSF1",				/* 32 */
387 	"Reserved/FSo2(Oxygen FS)",		/* 33 */
388 	"Unused/(Oxygen EXT)",			/* 34 */
389 	"Reserved",				/* 35 */
390 	"NEC DOS 3.x",				/* 36 */
391 	"Unknown",				/* 37 */
392 	"Reserved",				/* 38 */
393 	"Unknown",				/* 39 */
394 	"Unknown",				/* 40 */
395 	"Unknown",				/* 41 */
396 	"AtheOS File System",			/* 42 */
397 	"SyllableSecure",			/* 43 */
398 	"Unknown",				/* 44 */
399 	"Unknown",				/* 45 */
400 	"Unknown",				/* 46 */
401 	"Unknown",				/* 47 */
402 	"Unknown",				/* 48 */
403 	"Reserved",				/* 49 */
404 	"NOS",					/* 50 */
405 	"Reserved",				/* 51 */
406 	"Reserved",				/* 52 */
407 	"JFS on OS/2",				/* 53 */
408 	"Reserved",				/* 54 */
409 	"Unknown",				/* 55 */
410 	"THEOS 3.2 2GB",			/* 56 */
411 	"Plan9/THEOS 4",			/* 57 */
412 	"THEOS 4 4GB",				/* 58 */
413 	"THEOS 4 Extended",			/* 59 */
414 	"PartitionMagic Recovery",		/* 60 */
415 	"Hidden NetWare",			/* 61 */
416 	"Unknown",				/* 62 */
417 	"Unknown",				/* 63 */
418 	"Venix 80286",				/* 64 */
419 	"MINIX/PPC PReP Boot",			/* 65 */
420 	"Win2K Dynamic Disk/SFS(DOS)",		/* 66 */
421 	"Linux+DRDOS shared",			/* 67 */
422 	"GoBack partition",			/* 68 */
423 	"Boot-US boot manager",			/* 69 */
424 	"EUMEL/Elan",				/* 70 */
425 	"EUMEL/Elan",				/* 71 */
426 	"EUMEL/Elan",				/* 72 */
427 	"Unknown",				/* 73 */
428 	"ALFS/THIN FS for DOS",			/* 74 */
429 	"Unknown",				/* 75 */
430 	"Oberon partition",			/* 76 */
431 	"QNX 4,x",				/* 77 */
432 	"QNX 4,x 2nd Part",			/* 78 */
433 	"QNX 4,x 3rd Part",			/* 79 */
434 	"OnTrack DM R/O, Lynx RTOS",		/* 80 */
435 	"OnTrack DM R/W, Novell",		/* 81 */
436 	"CP/M",					/* 82 */
437 	"Disk Manager 6.0 Aux3",		/* 83 */
438 	"Disk Manager 6.0 DDO",			/* 84 */
439 	"EZ-Drive",				/* 85 */
440 	"Golden Bow VFeature/AT&T MS-DOS",	/* 86 */
441 	"DrivePro",				/* 87 */
442 	"Unknown",				/* 88 */
443 	"Unknown",				/* 89 */
444 	"Unknown",				/* 90 */
445 	"Unknown",				/* 91 */
446 	"Priam EDisk",				/* 92 */
447 	"Unknown",				/* 93 */
448 	"Unknown",				/* 94 */
449 	"Unknown",				/* 95 */
450 	"Unknown",				/* 96 */
451 	"SpeedStor",				/* 97 */
452 	"Unknown",				/* 98 */
453 	"Unix SysV, Mach, GNU Hurd",		/* 99 */
454 	"PC-ARMOUR, Netware 286",		/* 100 */
455 	"Netware 386",				/* 101 */
456 	"Netware SMS",				/* 102 */
457 	"Novell",				/* 103 */
458 	"Novell",				/* 104 */
459 	"Netware NSS",				/* 105 */
460 	"Unknown",				/* 106 */
461 	"Unknown",				/* 107 */
462 	"Unknown",				/* 108 */
463 	"Unknown",				/* 109 */
464 	"Unknown",				/* 110 */
465 	"Unknown",				/* 111 */
466 	"DiskSecure Multi-Boot",		/* 112 */
467 	"Reserved",				/* 113 */
468 	"Unknown",				/* 114 */
469 	"Reserved",				/* 115 */
470 	"Scramdisk partition",			/* 116 */
471 	"IBM PC/IX",				/* 117 */
472 	"Reserved",				/* 118 */
473 	"M2FS/M2CS,Netware VNDI",		/* 119 */
474 	"XOSL FS",				/* 120 */
475 	"Unknown",				/* 121 */
476 	"Unknown",				/* 122 */
477 	"Unknown",				/* 123 */
478 	"Unknown",				/* 124 */
479 	"Unknown",				/* 125 */
480 	"Unused",				/* 126 */
481 	"Unused",				/* 127 */
482 	"MINIX until 1.4a",			/* 128 */
483 	"MINIX since 1.4b, early Linux",	/* 129 */
484 	"Solaris/Linux swap",			/* 130 */
485 	"Linux native",				/* 131 */
486 	"OS/2 hidden,Win Hibernation",		/* 132 */
487 	"Linux extended",			/* 133 */
488 	"Old Linux RAID,NT FAT16 RAID",		/* 134 */
489 	"NTFS volume set",			/* 135 */
490 	"Linux plaintext part table",		/* 136 */
491 	"Unknown",				/* 137 */
492 	"Linux Kernel Partition",		/* 138 */
493 	"Fault Tolerant FAT32 volume",		/* 139 */
494 	"Fault Tolerant FAT32 volume",		/* 140 */
495 	"Free FDISK hidden PDOS FAT12",		/* 141 */
496 	"Linux LVM partition",			/* 142 */
497 	"Unknown",				/* 143 */
498 	"Free FDISK hidden PDOS FAT16",		/* 144 */
499 	"Free FDISK hidden DOS EXT",		/* 145 */
500 	"Free FDISK hidden FAT16 Large",	/* 146 */
501 	"Hidden Linux native, Amoeba",		/* 147 */
502 	"Amoeba Bad Block Table",		/* 148 */
503 	"MIT EXOPC Native",			/* 149 */
504 	"Unknown",				/* 150 */
505 	"Free FDISK hidden PDOS FAT32",		/* 151 */
506 	"Free FDISK hidden FAT32 LBA",		/* 152 */
507 	"DCE376 logical drive",			/* 153 */
508 	"Free FDISK hidden FAT16 LBA",		/* 154 */
509 	"Free FDISK hidden DOS EXT",		/* 155 */
510 	"Unknown",				/* 156 */
511 	"Unknown",				/* 157 */
512 	"Unknown",				/* 158 */
513 	"BSD/OS",				/* 159 */
514 	"Laptop hibernation",			/* 160 */
515 	"Laptop hibernate,HP SpeedStor",	/* 161 */
516 	"Unknown",				/* 162 */
517 	"HP SpeedStor",				/* 163 */
518 	"HP SpeedStor",				/* 164 */
519 	"BSD/386,386BSD,NetBSD,FreeBSD",	/* 165 */
520 	"OpenBSD,HP SpeedStor",			/* 166 */
521 	"NeXTStep",				/* 167 */
522 	"Mac OS-X",				/* 168 */
523 	"NetBSD",				/* 169 */
524 	"Olivetti FAT12 1.44MB Service",	/* 170 */
525 	"Mac OS-X Boot",			/* 171 */
526 	"Unknown",				/* 172 */
527 	"Unknown",				/* 173 */
528 	"ShagOS filesystem",			/* 174 */
529 	"ShagOS swap",				/* 175 */
530 	"BootStar Dummy",			/* 176 */
531 	"HP SpeedStor",				/* 177 */
532 	"Unknown",				/* 178 */
533 	"HP SpeedStor",				/* 179 */
534 	"HP SpeedStor",				/* 180 */
535 	"Unknown",				/* 181 */
536 	"Corrupted FAT16 NT Mirror Set",	/* 182 */
537 	"Corrupted NTFS NT Mirror Set",		/* 183 */
538 	"Old BSDI BSD/386 swap",		/* 184 */
539 	"Unknown",				/* 185 */
540 	"Unknown",				/* 186 */
541 	"Boot Wizard hidden",			/* 187 */
542 	"Unknown",				/* 188 */
543 	"Unknown",				/* 189 */
544 	"Solaris x86 boot",			/* 190 */
545 	"Solaris2",				/* 191 */
546 	"REAL/32 or Novell DOS secured",	/* 192 */
547 	"DRDOS/secured(FAT12)",			/* 193 */
548 	"Hidden Linux",				/* 194 */
549 	"Hidden Linux swap",			/* 195 */
550 	"DRDOS/secured(FAT16,< 32M)",		/* 196 */
551 	"DRDOS/secured(Extended)",		/* 197 */
552 	"NT corrupted FAT16 volume",		/* 198 */
553 	"NT corrupted NTFS volume",		/* 199 */
554 	"DRDOS8.0+",				/* 200 */
555 	"DRDOS8.0+",				/* 201 */
556 	"DRDOS8.0+",				/* 202 */
557 	"DRDOS7.04+ secured FAT32(CHS)",	/* 203 */
558 	"DRDOS7.04+ secured FAT32(LBA)",	/* 204 */
559 	"CTOS Memdump",				/* 205 */
560 	"DRDOS7.04+ FAT16X(LBA)",		/* 206 */
561 	"DRDOS7.04+ secure EXT DOS(LBA)",	/* 207 */
562 	"REAL/32 secure big, MDOS",		/* 208 */
563 	"Old MDOS secure FAT12",		/* 209 */
564 	"Unknown",				/* 210 */
565 	"Unknown",				/* 211 */
566 	"Old MDOS secure FAT16 <32M",		/* 212 */
567 	"Old MDOS secure EXT",			/* 213 */
568 	"Old MDOS secure FAT16 >=32M",		/* 214 */
569 	"Unknown",				/* 215 */
570 	"CP/M-86",				/* 216 */
571 	"Unknown",				/* 217 */
572 	"Non-FS Data",				/* 218 */
573 	"CP/M,Concurrent DOS,CTOS",		/* 219 */
574 	"Unknown",				/* 220 */
575 	"Hidden CTOS memdump",			/* 221 */
576 	"Dell PowerEdge utilities(FAT)",	/* 222 */
577 	"DG/UX virtual disk manager",		/* 223 */
578 	"ST AVFS(STMicroelectronics)",		/* 224 */
579 	"SpeedStor 12-bit FAT EXT",		/* 225 */
580 	"Unknown",				/* 226 */
581 	"SpeedStor",				/* 227 */
582 	"SpeedStor 16-bit FAT EXT",		/* 228 */
583 	"Tandy MSDOS",				/* 229 */
584 	"Storage Dimensions SpeedStor",		/* 230 */
585 	"Unknown",				/* 231 */
586 	"Unknown",				/* 232 */
587 	"Unknown",				/* 233 */
588 	"Unknown",				/* 234 */
589 	"BeOS BFS",				/* 235 */
590 	"SkyOS SkyFS",				/* 236 */
591 	"Unused",				/* 237 */
592 	"EFI Header Indicator",			/* 238 */
593 	"EFI Filesystem",			/* 239 */
594 	"Linux/PA-RISC boot loader",		/* 240 */
595 	"SpeedStor",				/* 241 */
596 	"DOS 3.3+ secondary",			/* 242 */
597 	"SpeedStor Reserved",			/* 243 */
598 	"SpeedStor Large",			/* 244 */
599 	"Prologue multi-volume",		/* 245 */
600 	"SpeedStor",				/* 246 */
601 	"Unused",				/* 247 */
602 	"Unknown",				/* 248 */
603 	"pCache",				/* 249 */
604 	"Bochs",				/* 250 */
605 	"VMware File System",			/* 251 */
606 	"VMware swap",				/* 252 */
607 	"Linux raid autodetect",		/* 253 */
608 	"NT Disk Administrator hidden",		/* 254 */
609 	"Xenix Bad Block Table"			/* 255 */
610 };
611 
612 /* Allowed extended partition menu options */
613 static char ext_part_menu_opts[] = "adhipr";
614 
615 /*
616  * Structure holding all information about the extended partition
617  * NOTE : As of now, there will be just one instance of ext_part_t, since most
618  * known systems allow only one extended dos partition per disk.
619  */
620 static ext_part_t *epp;
621 #endif
622 
623 static void update_disk_and_exit(boolean_t table_changed);
624 int main(int argc, char *argv[]);
625 static int read_geom(char *sgeom);
626 static void dev_mboot_read(void);
627 static void dev_mboot_write(off_t sect, char *buff, int bootsiz);
628 static void mboot_read(void);
629 static void fill_patt(void);
630 static void abs_read(void);
631 static void abs_write(void);
632 static void load(int funct, char *file);
633 static void Set_Table_CHS_Values(int ti);
634 static int nopartdefined();
635 static int insert_tbl(int id, int act,
636     int bhead, int bsect, int bcyl,
637     int ehead, int esect, int ecyl,
638     uint32_t rsect, uint32_t numsect, int startindex);
639 static int entry_from_old_table(int id, int act,
640     int bhead, int bsect, int bcyl,
641     int ehead, int esect, int ecyl,
642     uint32_t rsect, uint32_t numsect, int startindex);
643 static int verify_tbl(void);
644 static int pars_fdisk(char *line,
645     int *id, int *act,
646     int *bhead, int *bsect, int *bcyl,
647     int *ehead, int *esect, int *ecyl,
648     uint32_t *rsect, uint32_t *numsect);
649 static int validate_part(int id, uint32_t rsect, uint32_t numsect);
650 static void stage0(void);
651 static int pcreate(void);
652 static int specify(uchar_t tsystid);
653 static void dispmenu(void);
654 static int pchange(void);
655 static int ppartid(void);
656 static char pdelete(void);
657 static void rm_blanks(char *s);
658 static int getcyl(void);
659 static void disptbl(void);
660 static void print_Table(void);
661 static void copy_Table_to_Old_Table(void);
662 static void nulltbl(void);
663 static void copy_Bootblk_to_Table(void);
664 static void fill_ipart(char *bootptr, struct ipart *partp);
665 #ifdef sparc
666 uchar_t getbyte(char **bp);
667 uint32_t getlong(char **bp);
668 #endif
669 static void copy_Table_to_Bootblk(void);
670 static int TableChanged(void);
671 static void ffile_write(char *file);
672 static void fix_slice(void);
673 static int yesno(void);
674 static int readvtoc(void);
675 static int writevtoc(void);
676 static int efi_ioctl(int fd, int cmd, dk_efi_t *dk_ioc);
677 static int clear_efi(void);
678 static void clear_vtoc(int table, int part);
679 static int lecture_and_query(char *warning, char *devname);
680 static void sanity_check_provided_device(char *devname, int fd);
681 static char *get_node(char *devname);
682 static int efi_create(void);
683 
684 #ifdef i386
685 static void id_to_name(uchar_t sysid, char *buffer);
686 static void ext_read_input(char *buf);
687 static int ext_read_options(char *buf);
688 static int ext_invalid_option(char ch);
689 static void ext_read_valid_part_num(int *pno);
690 static void ext_read_valid_part_id(uchar_t *partid);
691 static int ext_read_valid_partition_start(uint32_t *begsec);
692 static void ext_read_valid_partition_size(uint32_t begsec, uint32_t *endsec);
693 static void ext_part_menu();
694 static void add_logical_drive();
695 static void delete_logical_drive();
696 static void ext_print_help_menu();
697 static void ext_change_logical_drive_id();
698 static void ext_print_part_types();
699 static void ext_print_logical_drive_layout();
700 static void preach_and_continue();
701 #ifdef DEBUG
702 static void ext_print_logdrive_layout_debug();
703 #endif	/* DEBUG */
704 #endif	/* i386 */
705 
706 /*
707  * This function is called only during the non-interactive mode.
708  * It is touchy and does not tolerate any errors. If there are
709  * mounted logical drives, changes to the partition table
710  * are disallowed.
711  */
712 static void
update_disk_and_exit(boolean_t table_changed)713 update_disk_and_exit(boolean_t table_changed)
714 {
715 #ifdef i386
716 	int rval;
717 #endif
718 	if (table_changed) {
719 		/*
720 		 * Copy the new table back to the sector buffer
721 		 * and write it to disk
722 		 */
723 		copy_Table_to_Bootblk();
724 		dev_mboot_write(0, Bootsect, sectsiz);
725 	}
726 
727 	/* If the VTOC table is wrong fix it (truncation only) */
728 	if (io_adjt)
729 		fix_slice();
730 
731 #ifdef i386
732 	if (!io_readonly) {
733 		rval = fdisk_commit_ext_part(epp);
734 		switch (rval) {
735 			case FDISK_SUCCESS:
736 				/* Success */
737 				break;
738 			case FDISK_ENOEXTPART:
739 				/* Nothing to do */
740 				break;
741 			default:
742 				(void) fprintf(stderr, "Error in"
743 				    " fdisk_commit_ext_part\n");
744 				exit(rval);
745 		}
746 	}
747 	libfdisk_fini(&epp);
748 #endif
749 	exit(0);
750 }
751 
752 /*
753  * main
754  * Process command-line options.
755  */
756 int
main(int argc,char * argv[])757 main(int argc, char *argv[])
758 {
759 	int c, i;
760 	extern	int optind;
761 	extern	char *optarg;
762 	int	errflg = 0;
763 	int	diag_cnt = 0;
764 	int openmode;
765 #ifdef i386
766 	int rval;
767 	int lf_op_flag = 0;
768 #endif
769 
770 	setbuf(stderr, 0);	/* so all output gets out on exit */
771 	setbuf(stdout, 0);
772 
773 	/* Process the options. */
774 	while ((c = getopt(argc, argv, "o:s:P:F:b:A:D:W:S:tTIhwvrndgGRBE:"))
775 	    != EOF) {
776 		switch (c) {
777 
778 			case 'o':
779 				io_offset = (off_t)strtoull(optarg, 0, 0);
780 				continue;
781 			case 's':
782 				io_size = (off_t)strtoull(optarg, 0, 0);
783 				continue;
784 			case 'P':
785 				diag_cnt++;
786 				io_patt++;
787 				io_fatt = optarg;
788 				continue;
789 			case 'w':
790 				diag_cnt++;
791 				io_wrt++;
792 				continue;
793 			case 'r':
794 				diag_cnt++;
795 				io_rd++;
796 				continue;
797 			case 'd':
798 				io_debug++;
799 				continue;
800 			case 'I':
801 				io_image++;
802 				continue;
803 			case 'R':
804 				io_readonly++;
805 				continue;
806 			case 'S':
807 				diag_cnt++;
808 				io_sgeom = optarg;
809 				continue;
810 			case 'T':
811 				io_ADJT++;
812 				/* FALLTHROUGH */
813 			case 't':
814 				io_adjt++;
815 				continue;
816 			case 'B':
817 				io_wholedisk++;
818 				io_fdisk++;
819 				continue;
820 			case 'E':
821 				if (sscanf(optarg, "%d:%d",
822 				    &io_EFIslot, &io_EFIactive) != 2) {
823 					io_EFIslot = io_EFIactive = 0;
824 					optind--;
825 				}
826 				io_EFIdisk++;
827 				io_fdisk++;
828 				continue;
829 			case 'g':
830 				diag_cnt++;
831 				io_lgeom++;
832 				continue;
833 			case 'G':
834 				diag_cnt++;
835 				io_pgeom++;
836 				continue;
837 			case 'n':
838 				io_nifdisk++;
839 				io_fdisk++;
840 				continue;
841 			case 'F':
842 				io_fdisk++;
843 				io_ffdisk = optarg;
844 				continue;
845 			case 'b':
846 				io_mboot = optarg;
847 				continue;
848 			case 'W':
849 				/*
850 				 * If '-' is the -W argument, then write
851 				 * to standard output, otherwise write
852 				 * to the specified file.
853 				 */
854 				if (strncmp(optarg, "-", 1) == 0)
855 					stdo_flag = 1;
856 				else
857 					io_Wfdisk = optarg;
858 				io_fdisk++;
859 				continue;
860 			case 'A':
861 				io_fdisk++;
862 				io_Afdisk = optarg;
863 				continue;
864 			case 'D':
865 				io_fdisk++;
866 				io_Dfdisk = optarg;
867 				continue;
868 			case 'h':
869 				(void) fprintf(stderr, "%s\n", Usage);
870 				(void) fprintf(stderr, "%s\n", Usage1);
871 				exit(0);
872 				/* FALLTHROUGH */
873 			case 'v':
874 				v_flag = 1;
875 				continue;
876 			case '?':
877 				errflg++;
878 				break;
879 		}
880 		break;
881 	}
882 
883 	if (io_image && io_sgeom && diag_cnt == 1) {
884 		diag_cnt = 0;
885 	}
886 
887 	/* User option checking */
888 
889 	/* By default, run in interactive mode */
890 	if (!io_fdisk && !diag_cnt && !io_nifdisk) {
891 		io_ifdisk++;
892 		io_fdisk++;
893 	}
894 	if (((io_fdisk || io_adjt) && diag_cnt) || (diag_cnt > 1)) {
895 		errflg++;
896 	}
897 
898 	/* Was any error detected? */
899 	if (errflg || argc == optind) {
900 		(void) fprintf(stderr, "%s\n", Usage);
901 		(void) fprintf(stderr,
902 		    "\nDetailed help is available with the -h option.\n");
903 		exit(2);
904 	}
905 
906 	/* Figure out the correct device node to open */
907 	Dfltdev = get_node(argv[optind]);
908 
909 	if (io_readonly)
910 		openmode = O_RDONLY;
911 	else
912 		openmode = O_RDWR|O_CREAT;
913 
914 	if ((Dev = open(Dfltdev, openmode, 0666)) == -1) {
915 		(void) fprintf(stderr,
916 		    "fdisk: Cannot open device %s.\n",
917 		    Dfltdev);
918 		exit(1);
919 	}
920 	/*
921 	 * not all disk (or disklike) drivers support DKIOCGMEDIAINFO
922 	 * in that case leave the minfo structure zeroed
923 	 */
924 	if (ioctl(Dev, DKIOCGMEDIAINFO, &minfo)) {
925 		(void) memset(&minfo, 0, sizeof (minfo));
926 	}
927 
928 	/* Get the disk geometry */
929 	if (!io_image) {
930 		/* Get disk's HBA (virtual) geometry */
931 		errno = 0;
932 		if (ioctl(Dev, DKIOCG_VIRTGEOM, &disk_geom)) {
933 
934 			/*
935 			 * If ioctl isn't implemented on this platform, then
936 			 * turn off flag to print out virtual geometry (-v),
937 			 * otherwise use the virtual geometry.
938 			 */
939 
940 			if (errno == ENOTTY) {
941 				v_flag = 0;
942 				no_virtgeom_ioctl = 1;
943 			} else if (errno == EINVAL) {
944 				/*
945 				 * This means that the ioctl exists, but
946 				 * is invalid for this disk, meaning the
947 				 * disk doesn't have an HBA geometry
948 				 * (like, say, it's larger than 8GB).
949 				 */
950 				v_flag = 0;
951 				hba_Numcyl = hba_heads = hba_sectors = 0;
952 			} else {
953 				(void) fprintf(stderr,
954 				    "%s: Cannot get virtual disk geometry.\n",
955 				    argv[optind]);
956 				exit(1);
957 			}
958 		} else {
959 			/* save virtual geometry values obtained by ioctl */
960 			hba_Numcyl = disk_geom.dkg_ncyl;
961 			hba_heads = disk_geom.dkg_nhead;
962 			hba_sectors = disk_geom.dkg_nsect;
963 		}
964 
965 		errno = 0;
966 		if (ioctl(Dev, DKIOCG_PHYGEOM, &disk_geom)) {
967 			if (errno == ENOTTY) {
968 				no_physgeom_ioctl = 1;
969 			} else {
970 				(void) fprintf(stderr,
971 				    "%s: Cannot get physical disk geometry.\n",
972 				    argv[optind]);
973 				exit(1);
974 			}
975 
976 		}
977 		/*
978 		 * Call DKIOCGGEOM if the ioctls for physical and virtual
979 		 * geometry fail. Get both from this generic call.
980 		 */
981 		if (no_virtgeom_ioctl && no_physgeom_ioctl) {
982 			errno = 0;
983 			if (ioctl(Dev, DKIOCGGEOM, &disk_geom)) {
984 				(void) fprintf(stderr,
985 				    "%s: Cannot get disk label geometry.\n",
986 				    argv[optind]);
987 				exit(1);
988 			}
989 		}
990 
991 		Numcyl = disk_geom.dkg_ncyl;
992 		heads = disk_geom.dkg_nhead;
993 		sectors = disk_geom.dkg_nsect;
994 
995 		if (minfo.dki_lbsize != 0)
996 			sectsiz = minfo.dki_lbsize;
997 		else
998 			sectsiz = 512;
999 
1000 		acyl = disk_geom.dkg_acyl;
1001 
1002 		/*
1003 		 * if hba geometry was not set by DKIOC_VIRTGEOM
1004 		 * or we got an invalid hba geometry
1005 		 * then set hba geometry based on max values
1006 		 */
1007 		if (no_virtgeom_ioctl ||
1008 		    disk_geom.dkg_ncyl == 0 ||
1009 		    disk_geom.dkg_nhead == 0 ||
1010 		    disk_geom.dkg_nsect == 0 ||
1011 		    disk_geom.dkg_ncyl > MAX_CYL ||
1012 		    disk_geom.dkg_nhead > MAX_HEAD + 1 ||
1013 		    disk_geom.dkg_nsect > MAX_SECT) {
1014 
1015 			/*
1016 			 * turn off flag to print out virtual geometry (-v)
1017 			 */
1018 			v_flag = 0;
1019 			hba_sectors	= MAX_SECT;
1020 			hba_heads	= MAX_HEAD + 1;
1021 			hba_Numcyl	= (Numcyl * heads * sectors) /
1022 			    (hba_sectors * hba_heads);
1023 		}
1024 
1025 		if (io_debug) {
1026 			(void) fprintf(stderr, "Physical Geometry:\n");
1027 			(void) fprintf(stderr,
1028 			    "  cylinders[%d] heads[%d] sectors[%d]\n"
1029 			    "  sector size[%d] blocks[%d] mbytes[%d]\n",
1030 			    Numcyl,
1031 			    heads,
1032 			    sectors,
1033 			    sectsiz,
1034 			    Numcyl * heads * sectors,
1035 			    (Numcyl * heads * sectors * sectsiz) / 1048576);
1036 			(void) fprintf(stderr, "Virtual (HBA) Geometry:\n");
1037 			(void) fprintf(stderr,
1038 			    "  cylinders[%d] heads[%d] sectors[%d]\n"
1039 			    "  sector size[%d] blocks[%d] mbytes[%d]\n",
1040 			    hba_Numcyl,
1041 			    hba_heads,
1042 			    hba_sectors,
1043 			    sectsiz,
1044 			    hba_Numcyl * hba_heads * hba_sectors,
1045 			    (hba_Numcyl * hba_heads * hba_sectors * sectsiz) /
1046 			    1048576);
1047 		}
1048 	}
1049 
1050 	/* If user has requested a geometry report just do it and exit */
1051 	if (io_lgeom) {
1052 		if (ioctl(Dev, DKIOCGGEOM, &disk_geom)) {
1053 			(void) fprintf(stderr,
1054 			    "%s: Cannot get disk label geometry.\n",
1055 			    argv[optind]);
1056 			exit(1);
1057 		}
1058 		Numcyl = disk_geom.dkg_ncyl;
1059 		heads = disk_geom.dkg_nhead;
1060 		sectors = disk_geom.dkg_nsect;
1061 		if (minfo.dki_lbsize != 0)
1062 			sectsiz = minfo.dki_lbsize;
1063 		else
1064 			sectsiz = 512;
1065 
1066 		acyl = disk_geom.dkg_acyl;
1067 		(void) printf("* Label geometry for device %s\n", Dfltdev);
1068 		(void) printf(
1069 		    "* PCYL     NCYL     ACYL     BCYL     NHEAD NSECT"
1070 		    " SECSIZ\n");
1071 		(void) printf("  %-8d %-8d %-8d %-8d %-5d %-5d %-6d\n",
1072 		    Numcyl,
1073 		    disk_geom.dkg_ncyl,
1074 		    disk_geom.dkg_acyl,
1075 		    disk_geom.dkg_bcyl,
1076 		    heads,
1077 		    sectors,
1078 		    sectsiz);
1079 		exit(0);
1080 	} else if (io_pgeom) {
1081 		if (ioctl(Dev, DKIOCG_PHYGEOM, &disk_geom)) {
1082 			(void) fprintf(stderr,
1083 			    "%s: Cannot get physical disk geometry.\n",
1084 			    argv[optind]);
1085 			exit(1);
1086 		}
1087 		(void) printf("* Physical geometry for device %s\n", Dfltdev);
1088 		(void) printf(
1089 		    "* PCYL     NCYL     ACYL     BCYL     NHEAD NSECT"
1090 		    " SECSIZ\n");
1091 		(void) printf("  %-8d %-8d %-8d %-8d %-5d %-5d %-6d\n",
1092 		    disk_geom.dkg_pcyl,
1093 		    disk_geom.dkg_ncyl,
1094 		    disk_geom.dkg_acyl,
1095 		    disk_geom.dkg_bcyl,
1096 		    disk_geom.dkg_nhead,
1097 		    disk_geom.dkg_nsect,
1098 		    sectsiz);
1099 		exit(0);
1100 	} else if (io_sgeom) {
1101 		if (read_geom(io_sgeom)) {
1102 			exit(1);
1103 		} else if (!io_image) {
1104 			exit(0);
1105 		}
1106 	}
1107 
1108 	/*
1109 	 * some drivers may not support DKIOCGMEDIAINFO
1110 	 * in that case use CHS
1111 	 */
1112 	chs_capacity = (diskaddr_t)Numcyl * heads * sectors;
1113 	dev_capacity = chs_capacity;
1114 	Numcyl_usable = Numcyl;
1115 
1116 	if (chs_capacity > DK_MAX_2TB) {
1117 		/* limit to 2TB */
1118 		Numcyl_usable = DK_MAX_2TB / (heads * sectors);
1119 		chs_capacity = (diskaddr_t)Numcyl_usable * heads * sectors;
1120 	}
1121 
1122 	if (minfo.dki_capacity > 0)
1123 		dev_capacity = minfo.dki_capacity;
1124 
1125 	/* Allocate memory to hold three complete sectors */
1126 	Bootsect = (char *)calloc(3 * sectsiz, 1);
1127 	if (Bootsect == NULL) {
1128 		(void) fprintf(stderr,
1129 		    "fdisk: Unable to obtain enough buffer memory"
1130 		    " (%d bytes).\n",
1131 		    3 * sectsiz);
1132 		exit(1);
1133 	}
1134 
1135 	Nullsect = Bootsect + sectsiz;
1136 	/* Zero out the "NULL" sector */
1137 	for (i = 0; i < sectsiz; i++) {
1138 		Nullsect[i] = 0;
1139 	}
1140 
1141 	/* Find out what the user wants done */
1142 	if (io_rd) {		/* abs disk read */
1143 		abs_read();	/* will not return */
1144 	} else if (io_wrt && !io_readonly) {
1145 		abs_write();	/* will not return */
1146 	} else if (io_patt && !io_readonly) {
1147 		fill_patt();	/* will not return */
1148 	}
1149 
1150 	/* This is the fdisk edit, the real reason for the program.	*/
1151 
1152 	sanity_check_provided_device(Dfltdev, Dev);
1153 
1154 	/* Get the new BOOT program in case we write a new fdisk table */
1155 	mboot_read();
1156 
1157 	/* Read from disk master boot */
1158 	dev_mboot_read();
1159 
1160 	/*
1161 	 * Verify and copy the device's fdisk table. This will be used
1162 	 * as the prototype mboot if the device's mboot looks invalid.
1163 	 */
1164 	Bootblk = (struct mboot *)Bootsect;
1165 	copy_Bootblk_to_Table();
1166 
1167 	/* save away a copy of Table in Old_Table for sensing changes */
1168 	copy_Table_to_Old_Table();
1169 
1170 #ifdef i386
1171 	/*
1172 	 * Read extended partition only when the fdisk table is not
1173 	 * supplied from a file
1174 	 */
1175 	if (!io_ffdisk) {
1176 		lf_op_flag |= FDISK_READ_DISK;
1177 	}
1178 	if ((rval = libfdisk_init(&epp, Dfltdev, &Table[0], lf_op_flag))
1179 	    != FDISK_SUCCESS) {
1180 		switch (rval) {
1181 			/*
1182 			 * FDISK_EBADLOGDRIVE, FDISK_ENOLOGDRIVE and
1183 			 * FDISK_EBADMAGIC can be considered as
1184 			 * soft errors and hence we do not exit
1185 			 */
1186 			case FDISK_EBADLOGDRIVE:
1187 				break;
1188 			case FDISK_ENOLOGDRIVE:
1189 				break;
1190 			case FDISK_EBADMAGIC:
1191 				break;
1192 			case FDISK_ENOVGEOM:
1193 				(void) fprintf(stderr, "Could not get virtual"
1194 				    " geometry for this device\n");
1195 				exit(1);
1196 				break;
1197 			case FDISK_ENOPGEOM:
1198 				(void) fprintf(stderr, "Could not get physical"
1199 				    " geometry for this device\n");
1200 				exit(1);
1201 				break;
1202 			case FDISK_ENOLGEOM:
1203 				(void) fprintf(stderr, "Could not get label"
1204 				    " geometry for this device\n");
1205 				exit(1);
1206 				break;
1207 			default:
1208 				perror("Failed to initialise libfdisk.\n");
1209 				exit(1);
1210 				break;
1211 		}
1212 	}
1213 #endif
1214 
1215 	/* Load fdisk table from specified file (-F fdisk_file) */
1216 	if (io_ffdisk) {
1217 		/* Load and verify user-specified table parameters */
1218 		load(LOADFILE, io_ffdisk);
1219 	}
1220 
1221 	/* Does user want to delete or add an entry? */
1222 	if (io_Dfdisk) {
1223 		load(LOADDEL, io_Dfdisk);
1224 	}
1225 	if (io_Afdisk) {
1226 		load(LOADADD, io_Afdisk);
1227 	}
1228 
1229 	if (!io_ffdisk && !io_Afdisk && !io_Dfdisk) {
1230 		/* Check if there is no fdisk table */
1231 		if (nopartdefined() || io_wholedisk || io_EFIdisk) {
1232 			if (io_ifdisk && !io_wholedisk && !io_EFIdisk) {
1233 				(void) printf(
1234 				    "No fdisk table exists. The default"
1235 				    " partition for the disk is:\n\n"
1236 				    "  a 100%% \"SOLARIS System\" "
1237 				    "partition\n\n"
1238 				    "Type \"y\" to accept the default "
1239 				    "partition,  otherwise type \"n\" to "
1240 				    "edit the\n partition table.\n");
1241 
1242 				if (Numcyl > Numcyl_usable)
1243 					(void) printf("WARNING: Disk is larger"
1244 					    " than 2TB. Solaris partition will"
1245 					    " be limited to 2 TB.\n");
1246 			}
1247 
1248 			/* Edit the partition table as directed */
1249 			if (io_wholedisk ||(io_ifdisk && yesno())) {
1250 
1251 				/* Default scenario */
1252 				nulltbl();
1253 				/* now set up UNIX System partition */
1254 				Table[0].bootid = ACTIVE;
1255 				Table[0].relsect = LE_32(heads * sectors);
1256 
1257 				Table[0].numsect =
1258 				    LE_32((ulong_t)((Numcyl_usable - 1) *
1259 				    heads * sectors));
1260 
1261 				Table[0].systid = SUNIXOS2;   /* Solaris */
1262 
1263 				/* calculate CHS values for table entry 0 */
1264 				Set_Table_CHS_Values(0);
1265 				update_disk_and_exit(B_TRUE);
1266 			} else if (io_EFIdisk) {
1267 				if (efi_create() == 0) {
1268 					(void) fprintf(stderr,
1269 					    "Error creating EFI partition\n");
1270 					exit(1);
1271 				}
1272 				(void) close(Dev);
1273 				exit(0);
1274 				/* NOTREACHED */
1275 			}
1276 		}
1277 	}
1278 
1279 	/* Display complete fdisk table entries for debugging purposes */
1280 	if (io_debug) {
1281 		(void) fprintf(stderr, "Partition Table Entry Values:\n");
1282 		print_Table();
1283 		if (io_ifdisk) {
1284 			(void) fprintf(stderr, "\n");
1285 			(void) fprintf(stderr, "Press Enter to continue.\n");
1286 			(void) fgets(s, sizeof (s), stdin);
1287 		}
1288 	}
1289 
1290 	/* Interactive fdisk mode */
1291 	if (io_ifdisk) {
1292 		(void) printf(CLR_SCR);
1293 		disptbl();
1294 		for (;;) {
1295 			stage0();
1296 			copy_Bootblk_to_Table();
1297 			disptbl();
1298 		}
1299 	}
1300 
1301 	/* If user wants to write the table to a file, do it */
1302 	if (io_Wfdisk)
1303 		ffile_write(io_Wfdisk);
1304 	else if (stdo_flag)
1305 		ffile_write((char *)stdout);
1306 
1307 	update_disk_and_exit(TableChanged() == 1);
1308 	return (0);
1309 }
1310 
1311 /*
1312  * read_geom
1313  * Read geometry from specified file (-S).
1314  */
1315 
1316 static int
read_geom(char * sgeom)1317 read_geom(char *sgeom)
1318 {
1319 	char	line[256];
1320 	FILE *fp;
1321 
1322 	/* open the prototype file */
1323 	if ((fp = fopen(sgeom, "r")) == NULL) {
1324 		(void) fprintf(stderr, "fdisk: Cannot open file %s.\n",
1325 		    io_sgeom);
1326 		return (1);
1327 	}
1328 
1329 	/* Read a line from the file */
1330 	while (fgets(line, sizeof (line) - 1, fp)) {
1331 		if (line[0] == '\0' || line[0] == '\n' || line[0] == '*') {
1332 			continue;
1333 		} else {
1334 			line[strlen(line)] = '\0';
1335 			if (sscanf(line, "%hu %hu %hu %hu %hu %hu %d",
1336 			    &disk_geom.dkg_pcyl,
1337 			    &disk_geom.dkg_ncyl,
1338 			    &disk_geom.dkg_acyl,
1339 			    &disk_geom.dkg_bcyl,
1340 			    &disk_geom.dkg_nhead,
1341 			    &disk_geom.dkg_nsect,
1342 			    &sectsiz) != 7) {
1343 				(void) fprintf(stderr,
1344 				    "Syntax error:\n	\"%s\".\n",
1345 				    line);
1346 				return (1);
1347 			}
1348 			break;
1349 		} /* else */
1350 	} /* while (fgets(line, sizeof (line) - 1, fp)) */
1351 
1352 	if (!io_image) {
1353 		if (ioctl(Dev, DKIOCSGEOM, &disk_geom)) {
1354 			(void) fprintf(stderr,
1355 			    "fdisk: Cannot set label geometry.\n");
1356 			return (1);
1357 		}
1358 	} else {
1359 		Numcyl = hba_Numcyl = disk_geom.dkg_ncyl;
1360 		heads = hba_heads = disk_geom.dkg_nhead;
1361 		sectors = hba_sectors = disk_geom.dkg_nsect;
1362 		acyl = disk_geom.dkg_acyl;
1363 	}
1364 
1365 	(void) fclose(fp);
1366 	return (0);
1367 }
1368 
1369 /*
1370  * dev_mboot_read
1371  * Read the master boot sector from the device.
1372  */
1373 static void
dev_mboot_read(void)1374 dev_mboot_read(void)
1375 {
1376 	if ((ioctl(Dev, DKIOCGMBOOT, Bootsect) < 0) && (errno != ENOTTY)) {
1377 		perror("Error in ioctl DKIOCGMBOOT");
1378 	}
1379 	if (errno == 0)
1380 		return;
1381 	if (lseek(Dev, 0, SEEK_SET) == -1) {
1382 		(void) fprintf(stderr,
1383 		    "fdisk: Error seeking to partition table on %s.\n",
1384 		    Dfltdev);
1385 		if (!io_image)
1386 			exit(1);
1387 	}
1388 	if (read(Dev, Bootsect, sectsiz) != sectsiz) {
1389 		(void) fprintf(stderr,
1390 		    "fdisk: Error reading partition table from %s.\n",
1391 		    Dfltdev);
1392 		if (!io_image)
1393 			exit(1);
1394 	}
1395 }
1396 
1397 /*
1398  * dev_mboot_write
1399  * Write the master boot sector to the device.
1400  */
1401 static void
dev_mboot_write(off_t sect,char * buff,int bootsiz)1402 dev_mboot_write(off_t sect, char *buff, int bootsiz)
1403 {
1404 	int	new_pt, old_pt, error;
1405 	int	clr_efi = -1;
1406 
1407 	if (io_readonly)
1408 		return;
1409 
1410 	if (io_debug) {
1411 		(void) fprintf(stderr, "About to write fdisk table:\n");
1412 		print_Table();
1413 		if (io_ifdisk) {
1414 			(void) fprintf(stderr, "Press Enter to continue.\n");
1415 			(void) fgets(s, sizeof (s), stdin);
1416 		}
1417 	}
1418 
1419 	/*
1420 	 * If the new table has any Solaris partitions and the old
1421 	 * table does not have an entry that describes it
1422 	 * exactly then clear the old vtoc (if any).
1423 	 */
1424 	for (new_pt = 0; new_pt < FD_NUMPART; new_pt++) {
1425 
1426 		/* We only care about potential Solaris parts. */
1427 		if (Table[new_pt].systid != SUNIXOS &&
1428 		    Table[new_pt].systid != SUNIXOS2)
1429 			continue;
1430 
1431 		/* Does the old table have an exact entry for the new entry? */
1432 		for (old_pt = 0; old_pt < FD_NUMPART; old_pt++) {
1433 
1434 			/* We only care about old Solaris partitions. */
1435 			if ((Old_Table[old_pt].systid == SUNIXOS) ||
1436 			    (Old_Table[old_pt].systid == SUNIXOS2)) {
1437 
1438 				/* Is this old one the same as a new one? */
1439 				if ((Old_Table[old_pt].relsect ==
1440 				    Table[new_pt].relsect) &&
1441 				    (Old_Table[old_pt].numsect ==
1442 				    Table[new_pt].numsect))
1443 					break; /* Yes */
1444 			}
1445 		}
1446 
1447 		/* Did a solaris partition change location or size? */
1448 		if (old_pt >= FD_NUMPART) {
1449 			/* Yes clear old vtoc */
1450 			if (io_debug) {
1451 				(void) fprintf(stderr,
1452 				    "Clearing VTOC labels from NEW"
1453 				    " table\n");
1454 			}
1455 			clear_vtoc(NEW, new_pt);
1456 		}
1457 	}
1458 
1459 	/* see if the old table had EFI */
1460 	for (old_pt = 0; old_pt < FD_NUMPART; old_pt++) {
1461 		if (Old_Table[old_pt].systid == EFI_PMBR) {
1462 			clr_efi = old_pt;
1463 		}
1464 	}
1465 
1466 	/* look to see if a EFI partition changed in relsect/numsect */
1467 	for (new_pt = 0; new_pt < FD_NUMPART; new_pt++) {
1468 		if (Table[new_pt].systid != EFI_PMBR)
1469 			continue;
1470 		for (old_pt = 0; old_pt < FD_NUMPART; old_pt++) {
1471 			if ((Old_Table[old_pt].systid ==
1472 			    Table[new_pt].systid) &&
1473 			    (Old_Table[old_pt].relsect ==
1474 			    Table[new_pt].relsect) &&
1475 			    (Old_Table[old_pt].numsect ==
1476 			    Table[new_pt].numsect)) {
1477 				/*
1478 				 * New EFI guard partition matches old.
1479 				 * Do not clear EFI labels in this case.
1480 				 */
1481 				clr_efi = -1;
1482 				break;
1483 			}
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
mboot_read(void)1539 mboot_read(void)
1540 {
1541 	int mDev, i;
1542 	struct ipart *part;
1543 
1544 	/*
1545 	 * If the master boot file hasn't been specified, try to use our
1546 	 * default.
1547 	 */
1548 	if (io_mboot == NULL) {
1549 		io_mboot = DEFAULT_MASTER_BOOT_FILE;
1550 
1551 		if ((mDev = open(io_mboot, O_RDONLY, 0666)) == -1) {
1552 			/*
1553 			 * This is not a fault from fdisk's point of view.
1554 			 * We do not install bootloader with fdisk,
1555 			 * so just throw away this error and return.
1556 			 */
1557 			return;
1558 		}
1559 	} else {
1560 		if ((mDev = open(io_mboot, O_RDONLY, 0666)) == -1) {
1561 			/*
1562 			 * The file name was provided by user, provide
1563 			 * the feedback.
1564 			 */
1565 			(void) fprintf(stderr,
1566 			    "fdisk: Cannot open master boot file '%s' : %s\n",
1567 			    io_mboot, strerror(errno));
1568 			exit(1);
1569 		}
1570 	}
1571 
1572 	/* Read the master boot program */
1573 	if (read(mDev, &BootCod, sizeof (struct mboot)) != sizeof
1574 	    (struct mboot)) {
1575 		(void) fprintf(stderr,
1576 		    "fdisk: Cannot read master boot file %s.\n",
1577 		    io_mboot);
1578 		exit(1);
1579 	}
1580 
1581 	/* Is this really a master boot record? */
1582 	if (LE_16(BootCod.signature) != MBB_MAGIC) {
1583 		(void) fprintf(stderr,
1584 		    "fdisk: Invalid master boot file %s.\n", io_mboot);
1585 		(void) fprintf(stderr,
1586 		    "Bad magic number: is %x, but should be %x.\n",
1587 		    LE_16(BootCod.signature), MBB_MAGIC);
1588 		exit(1);
1589 	}
1590 
1591 	(void) close(mDev);
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
fill_patt(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
abs_read(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
abs_write(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
load(int funct,char * file)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 	FILE *fp;
1765 	int	startindex = 0;
1766 	int	tmpindex = 0;
1767 #ifdef i386
1768 	int	ext_part_present = 0;
1769 	uint32_t	begsec, endsec, relsect;
1770 	logical_drive_t *temp;
1771 	int part_count = 0, ldcnt = 0;
1772 	uint32_t ext_beg_sec;
1773 	uint32_t old_ext_beg_sec = 0, old_ext_num_sec = 0;
1774 	uint32_t new_ext_beg_sec = 0, new_ext_num_sec = 0;
1775 	int ext_part_inited = 0;
1776 	uchar_t	systid;
1777 #endif
1778 
1779 	switch (funct) {
1780 
1781 	case LOADFILE:
1782 
1783 		/*
1784 		 * Zero out the table before loading it, which will
1785 		 * force it to be updated on disk later (-F
1786 		 * fdisk_file).
1787 		 */
1788 		nulltbl();
1789 
1790 		/* Open the prototype file */
1791 		if ((fp = fopen(file, "r")) == NULL) {
1792 			(void) fprintf(stderr,
1793 			    "fdisk: Cannot open prototype partition file %s.\n",
1794 			    file);
1795 			exit(1);
1796 		}
1797 
1798 		/* Read a line from the file */
1799 		while (fgets(line, sizeof (line) - 1, fp)) {
1800 			if (pars_fdisk(line, &id, &act, &bhead, &bsect,
1801 			    &bcyl, &ehead, &esect, &ecyl, &rsect, &numsect)) {
1802 				continue;
1803 			}
1804 #ifdef i386
1805 			part_count++;
1806 
1807 			if (fdisk_is_dos_extended((uchar_t)id)) {
1808 				if (ext_part_present) {
1809 					(void) fprintf(stderr,
1810 					    "Extended partition"
1811 					    " already exists\n");
1812 					(void) fprintf(stderr, "fdisk: Error on"
1813 					    " entry \"%s\".\n", line);
1814 					exit(1);
1815 				}
1816 				ext_part_present = 1;
1817 				/*
1818 				 * If the existing extended partition's start
1819 				 * and size matches the new one, do not
1820 				 * initialize the extended partition EBR
1821 				 * (Extended Boot Record) because there could
1822 				 * be existing logical drives.
1823 				 */
1824 				for (i = 0; i < FD_NUMPART; i++) {
1825 					systid = Old_Table[i].systid;
1826 					if (fdisk_is_dos_extended(systid)) {
1827 						old_ext_beg_sec =
1828 						    Old_Table[i].relsect;
1829 						old_ext_num_sec =
1830 						    Old_Table[i].numsect;
1831 						break;
1832 					}
1833 				}
1834 				new_ext_beg_sec = rsect;
1835 				new_ext_num_sec = numsect;
1836 				if ((old_ext_beg_sec != new_ext_beg_sec) ||
1837 				    (old_ext_num_sec != new_ext_num_sec)) {
1838 					(void) fdisk_init_ext_part(epp,
1839 					    new_ext_beg_sec, new_ext_num_sec);
1840 					ext_part_inited = 1;
1841 				}
1842 			}
1843 
1844 			if (part_count > FD_NUMPART) {
1845 				/* This line should be logical drive info */
1846 				int offset = MAX_LOGDRIVE_OFFSET;
1847 				if (!ext_part_present) {
1848 					/* Erroneous input file */
1849 					(void) fprintf(stderr,
1850 					    "More than 4 primary"
1851 					    " partitions found in input\n");
1852 					(void) fprintf(stderr, "Exiting...\n");
1853 					exit(1);
1854 				}
1855 
1856 				if (numsect == 0) {
1857 					continue;
1858 				}
1859 
1860 				/*
1861 				 * If the start and size of the existing
1862 				 * extended partition matches the new one and
1863 				 * new logical drives are being defined via
1864 				 * the input file, initialize the EBR.
1865 				 */
1866 				if (!ext_part_inited) {
1867 					(void) fdisk_init_ext_part(epp,
1868 					    new_ext_beg_sec, new_ext_num_sec);
1869 					ext_part_inited = 1;
1870 				}
1871 
1872 				begsec = rsect - offset;
1873 				if ((ldcnt =
1874 				    fdisk_get_logical_drive_count(epp)) == 0) {
1875 					/* Adding the first logical drive */
1876 					/*
1877 					 * Make sure that begsec doesnt wrap
1878 					 * around. This can happen if rsect is
1879 					 * less than offset.
1880 					 */
1881 					if (rsect < offset) {
1882 						(void) fprintf(stderr,
1883 						    "Minimum of "
1884 						    "63 free sectors required "
1885 						    "before the beginning of "
1886 						    "a logical drive.");
1887 						exit(1);
1888 					}
1889 					/*
1890 					 * Check if the first logical drive
1891 					 * is out of order. In that case, do
1892 					 * not subtract MAX_LOGDRIVE_OFFSET
1893 					 * from the given start of partition.
1894 					 */
1895 					if (begsec != new_ext_beg_sec) {
1896 						begsec = rsect;
1897 						offset = 0;
1898 					}
1899 				}
1900 				if (ldcnt >= MAX_EXT_PARTS) {
1901 					(void) fprintf(stderr,
1902 					    "\nError : Number of "
1903 					    "logical drives exceeds limit of "
1904 					    "%d.\n", MAX_EXT_PARTS);
1905 					exit(1);
1906 				}
1907 
1908 				if (id > FDISK_MAX_VALID_PART_ID) {
1909 					(void) fprintf(stderr,
1910 					    "Invalid partition ID\n");
1911 					(void) fprintf(stderr, "fdisk: Error on"
1912 					    " entry \"%s\".\n", line);
1913 					exit(1);
1914 				}
1915 
1916 				endsec = rsect + numsect - 1;
1917 				if (fdisk_validate_logical_drive(epp,
1918 				    begsec, offset, numsect) == 0) {
1919 					if (id == EFI_PMBR) {
1920 						(void) fprintf(stderr, "EFI "
1921 						    "partitions not supported "
1922 						    "inside extended "
1923 						    "partition\n");
1924 						exit(1);
1925 					}
1926 					fdisk_add_logical_drive(epp, begsec,
1927 					    endsec, id);
1928 					continue;
1929 				} else {
1930 					(void) fprintf(stderr, "fdisk: Error on"
1931 					    " entry \"%s\".\n", line);
1932 					exit(1);
1933 				}
1934 			}
1935 #endif
1936 
1937 			/*
1938 			 * Validate the partition. It cannot start at sector
1939 			 * 0 unless it is UNUSED or already exists
1940 			 */
1941 			if (validate_part(id, rsect, numsect) < 0) {
1942 				(void) fprintf(stderr,
1943 				    "fdisk: Error on entry \"%s\".\n",
1944 				    line);
1945 				exit(1);
1946 			}
1947 
1948 			if ((tmpindex = entry_from_old_table(id, act, bhead,
1949 			    bsect, bcyl, ehead, esect, ecyl, rsect, numsect,
1950 			    startindex)) != -1) {
1951 				/*
1952 				 * If we got here it means we copied an
1953 				 * unmodified entry. So there is no need
1954 				 * to insert it in the table or do any
1955 				 * checks against disk size.
1956 				 *
1957 				 * This is a work around on the following
1958 				 * situation (for IDE disks, at least):
1959 				 * Different operation systems calculate
1960 				 * disk size different ways, of which there
1961 				 * are two main ways.
1962 				 *
1963 				 * The first, rounds the disk size to modulo
1964 				 * cylinder size (virtual made-up cylinder
1965 				 * usually based on maximum number of heads
1966 				 * and sectors in partition table fields).
1967 				 * Our OS's (for IDE) and most other "Unix"
1968 				 * type OS's do this.
1969 				 *
1970 				 * The second, uses every single block
1971 				 * on the disk (to maximize available space).
1972 				 * Since disk manufactures do not know about
1973 				 * "virtual cylinders", there are some number
1974 				 * of blocks that make up a partial cylinder
1975 				 * at the end of the disk.
1976 				 *
1977 				 * The difference between these two methods
1978 				 * is where the problem is. When one
1979 				 * tries to install Solaris/OpenSolaris on
1980 				 * a disk that has another OS using that
1981 				 * "partial cylinder", install fails. It fails
1982 				 * since fdisk thinks its asked to create a
1983 				 * partition with the -F option that contains
1984 				 * a partition that runs off the end of the
1985 				 * disk.
1986 				 */
1987 				startindex = tmpindex + 1;
1988 				continue;
1989 			}
1990 
1991 			/*
1992 			 * Find an unused entry to use and put the entry
1993 			 * in table
1994 			 */
1995 			if ((startindex = insert_tbl(id, act, bhead, bsect,
1996 			    bcyl, ehead, esect, ecyl, rsect, numsect,
1997 			    startindex)) < 0) {
1998 				(void) fprintf(stderr,
1999 				    "fdisk: Error on entry \"%s\".\n",
2000 				    line);
2001 				exit(1);
2002 			}
2003 			startindex++;
2004 		} /* while (fgets(line, sizeof (line) - 1, fp)) */
2005 
2006 		if (verify_tbl() < 0) {
2007 			(void) fprintf(stderr,
2008 			    "fdisk: Cannot create partition table\n");
2009 			exit(1);
2010 		}
2011 
2012 		(void) fclose(fp);
2013 		return;
2014 
2015 	case LOADDEL:
2016 
2017 		/* Parse the user-supplied deletion line (-D) */
2018 		if (pars_fdisk(file, &id, &act, &bhead, &bsect, &bcyl,
2019 		    &ehead, &esect, &ecyl, &rsect, &numsect)) {
2020 			(void) fprintf(stderr,
2021 			    "fdisk: Syntax error \"%s\"\n", file);
2022 			exit(1);
2023 		}
2024 
2025 		/* Find the exact entry in the table */
2026 		for (i = 0; i < FD_NUMPART; i++) {
2027 			if (Table[i].systid == id &&
2028 			    Table[i].bootid == act &&
2029 			    Table[i].beghead == bhead &&
2030 			    Table[i].begsect == ((bsect & 0x3f) |
2031 			    (uchar_t)((bcyl>>2) & 0xc0)) &&
2032 			    Table[i].begcyl == (uchar_t)(bcyl & 0xff) &&
2033 			    Table[i].endhead == ehead &&
2034 			    Table[i].endsect == ((esect & 0x3f) |
2035 			    (uchar_t)((ecyl>>2) & 0xc0)) &&
2036 			    Table[i].endcyl == (uchar_t)(ecyl & 0xff) &&
2037 			    Table[i].relsect == LE_32(rsect) &&
2038 			    Table[i].numsect == LE_32(numsect)) {
2039 
2040 				(void) memset(&Table[i], 0,
2041 				    sizeof (struct ipart));
2042 #ifdef i386
2043 				if (fdisk_is_dos_extended(id)) {
2044 					(void) fdisk_delete_ext_part(epp);
2045 				}
2046 #endif
2047 				return;
2048 			}
2049 		}
2050 
2051 #ifdef i386
2052 		ldcnt = FD_NUMPART + 1;
2053 		for (temp = fdisk_get_ld_head(epp); temp != NULL;
2054 		    temp = temp->next) {
2055 			relsect = temp->abs_secnum + temp->logdrive_offset;
2056 			if (temp->parts[0].systid == id &&
2057 			    temp->parts[0].bootid == act &&
2058 			    temp->parts[0].beghead == bhead &&
2059 			    temp->parts[0].begsect == ((bsect & 0x3f) |
2060 			    (uchar_t)((bcyl>>2) & 0xc0)) &&
2061 			    temp->parts[0].begcyl == (uchar_t)(bcyl & 0xff) &&
2062 			    temp->parts[0].endhead == ehead &&
2063 			    temp->parts[0].endsect == ((esect & 0x3f) |
2064 			    (uchar_t)((ecyl>>2) & 0xc0)) &&
2065 			    temp->parts[0].endcyl == (uchar_t)(ecyl & 0xff) &&
2066 			    relsect == LE_32(rsect) &&
2067 			    temp->parts[0].numsect == LE_32(numsect)) {
2068 				fdisk_delete_logical_drive(epp, ldcnt);
2069 				return;
2070 			}
2071 			ldcnt++;
2072 		}
2073 #endif
2074 
2075 		(void) fprintf(stderr,
2076 		    "fdisk: Entry does not match any existing partition:\n"
2077 		    "	\"%s\"\n",
2078 		    file);
2079 		exit(1);
2080 		/* FALLTHROUGH */
2081 
2082 	case LOADADD:
2083 
2084 		/* Parse the user-supplied addition line (-A) */
2085 		if (pars_fdisk(file, &id, &act, &bhead, &bsect, &bcyl, &ehead,
2086 		    &esect, &ecyl, &rsect, &numsect)) {
2087 			(void) fprintf(stderr,
2088 			    "fdisk: Syntax error \"%s\"\n", file);
2089 			exit(1);
2090 		}
2091 
2092 		/* Validate the partition. It cannot start at sector 0 */
2093 		if (rsect == 0) {
2094 			(void) fprintf(stderr,
2095 			    "fdisk: New partition cannot start at sector 0:\n"
2096 			    "   \"%s\".\n",
2097 			    file);
2098 			exit(1);
2099 		}
2100 
2101 		/*
2102 		 * if the user wishes to add an EFI partition, we need
2103 		 * more extensive validation.  rsect should be 1, and
2104 		 * numsect should equal the entire disk capacity - 1
2105 		 */
2106 
2107 		if (id == EFI_PMBR) {
2108 			if (rsect != 1) {
2109 				(void) fprintf(stderr,
2110 				    "fdisk: EFI partitions must start at sector"
2111 				    " 1 (input rsect = %d)\n", rsect);
2112 				exit(1);
2113 			}
2114 
2115 
2116 			if (dev_capacity > DK_MAX_2TB) {
2117 				if (numsect != DK_MAX_2TB) {
2118 					(void) fprintf(stderr,
2119 					    "fdisk: EFI partitions must "
2120 					    "encompass the entire maximum 2 TB "
2121 					    "(input numsect: %u - max: %llu)\n",
2122 					    numsect, (diskaddr_t)DK_MAX_2TB);
2123 				exit(1);
2124 				}
2125 			} else if (numsect != dev_capacity - 1) {
2126 				(void) fprintf(stderr,
2127 				    "fdisk: EFI partitions must encompass the "
2128 				    "entire disk\n"
2129 				    "(input numsect: %u - avail: %llu)\n",
2130 				    numsect,
2131 				    dev_capacity - 1);
2132 				exit(1);
2133 			}
2134 		}
2135 
2136 #ifdef i386
2137 		if (id > FDISK_MAX_VALID_PART_ID) {
2138 			(void) printf("Invalid partition ID\n");
2139 			exit(1);
2140 		}
2141 
2142 		if ((fdisk_ext_part_exists(epp)) &&
2143 		    (fdisk_is_dos_extended(id))) {
2144 			(void) fprintf(stderr,
2145 			    "Extended partition already exists.\n");
2146 			(void) fprintf(stderr,
2147 			    "fdisk: Invalid entry could not be "
2148 			    "inserted:\n        \"%s\"\n", file);
2149 			exit(1);
2150 		}
2151 
2152 		if (fdisk_ext_part_exists(epp) &&
2153 		    (rsect >= (ext_beg_sec = fdisk_get_ext_beg_sec(epp))) &&
2154 		    (rsect <= (fdisk_get_ext_end_sec(epp)))) {
2155 			int offset = MAX_LOGDRIVE_OFFSET;
2156 
2157 			/*
2158 			 * Make sure that begsec doesnt wrap around.
2159 			 * This can happen if rsect is less than offset
2160 			 */
2161 			if (rsect < offset) {
2162 				return;
2163 			}
2164 			begsec = rsect - offset;
2165 			if ((ldcnt = fdisk_get_logical_drive_count(epp)) == 0) {
2166 				/*
2167 				 * Adding the first logical drive
2168 				 * Check if the first logical drive
2169 				 * is out of order. In that case, do
2170 				 * not subtract MAX_LOGDRIVE_OFFSET
2171 				 * from the given start of partition.
2172 				 */
2173 				if (begsec != ext_beg_sec) {
2174 					begsec = rsect;
2175 					offset = 0;
2176 				}
2177 			}
2178 
2179 			if (ldcnt >= MAX_EXT_PARTS) {
2180 				(void) printf("\nNumber of logical drives "
2181 				    "exceeds limit of %d.\n", MAX_EXT_PARTS);
2182 				(void) printf("Failing further additions.\n");
2183 				exit(1);
2184 			}
2185 
2186 			if (numsect == 0) {
2187 				(void) fprintf(stderr,
2188 				    "fdisk: Partition size cannot be zero:\n"
2189 				    "   \"%s\".\n",
2190 				    file);
2191 				exit(1);
2192 			}
2193 			endsec = rsect + numsect - 1;
2194 			if (fdisk_validate_logical_drive(epp, begsec,
2195 			    offset, numsect) == 0) {
2196 				/* Valid logical drive */
2197 				fdisk_add_logical_drive(epp, begsec, endsec,
2198 				    id);
2199 				return;
2200 			} else {
2201 				(void) fprintf(stderr,
2202 				    "fdisk: Invalid entry could not be "
2203 				    "inserted:\n        \"%s\"\n", file);
2204 				exit(1);
2205 			}
2206 		}
2207 #endif
2208 
2209 		/* Find unused entry for use and put entry in table */
2210 		if (insert_tbl(id, act, bhead, bsect, bcyl, ehead, esect,
2211 		    ecyl, rsect, numsect, 0) < 0) {
2212 			(void) fprintf(stderr,
2213 			    "fdisk: Invalid entry could not be inserted:\n"
2214 			    "	\"%s\"\n",
2215 			    file);
2216 			exit(1);
2217 		}
2218 
2219 		/* Make sure new entry does not overlap existing entry */
2220 		if (verify_tbl() < 0) {
2221 			(void) fprintf(stderr,
2222 			    "fdisk: Cannot create partition \"%s\"\n", file);
2223 			exit(1);
2224 		}
2225 	} /* switch funct */
2226 }
2227 
2228 /*
2229  * Set_Table_CHS_Values
2230  *
2231  * This will calculate the CHS values for beginning and ending CHS
2232  * for a single partition table entry (ti) based on the relsect
2233  * and numsect values contained in the partion table entry.
2234  *
2235  * hba_heads and hba_sectors contain the number of heads and sectors.
2236  *
2237  * If the number of cylinders exceeds the MAX_CYL,
2238  * then maximum values will be placed in the corresponding chs entry.
2239  */
2240 static void
Set_Table_CHS_Values(int ti)2241 Set_Table_CHS_Values(int ti)
2242 {
2243 	uint32_t	lba, cy, hd, sc;
2244 
2245 	lba = (uint32_t)Table[ti].relsect;
2246 	if (lba >= hba_heads * hba_sectors * MAX_CYL) {
2247 		/*
2248 		 * the lba address cannot be expressed in CHS value
2249 		 * so store the maximum CHS field values in the CHS fields.
2250 		 */
2251 		cy = MAX_CYL + 1;
2252 		hd = MAX_HEAD + 1;
2253 		sc = MAX_SECT;
2254 	} else {
2255 		cy = lba / hba_sectors / hba_heads;
2256 		hd = lba / hba_sectors % hba_heads;
2257 		sc = lba % hba_sectors + 1;
2258 	}
2259 	Table[ti].begcyl = cy & 0xff;
2260 	Table[ti].beghead = (uchar_t)hd;
2261 	Table[ti].begsect = (uchar_t)(((cy >> 2) & 0xc0) | sc);
2262 
2263 	/*
2264 	 * This code is identical to the code above
2265 	 * except that it works on ending CHS values
2266 	 */
2267 	lba = (uint32_t)(Table[ti].relsect + Table[ti].numsect - 1);
2268 	if (lba >= hba_heads * hba_sectors * MAX_CYL) {
2269 		cy = MAX_CYL + 1;
2270 		hd = MAX_HEAD + 1;
2271 		sc = MAX_SECT;
2272 	} else {
2273 		cy = lba / hba_sectors / hba_heads;
2274 		hd = lba / hba_sectors % hba_heads;
2275 		sc = lba % hba_sectors + 1;
2276 	}
2277 	Table[ti].endcyl = cy & 0xff;
2278 	Table[ti].endhead = (uchar_t)hd;
2279 	Table[ti].endsect = (uchar_t)(((cy >> 2) & 0xc0) | sc);
2280 }
2281 
2282 /*
2283  * insert_tbl
2284  *	Insert entry into fdisk table. Check all user-supplied values
2285  *	for the entry, but not the validity relative to other table
2286  *	entries!
2287  */
2288 static int
insert_tbl(int id,int act,int bhead,int bsect,int bcyl,int ehead,int esect,int ecyl,uint32_t rsect,uint32_t numsect,int startindex)2289 insert_tbl(
2290     int id, int act,
2291     int bhead, int bsect, int bcyl,
2292     int ehead, int esect, int ecyl,
2293     uint32_t rsect, uint32_t numsect, int startindex)
2294 {
2295 	int	i;
2296 
2297 	/* validate partition size */
2298 	if (((diskaddr_t)rsect + numsect) > dev_capacity) {
2299 		(void) fprintf(stderr,
2300 		    "fdisk: Partition table exceeds the size of the disk.\n");
2301 		return (-1);
2302 	}
2303 
2304 
2305 	/* find UNUSED partition table entry */
2306 	for (i = startindex; i < FD_NUMPART; i++) {
2307 		if (Table[i].systid == UNUSED) {
2308 			break;
2309 		}
2310 	}
2311 	if (i >= FD_NUMPART) {
2312 		(void) fprintf(stderr, "fdisk: Partition table is full.\n");
2313 		return (-1);
2314 	}
2315 
2316 	Table[i].systid = (uchar_t)id;
2317 	Table[i].bootid = (uchar_t)act;
2318 	Table[i].numsect = LE_32(numsect);
2319 	Table[i].relsect = LE_32(rsect);
2320 
2321 	if (id == UNUSED) {
2322 		(void) memset(&Table[i], 0, sizeof (struct ipart));
2323 	} else if (0 < bsect && bsect <= MAX_SECT &&
2324 	    0 <= bhead && bhead <= MAX_HEAD + 1 &&
2325 	    0 < esect && esect <= MAX_SECT &&
2326 	    0 <= ehead && ehead <= MAX_HEAD + 1) {
2327 
2328 		/*
2329 		 * If we have been called with a valid geometry, use it
2330 		 * valid means non-zero values that fit in the BIOS fields
2331 		 */
2332 		if (bcyl > MAX_CYL) {
2333 			/*
2334 			 * bcyl is set to the special fence value indicating
2335 			 * that the geometry is not representable for the
2336 			 * start LBA.
2337 			 * Set all fields to the maximum values.
2338 			 */
2339 			bcyl = MAX_CYL + 1;
2340 			bhead = MAX_HEAD + 1;
2341 			bsect = MAX_SECT;
2342 		}
2343 		if (ecyl > MAX_CYL) {
2344 			ecyl = MAX_CYL + 1;
2345 			ehead = MAX_HEAD + 1;
2346 			esect = MAX_SECT;
2347 		}
2348 		Table[i].begcyl = bcyl & 0xff;
2349 		Table[i].endcyl = ecyl & 0xff;
2350 		Table[i].beghead = (uchar_t)bhead;
2351 		Table[i].endhead = (uchar_t)ehead;
2352 		Table[i].begsect = (uchar_t)(((bcyl >> 2) & 0xc0) | bsect);
2353 		Table[i].endsect = ((ecyl >> 2) & 0xc0) | esect;
2354 	} else {
2355 
2356 		/*
2357 		 * The specified values are invalid,
2358 		 * so calculate the values based on hba_heads, hba_sectors
2359 		 */
2360 		Set_Table_CHS_Values(i);
2361 	}
2362 
2363 	/*
2364 	 * return partition index
2365 	 */
2366 	return (i);
2367 }
2368 
2369 /*
2370  * entry_from_old_table
2371  *	If the specified entry is in the old table and is not a Solaris entry
2372  *	then insert same entry into new fdisk table. If we do this then
2373  *	all checks are skipped for that entry!
2374  */
2375 static int
entry_from_old_table(int id,int act,int bhead,int bsect,int bcyl,int ehead,int esect,int ecyl,uint32_t rsect,uint32_t numsect,int startindex)2376 entry_from_old_table(
2377     int id, int act,
2378     int bhead, int bsect, int bcyl,
2379     int ehead, int esect, int ecyl,
2380     uint32_t rsect, uint32_t numsect, int startindex)
2381 {
2382 	uint32_t	i, j;
2383 
2384 	if (id == SUNIXOS || id == SUNIXOS2 || id == UNUSED)
2385 		return (-1);
2386 	for (i = 0; i < FD_NUMPART; i++) {
2387 		if (Old_Table[i].systid == id &&
2388 		    Old_Table[i].bootid == act &&
2389 		    Old_Table[i].beghead == bhead &&
2390 		    Old_Table[i].begsect == ((bsect & 0x3f) |
2391 		    (uchar_t)((bcyl>>2) & 0xc0)) &&
2392 		    Old_Table[i].begcyl == (uchar_t)(bcyl & 0xff) &&
2393 		    Old_Table[i].endhead == ehead &&
2394 		    Old_Table[i].endsect == ((esect & 0x3f) |
2395 		    (uchar_t)((ecyl>>2) & 0xc0)) &&
2396 		    Old_Table[i].endcyl == (uchar_t)(ecyl & 0xff) &&
2397 		    Old_Table[i].relsect == lel(rsect) &&
2398 		    Old_Table[i].numsect == lel(numsect)) {
2399 			/* find UNUSED partition table entry */
2400 			for (j = startindex; j < FD_NUMPART; j++) {
2401 				if (Table[j].systid == UNUSED) {
2402 					(void) memcpy(&Table[j], &Old_Table[i],
2403 					    sizeof (Table[0]));
2404 					skip_verify[j] = 1;
2405 					return (j);
2406 
2407 				}
2408 			}
2409 			return (-1);
2410 		}
2411 
2412 	}
2413 	return (-1);
2414 }
2415 
2416 /*
2417  * verify_tbl
2418  * Verify that no partition entries overlap or exceed the size of
2419  * the disk.
2420  */
2421 static int
verify_tbl(void)2422 verify_tbl(void)
2423 {
2424 	uint32_t	i, j, rsect, numsect;
2425 	int	noMoreParts = 0;
2426 	int	numParts = 0;
2427 
2428 	/* Make sure new entry does not overlap an existing entry */
2429 	for (i = 0; i < FD_NUMPART - 1; i++) {
2430 		if (Table[i].systid != UNUSED) {
2431 			numParts++;
2432 			/*
2433 			 * No valid partitions allowed after EFI_PMBR part
2434 			 */
2435 			if (noMoreParts) {
2436 				return (-1);
2437 			}
2438 
2439 			if (Table[i].systid == EFI_PMBR) {
2440 				/*
2441 				 * EFI_PMBR partition must be the only
2442 				 * partition
2443 				 */
2444 				noMoreParts = 1;
2445 
2446 				if (Table[i].relsect != 1) {
2447 					(void) fprintf(stderr, "ERROR: "
2448 					    "Invalid starting sector "
2449 					    "for EFI_PMBR partition:\n"
2450 					    "relsect %d "
2451 					    "(should be 1)\n",
2452 					    Table[i].relsect);
2453 
2454 					return (-1);
2455 				}
2456 
2457 				if (Table[i].numsect !=
2458 				    ((dev_capacity > DK_MAX_2TB) ? DK_MAX_2TB:
2459 				    (dev_capacity - 1))) {
2460 
2461 					(void) fprintf(stderr, "ERROR: "
2462 					    "EFI_PMBR partition must "
2463 					    "encompass the entire");
2464 
2465 					if (dev_capacity > DK_MAX_2TB)
2466 						(void) fprintf(stderr,
2467 						    "maximum 2 TB.\n "
2468 						    "numsect %u - "
2469 						    "actual %llu\n",
2470 						    Table[i].numsect,
2471 						    (diskaddr_t)DK_MAX_2TB);
2472 
2473 					else
2474 						(void) fprintf(stderr,
2475 						    "disk.\n numsect %u - "
2476 						    "actual %llu\n",
2477 						    Table[i].numsect,
2478 						    dev_capacity - 1);
2479 
2480 					return (-1);
2481 				}
2482 			}
2483 
2484 			/* make sure the partition isn't larger than the disk */
2485 			rsect = LE_32(Table[i].relsect);
2486 			numsect = LE_32(Table[i].numsect);
2487 
2488 			if ((((diskaddr_t)rsect + numsect) > dev_capacity) ||
2489 			    (((diskaddr_t)rsect + numsect) > DK_MAX_2TB)) {
2490 				if (!skip_verify[i])
2491 					return (-1);
2492 			}
2493 
2494 			for (j = i + 1; j < FD_NUMPART; j++) {
2495 				if (Table[j].systid != UNUSED) {
2496 					uint32_t t_relsect =
2497 					    LE_32(Table[j].relsect);
2498 					uint32_t t_numsect =
2499 					    LE_32(Table[j].numsect);
2500 
2501 					if (noMoreParts) {
2502 						(void) fprintf(stderr,
2503 						    "Cannot add partition to "
2504 						    "table; no more partitions "
2505 						    "allowed\n");
2506 
2507 						if (io_debug) {
2508 							(void) fprintf(stderr,
2509 							    "DEBUG: Current "
2510 							    "partition:\t"
2511 							    "%d:%d:%d:%d:%d:"
2512 							    "%d:%d:%d:%d:%d\n"
2513 							    "       Next "
2514 							    "partition:\t\t"
2515 							    "%d:%d:%d:%d:%d:"
2516 							    "%d:%d:%d:%d:%d\n",
2517 							    Table[i].systid,
2518 							    Table[i].bootid,
2519 							    Table[i].begcyl,
2520 							    Table[i].beghead,
2521 							    Table[i].begsect,
2522 							    Table[i].endcyl,
2523 							    Table[i].endhead,
2524 							    Table[i].endsect,
2525 							    Table[i].relsect,
2526 							    Table[i].numsect,
2527 							    Table[j].systid,
2528 							    Table[j].bootid,
2529 							    Table[j].begcyl,
2530 							    Table[j].beghead,
2531 							    Table[j].begsect,
2532 							    Table[j].endcyl,
2533 							    Table[j].endhead,
2534 							    Table[j].endsect,
2535 							    Table[j].relsect,
2536 							    Table[j].numsect);
2537 						}
2538 
2539 						return (-1);
2540 					}
2541 					if ((rsect >=
2542 					    (t_relsect + t_numsect)) ||
2543 					    ((rsect + numsect) <= t_relsect)) {
2544 						continue;
2545 					} else {
2546 						(void) fprintf(stderr, "ERROR: "
2547 						    "current partition overlaps"
2548 						    " following partition\n");
2549 
2550 						return (-1);
2551 					}
2552 				}
2553 			}
2554 		}
2555 	}
2556 	if (Table[i].systid != UNUSED) {
2557 		if (noMoreParts)
2558 			return (-1);
2559 		if (!skip_verify[i] &&
2560 		    ((((diskaddr_t)lel(Table[i].relsect) +
2561 		    lel(Table[i].numsect)) > dev_capacity) ||
2562 		    (((diskaddr_t)lel(Table[i].relsect) +
2563 		    lel(Table[i].numsect)) > DK_MAX_2TB))) {
2564 			return (-1);
2565 		}
2566 	}
2567 
2568 	return (numParts);
2569 }
2570 
2571 /*
2572  * pars_fdisk
2573  * Parse user-supplied data to set up fdisk partitions
2574  * (-A, -D, -F).
2575  */
2576 static int
pars_fdisk(char * line,int * id,int * act,int * bhead,int * bsect,int * bcyl,int * ehead,int * esect,int * ecyl,uint32_t * rsect,uint32_t * numsect)2577 pars_fdisk(
2578     char *line,
2579     int *id, int *act,
2580     int *bhead, int *bsect, int *bcyl,
2581     int *ehead, int *esect, int *ecyl,
2582     uint32_t *rsect, uint32_t *numsect)
2583 {
2584 	int	i;
2585 	int64_t test;
2586 	char *tok, *p;
2587 	char buf[256];
2588 
2589 	if (line[0] == '\0' || line[0] == '\n' || line[0] == '*')
2590 		return (1);
2591 	line[strlen(line)] = '\0';
2592 	for (i = 0; i < strlen(line); i++) {
2593 		if (line[i] == '\0') {
2594 			break;
2595 		} else if (line[i] == ':') {
2596 			line[i] = ' ';
2597 		}
2598 	}
2599 	(void) strncpy(buf, line, 256);
2600 	errno = 0;
2601 	tok = strtok(buf, ": \t\n");
2602 	while (tok != NULL) {
2603 		for (p = tok; *p != '\0'; p++) {
2604 			if (!isdigit(*p)) {
2605 				(void) printf("Invalid input %s in line %s.\n",
2606 				    tok, line);
2607 				exit(1);
2608 			}
2609 		}
2610 
2611 		test = strtoll(tok, (char **)NULL, 10);
2612 		if ((test < 0) || (test > 0xFFFFFFFF) || (errno != 0)) {
2613 			(void) printf("Invalid input %s in line %s.\n", tok,
2614 			    line);
2615 			exit(1);
2616 		}
2617 		tok = strtok(NULL, ": \t\n");
2618 	}
2619 	if (sscanf(line, "%d %d %d %d %d %d %d %d %u %u",
2620 	    id, act, bhead, bsect, bcyl, ehead, esect, ecyl,
2621 	    rsect, numsect) != 10) {
2622 		(void) fprintf(stderr, "Syntax error:\n	\"%s\".\n", line);
2623 		exit(1);
2624 	}
2625 	return (0);
2626 }
2627 
2628 /*
2629  * validate_part
2630  * Validate that a new partition does not start at sector 0. Only UNUSED
2631  * partitions and previously existing partitions are allowed to start at 0.
2632  */
2633 static int
validate_part(int id,uint32_t rsect,uint32_t numsect)2634 validate_part(int id, uint32_t rsect, uint32_t numsect)
2635 {
2636 	int i;
2637 	if ((id != UNUSED) && (rsect == 0)) {
2638 		for (i = 0; i < FD_NUMPART; i++) {
2639 			if ((Old_Table[i].systid == id) &&
2640 			    (Old_Table[i].relsect == LE_32(rsect)) &&
2641 			    (Old_Table[i].numsect == LE_32(numsect)))
2642 				return (0);
2643 		}
2644 		(void) fprintf(stderr,
2645 		    "New partition cannot start at sector 0\n");
2646 		return (-1);
2647 	}
2648 #ifdef i386
2649 	if (id > FDISK_MAX_VALID_PART_ID) {
2650 		(void) fprintf(stderr, "Invalid partition ID\n");
2651 		return (-1);
2652 	}
2653 #endif
2654 	return (0);
2655 }
2656 
2657 /*
2658  * stage0
2659  * Print out interactive menu and process user input.
2660  */
2661 static void
stage0(void)2662 stage0(void)
2663 {
2664 #ifdef i386
2665 	int rval;
2666 #endif
2667 	dispmenu();
2668 	for (;;) {
2669 		(void) printf(Q_LINE);
2670 		(void) printf("Enter Selection: ");
2671 		(void) fgets(s, sizeof (s), stdin);
2672 		rm_blanks(s);
2673 #ifdef i386
2674 		while (!((s[0] > '0') && (s[0] < '8') &&
2675 		    ((s[1] == '\0') || (s[1] == '\n')))) {
2676 #else
2677 		while (!((s[0] > '0') && (s[0] < '7') &&
2678 		    ((s[1] == '\0') || (s[1] == '\n')))) {
2679 #endif
2680 			(void) printf(E_LINE); /* Clear any previous error */
2681 #ifdef i386
2682 			(void) printf(
2683 			    "Enter a one-digit number between 1 and 7.");
2684 #else
2685 			(void) printf(
2686 			    "Enter a one-digit number between 1 and 6.");
2687 #endif
2688 			(void) printf(Q_LINE);
2689 			(void) printf("Enter Selection: ");
2690 			(void) fgets(s, sizeof (s), stdin);
2691 			rm_blanks(s);
2692 		}
2693 		(void) printf(E_LINE);
2694 		switch (s[0]) {
2695 			case '1':
2696 				if (pcreate() == -1)
2697 					return;
2698 				break;
2699 			case '2':
2700 				if (pchange() == -1)
2701 					return;
2702 				break;
2703 			case '3':
2704 				if (pdelete() == -1)
2705 					return;
2706 				break;
2707 			case '4':
2708 				if (ppartid() == -1)
2709 					return;
2710 				break;
2711 #ifdef i386
2712 			case '5':
2713 				if (fdisk_ext_part_exists(epp)) {
2714 					ext_part_menu();
2715 				} else {
2716 					(void) printf(Q_LINE);
2717 					(void) printf("\nNo extended partition"
2718 					    " found\n");
2719 					(void) printf("Press enter to "
2720 					    "continue\n");
2721 					ext_read_input(s);
2722 				}
2723 				break;
2724 			case '6':
2725 				/* update disk partition table, if changed */
2726 				if (TableChanged() == 1) {
2727 					copy_Table_to_Bootblk();
2728 					dev_mboot_write(0, Bootsect, sectsiz);
2729 				}
2730 
2731 				/*
2732 				 * If the VTOC table is wrong fix it
2733 				 * (truncate only)
2734 				 */
2735 				if (io_adjt) {
2736 					fix_slice();
2737 				}
2738 				if (!io_readonly) {
2739 					rval = fdisk_commit_ext_part(epp);
2740 					switch (rval) {
2741 						case FDISK_SUCCESS:
2742 							/* Success */
2743 							/* Fallthrough */
2744 						case FDISK_ENOEXTPART:
2745 							/* Nothing to do */
2746 							break;
2747 						case FDISK_EMOUNTED:
2748 							(void) printf(Q_LINE);
2749 							preach_and_continue();
2750 							continue;
2751 						default:
2752 							perror("Commit failed");
2753 							exit(1);
2754 					}
2755 					libfdisk_fini(&epp);
2756 				}
2757 				(void) close(Dev);
2758 				exit(0);
2759 				/* NOTREACHED */
2760 #else
2761 			case '5':
2762 				/* update disk partition table, if changed */
2763 				if (TableChanged() == 1) {
2764 					copy_Table_to_Bootblk();
2765 					dev_mboot_write(0, Bootsect, sectsiz);
2766 				}
2767 				/*
2768 				 * If the VTOC table is wrong fix it
2769 				 * (truncate only)
2770 				 */
2771 				if (io_adjt) {
2772 					fix_slice();
2773 				}
2774 				(void) close(Dev);
2775 				exit(0);
2776 				/* FALLTHROUGH */
2777 #endif
2778 #ifdef i386
2779 			case '7':
2780 #else
2781 			case '6':
2782 #endif
2783 				/*
2784 				 * If the VTOC table is wrong fix it
2785 				 * (truncate only)
2786 				 */
2787 				if (io_adjt) {
2788 					fix_slice();
2789 				}
2790 				(void) close(Dev);
2791 				exit(0);
2792 				/* FALLTHROUGH */
2793 			default:
2794 				break;
2795 		}
2796 		copy_Table_to_Bootblk();
2797 		disptbl();
2798 		dispmenu();
2799 	}
2800 }
2801 
2802 /*
2803  * pcreate
2804  * Create partition entry in the table (interactive mode).
2805  */
2806 static int
2807 pcreate(void)
2808 {
2809 	uchar_t tsystid = 'z';
2810 	int i, j;
2811 	uint32_t numsect;
2812 	int retCode = 0;
2813 #ifdef i386
2814 	int ext_part_present = 0;
2815 #endif
2816 
2817 	i = 0;
2818 	for (;;) {
2819 		if (i == FD_NUMPART) {
2820 			(void) printf(E_LINE);
2821 			(void) printf(
2822 			    "The partition table is full!\n"
2823 			    "You must delete a partition before creating"
2824 			    " a new one.\n");
2825 			return (-1);
2826 		}
2827 		if (Table[i].systid == UNUSED) {
2828 			break;
2829 		}
2830 		i++;
2831 	}
2832 
2833 	numsect = 0;
2834 	for (i = 0; i < FD_NUMPART; i++) {
2835 		if (Table[i].systid != UNUSED) {
2836 			numsect += LE_32(Table[i].numsect);
2837 		}
2838 #ifdef i386
2839 		/* Check if an extended partition already exists */
2840 		if (fdisk_is_dos_extended(Table[i].systid)) {
2841 			ext_part_present = 1;
2842 		}
2843 #endif
2844 		if (numsect >= chs_capacity) {
2845 			(void) printf(E_LINE);
2846 			(void) printf("There is no more room on the disk for"
2847 			    " another partition.\n");
2848 			(void) printf(
2849 			    "You must delete a partition before creating"
2850 			    " a new one.\n");
2851 			return (-1);
2852 		}
2853 	}
2854 	while (tsystid == 'z') {
2855 
2856 		/*
2857 		 * The question here is expanding to more than what is
2858 		 * allocated for question lines (Q_LINE) which garbles
2859 		 * at least warning line. Clearing warning line as workaround
2860 		 * for now.
2861 		 */
2862 
2863 		(void) printf(W_LINE);
2864 		(void) printf(Q_LINE);
2865 		(void) printf(
2866 		    "Select the partition type to create:\n"
2867 		    "   1=SOLARIS2  2=UNIX        3=PCIXOS     4=Other\n"
2868 		    "   5=DOS12     6=DOS16       7=DOSEXT     8=DOSBIG\n"
2869 		    "   9=DOS16LBA  A=x86 Boot    B=Diagnostic C=FAT32\n"
2870 		    "   D=FAT32LBA  E=DOSEXTLBA   F=EFI        0=Exit? ");
2871 		(void) fgets(s, sizeof (s), stdin);
2872 		rm_blanks(s);
2873 		if ((s[1] != '\0') && (s[1] != '\n')) {
2874 			(void) printf(E_LINE);
2875 			(void) printf("Invalid selection, try again.");
2876 			continue;
2877 		}
2878 		switch (s[0]) {
2879 		case '0':		/* exit */
2880 			(void) printf(E_LINE);
2881 			return (-1);
2882 		case '1':		/* Solaris partition */
2883 			tsystid = SUNIXOS2;
2884 			break;
2885 		case '2':		/* UNIX partition */
2886 			tsystid = UNIXOS;
2887 			break;
2888 		case '3':		/* PCIXOS partition */
2889 			tsystid = PCIXOS;
2890 			break;
2891 		case '4':		/* OTHEROS System partition */
2892 			tsystid = OTHEROS;
2893 			break;
2894 		case '5':
2895 			tsystid = DOSOS12; /* DOS 12 bit fat */
2896 			break;
2897 		case '6':
2898 			tsystid = DOSOS16; /* DOS 16 bit fat */
2899 			break;
2900 		case '7':
2901 #ifdef i386
2902 			if (ext_part_present) {
2903 				(void) printf(Q_LINE);
2904 				(void) printf(E_LINE);
2905 				(void) fprintf(stderr,
2906 				    "Extended partition already exists\n");
2907 				(void) fprintf(stderr,
2908 				    "Press enter to continue\n");
2909 				ext_read_input(s);
2910 				continue;
2911 			}
2912 #endif
2913 			tsystid = EXTDOS;
2914 			break;
2915 		case '8':
2916 			tsystid = DOSHUGE;
2917 			break;
2918 		case '9':
2919 			tsystid = FDISK_FAT95;  /* FAT16, need extended int13 */
2920 			break;
2921 		case 'a':		/* x86 Boot partition */
2922 		case 'A':
2923 			tsystid = X86BOOT;
2924 			break;
2925 		case 'b':		/* Diagnostic boot partition */
2926 		case 'B':
2927 			tsystid = DIAGPART;
2928 			break;
2929 		case 'c':		/* FAT32 */
2930 		case 'C':
2931 			tsystid = FDISK_WINDOWS;
2932 			break;
2933 		case 'd':		/* FAT32 and need extended int13 */
2934 		case 'D':
2935 			tsystid = FDISK_EXT_WIN;
2936 			break;
2937 		case 'e':	/* Extended partition, need extended int13 */
2938 		case 'E':
2939 #ifdef i386
2940 			if (ext_part_present) {
2941 				(void) printf(Q_LINE);
2942 				(void) printf(E_LINE);
2943 				(void) fprintf(stderr,
2944 				    "Extended partition already exists\n");
2945 				(void) fprintf(stderr,
2946 				    "Press enter to continue\n");
2947 				ext_read_input(s);
2948 				continue;
2949 			}
2950 #endif
2951 			tsystid = FDISK_EXTLBA;
2952 			break;
2953 		case 'f':
2954 		case 'F':
2955 			tsystid = EFI_PMBR;
2956 			break;
2957 		default:
2958 			(void) printf(E_LINE);
2959 			(void) printf("Invalid selection, try again.");
2960 			continue;
2961 		}
2962 	}
2963 
2964 	(void) printf(E_LINE);
2965 
2966 	if (tsystid != EFI_PMBR) {
2967 		(void) printf(W_LINE);
2968 		if ((dev_capacity > DK_MAX_2TB))
2969 			(void) printf("WARNING: Disk is larger than 2 TB. "
2970 			    "Upper limit is 2 TB for non-EFI partition ID\n");
2971 
2972 		/* create the new partition */
2973 		i = specify(tsystid);
2974 
2975 		if (i != -1) {
2976 			/* see if it should be the active partition */
2977 			(void) printf(E_LINE);
2978 			(void) printf(Q_LINE);
2979 
2980 			(void) printf(
2981 			    "Should this become the active partition? If "
2982 			    "yes, it  will be activated\n"
2983 			    "each time the computer is reset or turned on.\n"
2984 			    "Please type \"y\" or \"n\". ");
2985 
2986 			if (yesno()) {
2987 				(void) printf(E_LINE);
2988 				for (j = 0; j < FD_NUMPART; j++) {
2989 					if (j == i) {
2990 						Table[j].bootid = ACTIVE;
2991 						(void) printf(E_LINE);
2992 						(void) printf(
2993 						    "Partition %d is now "
2994 						    "the active partition.",
2995 						    j + 1);
2996 					} else {
2997 						Table[j].bootid = 0;
2998 					}
2999 				}
3000 			} else {
3001 				Table[i].bootid = 0;
3002 			}
3003 
3004 #ifdef i386
3005 			/*
3006 			 * If partition created is an extended partition, null
3007 			 * out the first sector of the first cylinder of the
3008 			 * extended partition
3009 			 */
3010 			if (fdisk_is_dos_extended(Table[i].systid)) {
3011 				(void) fdisk_init_ext_part(epp,
3012 				    LE_32(Table[i].relsect),
3013 				    LE_32(Table[i].numsect));
3014 			}
3015 #endif
3016 			/* set up the return code */
3017 			i = 1;
3018 		}
3019 	} else {
3020 		/*
3021 		 * partitions of type EFI_PMBR must be the only partitions in
3022 		 * the table
3023 		 *
3024 		 * First, make sure there were no errors the table is
3025 		 * empty
3026 		 */
3027 		retCode = verify_tbl();
3028 
3029 		if (retCode < 0) {
3030 			(void) fprintf(stderr,
3031 			    "fdisk: Cannot create EFI partition table; \n"
3032 			    "current partition table is invalid.\n");
3033 			return (-1);
3034 		} else if (retCode > 0) {
3035 			(void) printf(
3036 			    "An EFI partition must be the only partition on "
3037 			    "disk.  You may manually delete existing\n"
3038 			    "partitions, or fdisk can do it.\n"
3039 			    "Do you want fdisk to destroy existing "
3040 			    "partitions?\n"
3041 			    "Please type \"y\" or \"n\". ");
3042 
3043 			if (yesno()) {
3044 				nulltbl();
3045 			} else {
3046 				return (-1);
3047 			}
3048 		}
3049 
3050 		/* create the table entry - i should be 0 */
3051 		i = insert_tbl(tsystid, 0, 0, 0, 0, 0, 0, 0, 1,
3052 		    (dev_capacity > DK_MAX_2TB) ? DK_MAX_2TB:
3053 		    (dev_capacity - 1), 0);
3054 
3055 		if (i != 0) {
3056 			(void) printf("Error creating EFI partition!!!\n");
3057 			i = -1;
3058 		} else {
3059 
3060 			/* EFI partitions are currently never active */
3061 			Table[i].bootid = 0;
3062 
3063 			/* set up the return code */
3064 			i = 1;
3065 		}
3066 	}
3067 
3068 	return (i);
3069 }
3070 
3071 /*
3072  * specify
3073  * Query the user to specify the size of the new partition in
3074  * terms of percentage of the disk or by specifying the starting
3075  * cylinder and length in cylinders.
3076  */
3077 static int
3078 specify(uchar_t tsystid)
3079 {
3080 	int	i, j, percent = -1;
3081 	int	cyl, cylen;
3082 	diskaddr_t first_free, size_free;
3083 	diskaddr_t max_free;
3084 	int	cyl_size;
3085 	struct ipart *partition[FD_NUMPART];
3086 	struct ipart localpart[FD_NUMPART];
3087 
3088 	cyl_size = heads * sectors;
3089 
3090 	/*
3091 	 * make a local copy of the partition table
3092 	 * and sort it into relsect order
3093 	 */
3094 
3095 
3096 	for (i = 0, j = 0; i < FD_NUMPART; i++) {
3097 		if (Table[i].systid != UNUSED) {
3098 			localpart[j] = Table[i];
3099 			j++;
3100 		}
3101 	}
3102 
3103 	while (j < FD_NUMPART) {
3104 		(void) memset(&localpart[j], 0, sizeof (struct ipart));
3105 		j++;
3106 	}
3107 
3108 	for (i = 0; i < FD_NUMPART; i++)
3109 		partition[i] = &localpart[i];
3110 
3111 	for (i = 0; i < FD_NUMPART - 1; i++) {
3112 		if (partition[i]->systid == UNUSED)
3113 			break;
3114 		for (j = i + 1; j < FD_NUMPART; j++) {
3115 			if (partition[j]->systid == UNUSED)
3116 				break;
3117 			if (LE_32(partition[j]->relsect) <
3118 			    LE_32(partition[i]->relsect)) {
3119 				struct ipart *temp = partition[i];
3120 				partition[i] = partition[j];
3121 				partition[j] = temp;
3122 			}
3123 		}
3124 	}
3125 
3126 
3127 	(void) printf(Q_LINE);
3128 	(void) printf(
3129 	    "Specify the percentage of disk to use for this partition\n"
3130 	    "(or type \"c\" to specify the size in cylinders). ");
3131 	(void) fgets(s, sizeof (s), stdin);
3132 	rm_blanks(s);
3133 	if (s[0] != 'c') {	/* Specify size in percentage of disk */
3134 		i = 0;
3135 		while ((s[i] != '\0') && (s[i] != '\n')) {
3136 			if (s[i] < '0' || s[i] > '9') {
3137 				(void) printf(E_LINE);
3138 				(void) printf("Invalid percentage value "
3139 				    "specified; retry the operation.");
3140 				return (-1);
3141 			}
3142 			i++;
3143 			if (i > 3) {
3144 				(void) printf(E_LINE);
3145 				(void) printf("Invalid percentage value "
3146 				    "specified; retry the operation.");
3147 				return (-1);
3148 			}
3149 		}
3150 		if ((percent = atoi(s)) > 100) {
3151 			(void) printf(E_LINE);
3152 			(void) printf(
3153 			    "Percentage value is too large. The value must be"
3154 			    " between 1 and 100;\nretry the operation.\n");
3155 			return (-1);
3156 		}
3157 		if (percent < 1) {
3158 			(void) printf(E_LINE);
3159 			(void) printf(
3160 			    "Percentage value is too small. The value must be"
3161 			    " between 1 and 100;\nretry the operation.\n");
3162 			return (-1);
3163 		}
3164 
3165 		if (percent == 100)
3166 			cylen = Numcyl_usable - 1;
3167 		else
3168 			cylen = (Numcyl_usable * percent) / 100;
3169 
3170 		/* Verify DOS12 partition doesn't exceed max size of 32MB. */
3171 		if ((tsystid == DOSOS12) &&
3172 		    ((long)((long)cylen * cyl_size) > MAXDOS)) {
3173 			int n;
3174 			n = MAXDOS * 100 / (int)(cyl_size) / Numcyl_usable;
3175 			(void) printf(E_LINE);
3176 			(void) printf("Maximum size for a DOS partition "
3177 			    "is %d%%; retry the operation.",
3178 			    n <= 100 ? n : 100);
3179 			return (-1);
3180 		}
3181 
3182 
3183 		max_free = 0;
3184 		for (i = 0; i < FD_NUMPART; i++) {
3185 
3186 			/*
3187 			 * check for free space before partition i
3188 			 * where i varies from 0 to 3
3189 			 *
3190 			 * freespace after partition 3 is unusable
3191 			 * because there are no free partitions
3192 			 *
3193 			 * freespace begins at the end of previous partition
3194 			 * or cylinder 1
3195 			 */
3196 			if (i) {
3197 				/* Not an empty table */
3198 				first_free = LE_32(partition[i - 1]->relsect) +
3199 				    LE_32(partition[i - 1]->numsect);
3200 			} else {
3201 				first_free = cyl_size;
3202 			}
3203 
3204 			/*
3205 			 * freespace ends before the current partition
3206 			 * or the end of the disk (chs end)
3207 			 */
3208 			if (partition[i]->systid == UNUSED) {
3209 				size_free = chs_capacity - first_free;
3210 			} else {
3211 				/*
3212 				 * Partition might start before cylinder 1.
3213 				 * Make sure free space is not negative.
3214 				 */
3215 				size_free =
3216 				    (LE_32(partition[i]->relsect > first_free))
3217 				    ? (LE_32(partition[i]->relsect) -
3218 				    first_free) : 0;
3219 			}
3220 
3221 			/* save largest free space */
3222 			if (max_free < size_free)
3223 				max_free = size_free;
3224 
3225 			if (((uint64_t)cylen * cyl_size) <= size_free) {
3226 				/* We found a place to use */
3227 				break;
3228 			}
3229 			if (partition[i]->systid == UNUSED) {
3230 				(void) printf(E_LINE);
3231 				max_free /= (cyl_size);
3232 				(void) fprintf(stderr, "fdisk: "
3233 				    "Maximum percentage available is %lld\n",
3234 				    100 * max_free / Numcyl_usable);
3235 				return (-1);
3236 			}
3237 		}
3238 
3239 		(void) printf(E_LINE);
3240 		if (i >= FD_NUMPART) {
3241 			(void) fprintf(stderr,
3242 			    "fdisk: Partition table is full.\n");
3243 			return (-1);
3244 		}
3245 
3246 		if ((i = insert_tbl(tsystid, 0, 0, 0, 0, 0, 0, 0,
3247 		    first_free, cylen * cyl_size, 0)) >= 0)  {
3248 			return (i);
3249 		}
3250 		return (-1);
3251 	} else {
3252 
3253 		/* Specifying size in cylinders */
3254 		(void) printf(E_LINE);
3255 		(void) printf(Q_LINE);
3256 		(void) printf("Enter starting cylinder number: ");
3257 		if ((cyl = getcyl()) == -1) {
3258 			(void) printf(E_LINE);
3259 			(void) printf("Invalid number; retry the operation.");
3260 			return (-1);
3261 		}
3262 		if (cyl == 0) {
3263 			(void) printf(E_LINE);
3264 			(void) printf(
3265 			    "New partition cannot start at cylinder 0.\n");
3266 			return (-1);
3267 		}
3268 
3269 
3270 		if (cyl >= Numcyl_usable) {
3271 			(void) printf(E_LINE);
3272 			(void) printf(
3273 			    "Cylinder %d is out of bounds, "
3274 			    "the maximum is %d.\n",
3275 			    cyl, Numcyl_usable - 1);
3276 			return (-1);
3277 		}
3278 
3279 		(void) printf(Q_LINE);
3280 		(void) printf("Enter partition size in cylinders: ");
3281 		if ((cylen = getcyl()) == -1) {
3282 			(void) printf(E_LINE);
3283 			(void) printf("Invalid number, retry the operation.");
3284 			return (-1);
3285 		}
3286 
3287 		for (i = 0; i < FD_NUMPART; i++) {
3288 			uint32_t	t_relsect, t_numsect;
3289 
3290 			if (partition[i]->systid == UNUSED)
3291 				break;
3292 			t_relsect = LE_32(partition[i]->relsect);
3293 			t_numsect = LE_32(partition[i]->numsect);
3294 
3295 			if (cyl * cyl_size >= t_relsect &&
3296 			    cyl * cyl_size < t_relsect + t_numsect) {
3297 				(void) printf(E_LINE);
3298 				(void) printf(
3299 				    "Cylinder %d is already allocated"
3300 				    "\nretry the operation.",
3301 				    cyl);
3302 				return (-1);
3303 			}
3304 
3305 			if (cyl * cyl_size < t_relsect &&
3306 			    (cyl + cylen - 1) * cyl_size > t_relsect) {
3307 				(void) printf(E_LINE);
3308 				(void) printf(
3309 				    "Maximum size for partition is %u cylinders"
3310 				    "\nretry the operation.",
3311 				    (t_relsect - cyl * cyl_size) / cyl_size);
3312 				return (-1);
3313 			}
3314 		}
3315 
3316 		/* Verify partition doesn't exceed disk size or 2 TB */
3317 		if (cyl + cylen > Numcyl_usable) {
3318 			(void) printf(E_LINE);
3319 			if (Numcyl > Numcyl_usable) {
3320 				(void) printf(
3321 				    "Maximum size for partition is %d "
3322 				    "cylinders; \nretry the operation.",
3323 				    Numcyl_usable - cyl);
3324 			} else {
3325 				(void) printf(
3326 				    "Maximum size for partition is %d "
3327 				    "cylinders; \nretry the operation.",
3328 				    Numcyl_usable - cyl);
3329 			}
3330 			return (-1);
3331 		}
3332 
3333 		/* Verify DOS12 partition doesn't exceed max size of 32MB. */
3334 		if ((tsystid == DOSOS12) &&
3335 		    ((long)((long)cylen * cyl_size) > MAXDOS)) {
3336 			(void) printf(E_LINE);
3337 			(void) printf(
3338 			    "Maximum size for a %s partition is %ld cylinders;"
3339 			    "\nretry the operation.",
3340 			    Dstr, MAXDOS / (int)(cyl_size));
3341 			return (-1);
3342 		}
3343 
3344 		(void) printf(E_LINE);
3345 		i = insert_tbl(tsystid, 0, 0, 0, 0, 0, 0, 0,
3346 		    cyl * cyl_size, cylen * cyl_size, 0);
3347 		if (i < 0)
3348 			return (-1);
3349 
3350 		if (verify_tbl() < 0) {
3351 			(void) printf(E_LINE);
3352 			(void) printf("fdisk: Cannot create partition table\n");
3353 			return (-1);
3354 		}
3355 
3356 		return (i);
3357 	}
3358 }
3359 
3360 /*
3361  * dispmenu
3362  * Display command menu (interactive mode).
3363  */
3364 static void
3365 dispmenu(void)
3366 {
3367 	(void) printf(M_LINE);
3368 #ifdef i386
3369 	(void) printf(
3370 	    "SELECT ONE OF THE FOLLOWING:\n"
3371 	    "   1. Create a partition\n"
3372 	    "   2. Specify the active partition\n"
3373 	    "   3. Delete a partition\n"
3374 	    "   4. Change between Solaris and Solaris2 Partition IDs\n"
3375 	    "   5. Edit/View extended partitions\n"
3376 	    "   6. Exit (update disk configuration and exit)\n"
3377 	    "   7. Cancel (exit without updating disk configuration)\n");
3378 #else
3379 	(void) printf(
3380 	    "SELECT ONE OF THE FOLLOWING:\n"
3381 	    "   1. Create a partition\n"
3382 	    "   2. Specify the active partition\n"
3383 	    "   3. Delete a partition\n"
3384 	    "   4. Change between Solaris and Solaris2 Partition IDs\n"
3385 	    "   5. Exit (update disk configuration and exit)\n"
3386 	    "   6. Cancel (exit without updating disk configuration)\n");
3387 #endif
3388 }
3389 
3390 /*
3391  * pchange
3392  * Change the ACTIVE designation of a partition.
3393  */
3394 static int
3395 pchange(void)
3396 {
3397 	char s[80];
3398 	int i, j;
3399 
3400 	for (;;) {
3401 		(void) printf(Q_LINE);
3402 			{
3403 			(void) printf(
3404 			    "Specify the partition number to boot from"
3405 			    " (or specify 0 for none): ");
3406 			}
3407 		(void) fgets(s, sizeof (s), stdin);
3408 		rm_blanks(s);
3409 		if (((s[1] != '\0') && (s[1] != '\n')) ||
3410 		    (s[0] < '0') || (s[0] > '4')) {
3411 			(void) printf(E_LINE);
3412 			(void) printf(
3413 			    "Invalid response, please specify a number"
3414 			    " between 0 and 4.\n");
3415 		} else {
3416 			break;
3417 		}
3418 	}
3419 	if (s[0] == '0') {	/* No active partitions */
3420 		for (i = 0; i < FD_NUMPART; i++) {
3421 			if (Table[i].systid != UNUSED &&
3422 			    Table[i].bootid == ACTIVE)
3423 				Table[i].bootid = 0;
3424 		}
3425 		(void) printf(E_LINE);
3426 			(void) printf(
3427 			    "No partition is currently marked as active.");
3428 		return (0);
3429 	} else {	/* User has selected a partition to be active */
3430 
3431 		i = s[0] - '1';
3432 
3433 		if (Table[i].systid == UNUSED) {
3434 			(void) printf(E_LINE);
3435 			(void) printf("Partition does not exist.");
3436 			return (-1);
3437 		}
3438 		/* a DOS-DATA or EXT-DOS partition cannot be active */
3439 		else if ((Table[i].systid == DOSDATA) ||
3440 		    (Table[i].systid == EXTDOS) ||
3441 		    (Table[i].systid == FDISK_EXTLBA)) {
3442 			(void) printf(E_LINE);
3443 			(void) printf(
3444 			    "DOS-DATA, EXT_DOS and EXT_DOS_LBA partitions "
3445 			    "cannot be made active.\n");
3446 			(void) printf("Select another partition.");
3447 			return (-1);
3448 		}
3449 		Table[i].bootid = ACTIVE;
3450 		for (j = 0; j < FD_NUMPART; j++) {
3451 			if (j != i)
3452 			Table[j].bootid = 0;
3453 		}
3454 	}
3455 	(void) printf(E_LINE);
3456 		{
3457 		(void) printf(
3458 		    "Partition %d is now active. The system will start up"
3459 		    " from this\n", i + 1);
3460 		(void) printf("partition after the next reboot.");
3461 		}
3462 	return (1);
3463 }
3464 
3465 /*
3466  * Change between SOLARIS and SOLARIS2 partition id
3467  */
3468 static int
3469 ppartid(void)
3470 {
3471 	char	*p, s[80];
3472 	int	i;
3473 
3474 	for (;;) {
3475 		(void) printf(Q_LINE);
3476 		(void) printf("Specify the partition number to change"
3477 		    " (or enter 0 to exit): ");
3478 		if (!fgets(s, sizeof (s), stdin))
3479 			return (1);
3480 		i = strtol(s, &p, 10);
3481 
3482 		if (*p != '\n' || i < 0 || i > FD_NUMPART) {
3483 			(void) printf(E_LINE);
3484 			(void) printf(
3485 			    "Invalid response, retry the operation.\n");
3486 			continue;
3487 		}
3488 
3489 		if (i == 0) {
3490 			/* exit delete command */
3491 			(void) printf(E_LINE); /* clear error message */
3492 			return (1);
3493 		}
3494 
3495 		i -= 1;
3496 
3497 		if (Table[i].systid == SUNIXOS) {
3498 			Table[i].systid = SUNIXOS2;
3499 		} else if (Table[i].systid == SUNIXOS2) {
3500 			Table[i].systid = SUNIXOS;
3501 		} else {
3502 			(void) printf(E_LINE);
3503 			(void) printf(
3504 			    "Partition %d is not a Solaris partition.",
3505 			    i + 1);
3506 			continue;
3507 		}
3508 
3509 		(void) printf(E_LINE);
3510 		(void) printf("Partition %d has been changed.", i + 1);
3511 		return (1);
3512 	}
3513 }
3514 
3515 /*
3516  * pdelete
3517  * Remove partition entry from the table (interactive mode).
3518  */
3519 static char
3520 pdelete(void)
3521 {
3522 	char s[80];
3523 	int i;
3524 	char pactive;
3525 
3526 DEL1:	(void) printf(Q_LINE);
3527 	(void) printf("Specify the partition number to delete"
3528 	    " (or enter 0 to exit): ");
3529 	(void) fgets(s, sizeof (s), stdin);
3530 	rm_blanks(s);
3531 	if ((s[0] == '0')) {	/* exit delete command */
3532 		(void) printf(E_LINE);	/* clear error message */
3533 		return (1);
3534 	}
3535 	/* Accept only a single digit between 1 and 4 */
3536 	if (((s[1] != '\0') && (s[1] != '\n')) ||
3537 	    (i = atoi(s)) < 1 || i > FD_NUMPART) {
3538 		(void) printf(E_LINE);
3539 		(void) printf("Invalid response, retry the operation.\n");
3540 		goto DEL1;
3541 	} else {		/* Found a digit between 1 and 4 */
3542 		--i;	/* Structure begins with element 0 */
3543 	}
3544 
3545 	if (Table[i].systid == UNUSED) {
3546 		(void) printf(E_LINE);
3547 		(void) printf("Partition %d does not exist.", i + 1);
3548 		return (-1);
3549 	}
3550 
3551 #ifdef i386
3552 	if (fdisk_is_dos_extended(Table[i].systid) &&
3553 	    (Table[i].relsect == fdisk_get_ext_beg_sec(epp)) &&
3554 	    fdisk_get_logical_drive_count(epp)) {
3555 		(void) printf(Q_LINE);
3556 		(void) printf("There are logical drives inside the"
3557 		    " extended partition\n");
3558 		(void) printf("Are you sure of proceeding with deletion ?"
3559 		    " (type \"y\" or \"n\") ");
3560 
3561 		(void) printf(E_LINE);
3562 		if (! yesno()) {
3563 			return (1);
3564 		}
3565 		if (fdisk_mounted_logical_drives(epp) == FDISK_EMOUNTED) {
3566 			(void) printf(Q_LINE);
3567 			(void) printf("There are mounted logical drives. "
3568 			    "Committing changes now can cause data loss or "
3569 			    "corruption. Unmount all logical drives and then "
3570 			    "try committing the changes again.\n");
3571 			(void) printf("Press enter to continue.\n");
3572 			ext_read_input(s);
3573 			return (1);
3574 		}
3575 		(void) fdisk_delete_ext_part(epp);
3576 	} else {
3577 #endif
3578 		(void) printf(Q_LINE);
3579 		(void) printf("Are you sure you want to delete partition %d?"
3580 		    " This will make all files and \n", i + 1);
3581 		(void) printf("programs in this partition inaccessible (type"
3582 		    " \"y\" or \"n\"). ");
3583 
3584 		(void) printf(E_LINE);
3585 		if (! yesno()) {
3586 			return (1);
3587 		}
3588 #ifdef i386
3589 	}
3590 #endif
3591 
3592 	if (Table[i].bootid == ACTIVE) {
3593 		pactive = 1;
3594 	} else {
3595 		pactive = 0;
3596 	}
3597 
3598 	(void) memset(&Table[i], 0, sizeof (struct ipart));
3599 
3600 	(void) printf(E_LINE);
3601 	(void) printf("Partition %d has been deleted.", i + 1);
3602 
3603 	if (pactive) {
3604 		(void) printf(" This was the active partition.");
3605 	}
3606 
3607 	return (1);
3608 }
3609 
3610 /*
3611  * rm_blanks
3612  * Remove blanks from strings of user responses.
3613  */
3614 static void
3615 rm_blanks(char *s)
3616 {
3617 	register int i, j;
3618 
3619 	for (i = 0; i < CBUFLEN; i++) {
3620 		if ((s[i] == ' ') || (s[i] == '\t')) {
3621 			continue;
3622 		} else {
3623 			/* Found first non-blank character of the string */
3624 			break;
3625 		}
3626 	}
3627 	for (j = 0; i < CBUFLEN; j++, i++) {
3628 		if ((s[j] = s[i]) == '\0') {
3629 			/* Reached end of string */
3630 			return;
3631 		}
3632 	}
3633 }
3634 
3635 /*
3636  * getcyl
3637  * Take the user-specified cylinder number and convert it from a
3638  * string to a decimal value.
3639  */
3640 static int
3641 getcyl(void)
3642 {
3643 	int slen, i, j;
3644 	unsigned int cyl;
3645 	(void) fgets(s, sizeof (s), stdin);
3646 	rm_blanks(s);
3647 	slen = strlen(s);
3648 	if (s[slen - 1] == '\n')
3649 		slen--;
3650 	j = 1;
3651 	cyl = 0;
3652 	for (i = slen - 1; i >= 0; i--) {
3653 		if (s[i] < '0' || s[i] > '9') {
3654 			return (-1);
3655 		}
3656 		cyl += (j * (s[i] - '0'));
3657 		j *= 10;
3658 	}
3659 	return (cyl);
3660 }
3661 
3662 /*
3663  * disptbl
3664  * Display the current fdisk table; determine percentage
3665  * of the disk used for each partition.
3666  */
3667 static void
3668 disptbl(void)
3669 {
3670 	int i;
3671 	unsigned int startcyl, endcyl, length, percent, remainder;
3672 	char *stat, *type;
3673 	int is_pmbr = 0;
3674 
3675 	if ((heads == 0) || (sectors == 0)) {
3676 		(void) printf("WARNING: critical disk geometry information"
3677 		    " missing!\n");
3678 		(void) printf("\theads = %d, sectors = %d\n", heads, sectors);
3679 		exit(1);
3680 	}
3681 
3682 	(void) printf(HOME);
3683 	(void) printf(T_LINE);
3684 	(void) printf("             Total disk size is %d cylinders\n", Numcyl);
3685 	(void) printf("             Cylinder size is %d (%d byte) blocks\n\n",
3686 	    heads * sectors, sectsiz);
3687 	(void) printf(
3688 	    "                                               Cylinders\n");
3689 	(void) printf(
3690 	    "      Partition   Status    Type          Start   End   Length"
3691 	    "    %%\n");
3692 	(void) printf(
3693 	    "      =========   ======    ============  =====   ===   ======"
3694 	    "   ===");
3695 
3696 
3697 	for (i = 0; i < FD_NUMPART; i++) {
3698 
3699 		if (Table[i].systid == UNUSED) {
3700 			continue;
3701 		}
3702 
3703 		if (Table[i].bootid == ACTIVE)
3704 			stat = Actvstr;
3705 		else
3706 			stat = NAstr;
3707 		switch (Table[i].systid) {
3708 		case UNIXOS:
3709 			type = Ustr;
3710 			break;
3711 		case SUNIXOS:
3712 			type = SUstr;
3713 #ifdef i386
3714 			if (fdisk_is_linux_swap(epp, Table[i].relsect,
3715 			    NULL) == 0)
3716 				type = LINSWAPstr;
3717 #endif
3718 			break;
3719 		case SUNIXOS2:
3720 			type = SU2str;
3721 			break;
3722 		case X86BOOT:
3723 			type = X86str;
3724 			break;
3725 		case DOSOS12:
3726 			type = Dstr;
3727 			break;
3728 		case DOSOS16:
3729 			type = D16str;
3730 			break;
3731 		case EXTDOS:
3732 			type = EDstr;
3733 			break;
3734 		case DOSDATA:
3735 			type = DDstr;
3736 			break;
3737 		case DOSHUGE:
3738 			type = DBstr;
3739 			break;
3740 		case PCIXOS:
3741 			type = PCstr;
3742 			break;
3743 		case DIAGPART:
3744 			type = DIAGstr;
3745 			break;
3746 		case FDISK_IFS:
3747 			type = IFSstr;
3748 			break;
3749 		case FDISK_AIXBOOT:
3750 			type = AIXstr;
3751 			break;
3752 		case FDISK_AIXDATA:
3753 			type = AIXDstr;
3754 			break;
3755 		case FDISK_OS2BOOT:
3756 			type = OS2str;
3757 			break;
3758 		case FDISK_WINDOWS:
3759 			type = WINstr;
3760 			break;
3761 		case FDISK_EXT_WIN:
3762 			type = EWINstr;
3763 			break;
3764 		case FDISK_FAT95:
3765 			type = FAT95str;
3766 			break;
3767 		case FDISK_EXTLBA:
3768 			type = EXTLstr;
3769 			break;
3770 		case FDISK_LINUX:
3771 			type = LINUXstr;
3772 			break;
3773 		case FDISK_CPM:
3774 			type = CPMstr;
3775 			break;
3776 		case FDISK_NOVELL2:
3777 			type = NOV2str;
3778 			break;
3779 		case FDISK_NOVELL3:
3780 			type = NOVstr;
3781 			break;
3782 		case FDISK_QNX4:
3783 			type = QNXstr;
3784 			break;
3785 		case FDISK_QNX42:
3786 			type = QNX2str;
3787 			break;
3788 		case FDISK_QNX43:
3789 			type = QNX3str;
3790 			break;
3791 		case FDISK_LINUXNAT:
3792 			type = LINNATstr;
3793 			break;
3794 		case FDISK_NTFSVOL1:
3795 			type = NTFSVOL1str;
3796 			break;
3797 		case FDISK_NTFSVOL2:
3798 			type = NTFSVOL2str;
3799 			break;
3800 		case FDISK_BSD:
3801 			type = BSDstr;
3802 			break;
3803 		case FDISK_NEXTSTEP:
3804 			type = NEXTSTEPstr;
3805 			break;
3806 		case FDISK_BSDIFS:
3807 			type = BSDIFSstr;
3808 			break;
3809 		case FDISK_BSDISWAP:
3810 			type = BSDISWAPstr;
3811 			break;
3812 		case EFI_PMBR:
3813 			type = EFIstr;
3814 			if (LE_32(Table[i].numsect) == DK_MAX_2TB)
3815 				is_pmbr = 1;
3816 
3817 			break;
3818 		default:
3819 			type = Ostr;
3820 			break;
3821 		}
3822 		startcyl = LE_32(Table[i].relsect) /
3823 		    (unsigned long)(heads * sectors);
3824 
3825 		if (LE_32(Table[i].numsect) == DK_MAX_2TB) {
3826 			endcyl = Numcyl - 1;
3827 			length = endcyl - startcyl + 1;
3828 		} else {
3829 			length = LE_32(Table[i].numsect) /
3830 			    (unsigned long)(heads * sectors);
3831 			if (LE_32(Table[i].numsect) %
3832 			    (unsigned long)(heads * sectors))
3833 				length++;
3834 			endcyl = startcyl + length - 1;
3835 		}
3836 
3837 		percent = length * 100 / Numcyl_usable;
3838 		if ((remainder = (length * 100 % Numcyl_usable)) != 0) {
3839 			if ((remainder * 100 / Numcyl_usable) > 50) {
3840 				/* round up */
3841 				percent++;
3842 			}
3843 			/* Else leave the percent as is since it's already */
3844 			/* rounded down */
3845 		}
3846 		if (percent > 100)
3847 			percent = 100;
3848 		(void) printf(
3849 		    "\n          %d       %s    %-12.12s   %4d  %4d    %4d"
3850 		    "    %3d",
3851 		    i + 1, stat, type, startcyl, endcyl, length, percent);
3852 	}
3853 
3854 	/* Print warning message if table is empty */
3855 	if (nopartdefined()) {
3856 		(void) printf(W_LINE);
3857 		(void) printf("WARNING: no partitions are defined!");
3858 	} else {
3859 		/* Clear the warning line */
3860 		(void) printf(W_LINE);
3861 
3862 		/* Print warning if disk > 2TB and is not EFI PMBR */
3863 		if (!is_pmbr && (dev_capacity > DK_MAX_2TB))
3864 			(void) printf("WARNING: Disk is larger than 2 TB. "
3865 			    "Upper limit is 2 TB for non-EFI partition ID\n");
3866 	}
3867 }
3868 
3869 /*
3870  * print_Table
3871  * Write the detailed fdisk table to standard error for
3872  * the selected disk device.
3873  */
3874 static void
3875 print_Table(void)
3876 {
3877 	int i;
3878 
3879 	(void) fprintf(stderr,
3880 	    "  SYSID ACT BHEAD BSECT BEGCYL   EHEAD ESECT ENDCYL   RELSECT"
3881 	    "   NUMSECT\n");
3882 
3883 	for (i = 0; i < FD_NUMPART; i++) {
3884 		(void) fprintf(stderr, "  %-5d ", Table[i].systid);
3885 		(void) fprintf(stderr, "%-3d ", Table[i].bootid);
3886 		(void) fprintf(stderr, "%-5d ", Table[i].beghead);
3887 		(void) fprintf(stderr, "%-5d ", Table[i].begsect & 0x3f);
3888 		(void) fprintf(stderr, "%-8d ",
3889 		    (((uint_t)Table[i].begsect & 0xc0) << 2) + Table[i].begcyl);
3890 
3891 		(void) fprintf(stderr, "%-5d ", Table[i].endhead);
3892 		(void) fprintf(stderr, "%-5d ", Table[i].endsect & 0x3f);
3893 		(void) fprintf(stderr, "%-8d ",
3894 		    (((uint_t)Table[i].endsect & 0xc0) << 2) + Table[i].endcyl);
3895 		(void) fprintf(stderr, "%-10u ", LE_32(Table[i].relsect));
3896 		(void) fprintf(stderr, "%-10u\n", LE_32(Table[i].numsect));
3897 
3898 	}
3899 }
3900 
3901 /*
3902  * copy_Table_to_Old_Table
3903  * Copy Table into Old_Table. The function only copies the systid,
3904  * numsect, relsect, and bootid values because they are the only
3905  * ones compared when determining if Table has changed.
3906  */
3907 static void
3908 copy_Table_to_Old_Table(void)
3909 {
3910 	int i;
3911 	for (i = 0; i < FD_NUMPART; i++)  {
3912 		(void) memcpy(&Old_Table[i], &Table[i], sizeof (Table[0]));
3913 	}
3914 }
3915 
3916 /*
3917  * nulltbl
3918  * Zero out the systid, numsect, relsect, and bootid values in the
3919  * fdisk table.
3920  */
3921 static void
3922 nulltbl(void)
3923 {
3924 	int i;
3925 
3926 	for (i = 0; i < FD_NUMPART; i++)  {
3927 		Table[i].systid = UNUSED;
3928 		Table[i].numsect = LE_32(UNUSED);
3929 		Table[i].relsect = LE_32(UNUSED);
3930 		Table[i].bootid = 0;
3931 		skip_verify[i] = 0;
3932 	}
3933 }
3934 
3935 /*
3936  * copy_Bootblk_to_Table
3937  * Copy the bytes from the boot record to an internal "Table".
3938  * All unused are padded with zeros starting at offset 446.
3939  */
3940 static void
3941 copy_Bootblk_to_Table(void)
3942 {
3943 	int i;
3944 	char *bootptr;
3945 	struct ipart iparts[FD_NUMPART];
3946 
3947 	/* Get an aligned copy of the partition tables */
3948 	(void) memcpy(iparts, Bootblk->parts, sizeof (iparts));
3949 	bootptr = (char *)iparts;	/* Points to start of partition table */
3950 	if (LE_16(Bootblk->signature) != MBB_MAGIC)  {
3951 		/* Signature is missing */
3952 		nulltbl();
3953 		(void) memcpy(Bootblk->bootinst, &BootCod, BOOTSZ);
3954 		return;
3955 	}
3956 	/*
3957 	 * When the DOS fdisk command deletes a partition, it is not
3958 	 * recognized by the old algorithm.  The algorithm that
3959 	 * follows looks at each entry in the Bootrec and copies all
3960 	 * those that are valid.
3961 	 */
3962 	for (i = 0; i < FD_NUMPART; i++) {
3963 		if (iparts[i].systid == 0) {
3964 			/* Null entry */
3965 			(void) memset(&Table[i], 0, sizeof (struct ipart));
3966 		} else {
3967 			fill_ipart(bootptr, &Table[i]);
3968 		}
3969 		bootptr += sizeof (struct ipart);
3970 	}
3971 
3972 	/* For now, always replace the bootcode with ours */
3973 	(void) memcpy(Bootblk->bootinst, &BootCod, BOOTSZ);
3974 	copy_Table_to_Bootblk();
3975 }
3976 
3977 /*
3978  * fill_ipart
3979  * Initialize ipart structure values.
3980  */
3981 static void
3982 fill_ipart(char *bootptr, struct ipart *partp)
3983 {
3984 #ifdef sparc
3985 	/* Packing struct ipart for Sparc */
3986 	partp->bootid	= getbyte(&bootptr);
3987 	partp->beghead	= getbyte(&bootptr);
3988 	partp->begsect	= getbyte(&bootptr);
3989 	partp->begcyl	= getbyte(&bootptr);
3990 	partp->systid	= getbyte(&bootptr);
3991 	partp->endhead	= getbyte(&bootptr);
3992 	partp->endsect	= getbyte(&bootptr);
3993 	partp->endcyl	= getbyte(&bootptr);
3994 	partp->relsect	= (int32_t)getlong(&bootptr);
3995 	partp->numsect	= (int32_t)getlong(&bootptr);
3996 #else
3997 	*partp = *(struct ipart *)bootptr;
3998 #endif
3999 }
4000 
4001 /*
4002  * getbyte, getlong
4003  *	Get a byte, a short, or a long (SPARC only).
4004  */
4005 #ifdef sparc
4006 uchar_t
4007 getbyte(char **bp)
4008 {
4009 	uchar_t	b;
4010 
4011 	b = (uchar_t)**bp;
4012 	*bp = *bp + 1;
4013 	return (b);
4014 }
4015 
4016 uint32_t
4017 getlong(char **bp)
4018 {
4019 	int32_t	b, bh, bl;
4020 
4021 	bh = ((**bp) << 8) | *(*bp + 1);
4022 	*bp += 2;
4023 	bl = ((**bp) << 8) | *(*bp + 1);
4024 	*bp += 2;
4025 
4026 	b = (bh << 16) | bl;
4027 	return ((uint32_t)b);
4028 }
4029 #endif
4030 
4031 /*
4032  * copy_Table_to_Bootblk
4033  * Copy the table into the boot record. Note that the unused
4034  * entries will always be the last ones in the table and they are
4035  * marked with 100 in sysind. The the unused portion of the table
4036  * is padded with zeros in the bytes after the used entries.
4037  */
4038 static void
4039 copy_Table_to_Bootblk(void)
4040 {
4041 	struct ipart *boot_ptr, *tbl_ptr;
4042 
4043 	boot_ptr = (struct ipart *)Bootblk->parts;
4044 	tbl_ptr = (struct ipart *)&Table[0].bootid;
4045 	for (; tbl_ptr < (struct ipart *)&Table[FD_NUMPART].bootid;
4046 	    tbl_ptr++, boot_ptr++) {
4047 		if (tbl_ptr->systid == UNUSED)
4048 			(void) memset(boot_ptr, 0, sizeof (struct ipart));
4049 		else
4050 			(void) memcpy(boot_ptr, tbl_ptr, sizeof (struct ipart));
4051 	}
4052 	Bootblk->signature = LE_16(MBB_MAGIC);
4053 }
4054 
4055 /*
4056  * TableChanged
4057  *	Check for any changes in the partition table.
4058  */
4059 static int
4060 TableChanged(void)
4061 {
4062 	int i, changed;
4063 
4064 	changed = 0;
4065 	for (i = 0; i < FD_NUMPART; i++) {
4066 		if (memcmp(&Old_Table[i], &Table[i], sizeof (Table[0])) != 0) {
4067 			/* Partition table changed, write back to disk */
4068 			changed = 1;
4069 		}
4070 	}
4071 
4072 	return (changed);
4073 }
4074 
4075 /*
4076  * ffile_write
4077  *	Display contents of partition table to standard output or
4078  *	another file name without writing it to the disk (-W file).
4079  */
4080 static void
4081 ffile_write(char *file)
4082 {
4083 	register int	i;
4084 	FILE *fp;
4085 
4086 	/*
4087 	 * If file isn't standard output, then it's a file name.
4088 	 * Open file and write it.
4089 	 */
4090 	if (file != (char *)stdout) {
4091 		if ((fp = fopen(file, "w")) == NULL) {
4092 			(void) fprintf(stderr,
4093 			    "fdisk: Cannot open output file %s.\n",
4094 			    file);
4095 			exit(1);
4096 		}
4097 	}
4098 	else
4099 		fp = stdout;
4100 
4101 	/*
4102 	 * Write the fdisk table information
4103 	 */
4104 	(void) fprintf(fp, "\n* %s default fdisk table\n", Dfltdev);
4105 	(void) fprintf(fp, "* Dimensions:\n");
4106 	(void) fprintf(fp, "*   %4d bytes/sector\n", sectsiz);
4107 	(void) fprintf(fp, "*   %4d sectors/track\n", sectors);
4108 	(void) fprintf(fp, "*   %4d tracks/cylinder\n", heads);
4109 	(void) fprintf(fp, "*   %4d cylinders\n", Numcyl);
4110 	(void) fprintf(fp, "*\n");
4111 	/* Write virtual (HBA) geometry, if required	*/
4112 	if (v_flag) {
4113 		(void) fprintf(fp, "* HBA Dimensions:\n");
4114 		(void) fprintf(fp, "*   %4d bytes/sector\n", sectsiz);
4115 		(void) fprintf(fp, "*   %4d sectors/track\n", hba_sectors);
4116 		(void) fprintf(fp, "*   %4d tracks/cylinder\n", hba_heads);
4117 		(void) fprintf(fp, "*   %4d cylinders\n", hba_Numcyl);
4118 		(void) fprintf(fp, "*\n");
4119 	}
4120 	(void) fprintf(fp, "* systid:\n");
4121 	(void) fprintf(fp, "*    1: DOSOS12\n");
4122 	(void) fprintf(fp, "*    2: PCIXOS\n");
4123 	(void) fprintf(fp, "*    4: DOSOS16\n");
4124 	(void) fprintf(fp, "*    5: EXTDOS\n");
4125 	(void) fprintf(fp, "*    6: DOSBIG\n");
4126 	(void) fprintf(fp, "*    7: FDISK_IFS\n");
4127 	(void) fprintf(fp, "*    8: FDISK_AIXBOOT\n");
4128 	(void) fprintf(fp, "*    9: FDISK_AIXDATA\n");
4129 	(void) fprintf(fp, "*   10: FDISK_0S2BOOT\n");
4130 	(void) fprintf(fp, "*   11: FDISK_WINDOWS\n");
4131 	(void) fprintf(fp, "*   12: FDISK_EXT_WIN\n");
4132 	(void) fprintf(fp, "*   14: FDISK_FAT95\n");
4133 	(void) fprintf(fp, "*   15: FDISK_EXTLBA\n");
4134 	(void) fprintf(fp, "*   18: DIAGPART\n");
4135 	(void) fprintf(fp, "*   65: FDISK_LINUX\n");
4136 	(void) fprintf(fp, "*   82: FDISK_CPM\n");
4137 	(void) fprintf(fp, "*   86: DOSDATA\n");
4138 	(void) fprintf(fp, "*   98: OTHEROS\n");
4139 	(void) fprintf(fp, "*   99: UNIXOS\n");
4140 	(void) fprintf(fp, "*  100: FDISK_NOVELL2\n");
4141 	(void) fprintf(fp, "*  101: FDISK_NOVELL3\n");
4142 	(void) fprintf(fp, "*  119: FDISK_QNX4\n");
4143 	(void) fprintf(fp, "*  120: FDISK_QNX42\n");
4144 	(void) fprintf(fp, "*  121: FDISK_QNX43\n");
4145 	(void) fprintf(fp, "*  130: SUNIXOS\n");
4146 	(void) fprintf(fp, "*  131: FDISK_LINUXNAT\n");
4147 	(void) fprintf(fp, "*  134: FDISK_NTFSVOL1\n");
4148 	(void) fprintf(fp, "*  135: FDISK_NTFSVOL2\n");
4149 	(void) fprintf(fp, "*  165: FDISK_BSD\n");
4150 	(void) fprintf(fp, "*  167: FDISK_NEXTSTEP\n");
4151 	(void) fprintf(fp, "*  183: FDISK_BSDIFS\n");
4152 	(void) fprintf(fp, "*  184: FDISK_BSDISWAP\n");
4153 	(void) fprintf(fp, "*  190: X86BOOT\n");
4154 	(void) fprintf(fp, "*  191: SUNIXOS2\n");
4155 	(void) fprintf(fp, "*  238: EFI_PMBR\n");
4156 	(void) fprintf(fp, "*  239: EFI_FS\n");
4157 	(void) fprintf(fp, "*\n");
4158 	(void) fprintf(fp,
4159 	    "\n* Id    Act  Bhead  Bsect  Bcyl    Ehead  Esect  Ecyl"
4160 	    "    Rsect      Numsect\n");
4161 
4162 	for (i = 0; i < FD_NUMPART; i++) {
4163 		(void) fprintf(fp,
4164 		    "  %-5d %-4d %-6d %-6d %-7d %-6d %-6d %-7d %-10u"
4165 		    " %-10u\n",
4166 		    Table[i].systid,
4167 		    Table[i].bootid,
4168 		    Table[i].beghead,
4169 		    Table[i].begsect & 0x3f,
4170 		    ((Table[i].begcyl & 0xff) | ((Table[i].begsect &
4171 		    0xc0) << 2)),
4172 		    Table[i].endhead,
4173 		    Table[i].endsect & 0x3f,
4174 		    ((Table[i].endcyl & 0xff) | ((Table[i].endsect &
4175 		    0xc0) << 2)),
4176 		    LE_32(Table[i].relsect),
4177 		    LE_32(Table[i].numsect));
4178 	}
4179 #ifdef i386
4180 	if (fdisk_ext_part_exists(epp)) {
4181 		struct ipart ext_tab;
4182 		logical_drive_t *temp;
4183 		uint32_t rsect, numsect, tempsect = 0;
4184 		for (temp = fdisk_get_ld_head(epp); temp != NULL;
4185 		    temp = temp->next) {
4186 			ext_tab = temp->parts[0];
4187 			rsect = tempsect + LE_32(ext_tab.relsect) +
4188 			    fdisk_get_ext_beg_sec(epp);
4189 			numsect = LE_32(ext_tab.