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