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