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