xref: /netbsd-src/usr.sbin/sunlabel/sunlabel.c (revision b8c616269f5ebf18ab2e35cb8099d683130a177c)
1 /* $NetBSD: sunlabel.c,v 1.9 2003/01/27 01:29:06 uwe Exp $ */
2 
3 /*-
4  * Copyright (c) 2002 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by der Mouse.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *        This product includes software developed by the NetBSD
21  *        Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 #include <sys/cdefs.h>
40 __RCSID("$NetBSD: sunlabel.c,v 1.9 2003/01/27 01:29:06 uwe Exp $");
41 
42 #include <stdio.h>
43 #include <errno.h>
44 #include <ctype.h>
45 #include <stdlib.h>
46 #include <unistd.h>
47 #include <termcap.h>
48 #include <strings.h>
49 #include <inttypes.h>
50 #include <err.h>
51 
52 #include <sys/file.h>
53 #include <sys/ioctl.h>
54 #include <sys/disklabel.h>
55 
56 /* If neither S_COMMAND nor NO_S_COMMAND is defined, guess. */
57 #if !defined(S_COMMAND) && !defined(NO_S_COMMAND)
58 #define S_COMMAND
59 #include <util.h>
60 #endif
61 
62 /*
63  * NPART is the total number of partitions.  This must be <= 43, given the
64  * amount of space available to store extended partitions. It also must be
65  * <=26, given the use of single letters to name partitions.  The 8 is the
66  * number of `standard' partitions; this arguably should be a #define, since
67  * it occurs not only here but scattered throughout the code.
68  */
69 #define NPART 16
70 #define NXPART (NPART - 8)
71 #define PARTLETTER(i) ((i) + 'a')
72 #define LETTERPART(i) ((i) - 'a')
73 
74 /*
75  * A partition.  We keep redundant information around, making sure
76  * that whenever we change one, we keep another constant and update
77  * the third.  Which one is which depends.  Arguably a partition
78  * should also know its partition number; here, if we need that we
79  * cheat, using (effectively) ptr-&label.partitions[0].
80  */
81 struct part {
82 	uint32_t    startcyl;
83 	uint32_t    nblk;
84 	uint32_t    endcyl;
85 };
86 
87 /*
88  * A label.  As the embedded comments indicate, much of this structure
89  * corresponds directly to Sun's struct dk_label.  Some of the values
90  * here are historical holdovers.  Apparently really old Suns did
91  * their own sparing in software, so a sector or two per cylinder,
92  * plus a whole cylinder or two at the end, got set aside as spares.
93  * acyl and apc count those spares, and this is also why ncyl and pcyl
94  * both exist.  These days the spares generally are hidden from the
95  * host by the disk, and there's no reason not to set
96  * ncyl=pcyl=ceil(device size/spc) and acyl=apc=0.
97  *
98  * Note also that the geometry assumptions behind having nhead and
99  * nsect assume that the sect/trk and trk/cyl values are constant
100  * across the whole drive.  The latter is still usually true; the
101  * former isn't.  In my experience, you can just put fixed values
102  * here; the basis for software knowing the drive geometry is also
103  * mostly invalid these days anyway.  (I just use nhead=32 nsect=64,
104  * which gives me 1M "cylinders", a convenient size.)
105  */
106 struct label {
107 	/* BEGIN fields taken directly from struct dk_label */
108 	char asciilabel[128];
109 	uint32_t rpm;	/* Spindle rotation speed - useless now */
110 	uint32_t pcyl;	/* Physical cylinders */
111 	uint32_t apc;	/* Alternative sectors per cylinder */
112 	uint32_t obs1;	/* Obsolete? */
113 	uint32_t obs2;	/* Obsolete? */
114 	uint32_t intrlv;	/* Interleave - never anything but 1 IME */
115 	uint32_t ncyl;	/* Number of usable cylinders */
116 	uint32_t acyl;	/* Alternative cylinders - pcyl minus ncyl */
117 	uint32_t nhead;	/* Tracks-per-cylinder (usually # of heads) */
118 	uint32_t nsect;	/* Sectors-per-track */
119 	uint32_t obs3;	/* Obsolete? */
120 	uint32_t obs4;	/* Obsolete? */
121 	/* END fields taken directly from struct dk_label */
122 	uint32_t spc;	/* Sectors per cylinder - nhead*nsect */
123 	uint32_t dirty:1;/* Modified since last read */
124 	struct part partitions[NPART];/* The partitions themselves */
125 };
126 
127 /*
128  * Describes a field in the label.
129  *
130  * tag is a short name for the field, like "apc" or "nsect".  loc is a
131  * pointer to the place in the label where it's stored.  print is a
132  * function to print the value; the second argument is the current
133  * column number, and the return value is the new current column
134  * number.  (This allows print functions to do proper line wrapping.)
135  * chval is called to change a field; the first argument is the
136  * command line portion that contains the new value (in text form).
137  * The chval function is responsible for parsing and error-checking as
138  * well as doing the modification.  changed is a function which does
139  * field-specific actions necessary when the field has been changed.
140  * This could be rolled into the chval function, but I believe this
141  * way provides better code sharing.
142  *
143  * Note that while the fields in the label vary in size (8, 16, or 32
144  * bits), we store everything as ints in the label struct, above, and
145  * convert when packing and unpacking.  This allows us to have only
146  * one numeric chval function.
147  */
148 struct field {
149 	const char *tag;
150 	void *loc;
151 	int (*print)(struct field *, int);
152 	void (*chval)(const char *, struct field *);
153 	void (*changed)(void);
154 	int taglen;
155 };
156 
157 /* LABEL_MAGIC was chosen by Sun and cannot be trivially changed. */
158 #define LABEL_MAGIC 0xdabe
159 /*
160  * LABEL_XMAGIC needs to agree between here and any other code that uses
161  * extended partitions (mainly the kernel).
162  */
163 #define LABEL_XMAGIC (0x199d1fe2+8)
164 
165 static int diskfd;			/* fd on the disk */
166 static const char *diskname;		/* name of the disk, for messages */
167 static int readonly;			/* true iff it's open RO */
168 static unsigned char labelbuf[512];	/* Buffer holding the label sector */
169 static struct label label;		/* The label itself. */
170 static int fixmagic;			/* -m, ignore bad magic #s */
171 static int fixcksum;			/* -s, ignore bad cksums */
172 static int newlabel;			/* -n, ignore all on-disk values */
173 static int quiet;			/* -q, don't print chatter */
174 
175 /*
176  * The various functions that go in the field function pointers.  The
177  * _ascii functions are for 128-byte string fields (the ASCII label);
178  * the _int functions are for int-valued fields (everything else).
179  * update_spc is a `changed' function for updating the spc value when
180  * changing one of the two values that make it up.
181  */
182 static int print_ascii(struct field *, int);
183 static void chval_ascii(const char *, struct field *);
184 static int print_int(struct field *, int);
185 static void chval_int(const char *, struct field *);
186 static void update_spc(void);
187 
188 int  main(int, char **);
189 
190 /* The fields themselves. */
191 static struct field fields[] =
192 {
193 	{"ascii", &label.asciilabel[0], print_ascii, chval_ascii, 0},
194 	{"rpm", &label.rpm, print_int, chval_int, 0},
195 	{"pcyl", &label.pcyl, print_int, chval_int, 0},
196 	{"apc", &label.apc, print_int, chval_int, 0},
197 	{"obs1", &label.obs1, print_int, chval_int, 0},
198 	{"obs2", &label.obs2, print_int, chval_int, 0},
199 	{"intrlv", &label.intrlv, print_int, chval_int, 0},
200 	{"ncyl", &label.ncyl, print_int, chval_int, 0},
201 	{"acyl", &label.acyl, print_int, chval_int, 0},
202 	{"nhead", &label.nhead, print_int, chval_int, update_spc},
203 	{"nsect", &label.nsect, print_int, chval_int, update_spc},
204 	{"obs3", &label.obs3, print_int, chval_int, 0},
205 	{"obs4", &label.obs4, print_int, chval_int, 0},
206 	{NULL, NULL, NULL, NULL, 0}
207 };
208 
209 /*
210  * We'd _like_ to use howmany() from the include files, but can't count
211  *  on its being present or working.
212  */
213 static __inline__ uint32_t how_many(uint32_t amt, uint32_t unit)
214     __attribute__((__const__));
215 static __inline__ uint32_t
216 how_many(uint32_t amt, uint32_t unit)
217 {
218 	return ((amt + unit - 1) / unit);
219 }
220 
221 /*
222  * Try opening the disk, given a name.  If mustsucceed is true, we
223  *  "cannot fail"; failures produce gripe-and-exit, and if we return,
224  *  our return value is 1.  Otherwise, we return 1 on success and 0 on
225  *  failure.
226  */
227 static int
228 trydisk(const char *s, int mustsucceed)
229 {
230 	int ro = 0;
231 
232 	diskname = s;
233 	if ((diskfd = open(s, O_RDWR)) == -1 ||
234 	    (diskfd = open(s, O_RDWR | O_NDELAY)) == -1) {
235 		if ((diskfd = open(s, O_RDONLY)) == -1) {
236 			if (mustsucceed)
237 				err(1, "Cannot open `%s'", s);
238 			else
239 				return 0;
240 		}
241 		ro = 1;
242 	}
243 	if (ro && !quiet)
244 		warnx("No write access, label is readonly");
245 	readonly = ro;
246 	return 1;
247 }
248 
249 /*
250  * Set the disk device, given the user-supplied string.  Note that even
251  * if we malloc, we never free, because either trydisk eventually
252  * succeeds, in which case the string is saved in diskname, or it
253  * fails, in which case we exit and freeing is irrelevant.
254  */
255 static void
256 setdisk(const char *s)
257 {
258 	char *tmp;
259 
260 	if (strchr(s, '/')) {
261 		trydisk(s, 1);
262 		return;
263 	}
264 	if (trydisk(s, 0))
265 		return;
266 #ifndef DISTRIB /* native tool: search in /dev */
267 	tmp = malloc(strlen(s) + 7);
268 	sprintf(tmp, "/dev/%s", s);
269 	if (trydisk(tmp, 0))
270 		return;
271 	sprintf(tmp, "/dev/%s%c", s, getrawpartition() + 'a');
272 	if (trydisk(tmp, 0))
273 		return;
274 #endif
275 	errx(1, "Can't find device for disk `%s'", s);
276 }
277 
278 static void usage(void) __attribute__((__noreturn__));
279 static void
280 usage(void)
281 {
282 	(void)fprintf(stderr, "Usage: %s [-mnqs] disk\n", getprogname());
283 	exit(1);
284 }
285 
286 /*
287  * Command-line arguments.  We can have at most one non-flag
288  *  argument, which is the disk name; we can also have flags
289  *
290  *	-m
291  *		Turns on fixmagic, which causes bad magic numbers to be
292  *		ignored (though a complaint is still printed), rather
293  *		than being fatal errors.
294  *
295  *	-s
296  *		Turns on fixcksum, which causes bad checksums to be
297  *		ignored (though a complaint is still printed), rather
298  *		than being fatal errors.
299  *
300  *	-n
301  *		Turns on newlabel, which means we're creating a new
302  *		label and anything in the label sector should be
303  *		ignored.  This is a bit like -m -s, except that it
304  *		doesn't print complaints and it ignores possible
305  *		garbage on-disk.
306  *
307  *	-q
308  *		Turns on quiet, which suppresses printing of prompts
309  *		and other irrelevant chatter.  If you're trying to use
310  *		sunlabel in an automated way, you probably want this.
311  */
312 static void
313 handleargs(int ac, char **av)
314 {
315 	int c;
316 
317 	while ((c = getopt(ac, av, "mnqs")) != -1) {
318 		switch (c) {
319 		case 'm':
320 			fixmagic++;
321 			break;
322 		case 'n':
323 			newlabel++;
324 			break;
325 		case 'q':
326 			quiet++;
327 			break;
328 		case 's':
329 			fixcksum++;
330 			break;
331 		case '?':
332 			warnx("Illegal option `%c'", c);
333 			usage();
334 		}
335 	}
336 	ac -= optind;
337 	av += optind;
338 	if (ac != 1)
339 		usage();
340 	setdisk(av[0]);
341 }
342 
343 /*
344  * Sets the ending cylinder for a partition.  This exists mainly to
345  * centralize the check.  (If spc is zero, cylinder numbers make
346  * little sense, and the code would otherwise die on divide-by-0 if we
347  * barged blindly ahead.)  We need to call this on a partition
348  * whenever we change it; we need to call it on all partitions
349  * whenever we change spc.
350  */
351 static void
352 set_endcyl(struct part *p)
353 {
354 	if (label.spc == 0) {
355 		p->endcyl = p->startcyl;
356 	} else {
357 		p->endcyl = p->startcyl + how_many(p->nblk, label.spc);
358 	}
359 }
360 
361 /*
362  * Unpack a label from disk into the in-core label structure.  If
363  * newlabel is set, we don't actually do so; we just synthesize a
364  * blank label instead.  This is where knowledge of the Sun label
365  * format is kept for read; pack_label is the corresponding routine
366  * for write.  We are careful to use labelbuf, l_s, or l_l as
367  * appropriate to avoid byte-sex issues, so we can work on
368  * little-endian machines.
369  *
370  * Note that a bad magic number for the extended partition information
371  * is not considered an error; it simply indicates there is no
372  * extended partition information.  Arguably this is the Wrong Thing,
373  * and we should take zero as meaning no info, and anything other than
374  * zero or LABEL_XMAGIC as reason to gripe.
375  */
376 static const char *
377 unpack_label(void)
378 {
379 	unsigned short int l_s[256];
380 	unsigned long int l_l[128];
381 	int i;
382 	unsigned long int sum;
383 	int have_x;
384 
385 	if (newlabel) {
386 		bzero(&label.asciilabel[0], 128);
387 		label.rpm = 0;
388 		label.pcyl = 0;
389 		label.apc = 0;
390 		label.obs1 = 0;
391 		label.obs2 = 0;
392 		label.intrlv = 0;
393 		label.ncyl = 0;
394 		label.acyl = 0;
395 		label.nhead = 0;
396 		label.nsect = 0;
397 		label.obs3 = 0;
398 		label.obs4 = 0;
399 		for (i = 0; i < NPART; i++) {
400 			label.partitions[i].startcyl = 0;
401 			label.partitions[i].nblk = 0;
402 			set_endcyl(&label.partitions[i]);
403 		}
404 		label.spc = 0;
405 		label.dirty = 1;
406 		return (0);
407 	}
408 	for (i = 0; i < 256; i++)
409 		l_s[i] = (labelbuf[i + i] << 8) | labelbuf[i + i + 1];
410 	for (i = 0; i < 128; i++)
411 		l_l[i] = (l_s[i + i] << 16) | l_s[i + i + 1];
412 	if (l_s[254] != LABEL_MAGIC) {
413 		if (fixmagic) {
414 			label.dirty = 1;
415 			warnx("ignoring incorrect magic number.");
416 		} else {
417 			return "bad magic number";
418 		}
419 	}
420 	sum = 0;
421 	for (i = 0; i < 256; i++)
422 		sum ^= l_s[i];
423 	label.dirty = 0;
424 	if (sum != 0) {
425 		if (fixcksum) {
426 			label.dirty = 1;
427 			warnx("ignoring incorrect checksum.");
428 		} else {
429 			return "checksum wrong";
430 		}
431 	}
432 	(void)memcpy(&label.asciilabel[0], &labelbuf[0], 128);
433 	label.rpm = l_s[210];
434 	label.pcyl = l_s[211];
435 	label.apc = l_s[212];
436 	label.obs1 = l_s[213];
437 	label.obs2 = l_s[214];
438 	label.intrlv = l_s[215];
439 	label.ncyl = l_s[216];
440 	label.acyl = l_s[217];
441 	label.nhead = l_s[218];
442 	label.nsect = l_s[219];
443 	label.obs3 = l_s[220];
444 	label.obs4 = l_s[221];
445 	label.spc = label.nhead * label.nsect;
446 	for (i = 0; i < 8; i++) {
447 		label.partitions[i].startcyl = (uint32_t)l_l[i + i + 111];
448 		label.partitions[i].nblk = (uint32_t)l_l[i + i + 112];
449 		set_endcyl(&label.partitions[i]);
450 	}
451 	have_x = 0;
452 	if (l_l[33] == LABEL_XMAGIC) {
453 		sum = 0;
454 		for (i = 0; i < ((NXPART * 2) + 1); i++)
455 			sum += l_l[33 + i];
456 		if (sum != l_l[32]) {
457 			if (fixcksum) {
458 				label.dirty = 1;
459 				warnx("Ignoring incorrect extended-partition checksum.");
460 				have_x = 1;
461 			} else {
462 				warnx("Extended-partition magic right but checksum wrong.");
463 			}
464 		} else {
465 			have_x = 1;
466 		}
467 	}
468 	if (have_x) {
469 		for (i = 0; i < NXPART; i++) {
470 			int j = i + i + 34;
471 			label.partitions[i + 8].startcyl = (uint32_t)l_l[j++];
472 			label.partitions[i + 8].nblk = (uint32_t)l_l[j++];
473 			set_endcyl(&label.partitions[i + 8]);
474 		}
475 	} else {
476 		for (i = 0; i < NXPART; i++) {
477 			label.partitions[i + 8].startcyl = 0;
478 			label.partitions[i + 8].nblk = 0;
479 			set_endcyl(&label.partitions[i + 8]);
480 		}
481 	}
482 	return 0;
483 }
484 
485 /*
486  * Pack a label from the in-core label structure into on-disk format.
487  * This is where knowledge of the Sun label format is kept for write;
488  * unpack_label is the corresponding routine for read.  If all
489  * partitions past the first 8 are size=0 cyl=0, we store all-0s in
490  * the extended partition space, to be fully compatible with Sun
491  * labels.  Since AFIAK nothing works in that case that would break if
492  * we put extended partition info there in the same format we'd use if
493  * there were real info there, this is arguably unnecessary, but it's
494  * easy to do.
495  *
496  * We are careful to avoid endianness issues by constructing everything
497  * in an array of shorts.  We do this rather than using chars or longs
498  * because the checksum is defined in terms of shorts; using chars or
499  * longs would simplify small amounts of code at the price of
500  * complicating more.
501  */
502 static void
503 pack_label(void)
504 {
505 	unsigned short int l_s[256];
506 	int i;
507 	unsigned short int sum;
508 
509 	memset(&l_s[0], 0, 512);
510 	memcpy(&labelbuf[0], &label.asciilabel[0], 128);
511 	for (i = 0; i < 64; i++)
512 		l_s[i] = (labelbuf[i + i] << 8) | labelbuf[i + i + 1];
513 	l_s[210] = label.rpm;
514 	l_s[211] = label.pcyl;
515 	l_s[212] = label.apc;
516 	l_s[213] = label.obs1;
517 	l_s[214] = label.obs2;
518 	l_s[215] = label.intrlv;
519 	l_s[216] = label.ncyl;
520 	l_s[217] = label.acyl;
521 	l_s[218] = label.nhead;
522 	l_s[219] = label.nsect;
523 	l_s[220] = label.obs3;
524 	l_s[221] = label.obs4;
525 	for (i = 0; i < 8; i++) {
526 		l_s[(i * 4) + 222] = label.partitions[i].startcyl >> 16;
527 		l_s[(i * 4) + 223] = label.partitions[i].startcyl & 0xffff;
528 		l_s[(i * 4) + 224] = label.partitions[i].nblk >> 16;
529 		l_s[(i * 4) + 225] = label.partitions[i].nblk & 0xffff;
530 	}
531 	for (i = 0; i < NXPART; i++) {
532 		if (label.partitions[i + 8].startcyl ||
533 		    label.partitions[i + 8].nblk)
534 			break;
535 	}
536 	if (i < NXPART) {
537 		unsigned long int xsum;
538 		l_s[66] = LABEL_XMAGIC >> 16;
539 		l_s[67] = LABEL_XMAGIC & 0xffff;
540 		for (i = 0; i < NXPART; i++) {
541 			int j = (i * 4) + 68;
542 			l_s[j++] = label.partitions[i + 8].startcyl >> 16;
543 			l_s[j++] = label.partitions[i + 8].startcyl & 0xffff;
544 			l_s[j++] = label.partitions[i + 8].nblk >> 16;
545 			l_s[j++] = label.partitions[i + 8].nblk & 0xffff;
546 		}
547 		xsum = 0;
548 		for (i = 0; i < ((NXPART * 2) + 1); i++)
549 			xsum += (l_s[i + i + 66] << 16) | l_s[i + i + 67];
550 		l_s[64] = (int32_t)(xsum >> 16);
551 		l_s[65] = (int32_t)(xsum & 0xffff);
552 	}
553 	l_s[254] = LABEL_MAGIC;
554 	sum = 0;
555 	for (i = 0; i < 255; i++)
556 		sum ^= l_s[i];
557 	l_s[255] = sum;
558 	for (i = 0; i < 256; i++) {
559 		labelbuf[i + i] = ((uint32_t)l_s[i]) >> 8;
560 		labelbuf[i + i + 1] = l_s[i] & 0xff;
561 	}
562 }
563 
564 /*
565  * Get the label.  Read it off the disk and unpack it.  This function
566  *  is nothing but lseek, read, unpack_label, and error checking.
567  */
568 static void
569 getlabel(void)
570 {
571 	int rv;
572 	const char *lerr;
573 
574 	if (lseek(diskfd, (off_t)0, L_SET) == (off_t)-1)
575 		err(1, "lseek to 0 on `%s' failed", diskname);
576 
577 	if ((rv = read(diskfd, &labelbuf[0], 512)) == -1)
578 		err(1, "read label from `%s' failed", diskname);
579 
580 	if (rv != 512)
581 		errx(1, "short read from `%s' wanted %d, got %d.", diskname,
582 		    512, rv);
583 
584 	lerr = unpack_label();
585 	if (lerr)
586 		errx(1, "bogus label on `%s' (%s)", diskname, lerr);
587 }
588 
589 /*
590  * Put the label.  Pack it and write it to the disk.  This function is
591  *  little more than pack_label, lseek, write, and error checking.
592  */
593 static void
594 putlabel(void)
595 {
596 	int rv;
597 
598 	if (readonly) {
599 		warnx("No write access to `%s'", diskname);
600 		return;
601 	}
602 
603 	if (lseek(diskfd, (off_t)0, L_SET) < (off_t)-1)
604 		err(1, "lseek to 0 on `%s' failed", diskname);
605 
606 	pack_label();
607 
608 	if ((rv = write(diskfd, &labelbuf[0], 512)) == -1) {
609 		err(1, "write label to `%s' failed", diskname);
610 		exit(1);
611 	}
612 
613 	if (rv != 512)
614 		errx(1, "short write to `%s': wanted %d, got %d",
615 		    diskname, 512, rv);
616 
617 	label.dirty = 0;
618 }
619 
620 /*
621  * Skip whitespace.  Used several places in the command-line parsing
622  * code.
623  */
624 static void
625 skipspaces(const char **cpp)
626 {
627 	const char *cp = *cpp;
628 	while (*cp && isspace((unsigned char)*cp))
629 		cp++;
630 	*cpp = cp;
631 }
632 
633 /*
634  * Scan a number.  The first arg points to the char * that's moving
635  *  along the string.  The second arg points to where we should store
636  *  the result.  The third arg says what we're scanning, for errors.
637  *  The return value is 0 on error, or nonzero if all goes well.
638  */
639 static int
640 scannum(const char **cpp, uint32_t *np, const char *tag)
641 {
642 	uint32_t v;
643 	int nd;
644 	const char *cp;
645 
646 	skipspaces(cpp);
647 	v = 0;
648 	nd = 0;
649 
650 	cp = *cpp;
651 	while (*cp && isdigit(*cp)) {
652 		v = (10 * v) + (*cp++ - '0');
653 		nd++;
654 	}
655 	*cpp = cp;
656 
657 	if (nd == 0) {
658 		printf("Missing/invalid %s: %s\n", tag, cp);
659 		return (0);
660 	}
661 	*np = v;
662 	return (1);
663 }
664 
665 /*
666  * Change a partition.  pno is the number of the partition to change;
667  *  numbers is a pointer to the string containing the specification for
668  *  the new start and size.  This always takes the form "start size",
669  *  where start can be
670  *
671  *	a number
672  *		The partition starts at the beginning of that cylinder.
673  *
674  *	start-X
675  *		The partition starts at the same place partition X does.
676  *
677  *	end-X
678  *		The partition starts at the place partition X ends.  If
679  *		partition X does not exactly on a cylinder boundary, it
680  *		is effectively rounded up.
681  *
682  *  and size can be
683  *
684  *	a number
685  *		The partition is that many sectors long.
686  *
687  *	num/num/num
688  *		The three numbers are cyl/trk/sect counts.  n1/n2/n3 is
689  *		equivalent to specifying a single number
690  *		((n1*label.nhead)+n2)*label.nsect)+n3.  In particular,
691  *		if label.nhead or label.nsect is zero, this has limited
692  *		usefulness.
693  *
694  *	end-X
695  *		The partition ends where partition X ends.  It is an
696  *		error for partition X to end before the specified start
697  *		point.  This always goes to exactly where partition X
698  *		ends, even if that's partway through a cylinder.
699  *
700  *	start-X
701  *		The partition extends to end exactly where partition X
702  *		begins.  It is an error for partition X to begin before
703  *		the specified start point.
704  *
705  *	size-X
706  *		The partition has the same size as partition X.
707  *
708  * If label.spc is nonzero but the partition size is not a multiple of
709  *  it, a warning is printed, since you usually don't want this.  Most
710  *  often, in my experience, this comes from specifying a cylinder
711  *  count as a single number N instead of N/0/0.
712  */
713 static void
714 chpart(int pno, const char *numbers)
715 {
716 	uint32_t cyl0;
717 	uint32_t size;
718 	uint32_t sizec;
719 	uint32_t sizet;
720 	uint32_t sizes;
721 
722 	skipspaces(&numbers);
723 	if (!memcmp(numbers, "end-", 4) && numbers[4]) {
724 		int epno = LETTERPART(numbers[4]);
725 		if ((epno >= 0) && (epno < NPART)) {
726 			cyl0 = label.partitions[epno].endcyl;
727 			numbers += 5;
728 		} else {
729 			if (!scannum(&numbers, &cyl0, "starting cylinder"))
730 				return;
731 		}
732 	} else if (!memcmp(numbers, "start-", 6) && numbers[6]) {
733 		int spno = LETTERPART(numbers[6]);
734 		if ((spno >= 0) && (spno < NPART)) {
735 			cyl0 = label.partitions[spno].startcyl;
736 			numbers += 7;
737 		} else {
738 			if (!scannum(&numbers, &cyl0, "starting cylinder"))
739 				return;
740 		}
741 	} else {
742 		if (!scannum(&numbers, &cyl0, "starting cylinder"))
743 			return;
744 	}
745 	skipspaces(&numbers);
746 	if (!memcmp(numbers, "end-", 4) && numbers[4]) {
747 		int epno = LETTERPART(numbers[4]);
748 		if ((epno >= 0) && (epno < NPART)) {
749 			if (label.partitions[epno].endcyl <= cyl0) {
750 				warnx("Partition %c ends before cylinder %u",
751 				    PARTLETTER(epno), cyl0);
752 				return;
753 			}
754 			size = label.partitions[epno].nblk;
755 			/* Be careful of unsigned arithmetic */
756 			if (cyl0 > label.partitions[epno].startcyl) {
757 				size -= (cyl0 - label.partitions[epno].startcyl)
758 				    * label.spc;
759 			} else if (cyl0 < label.partitions[epno].startcyl) {
760 				size += (label.partitions[epno].startcyl - cyl0)
761 				    * label.spc;
762 			}
763 			numbers += 5;
764 		} else {
765 			if (!scannum(&numbers, &size, "partition size"))
766 				return;
767 		}
768 	} else if (!memcmp(numbers, "start-", 6) && numbers[6]) {
769 		int  spno = LETTERPART(numbers[6]);
770 		if ((spno >= 0) && (spno < NPART)) {
771 			if (label.partitions[spno].startcyl <= cyl0) {
772 				warnx("Partition %c starts before cylinder %u",
773 				    PARTLETTER(spno), cyl0);
774 				return;
775 			}
776 			size = (label.partitions[spno].startcyl - cyl0)
777 			    * label.spc;
778 			numbers += 7;
779 		} else {
780 			if (!scannum(&numbers, &size, "partition size"))
781 				return;
782 		}
783 	} else if (!memcmp(numbers, "size-", 5) && numbers[5]) {
784 		int spno = LETTERPART(numbers[5]);
785 		if ((spno >= 0) && (spno < NPART)) {
786 			size = label.partitions[spno].nblk;
787 			numbers += 6;
788 		} else {
789 			if (!scannum(&numbers, &size, "partition size"))
790 				return;
791 		}
792 	} else {
793 		if (!scannum(&numbers, &size, "partition size"))
794 			return;
795 		skipspaces(&numbers);
796 		if (*numbers == '/') {
797 			sizec = size;
798 			numbers++;
799 			if (!scannum(&numbers, &sizet,
800 			    "partition size track value"))
801 				return;
802 			skipspaces(&numbers);
803 			if (*numbers != '/') {
804 				warnx("Invalid c/t/s syntax - no second slash");
805 				return;
806 			}
807 			numbers++;
808 			if (!scannum(&numbers, &sizes,
809 			    "partition size sector value"))
810 				return;
811 			size = sizes + (label.nsect * (sizet
812 			    + (label.nhead * sizec)));
813 		}
814 	}
815 	if (label.spc && (size % label.spc)) {
816 		warnx("Size is not a multiple of cylinder size (is %u/%u/%u)",
817 		    size / label.spc,
818 		    (size % label.spc) / label.nsect, size % label.nsect);
819 	}
820 	label.partitions[pno].startcyl = cyl0;
821 	label.partitions[pno].nblk = size;
822 	set_endcyl(&label.partitions[pno]);
823 	if ((label.partitions[pno].startcyl * label.spc)
824 	    + label.partitions[pno].nblk > label.spc * label.ncyl) {
825 		warnx("Partition extends beyond end of disk");
826 	}
827 	label.dirty = 1;
828 }
829 
830 /*
831  * Change a 128-byte-string field.  There's currently only one such,
832  *  the ASCII label field.
833  */
834 static void
835 chval_ascii(const char *cp, struct field *f)
836 {
837 	const char *nl;
838 
839 	skipspaces(&cp);
840 	if ((nl = strchr(cp, '\n')) == NULL)
841 		nl = cp + strlen(cp);
842 	if (nl - cp > 128) {
843 		warnx("Ascii label string too long - max 128 characters");
844 	} else {
845 		memset(f->loc, 0, 128);
846 		memcpy(f->loc, cp, (size_t)(nl - cp));
847 		label.dirty = 1;
848 	}
849 }
850 /*
851  * Change an int-valued field.  As noted above, there's only one
852  *  function, regardless of the field size in the on-disk label.
853  */
854 static void
855 chval_int(const char *cp, struct field *f)
856 {
857 	uint32_t v;
858 
859 	if (!scannum(&cp, &v, "value"))
860 		return;
861 	*(uint32_t *)f->loc = v;
862 	label.dirty = 1;
863 }
864 /*
865  * Change a field's value.  The string argument contains the field name
866  *  and the new value in text form.  Look up the field and call its
867  *  chval and changed functions.
868  */
869 static void
870 chvalue(const char *str)
871 {
872 	const char *cp;
873 	int i;
874 	size_t n;
875 
876 	if (fields[0].taglen < 1) {
877 		for (i = 0; fields[i].tag; i++)
878 			fields[i].taglen = strlen(fields[i].tag);
879 	}
880 	skipspaces(&str);
881 	cp = str;
882 	while (*cp && !isspace(*cp))
883 		cp++;
884 	n = cp - str;
885 	for (i = 0; fields[i].tag; i++) {
886 		if ((n == fields[i].taglen) && !memcmp(str, fields[i].tag, n)) {
887 			(*fields[i].chval) (cp, &fields[i]);
888 			if (fields[i].changed)
889 				(*fields[i].changed)();
890 			break;
891 		}
892 	}
893 	if (!fields[i].tag)
894 		warnx("Bad name %.*s - see L output for names", (int)n, str);
895 }
896 
897 /*
898  * `changed' function for the ntrack and nsect fields; update label.spc
899  *  and call set_endcyl on all partitions.
900  */
901 static void
902 update_spc(void)
903 {
904 	int i;
905 
906 	label.spc = label.nhead * label.nsect;
907 	for (i = 0; i < NPART; i++)
908 		set_endcyl(&label.partitions[i]);
909 }
910 
911 /*
912  * Print function for 128-byte-string fields.  Currently only the ASCII
913  *  label, but we don't depend on that.
914  */
915 static int
916 /*ARGSUSED*/
917 print_ascii(struct field *f, int sofar __attribute__((__unused__)))
918 {
919 	printf("%s: %.128s\n", f->tag, (char *)f->loc);
920 	return 0;
921 }
922 
923 /*
924  * Print an int-valued field.  We are careful to do proper line wrap,
925  *  making each value occupy 16 columns.
926  */
927 static int
928 print_int(struct field *f, int sofar)
929 {
930 	if (sofar >= 60) {
931 		printf("\n");
932 		sofar = 0;
933 	}
934 	printf("%s: %-*u", f->tag, 14 - (int)strlen(f->tag),
935 	    *(uint32_t *)f->loc);
936 	return sofar + 16;
937 }
938 
939 /*
940  * Print the whole label.  Just call the print function for each field,
941  *  then append a newline if necessary.
942  */
943 static void
944 print_label(void)
945 {
946 	int i;
947 	int c;
948 
949 	c = 0;
950 	for (i = 0; fields[i].tag; i++)
951 		c = (*fields[i].print) (&fields[i], c);
952 	if (c > 0)
953 		printf("\n");
954 }
955 
956 /*
957  * Figure out how many columns wide the screen is.  We impose a minimum
958  *  width of 20 columns; I suspect the output code has some issues if
959  *  we have fewer columns than partitions.
960  */
961 static int
962 screen_columns(void)
963 {
964 	int ncols;
965 #ifndef NO_TERMCAP_WIDTH
966 	char *term;
967 	char tbuf[1024];
968 #endif
969 #if defined(TIOCGWINSZ)
970 	struct winsize wsz;
971 #elif defined(TIOCGSIZE)
972 	struct ttysize tsz;
973 #endif
974 
975 	ncols = 80;
976 #ifndef NO_TERMCAP_WIDTH
977 	term = getenv("TERM");
978 	if (term && (tgetent(&tbuf[0], term) == 1)) {
979 		int n = tgetnum("co");
980 		if (n > 1)
981 			ncols = n;
982 	}
983 #endif
984 #if defined(TIOCGWINSZ)
985 	if ((ioctl(1, TIOCGWINSZ, &wsz) == 0) && (wsz.ws_col > 0)) {
986 		ncols = wsz.ws_col;
987 	}
988 #elif defined(TIOCGSIZE)
989 	if ((ioctl(1, TIOCGSIZE, &tsz) == 0) && (tsz.ts_cols > 0)) {
990 		ncols = tsz.ts_cols;
991 	}
992 #endif
993 	if (ncols < 20)
994 		ncols = 20;
995 	return ncols;
996 }
997 
998 /*
999  * Print the partitions.  The argument is true iff we should print all
1000  * partitions, even those set start=0 size=0.  We generate one line
1001  * per partition (or, if all==0, per `interesting' partition), plus a
1002  * visually graphic map of partition letters.  Most of the hair in the
1003  * visual display lies in ensuring that nothing takes up less than one
1004  * character column, that if two boundaries appear visually identical,
1005  * they _are_ identical.  Within that constraint, we try to make the
1006  * number of character columns proportional to the size....
1007  */
1008 static void
1009 print_part(int all)
1010 {
1011 	int i, j, k, n, r, c;
1012 	size_t ncols;
1013 	uint32_t edges[2 * NPART];
1014 	int ce[2 * NPART];
1015 	int row[NPART];
1016 	unsigned char table[2 * NPART][NPART];
1017 	char *line;
1018 	struct part *p = label.partitions;
1019 
1020 	for (i = 0; i < NPART; i++) {
1021 		if (all || p[i].startcyl || p[i].nblk) {
1022 			printf("%c: start cyl = %6u, size = %8u (",
1023 			    PARTLETTER(i), p[i].startcyl, p[i].nblk);
1024 			if (label.spc) {
1025 				printf("%u/%u/%u - ", p[i].nblk / label.spc,
1026 				    (p[i].nblk % label.spc) / label.nsect,
1027 				    p[i].nblk % label.nsect);
1028 			}
1029 			printf("%gMb)\n", p[i].nblk / 2048.0);
1030 		}
1031 	}
1032 
1033 	j = 0;
1034 	for (i = 0; i < NPART; i++) {
1035 		if (p[i].nblk > 0) {
1036 			edges[j++] = p[i].startcyl;
1037 			edges[j++] = p[i].endcyl;
1038 		}
1039 	}
1040 
1041 	do {
1042 		n = 0;
1043 		for (i = 1; i < j; i++) {
1044 			if (edges[i] < edges[i - 1]) {
1045 				uint32_t    t;
1046 				t = edges[i];
1047 				edges[i] = edges[i - 1];
1048 				edges[i - 1] = t;
1049 				n++;
1050 			}
1051 		}
1052 	} while (n > 0);
1053 
1054 	for (i = 1; i < j; i++) {
1055 		if (edges[i] != edges[n]) {
1056 			n++;
1057 			if (n != i)
1058 				edges[n] = edges[i];
1059 		}
1060 	}
1061 
1062 	n++;
1063 	for (i = 0; i < NPART; i++) {
1064 		if (p[i].nblk > 0) {
1065 			for (j = 0; j < n; j++) {
1066 				if ((p[i].startcyl <= edges[j]) &&
1067 				    (p[i].endcyl > edges[j])) {
1068 					table[j][i] = 1;
1069 				} else {
1070 					table[j][i] = 0;
1071 				}
1072 			}
1073 		}
1074 	}
1075 
1076 	ncols = screen_columns() - 2;
1077 	for (i = 0; i < n; i++)
1078 		ce[i] = (edges[i] * ncols) / (double) edges[n - 1];
1079 
1080 	for (i = 1; i < n; i++)
1081 		if (ce[i] <= ce[i - 1])
1082 			ce[i] = ce[i - 1] + 1;
1083 
1084 	if (ce[n - 1] > ncols) {
1085 		ce[n - 1] = ncols;
1086 		for (i = n - 1; (i > 0) && (ce[i] <= ce[i - 1]); i--)
1087 			ce[i - 1] = ce[i] - 1;
1088 		if (ce[0] < 0)
1089 			for (i = 0; i < n; i++)
1090 				ce[i] = i;
1091 	}
1092 
1093 	printf("\n");
1094 	for (i = 0; i < NPART; i++) {
1095 		if (p[i].nblk > 0) {
1096 			r = -1;
1097 			do {
1098 				r++;
1099 				for (j = i - 1; j >= 0; j--) {
1100 					if (row[j] != r)
1101 						continue;
1102 					for (k = 0; k < n; k++)
1103 						if (table[k][i] && table[k][j])
1104 							break;
1105 					if (k < n)
1106 						break;
1107 				}
1108 			} while (j >= 0);
1109 			row[i] = r;
1110 		} else {
1111 			row[i] = -1;
1112 		}
1113 	}
1114 	r = row[0];
1115 	for (i = 1; i < NPART; i++)
1116 		if (row[i] > r)
1117 			r = row[i];
1118 
1119 	if ((line = malloc(ncols + 1)) == NULL)
1120 		err(1, "Can't allocate memory");
1121 
1122 	for (i = 0; i <= r; i++) {
1123 		for (j = 0; j < ncols; j++)
1124 			line[j] = ' ';
1125 		for (j = 0; j < NPART; j++) {
1126 			if (row[j] != i)
1127 				continue;
1128 			k = 0;
1129 			for (k = 0; k < n; k++) {
1130 				if (table[k][j]) {
1131 					for (c = ce[k]; c < ce[k + 1]; c++)
1132 						line[c] = 'a' + j;
1133 				}
1134 			}
1135 		}
1136 		for (j = ncols - 1; (j >= 0) && (line[j] == ' '); j--);
1137 		printf("%.*s\n", j + 1, line);
1138 	}
1139 	free(line);
1140 }
1141 
1142 #ifdef S_COMMAND
1143 /*
1144  * This computes an appropriate checksum for an in-core label.  It's
1145  * not really related to the S command, except that it's needed only
1146  * by setlabel(), which is #ifdef S_COMMAND.
1147  */
1148 static unsigned short int
1149 dkcksum(const struct disklabel *lp)
1150 {
1151 	const unsigned short int *start;
1152 	const unsigned short int *end;
1153 	unsigned short int sum;
1154 	const unsigned short int *p;
1155 
1156 	start = (const void *)lp;
1157 	end = (const void *)&lp->d_partitions[lp->d_npartitions];
1158 	sum = 0;
1159 	for (p = start; p < end; p++)
1160 		sum ^= *p;
1161 	return (sum);
1162 }
1163 
1164 /*
1165  * Set the in-core label.  This is basically putlabel, except it builds
1166  * a struct disklabel instead of a Sun label buffer, and uses
1167  * DIOCSDINFO instead of lseek-and-write.
1168  */
1169 static void
1170 setlabel(void)
1171 {
1172 	union {
1173 		struct disklabel l;
1174 		char pad[sizeof(struct disklabel) -
1175 		     (MAXPARTITIONS * sizeof(struct partition)) +
1176 		      (16 * sizeof(struct partition))];
1177 	} u;
1178 	int i;
1179 	struct part *p = label.partitions;
1180 
1181 	if (ioctl(diskfd, DIOCGDINFO, &u.l) == -1) {
1182 		warn("ioctl DIOCGDINFO failed");
1183 		return;
1184 	}
1185 	if (u.l.d_secsize != 512) {
1186 		warnx("Disk claims %d-byte sectors", (int)u.l.d_secsize);
1187 	}
1188 	u.l.d_nsectors = label.nsect;
1189 	u.l.d_ntracks = label.nhead;
1190 	u.l.d_ncylinders = label.ncyl;
1191 	u.l.d_secpercyl = label.nsect * label.nhead;
1192 	u.l.d_rpm = label.rpm;
1193 	u.l.d_interleave = label.intrlv;
1194 	u.l.d_npartitions = getmaxpartitions();
1195 	memset(&u.l.d_partitions[0], 0,
1196 	    u.l.d_npartitions * sizeof(struct partition));
1197 	for (i = 0; i < u.l.d_npartitions; i++) {
1198 		u.l.d_partitions[i].p_size = p[i].nblk;
1199 		u.l.d_partitions[i].p_offset = p[i].startcyl
1200 		    * label.nsect * label.nhead;
1201 		u.l.d_partitions[i].p_fsize = 0;
1202 		u.l.d_partitions[i].p_fstype = (i == 1) ? FS_SWAP :
1203 		    (i == 2) ? FS_UNUSED : FS_BSDFFS;
1204 		u.l.d_partitions[i].p_frag = 0;
1205 		u.l.d_partitions[i].p_cpg = 0;
1206 	}
1207 	u.l.d_checksum = 0;
1208 	u.l.d_checksum = dkcksum(&u.l);
1209 	if (ioctl(diskfd, DIOCSDINFO, &u.l) == -1) {
1210 		warn("ioctl DIOCSDINFO failed");
1211 		return;
1212 	}
1213 }
1214 #endif
1215 
1216 static const char *help[] = {
1217 	"?\t- print this help",
1218 	"L\t- print label, except for partition table",
1219 	"P\t- print partition table",
1220 	"PP\t- print partition table including size=0 offset=0 entries",
1221 	"[abcdefghijklmnop] <cylno> <size> - change partition",
1222 	"V <name> <value> - change a non-partition label value",
1223 	"W\t- write (possibly modified) label out",
1224 #ifdef S_COMMAND
1225 	"S\t- set label in the kernel (orthogonal to W)",
1226 #endif
1227 	"Q\t- quit program (error if no write since last change)",
1228 	"Q!\t- quit program (unconditionally) [EOF also quits]",
1229 	NULL
1230 };
1231 
1232 /*
1233  * Read and execute one command line from the user.
1234  */
1235 static void
1236 docmd(void)
1237 {
1238 	char cmdline[512];
1239 	int i;
1240 
1241 	if (!quiet)
1242 		printf("sunlabel> ");
1243 	if (fgets(&cmdline[0], sizeof(cmdline), stdin) != &cmdline[0])
1244 		exit(0);
1245 	switch (cmdline[0]) {
1246 	case '?':
1247 		for (i = 0; help[i]; i++)
1248 			printf("%s\n", help[i]);
1249 		break;
1250 	case 'L':
1251 		print_label();
1252 		break;
1253 	case 'P':
1254 		print_part(cmdline[1] == 'P');
1255 		break;
1256 	case 'W':
1257 		putlabel();
1258 		break;
1259 	case 'S':
1260 #ifdef S_COMMAND
1261 		setlabel();
1262 #else
1263 		printf("This compilation doesn't support S.\n");
1264 #endif
1265 		break;
1266 	case 'Q':
1267 		if ((cmdline[1] == '!') || !label.dirty)
1268 			exit(0);
1269 		printf("Label is dirty - use w to write it\n");
1270 		printf("Use Q! to quit anyway.\n");
1271 		break;
1272 	case 'a':
1273 	case 'b':
1274 	case 'c':
1275 	case 'd':
1276 	case 'e':
1277 	case 'f':
1278 	case 'g':
1279 	case 'h':
1280 	case 'i':
1281 	case 'j':
1282 	case 'k':
1283 	case 'l':
1284 	case 'm':
1285 	case 'n':
1286 	case 'o':
1287 	case 'p':
1288 		chpart(LETTERPART(cmdline[0]), &cmdline[1]);
1289 		break;
1290 	case 'V':
1291 		chvalue(&cmdline[1]);
1292 		break;
1293 	case '\n':
1294 		break;
1295 	default:
1296 		printf("(Unrecognized command character %c ignored.)\n",
1297 		    cmdline[0]);
1298 		break;
1299 	}
1300 }
1301 
1302 /*
1303  * main() (duh!).  Pretty boring.
1304  */
1305 int
1306 main(int ac, char **av)
1307 {
1308 	handleargs(ac, av);
1309 	getlabel();
1310 	for (;;)
1311 		docmd();
1312 }
1313