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