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