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