1 /* vi: set sw=4 ts=4: */
2 /* fdisk.c -- Partition table manipulator for Linux.
3  *
4  * Copyright (C) 1992  A. V. Le Blanc (LeBlanc@mcc.ac.uk)
5  * Copyright (C) 2001,2002 Vladimir Oleynik <dzo@simtreas.ru> (initial bb port)
6  *
7  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
8  */
9 //config:config FDISK
10 //config:	bool "fdisk"
11 //config:	default y
12 //config:	select PLATFORM_LINUX
13 //config:	help
14 //config:	  The fdisk utility is used to divide hard disks into one or more
15 //config:	  logical disks, which are generally called partitions. This utility
16 //config:	  can be used to list and edit the set of partitions or BSD style
17 //config:	  'disk slices' that are defined on a hard drive.
18 //config:
19 //config:config FDISK_SUPPORT_LARGE_DISKS
20 //config:	bool "Support over 4GB disks"
21 //config:	default y
22 //config:	depends on FDISK
23 //config:	depends on !LFS   # with LFS no special code is needed
24 //config:	help
25 //config:	  Enable this option to support large disks > 4GB.
26 //config:
27 //config:config FEATURE_FDISK_WRITABLE
28 //config:	bool "Write support"
29 //config:	default y
30 //config:	depends on FDISK
31 //config:	help
32 //config:	  Enabling this option allows you to create or change a partition table
33 //config:	  and write those changes out to disk. If you leave this option
34 //config:	  disabled, you will only be able to view the partition table.
35 //config:
36 //config:config FEATURE_AIX_LABEL
37 //config:	bool "Support AIX disklabels"
38 //config:	default n
39 //config:	depends on FDISK && FEATURE_FDISK_WRITABLE
40 //config:	help
41 //config:	  Enabling this option allows you to create or change AIX disklabels.
42 //config:	  Most people can safely leave this option disabled.
43 //config:
44 //config:config FEATURE_SGI_LABEL
45 //config:	bool "Support SGI disklabels"
46 //config:	default n
47 //config:	depends on FDISK && FEATURE_FDISK_WRITABLE
48 //config:	help
49 //config:	  Enabling this option allows you to create or change SGI disklabels.
50 //config:	  Most people can safely leave this option disabled.
51 //config:
52 //config:config FEATURE_SUN_LABEL
53 //config:	bool "Support SUN disklabels"
54 //config:	default n
55 //config:	depends on FDISK && FEATURE_FDISK_WRITABLE
56 //config:	help
57 //config:	  Enabling this option allows you to create or change SUN disklabels.
58 //config:	  Most people can safely leave this option disabled.
59 //config:
60 //config:config FEATURE_OSF_LABEL
61 //config:	bool "Support BSD disklabels"
62 //config:	default n
63 //config:	depends on FDISK && FEATURE_FDISK_WRITABLE
64 //config:	help
65 //config:	  Enabling this option allows you to create or change BSD disklabels
66 //config:	  and define and edit BSD disk slices.
67 //config:
68 //config:config FEATURE_GPT_LABEL
69 //config:	bool "Support GPT disklabels"
70 //config:	default n
71 //config:	depends on FDISK && FEATURE_FDISK_WRITABLE
72 //config:	help
73 //config:	  Enabling this option allows you to view GUID Partition Table
74 //config:	  disklabels.
75 //config:
76 //config:config FEATURE_FDISK_ADVANCED
77 //config:	bool "Support expert mode"
78 //config:	default y
79 //config:	depends on FDISK && FEATURE_FDISK_WRITABLE
80 //config:	help
81 //config:	  Enabling this option allows you to do terribly unsafe things like
82 //config:	  define arbitrary drive geometry, move the beginning of data in a
83 //config:	  partition, and similarly evil things. Unless you have a very good
84 //config:	  reason you would be wise to leave this disabled.
85 
86 //applet:IF_FDISK(APPLET(fdisk, BB_DIR_SBIN, BB_SUID_DROP))
87 
88 //kbuild:lib-$(CONFIG_FDISK) += fdisk.o
89 
90 /* Looks like someone forgot to add this to config system */
91 //usage:#ifndef ENABLE_FEATURE_FDISK_BLKSIZE
92 //usage:# define ENABLE_FEATURE_FDISK_BLKSIZE 0
93 //usage:# define IF_FEATURE_FDISK_BLKSIZE(a)
94 //usage:#endif
95 //usage:
96 //usage:#define fdisk_trivial_usage
97 //usage:       "[-ul" IF_FEATURE_FDISK_BLKSIZE("s") "] "
98 //usage:       "[-C CYLINDERS] [-H HEADS] [-S SECTORS] [-b SSZ] DISK"
99 //usage:#define fdisk_full_usage "\n\n"
100 //usage:       "Change partition table\n"
101 //usage:     "\n	-u		Start and End are in sectors (instead of cylinders)"
102 //usage:     "\n	-l		Show partition table for each DISK, then exit"
103 //usage:	IF_FEATURE_FDISK_BLKSIZE(
104 //usage:     "\n	-s		Show partition sizes in kb for each DISK, then exit"
105 //usage:	)
106 //usage:     "\n	-b 2048		(for certain MO disks) use 2048-byte sectors"
107 //usage:     "\n	-C CYLINDERS	Set number of cylinders/heads/sectors"
108 //usage:     "\n	-H HEADS"
109 //usage:     "\n	-S SECTORS"
110 
111 #ifndef _LARGEFILE64_SOURCE
112 /* For lseek64 */
113 # define _LARGEFILE64_SOURCE
114 #endif
115 #include <assert.h>             /* assert */
116 #include <sys/mount.h>
117 #if !defined(BLKSSZGET)
118 # define BLKSSZGET _IO(0x12, 104)
119 #endif
120 #if !defined(BLKGETSIZE64)
121 # define BLKGETSIZE64 _IOR(0x12,114,size_t)
122 #endif
123 #include "libbb.h"
124 #include "unicode.h"
125 
126 #if BB_LITTLE_ENDIAN
127 # define inline_if_little_endian ALWAYS_INLINE
128 #else
129 # define inline_if_little_endian /* nothing */
130 #endif
131 
132 
133 /* Looks like someone forgot to add this to config system */
134 #ifndef ENABLE_FEATURE_FDISK_BLKSIZE
135 # define ENABLE_FEATURE_FDISK_BLKSIZE 0
136 # define IF_FEATURE_FDISK_BLKSIZE(a)
137 #endif
138 
139 #define DEFAULT_SECTOR_SIZE      512
140 #define DEFAULT_SECTOR_SIZE_STR "512"
141 #define MAX_SECTOR_SIZE         2048
142 #define SECTOR_SIZE              512 /* still used in osf/sgi/sun code */
143 #define MAXIMUM_PARTS             60
144 
145 #define ACTIVE_FLAG             0x80
146 
147 #define EXTENDED                0x05
148 #define WIN98_EXTENDED          0x0f
149 #define LINUX_PARTITION         0x81
150 #define LINUX_SWAP              0x82
151 #define LINUX_NATIVE            0x83
152 #define LINUX_EXTENDED          0x85
153 #define LINUX_LVM               0x8e
154 #define LINUX_RAID              0xfd
155 
156 
157 enum {
158 	OPT_b = 1 << 0,
159 	OPT_C = 1 << 1,
160 	OPT_H = 1 << 2,
161 	OPT_l = 1 << 3,
162 	OPT_S = 1 << 4,
163 	OPT_u = 1 << 5,
164 	OPT_s = (1 << 6) * ENABLE_FEATURE_FDISK_BLKSIZE,
165 };
166 
167 
168 typedef unsigned long long ullong;
169 /* Used for sector numbers. Partition formats we know
170  * do not support more than 2^32 sectors
171  */
172 typedef uint32_t sector_t;
173 #if UINT_MAX == 4294967295
174 # define SECT_FMT ""
175 #elif ULONG_MAX == 4294967295
176 # define SECT_FMT "l"
177 #else
178 # error Cant detect sizeof(uint32_t)
179 #endif
180 
181 struct hd_geometry {
182 	unsigned char heads;
183 	unsigned char sectors;
184 	unsigned short cylinders;
185 	unsigned long start;
186 };
187 
188 #define HDIO_GETGEO     0x0301  /* get device geometry */
189 
190 static const char msg_building_new_label[] ALIGN1 =
191 "Building a new %s. Changes will remain in memory only,\n"
192 "until you decide to write them. After that the previous content\n"
193 "won't be recoverable.\n\n";
194 
195 static const char msg_part_already_defined[] ALIGN1 =
196 "Partition %u is already defined, delete it before re-adding\n";
197 
198 
199 struct partition {
200 	unsigned char boot_ind;         /* 0x80 - active */
201 	unsigned char head;             /* starting head */
202 	unsigned char sector;           /* starting sector */
203 	unsigned char cyl;              /* starting cylinder */
204 	unsigned char sys_ind;          /* what partition type */
205 	unsigned char end_head;         /* end head */
206 	unsigned char end_sector;       /* end sector */
207 	unsigned char end_cyl;          /* end cylinder */
208 	unsigned char start4[4];        /* starting sector counting from 0 */
209 	unsigned char size4[4];         /* nr of sectors in partition */
210 } PACKED;
211 
212 /*
213  * per partition table entry data
214  *
215  * The four primary partitions have the same sectorbuffer (MBRbuffer)
216  * and have NULL ext_pointer.
217  * Each logical partition table entry has two pointers, one for the
218  * partition and one link to the next one.
219  */
220 struct pte {
221 	struct partition *part_table;   /* points into sectorbuffer */
222 	struct partition *ext_pointer;  /* points into sectorbuffer */
223 	sector_t offset_from_dev_start; /* disk sector number */
224 	char *sectorbuffer;             /* disk sector contents */
225 #if ENABLE_FEATURE_FDISK_WRITABLE
226 	char changed;                   /* boolean */
227 #endif
228 };
229 
230 #define unable_to_open "can't open '%s'"
231 #define unable_to_read "can't read from %s"
232 #define unable_to_seek "can't seek on %s"
233 
234 enum label_type {
235 	LABEL_DOS, LABEL_SUN, LABEL_SGI, LABEL_AIX, LABEL_OSF, LABEL_GPT
236 };
237 
238 #define LABEL_IS_DOS	(LABEL_DOS == current_label_type)
239 
240 #if ENABLE_FEATURE_SUN_LABEL
241 #define LABEL_IS_SUN	(LABEL_SUN == current_label_type)
242 #define STATIC_SUN static
243 #else
244 #define LABEL_IS_SUN	0
245 #define STATIC_SUN extern
246 #endif
247 
248 #if ENABLE_FEATURE_SGI_LABEL
249 #define LABEL_IS_SGI	(LABEL_SGI == current_label_type)
250 #define STATIC_SGI static
251 #else
252 #define LABEL_IS_SGI	0
253 #define STATIC_SGI extern
254 #endif
255 
256 #if ENABLE_FEATURE_AIX_LABEL
257 #define LABEL_IS_AIX	(LABEL_AIX == current_label_type)
258 #define STATIC_AIX static
259 #else
260 #define LABEL_IS_AIX	0
261 #define STATIC_AIX extern
262 #endif
263 
264 #if ENABLE_FEATURE_OSF_LABEL
265 #define LABEL_IS_OSF	(LABEL_OSF == current_label_type)
266 #define STATIC_OSF static
267 #else
268 #define LABEL_IS_OSF	0
269 #define STATIC_OSF extern
270 #endif
271 
272 #if ENABLE_FEATURE_GPT_LABEL
273 #define LABEL_IS_GPT	(LABEL_GPT == current_label_type)
274 #define STATIC_GPT static
275 #else
276 #define LABEL_IS_GPT	0
277 #define STATIC_GPT extern
278 #endif
279 
280 enum action { OPEN_MAIN, TRY_ONLY, CREATE_EMPTY_DOS, CREATE_EMPTY_SUN };
281 
282 static void update_units(void);
283 #if ENABLE_FEATURE_FDISK_WRITABLE
284 static void change_units(void);
285 static void reread_partition_table(int leave);
286 static void delete_partition(int i);
287 static unsigned get_partition(int warn, unsigned max);
288 static void list_types(const char *const *sys);
289 static sector_t read_int(sector_t low, sector_t dflt, sector_t high, sector_t base, const char *mesg);
290 #endif
291 static const char *partition_type(unsigned char type);
292 static void get_geometry(void);
293 static void read_pte(struct pte *pe, sector_t offset);
294 #if ENABLE_FEATURE_SUN_LABEL || ENABLE_FEATURE_FDISK_WRITABLE
295 static int get_boot(enum action what);
296 #else
297 static int get_boot(void);
298 #endif
299 
300 #define PLURAL   0
301 #define SINGULAR 1
302 
303 static sector_t get_start_sect(const struct partition *p);
304 static sector_t get_nr_sects(const struct partition *p);
305 
306 /* DOS partition types */
307 
308 static const char *const i386_sys_types[] = {
309 	"\x00" "Empty",
310 	"\x01" "FAT12",
311 	"\x04" "FAT16 <32M",
312 	"\x05" "Extended",         /* DOS 3.3+ extended partition */
313 	"\x06" "FAT16",            /* DOS 16-bit >=32M */
314 	"\x07" "HPFS/NTFS",        /* OS/2 IFS, eg, HPFS or NTFS or QNX */
315 	"\x0a" "OS/2 Boot Manager",/* OS/2 Boot Manager */
316 	"\x0b" "Win95 FAT32",
317 	"\x0c" "Win95 FAT32 (LBA)",/* LBA really is 'Extended Int 13h' */
318 	"\x0e" "Win95 FAT16 (LBA)",
319 	"\x0f" "Win95 Ext'd (LBA)",
320 	"\x11" "Hidden FAT12",
321 	"\x12" "Compaq diagnostics",
322 	"\x14" "Hidden FAT16 <32M",
323 	"\x16" "Hidden FAT16",
324 	"\x17" "Hidden HPFS/NTFS",
325 	"\x1b" "Hidden Win95 FAT32",
326 	"\x1c" "Hidden W95 FAT32 (LBA)",
327 	"\x1e" "Hidden W95 FAT16 (LBA)",
328 	"\x3c" "Part.Magic recovery",
329 	"\x41" "PPC PReP Boot",
330 	"\x42" "SFS",
331 	"\x63" "GNU HURD or SysV", /* GNU HURD or Mach or Sys V/386 (such as ISC UNIX) */
332 	"\x80" "Old Minix",        /* Minix 1.4a and earlier */
333 	"\x81" "Minix / old Linux",/* Minix 1.4b and later */
334 	"\x82" "Linux swap",       /* also Solaris */
335 	"\x83" "Linux",
336 	"\x84" "OS/2 hidden C: drive",
337 	"\x85" "Linux extended",
338 	"\x86" "NTFS volume set",
339 	"\x87" "NTFS volume set",
340 	"\x8e" "Linux LVM",
341 	"\x9f" "BSD/OS",           /* BSDI */
342 	"\xa0" "Thinkpad hibernation",
343 	"\xa5" "FreeBSD",          /* various BSD flavours */
344 	"\xa6" "OpenBSD",
345 	"\xa8" "Darwin UFS",
346 	"\xa9" "NetBSD",
347 	"\xab" "Darwin boot",
348 	"\xb7" "BSDI fs",
349 	"\xb8" "BSDI swap",
350 	"\xbe" "Solaris boot",
351 	"\xeb" "BeOS fs",
352 	"\xee" "EFI GPT",                    /* Intel EFI GUID Partition Table */
353 	"\xef" "EFI (FAT-12/16/32)",         /* Intel EFI System Partition */
354 	"\xf0" "Linux/PA-RISC boot",         /* Linux/PA-RISC boot loader */
355 	"\xf2" "DOS secondary",              /* DOS 3.3+ secondary */
356 	"\xfd" "Linux raid autodetect",      /* New (2.2.x) raid partition with
357 						autodetect using persistent
358 						superblock */
359 #if 0 /* ENABLE_WEIRD_PARTITION_TYPES */
360 	"\x02" "XENIX root",
361 	"\x03" "XENIX usr",
362 	"\x08" "AIX",              /* AIX boot (AIX -- PS/2 port) or SplitDrive */
363 	"\x09" "AIX bootable",     /* AIX data or Coherent */
364 	"\x10" "OPUS",
365 	"\x18" "AST SmartSleep",
366 	"\x24" "NEC DOS",
367 	"\x39" "Plan 9",
368 	"\x40" "Venix 80286",
369 	"\x4d" "QNX4.x",
370 	"\x4e" "QNX4.x 2nd part",
371 	"\x4f" "QNX4.x 3rd part",
372 	"\x50" "OnTrack DM",
373 	"\x51" "OnTrack DM6 Aux1", /* (or Novell) */
374 	"\x52" "CP/M",             /* CP/M or Microport SysV/AT */
375 	"\x53" "OnTrack DM6 Aux3",
376 	"\x54" "OnTrackDM6",
377 	"\x55" "EZ-Drive",
378 	"\x56" "Golden Bow",
379 	"\x5c" "Priam Edisk",
380 	"\x61" "SpeedStor",
381 	"\x64" "Novell Netware 286",
382 	"\x65" "Novell Netware 386",
383 	"\x70" "DiskSecure Multi-Boot",
384 	"\x75" "PC/IX",
385 	"\x93" "Amoeba",
386 	"\x94" "Amoeba BBT",       /* (bad block table) */
387 	"\xa7" "NeXTSTEP",
388 	"\xbb" "Boot Wizard hidden",
389 	"\xc1" "DRDOS/sec (FAT-12)",
390 	"\xc4" "DRDOS/sec (FAT-16 < 32M)",
391 	"\xc6" "DRDOS/sec (FAT-16)",
392 	"\xc7" "Syrinx",
393 	"\xda" "Non-FS data",
394 	"\xdb" "CP/M / CTOS / ...",/* CP/M or Concurrent CP/M or
395 	                              Concurrent DOS or CTOS */
396 	"\xde" "Dell Utility",     /* Dell PowerEdge Server utilities */
397 	"\xdf" "BootIt",           /* BootIt EMBRM */
398 	"\xe1" "DOS access",       /* DOS access or SpeedStor 12-bit FAT
399 	                              extended partition */
400 	"\xe3" "DOS R/O",          /* DOS R/O or SpeedStor */
401 	"\xe4" "SpeedStor",        /* SpeedStor 16-bit FAT extended
402 	                              partition < 1024 cyl. */
403 	"\xf1" "SpeedStor",
404 	"\xf4" "SpeedStor",        /* SpeedStor large partition */
405 	"\xfe" "LANstep",          /* SpeedStor >1024 cyl. or LANstep */
406 	"\xff" "BBT",              /* Xenix Bad Block Table */
407 #endif
408 	NULL
409 };
410 
411 enum {
412 	dev_fd = 3                  /* the disk */
413 };
414 
415 /* Globals */
416 struct globals {
417 	char *line_ptr;
418 
419 	const char *disk_device;
420 	int g_partitions; // = 4;       /* maximum partition + 1 */
421 	unsigned units_per_sector; // = 1;
422 	unsigned sector_size; // = DEFAULT_SECTOR_SIZE;
423 	unsigned user_set_sector_size;
424 	unsigned sector_offset; // = 1;
425 	unsigned g_heads, g_sectors, g_cylinders;
426 	smallint /* enum label_type */ current_label_type;
427 	smallint display_in_cyl_units; // = 1;
428 #if ENABLE_FEATURE_OSF_LABEL
429 	smallint possibly_osf_label;
430 #endif
431 
432 	smallint listing;               /* no aborts for fdisk -l */
433 	smallint dos_compatible_flag; // = 1;
434 #if ENABLE_FEATURE_FDISK_WRITABLE
435 	//int dos_changed;
436 	smallint nowarn;                /* no warnings for fdisk -l/-s */
437 #endif
438 	int ext_index;                  /* the prime extended partition */
439 	unsigned user_cylinders, user_heads, user_sectors;
440 	unsigned pt_heads, pt_sectors;
441 	unsigned kern_heads, kern_sectors;
442 	sector_t extended_offset;       /* offset of link pointers */
443 	sector_t total_number_of_sectors;
444 
445 	jmp_buf listingbuf;
446 	char line_buffer[80];
447 	/* Raw disk label. For DOS-type partition tables the MBR,
448 	 * with descriptions of the primary partitions. */
449 	char MBRbuffer[MAX_SECTOR_SIZE];
450 	/* Partition tables */
451 	struct pte ptes[MAXIMUM_PARTS];
452 };
453 #define G (*ptr_to_globals)
454 #define line_ptr             (G.line_ptr            )
455 #define disk_device          (G.disk_device         )
456 #define g_partitions         (G.g_partitions        )
457 #define units_per_sector     (G.units_per_sector    )
458 #define sector_size          (G.sector_size         )
459 #define user_set_sector_size (G.user_set_sector_size)
460 #define sector_offset        (G.sector_offset       )
461 #define g_heads              (G.g_heads             )
462 #define g_sectors            (G.g_sectors           )
463 #define g_cylinders          (G.g_cylinders         )
464 #define current_label_type   (G.current_label_type  )
465 #define display_in_cyl_units (G.display_in_cyl_units)
466 #define possibly_osf_label   (G.possibly_osf_label  )
467 #define listing                 (G.listing                )
468 #define dos_compatible_flag     (G.dos_compatible_flag    )
469 #define nowarn                  (G.nowarn                 )
470 #define ext_index               (G.ext_index              )
471 #define user_cylinders          (G.user_cylinders         )
472 #define user_heads              (G.user_heads             )
473 #define user_sectors            (G.user_sectors           )
474 #define pt_heads                (G.pt_heads               )
475 #define pt_sectors              (G.pt_sectors             )
476 #define kern_heads              (G.kern_heads             )
477 #define kern_sectors            (G.kern_sectors           )
478 #define extended_offset         (G.extended_offset        )
479 #define total_number_of_sectors (G.total_number_of_sectors)
480 #define listingbuf      (G.listingbuf     )
481 #define line_buffer     (G.line_buffer    )
482 #define MBRbuffer       (G.MBRbuffer      )
483 #define ptes            (G.ptes           )
484 #define INIT_G() do { \
485 	SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
486 	sector_size = DEFAULT_SECTOR_SIZE; \
487 	sector_offset = 1; \
488 	g_partitions = 4; \
489 	display_in_cyl_units = 1; \
490 	units_per_sector = 1; \
491 	dos_compatible_flag = 1; \
492 } while (0)
493 
494 
495 /* TODO: move to libbb? */
496 /* TODO: return unsigned long long, FEATURE_FDISK_BLKSIZE _can_ handle
497  * disks > 2^32 sectors
498  */
bb_BLKGETSIZE_sectors(int fd)499 static sector_t bb_BLKGETSIZE_sectors(int fd)
500 {
501 	uint64_t v64;
502 	unsigned long longsectors;
503 
504 	if (ioctl(fd, BLKGETSIZE64, &v64) == 0) {
505 		/* Got bytes, convert to 512 byte sectors */
506 		v64 >>= 9;
507 		if (v64 != (sector_t)v64) {
508  ret_trunc:
509 			/* Not only DOS, but all other partition tables
510 			 * we support can't record more than 32 bit
511 			 * sector counts or offsets
512 			 */
513 			bb_error_msg("device has more than 2^32 sectors, can't use all of them");
514 			v64 = (uint32_t)-1L;
515 		}
516 		return v64;
517 	}
518 	/* Needs temp of type long */
519 	if (ioctl(fd, BLKGETSIZE, &longsectors)) {
520 		/* Perhaps this is a disk image */
521 		off_t sz = lseek(fd, 0, SEEK_END);
522 		longsectors = 0;
523 		if (sz > 0)
524 			longsectors = (uoff_t)sz / sector_size;
525 		lseek(fd, 0, SEEK_SET);
526 	}
527 	if (sizeof(long) > sizeof(sector_t)
528 	 && longsectors != (sector_t)longsectors
529 	) {
530 		goto ret_trunc;
531 	}
532 	return longsectors;
533 }
534 
535 
536 #define IS_EXTENDED(i) \
537 	((i) == EXTENDED || (i) == WIN98_EXTENDED || (i) == LINUX_EXTENDED)
538 
539 #define cround(n)       (display_in_cyl_units ? ((n)/units_per_sector)+1 : (n))
540 
541 #define scround(x)      (((x)+units_per_sector-1)/units_per_sector)
542 
543 #define pt_offset(b, n) \
544 	((struct partition *)((b) + 0x1be + (n) * sizeof(struct partition)))
545 
546 #define sector(s)       ((s) & 0x3f)
547 
548 #define cylinder(s, c)  ((c) | (((s) & 0xc0) << 2))
549 
550 static void
close_dev_fd(void)551 close_dev_fd(void)
552 {
553 	/* Not really closing, but making sure it is open, and to harmless place */
554 	xmove_fd(xopen(bb_dev_null, O_RDONLY), dev_fd);
555 }
556 
557 /* Return partition name */
558 static const char *
partname(const char * dev,int pno,int lth)559 partname(const char *dev, int pno, int lth)
560 {
561 	const char *p;
562 	int w, wp;
563 	int bufsiz;
564 	char *bufp;
565 
566 	bufp = auto_string(xzalloc(80));
567 	bufsiz = 80;
568 
569 	w = strlen(dev);
570 	p = "";
571 
572 	if (isdigit(dev[w-1]))
573 		p = "p";
574 
575 	/* devfs kludge - note: fdisk partition names are not supposed
576 	   to equal kernel names, so there is no reason to do this */
577 	if (strcmp(dev + w - 4, "disc") == 0) {
578 		w -= 4;
579 		p = "part";
580 	}
581 
582 	wp = strlen(p);
583 
584 	if (lth) {
585 		snprintf(bufp, bufsiz, "%*.*s%s%-2u",
586 			lth-wp-2, w, dev, p, pno);
587 	} else {
588 		snprintf(bufp, bufsiz, "%.*s%s%-2u", w, dev, p, pno);
589 	}
590 	return bufp;
591 }
592 
593 static ALWAYS_INLINE struct partition *
get_part_table(int i)594 get_part_table(int i)
595 {
596 	return ptes[i].part_table;
597 }
598 
599 static const char *
str_units(int n)600 str_units(int n)
601 {      /* n==1: use singular */
602 	if (n == 1)
603 		return display_in_cyl_units ? "cylinder" : "sector";
604 	return display_in_cyl_units ? "cylinders" : "sectors";
605 }
606 
607 static int
valid_part_table_flag(const char * mbuffer)608 valid_part_table_flag(const char *mbuffer)
609 {
610 	return (mbuffer[510] == 0x55 && (uint8_t)mbuffer[511] == 0xaa);
611 }
612 
fdisk_fatal(const char * why)613 static void fdisk_fatal(const char *why)
614 {
615 	if (listing) {
616 		close_dev_fd();
617 		longjmp(listingbuf, 1);
618 	}
619 	bb_error_msg_and_die(why, disk_device);
620 }
621 
622 static void
seek_sector(sector_t secno)623 seek_sector(sector_t secno)
624 {
625 #if ENABLE_FDISK_SUPPORT_LARGE_DISKS
626 	off64_t off = (off64_t)secno * sector_size;
627 	if (lseek64(dev_fd, off, SEEK_SET) == (off64_t) -1)
628 		fdisk_fatal(unable_to_seek);
629 #else
630 	uint64_t off = (uint64_t)secno * sector_size;
631 	if (off > MAXINT(off_t)
632 	 || lseek(dev_fd, (off_t)off, SEEK_SET) == (off_t) -1
633 	) {
634 		fdisk_fatal(unable_to_seek);
635 	}
636 #endif
637 }
638 
639 #if ENABLE_FEATURE_FDISK_WRITABLE
640 /* Read line; return 0 or first printable char */
641 static int
read_line(const char * prompt)642 read_line(const char *prompt)
643 {
644 	int sz;
645 
646 	sz = read_line_input(NULL, prompt, line_buffer, sizeof(line_buffer), /*timeout*/ -1);
647 	if (sz <= 0)
648 		exit(EXIT_SUCCESS); /* Ctrl-D or Ctrl-C */
649 
650 	if (line_buffer[sz-1] == '\n')
651 		line_buffer[--sz] = '\0';
652 
653 	line_ptr = line_buffer;
654 	while (*line_ptr != '\0' && (unsigned char)*line_ptr <= ' ')
655 		line_ptr++;
656 	return *line_ptr;
657 }
658 
659 static void
set_all_unchanged(void)660 set_all_unchanged(void)
661 {
662 	int i;
663 
664 	for (i = 0; i < MAXIMUM_PARTS; i++)
665 		ptes[i].changed = 0;
666 }
667 
668 static ALWAYS_INLINE void
set_changed(int i)669 set_changed(int i)
670 {
671 	ptes[i].changed = 1;
672 }
673 
674 static ALWAYS_INLINE void
write_part_table_flag(char * b)675 write_part_table_flag(char *b)
676 {
677 	b[510] = 0x55;
678 	b[511] = 0xaa;
679 }
680 
681 static char
read_nonempty(const char * mesg)682 read_nonempty(const char *mesg)
683 {
684 	while (!read_line(mesg))
685 		continue;
686 	return *line_ptr;
687 }
688 
689 static char
read_maybe_empty(const char * mesg)690 read_maybe_empty(const char *mesg)
691 {
692 	if (!read_line(mesg)) {
693 		line_ptr = line_buffer;
694 		line_ptr[0] = '\n';
695 		line_ptr[1] = '\0';
696 	}
697 	return line_ptr[0];
698 }
699 
700 static int
read_hex(const char * const * sys)701 read_hex(const char *const *sys)
702 {
703 	unsigned long v;
704 	while (1) {
705 		read_nonempty("Hex code (type L to list codes): ");
706 		if ((line_ptr[0] | 0x20) == 'l') {
707 			list_types(sys);
708 			continue;
709 		}
710 		v = bb_strtoul(line_ptr, NULL, 16);
711 		if (v <= 0xff)
712 			return v;
713 	}
714 }
715 
716 static void
write_sector(sector_t secno,const void * buf)717 write_sector(sector_t secno, const void *buf)
718 {
719 	seek_sector(secno);
720 	xwrite(dev_fd, buf, sector_size);
721 }
722 #endif /* FEATURE_FDISK_WRITABLE */
723 
724 
725 #include "fdisk_aix.c"
726 
727 struct sun_partition {
728 	unsigned char info[128];   /* Informative text string */
729 	unsigned char spare0[14];
730 	struct sun_info {
731 		unsigned char spare1;
732 		unsigned char id;
733 		unsigned char spare2;
734 		unsigned char flags;
735 	} infos[8];
736 	unsigned char spare1[246]; /* Boot information etc. */
737 	unsigned short rspeed;     /* Disk rotational speed */
738 	unsigned short pcylcount;  /* Physical cylinder count */
739 	unsigned short sparecyl;   /* extra sects per cylinder */
740 	unsigned char spare2[4];   /* More magic... */
741 	unsigned short ilfact;     /* Interleave factor */
742 	unsigned short ncyl;       /* Data cylinder count */
743 	unsigned short nacyl;      /* Alt. cylinder count */
744 	unsigned short ntrks;      /* Tracks per cylinder */
745 	unsigned short nsect;      /* Sectors per track */
746 	unsigned char spare3[4];   /* Even more magic... */
747 	struct sun_partinfo {
748 		uint32_t start_cylinder;
749 		uint32_t num_sectors;
750 	} partitions[8];
751 	unsigned short magic;      /* Magic number */
752 	unsigned short csum;       /* Label xor'd checksum */
753 } FIX_ALIASING;
754 typedef struct sun_partition sun_partition;
755 #define sunlabel ((sun_partition *)MBRbuffer)
756 STATIC_OSF void bsd_select(void);
757 STATIC_OSF void xbsd_print_disklabel(int);
758 #include "fdisk_osf.c"
759 
760 STATIC_GPT void gpt_list_table(int xtra);
761 #include "fdisk_gpt.c"
762 
763 #if ENABLE_FEATURE_SGI_LABEL || ENABLE_FEATURE_SUN_LABEL
764 static uint16_t
fdisk_swap16(uint16_t x)765 fdisk_swap16(uint16_t x)
766 {
767 	return (x << 8) | (x >> 8);
768 }
769 
770 static uint32_t
fdisk_swap32(uint32_t x)771 fdisk_swap32(uint32_t x)
772 {
773 	return (x << 24) |
774 	       ((x & 0xFF00) << 8) |
775 	       ((x & 0xFF0000) >> 8) |
776 	       (x >> 24);
777 }
778 #endif
779 
780 STATIC_SGI const char *const sgi_sys_types[];
781 STATIC_SGI unsigned sgi_get_num_sectors(int i);
782 STATIC_SGI int sgi_get_sysid(int i);
783 STATIC_SGI void sgi_delete_partition(int i);
784 STATIC_SGI void sgi_change_sysid(int i, int sys);
785 STATIC_SGI void sgi_list_table(int xtra);
786 #if ENABLE_FEATURE_FDISK_ADVANCED
787 STATIC_SGI void sgi_set_xcyl(void);
788 #endif
789 STATIC_SGI int verify_sgi(int verbose);
790 STATIC_SGI void sgi_add_partition(int n, int sys);
791 STATIC_SGI void sgi_set_swappartition(int i);
792 STATIC_SGI const char *sgi_get_bootfile(void);
793 STATIC_SGI void sgi_set_bootfile(const char* aFile);
794 STATIC_SGI void create_sgiinfo(void);
795 STATIC_SGI void sgi_write_table(void);
796 STATIC_SGI void sgi_set_bootpartition(int i);
797 #include "fdisk_sgi.c"
798 
799 STATIC_SUN const char *const sun_sys_types[];
800 STATIC_SUN void sun_delete_partition(int i);
801 STATIC_SUN void sun_change_sysid(int i, int sys);
802 STATIC_SUN void sun_list_table(int xtra);
803 STATIC_SUN void add_sun_partition(int n, int sys);
804 #if ENABLE_FEATURE_FDISK_ADVANCED
805 STATIC_SUN void sun_set_alt_cyl(void);
806 STATIC_SUN void sun_set_ncyl(int cyl);
807 STATIC_SUN void sun_set_xcyl(void);
808 STATIC_SUN void sun_set_ilfact(void);
809 STATIC_SUN void sun_set_rspeed(void);
810 STATIC_SUN void sun_set_pcylcount(void);
811 #endif
812 STATIC_SUN void toggle_sunflags(int i, unsigned char mask);
813 STATIC_SUN void verify_sun(void);
814 STATIC_SUN void sun_write_table(void);
815 #include "fdisk_sun.c"
816 
817 
818 static inline_if_little_endian unsigned
read4_little_endian(const unsigned char * cp)819 read4_little_endian(const unsigned char *cp)
820 {
821 	uint32_t v;
822 	move_from_unaligned32(v, cp);
823 	return SWAP_LE32(v);
824 }
825 
826 static sector_t
get_start_sect(const struct partition * p)827 get_start_sect(const struct partition *p)
828 {
829 	return read4_little_endian(p->start4);
830 }
831 
832 static sector_t
get_nr_sects(const struct partition * p)833 get_nr_sects(const struct partition *p)
834 {
835 	return read4_little_endian(p->size4);
836 }
837 
838 #if ENABLE_FEATURE_FDISK_WRITABLE
839 /* start_sect and nr_sects are stored little endian on all machines */
840 /* moreover, they are not aligned correctly */
841 static inline_if_little_endian void
store4_little_endian(unsigned char * cp,unsigned val)842 store4_little_endian(unsigned char *cp, unsigned val)
843 {
844 	uint32_t v = SWAP_LE32(val);
845 	move_to_unaligned32(cp, v);
846 }
847 
848 static void
set_start_sect(struct partition * p,unsigned start_sect)849 set_start_sect(struct partition *p, unsigned start_sect)
850 {
851 	store4_little_endian(p->start4, start_sect);
852 }
853 
854 static void
set_nr_sects(struct partition * p,unsigned nr_sects)855 set_nr_sects(struct partition *p, unsigned nr_sects)
856 {
857 	store4_little_endian(p->size4, nr_sects);
858 }
859 #endif
860 
861 /* Allocate a buffer and read a partition table sector */
862 static void
read_pte(struct pte * pe,sector_t offset)863 read_pte(struct pte *pe, sector_t offset)
864 {
865 	pe->offset_from_dev_start = offset;
866 	pe->sectorbuffer = xzalloc(sector_size);
867 	seek_sector(offset);
868 	/* xread would make us abort - bad for fdisk -l */
869 	if (full_read(dev_fd, pe->sectorbuffer, sector_size) != sector_size)
870 		fdisk_fatal(unable_to_read);
871 #if ENABLE_FEATURE_FDISK_WRITABLE
872 	pe->changed = 0;
873 #endif
874 	pe->part_table = pe->ext_pointer = NULL;
875 }
876 
877 static sector_t
get_partition_start_from_dev_start(const struct pte * pe)878 get_partition_start_from_dev_start(const struct pte *pe)
879 {
880 	return pe->offset_from_dev_start + get_start_sect(pe->part_table);
881 }
882 
883 #if ENABLE_FEATURE_FDISK_WRITABLE
884 /*
885  * Avoid warning about DOS partitions when no DOS partition was changed.
886  * Here a heuristic "is probably dos partition".
887  * We might also do the opposite and warn in all cases except
888  * for "is probably nondos partition".
889  */
890 #ifdef UNUSED
891 static int
is_dos_partition(int t)892 is_dos_partition(int t)
893 {
894 	return (t == 1 || t == 4 || t == 6 ||
895 		t == 0x0b || t == 0x0c || t == 0x0e ||
896 		t == 0x11 || t == 0x12 || t == 0x14 || t == 0x16 ||
897 		t == 0x1b || t == 0x1c || t == 0x1e || t == 0x24 ||
898 		t == 0xc1 || t == 0xc4 || t == 0xc6);
899 }
900 #endif
901 
902 static void
menu(void)903 menu(void)
904 {
905 	puts("Command Action");
906 	if (LABEL_IS_SUN) {
907 		puts("a\ttoggle a read only flag");           /* sun */
908 		puts("b\tedit bsd disklabel");
909 		puts("c\ttoggle the mountable flag");         /* sun */
910 		puts("d\tdelete a partition");
911 		puts("l\tlist known partition types");
912 		puts("n\tadd a new partition");
913 		puts("o\tcreate a new empty DOS partition table");
914 		puts("p\tprint the partition table");
915 		puts("q\tquit without saving changes");
916 		puts("s\tcreate a new empty Sun disklabel");  /* sun */
917 		puts("t\tchange a partition's system id");
918 		puts("u\tchange display/entry units");
919 		puts("v\tverify the partition table");
920 		puts("w\twrite table to disk and exit");
921 #if ENABLE_FEATURE_FDISK_ADVANCED
922 		puts("x\textra functionality (experts only)");
923 #endif
924 	} else if (LABEL_IS_SGI) {
925 		puts("a\tselect bootable partition");    /* sgi flavour */
926 		puts("b\tedit bootfile entry");          /* sgi */
927 		puts("c\tselect sgi swap partition");    /* sgi flavour */
928 		puts("d\tdelete a partition");
929 		puts("l\tlist known partition types");
930 		puts("n\tadd a new partition");
931 		puts("o\tcreate a new empty DOS partition table");
932 		puts("p\tprint the partition table");
933 		puts("q\tquit without saving changes");
934 		puts("s\tcreate a new empty Sun disklabel");  /* sun */
935 		puts("t\tchange a partition's system id");
936 		puts("u\tchange display/entry units");
937 		puts("v\tverify the partition table");
938 		puts("w\twrite table to disk and exit");
939 	} else if (LABEL_IS_AIX) {
940 		puts("o\tcreate a new empty DOS partition table");
941 		puts("q\tquit without saving changes");
942 		puts("s\tcreate a new empty Sun disklabel");  /* sun */
943 	} else if (LABEL_IS_GPT) {
944 		puts("o\tcreate a new empty DOS partition table");
945 		puts("p\tprint the partition table");
946 		puts("q\tquit without saving changes");
947 		puts("s\tcreate a new empty Sun disklabel");  /* sun */
948 	} else {
949 		puts("a\ttoggle a bootable flag");
950 		puts("b\tedit bsd disklabel");
951 		puts("c\ttoggle the dos compatibility flag");
952 		puts("d\tdelete a partition");
953 		puts("l\tlist known partition types");
954 		puts("n\tadd a new partition");
955 		puts("o\tcreate a new empty DOS partition table");
956 		puts("p\tprint the partition table");
957 		puts("q\tquit without saving changes");
958 		puts("s\tcreate a new empty Sun disklabel");  /* sun */
959 		puts("t\tchange a partition's system id");
960 		puts("u\tchange display/entry units");
961 		puts("v\tverify the partition table");
962 		puts("w\twrite table to disk and exit");
963 #if ENABLE_FEATURE_FDISK_ADVANCED
964 		puts("x\textra functionality (experts only)");
965 #endif
966 	}
967 }
968 #endif /* FEATURE_FDISK_WRITABLE */
969 
970 
971 #if ENABLE_FEATURE_FDISK_ADVANCED
972 static void
xmenu(void)973 xmenu(void)
974 {
975 	puts("Command Action");
976 	if (LABEL_IS_SUN) {
977 		puts("a\tchange number of alternate cylinders");      /*sun*/
978 		puts("c\tchange number of cylinders");
979 		puts("d\tprint the raw data in the partition table");
980 		puts("e\tchange number of extra sectors per cylinder");/*sun*/
981 		puts("h\tchange number of heads");
982 		puts("i\tchange interleave factor");                  /*sun*/
983 		puts("o\tchange rotation speed (rpm)");               /*sun*/
984 		puts("p\tprint the partition table");
985 		puts("q\tquit without saving changes");
986 		puts("r\treturn to main menu");
987 		puts("s\tchange number of sectors/track");
988 		puts("v\tverify the partition table");
989 		puts("w\twrite table to disk and exit");
990 		puts("y\tchange number of physical cylinders");       /*sun*/
991 	} else if (LABEL_IS_SGI) {
992 		puts("b\tmove beginning of data in a partition"); /* !sun */
993 		puts("c\tchange number of cylinders");
994 		puts("d\tprint the raw data in the partition table");
995 		puts("e\tlist extended partitions");          /* !sun */
996 		puts("g\tcreate an IRIX (SGI) partition table");/* sgi */
997 		puts("h\tchange number of heads");
998 		puts("p\tprint the partition table");
999 		puts("q\tquit without saving changes");
1000 		puts("r\treturn to main menu");
1001 		puts("s\tchange number of sectors/track");
1002 		puts("v\tverify the partition table");
1003 		puts("w\twrite table to disk and exit");
1004 	} else if (LABEL_IS_AIX) {
1005 		puts("b\tmove beginning of data in a partition"); /* !sun */
1006 		puts("c\tchange number of cylinders");
1007 		puts("d\tprint the raw data in the partition table");
1008 		puts("e\tlist extended partitions");          /* !sun */
1009 		puts("g\tcreate an IRIX (SGI) partition table");/* sgi */
1010 		puts("h\tchange number of heads");
1011 		puts("p\tprint the partition table");
1012 		puts("q\tquit without saving changes");
1013 		puts("r\treturn to main menu");
1014 		puts("s\tchange number of sectors/track");
1015 		puts("v\tverify the partition table");
1016 		puts("w\twrite table to disk and exit");
1017 	} else {
1018 		puts("b\tmove beginning of data in a partition"); /* !sun */
1019 		puts("c\tchange number of cylinders");
1020 		puts("d\tprint the raw data in the partition table");
1021 		puts("e\tlist extended partitions");          /* !sun */
1022 		puts("f\tfix partition order");               /* !sun, !aix, !sgi */
1023 #if ENABLE_FEATURE_SGI_LABEL
1024 		puts("g\tcreate an IRIX (SGI) partition table");/* sgi */
1025 #endif
1026 		puts("h\tchange number of heads");
1027 		puts("p\tprint the partition table");
1028 		puts("q\tquit without saving changes");
1029 		puts("r\treturn to main menu");
1030 		puts("s\tchange number of sectors/track");
1031 		puts("v\tverify the partition table");
1032 		puts("w\twrite table to disk and exit");
1033 	}
1034 }
1035 #endif /* ADVANCED mode */
1036 
1037 #if ENABLE_FEATURE_FDISK_WRITABLE
1038 static const char *const *
get_sys_types(void)1039 get_sys_types(void)
1040 {
1041 	return (
1042 		LABEL_IS_SUN ? sun_sys_types :
1043 		LABEL_IS_SGI ? sgi_sys_types :
1044 		i386_sys_types);
1045 }
1046 #else
1047 #define get_sys_types() i386_sys_types
1048 #endif
1049 
1050 static const char *
partition_type(unsigned char type)1051 partition_type(unsigned char type)
1052 {
1053 	int i;
1054 	const char *const *types = get_sys_types();
1055 
1056 	for (i = 0; types[i]; i++)
1057 		if ((unsigned char)types[i][0] == type)
1058 			return types[i] + 1;
1059 
1060 	return "Unknown";
1061 }
1062 
1063 static int
is_cleared_partition(const struct partition * p)1064 is_cleared_partition(const struct partition *p)
1065 {
1066 	/* We consider partition "cleared" only if it has only zeros */
1067 	const char *cp = (const char *)p;
1068 	int cnt = sizeof(*p);
1069 	char bits = 0;
1070 	while (--cnt >= 0)
1071 		bits |= *cp++;
1072 	return (bits == 0);
1073 }
1074 
1075 static void
clear_partition(struct partition * p)1076 clear_partition(struct partition *p)
1077 {
1078 	if (p)
1079 		memset(p, 0, sizeof(*p));
1080 }
1081 
1082 #if ENABLE_FEATURE_FDISK_WRITABLE
1083 static int
get_sysid(int i)1084 get_sysid(int i)
1085 {
1086 	return LABEL_IS_SUN ? sunlabel->infos[i].id :
1087 			(LABEL_IS_SGI ? sgi_get_sysid(i) :
1088 				ptes[i].part_table->sys_ind);
1089 }
1090 
1091 static void
list_types(const char * const * sys)1092 list_types(const char *const *sys)
1093 {
1094 	enum { COLS = 3 };
1095 
1096 	unsigned last[COLS];
1097 	unsigned done, next, size;
1098 	int i;
1099 
1100 	for (size = 0; sys[size]; size++)
1101 		continue;
1102 
1103 	done = 0;
1104 	for (i = COLS-1; i >= 0; i--) {
1105 		done += (size + i - done) / (i + 1);
1106 		last[COLS-1 - i] = done;
1107 	}
1108 
1109 	i = done = next = 0;
1110 	do {
1111 		printf("%c%2x %-22.22s", i ? ' ' : '\n',
1112 			(unsigned char)sys[next][0],
1113 			sys[next] + 1);
1114 		next = last[i++] + done;
1115 		if (i >= COLS || next >= last[i]) {
1116 			i = 0;
1117 			next = ++done;
1118 		}
1119 	} while (done < last[0]);
1120 	bb_putchar('\n');
1121 }
1122 
1123 #define set_hsc(h, s, c, sector) do \
1124 { \
1125 	s = sector % g_sectors + 1;  \
1126 	sector /= g_sectors;         \
1127 	h = sector % g_heads;        \
1128 	sector /= g_heads;           \
1129 	c = sector & 0xff;           \
1130 	s |= (sector >> 2) & 0xc0;   \
1131 } while (0)
1132 
set_hsc_start_end(struct partition * p,sector_t start,sector_t stop)1133 static void set_hsc_start_end(struct partition *p, sector_t start, sector_t stop)
1134 {
1135 	if (dos_compatible_flag && (start / (g_sectors * g_heads) > 1023))
1136 		start = g_heads * g_sectors * 1024 - 1;
1137 	set_hsc(p->head, p->sector, p->cyl, start);
1138 
1139 	if (dos_compatible_flag && (stop / (g_sectors * g_heads) > 1023))
1140 		stop = g_heads * g_sectors * 1024 - 1;
1141 	set_hsc(p->end_head, p->end_sector, p->end_cyl, stop);
1142 }
1143 
1144 static void
set_partition(int i,int doext,sector_t start,sector_t stop,int sysid)1145 set_partition(int i, int doext, sector_t start, sector_t stop, int sysid)
1146 {
1147 	struct partition *p;
1148 	sector_t offset;
1149 
1150 	if (doext) {
1151 		p = ptes[i].ext_pointer;
1152 		offset = extended_offset;
1153 	} else {
1154 		p = ptes[i].part_table;
1155 		offset = ptes[i].offset_from_dev_start;
1156 	}
1157 	p->boot_ind = 0;
1158 	p->sys_ind = sysid;
1159 	set_start_sect(p, start - offset);
1160 	set_nr_sects(p, stop - start + 1);
1161 	set_hsc_start_end(p, start, stop);
1162 	ptes[i].changed = 1;
1163 }
1164 #endif
1165 
1166 static int
warn_geometry(void)1167 warn_geometry(void)
1168 {
1169 	if (g_heads && g_sectors && g_cylinders)
1170 		return 0;
1171 
1172 	printf("Unknown value(s) for:");
1173 	if (!g_heads)
1174 		printf(" heads");
1175 	if (!g_sectors)
1176 		printf(" sectors");
1177 	if (!g_cylinders)
1178 		printf(" cylinders");
1179 #if ENABLE_FEATURE_FDISK_WRITABLE
1180 	puts(" (settable in the extra functions menu)");
1181 #else
1182 	bb_putchar('\n');
1183 #endif
1184 	return 1;
1185 }
1186 
1187 static void
update_units(void)1188 update_units(void)
1189 {
1190 	int cyl_units = g_heads * g_sectors;
1191 
1192 	if (display_in_cyl_units && cyl_units)
1193 		units_per_sector = cyl_units;
1194 	else
1195 		units_per_sector = 1;   /* in sectors */
1196 }
1197 
1198 #if ENABLE_FEATURE_FDISK_WRITABLE
1199 static void
warn_cylinders(void)1200 warn_cylinders(void)
1201 {
1202 	if (LABEL_IS_DOS && g_cylinders > 1024 && !nowarn)
1203 		printf("\n"
1204 "The number of cylinders for this disk is set to %u.\n"
1205 "There is nothing wrong with that, but this is larger than 1024,\n"
1206 "and could in certain setups cause problems with:\n"
1207 "1) software that runs at boot time (e.g., old versions of LILO)\n"
1208 "2) booting and partitioning software from other OSs\n"
1209 "   (e.g., DOS FDISK, OS/2 FDISK)\n",
1210 			g_cylinders);
1211 }
1212 #endif
1213 
1214 static void
read_extended(int ext)1215 read_extended(int ext)
1216 {
1217 	int i;
1218 	struct pte *pex;
1219 	struct partition *p, *q;
1220 
1221 	ext_index = ext;
1222 	pex = &ptes[ext];
1223 	pex->ext_pointer = pex->part_table;
1224 
1225 	p = pex->part_table;
1226 	if (!get_start_sect(p)) {
1227 		puts("Bad offset in primary extended partition");
1228 		return;
1229 	}
1230 
1231 	while (IS_EXTENDED(p->sys_ind)) {
1232 		struct pte *pe = &ptes[g_partitions];
1233 
1234 		if (g_partitions >= MAXIMUM_PARTS) {
1235 			/* This is not a Linux restriction, but
1236 			   this program uses arrays of size MAXIMUM_PARTS.
1237 			   Do not try to 'improve' this test. */
1238 			struct pte *pre = &ptes[g_partitions - 1];
1239 #if ENABLE_FEATURE_FDISK_WRITABLE
1240 			printf("Warning: deleting partitions after %u\n",
1241 				g_partitions);
1242 			pre->changed = 1;
1243 #endif
1244 			clear_partition(pre->ext_pointer);
1245 			return;
1246 		}
1247 
1248 		read_pte(pe, extended_offset + get_start_sect(p));
1249 
1250 		if (!extended_offset)
1251 			extended_offset = get_start_sect(p);
1252 
1253 		q = p = pt_offset(pe->sectorbuffer, 0);
1254 		for (i = 0; i < 4; i++, p++) if (get_nr_sects(p)) {
1255 			if (IS_EXTENDED(p->sys_ind)) {
1256 				if (pe->ext_pointer)
1257 					printf("Warning: extra link "
1258 						"pointer in partition table"
1259 						" %u\n", g_partitions + 1);
1260 				else
1261 					pe->ext_pointer = p;
1262 			} else if (p->sys_ind) {
1263 				if (pe->part_table)
1264 					printf("Warning: ignoring extra "
1265 						  "data in partition table"
1266 						  " %u\n", g_partitions + 1);
1267 				else
1268 					pe->part_table = p;
1269 			}
1270 		}
1271 
1272 		/* very strange code here... */
1273 		if (!pe->part_table) {
1274 			if (q != pe->ext_pointer)
1275 				pe->part_table = q;
1276 			else
1277 				pe->part_table = q + 1;
1278 		}
1279 		if (!pe->ext_pointer) {
1280 			if (q != pe->part_table)
1281 				pe->ext_pointer = q;
1282 			else
1283 				pe->ext_pointer = q + 1;
1284 		}
1285 
1286 		p = pe->ext_pointer;
1287 		g_partitions++;
1288 	}
1289 
1290 #if ENABLE_FEATURE_FDISK_WRITABLE
1291 	/* remove empty links */
1292  remove:
1293 	for (i = 4; i < g_partitions; i++) {
1294 		struct pte *pe = &ptes[i];
1295 
1296 		if (!get_nr_sects(pe->part_table)
1297 		 && (g_partitions > 5 || ptes[4].part_table->sys_ind)
1298 		) {
1299 			printf("Omitting empty partition (%u)\n", i+1);
1300 			delete_partition(i);
1301 			goto remove;    /* numbering changed */
1302 		}
1303 	}
1304 #endif
1305 }
1306 
1307 #if ENABLE_FEATURE_FDISK_WRITABLE
1308 static void
create_doslabel(void)1309 create_doslabel(void)
1310 {
1311 	printf(msg_building_new_label, "DOS disklabel");
1312 
1313 	current_label_type = LABEL_DOS;
1314 #if ENABLE_FEATURE_OSF_LABEL
1315 	possibly_osf_label = 0;
1316 #endif
1317 	g_partitions = 4;
1318 
1319 	memset(&MBRbuffer[510 - 4*16], 0, 4*16);
1320 	write_part_table_flag(MBRbuffer);
1321 	extended_offset = 0;
1322 	set_all_unchanged();
1323 	set_changed(0);
1324 	get_boot(CREATE_EMPTY_DOS);
1325 }
1326 #endif
1327 
1328 static void
get_sectorsize(void)1329 get_sectorsize(void)
1330 {
1331 	if (!user_set_sector_size) {
1332 		int arg;
1333 		if (ioctl(dev_fd, BLKSSZGET, &arg) == 0)
1334 			sector_size = arg;
1335 		if (sector_size != DEFAULT_SECTOR_SIZE)
1336 			printf("Note: sector size is %u "
1337 				"(not " DEFAULT_SECTOR_SIZE_STR ")\n",
1338 				sector_size);
1339 	}
1340 }
1341 
1342 static void
get_kernel_geometry(void)1343 get_kernel_geometry(void)
1344 {
1345 	struct hd_geometry geometry;
1346 
1347 	if (!ioctl(dev_fd, HDIO_GETGEO, &geometry)) {
1348 		kern_heads = geometry.heads;
1349 		kern_sectors = geometry.sectors;
1350 		/* never use geometry.cylinders - it is truncated */
1351 	}
1352 }
1353 
1354 static void
get_partition_table_geometry(void)1355 get_partition_table_geometry(void)
1356 {
1357 	const unsigned char *bufp = (const unsigned char *)MBRbuffer;
1358 	struct partition *p;
1359 	int i, h, s, hh, ss;
1360 	int first = 1;
1361 	int bad = 0;
1362 
1363 	if (!(valid_part_table_flag((char*)bufp)))
1364 		return;
1365 
1366 	hh = ss = 0;
1367 	for (i = 0; i < 4; i++) {
1368 		p = pt_offset(bufp, i);
1369 		if (p->sys_ind != 0) {
1370 			h = p->end_head + 1;
1371 			s = (p->end_sector & 077);
1372 			if (first) {
1373 				hh = h;
1374 				ss = s;
1375 				first = 0;
1376 			} else if (hh != h || ss != s)
1377 				bad = 1;
1378 		}
1379 	}
1380 
1381 	if (!first && !bad) {
1382 		pt_heads = hh;
1383 		pt_sectors = ss;
1384 	}
1385 }
1386 
1387 static void
get_geometry(void)1388 get_geometry(void)
1389 {
1390 	int sec_fac;
1391 
1392 	get_sectorsize();
1393 	sec_fac = sector_size / 512;
1394 #if ENABLE_FEATURE_SUN_LABEL
1395 	guess_device_type();
1396 #endif
1397 	g_heads = g_cylinders = g_sectors = 0;
1398 	kern_heads = kern_sectors = 0;
1399 	pt_heads = pt_sectors = 0;
1400 
1401 	get_kernel_geometry();
1402 	get_partition_table_geometry();
1403 
1404 	g_heads = user_heads ? user_heads :
1405 		pt_heads ? pt_heads :
1406 		kern_heads ? kern_heads : 255;
1407 	g_sectors = user_sectors ? user_sectors :
1408 		pt_sectors ? pt_sectors :
1409 		kern_sectors ? kern_sectors : 63;
1410 	total_number_of_sectors = bb_BLKGETSIZE_sectors(dev_fd);
1411 
1412 	sector_offset = 1;
1413 	if (dos_compatible_flag)
1414 		sector_offset = g_sectors;
1415 
1416 	g_cylinders = total_number_of_sectors / (g_heads * g_sectors * sec_fac);
1417 	if (!g_cylinders)
1418 		g_cylinders = user_cylinders;
1419 }
1420 
1421 /*
1422  * Opens disk_device and optionally reads MBR.
1423  *    If what == OPEN_MAIN:
1424  *      Open device, read MBR.  Abort program on short read.  Create empty
1425  *      disklabel if the on-disk structure is invalid (WRITABLE mode).
1426  *    If what == TRY_ONLY:
1427  *      Open device, read MBR.  Return an error if anything is out of place.
1428  *      Do not create an empty disklabel.  This is used for the "list"
1429  *      operations: "fdisk -l /dev/sda" and "fdisk -l" (all devices).
1430  *    If what == CREATE_EMPTY_*:
1431  *      This means that get_boot() was called recursively from create_*label().
1432  *      Do not re-open the device; just set up the ptes array and print
1433  *      geometry warnings.
1434  *
1435  * Returns:
1436  *   -1: no 0xaa55 flag present (possibly entire disk BSD)
1437  *    0: found or created label
1438  *    1: I/O error
1439  */
1440 #if ENABLE_FEATURE_SUN_LABEL || ENABLE_FEATURE_FDISK_WRITABLE
get_boot(enum action what)1441 static int get_boot(enum action what)
1442 #else
1443 static int get_boot(void)
1444 #define get_boot(what) get_boot()
1445 #endif
1446 {
1447 	int i, fd;
1448 
1449 	g_partitions = 4;
1450 	for (i = 0; i < 4; i++) {
1451 		struct pte *pe = &ptes[i];
1452 		pe->part_table = pt_offset(MBRbuffer, i);
1453 		pe->ext_pointer = NULL;
1454 		pe->offset_from_dev_start = 0;
1455 		pe->sectorbuffer = MBRbuffer;
1456 #if ENABLE_FEATURE_FDISK_WRITABLE
1457 		pe->changed = (what == CREATE_EMPTY_DOS);
1458 #endif
1459 	}
1460 
1461 #if ENABLE_FEATURE_FDISK_WRITABLE
1462 // ALERT! highly idiotic design!
1463 // We end up here when we call get_boot() recursively
1464 // via get_boot() [table is bad] -> create_doslabel() -> get_boot(CREATE_EMPTY_DOS).
1465 // or get_boot() [table is bad] -> create_sunlabel() -> get_boot(CREATE_EMPTY_SUN).
1466 // (just factor out re-init of ptes[0,1,2,3] in a separate fn instead?)
1467 // So skip opening device _again_...
1468 	if (what == CREATE_EMPTY_DOS  IF_FEATURE_SUN_LABEL(|| what == CREATE_EMPTY_SUN))
1469 		goto created_table;
1470 
1471 	fd = open(disk_device, (option_mask32 & OPT_l) ? O_RDONLY : O_RDWR);
1472 
1473 	if (fd < 0) {
1474 		fd = open(disk_device, O_RDONLY);
1475 		if (fd < 0) {
1476 			if (what == TRY_ONLY)
1477 				return 1;
1478 			fdisk_fatal(unable_to_open);
1479 		}
1480 		printf("'%s' is opened for read only\n", disk_device);
1481 	}
1482 	xmove_fd(fd, dev_fd);
1483 	if (512 != full_read(dev_fd, MBRbuffer, 512)) {
1484 		if (what == TRY_ONLY) {
1485 			close_dev_fd();
1486 			return 1;
1487 		}
1488 		fdisk_fatal(unable_to_read);
1489 	}
1490 #else
1491 	fd = open(disk_device, O_RDONLY);
1492 	if (fd < 0)
1493 		return 1;
1494 	if (512 != full_read(fd, MBRbuffer, 512)) {
1495 		close(fd);
1496 		return 1;
1497 	}
1498 	xmove_fd(fd, dev_fd);
1499 #endif
1500 
1501 	get_geometry();
1502 	update_units();
1503 
1504 #if ENABLE_FEATURE_SUN_LABEL
1505 	if (check_sun_label())
1506 		return 0;
1507 #endif
1508 #if ENABLE_FEATURE_SGI_LABEL
1509 	if (check_sgi_label())
1510 		return 0;
1511 #endif
1512 #if ENABLE_FEATURE_AIX_LABEL
1513 	if (check_aix_label())
1514 		return 0;
1515 #endif
1516 #if ENABLE_FEATURE_GPT_LABEL
1517 	if (check_gpt_label())
1518 		return 0;
1519 #endif
1520 #if ENABLE_FEATURE_OSF_LABEL
1521 	if (check_osf_label()) {
1522 		possibly_osf_label = 1;
1523 		if (!valid_part_table_flag(MBRbuffer)) {
1524 			current_label_type = LABEL_OSF;
1525 			return 0;
1526 		}
1527 		puts("This disk has both DOS and BSD magic.\n"
1528 		     "Give the 'b' command to go to BSD mode.");
1529 	}
1530 #endif
1531 
1532 #if !ENABLE_FEATURE_FDISK_WRITABLE
1533 	if (!valid_part_table_flag(MBRbuffer))
1534 		return -1;
1535 #else
1536 	if (!valid_part_table_flag(MBRbuffer)) {
1537 		if (what == OPEN_MAIN) {
1538 			puts("Device contains neither a valid DOS "
1539 			     "partition table, nor Sun, SGI, OSF or GPT "
1540 			     "disklabel");
1541 #ifdef __sparc__
1542 			IF_FEATURE_SUN_LABEL(create_sunlabel();)
1543 #else
1544 			create_doslabel();
1545 #endif
1546 			return 0;
1547 		}
1548 		/* TRY_ONLY: */
1549 		return -1;
1550 	}
1551  created_table:
1552 #endif /* FEATURE_FDISK_WRITABLE */
1553 
1554 
1555 	IF_FEATURE_FDISK_WRITABLE(warn_cylinders();)
1556 	warn_geometry();
1557 
1558 	for (i = 0; i < 4; i++) {
1559 		if (IS_EXTENDED(ptes[i].part_table->sys_ind)) {
1560 			if (g_partitions != 4)
1561 				printf("Ignoring extra extended "
1562 					"partition %u\n", i + 1);
1563 			else
1564 				read_extended(i);
1565 		}
1566 	}
1567 
1568 	for (i = 3; i < g_partitions; i++) {
1569 		struct pte *pe = &ptes[i];
1570 		if (!valid_part_table_flag(pe->sectorbuffer)) {
1571 			printf("Warning: invalid flag 0x%02x,0x%02x of partition "
1572 				"table %u will be corrected by w(rite)\n",
1573 				pe->sectorbuffer[510],
1574 				pe->sectorbuffer[511],
1575 				i + 1);
1576 			IF_FEATURE_FDISK_WRITABLE(pe->changed = 1;)
1577 		}
1578 	}
1579 
1580 	return 0;
1581 }
1582 
1583 #if ENABLE_FEATURE_FDISK_WRITABLE
1584 /*
1585  * Print the message MESG, then read an integer between LOW and HIGH (inclusive).
1586  * If the user hits Enter, DFLT is returned.
1587  * Answers like +10 are interpreted as offsets from BASE.
1588  *
1589  * There is no default if DFLT is not between LOW and HIGH.
1590  */
1591 static sector_t
read_int(sector_t low,sector_t dflt,sector_t high,sector_t base,const char * mesg)1592 read_int(sector_t low, sector_t dflt, sector_t high, sector_t base, const char *mesg)
1593 {
1594 	sector_t value;
1595 	int default_ok = 1;
1596 	const char *fmt = "%s (%u-%u, default %u): ";
1597 
1598 	if (dflt < low || dflt > high) {
1599 		fmt = "%s (%u-%u): ";
1600 		default_ok = 0;
1601 	}
1602 
1603 	while (1) {
1604 		int use_default = default_ok;
1605 
1606 		/* ask question and read answer */
1607 		do {
1608 			printf(fmt, mesg, low, high, dflt);
1609 			read_maybe_empty("");
1610 		} while (*line_ptr != '\n' && !isdigit(*line_ptr)
1611 		 && *line_ptr != '-' && *line_ptr != '+');
1612 
1613 		if (*line_ptr == '+' || *line_ptr == '-') {
1614 			int minus = (*line_ptr == '-');
1615 			int absolute = 0;
1616 
1617 			value = atoi(line_ptr + 1);
1618 
1619 			/* (1) if 2nd char is digit, use_default = 0.
1620 			 * (2) move line_ptr to first non-digit. */
1621 			while (isdigit(*++line_ptr))
1622 				use_default = 0;
1623 
1624 			switch (*line_ptr) {
1625 			case 'c':
1626 			case 'C':
1627 				if (!display_in_cyl_units)
1628 					value *= g_heads * g_sectors;
1629 				break;
1630 			case 'K':
1631 				absolute = 1024;
1632 				break;
1633 			case 'k':
1634 				absolute = 1000;
1635 				break;
1636 			case 'm':
1637 			case 'M':
1638 				absolute = 1000000;
1639 				break;
1640 			case 'g':
1641 			case 'G':
1642 				absolute = 1000000000;
1643 				break;
1644 			default:
1645 				break;
1646 			}
1647 			if (absolute) {
1648 				ullong bytes;
1649 				unsigned long unit;
1650 
1651 				bytes = (ullong) value * absolute;
1652 				unit = sector_size * units_per_sector;
1653 				bytes += unit/2; /* round */
1654 				bytes /= unit;
1655 				value = bytes;
1656 			}
1657 			if (minus)
1658 				value = -value;
1659 			value += base;
1660 		} else {
1661 			value = atoi(line_ptr);
1662 			while (isdigit(*line_ptr)) {
1663 				line_ptr++;
1664 				use_default = 0;
1665 			}
1666 		}
1667 		if (use_default) {
1668 			value = dflt;
1669 			printf("Using default value %u\n", value);
1670 		}
1671 		if (value >= low && value <= high)
1672 			break;
1673 		puts("Value is out of range");
1674 	}
1675 	return value;
1676 }
1677 
1678 static unsigned
get_partition(int warn,unsigned max)1679 get_partition(int warn, unsigned max)
1680 {
1681 	struct pte *pe;
1682 	unsigned i;
1683 
1684 	i = read_int(1, 0, max, 0, "Partition number") - 1;
1685 	pe = &ptes[i];
1686 
1687 	if (warn) {
1688 		if ((!LABEL_IS_SUN && !LABEL_IS_SGI && !pe->part_table->sys_ind)
1689 		 || (LABEL_IS_SUN && (!sunlabel->partitions[i].num_sectors || !sunlabel->infos[i].id))
1690 		 || (LABEL_IS_SGI && !sgi_get_num_sectors(i))
1691 		) {
1692 			printf("Warning: partition %u has empty type\n", i+1);
1693 		}
1694 	}
1695 	return i;
1696 }
1697 
1698 static int
get_existing_partition(int warn,unsigned max)1699 get_existing_partition(int warn, unsigned max)
1700 {
1701 	int pno = -1;
1702 	unsigned i;
1703 
1704 	for (i = 0; i < max; i++) {
1705 		struct pte *pe = &ptes[i];
1706 		struct partition *p = pe->part_table;
1707 
1708 		if (p && !is_cleared_partition(p)) {
1709 			if (pno >= 0)
1710 				goto not_unique;
1711 			pno = i;
1712 		}
1713 	}
1714 	if (pno >= 0) {
1715 		printf("Selected partition %u\n", pno+1);
1716 		return pno;
1717 	}
1718 	puts("No partition is defined yet!");
1719 	return -1;
1720 
1721  not_unique:
1722 	return get_partition(warn, max);
1723 }
1724 
1725 static int
get_nonexisting_partition(int warn,unsigned max)1726 get_nonexisting_partition(int warn, unsigned max)
1727 {
1728 	int pno = -1;
1729 	unsigned i;
1730 
1731 	for (i = 0; i < max; i++) {
1732 		struct pte *pe = &ptes[i];
1733 		struct partition *p = pe->part_table;
1734 
1735 		if (p && is_cleared_partition(p)) {
1736 			if (pno >= 0)
1737 				goto not_unique;
1738 			pno = i;
1739 		}
1740 	}
1741 	if (pno >= 0) {
1742 		printf("Selected partition %u\n", pno+1);
1743 		return pno;
1744 	}
1745 	puts("All primary partitions have been defined already!");
1746 	return -1;
1747 
1748  not_unique:
1749 	return get_partition(warn, max);
1750 }
1751 
1752 
1753 static void
change_units(void)1754 change_units(void)
1755 {
1756 	display_in_cyl_units = !display_in_cyl_units;
1757 	update_units();
1758 	printf("Changing display/entry units to %s\n",
1759 		str_units(PLURAL));
1760 }
1761 
1762 static void
toggle_active(int i)1763 toggle_active(int i)
1764 {
1765 	struct pte *pe = &ptes[i];
1766 	struct partition *p = pe->part_table;
1767 
1768 	if (IS_EXTENDED(p->sys_ind) && !p->boot_ind)
1769 		printf("WARNING: Partition %u is an extended partition\n", i + 1);
1770 	p->boot_ind = (p->boot_ind ? 0 : ACTIVE_FLAG);
1771 	pe->changed = 1;
1772 }
1773 
1774 static void
toggle_dos_compatibility_flag(void)1775 toggle_dos_compatibility_flag(void)
1776 {
1777 	dos_compatible_flag = 1 - dos_compatible_flag;
1778 	if (dos_compatible_flag) {
1779 		sector_offset = g_sectors;
1780 		printf("DOS Compatibility flag is %sset\n", "");
1781 	} else {
1782 		sector_offset = 1;
1783 		printf("DOS Compatibility flag is %sset\n", "not ");
1784 	}
1785 }
1786 
1787 static void
delete_partition(int i)1788 delete_partition(int i)
1789 {
1790 	struct pte *pe = &ptes[i];
1791 	struct partition *p = pe->part_table;
1792 	struct partition *q = pe->ext_pointer;
1793 
1794 /* Note that for the fifth partition (i == 4) we don't actually
1795  * decrement partitions.
1796  */
1797 
1798 	if (warn_geometry())
1799 		return;         /* C/H/S not set */
1800 	pe->changed = 1;
1801 
1802 	if (LABEL_IS_SUN) {
1803 		sun_delete_partition(i);
1804 		return;
1805 	}
1806 	if (LABEL_IS_SGI) {
1807 		sgi_delete_partition(i);
1808 		return;
1809 	}
1810 
1811 	if (i < 4) {
1812 		if (IS_EXTENDED(p->sys_ind) && i == ext_index) {
1813 			g_partitions = 4;
1814 			ptes[ext_index].ext_pointer = NULL;
1815 			extended_offset = 0;
1816 		}
1817 		clear_partition(p);
1818 		return;
1819 	}
1820 
1821 	if (!q->sys_ind && i > 4) {
1822 		/* the last one in the chain - just delete */
1823 		--g_partitions;
1824 		--i;
1825 		clear_partition(ptes[i].ext_pointer);
1826 		ptes[i].changed = 1;
1827 	} else {
1828 		/* not the last one - further ones will be moved down */
1829 		if (i > 4) {
1830 			/* delete this link in the chain */
1831 			p = ptes[i-1].ext_pointer;
1832 			*p = *q;
1833 			set_start_sect(p, get_start_sect(q));
1834 			set_nr_sects(p, get_nr_sects(q));
1835 			ptes[i-1].changed = 1;
1836 		} else if (g_partitions > 5) {    /* 5 will be moved to 4 */
1837 			/* the first logical in a longer chain */
1838 			pe = &ptes[5];
1839 
1840 			if (pe->part_table) /* prevent SEGFAULT */
1841 				set_start_sect(pe->part_table,
1842 						get_partition_start_from_dev_start(pe) -
1843 						extended_offset);
1844 			pe->offset_from_dev_start = extended_offset;
1845 			pe->changed = 1;
1846 		}
1847 
1848 		if (g_partitions > 5) {
1849 			g_partitions--;
1850 			while (i < g_partitions) {
1851 				ptes[i] = ptes[i+1];
1852 				i++;
1853 			}
1854 		} else {
1855 			/* the only logical: clear only */
1856 			clear_partition(ptes[i].part_table);
1857 		}
1858 	}
1859 }
1860 
1861 static void
change_sysid(void)1862 change_sysid(void)
1863 {
1864 	int i, sys, origsys;
1865 	struct partition *p;
1866 
1867 	/* If sgi_label then don't use get_existing_partition,
1868 	   let the user select a partition, since get_existing_partition()
1869 	   only works for Linux like partition tables. */
1870 	if (!LABEL_IS_SGI) {
1871 		i = get_existing_partition(0, g_partitions);
1872 	} else {
1873 		i = get_partition(0, g_partitions);
1874 	}
1875 	if (i == -1)
1876 		return;
1877 	p = ptes[i].part_table;
1878 	origsys = sys = get_sysid(i);
1879 
1880 	/* if changing types T to 0 is allowed, then
1881 	   the reverse change must be allowed, too */
1882 	if (!sys && !LABEL_IS_SGI && !LABEL_IS_SUN && !get_nr_sects(p))	{
1883 		printf("Partition %u does not exist yet!\n", i + 1);
1884 		return;
1885 	}
1886 	while (1) {
1887 		sys = read_hex(get_sys_types());
1888 
1889 		if (!sys && !LABEL_IS_SGI && !LABEL_IS_SUN) {
1890 			puts("Type 0 means free space to many systems\n"
1891 				"(but not to Linux). Having partitions of\n"
1892 				"type 0 is probably unwise.");
1893 			/* break; */
1894 		}
1895 
1896 		if (!LABEL_IS_SUN && !LABEL_IS_SGI) {
1897 			if (IS_EXTENDED(sys) != IS_EXTENDED(p->sys_ind)) {
1898 				puts("You cannot change a partition into"
1899 					" an extended one or vice versa");
1900 				break;
1901 			}
1902 		}
1903 
1904 		if (sys < 256) {
1905 #if ENABLE_FEATURE_SUN_LABEL
1906 			if (LABEL_IS_SUN && i == 2 && sys != SUN_WHOLE_DISK)
1907 				puts("Consider leaving partition 3 "
1908 					"as Whole disk (5),\n"
1909 					"as SunOS/Solaris expects it and "
1910 					"even Linux likes it\n");
1911 #endif
1912 #if ENABLE_FEATURE_SGI_LABEL
1913 			if (LABEL_IS_SGI &&
1914 				(
1915 					(i == 10 && sys != SGI_ENTIRE_DISK) ||
1916 					(i == 8 && sys != 0)
1917 				)
1918 			) {
1919 				puts("Consider leaving partition 9 "
1920 					"as volume header (0),\nand "
1921 					"partition 11 as entire volume (6)"
1922 					"as IRIX expects it\n");
1923 			}
1924 #endif
1925 			if (sys == origsys)
1926 				break;
1927 			if (LABEL_IS_SUN) {
1928 				sun_change_sysid(i, sys);
1929 			} else if (LABEL_IS_SGI) {
1930 				sgi_change_sysid(i, sys);
1931 			} else
1932 				p->sys_ind = sys;
1933 
1934 			printf("Changed system type of partition %u "
1935 				"to %x (%s)\n", i + 1, sys,
1936 				partition_type(sys));
1937 			ptes[i].changed = 1;
1938 			//if (is_dos_partition(origsys) || is_dos_partition(sys))
1939 			//	dos_changed = 1;
1940 			break;
1941 		}
1942 	}
1943 }
1944 #endif /* FEATURE_FDISK_WRITABLE */
1945 
1946 
1947 /* check_consistency() and linear2chs() added Sat Mar 6 12:28:16 1993,
1948  * faith@cs.unc.edu, based on code fragments from pfdisk by Gordon W. Ross,
1949  * Jan.  1990 (version 1.2.1 by Gordon W. Ross Aug. 1990; Modified by S.
1950  * Lubkin Oct.  1991). */
1951 
1952 static void
linear2chs(unsigned ls,unsigned * c,unsigned * h,unsigned * s)1953 linear2chs(unsigned ls, unsigned *c, unsigned *h, unsigned *s)
1954 {
1955 	int spc = g_heads * g_sectors;
1956 
1957 	*c = ls / spc;
1958 	ls = ls % spc;
1959 	*h = ls / g_sectors;
1960 	*s = ls % g_sectors + 1;  /* sectors count from 1 */
1961 }
1962 
1963 static void
check_consistency(const struct partition * p,int partition)1964 check_consistency(const struct partition *p, int partition)
1965 {
1966 	unsigned pbc, pbh, pbs;          /* physical beginning c, h, s */
1967 	unsigned pec, peh, pes;          /* physical ending c, h, s */
1968 	unsigned lbc, lbh, lbs;          /* logical beginning c, h, s */
1969 	unsigned lec, leh, les;          /* logical ending c, h, s */
1970 
1971 	if (!g_heads || !g_sectors || (partition >= 4))
1972 		return;         /* do not check extended partitions */
1973 
1974 /* physical beginning c, h, s */
1975 	pbc = cylinder(p->sector, p->cyl);
1976 	pbh = p->head;
1977 	pbs = sector(p->sector);
1978 
1979 /* physical ending c, h, s */
1980 	pec = cylinder(p->end_sector, p->end_cyl);
1981 	peh = p->end_head;
1982 	pes = sector(p->end_sector);
1983 
1984 /* compute logical beginning (c, h, s) */
1985 	linear2chs(get_start_sect(p), &lbc, &lbh, &lbs);
1986 
1987 /* compute logical ending (c, h, s) */
1988 	linear2chs(get_start_sect(p) + get_nr_sects(p) - 1, &lec, &leh, &les);
1989 
1990 /* Same physical / logical beginning? */
1991 	if (g_cylinders <= 1024 && (pbc != lbc || pbh != lbh || pbs != lbs)) {
1992 		printf("Partition %u has different physical/logical "
1993 			"start (non-Linux?):\n", partition + 1);
1994 		printf("     phys=(%u,%u,%u) ", pbc, pbh, pbs);
1995 		printf("logical=(%u,%u,%u)\n", lbc, lbh, lbs);
1996 	}
1997 
1998 /* Same physical / logical ending? */
1999 	if (g_cylinders <= 1024 && (pec != lec || peh != leh || pes != les)) {
2000 		printf("Partition %u has different physical/logical "
2001 			"end:\n", partition + 1);
2002 		printf("     phys=(%u,%u,%u) ", pec, peh, pes);
2003 		printf("logical=(%u,%u,%u)\n", lec, leh, les);
2004 	}
2005 
2006 /* Ending on cylinder boundary? */
2007 	if (peh != (g_heads - 1) || pes != g_sectors) {
2008 		printf("Partition %u does not end on cylinder boundary\n",
2009 			partition + 1);
2010 	}
2011 }
2012 
2013 static void
list_disk_geometry(void)2014 list_disk_geometry(void)
2015 {
2016 	ullong bytes = ((ullong)total_number_of_sectors << 9);
2017 	ullong xbytes = bytes / (1024*1024);
2018 	char x = 'M';
2019 
2020 	if (xbytes >= 10000) {
2021 		xbytes += 512; /* fdisk util-linux 2.28 does this */
2022 		xbytes /= 1024;
2023 		x = 'G';
2024 	}
2025 	printf("Disk %s: %llu %cB, %llu bytes, %"SECT_FMT"u sectors\n"
2026 		"%u cylinders, %u heads, %u sectors/track\n"
2027 		"Units: %s of %u * %u = %u bytes\n\n",
2028 		disk_device, xbytes, x,
2029 		bytes, total_number_of_sectors,
2030 		g_cylinders, g_heads, g_sectors,
2031 		str_units(PLURAL),
2032 		units_per_sector, sector_size, units_per_sector * sector_size
2033 	);
2034 }
2035 
2036 /*
2037  * Check whether partition entries are ordered by their starting positions.
2038  * Return 0 if OK. Return i if partition i should have been earlier.
2039  * Two separate checks: primary and logical partitions.
2040  */
2041 static int
wrong_p_order(int * prev)2042 wrong_p_order(int *prev)
2043 {
2044 	const struct pte *pe;
2045 	const struct partition *p;
2046 	sector_t last_p_start_pos = 0, p_start_pos;
2047 	unsigned i, last_i = 0;
2048 
2049 	for (i = 0; i < g_partitions; i++) {
2050 		if (i == 4) {
2051 			last_i = 4;
2052 			last_p_start_pos = 0;
2053 		}
2054 		pe = &ptes[i];
2055 		p = pe->part_table;
2056 		if (p->sys_ind) {
2057 			p_start_pos = get_partition_start_from_dev_start(pe);
2058 
2059 			if (last_p_start_pos > p_start_pos) {
2060 				if (prev)
2061 					*prev = last_i;
2062 				return i;
2063 			}
2064 
2065 			last_p_start_pos = p_start_pos;
2066 			last_i = i;
2067 		}
2068 	}
2069 	return 0;
2070 }
2071 
2072 #if ENABLE_FEATURE_FDISK_ADVANCED
2073 /*
2074  * Fix the chain of logicals.
2075  * extended_offset is unchanged, the set of sectors used is unchanged
2076  * The chain is sorted so that sectors increase, and so that
2077  * starting sectors increase.
2078  *
2079  * After this it may still be that cfdisk doesnt like the table.
2080  * (This is because cfdisk considers expanded parts, from link to
2081  * end of partition, and these may still overlap.)
2082  * Now
2083  *   sfdisk /dev/hda > ohda; sfdisk /dev/hda < ohda
2084  * may help.
2085  */
2086 static void
fix_chain_of_logicals(void)2087 fix_chain_of_logicals(void)
2088 {
2089 	int j, oj, ojj, sj, sjj;
2090 	struct partition *pj,*pjj,tmp;
2091 
2092 	/* Stage 1: sort sectors but leave sector of part 4 */
2093 	/* (Its sector is the global extended_offset.) */
2094  stage1:
2095 	for (j = 5; j < g_partitions - 1; j++) {
2096 		oj = ptes[j].offset_from_dev_start;
2097 		ojj = ptes[j+1].offset_from_dev_start;
2098 		if (oj > ojj) {
2099 			ptes[j].offset_from_dev_start = ojj;
2100 			ptes[j+1].offset_from_dev_start = oj;
2101 			pj = ptes[j].part_table;
2102 			set_start_sect(pj, get_start_sect(pj)+oj-ojj);
2103 			pjj = ptes[j+1].part_table;
2104 			set_start_sect(pjj, get_start_sect(pjj)+ojj-oj);
2105 			set_start_sect(ptes[j-1].ext_pointer,
2106 					   ojj-extended_offset);
2107 			set_start_sect(ptes[j].ext_pointer,
2108 					   oj-extended_offset);
2109 			goto stage1;
2110 		}
2111 	}
2112 
2113 	/* Stage 2: sort starting sectors */
2114  stage2:
2115 	for (j = 4; j < g_partitions - 1; j++) {
2116 		pj = ptes[j].part_table;
2117 		pjj = ptes[j+1].part_table;
2118 		sj = get_start_sect(pj);
2119 		sjj = get_start_sect(pjj);
2120 		oj = ptes[j].offset_from_dev_start;
2121 		ojj = ptes[j+1].offset_from_dev_start;
2122 		if (oj+sj > ojj+sjj) {
2123 			tmp = *pj;
2124 			*pj = *pjj;
2125 			*pjj = tmp;
2126 			set_start_sect(pj, ojj+sjj-oj);
2127 			set_start_sect(pjj, oj+sj-ojj);
2128 			goto stage2;
2129 		}
2130 	}
2131 
2132 	/* Probably something was changed */
2133 	for (j = 4; j < g_partitions; j++)
2134 		ptes[j].changed = 1;
2135 }
2136 
2137 
2138 static void
fix_partition_table_order(void)2139 fix_partition_table_order(void)
2140 {
2141 	struct pte *pei, *pek;
2142 	int i,k;
2143 
2144 	if (!wrong_p_order(NULL)) {
2145 		puts("Ordering is already correct\n");
2146 		return;
2147 	}
2148 
2149 	while ((i = wrong_p_order(&k)) != 0 && i < 4) {
2150 		/* partition i should have come earlier, move it */
2151 		/* We have to move data in the MBR */
2152 		struct partition *pi, *pk, *pe, pbuf;
2153 		pei = &ptes[i];
2154 		pek = &ptes[k];
2155 
2156 		pe = pei->ext_pointer;
2157 		pei->ext_pointer = pek->ext_pointer;
2158 		pek->ext_pointer = pe;
2159 
2160 		pi = pei->part_table;
2161 		pk = pek->part_table;
2162 
2163 		memmove(&pbuf, pi, sizeof(struct partition));
2164 		memmove(pi, pk, sizeof(struct partition));
2165 		memmove(pk, &pbuf, sizeof(struct partition));
2166 
2167 		pei->changed = pek->changed = 1;
2168 	}
2169 
2170 	if (i)
2171 		fix_chain_of_logicals();
2172 
2173 	puts("Done");
2174 }
2175 #endif
2176 
2177 static const char *
chs_string11(unsigned cyl,unsigned head,unsigned sect)2178 chs_string11(unsigned cyl, unsigned head, unsigned sect)
2179 {
2180 	char *buf = auto_string(xzalloc(sizeof(int)*3 * 3));
2181 	sprintf(buf, "%u,%u,%u", cylinder(sect,cyl), head, sector(sect));
2182 	return buf;
2183 }
2184 
2185 static void
list_table(int xtra)2186 list_table(int xtra)
2187 {
2188 	int i, w;
2189 
2190 	if (LABEL_IS_SUN) {
2191 		sun_list_table(xtra);
2192 		return;
2193 	}
2194 	if (LABEL_IS_SGI) {
2195 		sgi_list_table(xtra);
2196 		return;
2197 	}
2198 	if (LABEL_IS_GPT) {
2199 		gpt_list_table(xtra);
2200 		return;
2201 	}
2202 
2203 	list_disk_geometry();
2204 
2205 	if (LABEL_IS_OSF) {
2206 		xbsd_print_disklabel(xtra);
2207 		return;
2208 	}
2209 
2210 	/* Heuristic: we list partition 3 of /dev/foo as /dev/foo3,
2211 	 * but if the device name ends in a digit, say /dev/foo1,
2212 	 * then the partition is called /dev/foo1p3.
2213 	 */
2214 	w = strlen(disk_device);
2215 	if (w && isdigit(disk_device[w-1]))
2216 		w++;
2217 	if (w < 7)
2218 		w = 7;
2219 
2220 	printf("%-*s Boot StartCHS    EndCHS        StartLBA     EndLBA    Sectors  Size Id Type\n",
2221 		   w-1, "Device");
2222 
2223 	for (i = 0; i < g_partitions; i++) {
2224 		const struct partition *p;
2225 		const struct pte *pe = &ptes[i];
2226 		char boot4[4];
2227 		char numstr6[6];
2228 		sector_t start_sect;
2229 		sector_t end_sect;
2230 		sector_t nr_sects;
2231 
2232 		p = pe->part_table;
2233 		if (!p || is_cleared_partition(p))
2234 			continue;
2235 
2236 		sprintf(boot4, "%02x", p->boot_ind);
2237 		if ((p->boot_ind & 0x7f) == 0) {
2238 			/* 0x80 shown as '*', 0x00 is ' ' */
2239 			boot4[0] = p->boot_ind ? '*' : ' ';
2240 			boot4[1] = ' ';
2241 		}
2242 
2243 		start_sect = get_partition_start_from_dev_start(pe);
2244 		end_sect = start_sect;
2245 		nr_sects = get_nr_sects(p);
2246 		if (nr_sects != 0)
2247 			end_sect += nr_sects - 1;
2248 
2249 		smart_ulltoa5((ullong)nr_sects * sector_size,
2250 			numstr6, " KMGTPEZY")[0] = '\0';
2251 
2252 #define SFMT SECT_FMT
2253 		//      Boot StartCHS    EndCHS        StartLBA     EndLBA    Sectors  Size Id Type
2254 		printf("%s%s %-11s"/**/" %-11s"/**/" %10"SFMT"u %10"SFMT"u %10"SFMT"u %s %2x %s\n",
2255 			partname(disk_device, i+1, w+2),
2256 			boot4,
2257 			chs_string11(p->cyl, p->head, p->sector),
2258 			chs_string11(p->end_cyl, p->end_head, p->end_sector),
2259 			start_sect,
2260 			end_sect,
2261 			nr_sects,
2262 			numstr6,
2263 			p->sys_ind,
2264 			partition_type(p->sys_ind)
2265 		);
2266 #undef SFMT
2267 		check_consistency(p, i);
2268 	}
2269 
2270 	/* Is partition table in disk order? It need not be, but... */
2271 	/* partition table entries are not checked for correct order
2272 	 * if this is a sgi, sun or aix labeled disk... */
2273 	if (LABEL_IS_DOS && wrong_p_order(NULL)) {
2274 		/* FIXME */
2275 		puts("\nPartition table entries are not in disk order");
2276 	}
2277 }
2278 
2279 #if ENABLE_FEATURE_FDISK_ADVANCED
2280 static void
x_list_table(int extend)2281 x_list_table(int extend)
2282 {
2283 	const struct pte *pe;
2284 	const struct partition *p;
2285 	int i;
2286 
2287 	printf("\nDisk %s: %u heads, %u sectors, %u cylinders\n\n",
2288 		disk_device, g_heads, g_sectors, g_cylinders);
2289 	puts("Nr AF  Hd Sec  Cyl  Hd Sec  Cyl      Start       Size ID");
2290 	for (i = 0; i < g_partitions; i++) {
2291 		pe = &ptes[i];
2292 		p = (extend ? pe->ext_pointer : pe->part_table);
2293 		if (p != NULL) {
2294 			printf("%2u %02x%4u%4u%5u%4u%4u%5u%11"SECT_FMT"u%11"SECT_FMT"u %02x\n",
2295 				i + 1, p->boot_ind,
2296 				p->head,
2297 				sector(p->sector),
2298 				cylinder(p->sector, p->cyl),
2299 				p->end_head,
2300 				sector(p->end_sector),
2301 				cylinder(p->end_sector, p->end_cyl),
2302 				get_start_sect(p),
2303 				get_nr_sects(p),
2304 				p->sys_ind
2305 			);
2306 			if (p->sys_ind)
2307 				check_consistency(p, i);
2308 		}
2309 	}
2310 }
2311 #endif
2312 
2313 #if ENABLE_FEATURE_FDISK_WRITABLE
2314 static void
fill_bounds(sector_t * first,sector_t * last)2315 fill_bounds(sector_t *first, sector_t *last)
2316 {
2317 	unsigned i;
2318 	const struct pte *pe = &ptes[0];
2319 	const struct partition *p;
2320 
2321 	for (i = 0; i < g_partitions; pe++,i++) {
2322 		p = pe->part_table;
2323 		if (!p->sys_ind || IS_EXTENDED(p->sys_ind)) {
2324 			first[i] = 0xffffffff;
2325 			last[i] = 0;
2326 		} else {
2327 			first[i] = get_partition_start_from_dev_start(pe);
2328 			last[i] = first[i] + get_nr_sects(p) - 1;
2329 		}
2330 	}
2331 }
2332 
2333 static void
check(int n,unsigned h,unsigned s,unsigned c,sector_t start)2334 check(int n, unsigned h, unsigned s, unsigned c, sector_t start)
2335 {
2336 	sector_t total, real_s, real_c;
2337 
2338 	real_s = sector(s) - 1;
2339 	real_c = cylinder(s, c);
2340 	total = (real_c * g_sectors + real_s) * g_heads + h;
2341 	if (!total)
2342 		printf("Partition %u contains sector 0\n", n);
2343 	if (h >= g_heads)
2344 		printf("Partition %u: head %u greater than maximum %u\n",
2345 			n, h + 1, g_heads);
2346 	if (real_s >= g_sectors)
2347 		printf("Partition %u: sector %u greater than "
2348 			"maximum %u\n", n, s, g_sectors);
2349 	if (real_c >= g_cylinders)
2350 		printf("Partition %u: cylinder %"SECT_FMT"u greater than "
2351 			"maximum %u\n", n, real_c + 1, g_cylinders);
2352 	if (g_cylinders <= 1024 && start != total)
2353 		printf("Partition %u: previous sectors %"SECT_FMT"u disagrees with "
2354 			"total %"SECT_FMT"u\n", n, start, total);
2355 }
2356 
2357 static void
verify(void)2358 verify(void)
2359 {
2360 	int i, j;
2361 	sector_t total = 1;
2362 	sector_t chs_size;
2363 	sector_t first[g_partitions], last[g_partitions];
2364 	struct partition *p;
2365 
2366 	if (warn_geometry())
2367 		return;
2368 
2369 	if (LABEL_IS_SUN) {
2370 		verify_sun();
2371 		return;
2372 	}
2373 	if (LABEL_IS_SGI) {
2374 		verify_sgi(1);
2375 		return;
2376 	}
2377 
2378 	fill_bounds(first, last);
2379 	for (i = 0; i < g_partitions; i++) {
2380 		struct pte *pe = &ptes[i];
2381 
2382 		p = pe->part_table;
2383 		if (p->sys_ind && !IS_EXTENDED(p->sys_ind)) {
2384 			check_consistency(p, i);
2385 			if (get_partition_start_from_dev_start(pe) < first[i])
2386 				printf("Warning: bad start-of-data in "
2387 					"partition %u\n", i + 1);
2388 			check(i + 1, p->end_head, p->end_sector, p->end_cyl,
2389 				last[i]);
2390 			total += last[i] + 1 - first[i];
2391 			for (j = 0; j < i; j++) {
2392 				if ((first[i] >= first[j] && first[i] <= last[j])
2393 				 || ((last[i] <= last[j] && last[i] >= first[j]))) {
2394 					printf("Warning: partition %u overlaps "
2395 						"partition %u\n", j + 1, i + 1);
2396 					total += first[i] >= first[j] ?
2397 						first[i] : first[j];
2398 					total -= last[i] <= last[j] ?
2399 						last[i] : last[j];
2400 				}
2401 			}
2402 		}
2403 	}
2404 
2405 	if (extended_offset) {
2406 		struct pte *pex = &ptes[ext_index];
2407 		sector_t e_last = get_start_sect(pex->part_table) +
2408 			get_nr_sects(pex->part_table) - 1;
2409 
2410 		for (i = 4; i < g_partitions; i++) {
2411 			total++;
2412 			p = ptes[i].part_table;
2413 			if (!p->sys_ind) {
2414 				if (i != 4 || i + 1 < g_partitions)
2415 					printf("Warning: partition %u "
2416 						"is empty\n", i + 1);
2417 			} else if (first[i] < extended_offset || last[i] > e_last) {
2418 				printf("Logical partition %u not entirely in "
2419 					"partition %u\n", i + 1, ext_index + 1);
2420 			}
2421 		}
2422 	}
2423 
2424 	chs_size = (sector_t)g_heads * g_sectors * g_cylinders;
2425 	if (total > chs_size)
2426 		printf("Total allocated sectors %u"
2427 			" greater than CHS size %"SECT_FMT"u\n",
2428 			total, chs_size
2429 		);
2430 	else {
2431 		total = chs_size - total;
2432 		if (total != 0)
2433 			printf("%"SECT_FMT"u unallocated sectors\n", total);
2434 	}
2435 }
2436 
2437 static void
add_partition(int n,int sys)2438 add_partition(int n, int sys)
2439 {
2440 	char mesg[256];         /* 48 does not suffice in Japanese */
2441 	int i, num_read = 0;
2442 	struct partition *p = ptes[n].part_table;
2443 	struct partition *q = ptes[ext_index].part_table;
2444 	sector_t limit, temp;
2445 	sector_t start, stop = 0;
2446 	sector_t first[g_partitions], last[g_partitions];
2447 
2448 	if (p && p->sys_ind) {
2449 		printf(msg_part_already_defined, n + 1);
2450 		return;
2451 	}
2452 	fill_bounds(first, last);
2453 	if (n < 4) {
2454 		start = sector_offset;
2455 		if (display_in_cyl_units || !total_number_of_sectors)
2456 			limit = (sector_t) g_heads * g_sectors * g_cylinders - 1;
2457 		else
2458 			limit = total_number_of_sectors - 1;
2459 		if (extended_offset) {
2460 			first[ext_index] = extended_offset;
2461 			last[ext_index] = get_start_sect(q) +
2462 				get_nr_sects(q) - 1;
2463 		}
2464 	} else {
2465 		start = extended_offset + sector_offset;
2466 		limit = get_start_sect(q) + get_nr_sects(q) - 1;
2467 	}
2468 	if (display_in_cyl_units)
2469 		for (i = 0; i < g_partitions; i++)
2470 			first[i] = (cround(first[i]) - 1) * units_per_sector;
2471 
2472 	snprintf(mesg, sizeof(mesg), "First %s", str_units(SINGULAR));
2473 	do {
2474 		temp = start;
2475 		for (i = 0; i < g_partitions; i++) {
2476 			int lastplusoff;
2477 
2478 			if (start == ptes[i].offset_from_dev_start)
2479 				start += sector_offset;
2480 			lastplusoff = last[i] + ((n < 4) ? 0 : sector_offset);
2481 			if (start >= first[i] && start <= lastplusoff)
2482 				start = lastplusoff + 1;
2483 		}
2484 		if (start > limit)
2485 			break;
2486 		if (start >= temp+units_per_sector && num_read) {
2487 			printf("Sector %"SECT_FMT"u is already allocated\n", temp);
2488 			temp = start;
2489 			num_read = 0;
2490 		}
2491 		if (!num_read && start == temp) {
2492 			sector_t saved_start;
2493 
2494 			saved_start = start;
2495 			start = read_int(cround(saved_start), cround(saved_start), cround(limit), 0, mesg);
2496 			if (display_in_cyl_units) {
2497 				start = (start - 1) * units_per_sector;
2498 				if (start < saved_start)
2499 					start = saved_start;
2500 			}
2501 			num_read = 1;
2502 		}
2503 	} while (start != temp || !num_read);
2504 	if (n > 4) {                    /* NOT for fifth partition */
2505 		struct pte *pe = &ptes[n];
2506 
2507 		pe->offset_from_dev_start = start - sector_offset;
2508 		if (pe->offset_from_dev_start == extended_offset) { /* must be corrected */
2509 			pe->offset_from_dev_start++;
2510 			if (sector_offset == 1)
2511 				start++;
2512 		}
2513 	}
2514 
2515 	for (i = 0; i < g_partitions; i++) {
2516 		struct pte *pe = &ptes[i];
2517 
2518 		if (start < pe->offset_from_dev_start && limit >= pe->offset_from_dev_start)
2519 			limit = pe->offset_from_dev_start - 1;
2520 		if (start < first[i] && limit >= first[i])
2521 			limit = first[i] - 1;
2522 	}
2523 	if (start > limit) {
2524 		puts("No free sectors available");
2525 		if (n > 4)
2526 			g_partitions--;
2527 		return;
2528 	}
2529 	if (cround(start) == cround(limit)) {
2530 		stop = limit;
2531 	} else {
2532 		snprintf(mesg, sizeof(mesg),
2533 			 "Last %s or +size or +sizeM or +sizeK",
2534 			 str_units(SINGULAR));
2535 		stop = read_int(cround(start), cround(limit), cround(limit), cround(start), mesg);
2536 		if (display_in_cyl_units) {
2537 			stop = stop * units_per_sector - 1;
2538 			if (stop >limit)
2539 				stop = limit;
2540 		}
2541 	}
2542 
2543 	set_partition(n, 0, start, stop, sys);
2544 	if (n > 4)
2545 		set_partition(n - 1, 1, ptes[n].offset_from_dev_start, stop, EXTENDED);
2546 
2547 	if (IS_EXTENDED(sys)) {
2548 		struct pte *pe4 = &ptes[4];
2549 		struct pte *pen = &ptes[n];
2550 
2551 		ext_index = n;
2552 		pen->ext_pointer = p;
2553 		pe4->offset_from_dev_start = extended_offset = start;
2554 		pe4->sectorbuffer = xzalloc(sector_size);
2555 		pe4->part_table = pt_offset(pe4->sectorbuffer, 0);
2556 		pe4->ext_pointer = pe4->part_table + 1;
2557 		pe4->changed = 1;
2558 		g_partitions = 5;
2559 	}
2560 }
2561 
2562 static void
add_logical(void)2563 add_logical(void)
2564 {
2565 	if (g_partitions > 5 || ptes[4].part_table->sys_ind) {
2566 		struct pte *pe = &ptes[g_partitions];
2567 
2568 		pe->sectorbuffer = xzalloc(sector_size);
2569 		pe->part_table = pt_offset(pe->sectorbuffer, 0);
2570 		pe->ext_pointer = pe->part_table + 1;
2571 		pe->offset_from_dev_start = 0;
2572 		pe->changed = 1;
2573 		g_partitions++;
2574 	}
2575 	add_partition(g_partitions - 1, LINUX_NATIVE);
2576 }
2577 
2578 static void
new_partition(void)2579 new_partition(void)
2580 {
2581 	int i, free_primary = 0;
2582 
2583 	if (warn_geometry())
2584 		return;
2585 
2586 	if (LABEL_IS_SUN) {
2587 		add_sun_partition(get_partition(0, g_partitions), LINUX_NATIVE);
2588 		return;
2589 	}
2590 	if (LABEL_IS_SGI) {
2591 		sgi_add_partition(get_partition(0, g_partitions), LINUX_NATIVE);
2592 		return;
2593 	}
2594 	if (LABEL_IS_AIX) {
2595 		puts("Sorry - this fdisk cannot handle AIX disk labels.\n"
2596 "If you want to add DOS-type partitions, create a new empty DOS partition\n"
2597 "table first (use 'o'). This will destroy the present disk contents.");
2598 		return;
2599 	}
2600 
2601 	for (i = 0; i < 4; i++)
2602 		free_primary += !ptes[i].part_table->sys_ind;
2603 
2604 	if (!free_primary && g_partitions >= MAXIMUM_PARTS) {
2605 		puts("The maximum number of partitions has been created");
2606 		return;
2607 	}
2608 
2609 	if (!free_primary) {
2610 		if (extended_offset)
2611 			add_logical();
2612 		else
2613 			puts("You must delete some partition and add "
2614 				 "an extended partition first");
2615 	} else {
2616 		char c, line[80];
2617 		snprintf(line, sizeof(line),
2618 			"Command action\n"
2619 			"   %s\n"
2620 			"   p   primary partition (1-4)\n",
2621 			(extended_offset ?
2622 			"l   logical (5 or over)" : "e   extended"));
2623 		while (1) {
2624 			c = read_nonempty(line);
2625 			if ((c | 0x20) == 'p') {
2626 				i = get_nonexisting_partition(0, 4);
2627 				if (i >= 0)
2628 					add_partition(i, LINUX_NATIVE);
2629 				return;
2630 			}
2631 			if (c == 'l' && extended_offset) {
2632 				add_logical();
2633 				return;
2634 			}
2635 			if (c == 'e' && !extended_offset) {
2636 				i = get_nonexisting_partition(0, 4);
2637 				if (i >= 0)
2638 					add_partition(i, EXTENDED);
2639 				return;
2640 			}
2641 			printf("Invalid partition number "
2642 					 "for type '%c'\n", c);
2643 		}
2644 	}
2645 }
2646 
2647 static void
reread_partition_table(int leave)2648 reread_partition_table(int leave)
2649 {
2650 	int i;
2651 
2652 	puts("Calling ioctl() to re-read partition table");
2653 	sync();
2654 	/* Users with slow external USB disks on a 320MHz ARM system (year 2011)
2655 	 * report that sleep is needed, otherwise BLKRRPART may fail with -EIO:
2656 	 */
2657 	sleep(1);
2658 	i = ioctl_or_perror(dev_fd, BLKRRPART, NULL,
2659 			"WARNING: rereading partition table "
2660 			"failed, kernel still uses old table");
2661 #if 0
2662 	if (dos_changed)
2663 		puts(
2664 		"\nWARNING: If you have created or modified any DOS 6.x\n"
2665 		"partitions, please see the fdisk manual page for additional\n"
2666 		"information");
2667 #endif
2668 
2669 	if (leave) {
2670 		if (ENABLE_FEATURE_CLEAN_UP)
2671 			close_dev_fd();
2672 		exit(i != 0);
2673 	}
2674 }
2675 
2676 static void
write_table(void)2677 write_table(void)
2678 {
2679 	int i;
2680 
2681 	if (LABEL_IS_DOS) {
2682 		for (i = 0; i < 3; i++)
2683 			if (ptes[i].changed)
2684 				ptes[3].changed = 1;
2685 		for (i = 3; i < g_partitions; i++) {
2686 			struct pte *pe = &ptes[i];
2687 			if (pe->changed) {
2688 				write_part_table_flag(pe->sectorbuffer);
2689 				write_sector(pe->offset_from_dev_start, pe->sectorbuffer);
2690 			}
2691 		}
2692 	}
2693 	else if (LABEL_IS_SGI) {
2694 		/* no test on change? the "altered" msg below might be mistaken */
2695 		sgi_write_table();
2696 	}
2697 	else if (LABEL_IS_SUN) {
2698 		for (i = 0; i < 8; i++) {
2699 			if (ptes[i].changed) {
2700 				sun_write_table();
2701 				break;
2702 			}
2703 		}
2704 	}
2705 
2706 	puts("The partition table has been altered.");
2707 	reread_partition_table(1);
2708 }
2709 #endif /* FEATURE_FDISK_WRITABLE */
2710 
2711 #if ENABLE_FEATURE_FDISK_ADVANCED
2712 #define MAX_PER_LINE    16
2713 static void
print_buffer(char * pbuffer)2714 print_buffer(char *pbuffer)
2715 {
2716 	int i,l;
2717 
2718 	for (i = 0, l = 0; i < sector_size; i++, l++) {
2719 		if (l == 0)
2720 			printf("0x%03X:", i);
2721 		printf(" %02X", (unsigned char) pbuffer[i]);
2722 		if (l == MAX_PER_LINE - 1) {
2723 			bb_putchar('\n');
2724 			l = -1;
2725 		}
2726 	}
2727 	if (l > 0)
2728 		bb_putchar('\n');
2729 	bb_putchar('\n');
2730 }
2731 
2732 static void
print_raw(void)2733 print_raw(void)
2734 {
2735 	int i;
2736 
2737 	printf("Device: %s\n", disk_device);
2738 	if (LABEL_IS_SGI || LABEL_IS_SUN)
2739 		print_buffer(MBRbuffer);
2740 	else {
2741 		for (i = 3; i < g_partitions; i++)
2742 			print_buffer(ptes[i].sectorbuffer);
2743 	}
2744 }
2745 
2746 static void
move_begin(unsigned i)2747 move_begin(unsigned i)
2748 {
2749 	struct pte *pe = &ptes[i];
2750 	struct partition *p = pe->part_table;
2751 	sector_t new, first, nr_sects;
2752 
2753 	if (warn_geometry())
2754 		return;
2755 	nr_sects = get_nr_sects(p);
2756 	if (!p->sys_ind || !nr_sects || IS_EXTENDED(p->sys_ind)) {
2757 		printf("Partition %u has no data area\n", i + 1);
2758 		return;
2759 	}
2760 	first = get_partition_start_from_dev_start(pe); /* == pe->offset_from_dev_start + get_start_sect(p) */
2761 	new = read_int(0 /*was:first*/, first, first + nr_sects - 1, first, "New beginning of data");
2762 	if (new != first) {
2763 		sector_t new_relative = new - pe->offset_from_dev_start;
2764 		nr_sects += (get_start_sect(p) - new_relative);
2765 		set_start_sect(p, new_relative);
2766 		set_nr_sects(p, nr_sects);
2767 		read_nonempty("Recalculate C/H/S values? (Y/N): ");
2768 		if ((line_ptr[0] | 0x20) == 'y')
2769 			set_hsc_start_end(p, new, new + nr_sects - 1);
2770 		pe->changed = 1;
2771 	}
2772 }
2773 
2774 static void
xselect(void)2775 xselect(void)
2776 {
2777 	char c;
2778 
2779 	while (1) {
2780 		bb_putchar('\n');
2781 		c = 0x20 | read_nonempty("Expert command (m for help): ");
2782 		switch (c) {
2783 		case 'a':
2784 			if (LABEL_IS_SUN)
2785 				sun_set_alt_cyl();
2786 			break;
2787 		case 'b':
2788 			if (LABEL_IS_DOS)
2789 				move_begin(get_partition(0, g_partitions));
2790 			break;
2791 		case 'c':
2792 			user_cylinders = g_cylinders =
2793 				read_int(1, g_cylinders, 1048576, 0,
2794 					"Number of cylinders");
2795 			if (LABEL_IS_SUN)
2796 				sun_set_ncyl(g_cylinders);
2797 			if (LABEL_IS_DOS)
2798 				warn_cylinders();
2799 			break;
2800 		case 'd':
2801 			print_raw();
2802 			break;
2803 		case 'e':
2804 			if (LABEL_IS_SGI)
2805 				sgi_set_xcyl();
2806 			else if (LABEL_IS_SUN)
2807 				sun_set_xcyl();
2808 			else if (LABEL_IS_DOS)
2809 				x_list_table(1);
2810 			break;
2811 		case 'f':
2812 			if (LABEL_IS_DOS)
2813 				fix_partition_table_order();
2814 			break;
2815 		case 'g':
2816 #if ENABLE_FEATURE_SGI_LABEL
2817 			create_sgilabel();
2818 #endif
2819 			break;
2820 		case 'h':
2821 			user_heads = g_heads = read_int(1, g_heads, 256, 0, "Number of heads");
2822 			update_units();
2823 			break;
2824 		case 'i':
2825 			if (LABEL_IS_SUN)
2826 				sun_set_ilfact();
2827 			break;
2828 		case 'o':
2829 			if (LABEL_IS_SUN)
2830 				sun_set_rspeed();
2831 			break;
2832 		case 'p':
2833 			if (LABEL_IS_SUN)
2834 				list_table(1);
2835 			else
2836 				x_list_table(0);
2837 			break;
2838 		case 'q':
2839 			if (ENABLE_FEATURE_CLEAN_UP)
2840 				close_dev_fd();
2841 			bb_putchar('\n');
2842 			exit(EXIT_SUCCESS);
2843 		case 'r':
2844 			return;
2845 		case 's':
2846 			user_sectors = g_sectors = read_int(1, g_sectors, 63, 0, "Number of sectors");
2847 			if (dos_compatible_flag) {
2848 				sector_offset = g_sectors;
2849 				puts("Warning: setting sector offset for DOS "
2850 					"compatiblity");
2851 			}
2852 			update_units();
2853 			break;
2854 		case 'v':
2855 			verify();
2856 			break;
2857 		case 'w':
2858 			write_table();  /* does not return */
2859 			break;
2860 		case 'y':
2861 			if (LABEL_IS_SUN)
2862 				sun_set_pcylcount();
2863 			break;
2864 		default:
2865 			xmenu();
2866 		}
2867 	}
2868 }
2869 #endif /* ADVANCED mode */
2870 
2871 static int
is_ide_cdrom_or_tape(const char * device)2872 is_ide_cdrom_or_tape(const char *device)
2873 {
2874 	FILE *procf;
2875 	char buf[100];
2876 	struct stat statbuf;
2877 	int is_ide = 0;
2878 
2879 	/* No device was given explicitly, and we are trying some
2880 	   likely things.  But opening /dev/hdc may produce errors like
2881 	   "hdc: tray open or drive not ready"
2882 	   if it happens to be a CD-ROM drive. It even happens that
2883 	   the process hangs on the attempt to read a music CD.
2884 	   So try to be careful. This only works since 2.1.73. */
2885 
2886 	if (!is_prefixed_with(device, "/dev/hd"))
2887 		return 0;
2888 
2889 	snprintf(buf, sizeof(buf), "/proc/ide/%s/media", device+5);
2890 	procf = fopen_for_read(buf);
2891 	if (procf != NULL && fgets(buf, sizeof(buf), procf))
2892 		is_ide = (is_prefixed_with(buf, "cdrom") ||
2893 			  is_prefixed_with(buf, "tape"));
2894 	else
2895 		/* Now when this proc file does not exist, skip the
2896 		   device when it is read-only. */
2897 		if (stat(device, &statbuf) == 0)
2898 			is_ide = ((statbuf.st_mode & 0222) == 0);
2899 
2900 	if (procf)
2901 		fclose(procf);
2902 	return is_ide;
2903 }
2904 
2905 
2906 static void
open_list_and_close(const char * device,int user_specified)2907 open_list_and_close(const char *device, int user_specified)
2908 {
2909 	int gb;
2910 
2911 	disk_device = device;
2912 	if (setjmp(listingbuf))
2913 		return;
2914 	if (!user_specified)
2915 		if (is_ide_cdrom_or_tape(device))
2916 			return;
2917 
2918 	/* Open disk_device, save file descriptor to dev_fd */
2919 	errno = 0;
2920 	gb = get_boot(TRY_ONLY);
2921 	if (gb > 0) {   /* I/O error */
2922 		/* Ignore other errors, since we try IDE
2923 		   and SCSI hard disks which may not be
2924 		   installed on the system. */
2925 		if (user_specified || errno == EACCES)
2926 			bb_perror_msg("can't open '%s'", device);
2927 		return;
2928 	}
2929 
2930 	if (gb < 0) { /* no DOS signature */
2931 		list_disk_geometry();
2932 		if (LABEL_IS_AIX)
2933 			goto ret;
2934 #if ENABLE_FEATURE_OSF_LABEL
2935 		if (bsd_trydev(device) < 0)
2936 #endif
2937 			printf("Disk %s doesn't contain a valid "
2938 				"partition table\n", device);
2939 	} else {
2940 		list_table(0);
2941 #if ENABLE_FEATURE_FDISK_WRITABLE
2942 		if (!LABEL_IS_SUN && g_partitions > 4) {
2943 			delete_partition(ext_index);
2944 		}
2945 #endif
2946 	}
2947  ret:
2948 	close_dev_fd();
2949 }
2950 
2951 /* Is it a whole disk? The digit check is still useful
2952    for Xen devices for example. */
is_whole_disk(const char * disk)2953 static int is_whole_disk(const char *disk)
2954 {
2955 	unsigned len;
2956 	int fd = open(disk, O_RDONLY);
2957 
2958 	if (fd != -1) {
2959 		struct hd_geometry geometry;
2960 		int err = ioctl(fd, HDIO_GETGEO, &geometry);
2961 		close(fd);
2962 		if (!err)
2963 			return (geometry.start == 0);
2964 	}
2965 
2966 	/* Treat "nameN" as a partition name, not whole disk */
2967 	/* note: mmcblk0 should work from the geometry check above */
2968 	len = strlen(disk);
2969 	if (len != 0 && isdigit(disk[len - 1]))
2970 		return 0;
2971 
2972 	return 1;
2973 }
2974 
2975 /* for fdisk -l: try all things in /proc/partitions
2976    that look like a partition name (do not end in a digit) */
2977 static void
list_devs_in_proc_partititons(void)2978 list_devs_in_proc_partititons(void)
2979 {
2980 	FILE *procpt;
2981 	char line[100], ptname[100], devname[120];
2982 	int ma, mi, sz;
2983 
2984 	procpt = fopen_or_warn("/proc/partitions", "r");
2985 
2986 	while (fgets(line, sizeof(line), procpt)) {
2987 		if (sscanf(line, " %u %u %u %[^\n ]",
2988 				&ma, &mi, &sz, ptname) != 4)
2989 			continue;
2990 
2991 		sprintf(devname, "/dev/%s", ptname);
2992 		if (is_whole_disk(devname))
2993 			open_list_and_close(devname, 0);
2994 	}
2995 #if ENABLE_FEATURE_CLEAN_UP
2996 	fclose(procpt);
2997 #endif
2998 }
2999 
3000 #if ENABLE_FEATURE_FDISK_WRITABLE
3001 static void
unknown_command(int c)3002 unknown_command(int c)
3003 {
3004 	printf("%c: unknown command\n", c);
3005 }
3006 #endif
3007 
3008 int fdisk_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
fdisk_main(int argc UNUSED_PARAM,char ** argv)3009 int fdisk_main(int argc UNUSED_PARAM, char **argv)
3010 {
3011 	unsigned opt;
3012 	/*
3013 	 *  fdisk -v
3014 	 *  fdisk -l [-b sectorsize] [-u] device ...
3015 	 *  fdisk -s [partition] ...
3016 	 *  fdisk [-b sectorsize] [-u] device
3017 	 *
3018 	 * Options -C, -H, -S set the geometry.
3019 	 */
3020 	INIT_G();
3021 
3022 	close_dev_fd(); /* needed: fd 3 must not stay closed */
3023 
3024 	opt = getopt32(argv, "b:+C:+H:+lS:+u" IF_FEATURE_FDISK_BLKSIZE("s"),
3025 				&sector_size, &user_cylinders, &user_heads, &user_sectors);
3026 	argv += optind;
3027 	if (opt & OPT_b) {
3028 		/* Ugly: this sector size is really per device,
3029 		 * so cannot be combined with multiple disks,
3030 		 * and the same goes for the C/H/S options.
3031 		 */
3032 		if (sector_size < 512
3033 		 || sector_size > 0x10000
3034 		 || (sector_size & (sector_size-1)) /* not power of 2 */
3035 		) {
3036 			bb_show_usage();
3037 		}
3038 		sector_offset = 2;
3039 		user_set_sector_size = 1;
3040 	}
3041 	if (user_heads <= 0 || user_heads >= 256)
3042 		user_heads = 0;
3043 	if (user_sectors <= 0 || user_sectors >= 64)
3044 		user_sectors = 0;
3045 	if (opt & OPT_u)
3046 		display_in_cyl_units = 0; // -u
3047 
3048 #if ENABLE_FEATURE_FDISK_WRITABLE
3049 	if (opt & OPT_l) {
3050 		nowarn = 1;
3051 #endif
3052 		if (*argv) {
3053 			listing = 1;
3054 			do {
3055 				open_list_and_close(*argv, 1);
3056 			} while (*++argv);
3057 		} else {
3058 			/* we don't have device names, */
3059 			/* use /proc/partitions instead */
3060 			list_devs_in_proc_partititons();
3061 		}
3062 		return 0;
3063 #if ENABLE_FEATURE_FDISK_WRITABLE
3064 	}
3065 #endif
3066 
3067 #if ENABLE_FEATURE_FDISK_BLKSIZE
3068 	if (opt & OPT_s) {
3069 		int j;
3070 
3071 		nowarn = 1;
3072 		if (!argv[0])
3073 			bb_show_usage();
3074 		for (j = 0; argv[j]; j++) {
3075 			unsigned long long size;
3076 			fd = xopen(argv[j], O_RDONLY);
3077 			size = bb_BLKGETSIZE_sectors(fd) / 2;
3078 			close(fd);
3079 			if (argv[1])
3080 				printf("%llu\n", size);
3081 			else
3082 				printf("%s: %llu\n", argv[j], size);
3083 		}
3084 		return 0;
3085 	}
3086 #endif
3087 
3088 #if ENABLE_FEATURE_FDISK_WRITABLE
3089 	if (!argv[0] || argv[1])
3090 		bb_show_usage();
3091 
3092 	disk_device = argv[0];
3093 	get_boot(OPEN_MAIN);
3094 
3095 	if (LABEL_IS_OSF) {
3096 		/* OSF label, and no DOS label */
3097 		printf("Detected an OSF/1 disklabel on %s, entering "
3098 			"disklabel mode\n", disk_device);
3099 		bsd_select();
3100 		/*Why do we do this?  It seems to be counter-intuitive*/
3101 		current_label_type = LABEL_DOS;
3102 		/* If we return we may want to make an empty DOS label? */
3103 	}
3104 
3105 	while (1) {
3106 		int c;
3107 		bb_putchar('\n');
3108 		c = 0x20 | read_nonempty("Command (m for help): ");
3109 		switch (c) {
3110 		case 'a':
3111 			if (LABEL_IS_DOS)
3112 				toggle_active(get_partition(1, g_partitions));
3113 			else if (LABEL_IS_SUN)
3114 				toggle_sunflags(get_partition(1, g_partitions),
3115 						0x01);
3116 			else if (LABEL_IS_SGI)
3117 				sgi_set_bootpartition(
3118 					get_partition(1, g_partitions));
3119 			else
3120 				unknown_command(c);
3121 			break;
3122 		case 'b':
3123 			if (LABEL_IS_SGI) {
3124 				printf("\nThe current boot file is: %s\n",
3125 					sgi_get_bootfile());
3126 				if (read_maybe_empty("Please enter the name of the "
3127 						"new boot file: ") == '\n')
3128 					puts("Boot file unchanged");
3129 				else
3130 					sgi_set_bootfile(line_ptr);
3131 			}
3132 #if ENABLE_FEATURE_OSF_LABEL
3133 			else
3134 				bsd_select();
3135 #endif
3136 			break;
3137 		case 'c':
3138 			if (LABEL_IS_DOS)
3139 				toggle_dos_compatibility_flag();
3140 			else if (LABEL_IS_SUN)
3141 				toggle_sunflags(get_partition(1, g_partitions),
3142 						0x10);
3143 			else if (LABEL_IS_SGI)
3144 				sgi_set_swappartition(
3145 						get_partition(1, g_partitions));
3146 			else
3147 				unknown_command(c);
3148 			break;
3149 		case 'd':
3150 			{
3151 				int j;
3152 			/* If sgi_label then don't use get_existing_partition,
3153 			   let the user select a partition, since
3154 			   get_existing_partition() only works for Linux-like
3155 			   partition tables */
3156 				if (!LABEL_IS_SGI) {
3157 					j = get_existing_partition(1, g_partitions);
3158 				} else {
3159 					j = get_partition(1, g_partitions);
3160 				}
3161 				if (j >= 0)
3162 					delete_partition(j);
3163 			}
3164 			break;
3165 		case 'i':
3166 			if (LABEL_IS_SGI)
3167 				create_sgiinfo();
3168 			else
3169 				unknown_command(c);
3170 		case 'l':
3171 			list_types(get_sys_types());
3172 			break;
3173 		case 'm':
3174 			menu();
3175 			break;
3176 		case 'n':
3177 			new_partition();
3178 			break;
3179 		case 'o':
3180 			create_doslabel();
3181 			break;
3182 		case 'p':
3183 			list_table(0);
3184 			break;
3185 		case 'q':
3186 			if (ENABLE_FEATURE_CLEAN_UP)
3187 				close_dev_fd();
3188 			bb_putchar('\n');
3189 			return 0;
3190 		case 's':
3191 #if ENABLE_FEATURE_SUN_LABEL
3192 			create_sunlabel();
3193 #endif
3194 			break;
3195 		case 't':
3196 			change_sysid();
3197 			break;
3198 		case 'u':
3199 			change_units();
3200 			break;
3201 		case 'v':
3202 			verify();
3203 			break;
3204 		case 'w':
3205 			write_table();  /* does not return */
3206 			break;
3207 #if ENABLE_FEATURE_FDISK_ADVANCED
3208 		case 'x':
3209 			if (LABEL_IS_SGI) {
3210 				puts("\n\tSorry, no experts menu for SGI "
3211 					"partition tables available\n");
3212 			} else
3213 				xselect();
3214 			break;
3215 #endif
3216 		default:
3217 			unknown_command(c);
3218 			menu();
3219 		}
3220 	}
3221 	return 0;
3222 #endif /* FEATURE_FDISK_WRITABLE */
3223 }
3224