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