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