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