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