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