EXEC_PREFER_APPLETS support by Gabriel L. Somlo <somlo@cmu.edu>
[oweals/busybox.git] / util-linux / fdisk_osf.c
1 #if ENABLE_FEATURE_OSF_LABEL
2 /*
3  * Copyright (c) 1987, 1988 Regents of the University of California.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. All advertising materials mentioning features or use of this software
15  *    must display the following acknowledgment:
16  *      This product includes software developed by the University of
17  *      California, Berkeley and its contributors.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35
36 #ifndef BSD_DISKMAGIC
37 #define BSD_DISKMAGIC     ((uint32_t) 0x82564557)
38 #endif
39
40 #ifndef BSD_MAXPARTITIONS
41 #define BSD_MAXPARTITIONS 16
42 #endif
43
44 #define BSD_LINUX_BOOTDIR "/usr/ucb/mdec"
45
46 #if defined(i386) || defined(__sparc__) || defined(__arm__) \
47  || defined(__m68k__) || defined(__mips__) || defined(__s390__) \
48  || defined(__sh__) || defined(__x86_64__)
49 #define BSD_LABELSECTOR   1
50 #define BSD_LABELOFFSET   0
51 #elif defined(__alpha__) || defined(__powerpc__) || defined(__ia64__) \
52  || defined(__hppa__)
53 #define BSD_LABELSECTOR   0
54 #define BSD_LABELOFFSET   64
55 #elif defined(__s390__) || defined(__s390x__)
56 #define BSD_LABELSECTOR   1
57 #define BSD_LABELOFFSET   0
58 #else
59 #error unknown architecture
60 #endif
61
62 #define BSD_BBSIZE        8192          /* size of boot area, with label */
63 #define BSD_SBSIZE        8192          /* max size of fs superblock */
64
65 struct xbsd_disklabel {
66         uint32_t   d_magic;                /* the magic number */
67         int16_t    d_type;                 /* drive type */
68         int16_t    d_subtype;              /* controller/d_type specific */
69         char       d_typename[16];         /* type name, e.g. "eagle" */
70         char       d_packname[16];                 /* pack identifier */
71                         /* disk geometry: */
72         uint32_t   d_secsize;              /* # of bytes per sector */
73         uint32_t   d_nsectors;             /* # of data sectors per track */
74         uint32_t   d_ntracks;              /* # of tracks per cylinder */
75         uint32_t   d_ncylinders;           /* # of data cylinders per unit */
76         uint32_t   d_secpercyl;            /* # of data sectors per cylinder */
77         uint32_t   d_secperunit;           /* # of data sectors per unit */
78         /*
79          * Spares (bad sector replacements) below
80          * are not counted in d_nsectors or d_secpercyl.
81          * Spare sectors are assumed to be physical sectors
82          * which occupy space at the end of each track and/or cylinder.
83          */
84         uint16_t   d_sparespertrack;       /* # of spare sectors per track */
85         uint16_t   d_sparespercyl;         /* # of spare sectors per cylinder */
86         /*
87          * Alternate cylinders include maintenance, replacement,
88          * configuration description areas, etc.
89          */
90         uint32_t   d_acylinders;           /* # of alt. cylinders per unit */
91
92                         /* hardware characteristics: */
93         /*
94          * d_interleave, d_trackskew and d_cylskew describe perturbations
95          * in the media format used to compensate for a slow controller.
96          * Interleave is physical sector interleave, set up by the formatter
97          * or controller when formatting.  When interleaving is in use,
98          * logically adjacent sectors are not physically contiguous,
99          * but instead are separated by some number of sectors.
100          * It is specified as the ratio of physical sectors traversed
101          * per logical sector.  Thus an interleave of 1:1 implies contiguous
102          * layout, while 2:1 implies that logical sector 0 is separated
103          * by one sector from logical sector 1.
104          * d_trackskew is the offset of sector 0 on track N
105          * relative to sector 0 on track N-1 on the same cylinder.
106          * Finally, d_cylskew is the offset of sector 0 on cylinder N
107          * relative to sector 0 on cylinder N-1.
108          */
109         uint16_t   d_rpm;                  /* rotational speed */
110         uint16_t   d_interleave;           /* hardware sector interleave */
111         uint16_t   d_trackskew;            /* sector 0 skew, per track */
112         uint16_t   d_cylskew;              /* sector 0 skew, per cylinder */
113         uint32_t   d_headswitch;           /* head switch time, usec */
114         uint32_t   d_trkseek;              /* track-to-track seek, usec */
115         uint32_t   d_flags;                /* generic flags */
116 #define NDDATA 5
117         uint32_t   d_drivedata[NDDATA];    /* drive-type specific information */
118 #define NSPARE 5
119         uint32_t   d_spare[NSPARE];        /* reserved for future use */
120         uint32_t   d_magic2;               /* the magic number (again) */
121         uint16_t   d_checksum;             /* xor of data incl. partitions */
122                         /* filesystem and partition information: */
123         uint16_t   d_npartitions;          /* number of partitions in following */
124         uint32_t   d_bbsize;               /* size of boot area at sn0, bytes */
125         uint32_t   d_sbsize;               /* max size of fs superblock, bytes */
126         struct xbsd_partition    {      /* the partition table */
127                 uint32_t   p_size;         /* number of sectors in partition */
128                 uint32_t   p_offset;       /* starting sector */
129                 uint32_t   p_fsize;        /* filesystem basic fragment size */
130                 uint8_t    p_fstype;       /* filesystem type, see below */
131                 uint8_t    p_frag;         /* filesystem fragments per block */
132                 uint16_t   p_cpg;          /* filesystem cylinders per group */
133         } d_partitions[BSD_MAXPARTITIONS]; /* actually may be more */
134 };
135
136 /* d_type values: */
137 #define BSD_DTYPE_SMD           1               /* SMD, XSMD; VAX hp/up */
138 #define BSD_DTYPE_MSCP          2               /* MSCP */
139 #define BSD_DTYPE_DEC           3               /* other DEC (rk, rl) */
140 #define BSD_DTYPE_SCSI          4               /* SCSI */
141 #define BSD_DTYPE_ESDI          5               /* ESDI interface */
142 #define BSD_DTYPE_ST506         6               /* ST506 etc. */
143 #define BSD_DTYPE_HPIB          7               /* CS/80 on HP-IB */
144 #define BSD_DTYPE_HPFL          8               /* HP Fiber-link */
145 #define BSD_DTYPE_FLOPPY        10              /* floppy */
146
147 /* d_subtype values: */
148 #define BSD_DSTYPE_INDOSPART    0x8             /* is inside dos partition */
149 #define BSD_DSTYPE_DOSPART(s)   ((s) & 3)       /* dos partition number */
150 #define BSD_DSTYPE_GEOMETRY     0x10            /* drive params in label */
151
152 static const char * const xbsd_dktypenames[] = {
153         "unknown",
154         "SMD",
155         "MSCP",
156         "old DEC",
157         "SCSI",
158         "ESDI",
159         "ST506",
160         "HP-IB",
161         "HP-FL",
162         "type 9",
163         "floppy",
164         0
165 };
166 #define BSD_DKMAXTYPES  (sizeof(xbsd_dktypenames) / sizeof(xbsd_dktypenames[0]) - 1)
167
168 /*
169  * Filesystem type and version.
170  * Used to interpret other filesystem-specific
171  * per-partition information.
172  */
173 #define BSD_FS_UNUSED   0               /* unused */
174 #define BSD_FS_SWAP     1               /* swap */
175 #define BSD_FS_V6       2               /* Sixth Edition */
176 #define BSD_FS_V7       3               /* Seventh Edition */
177 #define BSD_FS_SYSV     4               /* System V */
178 #define BSD_FS_V71K     5               /* V7 with 1K blocks (4.1, 2.9) */
179 #define BSD_FS_V8       6               /* Eighth Edition, 4K blocks */
180 #define BSD_FS_BSDFFS   7               /* 4.2BSD fast file system */
181 #define BSD_FS_BSDLFS   9               /* 4.4BSD log-structured file system */
182 #define BSD_FS_OTHER    10              /* in use, but unknown/unsupported */
183 #define BSD_FS_HPFS     11              /* OS/2 high-performance file system */
184 #define BSD_FS_ISO9660  12              /* ISO-9660 filesystem (cdrom) */
185 #define BSD_FS_ISOFS    BSD_FS_ISO9660
186 #define BSD_FS_BOOT     13              /* partition contains bootstrap */
187 #define BSD_FS_ADOS     14              /* AmigaDOS fast file system */
188 #define BSD_FS_HFS      15              /* Macintosh HFS */
189 #define BSD_FS_ADVFS    16              /* Digital Unix AdvFS */
190
191 /* this is annoying, but it's also the way it is :-( */
192 #ifdef __alpha__
193 #define BSD_FS_EXT2     8               /* ext2 file system */
194 #else
195 #define BSD_FS_MSDOS    8               /* MS-DOS file system */
196 #endif
197
198 static const struct systypes xbsd_fstypes[] = {
199         { "\x00" "unused" },            /* BSD_FS_UNUSED  */
200         { "\x01" "swap" },              /* BSD_FS_SWAP    */
201         { "\x02" "Version 6" },         /* BSD_FS_V6      */
202         { "\x03" "Version 7" },         /* BSD_FS_V7      */
203         { "\x04" "System V" },          /* BSD_FS_SYSV    */
204         { "\x05" "4.1BSD" },            /* BSD_FS_V71K    */
205         { "\x06" "Eighth Edition" },    /* BSD_FS_V8      */
206         { "\x07" "4.2BSD" },            /* BSD_FS_BSDFFS  */
207 #ifdef __alpha__
208         { "\x08" "ext2" },              /* BSD_FS_EXT2    */
209 #else
210         { "\x08" "MS-DOS" },            /* BSD_FS_MSDOS   */
211 #endif
212         { "\x09" "4.4LFS" },            /* BSD_FS_BSDLFS  */
213         { "\x0a" "unknown" },           /* BSD_FS_OTHER   */
214         { "\x0b" "HPFS" },              /* BSD_FS_HPFS    */
215         { "\x0c" "ISO-9660" },          /* BSD_FS_ISO9660 */
216         { "\x0d" "boot" },              /* BSD_FS_BOOT    */
217         { "\x0e" "ADOS" },              /* BSD_FS_ADOS    */
218         { "\x0f" "HFS" },               /* BSD_FS_HFS     */
219         { "\x10" "AdvFS" },             /* BSD_FS_ADVFS   */
220         { NULL }
221 };
222 #define BSD_FSMAXTYPES (SIZE(xbsd_fstypes)-1)
223
224
225 /*
226  * flags shared by various drives:
227  */
228 #define BSD_D_REMOVABLE 0x01            /* removable media */
229 #define BSD_D_ECC       0x02            /* supports ECC */
230 #define BSD_D_BADSECT   0x04            /* supports bad sector forw. */
231 #define BSD_D_RAMDISK   0x08            /* disk emulator */
232 #define BSD_D_CHAIN     0x10            /* can do back-back transfers */
233 #define BSD_D_DOSPART   0x20            /* within MSDOS partition */
234
235 /*
236    Changes:
237    19990319 - Arnaldo Carvalho de Melo <acme@conectiva.com.br> - i18n/nls
238
239    20000101 - David Huggins-Daines <dhuggins@linuxcare.com> - Better
240    support for OSF/1 disklabels on Alpha.
241    Also fixed unaligned accesses in alpha_bootblock_checksum()
242 */
243
244 static int possibly_osf_label;
245
246 #define FREEBSD_PARTITION       0xa5
247 #define NETBSD_PARTITION        0xa9
248
249 static void xbsd_delete_part(void);
250 static void xbsd_new_part(void);
251 static void xbsd_write_disklabel(void);
252 static int xbsd_create_disklabel(void);
253 static void xbsd_edit_disklabel(void);
254 static void xbsd_write_bootstrap(void);
255 static void xbsd_change_fstype(void);
256 static int xbsd_get_part_index(int max);
257 static int xbsd_check_new_partition(int *i);
258 static void xbsd_list_types(void);
259 static uint16_t xbsd_dkcksum(struct xbsd_disklabel *lp);
260 static int xbsd_initlabel(struct partition *p, struct xbsd_disklabel *d);
261 static int xbsd_readlabel(struct partition *p, struct xbsd_disklabel *d);
262 static int xbsd_writelabel(struct partition *p, struct xbsd_disklabel *d);
263
264 #if defined(__alpha__)
265 static void alpha_bootblock_checksum(char *boot);
266 #endif
267
268 #if !defined(__alpha__)
269 static int xbsd_translate_fstype(int linux_type);
270 static void xbsd_link_part(void);
271 static struct partition *xbsd_part;
272 static int xbsd_part_index;
273 #endif
274
275 /* We access this through a uint64_t * when checksumming */
276 /* hopefully xmalloc gives us required alignment */
277 static char *disklabelbuffer; /*[BSD_BBSIZE]*/
278
279 static struct xbsd_disklabel xbsd_dlabel;
280
281 #define bsd_cround(n) \
282         (display_in_cyl_units ? ((n)/xbsd_dlabel.d_secpercyl) + 1 : (n))
283
284 /*
285  * Test whether the whole disk has BSD disk label magic.
286  *
287  * Note: often reformatting with DOS-type label leaves the BSD magic,
288  * so this does not mean that there is a BSD disk label.
289  */
290 static int
291 check_osf_label(void)
292 {
293         if (xbsd_readlabel(NULL, &xbsd_dlabel) == 0)
294                 return 0;
295         return 1;
296 }
297
298 static int
299 bsd_trydev(const char * dev)
300 {
301         if (xbsd_readlabel(NULL, &xbsd_dlabel) == 0)
302                 return -1;
303         printf(_("\nBSD label for device: %s\n"), dev);
304         xbsd_print_disklabel(0);
305         return 0;
306 }
307
308 static void
309 bsd_menu(void)
310 {
311         puts(_("Command Action"));
312         puts(_("d\tdelete a BSD partition"));
313         puts(_("e\tedit drive data"));
314         puts(_("i\tinstall bootstrap"));
315         puts(_("l\tlist known filesystem types"));
316         puts(_("n\tadd a new BSD partition"));
317         puts(_("p\tprint BSD partition table"));
318         puts(_("q\tquit without saving changes"));
319         puts(_("r\treturn to main menu"));
320         puts(_("s\tshow complete disklabel"));
321         puts(_("t\tchange a partition's filesystem id"));
322         puts(_("u\tchange units (cylinders/sectors)"));
323         puts(_("w\twrite disklabel to disk"));
324 #if !defined(__alpha__)
325         puts(_("x\tlink BSD partition to non-BSD partition"));
326 #endif
327 }
328
329 #if !defined(__alpha__)
330 static int
331 hidden(int type)
332 {
333         return type ^ 0x10;
334 }
335
336 static int
337 is_bsd_partition_type(int type)
338 {
339         return (type == FREEBSD_PARTITION ||
340                 type == hidden(FREEBSD_PARTITION) ||
341                 type == NETBSD_PARTITION ||
342                 type == hidden(NETBSD_PARTITION));
343 }
344 #endif
345
346 static void
347 bsd_select(void)
348 {
349 #if !defined(__alpha__)
350         int t, ss;
351         struct partition *p;
352
353         for (t = 0; t < 4; t++) {
354                 p = get_part_table(t);
355                 if (p && is_bsd_partition_type(p->sys_ind)) {
356                         xbsd_part = p;
357                         xbsd_part_index = t;
358                         ss = get_start_sect(xbsd_part);
359                         if (ss == 0) {
360                                 fprintf(stderr, _("Partition %s has invalid starting sector 0.\n"),
361                                         partname(disk_device, t+1, 0));
362                                 return;
363                         }
364                                 printf(_("Reading disklabel of %s at sector %d.\n"),
365                                         partname(disk_device, t+1, 0), ss + BSD_LABELSECTOR);
366                         if (xbsd_readlabel(xbsd_part, &xbsd_dlabel) == 0)
367                                 if (xbsd_create_disklabel() == 0)
368                                         return;
369                                 break;
370                 }
371         }
372
373         if (t == 4) {
374                 printf(_("There is no *BSD partition on %s.\n"), disk_device);
375                 return;
376         }
377
378 #elif defined(__alpha__)
379
380         if (xbsd_readlabel(NULL, &xbsd_dlabel) == 0)
381                 if (xbsd_create_disklabel() == 0)
382                         exit(EXIT_SUCCESS);
383
384 #endif
385
386         while (1) {
387                 putchar('\n');
388                 switch (tolower(read_nonempty(_("BSD disklabel command (m for help): ")))) {
389                 case 'd':
390                         xbsd_delete_part();
391                         break;
392                 case 'e':
393                         xbsd_edit_disklabel();
394                         break;
395                 case 'i':
396                         xbsd_write_bootstrap();
397                         break;
398                 case 'l':
399                         xbsd_list_types();
400                         break;
401                 case 'n':
402                         xbsd_new_part();
403                         break;
404                 case 'p':
405                         xbsd_print_disklabel(0);
406                         break;
407                 case 'q':
408                         close(fd);
409                         exit(EXIT_SUCCESS);
410                 case 'r':
411                         return;
412                 case 's':
413                         xbsd_print_disklabel(1);
414                         break;
415                 case 't':
416                         xbsd_change_fstype();
417                         break;
418                 case 'u':
419                         change_units();
420                         break;
421                 case 'w':
422                         xbsd_write_disklabel();
423                         break;
424 #if !defined(__alpha__)
425                 case 'x':
426                         xbsd_link_part();
427                         break;
428 #endif
429                 default:
430                         bsd_menu();
431                         break;
432                 }
433         }
434 }
435
436 static void
437 xbsd_delete_part(void)
438 {
439         int i;
440
441         i = xbsd_get_part_index(xbsd_dlabel.d_npartitions);
442         xbsd_dlabel.d_partitions[i].p_size   = 0;
443         xbsd_dlabel.d_partitions[i].p_offset = 0;
444         xbsd_dlabel.d_partitions[i].p_fstype = BSD_FS_UNUSED;
445         if (xbsd_dlabel.d_npartitions == i + 1)
446                 while (xbsd_dlabel.d_partitions[xbsd_dlabel.d_npartitions-1].p_size == 0)
447                         xbsd_dlabel.d_npartitions--;
448 }
449
450 static void
451 xbsd_new_part(void)
452 {
453         off_t begin, end;
454         char mesg[256];
455         int i;
456
457         if (!xbsd_check_new_partition(&i))
458                 return;
459
460 #if !defined(__alpha__) && !defined(__powerpc__) && !defined(__hppa__)
461         begin = get_start_sect(xbsd_part);
462         end = begin + get_nr_sects(xbsd_part) - 1;
463 #else
464         begin = 0;
465         end = xbsd_dlabel.d_secperunit - 1;
466 #endif
467
468         snprintf(mesg, sizeof(mesg), _("First %s"), str_units(SINGULAR));
469         begin = read_int(bsd_cround(begin), bsd_cround(begin), bsd_cround(end),
470                 0, mesg);
471
472         if (display_in_cyl_units)
473                 begin = (begin - 1) * xbsd_dlabel.d_secpercyl;
474
475         snprintf(mesg, sizeof(mesg), _("Last %s or +size or +sizeM or +sizeK"),
476                 str_units(SINGULAR));
477         end = read_int(bsd_cround(begin), bsd_cround(end), bsd_cround(end),
478                 bsd_cround(begin), mesg);
479
480         if (display_in_cyl_units)
481                 end = end * xbsd_dlabel.d_secpercyl - 1;
482
483         xbsd_dlabel.d_partitions[i].p_size   = end - begin + 1;
484         xbsd_dlabel.d_partitions[i].p_offset = begin;
485         xbsd_dlabel.d_partitions[i].p_fstype = BSD_FS_UNUSED;
486 }
487
488 static void
489 xbsd_print_disklabel(int show_all)
490 {
491         struct xbsd_disklabel *lp = &xbsd_dlabel;
492         struct xbsd_partition *pp;
493         int i, j;
494
495         if (show_all) {
496 #if defined(__alpha__)
497                 printf("# %s:\n", disk_device);
498 #else
499                 printf("# %s:\n", partname(disk_device, xbsd_part_index+1, 0));
500 #endif
501                 if ((unsigned) lp->d_type < BSD_DKMAXTYPES)
502                         printf(_("type: %s\n"), xbsd_dktypenames[lp->d_type]);
503                 else
504                         printf(_("type: %d\n"), lp->d_type);
505                 printf(_("disk: %.*s\n"), (int) sizeof(lp->d_typename), lp->d_typename);
506                 printf(_("label: %.*s\n"), (int) sizeof(lp->d_packname), lp->d_packname);
507                 printf(_("flags:"));
508                 if (lp->d_flags & BSD_D_REMOVABLE)
509                         printf(_(" removable"));
510                 if (lp->d_flags & BSD_D_ECC)
511                         printf(_(" ecc"));
512                 if (lp->d_flags & BSD_D_BADSECT)
513                         printf(_(" badsect"));
514                 puts("");
515                 /* On various machines the fields of *lp are short/int/long */
516                 /* In order to avoid problems, we cast them all to long. */
517                 printf(_("bytes/sector: %ld\n"), (long) lp->d_secsize);
518                 printf(_("sectors/track: %ld\n"), (long) lp->d_nsectors);
519                 printf(_("tracks/cylinder: %ld\n"), (long) lp->d_ntracks);
520                 printf(_("sectors/cylinder: %ld\n"), (long) lp->d_secpercyl);
521                 printf(_("cylinders: %ld\n"), (long) lp->d_ncylinders);
522                 printf(_("rpm: %d\n"), lp->d_rpm);
523                 printf(_("interleave: %d\n"), lp->d_interleave);
524                 printf(_("trackskew: %d\n"), lp->d_trackskew);
525                 printf(_("cylinderskew: %d\n"), lp->d_cylskew);
526                 printf(_("headswitch: %ld\t\t# milliseconds\n"),
527                         (long) lp->d_headswitch);
528                 printf(_("track-to-track seek: %ld\t# milliseconds\n"),
529                         (long) lp->d_trkseek);
530                 printf(_("drivedata: "));
531                 for (i = NDDATA - 1; i >= 0; i--)
532                         if (lp->d_drivedata[i])
533                                 break;
534                 if (i < 0)
535                         i = 0;
536                 for (j = 0; j <= i; j++)
537                         printf("%ld ", (long) lp->d_drivedata[j]);
538         }
539         printf(_("\n%d partitions:\n"), lp->d_npartitions);
540         printf(_("#       start       end      size     fstype   [fsize bsize   cpg]\n"));
541         pp = lp->d_partitions;
542         for (i = 0; i < lp->d_npartitions; i++, pp++) {
543                 if (pp->p_size) {
544                         if (display_in_cyl_units && lp->d_secpercyl) {
545                                 printf("  %c: %8ld%c %8ld%c %8ld%c  ",
546                                         'a' + i,
547                                         (long) pp->p_offset / lp->d_secpercyl + 1,
548                                         (pp->p_offset % lp->d_secpercyl) ? '*' : ' ',
549                                         (long) (pp->p_offset + pp->p_size + lp->d_secpercyl - 1) / lp->d_secpercyl,
550                                         ((pp->p_offset + pp->p_size) % lp->d_secpercyl) ? '*' : ' ',
551                                         (long) pp->p_size / lp->d_secpercyl,
552                                         (pp->p_size % lp->d_secpercyl) ? '*' : ' '
553                                 );
554                         } else {
555                                 printf("  %c: %8ld  %8ld  %8ld   ",
556                                         'a' + i,
557                                         (long) pp->p_offset,
558                                         (long) pp->p_offset + pp->p_size - 1,
559                                         (long) pp->p_size
560                                 );
561                         }
562
563                         if ((unsigned) pp->p_fstype < BSD_FSMAXTYPES)
564                                 printf("%8.8s", xbsd_fstypes[pp->p_fstype].name);
565                         else
566                                 printf("%8x", pp->p_fstype);
567
568                         switch (pp->p_fstype) {
569                         case BSD_FS_UNUSED:
570                                 printf("    %5ld %5ld %5.5s ",
571                                         (long) pp->p_fsize, (long) pp->p_fsize * pp->p_frag, "");
572                                 break;
573                         case BSD_FS_BSDFFS:
574                                 printf("    %5ld %5ld %5d ",
575                                         (long) pp->p_fsize, (long) pp->p_fsize * pp->p_frag, pp->p_cpg);
576                                 break;
577                         default:
578                                 printf("%22.22s", "");
579                                 break;
580                         }
581                         puts("");
582                 }
583         }
584 }
585
586 static void
587 xbsd_write_disklabel(void)
588 {
589 #if defined(__alpha__)
590         printf(_("Writing disklabel to %s.\n"), disk_device);
591         xbsd_writelabel(NULL, &xbsd_dlabel);
592 #else
593         printf(_("Writing disklabel to %s.\n"),
594                 partname(disk_device, xbsd_part_index + 1, 0));
595         xbsd_writelabel(xbsd_part, &xbsd_dlabel);
596 #endif
597         reread_partition_table(0);      /* no exit yet */
598 }
599
600 static int
601 xbsd_create_disklabel(void)
602 {
603         char c;
604
605 #if defined(__alpha__)
606         fprintf(stderr, _("%s contains no disklabel.\n"), disk_device);
607 #else
608         fprintf(stderr, _("%s contains no disklabel.\n"),
609                 partname(disk_device, xbsd_part_index + 1, 0));
610 #endif
611
612         while (1) {
613                 c = read_nonempty(_("Do you want to create a disklabel? (y/n) "));
614                 if (c == 'y' || c == 'Y') {
615                         if (xbsd_initlabel(
616 #if defined(__alpha__) || defined(__powerpc__) || defined(__hppa__) || \
617         defined(__s390__) || defined(__s390x__)
618                                 NULL, &xbsd_dlabel
619 #else
620                                 xbsd_part, &xbsd_dlabel/* not used, xbsd_part_index*/
621 #endif
622                                 ) == 1) {
623                                 xbsd_print_disklabel(1);
624                                 return 1;
625                         } else
626                                 return 0;
627                 } else if (c == 'n')
628                         return 0;
629         }
630 }
631
632 static int
633 edit_int(int def, const char *mesg)
634 {
635         mesg = xasprintf("%s (%d): ", mesg, def);
636         do {
637                 if (!read_line(mesg))
638                         goto ret;
639         } while (!isdigit(*line_ptr));
640         def = atoi(line_ptr);
641  ret:
642         free((char*)mesg);
643         return def;
644 }
645
646 static void
647 xbsd_edit_disklabel(void)
648 {
649         struct xbsd_disklabel *d;
650
651         d = &xbsd_dlabel;
652
653 #if defined(__alpha__) || defined(__ia64__)
654         d->d_secsize    = edit_int(d->d_secsize     ,_("bytes/sector"));
655         d->d_nsectors   = edit_int(d->d_nsectors    ,_("sectors/track"));
656         d->d_ntracks    = edit_int(d->d_ntracks     ,_("tracks/cylinder"));
657         d->d_ncylinders = edit_int(d->d_ncylinders  ,_("cylinders"));
658 #endif
659
660         /* d->d_secpercyl can be != d->d_nsectors * d->d_ntracks */
661         while (1) {
662                 d->d_secpercyl = edit_int(d->d_nsectors * d->d_ntracks,
663                                 _("sectors/cylinder"));
664                 if (d->d_secpercyl <= d->d_nsectors * d->d_ntracks)
665                         break;
666
667                 printf(_("Must be <= sectors/track * tracks/cylinder (default).\n"));
668         }
669         d->d_rpm        = edit_int(d->d_rpm       ,_("rpm"));
670         d->d_interleave = edit_int(d->d_interleave,_("interleave"));
671         d->d_trackskew  = edit_int(d->d_trackskew ,_("trackskew"));
672         d->d_cylskew    = edit_int(d->d_cylskew   ,_("cylinderskew"));
673         d->d_headswitch = edit_int(d->d_headswitch,_("headswitch"));
674         d->d_trkseek    = edit_int(d->d_trkseek   ,_("track-to-track seek"));
675
676         d->d_secperunit = d->d_secpercyl * d->d_ncylinders;
677 }
678
679 static int
680 xbsd_get_bootstrap(char *path, void *ptr, int size)
681 {
682         int fdb;
683
684         fdb = open(path, O_RDONLY);
685         if (fdb < 0) {
686                 perror(path);
687                 return 0;
688         }
689         if (read(fdb, ptr, size) < 0) {
690                 perror(path);
691                 close(fdb);
692                 return 0;
693         }
694         printf(" ... %s\n", path);
695         close(fdb);
696         return 1;
697 }
698
699 static void
700 sync_disks(void)
701 {
702         printf(_("\nSyncing disks.\n"));
703         sync();
704         sleep(4); /* What? */
705 }
706
707 static void
708 xbsd_write_bootstrap(void)
709 {
710         char path[MAXPATHLEN];
711         const char *bootdir = BSD_LINUX_BOOTDIR;
712         const char *dkbasename;
713         struct xbsd_disklabel dl;
714         char *d, *p, *e;
715         int sector;
716
717         if (xbsd_dlabel.d_type == BSD_DTYPE_SCSI)
718                 dkbasename = "sd";
719         else
720                 dkbasename = "wd";
721
722         snprintf(path, sizeof(path), "Bootstrap: %sboot -> boot%s (%s): ",
723                 dkbasename, dkbasename, dkbasename);
724         if (read_line(path)) {
725                 dkbasename = line_ptr;
726         }
727         snprintf(path, sizeof(path), "%s/%sboot", bootdir, dkbasename);
728         if (!xbsd_get_bootstrap(path, disklabelbuffer, (int) xbsd_dlabel.d_secsize))
729                 return;
730
731 /* We need a backup of the disklabel (xbsd_dlabel might have changed). */
732         d = &disklabelbuffer[BSD_LABELSECTOR * SECTOR_SIZE];
733         memmove(&dl, d, sizeof(struct xbsd_disklabel));
734
735 /* The disklabel will be overwritten by 0's from bootxx anyway */
736         memset(d, 0, sizeof(struct xbsd_disklabel));
737
738         snprintf(path, sizeof(path), "%s/boot%s", bootdir, dkbasename);
739         if (!xbsd_get_bootstrap(path, &disklabelbuffer[xbsd_dlabel.d_secsize],
740                         (int) xbsd_dlabel.d_bbsize - xbsd_dlabel.d_secsize))
741                 return;
742
743         e = d + sizeof(struct xbsd_disklabel);
744         for (p = d; p < e; p++)
745                 if (*p) {
746                         fprintf(stderr, _("Bootstrap overlaps with disk label!\n"));
747                         exit(EXIT_FAILURE);
748                 }
749
750         memmove(d, &dl, sizeof(struct xbsd_disklabel));
751
752 #if defined(__powerpc__) || defined(__hppa__)
753         sector = 0;
754 #elif defined(__alpha__)
755         sector = 0;
756         alpha_bootblock_checksum(disklabelbuffer);
757 #else
758         sector = get_start_sect(xbsd_part);
759 #endif
760
761         if (lseek(fd, sector * SECTOR_SIZE, SEEK_SET) == -1)
762                 fdisk_fatal(unable_to_seek);
763         if (BSD_BBSIZE != write(fd, disklabelbuffer, BSD_BBSIZE))
764                 fdisk_fatal(unable_to_write);
765
766 #if defined(__alpha__)
767         printf(_("Bootstrap installed on %s.\n"), disk_device);
768 #else
769         printf(_("Bootstrap installed on %s.\n"),
770                 partname(disk_device, xbsd_part_index+1, 0));
771 #endif
772
773         sync_disks();
774 }
775
776 static void
777 xbsd_change_fstype(void)
778 {
779         int i;
780
781         i = xbsd_get_part_index(xbsd_dlabel.d_npartitions);
782         xbsd_dlabel.d_partitions[i].p_fstype = read_hex(xbsd_fstypes);
783 }
784
785 static int
786 xbsd_get_part_index(int max)
787 {
788         char prompt[256];
789         char l;
790
791         snprintf(prompt, sizeof(prompt), _("Partition (a-%c): "), 'a' + max - 1);
792         do
793                 l = tolower(read_nonempty(prompt));
794         while (l < 'a' || l > 'a' + max - 1);
795         return l - 'a';
796 }
797
798 static int
799 xbsd_check_new_partition(int *i)
800 {
801         /* room for more? various BSD flavours have different maxima */
802         if (xbsd_dlabel.d_npartitions == BSD_MAXPARTITIONS) {
803                 int t;
804
805                 for (t = 0; t < BSD_MAXPARTITIONS; t++)
806                         if (xbsd_dlabel.d_partitions[t].p_size == 0)
807                                 break;
808
809                 if (t == BSD_MAXPARTITIONS) {
810                         fprintf(stderr, _("The maximum number of partitions "
811                                            "has been created\n"));
812                         return 0;
813                 }
814         }
815
816         *i = xbsd_get_part_index(BSD_MAXPARTITIONS);
817
818         if (*i >= xbsd_dlabel.d_npartitions)
819                 xbsd_dlabel.d_npartitions = (*i) + 1;
820
821         if (xbsd_dlabel.d_partitions[*i].p_size != 0) {
822                 fprintf(stderr, _("This partition already exists.\n"));
823                 return 0;
824         }
825
826         return 1;
827 }
828
829 static void
830 xbsd_list_types(void)
831 {
832         list_types(xbsd_fstypes);
833 }
834
835 static uint16_t
836 xbsd_dkcksum(struct xbsd_disklabel *lp)
837 {
838         uint16_t *start, *end;
839         uint16_t sum = 0;
840
841         start = (uint16_t *) lp;
842         end = (uint16_t *) &lp->d_partitions[lp->d_npartitions];
843         while (start < end)
844                 sum ^= *start++;
845         return sum;
846 }
847
848 static int
849 xbsd_initlabel(struct partition *p, struct xbsd_disklabel *d)
850 {
851         struct xbsd_partition *pp;
852
853         get_geometry();
854         memset(d, 0, sizeof(struct xbsd_disklabel));
855
856         d->d_magic = BSD_DISKMAGIC;
857
858         if (strncmp(disk_device, "/dev/sd", 7) == 0)
859                 d->d_type = BSD_DTYPE_SCSI;
860         else
861                 d->d_type = BSD_DTYPE_ST506;
862
863 #if !defined(__alpha__)
864         d->d_flags = BSD_D_DOSPART;
865 #else
866         d->d_flags = 0;
867 #endif
868         d->d_secsize = SECTOR_SIZE;           /* bytes/sector  */
869         d->d_nsectors = sectors;              /* sectors/track */
870         d->d_ntracks = heads;                 /* tracks/cylinder (heads) */
871         d->d_ncylinders = cylinders;
872         d->d_secpercyl  = sectors * heads;    /* sectors/cylinder */
873         if (d->d_secpercyl == 0)
874                 d->d_secpercyl = 1;           /* avoid segfaults */
875         d->d_secperunit = d->d_secpercyl * d->d_ncylinders;
876
877         d->d_rpm = 3600;
878         d->d_interleave = 1;
879         d->d_trackskew = 0;
880         d->d_cylskew = 0;
881         d->d_headswitch = 0;
882         d->d_trkseek = 0;
883
884         d->d_magic2 = BSD_DISKMAGIC;
885         d->d_bbsize = BSD_BBSIZE;
886         d->d_sbsize = BSD_SBSIZE;
887
888 #if !defined(__alpha__)
889         d->d_npartitions = 4;
890         pp = &d->d_partitions[2]; /* Partition C should be NetBSD partition */
891
892         pp->p_offset = get_start_sect(p);
893         pp->p_size   = get_nr_sects(p);
894         pp->p_fstype = BSD_FS_UNUSED;
895         pp = &d->d_partitions[3]; /* Partition D should be whole disk */
896
897         pp->p_offset = 0;
898         pp->p_size   = d->d_secperunit;
899         pp->p_fstype = BSD_FS_UNUSED;
900 #elif defined(__alpha__)
901         d->d_npartitions = 3;
902         pp = &d->d_partitions[2];             /* Partition C should be
903                                                    the whole disk */
904         pp->p_offset = 0;
905         pp->p_size   = d->d_secperunit;
906         pp->p_fstype = BSD_FS_UNUSED;
907 #endif
908
909         return 1;
910 }
911
912 /*
913  * Read a xbsd_disklabel from sector 0 or from the starting sector of p.
914  * If it has the right magic, return 1.
915  */
916 static int
917 xbsd_readlabel(struct partition *p, struct xbsd_disklabel *d)
918 {
919         int t, sector;
920
921         if (!disklabelbuffer)
922                 disklabelbuffer = xmalloc(BSD_BBSIZE);
923
924         /* p is used only to get the starting sector */
925 #if !defined(__alpha__)
926         sector = (p ? get_start_sect(p) : 0);
927 #elif defined(__alpha__)
928         sector = 0;
929 #endif
930
931         if (lseek(fd, sector * SECTOR_SIZE, SEEK_SET) == -1)
932                 fdisk_fatal(unable_to_seek);
933         if (BSD_BBSIZE != read(fd, disklabelbuffer, BSD_BBSIZE))
934                 fdisk_fatal(unable_to_read);
935
936         memmove(d, &disklabelbuffer[BSD_LABELSECTOR * SECTOR_SIZE + BSD_LABELOFFSET],
937                    sizeof(struct xbsd_disklabel));
938
939         if (d->d_magic != BSD_DISKMAGIC || d->d_magic2 != BSD_DISKMAGIC)
940                 return 0;
941
942         for (t = d->d_npartitions; t < BSD_MAXPARTITIONS; t++) {
943                 d->d_partitions[t].p_size   = 0;
944                 d->d_partitions[t].p_offset = 0;
945                 d->d_partitions[t].p_fstype = BSD_FS_UNUSED;
946         }
947
948         if (d->d_npartitions > BSD_MAXPARTITIONS)
949                 fprintf(stderr, _("Warning: too many partitions "
950                                 "(%d, maximum is %d).\n"),
951                         d->d_npartitions, BSD_MAXPARTITIONS);
952         return 1;
953 }
954
955 static int
956 xbsd_writelabel(struct partition *p, struct xbsd_disklabel *d)
957 {
958         unsigned int sector;
959
960 #if !defined(__alpha__) && !defined(__powerpc__) && !defined(__hppa__)
961         sector = get_start_sect(p) + BSD_LABELSECTOR;
962 #else
963         sector = BSD_LABELSECTOR;
964 #endif
965
966         d->d_checksum = 0;
967         d->d_checksum = xbsd_dkcksum(d);
968
969         /* This is necessary if we want to write the bootstrap later,
970            otherwise we'd write the old disklabel with the bootstrap.
971         */
972         memmove(&disklabelbuffer[BSD_LABELSECTOR * SECTOR_SIZE + BSD_LABELOFFSET],
973                 d, sizeof(struct xbsd_disklabel));
974
975 #if defined(__alpha__) && BSD_LABELSECTOR == 0
976         alpha_bootblock_checksum(disklabelbuffer);
977         if (lseek(fd, 0, SEEK_SET) == -1)
978                 fdisk_fatal(unable_to_seek);
979         if (BSD_BBSIZE != write(fd, disklabelbuffer, BSD_BBSIZE))
980                 fdisk_fatal(unable_to_write);
981 #else
982         if (lseek(fd, sector * SECTOR_SIZE + BSD_LABELOFFSET, SEEK_SET) == -1)
983                 fdisk_fatal(unable_to_seek);
984         if (sizeof(struct xbsd_disklabel) != write(fd, d, sizeof(struct xbsd_disklabel)))
985                 fdisk_fatal(unable_to_write);
986 #endif
987         sync_disks();
988         return 1;
989 }
990
991
992 #if !defined(__alpha__)
993 static int
994 xbsd_translate_fstype(int linux_type)
995 {
996         switch (linux_type) {
997         case 0x01: /* DOS 12-bit FAT   */
998         case 0x04: /* DOS 16-bit <32M  */
999         case 0x06: /* DOS 16-bit >=32M */
1000         case 0xe1: /* DOS access       */
1001         case 0xe3: /* DOS R/O          */
1002         case 0xf2: /* DOS secondary    */
1003                 return BSD_FS_MSDOS;
1004         case 0x07: /* OS/2 HPFS        */
1005                 return BSD_FS_HPFS;
1006         default:
1007                 return BSD_FS_OTHER;
1008         }
1009 }
1010
1011 static void
1012 xbsd_link_part(void)
1013 {
1014         int k, i;
1015         struct partition *p;
1016
1017         k = get_partition(1, partitions);
1018
1019         if (!xbsd_check_new_partition(&i))
1020                 return;
1021
1022         p = get_part_table(k);
1023
1024         xbsd_dlabel.d_partitions[i].p_size   = get_nr_sects(p);
1025         xbsd_dlabel.d_partitions[i].p_offset = get_start_sect(p);
1026         xbsd_dlabel.d_partitions[i].p_fstype = xbsd_translate_fstype(p->sys_ind);
1027 }
1028 #endif
1029
1030 #if defined(__alpha__)
1031
1032 static void
1033 alpha_bootblock_checksum(char *boot)
1034 {
1035         uint64_t *dp, sum;
1036         int i;
1037
1038         dp = (uint64_t *)boot;
1039         sum = 0;
1040         for (i = 0; i < 63; i++)
1041                 sum += dp[i];
1042         dp[63] = sum;
1043 }
1044 #endif /* __alpha__ */
1045
1046 #endif /* OSF_LABEL */