Initial import from FreeBSD RELENG_4:
[games.git] / usr.sbin / diskpart / diskpart.c
1 /*
2  * Copyright (c) 1983, 1988, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1983, 1988, 1993\n\
37         The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)diskpart.c  8.3 (Berkeley) 11/30/94";
43 #endif
44 static const char rcsid[] =
45   "$FreeBSD: src/usr.sbin/diskpart/diskpart.c,v 1.11.2.2 2002/12/04 16:24:08 roam Exp $";
46 #endif /* not lint */
47
48 /*
49  * Program to calculate standard disk partition sizes.
50  */
51 #include <sys/param.h>
52 #define DKTYPENAMES
53 #include <sys/disklabel.h>
54
55 #include <ctype.h>
56 #include <err.h>
57 #include <stdio.h>
58 #include <unistd.h>
59
60 #define for_now                 /* show all of `c' partition for disklabel */
61 #define NPARTITIONS     8
62 #define PART(x)         (x - 'a')
63
64 /*
65  * Default partition sizes, where they exist.
66  */
67 #define NDEFAULTS       4
68 int     defpart[NDEFAULTS][NPARTITIONS] = {
69    { 15884, 66880, 0, 15884, 307200, 0, 0, 291346 },    /* ~ 356+ Mbytes */
70    { 15884, 33440, 0, 15884, 55936, 0, 0, 291346 },     /* ~ 206-355 Mbytes */
71    { 15884, 33440, 0, 15884, 55936, 0, 0, 0 },          /* ~ 61-205 Mbytes */
72    { 15884, 10032, 0, 15884, 0, 0, 0, 0 },              /* ~ 20-60 Mbytes */
73 };
74
75 /*
76  * Each array defines a layout for a disk;
77  * that is, the collection of partitions totally
78  * covers the physical space on a disk.
79  */
80 #define NLAYOUTS        3
81 char    layouts[NLAYOUTS][NPARTITIONS] = {
82    { 'a', 'b', 'h', 'g' },
83    { 'a', 'b', 'h', 'd', 'e', 'f' },
84    { 'c' },
85 };
86
87 /*
88  * Default disk block and disk block fragment
89  * sizes for each file system.  Those file systems
90  * with zero block and frag sizes are special cases
91  * (e.g. swap areas or for access to the entire device).
92  */
93 struct  partition defparam[NPARTITIONS] = {
94         { 0, 0, 1024, FS_UNUSED, 8, 0 },                /* a */
95         { 0, 0, 1024, FS_SWAP,   8, 0 },                /* b */
96         { 0, 0, 1024, FS_UNUSED, 8, 0 },                /* c */
97         { 0, 0,  512, FS_UNUSED, 8, 0 },                /* d */
98         { 0, 0, 1024, FS_UNUSED, 8, 0 },                /* e */
99         { 0, 0, 1024, FS_UNUSED, 8, 0 },                /* f */
100         { 0, 0, 1024, FS_UNUSED, 8, 0 },                /* g */
101         { 0, 0, 1024, FS_UNUSED, 8, 0 }                 /* h */
102 };
103
104 /*
105  * Each disk has some space reserved for a bad sector
106  * forwarding table.  DEC standard 144 uses the first
107  * 5 even numbered sectors in the last track of the
108  * last cylinder for replicated storage of the bad sector
109  * table; another 126 sectors past this is needed as a
110  * pool of replacement sectors.
111  */
112 int     badsecttable = 126;     /* # sectors */
113
114 int     pflag;                  /* print device driver partition tables */
115 int     dflag;                  /* print disktab entry */
116
117 struct  disklabel *promptfordisk();
118 static void usage __P((void));
119
120 int
121 main(argc, argv)
122         int argc;
123         char *argv[];
124 {
125         struct disklabel *dp;
126         register int curcyl, spc, def, part, layout, j;
127         int threshhold, numcyls[NPARTITIONS], startcyl[NPARTITIONS];
128         int totsize = 0;
129         char *lp, *tyname;
130         int ch;
131
132         while ((ch = getopt(argc, argv, "dps:")) != EOF)
133                 switch (ch) {
134                         case 'd':
135                                 dflag++;
136                                 break;
137                                 
138                         case 'p':
139                                 pflag++;
140                                 break;
141
142                         case 's':
143                                 totsize = atoi(optarg);
144                                 break;
145                 }
146         argc -= optind;
147         argv += optind;
148
149         if (dflag && pflag)
150                 usage();
151         if (argc < 1)
152                 usage();
153         dp = getdiskbyname(*argv);
154         if (dp == NULL) {
155                 if (isatty(0))
156                         dp = promptfordisk(*argv);
157                 if (dp == NULL)
158                         errx(2, "%s: unknown disk type", *argv);
159         } else {
160                 if (dp->d_flags & D_REMOVABLE)
161                         tyname = "removable";
162                 else if (dp->d_flags & D_RAMDISK)
163                         tyname = "simulated";
164                 else
165                         tyname = "winchester";
166         }
167         spc = dp->d_secpercyl;
168         /*
169          * Bad sector table contains one track for the replicated
170          * copies of the table and enough full tracks preceding
171          * the last track to hold the pool of free blocks to which
172          * bad sectors are mapped.
173          * If disk size was specified explicitly, use specified size.
174          */
175         if (dp->d_type == DTYPE_SMD && dp->d_flags & D_BADSECT &&
176             totsize == 0) {
177                 badsecttable = dp->d_nsectors +
178                     roundup(badsecttable, dp->d_nsectors);
179                 threshhold = howmany(spc, badsecttable);
180         } else {
181                 badsecttable = 0;
182                 threshhold = 0;
183         }
184         /*
185          * If disk size was specified, recompute number of cylinders
186          * that may be used, and set badsecttable to any remaining
187          * fraction of the last cylinder.
188          */
189         if (totsize != 0) {
190                 dp->d_ncylinders = howmany(totsize, spc);
191                 badsecttable = spc * dp->d_ncylinders - totsize;
192         }
193
194         /*
195          * Figure out if disk is large enough for
196          * expanded swap area and 'd', 'e', and 'f'
197          * partitions.  Otherwise, use smaller defaults
198          * based on RK07.
199          */
200         for (def = 0; def < NDEFAULTS; def++) {
201                 curcyl = 0;
202                 for (part = PART('a'); part < NPARTITIONS; part++)
203                         curcyl += howmany(defpart[def][part], spc);
204                 if (curcyl < dp->d_ncylinders - threshhold)
205                         break;
206         }
207         if (def >= NDEFAULTS)
208                 errx(3, "%s: disk too small, calculate by hand", *argv);
209
210         /*
211          * Calculate number of cylinders allocated to each disk
212          * partition.  We may waste a bit of space here, but it's
213          * in the interest of (very backward) compatibility
214          * (for mixed disk systems).
215          */
216         for (curcyl = 0, part = PART('a'); part < NPARTITIONS; part++) {
217                 numcyls[part] = 0;
218                 if (defpart[def][part] != 0) {
219                         numcyls[part] = howmany(defpart[def][part], spc);
220                         curcyl += numcyls[part];
221                 }
222         }
223         numcyls[PART('f')] = dp->d_ncylinders - curcyl;
224         numcyls[PART('g')] =
225                 numcyls[PART('d')] + numcyls[PART('e')] + numcyls[PART('f')];
226         numcyls[PART('c')] = dp->d_ncylinders;
227         defpart[def][PART('f')] = numcyls[PART('f')] * spc - badsecttable;
228         defpart[def][PART('g')] = numcyls[PART('g')] * spc - badsecttable;
229         defpart[def][PART('c')] = numcyls[PART('c')] * spc;
230 #ifndef for_now
231         if (totsize || !pflag)
232 #else
233         if (totsize)
234 #endif
235                 defpart[def][PART('c')] -= badsecttable;
236
237         /*
238          * Calculate starting cylinder number for each partition.
239          * Note the 'h' partition is physically located before the
240          * 'g' or 'd' partition.  This is reflected in the layout
241          * arrays defined above.
242          */
243         for (layout = 0; layout < NLAYOUTS; layout++) {
244                 curcyl = 0;
245                 for (lp = layouts[layout]; *lp != 0; lp++) {
246                         startcyl[PART(*lp)] = curcyl;
247                         curcyl += numcyls[PART(*lp)];
248                 }
249         }
250
251         if (pflag) {
252                 printf("}, %s_sizes[%d] = {\n", dp->d_typename, NPARTITIONS);
253                 for (part = PART('a'); part < NPARTITIONS; part++) {
254                         if (numcyls[part] == 0) {
255                                 printf("\t0,\t0,\n");
256                                 continue;
257                         }
258                         if (dp->d_type != DTYPE_MSCP) {
259                                printf("\t%d,\t%d,\t\t/* %c=cyl %d thru %d */\n",
260                                         defpart[def][part], startcyl[part],
261                                         'A' + part, startcyl[part],
262                                         startcyl[part] + numcyls[part] - 1);
263                                 continue;
264                         }
265                         printf("\t%d,\t%d,\t\t/* %c=sectors %d thru %d */\n",
266                                 defpart[def][part], spc * startcyl[part],
267                                 'A' + part, spc * startcyl[part],
268                                 spc * startcyl[part] + defpart[def][part] - 1);
269                 }
270                 exit(0);
271         }
272         if (dflag) {
273                 int nparts;
274
275                 /*
276                  * In case the disk is in the ``in-between'' range
277                  * where the 'g' partition is smaller than the 'h'
278                  * partition, reverse the frag sizes so the /usr partition
279                  * is always set up with a frag size larger than the
280                  * user's partition.
281                  */
282                 if (defpart[def][PART('g')] < defpart[def][PART('h')]) {
283                         int temp;
284
285                         temp = defparam[PART('h')].p_fsize;
286                         defparam[PART('h')].p_fsize =
287                                 defparam[PART('g')].p_fsize;
288                         defparam[PART('g')].p_fsize = temp;
289                 }
290                 printf("%s:\\\n", dp->d_typename);
291                 printf("\t:ty=%s:ns#%d:nt#%d:nc#%d:", tyname,
292                         dp->d_nsectors, dp->d_ntracks, dp->d_ncylinders);
293                 if (dp->d_secpercyl != dp->d_nsectors * dp->d_ntracks)
294                         printf("sc#%d:", dp->d_secpercyl);
295                 if (dp->d_type == DTYPE_SMD && dp->d_flags & D_BADSECT)
296                         printf("sf:");
297                 printf("\\\n\t:dt=%s:", dktypenames[dp->d_type]);
298                 for (part = NDDATA - 1; part >= 0; part--)
299                         if (dp->d_drivedata[part])
300                                 break;
301                 for (j = 0; j <= part; j++)
302                         printf("d%d#%d:", j, dp->d_drivedata[j]);
303                 printf("\\\n");
304                 for (nparts = 0, part = PART('a'); part < NPARTITIONS; part++)
305                         if (defpart[def][part] != 0)
306                                 nparts++;
307                 for (part = PART('a'); part < NPARTITIONS; part++) {
308                         if (defpart[def][part] == 0)
309                                 continue;
310                         printf("\t:p%c#%d:", 'a' + part, defpart[def][part]);
311                         printf("o%c#%d:b%c#%d:f%c#%d:",
312                             'a' + part, spc * startcyl[part],
313                             'a' + part,
314                             defparam[part].p_frag * defparam[part].p_fsize,
315                             'a' + part, defparam[part].p_fsize);
316                         if (defparam[part].p_fstype == FS_SWAP)
317                                 printf("t%c=swap:", 'a' + part);
318                         nparts--;
319                         printf("%s\n", nparts > 0 ? "\\" : "");
320                 }
321 #ifdef for_now
322                 defpart[def][PART('c')] -= badsecttable;
323                 part = PART('c');
324                 printf("#\t:p%c#%d:", 'a' + part, defpart[def][part]);
325                 printf("o%c#%d:b%c#%d:f%c#%d:\n",
326                     'a' + part, spc * startcyl[part],
327                     'a' + part,
328                     defparam[part].p_frag * defparam[part].p_fsize,
329                     'a' + part, defparam[part].p_fsize);
330 #endif
331                 exit(0);
332         }
333         printf("%s: #sectors/track=%d, #tracks/cylinder=%d #cylinders=%d\n",
334                 dp->d_typename, dp->d_nsectors, dp->d_ntracks,
335                 dp->d_ncylinders);
336         printf("\n    Partition\t   Size\t Offset\t   Range\n");
337         for (part = PART('a'); part < NPARTITIONS; part++) {
338                 printf("\t%c\t", 'a' + part);
339                 if (numcyls[part] == 0) {
340                         printf(" unused\n");
341                         continue;
342                 }
343                 printf("%7d\t%7d\t%4d - %d%s\n",
344                         defpart[def][part], startcyl[part] * spc,
345                         startcyl[part], startcyl[part] + numcyls[part] - 1,
346                         defpart[def][part] % spc ? "*" : "");
347         }
348 }
349
350 static void
351 usage()
352 {
353         fprintf(stderr, "usage: diskpart [-p] [-d] [-s size] disk-type\n");
354         exit(1);
355 }
356
357 struct disklabel disk;
358
359 struct  field {
360         char            *f_name;
361         char            *f_defaults;
362         u_int32_t       *f_location;
363 } fields[] = {
364         { "sector size",                "512",  &disk.d_secsize },
365         { "#sectors/track",             0,      &disk.d_nsectors },
366         { "#tracks/cylinder",           0,      &disk.d_ntracks },
367         { "#cylinders",                 0,      &disk.d_ncylinders },
368         { 0, 0, 0 },
369 };
370
371 char *
372 mygets(buf)
373         char *buf;
374 {
375         size_t len;
376
377         if (fgets(buf, BUFSIZ, stdin) == NULL)
378                 buf[0] = '\0';
379         len = strlen(buf);
380         if (len != 0 && buf[len - 1] == '\n')
381                 buf[len - 1] = '\0';
382         return (buf);
383 }
384
385 struct disklabel *
386 promptfordisk(name)
387         char *name;
388 {
389         struct disklabel *dp = &disk;
390         struct field *fp;
391         int i;
392         char buf[BUFSIZ], **tp, *cp;
393
394         strncpy(dp->d_typename, name, sizeof(dp->d_typename));
395         fprintf(stderr,
396                 "%s: unknown disk type, want to supply parameters (y/n)? ",
397                 name);
398         (void) mygets(buf);
399         if (*buf != 'y')
400                 return ((struct disklabel *)0);
401         for (;;) {
402                 fprintf(stderr, "Disk/controller type (%s)? ", dktypenames[1]);
403                 (void) mygets(buf);
404                 if (buf[0] == 0) {
405                         dp->d_type = 1;
406                         break;
407                 }
408                 if ((i = gettype(buf, dktypenames)) >= 0) {
409                         dp->d_type = i;
410                         break;
411                 }
412                 fprintf(stderr, "%s: unrecognized controller type\n", buf);
413                 fprintf(stderr, "use one of:\n");
414                 for (tp = dktypenames; *tp; tp++)
415                         if (index(*tp, ' ') == 0)
416                                 fprintf(stderr, "\t%s\n", *tp);
417         }
418 gettype:
419         dp->d_flags = 0;
420         fprintf(stderr, "type (winchester|removable|simulated)? ");
421         (void) mygets(buf);
422         if (strcmp(buf, "removable") == 0)
423                 dp->d_flags = D_REMOVABLE;
424         else if (strcmp(buf, "simulated") == 0)
425                 dp->d_flags = D_RAMDISK;
426         else if (strcmp(buf, "winchester")) {
427                 fprintf(stderr, "%s: bad disk type\n", buf);
428                 goto gettype;
429         }
430         strncpy(dp->d_typename, buf, sizeof(dp->d_typename));
431         fprintf(stderr, "(type <cr> to get default value, if only one)\n");
432         if (dp->d_type == DTYPE_SMD)
433            fprintf(stderr, "Do %ss support bad144 bad block forwarding (yes)? ",
434                 dp->d_typename);
435         (void) mygets(buf);
436         if (*buf != 'n')
437                 dp->d_flags |= D_BADSECT;
438         for (fp = fields; fp->f_name != NULL; fp++) {
439 again:
440                 fprintf(stderr, "%s ", fp->f_name);
441                 if (fp->f_defaults != NULL)
442                         fprintf(stderr, "(%s)", fp->f_defaults);
443                 fprintf(stderr, "? ");
444                 cp = mygets(buf);
445                 if (*cp == '\0') {
446                         if (fp->f_defaults == NULL) {
447                                 fprintf(stderr, "no default value\n");
448                                 goto again;
449                         }
450                         cp = fp->f_defaults;
451                 }
452                 *fp->f_location = atol(cp);
453                 if (*fp->f_location == 0) {
454                         fprintf(stderr, "%s: bad value\n", cp);
455                         goto again;
456                 }
457         }
458         fprintf(stderr, "sectors/cylinder (%d)? ",
459             dp->d_nsectors * dp->d_ntracks);
460         (void) mygets(buf);
461         if (buf[0] == 0)
462                 dp->d_secpercyl = dp->d_nsectors * dp->d_ntracks;
463         else
464                 dp->d_secpercyl = atol(buf);
465         fprintf(stderr, "Drive-type-specific parameters, <cr> to terminate:\n");
466         for (i = 0; i < NDDATA; i++) {
467                 fprintf(stderr, "d%d? ", i);
468                 (void) mygets(buf);
469                 if (buf[0] == 0)
470                         break;
471                 dp->d_drivedata[i] = atol(buf);
472         }
473         return (dp);
474 }
475
476 gettype(t, names)
477         char *t;
478         char **names;
479 {
480         register char **nm;
481
482         for (nm = names; *nm; nm++)
483                 if (ustrcmp(t, *nm) == 0)
484                         return (nm - names);
485         if (isdigit(*t))
486                 return (atoi(t));
487         return (-1);
488 }
489
490 ustrcmp(s1, s2)
491         register char *s1, *s2;
492 {
493 #define lower(c)        (islower(c) ? (c) : tolower(c))
494
495         for (; *s1; s1++, s2++) {
496                 if (*s1 == *s2)
497                         continue;
498                 if (isalpha(*s1) && isalpha(*s2) &&
499                     lower(*s1) == lower(*s2))
500                         continue;
501                 return (*s2 - *s1);
502         }
503         return (0);
504 }