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