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