+ wrap things in B<> to make pod2man happy
[oweals/busybox.git] / sfdisk.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * sfdisk version 3.0 - aeb - 950813
4  *
5  * Copyright (C) 1995  Andries E. Brouwer (aeb@cwi.nl)
6  *
7  * This program is free software. You can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation: either Version 1
10  * or (at your option) any later version.
11  *
12  * A.V. Le Blanc (LeBlanc@mcc.ac.uk) wrote Linux fdisk 1992-1994,
13  * patched by various people (faith@cs.unc.edu, martin@cs.unc.edu,
14  * leisner@sdsp.mc.xerox.com, esr@snark.thyrsus.com, aeb@cwi.nl)
15  * 1993-1995, with version numbers (as far as I have seen) 0.93 - 2.0e.
16  * This program had (head,sector,cylinder) as basic unit, and was
17  * (therefore) broken in several ways for the use on larger disks -
18  * for example, my last patch (from 2.0d to 2.0e) was required
19  * to allow a partition to cross cylinder 8064, and to write an
20  * extended partition past the 4GB mark.
21  *
22  * The current program is a rewrite from scratch, and I started a
23  * version numbering at 3.0.
24  *      Andries Brouwer, aeb@cwi.nl, 950813
25  *
26  * Well, a good user interface is still lacking. On the other hand,
27  * many configurations cannot be handled by any other fdisk.
28  * I changed the name to sfdisk to prevent confusion. - aeb, 970501
29  *
30  * Changes:
31  * 19990319 - Arnaldo Carvalho de Melo <acme@conectiva.com.br> - i18n
32  *
33  * busyboxed by Erik Andersen <andersee@debian.org> -- I stipped out
34  * all the NLS, pulled in some includes, and made stuff smaller...
35  */
36
37 #define PROGNAME "sfdisk"
38 #define VERSION "3.07"
39 #define DATE "990908"
40
41 #include "internal.h"
42 #include <stdio.h>
43 #include <stdlib.h>                             /* atoi, free */
44 #include <stdarg.h>                             /* varargs */
45 #include <unistd.h>                             /* read, write */
46 #include <fcntl.h>                              /* O_RDWR */
47 #include <errno.h>                              /* ERANGE */
48 #include <string.h>                             /* index() */
49 #include <ctype.h>
50 #include <getopt.h>
51 #include <sys/ioctl.h>
52 #include <sys/stat.h>
53 #include <linux/unistd.h>               /* _syscall */
54 #include <linux/hdreg.h>                /* HDIO_GETGEO */
55 #include <linux/fs.h>                   /* BLKGETSIZE */
56
57
58 static const char sfdisk_usage[] =
59         "sfdisk [options] device ...\n"
60         "device: something like /dev/hda or /dev/sda\n"
61         "useful options:\n"
62         "    -s [or --show-size]: list size of a partition\n"
63         "    -c [or --id]:        print or change partition Id\n"
64         "    -l [or --list]:      list partitions of each device\n"
65         "    -d [or --dump]:      idem, but in a format suitable for later input\n"
66         "    -i [or --increment]: number cylinders etc. from 1 instead of from 0\n"
67         "    -uS, -uB, -uC, -uM:  accept/report in units of sectors/blocks/cylinders/MB\n"
68         "    -T [or --list-types]:list the known partition types\n"
69         "    -D [or --DOS]:       for DOS-compatibility: waste a little space\n"
70         "    -R [or --re-read]:   make kernel reread partition table\n"
71         "    -N# :                change only the partition with number #\n"
72         "    -n :                 do not actually write to disk\n"
73         "    -O file :            save the sectors that will be overwritten to file\n"
74         "    -I file :            restore these sectors again\n"
75         "    -v [or --version]:   print version\n"
76         "    -? [or --help]:      print this message\n"
77         "dangerous options:\n"
78         "    -g [or --show-geometry]: print the kernel's idea of the geometry\n"
79         "    -x [or --show-extended]: also list extended partitions on output\n\n"
80         "                             or expect descriptors for them on input\n"
81         "    -L  [or --Linux]:      do not complain about things irrelevant for Linux\n"
82         "    -q  [or --quiet]:      suppress warning messages\n"
83         "    You can override the detected geometry using:\n"
84         "    -C# [or --cylinders #]:set the number of cylinders to use\n"
85         "    -H# [or --heads #]:    set the number of heads to use\n"
86         "    -S# [or --sectors #]:  set the number of sectors to use\n"
87
88         "You can disable all consistency checking with:\n"
89         "    -f  [or --force]:      do what I say, even if it is stupid\n";
90
91
92
93 /* common stuff for fdisk, cfdisk, sfdisk */
94 struct systypes {
95         unsigned char type;
96         char *name;
97 };
98
99 static struct systypes i386_sys_types[] = {
100         {0x00, "Empty"},
101         {0x01, "FAT12"},
102         {0x02, "XENIX root"},
103         {0x03, "XENIX usr"},
104         {0x04, "FAT16 <32M"},
105         {0x05, "Extended"},                     /* DOS 3.3+ extended partition */
106         {0x06, "FAT16"},                        /* DOS 16-bit >=32M */
107         {0x07, "HPFS/NTFS"},            /* OS/2 IFS, eg, HPFS or NTFS or QNX */
108         {0x08, "AIX"},                          /* AIX boot (AIX -- PS/2 port or SplitDrive) */
109         {0x09, "AIX bootable"},         /* AIX data or Coherent */
110         {0x0a, "OS/2 Boot Manager"},    /* OS/2 Boot Manager */
111         {0x0b, "Win95 FAT32"},
112         {0x0c, "Win95 FAT32 (LBA)"},    /* LBA really is `Extended Int 13h' */
113         {0x0e, "Win95 FAT16 (LBA)"},
114         {0x0f, "Win95 Ext'd (LBA)"},
115         {0x10, "OPUS"},
116         {0x11, "Hidden FAT12"},
117         {0x12, "Compaq diagnostics"},
118         {0x14, "Hidden FAT16 <32M"},
119         {0x16, "Hidden FAT16"},
120         {0x17, "Hidden HPFS/NTFS"},
121         {0x18, "AST Windows swapfile"},
122         {0x1b, "Hidden Win95 FAT32"},
123         {0x1c, "Hidden Win95 FAT32 (LBA)"},
124         {0x1e, "Hidden Win95 FAT16 (LBA)"},
125         {0x24, "NEC DOS"},
126         {0x3c, "PartitionMagic recovery"},
127         {0x40, "Venix 80286"},
128         {0x41, "PPC PReP Boot"},
129         {0x42, "SFS"},
130         {0x4d, "QNX4.x"},
131         {0x4e, "QNX4.x 2nd part"},
132         {0x4f, "QNX4.x 3rd part"},
133         {0x50, "OnTrack DM"},
134         {0x51, "OnTrack DM6 Aux1"},     /* (or Novell) */
135         {0x52, "CP/M"},                         /* CP/M or Microport SysV/AT */
136         {0x53, "OnTrack DM6 Aux3"},
137         {0x54, "OnTrackDM6"},
138         {0x55, "EZ-Drive"},
139         {0x56, "Golden Bow"},
140         {0x5c, "Priam Edisk"},
141         {0x61, "SpeedStor"},
142         {0x63, "GNU HURD or SysV"},     /* GNU HURD or Mach or Sys V/386 (such as ISC UNIX) */
143         {0x64, "Novell Netware 286"},
144         {0x65, "Novell Netware 386"},
145         {0x70, "DiskSecure Multi-Boot"},
146         {0x75, "PC/IX"},
147         {0x80, "Old Minix"},            /* Minix 1.4a and earlier */
148         {0x81, "Minix / old Linux"},    /* Minix 1.4b and later */
149         {0x82, "Linux swap"},           /* also Solaris */
150         {0x83, "Linux"},
151         {0x84, "OS/2 hidden C: drive"},
152         {0x85, "Linux extended"},
153         {0x86, "NTFS volume set"},
154         {0x87, "NTFS volume set"},
155         {0x93, "Amoeba"},
156         {0x94, "Amoeba BBT"},           /* (bad block table) */
157         {0xa0, "IBM Thinkpad hibernation"},
158         {0xa5, "BSD/386"},
159         {0xa6, "OpenBSD"},
160         {0xa7, "NeXTSTEP"},
161         {0xb7, "BSDI fs"},
162         {0xb8, "BSDI swap"},
163         {0xc1, "DRDOS/sec (FAT-12)"},
164         {0xc4, "DRDOS/sec (FAT-16 < 32M)"},
165         {0xc6, "DRDOS/sec (FAT-16)"},
166         {0xc7, "Syrinx"},
167         {0xdb, "CP/M / CTOS / ..."},    /* CP/M or Concurrent CP/M or Concurrent DOS or CTOS */
168         {0xe1, "DOS access"},           /* DOS access or SpeedStor 12-bit FAT extended partition */
169         {0xe3, "DOS R/O"},                      /* DOS R/O or SpeedStor */
170         {0xe4, "SpeedStor"},            /* SpeedStor 16-bit FAT extended partition < 1024 cyl. */
171         {0xeb, "BeOS fs"},
172         {0xf1, "SpeedStor"},
173         {0xf4, "SpeedStor"},            /* SpeedStor large partition */
174         {0xf2, "DOS secondary"},        /* DOS 3.3+ secondary */
175         {0xfd, "Linux raid autodetect"},        /* New (2.2.x) raid partition with autodetect
176                                                                                    using persistent superblock */
177         {0xfe, "LANstep"},                      /* SpeedStor >1024 cyl. or LANstep */
178         {0xff, "BBT"},                          /* Xenix Bad Block Table */
179         {0, 0}
180 };
181
182 #define SIZE(a) (sizeof(a)/sizeof(a[0]))
183
184 /*
185  * Table of contents:
186  *  A. About seeking
187  *  B. About sectors
188  *  C. About heads, sectors and cylinders
189  *  D. About system Ids
190  *  E. About partitions
191  *  F. The standard input
192  *  G. The command line
193  *  H. Listing the current situation
194  *  I. Writing the new situation
195  */
196 static int exit_status = 0;
197
198 static int force = 0;                   /* 1: do what I say, even if it is stupid ... */
199 static int quiet = 0;                   /* 1: suppress all warnings */
200 static int Linux = 0;                   /* 1: suppress warnings irrelevant for Linux */
201 static int DOS = 0;                             /* 1: shift extended partitions by #sectors, not 1 */
202 static int dump = 0;                    /* 1: list in a format suitable for later input */
203 static int verify = 0;                  /* 1: check that listed partition is reasonable */
204 static int no_write = 0;                /* 1: do not actually write to disk */
205 static int no_reread = 0;               /* 1: skip the BLKRRPART ioctl test at startup */
206 static int leave_last = 0;              /* 1: don't allocate the last cylinder */
207 static int opt_list = 0;
208 static char *save_sector_file = NULL;
209 static char *restore_sector_file = NULL;
210
211 static void warn(char *s, ...) __attribute__ ((format (printf, 1, 2)));
212 static void warn(char *s, ...)
213 {
214         va_list p;
215
216         va_start(p, s);
217         fflush(stdout);
218         if (!quiet)
219                 vfprintf(stderr, s, p);
220         va_end(p);
221 }
222
223 /*
224  *  A. About seeking
225  */
226
227 /*
228  * sseek: seek to specified sector - return 0 on failure
229  *
230  * For >4GB disks lseek needs a > 32bit arg, and we have to use llseek.
231  * On the other hand, a 32 bit sector number is OK until 2TB.
232  * The routines _llseek and sseek below are the only ones that
233  * know about the loff_t type.
234  */
235 #ifndef __alpha__
236 static
237 _syscall5(int, _llseek, uint, fd, ulong, hi, ulong, lo,
238                   loff_t *, res, uint, wh);
239 #endif
240
241 static int sseek(char *dev, unsigned int fd, unsigned long s)
242 {
243         loff_t in, out;
244
245         in = ((loff_t) s << 9);
246         out = 1;
247
248 #ifndef __alpha__
249         if (_llseek(fd, in >> 32, in & 0xffffffff, &out, SEEK_SET) != 0) {
250 #else
251         if ((out = lseek(fd, in, SEEK_SET)) != in) {
252 #endif
253                 perror("llseek");
254                 errorMsg("seek error on %s - cannot seek to %lu\n", dev, s);
255                 return 0;
256         }
257
258         if (in != out) {
259                 errorMsg("seek error: wanted 0x%08x%08x, got 0x%08x%08x\n",
260                           (uint) (in >> 32), (uint) (in & 0xffffffff),
261                           (uint) (out >> 32), (uint) (out & 0xffffffff));
262                 return 0;
263         }
264         return 1;
265 }
266
267 /*
268  *  B. About sectors
269  */
270
271 /*
272  * We preserve all sectors read in a chain - some of these will
273  * have to be modified and written back.
274  */
275 struct sector {
276         struct sector *next;
277         unsigned long sectornumber;
278         int to_be_written;
279         char data[512];
280 } *sectorhead;
281
282 static void free_sectors(void)
283 {
284         struct sector *s;
285
286         while (sectorhead) {
287                 s = sectorhead;
288                 sectorhead = s->next;
289                 free(s);
290         }
291 }
292
293 static struct sector *get_sector(char *dev, int fd, unsigned long sno)
294 {
295         struct sector *s;
296
297         for (s = sectorhead; s; s = s->next)
298                 if (s->sectornumber == sno)
299                         return s;
300
301         if (!sseek(dev, fd, sno))
302                 return 0;
303
304         s = (struct sector *) xmalloc(sizeof(struct sector));
305
306         if (read(fd, s->data, sizeof(s->data)) != sizeof(s->data)) {
307                 perror("read");
308                 errorMsg("read error on %s - cannot read sector %lu\n", dev, sno);
309                 free(s);
310                 return 0;
311         }
312
313         s->next = sectorhead;
314         sectorhead = s;
315         s->sectornumber = sno;
316         s->to_be_written = 0;
317
318         return s;
319 }
320
321 static int msdos_signature(struct sector *s)
322 {
323         if (*(unsigned short *) (s->data + 0x1fe) != 0xaa55) {
324                 errorMsg("ERROR: sector %lu does not have an msdos signature\n",
325                           s->sectornumber);
326                 return 0;
327         }
328         return 1;
329 }
330
331 static int write_sectors(char *dev, int fd)
332 {
333         struct sector *s;
334
335         for (s = sectorhead; s; s = s->next)
336                 if (s->to_be_written) {
337                         if (!sseek(dev, fd, s->sectornumber))
338                                 return 0;
339                         if (write(fd, s->data, sizeof(s->data)) != sizeof(s->data)) {
340                                 perror("write");
341                                 errorMsg("write error on %s - cannot write sector %lu\n",
342                                           dev, s->sectornumber);
343                                 return 0;
344                         }
345                         s->to_be_written = 0;
346                 }
347         return 1;
348 }
349
350 static void ulong_to_chars(unsigned long u, char *uu)
351 {
352         int i;
353
354         for (i = 0; i < 4; i++) {
355                 uu[i] = (u & 0xff);
356                 u >>= 8;
357         }
358 }
359
360 static unsigned long chars_to_ulong(unsigned char *uu)
361 {
362         int i;
363         unsigned long u = 0;
364
365         for (i = 3; i >= 0; i--)
366                 u = (u << 8) | uu[i];
367         return u;
368 }
369
370 static int save_sectors(char *dev, int fdin)
371 {
372         struct sector *s;
373         char ss[516];
374         int fdout;
375
376         fdout = open(save_sector_file, O_WRONLY | O_CREAT, 0444);
377         if (fdout < 0) {
378                 perror(save_sector_file);
379                 errorMsg("cannot open partition sector save file (%s)\n",
380                           save_sector_file);
381                 return 0;
382         }
383
384         for (s = sectorhead; s; s = s->next)
385                 if (s->to_be_written) {
386                         ulong_to_chars(s->sectornumber, ss);
387                         if (!sseek(dev, fdin, s->sectornumber))
388                                 return 0;
389                         if (read(fdin, ss + 4, 512) != 512) {
390                                 perror("read");
391                                 errorMsg("read error on %s - cannot read sector %lu\n",
392                                           dev, s->sectornumber);
393                                 return 0;
394                         }
395                         if (write(fdout, ss, sizeof(ss)) != sizeof(ss)) {
396                                 perror("write");
397                                 errorMsg("write error on %s\n", save_sector_file);
398                                 return 0;
399                         }
400                 }
401         return 1;
402 }
403
404 static void reread_disk_partition(char *dev, int fd);
405
406 static int restore_sectors(char *dev)
407 {
408         int fdin, fdout, ct;
409         struct stat statbuf;
410         char *ss0, *ss;
411         unsigned long sno;
412
413         if (stat(restore_sector_file, &statbuf) < 0) {
414                 perror(restore_sector_file);
415                 errorMsg("cannot stat partition restore file (%s)\n",
416                           restore_sector_file);
417                 return 0;
418         }
419         if (statbuf.st_size % 516) {
420                 errorMsg("partition restore file has wrong size - not restoring\n");
421                 return 0;
422         }
423         if (!(ss = (char *) malloc(statbuf.st_size))) {
424                 errorMsg("out of memory?\n");
425                 return 0;
426         }
427         fdin = open(restore_sector_file, O_RDONLY);
428         if (fdin < 0) {
429                 perror(restore_sector_file);
430                 errorMsg("cannot open partition restore file (%s)\n",
431                           restore_sector_file);
432                 return 0;
433         }
434         if (read(fdin, ss, statbuf.st_size) != statbuf.st_size) {
435                 perror("read");
436                 errorMsg("error reading %s\n", restore_sector_file);
437                 return 0;
438         }
439
440         fdout = open(dev, O_WRONLY);
441         if (fdout < 0) {
442                 perror(dev);
443                 errorMsg("cannot open device %s for writing\n", dev);
444                 return 0;
445         }
446
447         ss0 = ss;
448         ct = statbuf.st_size / 516;
449         while (ct--) {
450                 sno = chars_to_ulong(ss);
451                 if (!sseek(dev, fdout, sno))
452                         return 0;
453                 if (write(fdout, ss + 4, 512) != 512) {
454                         perror(dev);
455                         errorMsg("error writing sector %lu on %s\n", sno, dev);
456                         return 0;
457                 }
458                 ss += 516;
459         }
460         free(ss0);
461
462         reread_disk_partition(dev, fdout);
463
464         return 1;
465 }
466
467 /*
468  *  C. About heads, sectors and cylinders
469  */
470
471 /*
472  * <linux/hdreg.h> defines HDIO_GETGEO and
473  * struct hd_geometry {
474  *      unsigned char heads;
475  *      unsigned char sectors;
476  *      unsigned short cylinders;
477  *      unsigned long start;
478  * };
479  */
480
481 /*
482  * We consider several geometries for a disk:
483  * B - the BIOS geometry, gotten from the kernel via HDIO_GETGEO
484  * F - the fdisk geometry
485  * U - the user-specified geometry
486  *
487  * 0 means unspecified / unknown
488  */
489 struct geometry {
490         unsigned long cylindersize;
491         unsigned long heads, sectors, cylinders;
492 } B, F, U;
493
494 static void get_cylindersize(char *dev, int fd, int silent)
495 {
496         struct hd_geometry g;
497         int ioctl_ok = 0;
498
499         B.heads = B.sectors = B.cylinders = 0;
500
501         if (!ioctl(fd, HDIO_GETGEO, &g)) {
502                 ioctl_ok = 1;
503
504                 B.heads = g.heads;
505                 B.sectors = g.sectors;
506                 B.cylinders = g.cylinders;
507         }
508
509         if (U.heads)
510                 B.heads = U.heads;
511         if (U.sectors)
512                 B.sectors = U.sectors;
513         if (U.cylinders)
514                 B.cylinders = U.cylinders;
515
516         B.cylindersize = B.heads * B.sectors;
517
518         if (ioctl_ok) {
519                 if (g.start && !force) {
520                         warn
521                                 ("Warning: start=%ld - this looks like a partition rather than\n"
522                                  "the entire disk. Using fdisk on it is probably meaningless.\n"
523                                  "[Use the --force option if you really want this]\n",
524                                  g.start);
525                         exit(1);
526                 }
527                 if (B.heads != g.heads)
528                         warn("Warning: HDIO_GETGEO says that there are %d heads\n",
529                                  g.heads);
530                 if (B.sectors != g.sectors)
531                         warn("Warning: HDIO_GETGEO says that there are %d sectors\n",
532                                  g.sectors);
533                 if (B.cylinders != g.cylinders)
534                         warn("Warning: HDIO_GETGEO says that there are %d cylinders\n",
535                                  g.cylinders);
536         } else if (!silent)
537                 if (!B.heads || !B.sectors || !B.cylinders)
538                         printf("Disk %s: cannot get geometry\n", dev);
539         if (B.sectors > 63)
540                 warn
541                         ("Warning: unlikely number of sectors (%ld - usually at most 63\n"
542                          "This will give problems with all software that uses C/H/S addressing.\n",
543                          B.sectors);
544         if (!silent)
545                 printf("\nDisk %s: %lu cylinders, %lu heads, %lu sectors/track\n",
546                            dev, B.cylinders, B.heads, B.sectors);
547 }
548
549 typedef struct {
550         unsigned char h, s, c;
551 } chs;                                                  /* has some c bits in s */
552 static chs zero_chs = { 0, 0, 0 };
553
554 typedef struct {
555         unsigned long h, s, c;
556 } longchs;
557 static longchs zero_longchs;
558
559 static chs longchs_to_chs(longchs aa, struct geometry G)
560 {
561         chs a;
562
563         if (aa.h < 256 && aa.s < 64 && aa.c < 1024) {
564                 a.h = aa.h;
565                 a.s = aa.s | ((aa.c >> 2) & 0xc0);
566                 a.c = (aa.c & 0xff);
567         } else if (G.heads && G.sectors) {
568                 a.h = G.heads - 1;
569                 a.s = G.sectors | 0xc0;
570                 a.c = 0xff;
571         } else
572                 a = zero_chs;
573         return a;
574 }
575
576 static longchs chs_to_longchs(chs a)
577 {
578         longchs aa;
579
580         aa.h = a.h;
581         aa.s = (a.s & 0x3f);
582         aa.c = (a.s & 0xc0);
583         aa.c = (aa.c << 2) + a.c;
584         return aa;
585 }
586
587 static longchs ulong_to_longchs(unsigned long sno, struct geometry G)
588 {
589         longchs aa;
590
591         if (G.heads && G.sectors && G.cylindersize) {
592                 aa.s = 1 + sno % G.sectors;
593                 aa.h = (sno / G.sectors) % G.heads;
594                 aa.c = sno / G.cylindersize;
595                 return aa;
596         } else {
597                 return zero_longchs;
598         }
599 }
600
601 //static unsigned long
602 //longchs_to_ulong (longchs aa, struct geometry G) {
603 //    return (aa.c*G.cylindersize + aa.h*G.sectors + aa.s - 1);
604 //}
605
606 static chs ulong_to_chs(unsigned long sno, struct geometry G)
607 {
608         return longchs_to_chs(ulong_to_longchs(sno, G), G);
609 }
610
611 //static unsigned long
612 //chs_to_ulong (chs a, struct geometry G) {
613 //    return longchs_to_ulong(chs_to_longchs(a), G);
614 //}
615
616 static int is_equal_chs(chs a, chs b)
617 {
618         return (a.h == b.h && a.s == b.s && a.c == b.c);
619 }
620
621 static int chs_ok(chs a, char *v, char *w)
622 {
623         longchs aa = chs_to_longchs(a);
624         int ret = 1;
625
626         if (is_equal_chs(a, zero_chs))
627                 return 1;
628         if (B.heads && aa.h >= B.heads) {
629                 warn("%s of partition %s has impossible value for head: "
630                          "%ld (should be in 0-%ld)\n", w, v, aa.h, B.heads - 1);
631                 ret = 0;
632         }
633         if (B.sectors && (aa.s == 0 || aa.s > B.sectors)) {
634                 warn("%s of partition %s has impossible value for sector: "
635                          "%ld (should be in 1-%ld)\n", w, v, aa.s, B.sectors);
636                 ret = 0;
637         }
638         if (B.cylinders && aa.c >= B.cylinders) {
639                 warn("%s of partition %s has impossible value for cylinders: "
640                          "%ld (should be in 0-%ld)\n", w, v, aa.c, B.cylinders - 1);
641                 ret = 0;
642         }
643         return ret;
644 }
645
646 /*
647  *  D. About system Ids
648  */
649
650 #define EMPTY_PARTITION         0
651 #define EXTENDED_PARTITION      5
652 #define WIN98_EXTENDED          0x0f
653 #define DM6_AUX1PARTITION       0x51
654 #define DM6_AUX3PARTITION       0x53
655 #define DM6_PARTITION           0x54
656 #define EZD_PARTITION           0x55
657 #define LINUX_SWAP              0x82
658 #define LINUX_NATIVE            0x83
659 #define LINUX_EXTENDED          0x85
660 #define BSD_PARTITION           0xa5
661
662 /* List of partition types now in i386_sys_types.c */
663
664 static const char *sysname(unsigned char type)
665 {
666         struct systypes *s;
667
668         for (s = i386_sys_types; s->name; s++)
669                 if (s->type == type)
670                         return s->name;
671         return "Unknown";
672 }
673
674 static void list_types(void)
675 {
676         struct systypes *s;
677
678         printf("Id  Name\n\n");
679         for (s = i386_sys_types; s->name; s++)
680                 printf("%2x  %s\n", s->type, s->name);
681 }
682
683 static int is_extended(unsigned char type)
684 {
685         return (type == EXTENDED_PARTITION
686                         || type == LINUX_EXTENDED || type == WIN98_EXTENDED);
687 }
688
689 static int is_bsd(unsigned char type)
690 {
691         return (type == BSD_PARTITION);
692 }
693
694 /*
695  *  E. About partitions
696  */
697
698 /* MS/DOS partition */
699
700 struct partition {
701         unsigned char bootable;         /* 0 or 0x80 */
702         chs begin_chs;
703         unsigned char sys_type;
704         chs end_chs;
705         unsigned int start_sect;        /* starting sector counting from 0 */
706         unsigned int nr_sects;          /* nr of sectors in partition */
707 };
708
709 /* Unfortunately, partitions are not aligned, and non-Intel machines
710    are unhappy with non-aligned integers. So, we need a copy by hand. */
711 static int copy_to_int(unsigned char *cp)
712 {
713         unsigned int m;
714
715         m = *cp++;
716         m += (*cp++ << 8);
717         m += (*cp++ << 16);
718         m += (*cp++ << 24);
719         return m;
720 }
721
722 static void copy_from_int(int m, char *cp)
723 {
724         *cp++ = (m & 0xff);
725         m >>= 8;
726         *cp++ = (m & 0xff);
727         m >>= 8;
728         *cp++ = (m & 0xff);
729         m >>= 8;
730         *cp++ = (m & 0xff);
731 }
732
733 static void copy_to_part(char *cp, struct partition *p)
734 {
735         p->bootable = *cp++;
736         p->begin_chs.h = *cp++;
737         p->begin_chs.s = *cp++;
738         p->begin_chs.c = *cp++;
739         p->sys_type = *cp++;
740         p->end_chs.h = *cp++;
741         p->end_chs.s = *cp++;
742         p->end_chs.c = *cp++;
743         p->start_sect = copy_to_int(cp);
744         p->nr_sects = copy_to_int(cp + 4);
745 }
746
747 static void copy_from_part(struct partition *p, char *cp)
748 {
749         *cp++ = p->bootable;
750         *cp++ = p->begin_chs.h;
751         *cp++ = p->begin_chs.s;
752         *cp++ = p->begin_chs.c;
753         *cp++ = p->sys_type;
754         *cp++ = p->end_chs.h;
755         *cp++ = p->end_chs.s;
756         *cp++ = p->end_chs.c;
757         copy_from_int(p->start_sect, cp);
758         copy_from_int(p->nr_sects, cp + 4);
759 }
760
761 /* Roughly speaking, Linux doesn't use any of the above fields except
762    for partition type, start sector and number of sectors. (However,
763    see also linux/drivers/scsi/fdomain.c.)
764    The only way partition type is used (in the kernel) is the comparison
765    for equality with EXTENDED_PARTITION (and these Disk Manager types). */
766
767 struct part_desc {
768         unsigned long start;
769         unsigned long size;
770         unsigned long sector, offset;   /* disk location of this info */
771         struct partition p;
772         struct part_desc *ep;           /* extended partition containing this one */
773         int ptype;
774 #define DOS_TYPE        0
775 #define BSD_TYPE        1
776 } zero_part_desc;
777
778 struct part_desc *outer_extended_partition(struct part_desc *p)
779 {
780         while (p->ep)
781                 p = p->ep;
782         return p;
783 }
784
785 static int is_parent(struct part_desc *pp, struct part_desc *p)
786 {
787         while (p) {
788                 if (pp == p)
789                         return 1;
790                 p = p->ep;
791         }
792         return 0;
793 }
794
795 struct disk_desc {
796         struct part_desc partitions[128];
797         int partno;
798 } oldp, newp;
799
800 /* determine where on the disk this information goes */
801 static void add_sector_and_offset(struct disk_desc *z)
802 {
803         int pno;
804         struct part_desc *p;
805
806         for (pno = 0; pno < z->partno; pno++) {
807                 p = &(z->partitions[pno]);
808                 p->offset = 0x1be + (pno % 4) * sizeof(struct partition);
809
810                 p->sector = (p->ep ? p->ep->start : 0);
811         }
812 }
813
814 /* tell the kernel to reread the partition tables */
815 static int reread_ioctl(int fd)
816 {
817         if (ioctl(fd, BLKRRPART)) {
818                 perror("BLKRRPART");
819                 return -1;
820         }
821         return 0;
822 }
823
824 static int is_blockdev(int fd)
825 {
826         struct stat statbuf;
827
828         return (fstat(fd, &statbuf) == 0 && S_ISBLK(statbuf.st_mode));
829 }
830
831 /* reread after writing */
832 static void reread_disk_partition(char *dev, int fd)
833 {
834         printf("Re-reading the partition table ...\n");
835         fflush(stdout);
836         sync();
837         sleep(3);                                       /* superfluous since 1.3.20 */
838
839         if (reread_ioctl(fd) && is_blockdev(fd))
840                 printf("The command to re-read the partition table failed\n"
841                            "Reboot your system now, before using mkfs\n");
842
843         if (close(fd)) {
844                 perror(dev);
845                 printf("Error closing %s\n", dev);
846         }
847         printf("\n");
848 }
849
850 /* find Linux name of this partition, assuming that it will have a name */
851 static int index_to_linux(int pno, struct disk_desc *z)
852 {
853         int i, ct = 1;
854         struct part_desc *p = &(z->partitions[0]);
855
856         for (i = 0; i < pno; i++, p++)
857                 if (i < 4 || (p->size > 0 && !is_extended(p->p.sys_type)))
858                         ct++;
859         return ct;
860 }
861
862 static int linux_to_index(int lpno, struct disk_desc *z)
863 {
864         int i, ct = 0;
865         struct part_desc *p = &(z->partitions[0]);
866
867         for (i = 0; i < z->partno && ct < lpno; i++, p++)
868                 if ((i < 4 || (p->size > 0 && !is_extended(p->p.sys_type)))
869                         && ++ct == lpno)
870                         return i;
871         return -1;
872 }
873
874 static int asc_to_index(char *pnam, struct disk_desc *z)
875 {
876         int pnum, pno;
877
878         if (*pnam == '#') {
879                 pno = atoi(pnam + 1);
880         } else {
881                 pnum = atoi(pnam);
882                 pno = linux_to_index(pnum, z);
883         }
884         if (!(pno >= 0 && pno < z->partno))
885                 fatalError("%s: no such partition\n", pnam);
886         return pno;
887 }
888
889 /*
890  * List partitions - in terms of sectors, blocks or cylinders
891  */
892 #define F_SECTOR   1
893 #define F_BLOCK    2
894 #define F_CYLINDER 3
895 #define F_MEGABYTE 4
896
897 static int default_format = F_MEGABYTE;
898 static int specified_format = 0;
899 static int show_extended = 0;
900 static int one_only = 0;
901 static int one_only_pno;
902 static int increment = 0;
903
904 static void set_format(char c)
905 {
906         switch (c) {
907         default:
908                 printf("unrecognized format - using sectors\n");
909         case 'S':
910                 specified_format = F_SECTOR;
911                 break;
912         case 'B':
913                 specified_format = F_BLOCK;
914                 break;
915         case 'C':
916                 specified_format = F_CYLINDER;
917                 break;
918         case 'M':
919                 specified_format = F_MEGABYTE;
920                 break;
921         }
922 }
923
924 static unsigned long unitsize(int format)
925 {
926         default_format = (B.cylindersize ? F_CYLINDER : F_MEGABYTE);
927         if (!format && !(format = specified_format))
928                 format = default_format;
929
930         switch (format) {
931         default:
932         case F_CYLINDER:
933                 if (B.cylindersize)
934                         return B.cylindersize;
935         case F_SECTOR:
936                 return 1;
937         case F_BLOCK:
938                 return 2;
939         case F_MEGABYTE:
940                 return 2048;
941         }
942 }
943
944 static unsigned long get_disksize(int format)
945 {
946         unsigned long cs = B.cylinders;
947
948         if (cs && leave_last)
949                 cs--;
950         return (cs * B.cylindersize) / unitsize(format);
951 }
952
953 static void out_partition_header(char *dev, int format, struct geometry G)
954 {
955         if (dump) {
956                 printf("# partition table of %s\n", dev);
957                 printf("unit: sectors\n\n");
958                 return;
959         }
960
961         default_format = (G.cylindersize ? F_CYLINDER : F_MEGABYTE);
962         if (!format && !(format = specified_format))
963                 format = default_format;
964
965         switch (format) {
966         default:
967                 printf("unimplemented format - using %s\n",
968                            G.cylindersize ? "cylinders" : "sectors");
969         case F_CYLINDER:
970                 if (G.cylindersize) {
971                         printf("Units = cylinders of %lu bytes, blocks of 1024 bytes"
972                                    ", counting from %d\n\n",
973                                    G.cylindersize << 9, increment);
974                         printf
975                                 ("   Device Boot Start     End   #cyls   #blocks   Id  System\n");
976                         break;
977                 }
978                 /* fall through */
979         case F_SECTOR:
980                 printf("Units = sectors of 512 bytes, counting from %d\n\n",
981                            increment);
982                 printf
983                         ("   Device Boot    Start       End  #sectors  Id  System\n");
984                 break;
985         case F_BLOCK:
986                 printf("Units = blocks of 1024 bytes, counting from %d\n\n",
987                            increment);
988                 printf
989                         ("   Device Boot   Start       End   #blocks   Id  System\n");
990                 break;
991         case F_MEGABYTE:
992                 printf("Units = megabytes of 1048576 bytes, blocks of 1024 bytes"
993                            ", counting from %d\n\n", increment);
994                 printf
995                         ("   Device Boot Start   End     MB   #blocks   Id  System\n");
996                 break;
997         }
998 }
999
1000 static void
1001 out_rounddown(int width, unsigned long n, unsigned long unit, int inc)
1002 {
1003         printf("%*lu", width, inc + n / unit);
1004         if (unit != 1)
1005                 putchar((n % unit) ? '+' : ' ');
1006         putchar(' ');
1007 }
1008
1009 static void
1010 out_roundup(int width, unsigned long n, unsigned long unit, int inc)
1011 {
1012         if (n == (unsigned long) (-1))
1013                 printf("%*s", width, "-");
1014         else
1015                 printf("%*lu", width, inc + n / unit);
1016         if (unit != 1)
1017                 putchar(((n + 1) % unit) ? '-' : ' ');
1018         putchar(' ');
1019 }
1020
1021 static void
1022 out_roundup_size(int width, unsigned long n, unsigned long unit)
1023 {
1024         printf("%*lu", width, (n + unit - 1) / unit);
1025         if (unit != 1)
1026                 putchar((n % unit) ? '-' : ' ');
1027         putchar(' ');
1028 }
1029
1030 static int get_fdisk_geometry(struct part_desc *p)
1031 {
1032         chs b = p->p.end_chs;
1033         longchs bb = chs_to_longchs(b);
1034
1035         F.heads = bb.h + 1;
1036         F.sectors = bb.s;
1037         F.cylindersize = F.heads * F.sectors;
1038         return (F.sectors != B.sectors || F.heads != B.heads);
1039 }
1040
1041 static void
1042 out_partition(char *dev, int format, struct part_desc *p,
1043                           struct disk_desc *z, struct geometry G)
1044 {
1045         unsigned long start, end, size;
1046         int pno, lpno;
1047
1048         if (!format && !(format = specified_format))
1049                 format = default_format;
1050
1051         pno = p - &(z->partitions[0]);  /* our index */
1052         lpno = index_to_linux(pno, z);  /* name of next one that has a name */
1053         if (pno == linux_to_index(lpno, z))     /* was that us? */
1054                 printf("%8s%-2u", dev, lpno);   /* yes */
1055         else if (show_extended)
1056                 printf("    -     ");
1057         else
1058                 return;
1059         putchar(dump ? ':' : ' ');
1060
1061         start = p->start;
1062         end = p->start + p->size - 1;
1063         size = p->size;
1064
1065         if (dump) {
1066                 printf(" start=%9lu", start);
1067                 printf(", size=%8lu", size);
1068                 if (p->ptype == DOS_TYPE) {
1069                         printf(", Id=%2x", p->p.sys_type);
1070                         if (p->p.bootable == 0x80)
1071                                 printf(", bootable");
1072                 }
1073                 printf("\n");
1074                 return;
1075         }
1076
1077         if (p->ptype != DOS_TYPE || p->p.bootable == 0)
1078                 printf("   ");
1079         else if (p->p.bootable == 0x80)
1080                 printf(" * ");
1081         else
1082                 printf(" ? ");                  /* garbage */
1083
1084         switch (format) {
1085         case F_CYLINDER:
1086                 if (G.cylindersize) {
1087                         out_rounddown(6, start, G.cylindersize, increment);
1088                         out_roundup(6, end, G.cylindersize, increment);
1089                         out_roundup_size(6, size, G.cylindersize);
1090                         out_rounddown(8, size, 2, 0);
1091                         break;
1092                 }
1093                 /* fall through */
1094         default:
1095         case F_SECTOR:
1096                 out_rounddown(9, start, 1, increment);
1097                 out_roundup(9, end, 1, increment);
1098                 out_rounddown(9, size, 1, 0);
1099                 break;
1100         case F_BLOCK:
1101 #if 0
1102                 printf("%8lu,%3lu ",
1103                            p->sector / 2, ((p->sector & 1) ? 512 : 0) + p->offset);
1104 #endif
1105                 out_rounddown(8, start, 2, increment);
1106                 out_roundup(8, end, 2, increment);
1107                 out_rounddown(8, size, 2, 0);
1108                 break;
1109         case F_MEGABYTE:
1110                 out_rounddown(5, start, 2048, increment);
1111                 out_roundup(5, end, 2048, increment);
1112                 out_roundup_size(5, size, 2048);
1113                 out_rounddown(8, size, 2, 0);
1114                 break;
1115         }
1116         if (p->ptype == DOS_TYPE) {
1117                 printf(" %2x  %s\n", p->p.sys_type, sysname(p->p.sys_type));
1118         } else {
1119                 printf("\n");
1120         }
1121
1122         /* Is chs as we expect? */
1123         if (!quiet && p->ptype == DOS_TYPE) {
1124                 chs a, b;
1125                 longchs aa, bb;
1126
1127                 a = (size ? ulong_to_chs(start, G) : zero_chs);
1128                 b = p->p.begin_chs;
1129                 aa = chs_to_longchs(a);
1130                 bb = chs_to_longchs(b);
1131                 if (a.s && !is_equal_chs(a, b))
1132                         printf
1133                                 ("\t\tstart: (c,h,s) expected (%ld,%ld,%ld) found (%ld,%ld,%ld)\n",
1134                                  aa.c, aa.h, aa.s, bb.c, bb.h, bb.s);
1135                 a = (size ? ulong_to_chs(end, G) : zero_chs);
1136                 b = p->p.end_chs;
1137                 aa = chs_to_longchs(a);
1138                 bb = chs_to_longchs(b);
1139                 if (a.s && !is_equal_chs(a, b))
1140                         printf
1141                                 ("\t\tend: (c,h,s) expected (%ld,%ld,%ld) found (%ld,%ld,%ld)\n",
1142                                  aa.c, aa.h, aa.s, bb.c, bb.h, bb.s);
1143                 if (G.cylinders && G.cylinders < 1024 && bb.c > G.cylinders)
1144                         printf
1145                                 ("partition ends on cylinder %ld, beyond the end of the disk\n",
1146                                  bb.c);
1147         }
1148 }
1149
1150 static void out_partitions(char *dev, struct disk_desc *z)
1151 {
1152         struct part_desc *p;
1153         int pno, format = 0;
1154
1155         if (z->partno == 0)
1156                 printf("No partitions found\n");
1157         else {
1158                 for (pno = 0; pno < z->partno; pno++) {
1159                         p = &(z->partitions[pno]);
1160                         if (p->size != 0 && p->p.sys_type != 0) {
1161                                 if (get_fdisk_geometry(p))
1162                                         printf
1163                                                 ("Warning: The first partition looks like it was made\n"
1164                                                  "  for C/H/S=*/%ld/%ld (instead of %ld/%ld/%ld).\n"
1165                                                  "For this listing I'll assume that geometry.\n",
1166                                                  F.heads, F.sectors, B.cylinders, B.heads,
1167                                                  B.sectors);
1168                                 break;
1169                         }
1170                 }
1171                 out_partition_header(dev, format, F);
1172                 for (pno = 0; pno < z->partno; pno++) {
1173                         out_partition(dev, format, &(z->partitions[pno]), z, F);
1174                         if (show_extended && pno % 4 == 3)
1175                                 printf("\n");
1176                 }
1177         }
1178 }
1179
1180 static int disj(struct part_desc *p, struct part_desc *q)
1181 {
1182         return ((p->start + p->size <= q->start)
1183                         || (is_extended(p->p.sys_type)
1184                                 && q->start + q->size <= p->start + p->size));
1185 }
1186
1187 static char *pnumber(struct part_desc *p, struct disk_desc *z)
1188 {
1189         static char buf[20];
1190         int this, next;
1191         struct part_desc *p0 = &(z->partitions[0]);
1192
1193         this = index_to_linux(p - p0, z);
1194         next = index_to_linux(p - p0 + 1, z);
1195
1196         if (next > this)
1197                 sprintf(buf, "%d", this);
1198         else
1199                 sprintf(buf, "[%d]", this);
1200         return buf;
1201 }
1202
1203 static int partitions_ok(struct disk_desc *z)
1204 {
1205         struct part_desc *partitions = &(z->partitions[0]), *p, *q;
1206         int partno = z->partno;
1207
1208 #define PNO(p) pnumber(p, z)
1209
1210         /* Have at least 4 partitions been defined? */
1211         if (partno < 4) {
1212                 if (!partno)
1213                         fatalError("no partition table present.\n");
1214                 else
1215                         fatalError("strange, only %d partitions defined.\n", partno);
1216                 return 0;
1217         }
1218
1219         /* Are the partitions of size 0 marked empty?
1220            And do they have start = 0? And bootable = 0? */
1221         for (p = partitions; p - partitions < partno; p++)
1222                 if (p->size == 0) {
1223                         if (p->p.sys_type != EMPTY_PARTITION)
1224                                 warn
1225                                         ("Warning: partition %s has size 0 but is not marked Empty\n",
1226                                          PNO(p));
1227                         else if (p->p.bootable != 0)
1228                                 warn("Warning: partition %s has size 0 and is bootable\n",
1229                                          PNO(p));
1230                         else if (p->p.start_sect != 0)
1231                                 warn
1232                                         ("Warning: partition %s has size 0 and nonzero start\n",
1233                                          PNO(p));
1234                         /* all this is probably harmless, no error return */
1235                 }
1236
1237         /* Are the logical partitions contained in their extended partitions? */
1238         for (p = partitions + 4; p < partitions + partno; p++)
1239                 if (p->ptype == DOS_TYPE)
1240                         if (p->size && !is_extended(p->p.sys_type)) {
1241                                 q = p->ep;
1242                                 if (p->start < q->start
1243                                         || p->start + p->size > q->start + q->size) {
1244                                         warn("Warning: partition %s ", PNO(p));
1245                                         warn("is not contained in partition %s\n", PNO(q));
1246                                         return 0;
1247                                 }
1248                         }
1249
1250         /* Are the data partitions mutually disjoint? */
1251         for (p = partitions; p < partitions + partno; p++)
1252                 if (p->size && !is_extended(p->p.sys_type))
1253                         for (q = p + 1; q < partitions + partno; q++)
1254                                 if (q->size && !is_extended(q->p.sys_type))
1255                                         if (!((p->start > q->start) ? disj(q, p) : disj(p, q))) {
1256                                                 warn("Warning: partitions %s ", PNO(p));
1257                                                 warn("and %s overlap\n", PNO(q));
1258                                                 return 0;
1259                                         }
1260
1261         /* Are the data partitions and the extended partition
1262            table sectors disjoint? */
1263         for (p = partitions; p < partitions + partno; p++)
1264                 if (p->size && !is_extended(p->p.sys_type))
1265                         for (q = partitions; q < partitions + partno; q++)
1266                                 if (is_extended(q->p.sys_type))
1267                                         if (p->start <= q->start
1268                                                 && p->start + p->size > q->start) {
1269                                                 warn("Warning: partition %s contains part of ",
1270                                                          PNO(p));
1271                                                 warn("the partition table (sector %lu),\n",
1272                                                          q->start);
1273                                                 warn("and will destroy it when filled\n");
1274                                                 return 0;
1275                                         }
1276
1277         /* Do they start past zero and end before end-of-disk? */
1278         {
1279                 unsigned long ds = get_disksize(F_SECTOR);
1280
1281                 for (p = partitions; p < partitions + partno; p++)
1282                         if (p->size) {
1283                                 if (p->start == 0) {
1284                                         warn("Warning: partition %s starts at sector 0\n",
1285                                                  PNO(p));
1286                                         return 0;
1287                                 }
1288                                 if (p->size && p->start + p->size > ds) {
1289                                         warn
1290                                                 ("Warning: partition %s extends past end of disk\n",
1291                                                  PNO(p));
1292                                         return 0;
1293                                 }
1294                         }
1295         }
1296
1297         /* At most one chain of DOS extended partitions ? */
1298         /* It seems that the OS/2 fdisk has the additional requirement
1299            that the extended partition must be the fourth one */
1300         {
1301                 int ect = 0;
1302
1303                 for (p = partitions; p < partitions + 4; p++)
1304                         if (p->p.sys_type == EXTENDED_PARTITION)
1305                                 ect++;
1306                 if (ect > 1 && !Linux) {
1307                         warn
1308                                 ("Among the primary partitions, at most one can be extended\n");
1309                         warn(" (although this is not a problem under Linux)\n");
1310                         return 0;
1311                 }
1312         }
1313
1314         /*
1315          * Do all partitions start at a cylinder boundary ?
1316          * (this is not required for Linux)
1317          * The first partition starts after MBR.
1318          * Logical partitions start slightly after the containing extended partn.
1319          */
1320         if (B.cylindersize) {
1321                 for (p = partitions; p < partitions + partno; p++)
1322                         if (p->size) {
1323                                 if (p->start % B.cylindersize != 0
1324                                         && (!p->ep
1325                                                 || p->start / B.cylindersize !=
1326                                                 p->ep->start / B.cylindersize)
1327                                         && (p->p.start_sect >= B.cylindersize)) {
1328                                         warn("Warning: partition %s does not start "
1329                                                  "at a cylinder boundary\n", PNO(p));
1330                                         if (!Linux)
1331                                                 return 0;
1332                                 }
1333                                 if ((p->start + p->size) % B.cylindersize) {
1334                                         warn("Warning: partition %s does not end "
1335                                                  "at a cylinder boundary\n", PNO(p));
1336                                         if (!Linux)
1337                                                 return 0;
1338                                 }
1339                         }
1340         }
1341
1342         /* Usually, one can boot only from primary partitions. */
1343         /* In fact, from a unique one only. */
1344         /* do not warn about bootable extended partitions -
1345            often LILO is there */
1346         {
1347                 int pno = -1;
1348
1349                 for (p = partitions; p < partitions + partno; p++)
1350                         if (p->p.bootable) {
1351                                 if (pno == -1)
1352                                         pno = p - partitions;
1353                                 else if (p - partitions < 4) {
1354                                         warn
1355                                                 ("Warning: more than one primary partition is marked "
1356                                                  "bootable (active)\n"
1357                                                  "This does not matter for LILO, but the DOS MBR will "
1358                                                  "not boot this disk.\n");
1359                                         break;
1360                                 }
1361                                 if (p - partitions >= 4) {
1362                                         warn
1363                                                 ("Warning: usually one can boot from primary partitions "
1364                                                  "only\nLILO disregards the `bootable' flag.\n");
1365                                         break;
1366                                 }
1367                         }
1368                 if (pno == -1 || pno >= 4)
1369                         warn
1370                                 ("Warning: no primary partition is marked bootable (active)\n"
1371                                  "This does not matter for LILO, but the DOS MBR will "
1372                                  "not boot this disk.\n");
1373         }
1374
1375         /* Is chs as we expect? */
1376         for (p = partitions; p < partitions + partno; p++)
1377                 if (p->ptype == DOS_TYPE) {
1378                         chs a, b;
1379                         longchs aa, bb;
1380
1381                         a = p->size ? ulong_to_chs(p->start, B) : zero_chs;
1382                         b = p->p.begin_chs;
1383                         aa = chs_to_longchs(a);
1384                         bb = chs_to_longchs(b);
1385                         if (!chs_ok(b, PNO(p), "start"))
1386                                 return 0;
1387                         if (a.s && !is_equal_chs(a, b))
1388                                 warn
1389                                         ("partition %s: start: (c,h,s) expected (%ld,%ld,%ld) found (%ld,%ld,%ld)\n",
1390                                          PNO(p), aa.c, aa.h, aa.s, bb.c, bb.h, bb.s);
1391                         a =
1392                                 p->size ? ulong_to_chs(p->start + p->size - 1,
1393                                                                            B) : zero_chs;
1394                         b = p->p.end_chs;
1395                         aa = chs_to_longchs(a);
1396                         bb = chs_to_longchs(b);
1397                         if (!chs_ok(b, PNO(p), "end"))
1398                                 return 0;
1399                         if (a.s && !is_equal_chs(a, b))
1400                                 warn
1401                                         ("partition %s: end: (c,h,s) expected (%ld,%ld,%ld) found (%ld,%ld,%ld)\n",
1402                                          PNO(p), aa.c, aa.h, aa.s, bb.c, bb.h, bb.s);
1403                         if (B.cylinders && B.cylinders < 1024 && bb.c > B.cylinders)
1404                                 warn
1405                                         ("partition %s ends on cylinder %ld, beyond the end of the disk\n",
1406                                          PNO(p), bb.c);
1407                 }
1408
1409         return 1;
1410
1411 #undef PNO
1412 }
1413
1414 static void
1415 extended_partition(char *dev, int fd, struct part_desc *ep,
1416                                    struct disk_desc *z)
1417 {
1418         char *cp;
1419         struct sector *s;
1420         unsigned long start, here, next;
1421         int i, moretodo = 1;
1422         struct partition p;
1423         struct part_desc *partitions = &(z->partitions[0]);
1424         int pno = z->partno;
1425
1426         here = start = ep->start;
1427
1428         while (moretodo) {
1429                 moretodo = 0;
1430
1431                 if (!(s = get_sector(dev, fd, here)))
1432                         break;
1433
1434                 if (!msdos_signature(s))
1435                         break;
1436
1437                 cp = s->data + 0x1be;
1438
1439                 if (pno + 4 >= SIZE(z->partitions)) {
1440                         printf("too many partitions - ignoring those past nr (%d)\n",
1441                                    pno - 1);
1442                         break;
1443                 }
1444
1445                 next = 0;
1446
1447                 for (i = 0; i < 4; i++, cp += sizeof(struct partition)) {
1448                         partitions[pno].sector = here;
1449                         partitions[pno].offset = cp - s->data;
1450                         partitions[pno].ep = ep;
1451                         copy_to_part(cp, &p);
1452                         if (is_extended(p.sys_type)) {
1453                                 partitions[pno].start = start + p.start_sect;
1454                                 if (next)
1455                                         printf("tree of partitions?\n");
1456                                 else
1457                                         next = partitions[pno].start;   /* follow `upper' branch */
1458                                 moretodo = 1;
1459                         } else {
1460                                 partitions[pno].start = here + p.start_sect;
1461                         }
1462                         partitions[pno].size = p.nr_sects;
1463                         partitions[pno].ptype = DOS_TYPE;
1464                         partitions[pno].p = p;
1465                         pno++;
1466                 }
1467                 here = next;
1468         }
1469
1470         z->partno = pno;
1471 }
1472
1473 #define BSD_DISKMAGIC   (0x82564557UL)
1474 #define BSD_MAXPARTITIONS       8
1475 #define BSD_FS_UNUSED           0
1476 typedef unsigned char u8;
1477 typedef unsigned short u16;
1478 typedef unsigned int u32;
1479 struct bsd_disklabel {
1480         u32 d_magic;
1481         char d_junk1[4];
1482         char d_typename[16];
1483         char d_packname[16];
1484         char d_junk2[92];
1485         u32 d_magic2;
1486         char d_junk3[2];
1487         u16 d_npartitions;                      /* number of partitions in following */
1488         char d_junk4[8];
1489         struct bsd_partition {          /* the partition table */
1490                 u32 p_size;                             /* number of sectors in partition */
1491                 u32 p_offset;                   /* starting sector */
1492                 u32 p_fsize;                    /* filesystem basic fragment size */
1493                 u8 p_fstype;                    /* filesystem type, see below */
1494                 u8 p_frag;                              /* filesystem fragments per block */
1495                 u16 p_cpg;                              /* filesystem cylinders per group */
1496         } d_partitions[BSD_MAXPARTITIONS];      /* actually may be more */
1497 };
1498
1499 static void
1500 bsd_partition(char *dev, int fd, struct part_desc *ep, struct disk_desc *z)
1501 {
1502         struct bsd_disklabel *l;
1503         struct bsd_partition *bp, *bp0;
1504         unsigned long start = ep->start;
1505         struct sector *s;
1506         struct part_desc *partitions = &(z->partitions[0]);
1507         int pno = z->partno;
1508
1509         if (!(s = get_sector(dev, fd, start + 1)))
1510                 return;
1511         l = (struct bsd_disklabel *) (s->data);
1512         if (l->d_magic != BSD_DISKMAGIC)
1513                 return;
1514
1515         bp = bp0 = &l->d_partitions[0];
1516         while (bp - bp0 <= BSD_MAXPARTITIONS) {
1517                 if (pno + 1 >= SIZE(z->partitions)) {
1518                         printf("too many partitions - ignoring those "
1519                                    "past nr (%d)\n", pno - 1);
1520                         break;
1521                 }
1522                 if (bp->p_fstype != BSD_FS_UNUSED) {
1523                         partitions[pno].start = bp->p_offset;
1524                         partitions[pno].size = bp->p_size;
1525                         partitions[pno].sector = start + 1;
1526                         partitions[pno].offset = (char *) bp - (char *) bp0;
1527                         partitions[pno].ep = 0;
1528                         partitions[pno].ptype = BSD_TYPE;
1529                         pno++;
1530                 }
1531                 bp++;
1532         }
1533         z->partno = pno;
1534 }
1535
1536 static int
1537 msdos_partition(char *dev, int fd, unsigned long start,
1538                                 struct disk_desc *z)
1539 {
1540         int i;
1541         char *cp;
1542         struct partition pt;
1543         struct sector *s;
1544         struct part_desc *partitions = &(z->partitions[0]);
1545         int pno = z->partno;
1546
1547         if (!(s = get_sector(dev, fd, start)))
1548                 return 0;
1549
1550         if (!msdos_signature(s))
1551                 return 0;
1552
1553         cp = s->data + 0x1be;
1554         copy_to_part(cp, &pt);
1555
1556         /* If I am not mistaken, recent kernels will hide this from us,
1557            so we will never actually see traces of a Disk Manager */
1558         if (pt.sys_type == DM6_PARTITION
1559                 || pt.sys_type == EZD_PARTITION
1560                 || pt.sys_type == DM6_AUX1PARTITION
1561                 || pt.sys_type == DM6_AUX3PARTITION) {
1562                 printf("detected Disk Manager - unable to handle that\n");
1563                 return 0;
1564         }
1565         {
1566                 unsigned int sig = *(unsigned short *) (s->data + 2);
1567
1568                 if (sig <= 0x1ae
1569                         && *(unsigned short *) (s->data + sig) == 0x55aa
1570                         && (1 & *(unsigned char *) (s->data + sig + 2))) {
1571                         printf("DM6 signature found - giving up\n");
1572                         return 0;
1573                 }
1574         }
1575
1576         for (pno = 0; pno < 4; pno++, cp += sizeof(struct partition)) {
1577                 partitions[pno].sector = start;
1578                 partitions[pno].offset = cp - s->data;
1579                 copy_to_part(cp, &pt);
1580                 partitions[pno].start = start + pt.start_sect;
1581                 partitions[pno].size = pt.nr_sects;
1582                 partitions[pno].ep = 0;
1583                 partitions[pno].p = pt;
1584         }
1585
1586         z->partno = pno;
1587
1588         for (i = 0; i < 4; i++) {
1589                 if (is_extended(partitions[i].p.sys_type)) {
1590                         if (!partitions[i].size) {
1591                                 printf("strange..., an extended partition of size 0?\n");
1592                                 continue;
1593                         }
1594                         extended_partition(dev, fd, &partitions[i], z);
1595                 }
1596                 if (is_bsd(partitions[i].p.sys_type)) {
1597                         if (!partitions[i].size) {
1598                                 printf("strange..., a BSD partition of size 0?\n");
1599                                 continue;
1600                         }
1601                         bsd_partition(dev, fd, &partitions[i], z);
1602                 }
1603         }
1604         return 1;
1605 }
1606
1607 static int
1608 osf_partition(char *dev, int fd, unsigned long start, struct disk_desc *z)
1609 {
1610         return 0;
1611 }
1612
1613 static int
1614 sun_partition(char *dev, int fd, unsigned long start, struct disk_desc *z)
1615 {
1616         return 0;
1617 }
1618
1619 static int
1620 amiga_partition(char *dev, int fd, unsigned long start,
1621                                 struct disk_desc *z)
1622 {
1623         return 0;
1624 }
1625
1626 static void get_partitions(char *dev, int fd, struct disk_desc *z)
1627 {
1628         z->partno = 0;
1629
1630         if (!msdos_partition(dev, fd, 0, z)
1631                 && !osf_partition(dev, fd, 0, z)
1632                 && !sun_partition(dev, fd, 0, z)
1633                 && !amiga_partition(dev, fd, 0, z)) {
1634                 printf(" %s: unrecognized partition\n", dev);
1635                 return;
1636         }
1637 }
1638
1639 static int write_partitions(char *dev, int fd, struct disk_desc *z)
1640 {
1641         struct sector *s;
1642         struct part_desc *partitions = &(z->partitions[0]), *p;
1643         int pno = z->partno;
1644
1645         if (no_write) {
1646                 printf("-n flag was given: Nothing changed\n");
1647                 exit(0);
1648         }
1649
1650         for (p = partitions; p < partitions + pno; p++) {
1651                 s = get_sector(dev, fd, p->sector);
1652                 if (!s)
1653                         return 0;
1654                 s->to_be_written = 1;
1655                 copy_from_part(&(p->p), s->data + p->offset);
1656                 *(unsigned short *) (&(s->data[0x1fe])) = 0xaa55;
1657         }
1658         if (save_sector_file) {
1659                 if (!save_sectors(dev, fd)) {
1660                         fatalError("Failed saving the old sectors - aborting\n");
1661                         return 0;
1662                 }
1663         }
1664         if (!write_sectors(dev, fd)) {
1665                 errorMsg("Failed writing the partition on %s\n", dev);
1666                 return 0;
1667         }
1668         return 1;
1669 }
1670
1671 /*
1672  *  F. The standard input
1673  */
1674
1675 /*
1676  * Input format:
1677  * <start> <size> <type> <bootable> <c,h,s> <c,h,s>
1678  * Fields are separated by whitespace or comma or semicolon possibly
1679  * followed by whitespace; initial and trailing whitespace is ignored.
1680  * Numbers can be octal, decimal or hexadecimal, decimal is default
1681  * The <c,h,s> parts can (and probably should) be omitted.
1682  * Bootable is specified as [*|-], with as default not-bootable.
1683  * Type is given in hex, without the 0x prefix, or is [E|S|L|X], where
1684  * L (LINUX_NATIVE (83)) is the default, S is LINUX_SWAP (82), and E
1685  * is EXTENDED_PARTITION (5), X is LINUX_EXTENDED (85).
1686  * The default value of start is the first nonassigned sector/cylinder/...
1687  * The default value of size is as much as possible (until next
1688  * partition or end-of-disk).
1689  * .: end of chain of extended partitions.
1690  *
1691  * On interactive input an empty line means: all defaults.
1692  * Otherwise empty lines are ignored.
1693  */
1694
1695 static int eof, eob;
1696
1697 struct dumpfld {
1698         int fldno;
1699         char *fldname;
1700         int is_bool;
1701 } dumpflds[] = {
1702         {
1703         0, "start", 0}, {
1704         1, "size", 0}, {
1705         2, "Id", 0}, {
1706         3, "bootable", 1}, {
1707         4, "bh", 0}, {
1708         5, "bs", 0}, {
1709         6, "bc", 0}, {
1710         7, "eh", 0}, {
1711         8, "es", 0}, {
1712         9, "ec", 0}
1713 };
1714
1715 /*
1716  * Read a line, split it into fields
1717  *
1718  * (some primitive handwork, but a more elaborate parser seems
1719  *  unnecessary)
1720  */
1721 #define RD_EOF (-1)
1722 #define RD_CMD (-2)
1723
1724 static int
1725 read_stdin(unsigned char **fields, unsigned char *line, int fieldssize,
1726                    int linesize)
1727 {
1728         unsigned char *lp, *ip;
1729         int c, fno;
1730
1731         /* boolean true and empty string at start */
1732         line[0] = '*';
1733         line[1] = 0;
1734         for (fno = 0; fno < fieldssize; fno++)
1735                 fields[fno] = line + 1;
1736         fno = 0;
1737
1738         /* read a line from stdin */
1739         lp = fgets(line + 2, linesize, stdin);
1740         if (lp == NULL) {
1741                 eof = 1;
1742                 return RD_EOF;
1743         }
1744         if (!(lp = index(lp, '\n')))
1745                 fatalError("long or incomplete input line - quitting\n");
1746         *lp = 0;
1747
1748         /* remove comments, if any */
1749         if ((lp = index(line + 2, '#')) != 0)
1750                 *lp = 0;
1751
1752         /* recognize a few commands - to be expanded */
1753         if (!strcmp(line + 2, "unit: sectors")) {
1754                 specified_format = F_SECTOR;
1755                 return RD_CMD;
1756         }
1757
1758         /* dump style? - then bad input is fatal */
1759         if ((ip = index(line + 2, ':')) != 0) {
1760                 struct dumpfld *d;
1761
1762           nxtfld:
1763                 ip++;
1764                 while (isspace(*ip))
1765                         ip++;
1766                 if (*ip == 0)
1767                         return fno;
1768                 for (d = dumpflds; d - dumpflds < SIZE(dumpflds); d++) {
1769                         if (!strncmp(ip, d->fldname, strlen(d->fldname))) {
1770                                 ip += strlen(d->fldname);
1771                                 while (isspace(*ip))
1772                                         ip++;
1773                                 if (d->is_bool)
1774                                         fields[d->fldno] = line;
1775                                 else if (*ip == '=') {
1776                                         while (isspace(*++ip));
1777                                         fields[d->fldno] = ip;
1778                                         while (isalnum(*ip))    /* 0x07FF */
1779                                                 ip++;
1780                                 } else
1781                                         fatalError("input error: `=' expected after %s field\n",
1782                                                   d->fldname);
1783                                 if (fno <= d->fldno)
1784                                         fno = d->fldno + 1;
1785                                 if (*ip == 0)
1786                                         return fno;
1787                                 if (*ip != ',' && *ip != ';')
1788                                         fatalError
1789                                                 ("input error: unexpected character %c after %s field\n",
1790                                                  *ip, d->fldname);
1791                                 *ip = 0;
1792                                 goto nxtfld;
1793                         }
1794                 }
1795                 fatalError("unrecognized input: %s\n", ip);
1796         }
1797
1798         /* split line into fields */
1799         lp = ip = line + 2;
1800         fields[fno++] = lp;
1801         while ((c = *ip++) != 0) {
1802                 if (!lp[-1] && (c == '\t' || c == ' '));
1803                 else if (c == '\t' || c == ' ' || c == ',' || c == ';') {
1804                         *lp++ = 0;
1805                         if (fno < fieldssize)
1806                                 fields[fno++] = lp;
1807                         continue;
1808                 } else
1809                         *lp++ = c;
1810         }
1811
1812         if (lp == fields[fno - 1])
1813                 fno--;
1814         return fno;
1815 }
1816
1817 /* read a number, use default if absent */
1818 static int get_ul(char *u, unsigned long *up, unsigned long def, int base)
1819 {
1820         char *nu;
1821
1822         if (*u) {
1823                 errno = 0;
1824                 *up = strtoul(u, &nu, base);
1825                 if (errno == ERANGE) {
1826                         printf("number too big\n");
1827                         return -1;
1828                 }
1829                 if (*nu) {
1830                         printf("trailing junk after number\n");
1831                         return -1;
1832                 }
1833         } else
1834                 *up = def;
1835         return 0;
1836 }
1837
1838 /* There are two common ways to structure extended partitions:
1839    as nested boxes, and as a chain. Sometimes the partitions
1840    must be given in order. Sometimes all logical partitions
1841    must lie inside the outermost extended partition.
1842 NESTED: every partition is contained in the surrounding partitions
1843    and is disjoint from all others.
1844 CHAINED: every data partition is contained in the surrounding partitions
1845    and disjoint from all others, but extended partitions may lie outside
1846    (insofar as allowed by all_logicals_inside_outermost_extended).
1847 ONESECTOR: all data partitions are mutually disjoint; extended partitions
1848    each use one sector only (except perhaps for the outermost one).
1849 */
1850 static int partitions_in_order = 0;
1851 static int all_logicals_inside_outermost_extended = 1;
1852 static enum { NESTED, CHAINED, ONESECTOR } boxes = NESTED;
1853
1854 /* find the default value for <start> - assuming entire units */
1855 static unsigned long
1856 first_free(int pno, int is_extended, struct part_desc *ep, int format,
1857                    unsigned long mid, struct disk_desc *z)
1858 {
1859         unsigned long ff, fff;
1860         unsigned long unit = unitsize(format);
1861         struct part_desc *partitions = &(z->partitions[0]), *pp = 0;
1862
1863         /* if containing ep undefined, look at its container */
1864         if (ep && ep->p.sys_type == EMPTY_PARTITION)
1865                 ep = ep->ep;
1866
1867         if (ep) {
1868                 if (boxes == NESTED || (boxes == CHAINED && !is_extended))
1869                         pp = ep;
1870                 else if (all_logicals_inside_outermost_extended)
1871                         pp = outer_extended_partition(ep);
1872         }
1873 #if 0
1874         ff = pp ? (pp->start + unit - 1) / unit : 0;
1875 #else
1876         /* rounding up wastes almost an entire cylinder - round down
1877            and leave it to compute_start_sect() to fix the difference */
1878         ff = pp ? pp->start / unit : 0;
1879 #endif
1880         /* MBR and 1st sector of an extended partition are never free */
1881         if (unit == 1)
1882                 ff++;
1883
1884   again:
1885         for (pp = partitions; pp < partitions + pno; pp++) {
1886                 if (!is_parent(pp, ep) && pp->size > 0) {
1887                         if ((partitions_in_order || pp->start / unit <= ff
1888                                  || (mid && pp->start / unit <= mid))
1889                                 && (fff = (pp->start + pp->size + unit - 1) / unit) > ff) {
1890                                 ff = fff;
1891                                 goto again;
1892                         }
1893                 }
1894         }
1895
1896         return ff;
1897 }
1898
1899 /* find the default value for <size> - assuming entire units */
1900 static unsigned long
1901 max_length(int pno, int is_extended, struct part_desc *ep, int format,
1902                    unsigned long start, struct disk_desc *z)
1903 {
1904         unsigned long fu;
1905         unsigned long unit = unitsize(format);
1906         struct part_desc *partitions = &(z->partitions[0]), *pp = 0;
1907
1908         /* if containing ep undefined, look at its container */
1909         if (ep && ep->p.sys_type == EMPTY_PARTITION)
1910                 ep = ep->ep;
1911
1912         if (ep) {
1913                 if (boxes == NESTED || (boxes == CHAINED && !is_extended))
1914                         pp = ep;
1915                 else if (all_logicals_inside_outermost_extended)
1916                         pp = outer_extended_partition(ep);
1917         }
1918         fu = pp ? (pp->start + pp->size) / unit : get_disksize(format);
1919
1920         for (pp = partitions; pp < partitions + pno; pp++)
1921                 if (!is_parent(pp, ep) && pp->size > 0
1922                         && pp->start / unit >= start && pp->start / unit < fu)
1923                         fu = pp->start / unit;
1924
1925         return (fu > start) ? fu - start : 0;
1926 }
1927
1928 /* compute starting sector of a partition inside an extended one */
1929 /* ep is 0 or points to surrounding extended partition */
1930 static int compute_start_sect(struct part_desc *p, struct part_desc *ep)
1931 {
1932         unsigned long base;
1933         int inc = (DOS && B.sectors) ? B.sectors : 1;
1934         int delta;
1935
1936         if (ep && p->start + p->size >= ep->start + 1)
1937                 delta = p->start - ep->start - inc;
1938         else if (p->start == 0 && p->size > 0)
1939                 delta = -inc;
1940         else
1941                 delta = 0;
1942         if (delta < 0) {
1943                 p->start -= delta;
1944                 p->size += delta;
1945                 if (is_extended(p->p.sys_type) && boxes == ONESECTOR)
1946                         p->size = inc;
1947                 else if ((int) (p->size) <= 0) {
1948                         warn("no room for partition descriptor\n");
1949                         return 0;
1950                 }
1951         }
1952         base = (!ep ? 0
1953                         : (is_extended(p->p.sys_type) ?
1954                            outer_extended_partition(ep) : ep)->start);
1955         p->ep = ep;
1956         if (p->p.sys_type == EMPTY_PARTITION && p->size == 0) {
1957                 p->p.start_sect = 0;
1958                 p->p.begin_chs = zero_chs;
1959                 p->p.end_chs = zero_chs;
1960         } else {
1961                 p->p.start_sect = p->start - base;
1962                 p->p.begin_chs = ulong_to_chs(p->start, B);
1963                 p->p.end_chs = ulong_to_chs(p->start + p->size - 1, B);
1964         }
1965         p->p.nr_sects = p->size;
1966         return 1;
1967 }
1968
1969 /* build the extended partition surrounding a given logical partition */
1970 static int
1971 build_surrounding_extended(struct part_desc *p, struct part_desc *ep,
1972                                                    struct disk_desc *z)
1973 {
1974         int inc = (DOS && B.sectors) ? B.sectors : 1;
1975         int format = F_SECTOR;
1976         struct part_desc *p0 = &(z->partitions[0]), *eep = ep->ep;
1977
1978         if (boxes == NESTED) {
1979                 ep->start = first_free(ep - p0, 1, eep, format, p->start, z);
1980                 ep->size = max_length(ep - p0, 1, eep, format, ep->start, z);
1981                 if (ep->start > p->start
1982                         || ep->start + ep->size < p->start + p->size) {
1983                         warn("cannot build surrounding extended partition\n");
1984                         return 0;
1985                 }
1986         } else {
1987                 ep->start = p->start;
1988                 if (boxes == CHAINED)
1989                         ep->size = p->size;
1990                 else
1991                         ep->size = inc;
1992         }
1993
1994         ep->p.nr_sects = ep->size;
1995         ep->p.bootable = 0;
1996         ep->p.sys_type = EXTENDED_PARTITION;
1997         if (!compute_start_sect(ep, eep) || !compute_start_sect(p, ep)) {
1998                 ep->p.sys_type = EMPTY_PARTITION;
1999                 ep->size = 0;
2000                 return 0;
2001         }
2002
2003         return 1;
2004 }
2005
2006 static int
2007 read_line(int pno, struct part_desc *ep, char *dev, int interactive,
2008                   struct disk_desc *z)
2009 {
2010         unsigned char line[1000];
2011         unsigned char *fields[11];
2012         int fno, pct = pno % 4;
2013         struct part_desc p, *orig;
2014         unsigned long ff, ff1, ul, ml, ml1, def;
2015         int format, lpno, is_extd;
2016
2017         if (eof || eob)
2018                 return -1;
2019
2020         lpno = index_to_linux(pno, z);
2021
2022         if (interactive) {
2023                 if (pct == 0 && (show_extended || pno == 0))
2024                         warn("\n");
2025                 warn("%8s%d: ", dev, lpno);
2026         }
2027
2028         /* read input line - skip blank lines when reading from a file */
2029         do {
2030                 fno = read_stdin(fields, line, SIZE(fields), SIZE(line));
2031         } while (fno == RD_CMD || (fno == 0 && !interactive));
2032         if (fno == RD_EOF) {
2033                 return -1;
2034         } else if (fno > 10 && *(fields[10]) != 0) {
2035                 printf("too many input fields\n");
2036                 return 0;
2037         }
2038
2039         if (fno == 1 && !strcmp(fields[0], ".")) {
2040                 eob = 1;
2041                 return -1;
2042         }
2043
2044         /* use specified format, but round to cylinders if F_MEGABYTE specified */
2045         format = 0;
2046         if (B.cylindersize && specified_format == F_MEGABYTE)
2047                 format = F_CYLINDER;
2048
2049         orig = (one_only ? &(oldp.partitions[pno]) : 0);
2050
2051         p = zero_part_desc;
2052         p.ep = ep;
2053
2054         /* first read the type - we need to know whether it is extended */
2055         /* stop reading when input blank (defaults) and all is full */
2056         is_extd = 0;
2057         if (fno == 0) {                         /* empty line */
2058                 if (orig && is_extended(orig->p.sys_type))
2059                         is_extd = 1;
2060                 ff = first_free(pno, is_extd, ep, format, 0, z);
2061                 ml = max_length(pno, is_extd, ep, format, ff, z);
2062                 if (ml == 0 && is_extd == 0) {
2063                         is_extd = 1;
2064                         ff = first_free(pno, is_extd, ep, format, 0, z);
2065                         ml = max_length(pno, is_extd, ep, format, ff, z);
2066                 }
2067                 if (ml == 0 && pno >= 4) {
2068                         /* no free blocks left - don't read any further */
2069                         warn("No room for more\n");
2070                         return -1;
2071                 }
2072         }
2073         if (fno < 3 || !*(fields[2]))
2074                 ul = orig ? orig->p.sys_type :
2075                         (is_extd || (pno > 3 && pct == 1 && show_extended))
2076                         ? EXTENDED_PARTITION : LINUX_NATIVE;
2077         else if (!strcmp(fields[2], "L"))
2078                 ul = LINUX_NATIVE;
2079         else if (!strcmp(fields[2], "S"))
2080                 ul = LINUX_SWAP;
2081         else if (!strcmp(fields[2], "E"))
2082                 ul = EXTENDED_PARTITION;
2083         else if (!strcmp(fields[2], "X"))
2084                 ul = LINUX_EXTENDED;
2085         else if (get_ul(fields[2], &ul, LINUX_NATIVE, 16))
2086                 return 0;
2087         if (ul > 255) {
2088                 warn("Illegal type\n");
2089                 return 0;
2090         }
2091         p.p.sys_type = ul;
2092         is_extd = is_extended(ul);
2093
2094         /* find start */
2095         ff = first_free(pno, is_extd, ep, format, 0, z);
2096         ff1 = ff * unitsize(format);
2097         def = orig ? orig->start : (pno > 4 && pct > 1) ? 0 : ff1;
2098         if (fno < 1 || !*(fields[0]))
2099                 p.start = def;
2100         else {
2101                 if (get_ul(fields[0], &ul, def / unitsize(0), 0))
2102                         return 0;
2103                 p.start = ul * unitsize(0);
2104                 p.start -= (p.start % unitsize(format));
2105         }
2106
2107         /* find length */
2108         ml =
2109                 max_length(pno, is_extd, ep, format, p.start / unitsize(format),
2110                                    z);
2111         ml1 = ml * unitsize(format);
2112         def = orig ? orig->size : (pno > 4 && pct > 1) ? 0 : ml1;
2113         if (fno < 2 || !*(fields[1]))
2114                 p.size = def;
2115         else {
2116                 if (get_ul(fields[1], &ul, def / unitsize(0), 0))
2117                         return 0;
2118                 p.size = ul * unitsize(0) + unitsize(format) - 1;
2119                 p.size -= (p.size % unitsize(format));
2120         }
2121         if (p.size > ml1) {
2122                 warn("Warning: exceeds max allowable size (%lu)\n",
2123                          ml1 / unitsize(0));
2124                 if (!force)
2125                         return 0;
2126         }
2127         if (p.size == 0 && pno >= 4 && (fno < 2 || !*(fields[1]))) {
2128                 warn("Warning: empty partition\n");
2129                 if (!force)
2130                         return 0;
2131         }
2132         p.p.nr_sects = p.size;
2133
2134         if (p.size == 0 && !orig) {
2135                 if (fno < 1 || !*(fields[0]))
2136                         p.start = 0;
2137                 if (fno < 3 || !*(fields[2]))
2138                         p.p.sys_type = EMPTY_PARTITION;
2139         }
2140
2141         if (p.start < ff1 && p.size > 0) {
2142                 warn("Warning: bad partition start (earliest %lu)\n",
2143                          (ff1 + unitsize(0) - 1) / unitsize(0));
2144                 if (!force)
2145                         return 0;
2146         }
2147
2148         if (fno < 4 || !*(fields[3]))
2149                 ul = (orig ? orig->p.bootable : 0);
2150         else if (!strcmp(fields[3], "-"))
2151                 ul = 0;
2152         else if (!strcmp(fields[3], "*") || !strcmp(fields[3], "+"))
2153                 ul = 0x80;
2154         else {
2155                 warn("unrecognized bootable flag - choose - or *\n");
2156                 return 0;
2157         }
2158         p.p.bootable = ul;
2159
2160         if (ep && ep->p.sys_type == EMPTY_PARTITION) {
2161                 if (!build_surrounding_extended(&p, ep, z))
2162                         return 0;
2163         } else if (!compute_start_sect(&p, ep))
2164                 return 0;
2165
2166         {
2167                 longchs aa = chs_to_longchs(p.p.begin_chs), bb;
2168
2169                 if (fno < 5) {
2170                         bb = aa;
2171                 } else if (fno < 7) {
2172                         warn("partial c,h,s specification?\n");
2173                         return 0;
2174                 } else if (get_ul(fields[4], &bb.c, aa.c, 0) ||
2175                                    get_ul(fields[5], &bb.h, aa.h, 0) ||
2176                                    get_ul(fields[6], &bb.s, aa.s, 0))
2177                         return 0;
2178                 p.p.begin_chs = longchs_to_chs(bb, B);
2179         }
2180         {
2181                 longchs aa = chs_to_longchs(p.p.end_chs), bb;
2182
2183                 if (fno < 8) {
2184                         bb = aa;
2185                 } else if (fno < 10) {
2186                         warn("partial c,h,s specification?\n");
2187                         return 0;
2188                 } else if (get_ul(fields[7], &bb.c, aa.c, 0) ||
2189                                    get_ul(fields[8], &bb.h, aa.h, 0) ||
2190                                    get_ul(fields[9], &bb.s, aa.s, 0))
2191                         return 0;
2192                 p.p.end_chs = longchs_to_chs(bb, B);
2193         }
2194
2195         if (pno > 3 && p.size && show_extended
2196                 && p.p.sys_type != EMPTY_PARTITION
2197                 && (is_extended(p.p.sys_type) != (pct == 1))) {
2198                 warn("Extended partition not where expected\n");
2199                 if (!force)
2200                         return 0;
2201         }
2202
2203         z->partitions[pno] = p;
2204         if (pno >= z->partno)
2205                 z->partno += 4;                 /* reqd for out_partition() */
2206
2207         if (interactive)
2208                 out_partition(dev, 0, &(z->partitions[pno]), z, B);
2209
2210         return 1;
2211 }
2212
2213 /* ep either points to the extended partition to contain this one,
2214    or to the empty partition that may become extended or is 0 */
2215 static int
2216 read_partition(char *dev, int interactive, int pno, struct part_desc *ep,
2217                            struct disk_desc *z)
2218 {
2219         struct part_desc *p = &(z->partitions[pno]);
2220         int i;
2221
2222         if (one_only) {
2223                 *p = oldp.partitions[pno];
2224                 if (one_only_pno != pno)
2225                         goto ret;
2226         } else if (!show_extended && pno > 4 && pno % 4)
2227                 goto ret;
2228
2229         while (!(i = read_line(pno, ep, dev, interactive, z)))
2230                 if (!interactive)
2231                         fatalError("bad input\n");
2232         if (i < 0) {
2233                 p->ep = ep;
2234                 return 0;
2235         }
2236
2237   ret:
2238         p->ep = ep;
2239         if (pno >= z->partno)
2240                 z->partno += 4;
2241         return 1;
2242 }
2243
2244 static void
2245 read_partition_chain(char *dev, int interactive, struct part_desc *ep,
2246                                          struct disk_desc *z)
2247 {
2248         int i, base;
2249
2250         eob = 0;
2251         while (1) {
2252                 base = z->partno;
2253                 if (base + 4 > SIZE(z->partitions)) {
2254                         printf("too many partitions\n");
2255                         break;
2256                 }
2257                 for (i = 0; i < 4; i++)
2258                         if (!read_partition(dev, interactive, base + i, ep, z))
2259                                 return;
2260                 for (i = 0; i < 4; i++) {
2261                         ep = &(z->partitions[base + i]);
2262                         if (is_extended(ep->p.sys_type) && ep->size)
2263                                 break;
2264                 }
2265                 if (i == 4) {
2266                         /* nothing found - maybe an empty partition is going
2267                            to be extended */
2268                         if (one_only || show_extended)
2269                                 break;
2270                         ep = &(z->partitions[base + 1]);
2271                         if (ep->size || ep->p.sys_type != EMPTY_PARTITION)
2272                                 break;
2273                 }
2274         }
2275 }
2276
2277 static void read_input(char *dev, int interactive, struct disk_desc *z)
2278 {
2279         int i;
2280         struct part_desc *partitions = &(z->partitions[0]), *ep;
2281
2282         for (i = 0; i < SIZE(z->partitions); i++)
2283                 partitions[i] = zero_part_desc;
2284         z->partno = 0;
2285
2286         if (interactive)
2287                 warn
2288                         ("Input in the following format; absent fields get a default value.\n"
2289                          "<start> <size> <type [E,S,L,X,hex]> <bootable [-,*]> <c,h,s> <c,h,s>\n"
2290                          "Usually you only need to specify <start> and <size> (and perhaps <type>).\n");
2291         eof = 0;
2292
2293         for (i = 0; i < 4; i++)
2294                 read_partition(dev, interactive, i, 0, z);
2295         for (i = 0; i < 4; i++) {
2296                 ep = partitions + i;
2297                 if (is_extended(ep->p.sys_type) && ep->size)
2298                         read_partition_chain(dev, interactive, ep, z);
2299         }
2300         add_sector_and_offset(z);
2301 }
2302
2303 /*
2304  *  G. The command line
2305  */
2306
2307 static void version(void)
2308 {
2309         printf("%s %s %s (aeb@cwi.nl, %s)\n", PROGNAME, "version", VERSION,
2310                    DATE);
2311 }
2312
2313 static char short_opts[] = "cdfgilnqsu:vx?1A::C:DH:I:LN:O:RS:TU::V";
2314
2315 #define PRINT_ID 0400
2316 #define CHANGE_ID 01000
2317
2318 static const struct option long_opts[] = {
2319         {"change-id", no_argument, NULL, 'c' + CHANGE_ID},
2320         {"print-id", no_argument, NULL, 'c' + PRINT_ID},
2321         {"id", no_argument, NULL, 'c'},
2322         {"dump", no_argument, NULL, 'd'},
2323         {"force", no_argument, NULL, 'f'},
2324         {"show-geometry", no_argument, NULL, 'g'},
2325         {"increment", no_argument, NULL, 'i'},
2326         {"list", no_argument, NULL, 'l'},
2327         {"quiet", no_argument, NULL, 'q'},
2328         {"show-size", no_argument, NULL, 's'},
2329         {"unit", required_argument, NULL, 'u'},
2330         {"version", no_argument, NULL, 'v'},
2331         {"show-extended", no_argument, NULL, 'x'},
2332         {"help", no_argument, NULL, '?'},
2333         {"one-only", no_argument, NULL, '1'},
2334         {"cylinders", required_argument, NULL, 'C'},
2335         {"heads", required_argument, NULL, 'H'},
2336         {"sectors", required_argument, NULL, 'S'},
2337         {"activate", optional_argument, NULL, 'A'},
2338         {"DOS", no_argument, NULL, 'D'},
2339         {"Linux", no_argument, NULL, 'L'},
2340         {"re-read", no_argument, NULL, 'R'},
2341         {"list-types", no_argument, NULL, 'T'},
2342         {"unhide", optional_argument, NULL, 'U'},
2343         {"no-reread", no_argument, NULL, 160},
2344         {"IBM", no_argument, NULL, 161},
2345         {"leave-last", no_argument, NULL, 161},
2346 /* undocumented flags - not all completely implemented */
2347         {"in-order", no_argument, NULL, 128},
2348         {"not-in-order", no_argument, NULL, 129},
2349         {"inside-outer", no_argument, NULL, 130},
2350         {"not-inside-outer", no_argument, NULL, 131},
2351         {"nested", no_argument, NULL, 132},
2352         {"chained", no_argument, NULL, 133},
2353         {"onesector", no_argument, NULL, 134},
2354         {NULL, 0, NULL, 0}
2355 };
2356
2357 /* default devices to list */
2358 static struct devd {
2359         char *pref, *letters;
2360 } defdevs[] = {
2361         {
2362         "hd", "abcdefgh"}, {
2363         "sd", "abcde"}, {
2364         "xd", "ab"}, {
2365         "ed", "abcd"}
2366 };
2367
2368 static int is_ide_cdrom(char *device)
2369 {
2370         /* No device was given explicitly, and we are trying some
2371            likely things.  But opening /dev/hdc may produce errors like
2372            "hdc: tray open or drive not ready"
2373            if it happens to be a CD-ROM drive. So try to be careful.
2374            This only works since 2.1.73. */
2375
2376         FILE *procf;
2377         char buf[100];
2378         struct stat statbuf;
2379
2380         sprintf(buf, "/proc/ide/%s/media", device + 5);
2381         procf = fopen(buf, "r");
2382         if (procf != NULL && fgets(buf, sizeof(buf), procf))
2383                 return !strncmp(buf, "cdrom", 5);
2384
2385         /* Now when this proc file does not exist, skip the
2386            device when it is read-only. */
2387         if (stat(device, &statbuf) == 0)
2388                 return (statbuf.st_mode & 0222) == 0;
2389
2390         return 0;
2391 }
2392
2393 static void do_list(char *dev, int silent);
2394 static void do_size(char *dev, int silent);
2395 static void do_geom(char *dev, int silent);
2396 static void do_fdisk(char *dev);
2397 static void do_reread(char *dev);
2398 static void do_change_id(char *dev, char *part, char *id);
2399 static void do_unhide(char **av, int ac, char *arg);
2400 static void do_activate(char **av, int ac, char *arg);
2401
2402 static int total_size;
2403
2404 extern int sfdisk_main(int argc, char **argv)
2405 {
2406         int c;
2407         char *dev;
2408         int opt_size = 0;
2409         int opt_out_geom = 0;
2410         int opt_reread = 0;
2411         int activate = 0;
2412         int do_id = 0;
2413         int unhide = 0;
2414         char *activatearg = 0;
2415         char *unhidearg = 0;
2416
2417         if (argc < 1)
2418                 usage(sfdisk_usage);
2419
2420         while ((c = getopt_long(argc, argv, short_opts, long_opts, NULL)) !=
2421                    -1) {
2422                 switch (c) {
2423                 case 'f':
2424                         force = 1;
2425                         break;                          /* does not imply quiet */
2426                 case 'g':
2427                         opt_out_geom = 1;
2428                         break;
2429                 case 'i':
2430                         increment = 1;
2431                         break;
2432                 case 'c':
2433                 case 'c' + PRINT_ID:
2434                 case 'c' + CHANGE_ID:
2435                         do_id = c;
2436                         break;
2437                 case 'd':
2438                         dump = 1;                       /* fall through */
2439                 case 'l':
2440                         opt_list = 1;
2441                         break;
2442                 case 'n':
2443                         no_write = 1;
2444                         break;
2445                 case 'q':
2446                         quiet = 1;
2447                         break;
2448                 case 's':
2449                         opt_size = 1;
2450                         break;
2451                 case 'u':
2452                         set_format(*optarg);
2453                         break;
2454                 case 'v':
2455                         version();
2456                         exit(0);
2457                 case 'x':
2458                         show_extended = 1;
2459                         break;
2460                 case 'A':
2461                         activatearg = optarg;
2462                         activate = 1;
2463                         break;
2464                 case 'C':
2465                         U.cylinders = atoi(optarg);
2466                         break;
2467                 case 'D':
2468                         DOS = 1;
2469                         break;
2470                 case 'H':
2471                         U.heads = atoi(optarg);
2472                         break;
2473                 case 'L':
2474                         Linux = 1;
2475                         break;
2476                 case 'N':
2477                         one_only = atoi(optarg);
2478                         break;
2479                 case 'I':
2480                         restore_sector_file = optarg;
2481                         break;
2482                 case 'O':
2483                         save_sector_file = optarg;
2484                         break;
2485                 case 'R':
2486                         opt_reread = 1;
2487                         break;
2488                 case 'S':
2489                         U.sectors = atoi(optarg);
2490                         break;
2491                 case 'T':
2492                         list_types();
2493                         exit(0);
2494                 case 'U':
2495                         unhidearg = optarg;
2496                         unhide = 1;
2497                         break;
2498                 case 'V':
2499                         verify = 1;
2500                         break;
2501                 case '?':
2502                 default:
2503                         usage(sfdisk_usage);
2504
2505                         /* undocumented flags */
2506                 case 128:
2507                         partitions_in_order = 1;
2508                         break;
2509                 case 129:
2510                         partitions_in_order = 0;
2511                         break;
2512                 case 130:
2513                         all_logicals_inside_outermost_extended = 1;
2514                         break;
2515                 case 131:
2516                         all_logicals_inside_outermost_extended = 0;
2517                         break;
2518                 case 132:
2519                         boxes = NESTED;
2520                         break;
2521                 case 133:
2522                         boxes = CHAINED;
2523                         break;
2524                 case 134:
2525                         boxes = ONESECTOR;
2526                         break;
2527
2528                         /* more flags */
2529                 case 160:
2530                         no_reread = 1;
2531                         break;
2532                 case 161:
2533                         leave_last = 1;
2534                         break;
2535                 }
2536         }
2537
2538         if (optind == argc && (opt_list || opt_out_geom || opt_size || verify)) {
2539                 struct devd *dp;
2540                 char *lp;
2541                 char device[10];
2542
2543                 total_size = 0;
2544
2545                 for (dp = defdevs; dp - defdevs < SIZE(defdevs); dp++) {
2546                         lp = dp->letters;
2547                         while (*lp) {
2548                                 sprintf(device, "/dev/%s%c", dp->pref, *lp++);
2549                                 if (!strcmp(dp->pref, "hd") && is_ide_cdrom(device))
2550                                         continue;
2551                                 if (opt_out_geom)
2552                                         do_geom(device, 1);
2553                                 if (opt_size)
2554                                         do_size(device, 1);
2555                                 if (opt_list || verify)
2556                                         do_list(device, 1);
2557                         }
2558                 }
2559
2560                 if (opt_size)
2561                         printf("total: %d blocks\n", total_size);
2562
2563                 exit(exit_status);
2564         }
2565
2566         if (optind == argc)
2567                 usage(sfdisk_usage);
2568
2569         if (opt_list || opt_out_geom || opt_size || verify) {
2570                 while (optind < argc) {
2571                         if (opt_out_geom)
2572                                 do_geom(argv[optind], 0);
2573                         if (opt_size)
2574                                 do_size(argv[optind], 0);
2575                         if (opt_list || verify)
2576                                 do_list(argv[optind], 0);
2577                         optind++;
2578                 }
2579                 exit(exit_status);
2580         }
2581
2582         if (activate) {
2583                 do_activate(argv + optind, argc - optind, activatearg);
2584                 exit(exit_status);
2585         }
2586         if (unhide) {
2587                 do_unhide(argv + optind, argc - optind, unhidearg);
2588                 exit(exit_status);
2589         }
2590         if (do_id) {
2591                 if ((do_id & PRINT_ID) != 0 && optind != argc - 2)
2592                         fatalError("usage: sfdisk --print-id device partition-number\n");
2593                 else if ((do_id & CHANGE_ID) != 0 && optind != argc - 3)
2594                         fatalError
2595                                 ("usage: sfdisk --change-id device partition-number Id\n");
2596                 else if (optind != argc - 3 && optind != argc - 2)
2597                         fatalError("usage: sfdisk --id device partition-number [Id]\n");
2598                 do_change_id(argv[optind], argv[optind + 1],
2599                                          (optind == argc - 2) ? 0 : argv[optind + 2]);
2600                 exit(exit_status);
2601         }
2602
2603         if (optind != argc - 1)
2604                 fatalError("can specify only one device (except with -l or -s)\n");
2605         dev = argv[optind];
2606
2607         if (opt_reread)
2608                 do_reread(dev);
2609         else if (restore_sector_file)
2610                 restore_sectors(dev);
2611         else
2612                 do_fdisk(dev);
2613
2614         return (TRUE);
2615 }
2616
2617 /*
2618  *  H. Listing the current situation
2619  */
2620
2621 static int my_open(char *dev, int rw, int silent)
2622 {
2623         int fd, mode;
2624
2625         mode = (rw ? O_RDWR : O_RDONLY);
2626         fd = open(dev, mode);
2627         if (fd < 0 && !silent) {
2628                 perror(dev);
2629                 fatalError("cannot open %s %s\n", dev,
2630                           rw ? "read-write" : "for reading");
2631         }
2632         return fd;
2633 }
2634
2635 static void do_list(char *dev, int silent)
2636 {
2637         int fd;
2638         struct disk_desc *z;
2639
2640         fd = my_open(dev, 0, silent);
2641         if (fd < 0)
2642                 return;
2643
2644         z = &oldp;
2645
2646         free_sectors();
2647         get_cylindersize(dev, fd, dump ? 1 : opt_list ? 0 : 1);
2648         get_partitions(dev, fd, z);
2649
2650         if (opt_list)
2651                 out_partitions(dev, z);
2652
2653         if (verify) {
2654                 if (partitions_ok(z))
2655                         warn("%s: OK\n", dev);
2656                 else
2657                         exit_status = 1;
2658         }
2659 }
2660
2661 static void do_geom(char *dev, int silent)
2662 {
2663         int fd;
2664         struct hd_geometry g;
2665
2666         fd = my_open(dev, 0, silent);
2667         if (fd < 0)
2668                 return;
2669
2670         /* get_cylindersize(dev, fd, silent); */
2671         if (!ioctl(fd, HDIO_GETGEO, &g))
2672                 printf("%s: %d cylinders, %d heads, %d sectors/track\n",
2673                            dev, g.cylinders, g.heads, g.sectors);
2674         else
2675                 printf("%s: unknown geometry\n", dev);
2676 }
2677
2678 /* for compatibility with earlier fdisk: provide option -s */
2679 static void do_size(char *dev, int silent)
2680 {
2681         int fd;
2682         long size;
2683
2684         fd = my_open(dev, 0, silent);
2685         if (fd < 0)
2686                 return;
2687
2688         if (ioctl(fd, BLKGETSIZE, &size)) {
2689                 if (!silent) {
2690                         perror(dev);
2691                         fatalError("BLKGETSIZE ioctl failed for %s\n", dev);
2692                 }
2693                 return;
2694         }
2695
2696         size /= 2;                                      /* convert sectors to blocks */
2697
2698         /* a CDROM drive without mounted CD yields MAXINT */
2699         if (silent && size == ((1 << 30) - 1))
2700                 return;
2701
2702         if (silent)
2703                 printf("%s: %9ld\n", dev, size);
2704         else
2705                 printf("%ld\n", size);
2706
2707         total_size += size;
2708 }
2709
2710 /*
2711  * Activate: usually one wants to have a single primary partition
2712  * to be active. OS/2 fdisk makes non-bootable logical partitions
2713  * active - I don't know what that means to OS/2 Boot Manager.
2714  *
2715  * Call: activate /dev/hda 2 5 7        make these partitions active
2716  *                                      and the remaining ones inactive
2717  * Or:   sfdisk -A /dev/hda 2 5 7
2718  *
2719  * If only a single partition must be active, one may also use the form
2720  *       sfdisk -A2 /dev/hda
2721  *
2722  * With "activate /dev/hda" or "sfdisk -A /dev/hda" the active partitions
2723  * are listed but not changed. To get zero active partitions, use
2724  * "activate /dev/hda none" or "sfdisk -A /dev/hda none".
2725  * Use something like `echo ",,,*" | sfdisk -N2 /dev/hda' to only make
2726  * /dev/hda2 active, without changing other partitions.
2727  *
2728  * A warning will be given if after the change not precisely one primary
2729  * partition is active.
2730  *
2731  * The present syntax was chosen to be (somewhat) compatible with the
2732  * activate from the LILO package.
2733  */
2734 static void set_active(struct disk_desc *z, char *pnam)
2735 {
2736         int pno;
2737
2738         pno = asc_to_index(pnam, z);
2739         z->partitions[pno].p.bootable = 0x80;
2740 }
2741
2742 static void do_activate(char **av, int ac, char *arg)
2743 {
2744         char *dev = av[0];
2745         int fd;
2746         int rw, i, pno, lpno;
2747         struct disk_desc *z;
2748
2749         z = &oldp;
2750
2751         rw = (!no_write && (arg || ac > 1));
2752         fd = my_open(dev, rw, 0);
2753
2754         free_sectors();
2755         get_cylindersize(dev, fd, 1);
2756         get_partitions(dev, fd, z);
2757
2758         if (!arg && ac == 1) {
2759                 /* list active partitions */
2760                 for (pno = 0; pno < z->partno; pno++) {
2761                         if (z->partitions[pno].p.bootable) {
2762                                 lpno = index_to_linux(pno, z);
2763                                 if (pno == linux_to_index(lpno, z))
2764                                         printf("%s%d\n", dev, lpno);
2765                                 else
2766                                         printf("%s#%d\n", dev, pno);
2767                                 if (z->partitions[pno].p.bootable != 0x80)
2768                                         warn("bad active byte: 0x%x instead of 0x80\n",
2769                                                  z->partitions[pno].p.bootable);
2770                         }
2771                 }
2772         } else {
2773                 /* clear `active byte' everywhere */
2774                 for (pno = 0; pno < z->partno; pno++)
2775                         z->partitions[pno].p.bootable = 0;
2776
2777                 /* then set where desired */
2778                 if (ac == 1)
2779                         set_active(z, arg);
2780                 else
2781                         for (i = 1; i < ac; i++)
2782                                 set_active(z, av[i]);
2783
2784                 /* then write to disk */
2785                 if (write_partitions(dev, fd, z))
2786                         warn("Done\n\n");
2787                 else
2788                         exit_status = 1;
2789         }
2790         i = 0;
2791         for (pno = 0; pno < z->partno && pno < 4; pno++)
2792                 if (z->partitions[pno].p.bootable)
2793                         i++;
2794         if (i != 1)
2795                 warn
2796                         ("You have %d active primary partitions. This does not matter for LILO,\n"
2797                          "but the DOS MBR will only boot a disk with 1 active partition.\n",
2798                          i);
2799 }
2800
2801 static void set_unhidden(struct disk_desc *z, char *pnam)
2802 {
2803         int pno;
2804         unsigned char id;
2805
2806         pno = asc_to_index(pnam, z);
2807         id = z->partitions[pno].p.sys_type;
2808         if (id == 0x11 || id == 0x14 || id == 0x16 || id == 0x17)
2809                 id -= 0x10;
2810         else
2811                 fatalError("partition %s has id %x and is not hidden\n", pnam, id);
2812         z->partitions[pno].p.sys_type = id;
2813 }
2814
2815 /*
2816  * maybe remove and make part of --change-id
2817  */
2818 static void do_unhide(char **av, int ac, char *arg)
2819 {
2820         char *dev = av[0];
2821         int fd, rw, i;
2822         struct disk_desc *z;
2823
2824         z = &oldp;
2825
2826         rw = !no_write;
2827         fd = my_open(dev, rw, 0);
2828
2829         free_sectors();
2830         get_cylindersize(dev, fd, 1);
2831         get_partitions(dev, fd, z);
2832
2833         /* unhide where desired */
2834         if (ac == 1)
2835                 set_unhidden(z, arg);
2836         else
2837                 for (i = 1; i < ac; i++)
2838                         set_unhidden(z, av[i]);
2839
2840         /* then write to disk */
2841         if (write_partitions(dev, fd, z))
2842                 warn("Done\n\n");
2843         else
2844                 exit_status = 1;
2845 }
2846
2847 static void do_change_id(char *dev, char *pnam, char *id)
2848 {
2849         int fd, rw, pno;
2850         struct disk_desc *z;
2851         unsigned long i;
2852
2853         z = &oldp;
2854
2855         rw = !no_write;
2856         fd = my_open(dev, rw, 0);
2857
2858         free_sectors();
2859         get_cylindersize(dev, fd, 1);
2860         get_partitions(dev, fd, z);
2861
2862         pno = asc_to_index(pnam, z);
2863         if (id == 0) {
2864                 printf("%x\n", z->partitions[pno].p.sys_type);
2865                 return;
2866         }
2867         i = strtoul(id, NULL, 16);
2868         if (i > 255)
2869                 fatalError("Bad Id %lx\n", i);
2870         z->partitions[pno].p.sys_type = i;
2871
2872         if (write_partitions(dev, fd, z))
2873                 warn("Done\n\n");
2874         else
2875                 exit_status = 1;
2876 }
2877
2878 static void do_reread(char *dev)
2879 {
2880         int fd;
2881
2882         fd = my_open(dev, 0, 0);
2883         if (reread_ioctl(fd))
2884                 printf("This disk is currently in use.\n");
2885 }
2886
2887 /*
2888  *  I. Writing the new situation
2889  */
2890
2891 static void do_fdisk(char *dev)
2892 {
2893         int fd;
2894         int c, answer;
2895         struct stat statbuf;
2896         int interactive = isatty(0);
2897         struct disk_desc *z;
2898
2899         if (stat(dev, &statbuf) < 0) {
2900                 perror(dev);
2901                 fatalError("Fatal error: cannot find %s\n", dev);
2902         }
2903         if (!S_ISBLK(statbuf.st_mode)) {
2904                 warn("Warning: %s is not a block device\n", dev);
2905                 no_reread = 1;
2906         }
2907         fd = my_open(dev, !no_write, 0);
2908
2909         if (!no_write && !no_reread) {
2910                 warn("Checking that no-one is using this disk right now ...\n");
2911                 if (reread_ioctl(fd)) {
2912                         printf
2913                                 ("\nThis disk is currently in use - repartitioning is probably a bad idea."
2914                                  "Umount all file systems, and swapoff all swap partitions on this disk."
2915                                  "Use the --no-reread flag to suppress this check.\n");
2916                         if (!force) {
2917                                 printf("Use the --force flag to overrule all checks.\n");
2918                                 exit(1);
2919                         }
2920                 } else
2921                         warn("OK");
2922         }
2923
2924         z = &oldp;
2925
2926         free_sectors();
2927         get_cylindersize(dev, fd, 0);
2928         get_partitions(dev, fd, z);
2929
2930         printf("Old situation:\n");
2931         out_partitions(dev, z);
2932
2933         if (one_only && (one_only_pno = linux_to_index(one_only, z)) < 0)
2934                 fatalError("Partition %d does not exist, cannot change it\n", one_only);
2935
2936         z = &newp;
2937
2938         while (1) {
2939
2940                 read_input(dev, interactive, z);
2941
2942                 printf("New situation:\n");
2943                 out_partitions(dev, z);
2944
2945                 if (!partitions_ok(z) && !force) {
2946                         if (!interactive)
2947                                 fatalError("I don't like these partitions - nothing changed.\n"
2948                                           "(If you really want this, use the --force option.)\n");
2949                         else
2950                                 printf
2951                                         ("I don't like this - probably you should answer No\n");
2952                 }
2953           ask:
2954                 if (interactive) {
2955                         if (no_write)
2956                                 printf("Are you satisfied with this? [ynq] ");
2957                         else
2958                                 printf("Do you want to write this to disk? [ynq] ");
2959                         answer = c = getchar();
2960                         while (c != '\n' && c != EOF)
2961                                 c = getchar();
2962                         if (c == EOF)
2963                                 printf("\nsfdisk: premature end of input\n");
2964                         if (c == EOF || answer == 'q' || answer == 'Q') {
2965                                 fatalError("Quitting - nothing changed\n");
2966                         } else if (answer == 'n' || answer == 'N') {
2967                                 continue;
2968                         } else if (answer == 'y' || answer == 'Y') {
2969                                 break;
2970                         } else {
2971                                 printf("Please answer one of y,n,q\n");
2972                                 goto ask;
2973                         }
2974                 } else
2975                         break;
2976         }
2977
2978         if (write_partitions(dev, fd, z))
2979                 printf("Successfully wrote the new partition table\n\n");
2980         else
2981                 exit_status = 1;
2982
2983         reread_disk_partition(dev, fd);
2984
2985         warn
2986                 ("If you created or changed a DOS partition, /dev/foo7, say, then use dd(1)\n"
2987                  "to zero the first 512 bytes:  dd if=/dev/zero of=/dev/foo7 bs=512 count=1\n"
2988                  "(See fdisk(8).)\n");
2989
2990         sync();                                         /* superstition */
2991         sleep(3);
2992         exit(exit_status);
2993 }