"Fossies" - the Fresh Open Source Software Archive

Member "sfdisk-3.07/sfdisk.c" (17 May 1998, 75338 Bytes) of package /linux/misc/old/sfdisk-3.07.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file.

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