xref: /openbsd-src/sys/kern/subr_disk.c (revision d0f299081ecdda98dc7a87b149b17b038a84b9fa)
1 /*	$OpenBSD: subr_disk.c,v 1.247 2021/12/22 22:20:13 bluhm Exp $	*/
2 /*	$NetBSD: subr_disk.c,v 1.17 1996/03/16 23:17:08 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1995 Jason R. Thorpe.  All rights reserved.
6  * Copyright (c) 1982, 1986, 1988, 1993
7  *	The Regents of the University of California.  All rights reserved.
8  * (c) UNIX System Laboratories, Inc.
9  * All or some portions of this file are derived from material licensed
10  * to the University of California by American Telephone and Telegraph
11  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
12  * the permission of UNIX System Laboratories, Inc.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)ufs_disksubr.c	8.5 (Berkeley) 1/21/94
39  */
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/kernel.h>
44 #include <sys/malloc.h>
45 #include <sys/fcntl.h>
46 #include <sys/buf.h>
47 #include <sys/stat.h>
48 #include <sys/syslog.h>
49 #include <sys/device.h>
50 #include <sys/time.h>
51 #include <sys/disklabel.h>
52 #include <sys/conf.h>
53 #include <sys/lock.h>
54 #include <sys/disk.h>
55 #include <sys/reboot.h>
56 #include <sys/dkio.h>
57 #include <sys/vnode.h>
58 #include <sys/task.h>
59 #include <sys/stdint.h>
60 
61 #include <sys/socket.h>
62 #include <sys/socketvar.h>
63 
64 #include <net/if.h>
65 
66 #include <dev/cons.h>
67 
68 #include <lib/libz/zlib.h>
69 
70 #include "softraid.h"
71 
72 #ifdef DEBUG
73 #define DPRINTF(x...)	printf(x)
74 #else
75 #define DPRINTF(x...)
76 #endif
77 
78 /*
79  * A global list of all disks attached to the system.  May grow or
80  * shrink over time.
81  */
82 struct	disklist_head disklist;	/* TAILQ_HEAD */
83 int	disk_count;		/* number of drives in global disklist */
84 int	disk_change;		/* set if a disk has been attached/detached
85 				 * since last we looked at this variable. This
86 				 * is reset by hw_sysctl()
87 				 */
88 
89 #define DUID_SIZE 8
90 
91 u_char	bootduid[DUID_SIZE];	/* DUID of boot disk. */
92 u_char	rootduid[DUID_SIZE];	/* DUID of root disk. */
93 
94 /* softraid callback, do not use! */
95 void (*softraid_disk_attach)(struct disk *, int);
96 
97 void sr_map_root(void);
98 
99 struct disk_attach_task {
100 	struct task task;
101 	struct disk *dk;
102 };
103 
104 void disk_attach_callback(void *);
105 
106 int spoofgptlabel(struct buf *, void (*)(struct buf *), struct disklabel *);
107 
108 int gpt_chk_mbr(struct dos_partition *, uint64_t);
109 int gpt_chk_hdr(struct gpt_header *, struct disklabel *);
110 int gpt_chk_parts(struct gpt_header *, struct gpt_partition *);
111 int gpt_get_fstype(struct uuid *);
112 
113 int duid_equal(u_char *, u_char *);
114 
115 /*
116  * Compute checksum for disk label.
117  */
118 u_int
119 dkcksum(struct disklabel *lp)
120 {
121 	u_int16_t *start, *end;
122 	u_int16_t sum = 0;
123 
124 	start = (u_int16_t *)lp;
125 	end = (u_int16_t *)&lp->d_partitions[lp->d_npartitions];
126 	while (start < end)
127 		sum ^= *start++;
128 	return (sum);
129 }
130 
131 int
132 initdisklabel(struct disklabel *lp)
133 {
134 	int i;
135 
136 	/* minimal requirements for archetypal disk label */
137 	if (lp->d_secsize < DEV_BSIZE)
138 		lp->d_secsize = DEV_BSIZE;
139 	if (DL_GETDSIZE(lp) == 0)
140 		DL_SETDSIZE(lp, MAXDISKSIZE);
141 	if (lp->d_secpercyl == 0)
142 		return (ERANGE);
143 	lp->d_npartitions = MAXPARTITIONS;
144 	for (i = 0; i < RAW_PART; i++) {
145 		DL_SETPSIZE(&lp->d_partitions[i], 0);
146 		DL_SETPOFFSET(&lp->d_partitions[i], 0);
147 	}
148 	if (DL_GETPSIZE(&lp->d_partitions[RAW_PART]) == 0)
149 		DL_SETPSIZE(&lp->d_partitions[RAW_PART], DL_GETDSIZE(lp));
150 	DL_SETPOFFSET(&lp->d_partitions[RAW_PART], 0);
151 	DL_SETBSTART(lp, 0);
152 	DL_SETBEND(lp, DL_GETDSIZE(lp));
153 	lp->d_version = 1;
154 	lp->d_bbsize = 8192;
155 	lp->d_sbsize = 64*1024;			/* XXX ? */
156 	return (0);
157 }
158 
159 /*
160  * Check an incoming block to make sure it is a disklabel, convert it to
161  * a newer version if needed, etc etc.
162  */
163 int
164 checkdisklabel(void *rlp, struct disklabel *lp, u_int64_t boundstart,
165     u_int64_t boundend)
166 {
167 	struct disklabel *dlp = rlp;
168 	struct __partitionv0 *v0pp;
169 	struct partition *pp;
170 	u_int64_t disksize;
171 	int error = 0;
172 	int i;
173 
174 	if (dlp->d_magic != DISKMAGIC || dlp->d_magic2 != DISKMAGIC)
175 		error = ENOENT;	/* no disk label */
176 	else if (dlp->d_npartitions > MAXPARTITIONS)
177 		error = E2BIG;	/* too many partitions */
178 	else if (dlp->d_secpercyl == 0)
179 		error = EINVAL;	/* invalid label */
180 	else if (dlp->d_secsize == 0)
181 		error = ENOSPC;	/* disk too small */
182 	else if (dkcksum(dlp) != 0)
183 		error = EINVAL;	/* incorrect checksum */
184 
185 	if (error) {
186 		u_int16_t *start, *end, sum = 0;
187 
188 		/* If it is byte-swapped, attempt to convert it */
189 		if (swap32(dlp->d_magic) != DISKMAGIC ||
190 		    swap32(dlp->d_magic2) != DISKMAGIC ||
191 		    swap16(dlp->d_npartitions) > MAXPARTITIONS)
192 			return (error);
193 
194 		/*
195 		 * Need a byte-swap aware dkcksum variant
196 		 * inlined, because dkcksum uses a sub-field
197 		 */
198 		start = (u_int16_t *)dlp;
199 		end = (u_int16_t *)&dlp->d_partitions[
200 		    swap16(dlp->d_npartitions)];
201 		while (start < end)
202 			sum ^= *start++;
203 		if (sum != 0)
204 			return (error);
205 
206 		dlp->d_magic = swap32(dlp->d_magic);
207 		dlp->d_type = swap16(dlp->d_type);
208 
209 		/* d_typename and d_packname are strings */
210 
211 		dlp->d_secsize = swap32(dlp->d_secsize);
212 		dlp->d_nsectors = swap32(dlp->d_nsectors);
213 		dlp->d_ntracks = swap32(dlp->d_ntracks);
214 		dlp->d_ncylinders = swap32(dlp->d_ncylinders);
215 		dlp->d_secpercyl = swap32(dlp->d_secpercyl);
216 		dlp->d_secperunit = swap32(dlp->d_secperunit);
217 
218 		/* d_uid is a string */
219 
220 		dlp->d_acylinders = swap32(dlp->d_acylinders);
221 
222 		dlp->d_flags = swap32(dlp->d_flags);
223 
224 		for (i = 0; i < NDDATA; i++)
225 			dlp->d_drivedata[i] = swap32(dlp->d_drivedata[i]);
226 
227 		dlp->d_secperunith = swap16(dlp->d_secperunith);
228 		dlp->d_version = swap16(dlp->d_version);
229 
230 		for (i = 0; i < NSPARE; i++)
231 			dlp->d_spare[i] = swap32(dlp->d_spare[i]);
232 
233 		dlp->d_magic2 = swap32(dlp->d_magic2);
234 
235 		dlp->d_npartitions = swap16(dlp->d_npartitions);
236 		dlp->d_bbsize = swap32(dlp->d_bbsize);
237 		dlp->d_sbsize = swap32(dlp->d_sbsize);
238 
239 		for (i = 0; i < MAXPARTITIONS; i++) {
240 			pp = &dlp->d_partitions[i];
241 			pp->p_size = swap32(pp->p_size);
242 			pp->p_offset = swap32(pp->p_offset);
243 			if (dlp->d_version == 0) {
244 				v0pp = (struct __partitionv0 *)pp;
245 				v0pp->p_fsize = swap32(v0pp->p_fsize);
246 			} else {
247 				pp->p_offseth = swap16(pp->p_offseth);
248 				pp->p_sizeh = swap16(pp->p_sizeh);
249 			}
250 			pp->p_cpg = swap16(pp->p_cpg);
251 		}
252 
253 		dlp->d_checksum = 0;
254 		dlp->d_checksum = dkcksum(dlp);
255 		error = 0;
256 	}
257 
258 	/* XXX should verify lots of other fields and whine a lot */
259 
260 	/* Initial passed in lp contains the real disk size. */
261 	disksize = DL_GETDSIZE(lp);
262 
263 	if (lp != dlp)
264 		*lp = *dlp;
265 
266 	if (lp->d_version == 0) {
267 		lp->d_version = 1;
268 		lp->d_secperunith = 0;
269 
270 		v0pp = (struct __partitionv0 *)lp->d_partitions;
271 		pp = lp->d_partitions;
272 		for (i = 0; i < lp->d_npartitions; i++, pp++, v0pp++) {
273 			pp->p_fragblock = DISKLABELV1_FFS_FRAGBLOCK(v0pp->
274 			    p_fsize, v0pp->p_frag);
275 			pp->p_offseth = 0;
276 			pp->p_sizeh = 0;
277 		}
278 	}
279 
280 #ifdef DEBUG
281 	if (DL_GETDSIZE(lp) != disksize)
282 		printf("on-disk disklabel has incorrect disksize (%llu)\n",
283 		    DL_GETDSIZE(lp));
284 	if (DL_GETPSIZE(&lp->d_partitions[RAW_PART]) != disksize)
285 		printf("on-disk disklabel RAW_PART has incorrect size (%llu)\n",
286 		    DL_GETPSIZE(&lp->d_partitions[RAW_PART]));
287 	if (DL_GETPOFFSET(&lp->d_partitions[RAW_PART]) != 0)
288 		printf("on-disk disklabel RAW_PART offset != 0 (%llu)\n",
289 		    DL_GETPOFFSET(&lp->d_partitions[RAW_PART]));
290 #endif
291 	DL_SETDSIZE(lp, disksize);
292 	DL_SETPSIZE(&lp->d_partitions[RAW_PART], disksize);
293 	DL_SETPOFFSET(&lp->d_partitions[RAW_PART], 0);
294 	DL_SETBSTART(lp, boundstart);
295 	DL_SETBEND(lp, boundend < DL_GETDSIZE(lp) ? boundend : DL_GETDSIZE(lp));
296 
297 	lp->d_checksum = 0;
298 	lp->d_checksum = dkcksum(lp);
299 	return (0);
300 }
301 
302 /*
303  * Read a disk sector.
304  */
305 int
306 readdisksector(struct buf *bp, void (*strat)(struct buf *),
307     struct disklabel *lp, u_int64_t sector)
308 {
309 	bp->b_blkno = DL_SECTOBLK(lp, sector);
310 	bp->b_bcount = lp->d_secsize;
311 	bp->b_error = 0;
312 	CLR(bp->b_flags, B_READ | B_WRITE | B_DONE | B_ERROR);
313 	SET(bp->b_flags, B_BUSY | B_READ | B_RAW);
314 
315 	(*strat)(bp);
316 
317 	return (biowait(bp));
318 }
319 
320 /*
321  * If dos partition table requested, attempt to load it and
322  * find disklabel inside a DOS partition. Return buffer
323  * for use in signalling errors if requested.
324  *
325  * We would like to check if each MBR has a valid BOOT_MAGIC, but
326  * we cannot because it doesn't always exist. So.. we assume the
327  * MBR is valid.
328  */
329 int
330 readdoslabel(struct buf *bp, void (*strat)(struct buf *),
331     struct disklabel *lp, daddr_t *partoffp, int spoofonly)
332 {
333 	struct dos_partition dp[NDOSPART], *dp2;
334 	struct disklabel *gptlp;
335 	u_int64_t dospartoff = 0, dospartend = DL_GETBEND(lp);
336 	u_int64_t sector = DOSBBSECTOR;
337 	u_int32_t extoff = 0;
338 	int ourpart = -1, wander = 1, n = 0, loop = 0;
339 	int efi, error, i, offset;
340 
341 	if (lp->d_secpercyl == 0)
342 		return (EINVAL);	/* invalid label */
343 	if (lp->d_secsize == 0)
344 		return (ENOSPC);	/* disk too small */
345 
346 	/* do DOS partitions in the process of getting disklabel? */
347 
348 	/*
349 	 * Read dos partition table, follow extended partitions.
350 	 * Map the partitions to disklabel entries i-p
351 	 */
352 	while (wander && loop < DOS_MAXEBR) {
353 		loop++;
354 		wander = 0;
355 		if (sector < extoff)
356 			sector = extoff;
357 
358 		/* read MBR/EBR */
359 		error = readdisksector(bp, strat, lp, sector);
360 		if (error) {
361 /*wrong*/		if (partoffp)
362 /*wrong*/			*partoffp = -1;
363 			return (error);
364 		}
365 
366 		bcopy(bp->b_data + DOSPARTOFF, dp, sizeof(dp));
367 
368 		if (n == 0 && sector == DOSBBSECTOR) {
369 			u_int16_t mbrtest;
370 
371 			/* Check the end of sector marker. */
372 			mbrtest = ((bp->b_data[510] << 8) & 0xff00) |
373 			    (bp->b_data[511] & 0xff);
374 			if (mbrtest != 0x55aa)
375 				goto notmbr;
376 
377 			efi = gpt_chk_mbr(dp, DL_GETDSIZE(lp));
378 			if (efi == -1)
379 				goto notgpt;
380 
381 			gptlp = malloc(sizeof(struct disklabel), M_DEVBUF,
382 			    M_NOWAIT);
383 			if (gptlp == NULL)
384 				return (ENOMEM);
385 			*gptlp = *lp;
386 			error = spoofgptlabel(bp, strat, gptlp);
387 			if (error == 0) {
388 				dospartoff = DL_GETBSTART(gptlp);
389 				dospartend = DL_GETBEND(gptlp);
390 				if (partoffp == NULL)
391 					*lp = *gptlp;
392 				free(gptlp, M_DEVBUF,
393 				    sizeof(struct disklabel));
394 				if (partoffp && dospartoff == 0)
395 					return (ENXIO);
396 				goto notfat;
397 			} else {
398 				free(gptlp, M_DEVBUF,
399 				    sizeof(struct disklabel));
400 				goto notmbr;
401 			}
402 		}
403 
404 notgpt:
405 		if (ourpart == -1) {
406 			/* Search for our MBR partition */
407 			for (dp2=dp, i=0; i < NDOSPART && ourpart == -1;
408 			    i++, dp2++)
409 				if (letoh32(dp2->dp_size) &&
410 				    dp2->dp_typ == DOSPTYP_OPENBSD)
411 					ourpart = i;
412 			if (ourpart == -1)
413 				goto donot;
414 			/*
415 			 * This is our MBR partition. need sector
416 			 * address for SCSI/IDE, cylinder for
417 			 * ESDI/ST506/RLL
418 			 */
419 			dp2 = &dp[ourpart];
420 			dospartoff = letoh32(dp2->dp_start) + sector;
421 			dospartend = dospartoff + letoh32(dp2->dp_size);
422 
423 			/*
424 			 * Record the OpenBSD partition's placement (in
425 			 * 512-byte blocks!) for the caller. No need to
426 			 * finish spoofing.
427 			 */
428 			if (partoffp) {
429 				*partoffp = DL_SECTOBLK(lp, dospartoff);
430 				return (0);
431 			}
432 
433 			if (lp->d_ntracks == 0)
434 				lp->d_ntracks = dp2->dp_ehd + 1;
435 			if (lp->d_nsectors == 0)
436 				lp->d_nsectors = DPSECT(dp2->dp_esect);
437 			if (lp->d_secpercyl == 0)
438 				lp->d_secpercyl = lp->d_ntracks *
439 				    lp->d_nsectors;
440 		}
441 donot:
442 		/*
443 		 * In case the disklabel read below fails, we want to
444 		 * provide a fake label in i-p.
445 		 */
446 		for (dp2=dp, i=0; i < NDOSPART; i++, dp2++) {
447 			struct partition *pp;
448 			u_int8_t fstype;
449 
450 			if (dp2->dp_typ == DOSPTYP_OPENBSD ||
451 			    dp2->dp_typ == DOSPTYP_EFI)
452 				continue;
453 			if (letoh32(dp2->dp_size) > DL_GETDSIZE(lp))
454 				continue;
455 			if (letoh32(dp2->dp_start) > DL_GETDSIZE(lp))
456 				continue;
457 			if (letoh32(dp2->dp_size) == 0)
458 				continue;
459 
460 			switch (dp2->dp_typ) {
461 			case DOSPTYP_UNUSED:
462 				fstype = FS_UNUSED;
463 				break;
464 
465 			case DOSPTYP_LINUX:
466 				fstype = FS_EXT2FS;
467 				break;
468 
469 			case DOSPTYP_NTFS:
470 				fstype = FS_NTFS;
471 				break;
472 
473 			case DOSPTYP_EFISYS:
474 			case DOSPTYP_FAT12:
475 			case DOSPTYP_FAT16S:
476 			case DOSPTYP_FAT16B:
477 			case DOSPTYP_FAT16L:
478 			case DOSPTYP_FAT32:
479 			case DOSPTYP_FAT32L:
480 				fstype = FS_MSDOS;
481 				break;
482 			case DOSPTYP_EXTEND:
483 			case DOSPTYP_EXTENDL:
484 				sector = letoh32(dp2->dp_start) + extoff;
485 				if (!extoff) {
486 					extoff = letoh32(dp2->dp_start);
487 					sector = 0;
488 				}
489 				wander = 1;
490 				continue;
491 				break;
492 			default:
493 				fstype = FS_OTHER;
494 				break;
495 			}
496 
497 			/*
498 			 * Don't set fstype/offset/size when just looking for
499 			 * the offset of the OpenBSD partition. It would
500 			 * invalidate the disklabel checksum!
501 			 *
502 			 * Don't try to spoof more than 8 partitions, i.e.
503 			 * 'i' -'p'.
504 			 */
505 			if (partoffp || n >= 8)
506 				continue;
507 
508 			pp = &lp->d_partitions[8+n];
509 			n++;
510 			pp->p_fstype = fstype;
511 			if (letoh32(dp2->dp_start))
512 				DL_SETPOFFSET(pp,
513 				    letoh32(dp2->dp_start) + sector);
514 			DL_SETPSIZE(pp, letoh32(dp2->dp_size));
515 		}
516 	}
517 
518 notmbr:
519 	if (n == 0 && sector == DOSBBSECTOR && ourpart == -1) {
520 		u_int16_t fattest;
521 
522 		/* Check for a valid initial jmp instruction. */
523 		switch ((u_int8_t)bp->b_data[0]) {
524 		case 0xeb:
525 			/*
526 			 * Two-byte jmp instruction. The 2nd byte is the number
527 			 * of bytes to jmp and the 3rd byte must be a NOP.
528 			 */
529 			if ((u_int8_t)bp->b_data[2] != 0x90)
530 				goto notfat;
531 			break;
532 		case 0xe9:
533 			/*
534 			 * Three-byte jmp instruction. The next two bytes are a
535 			 * little-endian 16 bit value.
536 			 */
537 			break;
538 		default:
539 			goto notfat;
540 			break;
541 		}
542 
543 		/* Check for a valid bytes per sector value. */
544 		fattest = ((bp->b_data[12] << 8) & 0xff00) |
545 		    (bp->b_data[11] & 0xff);
546 		if (fattest < 512 || fattest > 4096 || (fattest % 512 != 0))
547 			goto notfat;
548 
549 		if (partoffp)
550 			return (ENXIO);	/* No place for disklabel on FAT! */
551 
552 		DL_SETPSIZE(&lp->d_partitions['i' - 'a'],
553 		    DL_GETPSIZE(&lp->d_partitions[RAW_PART]));
554 		DL_SETPOFFSET(&lp->d_partitions['i' - 'a'], 0);
555 		lp->d_partitions['i' - 'a'].p_fstype = FS_MSDOS;
556 
557 		spoofonly = 1;	/* No disklabel to read from disk. */
558 	}
559 
560 notfat:
561 	/* record the OpenBSD partition's placement for the caller */
562 	if (partoffp)
563 		*partoffp = DL_SECTOBLK(lp, dospartoff);
564 	else {
565 		DL_SETBSTART(lp, dospartoff);
566 		DL_SETBEND(lp, (dospartend < DL_GETDSIZE(lp)) ? dospartend :
567 		    DL_GETDSIZE(lp));
568 	}
569 
570 	/* don't read the on-disk label if we are in spoofed-only mode */
571 	if (spoofonly)
572 		return (0);
573 
574 	error = readdisksector(bp, strat, lp, dospartoff +
575 	    DL_BLKTOSEC(lp, DOS_LABELSECTOR));
576 	if (error)
577 		return (bp->b_error);
578 
579 	offset = DL_BLKOFFSET(lp, DOS_LABELSECTOR);
580 	error = checkdisklabel(bp->b_data + offset, lp,
581 	    DL_GETBSTART((struct disklabel*)(bp->b_data+offset)),
582 	    DL_GETBEND((struct disklabel *)(bp->b_data+offset)));
583 
584 	return (error);
585 }
586 
587 /*
588  * Return the index into dp[] of the EFI GPT (0xEE) partition, or -1 if no such
589  * partition exists.
590  *
591  * Copied into sbin/fdisk/mbr.c.
592  */
593 int
594 gpt_chk_mbr(struct dos_partition *dp, uint64_t dsize)
595 {
596 	struct dos_partition *dp2;
597 	int efi, eficnt, found, i;
598 	uint32_t psize;
599 
600 	found = efi = eficnt = 0;
601 	for (dp2 = dp, i = 0; i < NDOSPART; i++, dp2++) {
602 		if (dp2->dp_typ == DOSPTYP_UNUSED)
603 			continue;
604 		found++;
605 		if (dp2->dp_typ != DOSPTYP_EFI)
606 			continue;
607 		if (letoh32(dp2->dp_start) != GPTSECTOR)
608 			continue;
609 		psize = letoh32(dp2->dp_size);
610 		if (psize <= (dsize - GPTSECTOR) || psize == UINT32_MAX) {
611 			efi = i;
612 			eficnt++;
613 		}
614 	}
615 	if (found == 1 && eficnt == 1)
616 		return (efi);
617 
618 	return (-1);
619 }
620 
621 int
622 gpt_chk_hdr(struct gpt_header *gh, struct disklabel *lp)
623 {
624 	uint64_t ghpartlba;
625 	uint64_t ghlbaend, ghlbastart;
626 	uint32_t orig_gh_csum;
627 	uint32_t ghsize, ghpartsize, ghpartspersec;
628 
629 	if (letoh64(gh->gh_sig) != GPTSIGNATURE)
630 		return (EINVAL);
631 
632 	if (letoh32(gh->gh_rev) != GPTREVISION)
633 		return (EINVAL);
634 
635 	ghsize = letoh32(gh->gh_size);
636 	ghpartsize = letoh32(gh->gh_part_size);
637 	ghpartspersec = lp->d_secsize / ghpartsize;
638 	ghpartlba = letoh64(gh->gh_part_lba);
639 	ghlbaend = letoh64(gh->gh_lba_end);
640 	ghlbastart = letoh64(gh->gh_lba_start);
641 
642 	if (ghsize < GPTMINHDRSIZE || ghsize > sizeof(struct gpt_header))
643 		return (EINVAL);
644 
645 	orig_gh_csum = gh->gh_csum;
646 	gh->gh_csum = 0;
647 	gh->gh_csum = crc32(0, (unsigned char *)gh, ghsize);
648 
649 	if (orig_gh_csum != gh->gh_csum)
650 		return (EINVAL);
651 
652 	if (ghlbastart >= DL_GETDSIZE(lp) ||
653 	    ghpartlba >= DL_GETDSIZE(lp))
654 		return (EINVAL);
655 
656 	/*
657 	* Size per partition entry shall be 128*(2**n) with n >= 0.
658 	* We don't support partition entries larger than block size.
659 	*/
660 	if (ghpartsize % GPTMINPARTSIZE || ghpartsize > lp->d_secsize
661 	    || ghpartspersec == 0) {
662 		DPRINTF("invalid partition size\n");
663 		return (EINVAL);
664 	}
665 
666 	/* XXX: we don't support multiples of GPTMINPARTSIZE yet */
667 	if (ghpartsize != GPTMINPARTSIZE) {
668 		DPRINTF("partition sizes larger than %d bytes are not "
669 		    "supported", GPTMINPARTSIZE);
670 		return (EINVAL);
671 	}
672 
673 	return 0;
674 }
675 
676 int
677 gpt_chk_parts(struct gpt_header *gh, struct gpt_partition *gp)
678 {
679 	u_int32_t checksum;
680 	checksum = crc32(0, (unsigned char *)gp,
681 	    letoh32(gh->gh_part_num) * letoh32(gh->gh_part_size));
682 
683 	if (checksum != gh->gh_part_csum)
684 		return (EINVAL);
685 
686 	return 0;
687 }
688 
689 int
690 gpt_get_fstype(struct uuid *uuid_part)
691 {
692 	static int init = 0;
693 	static struct uuid uuid_openbsd, uuid_msdos, uuid_chromefs,
694 	    uuid_linux, uuid_hfs, uuid_unused, uuid_efi_system, uuid_bios_boot;
695 	static const uint8_t gpt_uuid_openbsd[] = GPT_UUID_OPENBSD;
696 	static const uint8_t gpt_uuid_msdos[] = GPT_UUID_MSDOS;
697 	static const uint8_t gpt_uuid_chromerootfs[] = GPT_UUID_CHROMEROOTFS;
698 	static const uint8_t gpt_uuid_linux[] = GPT_UUID_LINUX;
699 	static const uint8_t gpt_uuid_hfs[] = GPT_UUID_APPLE_HFS;
700 	static const uint8_t gpt_uuid_unused[] = GPT_UUID_UNUSED;
701 	static const uint8_t gpt_uuid_efi_system[] = GPT_UUID_EFI_SYSTEM;
702 	static const uint8_t gpt_uuid_bios_boot[] = GPT_UUID_BIOS_BOOT;
703 
704 	if (init == 0) {
705 		uuid_dec_be(gpt_uuid_openbsd, &uuid_openbsd);
706 		uuid_dec_be(gpt_uuid_msdos, &uuid_msdos);
707 		uuid_dec_be(gpt_uuid_chromerootfs, &uuid_chromefs);
708 		uuid_dec_be(gpt_uuid_linux, &uuid_linux);
709 		uuid_dec_be(gpt_uuid_hfs, &uuid_hfs);
710 		uuid_dec_be(gpt_uuid_unused, &uuid_unused);
711 		uuid_dec_be(gpt_uuid_efi_system, &uuid_efi_system);
712 		uuid_dec_be(gpt_uuid_bios_boot, &uuid_bios_boot);
713 		init = 1;
714 	}
715 
716 	if (!memcmp(uuid_part, &uuid_unused, sizeof(struct uuid)))
717 		return FS_UNUSED;
718 	else if (!memcmp(uuid_part, &uuid_openbsd, sizeof(struct uuid)))
719 		return FS_BSDFFS;
720 	else if (!memcmp(uuid_part, &uuid_msdos, sizeof(struct uuid)))
721 		return FS_MSDOS;
722 	else if (!memcmp(uuid_part, &uuid_chromefs, sizeof(struct uuid)))
723 		return FS_EXT2FS;
724 	else if (!memcmp(uuid_part, &uuid_linux, sizeof(struct uuid)))
725 		return FS_EXT2FS;
726 	else if (!memcmp(uuid_part, &uuid_hfs, sizeof(struct uuid)))
727 		return FS_HFS;
728 	else if (!memcmp(uuid_part, &uuid_efi_system, sizeof(struct uuid)))
729 		return FS_MSDOS;
730 	else if (!memcmp(uuid_part, &uuid_bios_boot, sizeof(struct uuid)))
731 		return FS_BOOT;
732 	else
733 		return FS_OTHER;
734 }
735 
736 /*
737  * Spoof a disklabel based on the GPT information on the disk.
738  */
739 int
740 spoofgptlabel(struct buf *bp, void (*strat)(struct buf *),
741     struct disklabel *lp)
742 {
743 	static const u_int8_t gpt_uuid_openbsd[] = GPT_UUID_OPENBSD;
744 	struct gpt_header gh;
745 	struct uuid uuid_part, uuid_openbsd;
746 	struct gpt_partition *gp;
747 	struct partition *pp;
748 	size_t gpsz;
749 	u_int64_t ghlbaend, ghlbastart, sector;
750 	u_int64_t start, end;
751 	int i, error, found, n;
752 	uint32_t ghpartnum;
753 
754 	uuid_dec_be(gpt_uuid_openbsd, &uuid_openbsd);
755 
756 	for (sector = GPTSECTOR; ; sector = DL_GETDSIZE(lp) - 1) {
757 		uint64_t ghpartlba;
758 		uint32_t ghpartsize;
759 		uint32_t ghpartspersec;
760 
761 		error = readdisksector(bp, strat, lp, sector);
762 		if (error) {
763 			DPRINTF("error reading from disk\n");
764 			return (error);
765 		}
766 
767 		bcopy(bp->b_data, &gh, sizeof(gh));
768 
769 		if (gpt_chk_hdr(&gh, lp)) {
770 			if (sector != GPTSECTOR) {
771 				DPRINTF("alternate header also broken\n");
772 				return (EINVAL);
773 			}
774 			continue;
775 		}
776 
777 		ghpartsize = letoh32(gh.gh_part_size);
778 		ghpartspersec = lp->d_secsize / ghpartsize;
779 		ghpartnum = letoh32(gh.gh_part_num);
780 		ghpartlba = letoh64(gh.gh_part_lba);
781 		ghlbaend = letoh64(gh.gh_lba_end);
782 		ghlbastart = letoh64(gh.gh_lba_start);
783 
784 		/* read GPT partition entry array */
785 		gp = mallocarray(ghpartnum, sizeof(struct gpt_partition),
786 		    M_DEVBUF, M_NOWAIT|M_ZERO);
787 		if (gp == NULL)
788 			return (ENOMEM);
789 		gpsz = ghpartnum * sizeof(struct gpt_partition);
790 
791 		/*
792 		* XXX:	Fails if # of partition entries is not a multiple of
793 		*	ghpartspersec.
794 		*/
795 		for (i = 0; i < ghpartnum / ghpartspersec; i++) {
796 			error = readdisksector(bp, strat, lp, ghpartlba + i);
797 			if (error) {
798 				free(gp, M_DEVBUF, gpsz);
799 				return (error);
800 			}
801 
802 			bcopy(bp->b_data, gp + i * ghpartspersec,
803 			    ghpartspersec * sizeof(struct gpt_partition));
804 		}
805 
806 		if (gpt_chk_parts(&gh, gp)) {
807 			free(gp, M_DEVBUF, gpsz);
808 			if (letoh64(gh.gh_lba_self) != GPTSECTOR) {
809 				DPRINTF("alternate partition entries are also "
810 				    "broken\n");
811 				return (EINVAL);
812 			}
813 			continue;
814 		}
815 		break;
816 	}
817 
818 	/* Find OpenBSD partition and spoof others along the way. */
819 	DL_SETBSTART(lp, ghlbastart);
820 	DL_SETBEND(lp, ghlbaend + 1);
821 	found = 0;
822 	n = 'i' - 'a';	/* Start spoofing at 'i', a.k.a. 8. */
823 	for (i = 0; i < ghpartnum; i++) {
824 		start = letoh64(gp[i].gp_lba_start);
825 		end = letoh64(gp[i].gp_lba_end);
826 		if (start > end || start < ghlbastart || end > ghlbaend)
827 			continue; /* entry invalid */
828 
829 		uuid_dec_le(&gp[i].gp_type, &uuid_part);
830 		if (memcmp(&uuid_part, &uuid_openbsd, sizeof(struct uuid)) == 0) {
831 			if (found == 0) {
832 				found = 1;
833 				DL_SETBSTART(lp, start);
834 				DL_SETBEND(lp, end + 1);
835 			}
836 		} else if (n < MAXPARTITIONS) {
837 			pp = &lp->d_partitions[n];
838 			n++;
839 			pp->p_fstype = gpt_get_fstype(&uuid_part);
840 			DL_SETPOFFSET(pp, start);
841 			DL_SETPSIZE(pp, end - start + 1);
842 		}
843 	}
844 
845 	free(gp, M_DEVBUF, gpsz);
846 
847 	return (0);
848 }
849 
850 /*
851  * Check new disk label for sensibility before setting it.
852  */
853 int
854 setdisklabel(struct disklabel *olp, struct disklabel *nlp, u_int openmask)
855 {
856 	struct partition *opp, *npp;
857 	struct disk *dk;
858 	int i;
859 
860 	/* sanity clause */
861 	if (nlp->d_secpercyl == 0 || nlp->d_secsize == 0 ||
862 	    (nlp->d_secsize % DEV_BSIZE) != 0)
863 		return (EINVAL);
864 
865 	/* special case to allow disklabel to be invalidated */
866 	if (nlp->d_magic == 0xffffffff) {
867 		*olp = *nlp;
868 		return (0);
869 	}
870 
871 	if (nlp->d_magic != DISKMAGIC || nlp->d_magic2 != DISKMAGIC ||
872 	    dkcksum(nlp) != 0)
873 		return (EINVAL);
874 
875 	/* XXX missing check if other dos partitions will be overwritten */
876 
877 	for (i = 0; i < MAXPARTITIONS; i++) {
878 		opp = &olp->d_partitions[i];
879 		npp = &nlp->d_partitions[i];
880 		if ((openmask & (1 << i)) &&
881 		    (DL_GETPOFFSET(npp) != DL_GETPOFFSET(opp) ||
882 		    DL_GETPSIZE(npp) < DL_GETPSIZE(opp)))
883 			return (EBUSY);
884 		/*
885 		 * Copy internally-set partition information
886 		 * if new label doesn't include it.		XXX
887 		 */
888 		if (npp->p_fstype == FS_UNUSED && opp->p_fstype != FS_UNUSED) {
889 			npp->p_fragblock = opp->p_fragblock;
890 			npp->p_cpg = opp->p_cpg;
891 		}
892 	}
893 
894 	/* Generate a UID if the disklabel does not already have one. */
895 	if (duid_iszero(nlp->d_uid)) {
896 		do {
897 			arc4random_buf(nlp->d_uid, sizeof(nlp->d_uid));
898 			TAILQ_FOREACH(dk, &disklist, dk_link)
899 				if (dk->dk_label &&
900 				    duid_equal(dk->dk_label->d_uid, nlp->d_uid))
901 					break;
902 		} while (dk != NULL || duid_iszero(nlp->d_uid));
903 	}
904 
905 	/* Preserve the disk size and RAW_PART values. */
906 	DL_SETDSIZE(nlp, DL_GETDSIZE(olp));
907 	npp = &nlp->d_partitions[RAW_PART];
908 	DL_SETPOFFSET(npp, 0);
909 	DL_SETPSIZE(npp, DL_GETDSIZE(nlp));
910 
911 	nlp->d_checksum = 0;
912 	nlp->d_checksum = dkcksum(nlp);
913 	*olp = *nlp;
914 
915 	disk_change = 1;
916 
917 	return (0);
918 }
919 
920 /*
921  * Determine the size of the transfer, and make sure it is within the
922  * boundaries of the partition. Adjust transfer if needed, and signal errors or
923  * early completion.
924  */
925 int
926 bounds_check_with_label(struct buf *bp, struct disklabel *lp)
927 {
928 	struct partition *p = &lp->d_partitions[DISKPART(bp->b_dev)];
929 	daddr_t partblocks, sz;
930 
931 	/* Avoid division by zero, negative offsets, and negative sizes. */
932 	if (lp->d_secpercyl == 0 || bp->b_blkno < 0 || bp->b_bcount < 0)
933 		goto bad;
934 
935 	/* Ensure transfer is a whole number of aligned sectors. */
936 	if ((bp->b_blkno % DL_BLKSPERSEC(lp)) != 0 ||
937 	    (bp->b_bcount % lp->d_secsize) != 0)
938 		goto bad;
939 
940 	/* Ensure transfer starts within partition boundary. */
941 	partblocks = DL_SECTOBLK(lp, DL_GETPSIZE(p));
942 	if (bp->b_blkno > partblocks)
943 		goto bad;
944 
945 	/* If exactly at end of partition or null transfer, return EOF. */
946 	if (bp->b_blkno == partblocks || bp->b_bcount == 0)
947 		goto done;
948 
949 	/* Truncate request if it extends past the end of the partition. */
950 	sz = bp->b_bcount >> DEV_BSHIFT;
951 	if (sz > partblocks - bp->b_blkno) {
952 		sz = partblocks - bp->b_blkno;
953 		bp->b_bcount = sz << DEV_BSHIFT;
954 	}
955 
956 	return (0);
957 
958  bad:
959 	bp->b_error = EINVAL;
960 	bp->b_flags |= B_ERROR;
961  done:
962 	bp->b_resid = bp->b_bcount;
963 	return (-1);
964 }
965 
966 /*
967  * Disk error is the preface to plaintive error messages
968  * about failing disk transfers.  It prints messages of the form
969 
970 hp0g: hard error reading fsbn 12345 of 12344-12347 (hp0 bn %d cn %d tn %d sn %d)
971 
972  * if the offset of the error in the transfer and a disk label
973  * are both available.  blkdone should be -1 if the position of the error
974  * is unknown; the disklabel pointer may be null from drivers that have not
975  * been converted to use them.  The message is printed with printf
976  * if pri is LOG_PRINTF, otherwise it uses log at the specified priority.
977  * The message should be completed (with at least a newline) with printf
978  * or addlog, respectively.  There is no trailing space.
979  */
980 void
981 diskerr(struct buf *bp, char *dname, char *what, int pri, int blkdone,
982     struct disklabel *lp)
983 {
984 	int unit = DISKUNIT(bp->b_dev), part = DISKPART(bp->b_dev);
985 	int (*pr)(const char *, ...) __attribute__((__format__(__kprintf__,1,2)));
986 	char partname = 'a' + part;
987 	daddr_t sn;
988 
989 	if (pri != LOG_PRINTF) {
990 		log(pri, "%s", "");
991 		pr = addlog;
992 	} else
993 		pr = printf;
994 	(*pr)("%s%d%c: %s %sing fsbn ", dname, unit, partname, what,
995 	    bp->b_flags & B_READ ? "read" : "writ");
996 	sn = bp->b_blkno;
997 	if (bp->b_bcount <= DEV_BSIZE)
998 		(*pr)("%lld", (long long)sn);
999 	else {
1000 		if (blkdone >= 0) {
1001 			sn += blkdone;
1002 			(*pr)("%lld of ", (long long)sn);
1003 		}
1004 		(*pr)("%lld-%lld", (long long)bp->b_blkno,
1005 		    (long long)(bp->b_blkno + (bp->b_bcount - 1) / DEV_BSIZE));
1006 	}
1007 	if (lp && (blkdone >= 0 || bp->b_bcount <= lp->d_secsize)) {
1008 		sn += DL_SECTOBLK(lp, DL_GETPOFFSET(&lp->d_partitions[part]));
1009 		(*pr)(" (%s%d bn %lld; cn %lld", dname, unit, (long long)sn,
1010 		    (long long)(sn / DL_SECTOBLK(lp, lp->d_secpercyl)));
1011 		sn %= DL_SECTOBLK(lp, lp->d_secpercyl);
1012 		(*pr)(" tn %lld sn %lld)",
1013 		    (long long)(sn / DL_SECTOBLK(lp, lp->d_nsectors)),
1014 		    (long long)(sn % DL_SECTOBLK(lp, lp->d_nsectors)));
1015 	}
1016 }
1017 
1018 /*
1019  * Initialize the disklist.  Called by main() before autoconfiguration.
1020  */
1021 void
1022 disk_init(void)
1023 {
1024 
1025 	TAILQ_INIT(&disklist);
1026 	disk_count = disk_change = 0;
1027 }
1028 
1029 int
1030 disk_construct(struct disk *diskp)
1031 {
1032 	rw_init_flags(&diskp->dk_lock, "dklk", RWL_IS_VNODE);
1033 	mtx_init(&diskp->dk_mtx, IPL_BIO);
1034 
1035 	diskp->dk_flags |= DKF_CONSTRUCTED;
1036 
1037 	return (0);
1038 }
1039 
1040 /*
1041  * Attach a disk.
1042  */
1043 void
1044 disk_attach(struct device *dv, struct disk *diskp)
1045 {
1046 	int majdev;
1047 
1048 	KERNEL_ASSERT_LOCKED();
1049 
1050 	if (!ISSET(diskp->dk_flags, DKF_CONSTRUCTED))
1051 		disk_construct(diskp);
1052 
1053 	/*
1054 	 * Allocate and initialize the disklabel structures.  Note that
1055 	 * it's not safe to sleep here, since we're probably going to be
1056 	 * called during autoconfiguration.
1057 	 */
1058 	diskp->dk_label = malloc(sizeof(struct disklabel), M_DEVBUF,
1059 	    M_NOWAIT|M_ZERO);
1060 	if (diskp->dk_label == NULL)
1061 		panic("disk_attach: can't allocate storage for disklabel");
1062 
1063 	/*
1064 	 * Set the attached timestamp.
1065 	 */
1066 	microuptime(&diskp->dk_attachtime);
1067 
1068 	/*
1069 	 * Link into the disklist.
1070 	 */
1071 	TAILQ_INSERT_TAIL(&disklist, diskp, dk_link);
1072 	++disk_count;
1073 	disk_change = 1;
1074 
1075 	/*
1076 	 * Store device structure and number for later use.
1077 	 */
1078 	diskp->dk_device = dv;
1079 	diskp->dk_devno = NODEV;
1080 	if (dv != NULL) {
1081 		majdev = findblkmajor(dv);
1082 		if (majdev >= 0)
1083 			diskp->dk_devno =
1084 			    MAKEDISKDEV(majdev, dv->dv_unit, RAW_PART);
1085 
1086 		if (diskp->dk_devno != NODEV) {
1087 			struct disk_attach_task *dat;
1088 
1089 			dat = malloc(sizeof(*dat), M_TEMP, M_WAITOK);
1090 
1091 			/* XXX: Assumes dk is part of the device softc. */
1092 			device_ref(dv);
1093 			dat->dk = diskp;
1094 
1095 			task_set(&dat->task, disk_attach_callback, dat);
1096 			task_add(systq, &dat->task);
1097 		}
1098 	}
1099 
1100 	if (softraid_disk_attach)
1101 		softraid_disk_attach(diskp, 1);
1102 }
1103 
1104 void
1105 disk_attach_callback(void *xdat)
1106 {
1107 	struct disk_attach_task *dat = xdat;
1108 	struct disk *dk = dat->dk;
1109 	struct disklabel dl;
1110 	char errbuf[100];
1111 
1112 	free(dat, M_TEMP, sizeof(*dat));
1113 
1114 	if (dk->dk_flags & (DKF_OPENED | DKF_NOLABELREAD))
1115 		goto done;
1116 
1117 	/* Read disklabel. */
1118 	if (disk_readlabel(&dl, dk->dk_devno, errbuf, sizeof(errbuf)) == NULL) {
1119 		enqueue_randomness(dl.d_checksum);
1120 		dk->dk_flags |= DKF_LABELVALID;
1121 	}
1122 
1123 done:
1124 	dk->dk_flags |= DKF_OPENED;
1125 	device_unref(dk->dk_device);
1126 	wakeup(dk);
1127 }
1128 
1129 /*
1130  * Detach a disk.
1131  */
1132 void
1133 disk_detach(struct disk *diskp)
1134 {
1135 	KERNEL_ASSERT_LOCKED();
1136 
1137 	if (softraid_disk_attach)
1138 		softraid_disk_attach(diskp, -1);
1139 
1140 	/*
1141 	 * Free the space used by the disklabel structures.
1142 	 */
1143 	free(diskp->dk_label, M_DEVBUF, sizeof(*diskp->dk_label));
1144 
1145 	/*
1146 	 * Remove from the disklist.
1147 	 */
1148 	TAILQ_REMOVE(&disklist, diskp, dk_link);
1149 	disk_change = 1;
1150 	if (--disk_count < 0)
1151 		panic("disk_detach: disk_count < 0");
1152 }
1153 
1154 int
1155 disk_openpart(struct disk *dk, int part, int fmt, int haslabel)
1156 {
1157 	KASSERT(part >= 0 && part < MAXPARTITIONS);
1158 
1159 	/* Unless opening the raw partition, check that the partition exists. */
1160 	if (part != RAW_PART && (!haslabel ||
1161 	    part >= dk->dk_label->d_npartitions ||
1162 	    dk->dk_label->d_partitions[part].p_fstype == FS_UNUSED))
1163 		return (ENXIO);
1164 
1165 	/* Ensure the partition doesn't get changed under our feet. */
1166 	switch (fmt) {
1167 	case S_IFCHR:
1168 		dk->dk_copenmask |= (1 << part);
1169 		break;
1170 	case S_IFBLK:
1171 		dk->dk_bopenmask |= (1 << part);
1172 		break;
1173 	}
1174 	dk->dk_openmask = dk->dk_copenmask | dk->dk_bopenmask;
1175 
1176 	return (0);
1177 }
1178 
1179 void
1180 disk_closepart(struct disk *dk, int part, int fmt)
1181 {
1182 	KASSERT(part >= 0 && part < MAXPARTITIONS);
1183 
1184 	switch (fmt) {
1185 	case S_IFCHR:
1186 		dk->dk_copenmask &= ~(1 << part);
1187 		break;
1188 	case S_IFBLK:
1189 		dk->dk_bopenmask &= ~(1 << part);
1190 		break;
1191 	}
1192 	dk->dk_openmask = dk->dk_copenmask | dk->dk_bopenmask;
1193 }
1194 
1195 void
1196 disk_gone(int (*open)(dev_t, int, int, struct proc *), int unit)
1197 {
1198 	int bmaj, cmaj, mn;
1199 
1200 	/* Locate the lowest minor number to be detached. */
1201 	mn = DISKMINOR(unit, 0);
1202 
1203 	for (bmaj = 0; bmaj < nblkdev; bmaj++)
1204 		if (bdevsw[bmaj].d_open == open)
1205 			vdevgone(bmaj, mn, mn + MAXPARTITIONS - 1, VBLK);
1206 	for (cmaj = 0; cmaj < nchrdev; cmaj++)
1207 		if (cdevsw[cmaj].d_open == open)
1208 			vdevgone(cmaj, mn, mn + MAXPARTITIONS - 1, VCHR);
1209 }
1210 
1211 /*
1212  * Increment a disk's busy counter.  If the counter is going from
1213  * 0 to 1, set the timestamp.
1214  */
1215 void
1216 disk_busy(struct disk *diskp)
1217 {
1218 
1219 	/*
1220 	 * XXX We'd like to use something as accurate as microtime(),
1221 	 * but that doesn't depend on the system TOD clock.
1222 	 */
1223 	mtx_enter(&diskp->dk_mtx);
1224 	if (diskp->dk_busy++ == 0)
1225 		microuptime(&diskp->dk_timestamp);
1226 	mtx_leave(&diskp->dk_mtx);
1227 }
1228 
1229 /*
1230  * Decrement a disk's busy counter, increment the byte count, total busy
1231  * time, and reset the timestamp.
1232  */
1233 void
1234 disk_unbusy(struct disk *diskp, long bcount, daddr_t blkno, int read)
1235 {
1236 	struct timeval dv_time, diff_time;
1237 
1238 	mtx_enter(&diskp->dk_mtx);
1239 
1240 	if (diskp->dk_busy-- == 0)
1241 		printf("disk_unbusy: %s: dk_busy < 0\n", diskp->dk_name);
1242 
1243 	microuptime(&dv_time);
1244 
1245 	timersub(&dv_time, &diskp->dk_timestamp, &diff_time);
1246 	timeradd(&diskp->dk_time, &diff_time, &diskp->dk_time);
1247 
1248 	diskp->dk_timestamp = dv_time;
1249 	if (bcount > 0) {
1250 		if (read) {
1251 			diskp->dk_rbytes += bcount;
1252 			diskp->dk_rxfer++;
1253 		} else {
1254 			diskp->dk_wbytes += bcount;
1255 			diskp->dk_wxfer++;
1256 		}
1257 	} else
1258 		diskp->dk_seek++;
1259 
1260 	mtx_leave(&diskp->dk_mtx);
1261 
1262 	enqueue_randomness(bcount ^ diff_time.tv_usec ^
1263 	    (blkno >> 32) ^ (blkno & 0xffffffff));
1264 }
1265 
1266 int
1267 disk_lock(struct disk *dk)
1268 {
1269 	return (rw_enter(&dk->dk_lock, RW_WRITE|RW_INTR));
1270 }
1271 
1272 void
1273 disk_lock_nointr(struct disk *dk)
1274 {
1275 	rw_enter_write(&dk->dk_lock);
1276 }
1277 
1278 void
1279 disk_unlock(struct disk *dk)
1280 {
1281 	rw_exit_write(&dk->dk_lock);
1282 }
1283 
1284 int
1285 dk_mountroot(void)
1286 {
1287 	char errbuf[100];
1288 	int part = DISKPART(rootdev);
1289 	int (*mountrootfn)(void);
1290 	struct disklabel dl;
1291 	char *error;
1292 
1293 	error = disk_readlabel(&dl, rootdev, errbuf, sizeof(errbuf));
1294 	if (error)
1295 		panic("%s", error);
1296 
1297 	if (DL_GETPSIZE(&dl.d_partitions[part]) == 0)
1298 		panic("root filesystem has size 0");
1299 	switch (dl.d_partitions[part].p_fstype) {
1300 #ifdef EXT2FS
1301 	case FS_EXT2FS:
1302 		{
1303 		extern int ext2fs_mountroot(void);
1304 		mountrootfn = ext2fs_mountroot;
1305 		}
1306 		break;
1307 #endif
1308 #ifdef FFS
1309 	case FS_BSDFFS:
1310 		{
1311 		extern int ffs_mountroot(void);
1312 		mountrootfn = ffs_mountroot;
1313 		}
1314 		break;
1315 #endif
1316 #ifdef CD9660
1317 	case FS_ISO9660:
1318 		{
1319 		extern int cd9660_mountroot(void);
1320 		mountrootfn = cd9660_mountroot;
1321 		}
1322 		break;
1323 #endif
1324 	default:
1325 #ifdef FFS
1326 		{
1327 		extern int ffs_mountroot(void);
1328 
1329 		printf("filesystem type %d not known.. assuming ffs\n",
1330 		    dl.d_partitions[part].p_fstype);
1331 		mountrootfn = ffs_mountroot;
1332 		}
1333 #else
1334 		panic("disk 0x%x filesystem type %d not known",
1335 		    rootdev, dl.d_partitions[part].p_fstype);
1336 #endif
1337 	}
1338 	return (*mountrootfn)();
1339 }
1340 
1341 struct device *
1342 getdisk(char *str, int len, int defpart, dev_t *devp)
1343 {
1344 	struct device *dv;
1345 
1346 	if ((dv = parsedisk(str, len, defpart, devp)) == NULL) {
1347 		printf("use one of: exit");
1348 		TAILQ_FOREACH(dv, &alldevs, dv_list) {
1349 			if (dv->dv_class == DV_DISK)
1350 				printf(" %s[a-p]", dv->dv_xname);
1351 #if defined(NFSCLIENT)
1352 			if (dv->dv_class == DV_IFNET)
1353 				printf(" %s", dv->dv_xname);
1354 #endif
1355 		}
1356 		printf("\n");
1357 	}
1358 	return (dv);
1359 }
1360 
1361 struct device *
1362 parsedisk(char *str, int len, int defpart, dev_t *devp)
1363 {
1364 	struct device *dv;
1365 	int majdev, part = defpart;
1366 	char c;
1367 
1368 	if (len == 0)
1369 		return (NULL);
1370 	c = str[len-1];
1371 	if (c >= 'a' && (c - 'a') < MAXPARTITIONS) {
1372 		part = c - 'a';
1373 		len -= 1;
1374 	}
1375 
1376 	TAILQ_FOREACH(dv, &alldevs, dv_list) {
1377 		if (dv->dv_class == DV_DISK &&
1378 		    strncmp(str, dv->dv_xname, len) == 0 &&
1379 		    dv->dv_xname[len] == '\0') {
1380 			majdev = findblkmajor(dv);
1381 			if (majdev < 0)
1382 				return NULL;
1383 			*devp = MAKEDISKDEV(majdev, dv->dv_unit, part);
1384 			break;
1385 		}
1386 #if defined(NFSCLIENT)
1387 		if (dv->dv_class == DV_IFNET &&
1388 		    strncmp(str, dv->dv_xname, len) == 0 &&
1389 		    dv->dv_xname[len] == '\0') {
1390 			*devp = NODEV;
1391 			break;
1392 		}
1393 #endif
1394 	}
1395 
1396 	return (dv);
1397 }
1398 
1399 void
1400 setroot(struct device *bootdv, int part, int exitflags)
1401 {
1402 	int majdev, unit, len, s, slept = 0;
1403 	struct swdevt *swp;
1404 	struct device *rootdv, *dv;
1405 	dev_t nrootdev, nswapdev = NODEV, temp = NODEV;
1406 	struct ifnet *ifp = NULL;
1407 	struct disk *dk;
1408 	char buf[128];
1409 #if defined(NFSCLIENT)
1410 	extern char *nfsbootdevname;
1411 #endif
1412 
1413 	/* Ensure that all disk attach callbacks have completed. */
1414 	do {
1415 		TAILQ_FOREACH(dk, &disklist, dk_link) {
1416 			if (dk->dk_devno != NODEV &&
1417 			    (dk->dk_flags & DKF_OPENED) == 0) {
1418 				tsleep_nsec(dk, 0, "dkopen", SEC_TO_NSEC(1));
1419 				slept++;
1420 				break;
1421 			}
1422 		}
1423 	} while (dk != NULL && slept < 5);
1424 
1425 	if (slept == 5) {
1426 		printf("disklabels not read:");
1427 		TAILQ_FOREACH(dk, &disklist, dk_link)
1428 			if (dk->dk_devno != NODEV &&
1429 			    (dk->dk_flags & DKF_OPENED) == 0)
1430 				printf(" %s", dk->dk_name);
1431 		printf("\n");
1432 	}
1433 
1434 	if (duid_iszero(bootduid)) {
1435 		/* Locate DUID for boot disk since it was not provided. */
1436 		TAILQ_FOREACH(dk, &disklist, dk_link)
1437 			if (dk->dk_device == bootdv)
1438 				break;
1439 		if (dk && (dk->dk_flags & DKF_LABELVALID))
1440 			bcopy(dk->dk_label->d_uid, bootduid, sizeof(bootduid));
1441 	} else if (bootdv == NULL) {
1442 		/* Locate boot disk based on the provided DUID. */
1443 		TAILQ_FOREACH(dk, &disklist, dk_link)
1444 			if (duid_equal(dk->dk_label->d_uid, bootduid))
1445 				break;
1446 		if (dk && (dk->dk_flags & DKF_LABELVALID))
1447 			bootdv = dk->dk_device;
1448 	}
1449 	bcopy(bootduid, rootduid, sizeof(rootduid));
1450 
1451 #if NSOFTRAID > 0
1452 	sr_map_root();
1453 #endif
1454 
1455 	/*
1456 	 * If `swap generic' and we couldn't determine boot device,
1457 	 * ask the user.
1458 	 */
1459 	dk = NULL;
1460 	if (mountroot == NULL && bootdv == NULL)
1461 		boothowto |= RB_ASKNAME;
1462 	if (boothowto & RB_ASKNAME) {
1463 		while (1) {
1464 			printf("root device");
1465 			if (bootdv != NULL) {
1466 				printf(" (default %s", bootdv->dv_xname);
1467 				if (bootdv->dv_class == DV_DISK)
1468 					printf("%c", 'a' + part);
1469 				printf(")");
1470 			}
1471 			printf(": ");
1472 			s = splhigh();
1473 			cnpollc(1);
1474 			len = getsn(buf, sizeof(buf));
1475 			cnpollc(0);
1476 			splx(s);
1477 			if (strcmp(buf, "exit") == 0)
1478 				reboot(exitflags);
1479 			if (len == 0 && bootdv != NULL) {
1480 				strlcpy(buf, bootdv->dv_xname, sizeof buf);
1481 				len = strlen(buf);
1482 			}
1483 			if (len > 0 && buf[len - 1] == '*') {
1484 				buf[--len] = '\0';
1485 				dv = getdisk(buf, len, part, &nrootdev);
1486 				if (dv != NULL) {
1487 					rootdv = dv;
1488 					nswapdev = nrootdev;
1489 					goto gotswap;
1490 				}
1491 			}
1492 			dv = getdisk(buf, len, part, &nrootdev);
1493 			if (dv != NULL) {
1494 				rootdv = dv;
1495 				break;
1496 			}
1497 		}
1498 
1499 		if (rootdv->dv_class == DV_IFNET)
1500 			goto gotswap;
1501 
1502 		/* try to build swap device out of new root device */
1503 		while (1) {
1504 			printf("swap device");
1505 			if (rootdv != NULL)
1506 				printf(" (default %s%s)", rootdv->dv_xname,
1507 				    rootdv->dv_class == DV_DISK ? "b" : "");
1508 			printf(": ");
1509 			s = splhigh();
1510 			cnpollc(1);
1511 			len = getsn(buf, sizeof(buf));
1512 			cnpollc(0);
1513 			splx(s);
1514 			if (strcmp(buf, "exit") == 0)
1515 				reboot(exitflags);
1516 			if (len == 0 && rootdv != NULL) {
1517 				switch (rootdv->dv_class) {
1518 				case DV_IFNET:
1519 					nswapdev = NODEV;
1520 					break;
1521 				case DV_DISK:
1522 					nswapdev = MAKEDISKDEV(major(nrootdev),
1523 					    DISKUNIT(nrootdev), 1);
1524 					if (nswapdev == nrootdev)
1525 						continue;
1526 					break;
1527 				default:
1528 					break;
1529 				}
1530 				break;
1531 			}
1532 			dv = getdisk(buf, len, 1, &nswapdev);
1533 			if (dv) {
1534 				if (dv->dv_class == DV_IFNET)
1535 					nswapdev = NODEV;
1536 				if (nswapdev == nrootdev)
1537 					continue;
1538 				break;
1539 			}
1540 		}
1541 gotswap:
1542 		rootdev = nrootdev;
1543 		dumpdev = nswapdev;
1544 		swdevt[0].sw_dev = nswapdev;
1545 		swdevt[1].sw_dev = NODEV;
1546 #if defined(NFSCLIENT)
1547 	} else if (mountroot == nfs_mountroot) {
1548 		rootdv = bootdv;
1549 		rootdev = dumpdev = swapdev = NODEV;
1550 #endif
1551 	} else if (mountroot == NULL && rootdev == NODEV) {
1552 		/*
1553 		 * `swap generic'
1554 		 */
1555 		rootdv = bootdv;
1556 
1557 		if (bootdv->dv_class == DV_DISK) {
1558 			if (!duid_iszero(rootduid)) {
1559 				TAILQ_FOREACH(dk, &disklist, dk_link)
1560 					if ((dk->dk_flags & DKF_LABELVALID) &&
1561 					    dk->dk_label && duid_equal(
1562 					    dk->dk_label->d_uid, rootduid))
1563 						break;
1564 				if (dk == NULL)
1565 					panic("root device (%s) not found",
1566 					    duid_format(rootduid));
1567 				rootdv = dk->dk_device;
1568 			}
1569 		}
1570 
1571 		majdev = findblkmajor(rootdv);
1572 		if (majdev >= 0) {
1573 			/*
1574 			 * Root and swap are on the disk.
1575 			 * Assume swap is on partition b.
1576 			 */
1577 			rootdev = MAKEDISKDEV(majdev, rootdv->dv_unit, part);
1578 			nswapdev = MAKEDISKDEV(majdev, rootdv->dv_unit, 1);
1579 		} else {
1580 			/*
1581 			 * Root and swap are on a net.
1582 			 */
1583 			nswapdev = NODEV;
1584 		}
1585 		dumpdev = nswapdev;
1586 		swdevt[0].sw_dev = nswapdev;
1587 		/* swdevt[1].sw_dev = NODEV; */
1588 	} else {
1589 		/* Completely pre-configured, but we want rootdv .. */
1590 		majdev = major(rootdev);
1591 		if (findblkname(majdev) == NULL)
1592 			return;
1593 		unit = DISKUNIT(rootdev);
1594 		part = DISKPART(rootdev);
1595 		snprintf(buf, sizeof buf, "%s%d%c",
1596 		    findblkname(majdev), unit, 'a' + part);
1597 		rootdv = parsedisk(buf, strlen(buf), 0, &nrootdev);
1598 		if (rootdv == NULL)
1599 			panic("root device (%s) not found", buf);
1600 	}
1601 
1602 	if (bootdv != NULL && bootdv->dv_class == DV_IFNET)
1603 		ifp = if_unit(bootdv->dv_xname);
1604 
1605 	if (ifp) {
1606 		if_addgroup(ifp, "netboot");
1607 		if_put(ifp);
1608 	}
1609 
1610 	switch (rootdv->dv_class) {
1611 #if defined(NFSCLIENT)
1612 	case DV_IFNET:
1613 		mountroot = nfs_mountroot;
1614 		nfsbootdevname = rootdv->dv_xname;
1615 		return;
1616 #endif
1617 	case DV_DISK:
1618 		mountroot = dk_mountroot;
1619 		part = DISKPART(rootdev);
1620 		break;
1621 	default:
1622 		printf("can't figure root, hope your kernel is right\n");
1623 		return;
1624 	}
1625 
1626 	printf("root on %s%c", rootdv->dv_xname, 'a' + part);
1627 
1628 	if (dk && dk->dk_device == rootdv)
1629 		printf(" (%s.%c)", duid_format(rootduid), 'a' + part);
1630 
1631 	/*
1632 	 * Make the swap partition on the root drive the primary swap.
1633 	 */
1634 	for (swp = swdevt; swp->sw_dev != NODEV; swp++) {
1635 		if (major(rootdev) == major(swp->sw_dev) &&
1636 		    DISKUNIT(rootdev) == DISKUNIT(swp->sw_dev)) {
1637 			temp = swdevt[0].sw_dev;
1638 			swdevt[0].sw_dev = swp->sw_dev;
1639 			swp->sw_dev = temp;
1640 			break;
1641 		}
1642 	}
1643 	if (swp->sw_dev != NODEV) {
1644 		/*
1645 		 * If dumpdev was the same as the old primary swap device,
1646 		 * move it to the new primary swap device.
1647 		 */
1648 		if (temp == dumpdev)
1649 			dumpdev = swdevt[0].sw_dev;
1650 	}
1651 	if (swdevt[0].sw_dev != NODEV)
1652 		printf(" swap on %s%d%c", findblkname(major(swdevt[0].sw_dev)),
1653 		    DISKUNIT(swdevt[0].sw_dev),
1654 		    'a' + DISKPART(swdevt[0].sw_dev));
1655 	if (dumpdev != NODEV)
1656 		printf(" dump on %s%d%c", findblkname(major(dumpdev)),
1657 		    DISKUNIT(dumpdev), 'a' + DISKPART(dumpdev));
1658 	printf("\n");
1659 }
1660 
1661 extern struct nam2blk nam2blk[];
1662 
1663 int
1664 findblkmajor(struct device *dv)
1665 {
1666 	char buf[16], *p;
1667 	int i;
1668 
1669 	if (strlcpy(buf, dv->dv_xname, sizeof buf) >= sizeof buf)
1670 		return (-1);
1671 	for (p = buf; *p; p++)
1672 		if (*p >= '0' && *p <= '9')
1673 			*p = '\0';
1674 
1675 	for (i = 0; nam2blk[i].name; i++)
1676 		if (!strcmp(buf, nam2blk[i].name))
1677 			return (nam2blk[i].maj);
1678 	return (-1);
1679 }
1680 
1681 char *
1682 findblkname(int maj)
1683 {
1684 	int i;
1685 
1686 	for (i = 0; nam2blk[i].name; i++)
1687 		if (nam2blk[i].maj == maj)
1688 			return (nam2blk[i].name);
1689 	return (NULL);
1690 }
1691 
1692 char *
1693 disk_readlabel(struct disklabel *dl, dev_t dev, char *errbuf, size_t errsize)
1694 {
1695 	struct vnode *vn;
1696 	dev_t chrdev, rawdev;
1697 	int error;
1698 
1699 	chrdev = blktochr(dev);
1700 	rawdev = MAKEDISKDEV(major(chrdev), DISKUNIT(chrdev), RAW_PART);
1701 
1702 #ifdef DEBUG
1703 	printf("dev=0x%x chrdev=0x%x rawdev=0x%x\n", dev, chrdev, rawdev);
1704 #endif
1705 
1706 	if (cdevvp(rawdev, &vn)) {
1707 		snprintf(errbuf, errsize,
1708 		    "cannot obtain vnode for 0x%x/0x%x", dev, rawdev);
1709 		return (errbuf);
1710 	}
1711 
1712 	error = VOP_OPEN(vn, FREAD, NOCRED, curproc);
1713 	if (error) {
1714 		snprintf(errbuf, errsize,
1715 		    "cannot open disk, 0x%x/0x%x, error %d",
1716 		    dev, rawdev, error);
1717 		goto done;
1718 	}
1719 
1720 	error = VOP_IOCTL(vn, DIOCGDINFO, (caddr_t)dl, FREAD, NOCRED, curproc);
1721 	if (error) {
1722 		snprintf(errbuf, errsize,
1723 		    "cannot read disk label, 0x%x/0x%x, error %d",
1724 		    dev, rawdev, error);
1725 	}
1726 done:
1727 	VOP_CLOSE(vn, FREAD, NOCRED, curproc);
1728 	vput(vn);
1729 	if (error)
1730 		return (errbuf);
1731 	return (NULL);
1732 }
1733 
1734 int
1735 disk_map(char *path, char *mappath, int size, int flags)
1736 {
1737 	struct disk *dk, *mdk;
1738 	u_char uid[8];
1739 	char c, part;
1740 	int i;
1741 
1742 	/*
1743 	 * Attempt to map a request for a disklabel UID to the correct device.
1744 	 * We should be supplied with a disklabel UID which has the following
1745 	 * format:
1746 	 *
1747 	 * [disklabel uid] . [partition]
1748 	 *
1749 	 * Alternatively, if the DM_OPENPART flag is set the disklabel UID can
1750 	 * based passed on its own.
1751 	 */
1752 
1753 	if (strchr(path, '/') != NULL)
1754 		return -1;
1755 
1756 	/* Verify that the device name is properly formed. */
1757 	if (!((strlen(path) == 16 && (flags & DM_OPENPART)) ||
1758 	    (strlen(path) == 18 && path[16] == '.')))
1759 		return -1;
1760 
1761 	/* Get partition. */
1762 	if (flags & DM_OPENPART)
1763 		part = 'a' + RAW_PART;
1764 	else
1765 		part = path[17];
1766 
1767 	if (part < 'a' || part >= 'a' + MAXPARTITIONS)
1768 		return -1;
1769 
1770 	/* Derive label UID. */
1771 	memset(uid, 0, sizeof(uid));
1772 	for (i = 0; i < 16; i++) {
1773 		c = path[i];
1774 		if (c >= '0' && c <= '9')
1775 			c -= '0';
1776 		else if (c >= 'a' && c <= 'f')
1777 			c -= ('a' - 10);
1778 		else
1779 			return -1;
1780 
1781 		uid[i / 2] <<= 4;
1782 		uid[i / 2] |= c & 0xf;
1783 	}
1784 
1785 	mdk = NULL;
1786 	TAILQ_FOREACH(dk, &disklist, dk_link) {
1787 		if ((dk->dk_flags & DKF_LABELVALID) && dk->dk_label &&
1788 		    memcmp(dk->dk_label->d_uid, uid,
1789 		    sizeof(dk->dk_label->d_uid)) == 0) {
1790 			/* Fail if there are duplicate UIDs! */
1791 			if (mdk != NULL)
1792 				return -1;
1793 			mdk = dk;
1794 		}
1795 	}
1796 
1797 	if (mdk == NULL || mdk->dk_name == NULL)
1798 		return -1;
1799 
1800 	snprintf(mappath, size, "/dev/%s%s%c",
1801 	    (flags & DM_OPENBLCK) ? "" : "r", mdk->dk_name, part);
1802 
1803 	return 0;
1804 }
1805 
1806 /*
1807  * Lookup a disk device and verify that it has completed attaching.
1808  */
1809 struct device *
1810 disk_lookup(struct cfdriver *cd, int unit)
1811 {
1812 	struct device *dv;
1813 	struct disk *dk;
1814 
1815 	dv = device_lookup(cd, unit);
1816 	if (dv == NULL)
1817 		return (NULL);
1818 
1819 	TAILQ_FOREACH(dk, &disklist, dk_link)
1820 		if (dk->dk_device == dv)
1821 			break;
1822 
1823 	if (dk == NULL) {
1824 		device_unref(dv);
1825 		return (NULL);
1826 	}
1827 
1828 	return (dv);
1829 }
1830 
1831 int
1832 duid_equal(u_char *duid1, u_char *duid2)
1833 {
1834 	return (memcmp(duid1, duid2, DUID_SIZE) == 0);
1835 }
1836 
1837 int
1838 duid_iszero(u_char *duid)
1839 {
1840 	u_char zeroduid[DUID_SIZE];
1841 
1842 	memset(zeroduid, 0, sizeof(zeroduid));
1843 
1844 	return (duid_equal(duid, zeroduid));
1845 }
1846 
1847 const char *
1848 duid_format(u_char *duid)
1849 {
1850 	static char duid_str[17];
1851 
1852 	KERNEL_ASSERT_LOCKED();
1853 
1854 	snprintf(duid_str, sizeof(duid_str),
1855 	    "%02x%02x%02x%02x%02x%02x%02x%02x",
1856 	    duid[0], duid[1], duid[2], duid[3],
1857 	    duid[4], duid[5], duid[6], duid[7]);
1858 
1859 	return (duid_str);
1860 }
1861