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