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