xref: /netbsd-src/sys/kern/subr_disk_mbr.c (revision eb961d0e02b7a46a9acfa877b02df48df6637278)
1 /*	$NetBSD: subr_disk_mbr.c,v 1.17 2006/01/28 19:57:07 dsl Exp $	*/
2 
3 /*
4  * Copyright (c) 1982, 1986, 1988 Regents of the University of California.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	@(#)ufs_disksubr.c	7.16 (Berkeley) 5/4/91
32  */
33 
34 /*
35  * Code to find a NetBSD label on a disk that contains an i386 style MBR.
36  * The first NetBSD label found in the 2nd sector of a NetBSD partition
37  * is used.
38  * If we don't find a label searching the MBR, we look at the start of the
39  * disk, if that fails then a label is faked up from the MBR.
40  *
41  * If there isn't a disklabel or anything in the MBR then partition a
42  * is set to cover the whole disk.
43  * Useful for files that contain single filesystems (etc).
44  *
45  * This code will read host endian netbsd labels from little endian MBR.
46  *
47  * Based on the i386 disksubr.c
48  *
49  * Since the mbr only has 32bit fields for sector addresses, we do the same.
50  *
51  * XXX There are potential problems writing labels to disks where there
52  * is only space for 8 netbsd partitions but this code has been compiled
53  * with MAXPARTITIONS=16.
54  */
55 
56 #include <sys/cdefs.h>
57 __KERNEL_RCSID(0, "$NetBSD: subr_disk_mbr.c,v 1.17 2006/01/28 19:57:07 dsl Exp $");
58 
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/buf.h>
62 #include <sys/disklabel.h>
63 #include <sys/disk.h>
64 #include <sys/syslog.h>
65 
66 #include "opt_mbr.h"
67 
68 typedef struct mbr_partition mbr_partition_t;
69 
70 /*
71  * We allocate a buffer 2 sectors large, and look in both....
72  * That means we find labels written by other ports with different offsets.
73  * LABELSECTOR and LABELOFFSET are only used if the disk doesn't have a label.
74  */
75 #if LABELSECTOR > 1 || LABELOFFSET > 512
76 #error Invalid LABELSECTOR or LABELOFFSET
77 #endif
78 
79 #define MBR_LABELSECTOR	1
80 
81 #define SCAN_CONTINUE	0
82 #define SCAN_FOUND	1
83 #define SCAN_ERROR	2
84 
85 typedef struct mbr_args {
86 	struct disklabel *lp;
87 	void		(*strat)(struct buf *);
88 	struct buf	*bp;
89 	const char	*msg;
90 	int		error;
91 	int		written;	/* number of times we wrote label */
92 	int		found_mbr;	/* set if disk has a valid mbr */
93 	uint		label_sector;	/* where we found the label */
94 	int		action;
95 #define READ_LABEL	1
96 #define UPDATE_LABEL	2
97 #define WRITE_LABEL	3
98 } mbr_args_t;
99 
100 static int validate_label(mbr_args_t *, uint);
101 static int look_netbsd_part(mbr_args_t *, mbr_partition_t *, int, uint);
102 static int write_netbsd_label(mbr_args_t *, mbr_partition_t *, int, uint);
103 
104 static int
105 read_sector(mbr_args_t *a, uint sector, int count)
106 {
107 	struct buf *bp = a->bp;
108 	int error;
109 
110 	bp->b_blkno = sector;
111 	bp->b_bcount = count * a->lp->d_secsize;
112 	bp->b_flags = (bp->b_flags & ~(B_WRITE | B_DONE)) | B_READ;
113 	bp->b_cylinder = sector / a->lp->d_secpercyl;
114 	(*a->strat)(bp);
115 	error = biowait(bp);
116 	if (error != 0)
117 		a->error = error;
118 	return error;
119 }
120 
121 /*
122  * Scan MBR for partitions, call 'action' routine for each.
123  */
124 
125 static int
126 scan_mbr(mbr_args_t *a, int (*actn)(mbr_args_t *, mbr_partition_t *, int, uint))
127 {
128 	mbr_partition_t ptns[MBR_PART_COUNT];
129 	mbr_partition_t *dp;
130 	struct mbr_sector *mbr;
131 	uint ext_base, this_ext, next_ext;
132 	int rval;
133 	int i;
134 #ifdef COMPAT_386BSD_MBRPART
135 	int dp_386bsd = -1;
136 #endif
137 
138 	ext_base = 0;
139 	this_ext = 0;
140 	for (;;) {
141 		if (read_sector(a, this_ext, 1)) {
142 			a->msg = "dos partition I/O error";
143 			return SCAN_ERROR;
144 		}
145 
146 		/* Note: Magic number is little-endian. */
147 		mbr = (void *)a->bp->b_data;
148 		if (mbr->mbr_magic != htole16(MBR_MAGIC))
149 			return SCAN_CONTINUE;
150 
151 		/* Copy data out of buffer so action can use bp */
152 		memcpy(ptns, &mbr->mbr_parts, sizeof ptns);
153 
154 		/* Look for drivers and skip them */
155 		if (ext_base == 0 && ptns[0].mbrp_type == MBR_PTYPE_DM6_DDO) {
156 			/* We've found a DM6 DDO partition type (used by
157 			 * the Ontrack Disk Manager drivers).
158 			 *
159 			 * Ensure that there are no other partitions in the
160 			 * MBR and jump to the real partition table (stored
161 			 * in the first sector of the second track). */
162 			boolean_t ok = TRUE;
163 
164 			for (i = 1; i < MBR_PART_COUNT; i++)
165 				if (ptns[i].mbrp_type != MBR_PTYPE_UNUSED)
166 					ok = FALSE;
167 
168 			if (ok) {
169 				this_ext = le32toh(a->lp->d_secpercyl /
170 				    a->lp->d_ntracks);
171 				continue;
172 			}
173 		}
174 
175 		/* look for NetBSD partition */
176 		next_ext = 0;
177 		dp = ptns;
178 		for (i = 0; i < MBR_PART_COUNT; i++, dp++) {
179 			if (dp->mbrp_type == 0)
180 				continue;
181 			/* Check end of partition is inside disk limits */
182 			if ((uint64_t)ext_base + le32toh(dp->mbrp_start) +
183 			    le32toh(dp->mbrp_size) > a->lp->d_secperunit) {
184 				/* This mbr doesn't look good.... */
185 				a->msg = "mbr partition exceeds disk size";
186 				/* ...but don't report this as an error (yet) */
187 				return SCAN_CONTINUE;
188 			}
189 			a->found_mbr = 1;
190 			if (MBR_IS_EXTENDED(dp->mbrp_type)) {
191 				next_ext = le32toh(dp->mbrp_start);
192 				continue;
193 			}
194 #ifdef COMPAT_386BSD_MBRPART
195 			if (dp->mbrp_type == MBR_PTYPE_386BSD) {
196 				/*
197 				 * If more than one matches, take last,
198 				 * as NetBSD install tool does.
199 				 */
200 				if (this_ext == 0)
201 					dp_386bsd = i;
202 				continue;
203 			}
204 #endif
205 			rval = (*actn)(a, dp, i, this_ext);
206 			if (rval != SCAN_CONTINUE)
207 				return rval;
208 		}
209 		if (next_ext == 0)
210 			break;
211 		if (ext_base == 0) {
212 			ext_base = next_ext;
213 			next_ext = 0;
214 		}
215 		next_ext += ext_base;
216 		if (next_ext <= this_ext)
217 			break;
218 		this_ext = next_ext;
219 	}
220 #ifdef COMPAT_386BSD_MBRPART
221 	if (this_ext == 0 && dp_386bsd != -1)
222 		return (*actn)(a, &ptns[dp_386bsd], dp_386bsd, 0);
223 #endif
224 	return SCAN_CONTINUE;
225 }
226 
227 /*
228  * Attempt to read a disk label from a device
229  * using the indicated strategy routine.
230  * The label must be partly set up before this:
231  * secpercyl, secsize and anything required for a block i/o read
232  * operation in the driver's strategy/start routines
233  * must be filled in before calling us.
234  *
235  * If dos partition table requested, attempt to load it and
236  * find disklabel inside a DOS partition. Also, if bad block
237  * table needed, attempt to extract it as well. Return buffer
238  * for use in signalling errors if requested.
239  *
240  * Returns null on success and an error string on failure.
241  */
242 const char *
243 readdisklabel(dev_t dev, void (*strat)(struct buf *), struct disklabel *lp,
244     struct cpu_disklabel *osdep)
245 {
246 	struct dkbad *bdp;
247 	int rval;
248 	int i;
249 	mbr_args_t a;
250 
251 	memset(&a, 0, sizeof a);
252 	a.lp = lp;
253 	a.strat = strat;
254 	a.action = READ_LABEL;
255 
256 	/* minimal requirements for architypal disk label */
257 	if (lp->d_secsize == 0)
258 		lp->d_secsize = DEV_BSIZE;
259 	if (lp->d_secperunit == 0)
260 		lp->d_secperunit = 0x1fffffff;
261 	lp->d_npartitions = RAW_PART + 1;
262 	for (i = 0; i < RAW_PART; i++) {
263 		lp->d_partitions[i].p_size = 0;
264 		lp->d_partitions[i].p_offset = 0;
265 	}
266 	if (lp->d_partitions[RAW_PART].p_size == 0)
267 		lp->d_partitions[RAW_PART].p_size = lp->d_secperunit;
268 	lp->d_partitions[RAW_PART].p_offset = 0;
269 
270 	/*
271 	 * Set partition 'a' to be the whole disk.
272 	 * Cleared if we find an mbr or a netbsd label.
273 	 */
274 	lp->d_partitions[0].p_size = lp->d_partitions[RAW_PART].p_size;
275 	lp->d_partitions[0].p_fstype = FS_BSDFFS;
276 
277 	/* get a buffer and initialize it */
278 	a.bp = geteblk(2 * (int)lp->d_secsize);
279 	a.bp->b_dev = dev;
280 
281 	if (osdep)
282 		/*
283 		 * Scan mbr searching for netbsd partition and saving
284 		 * bios partition information to use if the netbsd one
285 		 * is absent.
286 		 */
287 		rval = scan_mbr(&a, look_netbsd_part);
288 	else
289 		rval = SCAN_CONTINUE;
290 
291 	if (rval == SCAN_CONTINUE) {
292 		/* Look at start of disk */
293 		rval = validate_label(&a, 0);
294 	}
295 
296 #if 0
297 	/*
298 	 * Save sector where we found the label for the 'don't overwrite
299 	 * the label' check in bounds_check_with_label.
300 	 */
301 	if (rval == SCAN_FOUND)
302 		xxx->label_sector = a.label_sector;
303 #endif
304 
305 	/* Obtain bad sector table if requested and present */
306 	if (rval == SCAN_FOUND && osdep && (lp->d_flags & D_BADSECT)) {
307 		struct dkbad *db;
308 		int blkno;
309 
310 		bdp = &osdep->bad;
311 		i = 0;
312 		rval = SCAN_ERROR;
313 		do {
314 			/* read a bad sector table */
315 			blkno = lp->d_secperunit - lp->d_nsectors + i;
316 			if (lp->d_secsize > DEV_BSIZE)
317 				blkno *= lp->d_secsize / DEV_BSIZE;
318 			else
319 				blkno /= DEV_BSIZE / lp->d_secsize;
320 			/* if successful, validate, otherwise try another */
321 			if (read_sector(&a, blkno, 1)) {
322 				a.msg = "bad sector table I/O error";
323 				continue;
324 			}
325 			db = (struct dkbad *)(a.bp->b_data);
326 #define DKBAD_MAGIC 0x4321
327 			if (db->bt_mbz != 0 || db->bt_flag != DKBAD_MAGIC) {
328 				a.msg = "bad sector table corrupted";
329 				continue;
330 			}
331 			rval = SCAN_FOUND;
332 			*bdp = *db;
333 			break;
334 		} while ((a.bp->b_flags & B_ERROR) && (i += 2) < 10 &&
335 			i < lp->d_nsectors);
336 	}
337 
338 	brelse(a.bp);
339 	if (rval == SCAN_ERROR || rval == SCAN_CONTINUE)
340 		return a.msg;
341 	return NULL;
342 }
343 
344 static int
345 look_netbsd_part(mbr_args_t *a, mbr_partition_t *dp, int slot, uint ext_base)
346 {
347 	struct partition *pp;
348 	int ptn_base = ext_base + le32toh(dp->mbrp_start);
349 	int rval;
350 
351 	if (
352 #ifdef COMPAT_386BSD_MBRPART
353 	    dp->mbrp_type == MBR_PTYPE_386BSD ||
354 #endif
355 	    dp->mbrp_type == MBR_PTYPE_NETBSD) {
356 		rval = validate_label(a, ptn_base);
357 
358 #if RAW_PART == 3
359 		/* Put actual location where we found the label into ptn 2 */
360 		if (rval == SCAN_FOUND || a->lp->d_partitions[2].p_size == 0) {
361 			a->lp->d_partitions[2].p_size = le32toh(dp->mbrp_size);
362 			a->lp->d_partitions[2].p_offset = ptn_base;
363 		}
364 #endif
365 
366 		/* If we got a netbsd label look no further */
367 		if (rval == SCAN_FOUND)
368 			return rval;
369 	}
370 
371 	/* Install main partitions into e..h and extended into i+ */
372 	if (ext_base == 0)
373 		slot += 4;
374 	else {
375 		slot = 4 + MBR_PART_COUNT;
376 		pp = &a->lp->d_partitions[slot];
377 		for (; slot < MAXPARTITIONS; pp++, slot++) {
378 			/* This gets called twice - avoid duplicates */
379 			if (pp->p_offset == ptn_base &&
380 			    pp->p_size == le32toh(dp->mbrp_size))
381 				break;
382 			if (pp->p_size == 0)
383 				break;
384 		}
385 	}
386 
387 	if (slot < MAXPARTITIONS) {
388 		/* Stop 'a' being the entire disk */
389 		a->lp->d_partitions[0].p_size = 0;
390 		a->lp->d_partitions[0].p_fstype = 0;
391 
392 		/* save partition info */
393 		pp = &a->lp->d_partitions[slot];
394 		pp->p_offset = ptn_base;
395 		pp->p_size = le32toh(dp->mbrp_size);
396 		pp->p_fstype = xlat_mbr_fstype(dp->mbrp_type);
397 
398 		if (slot >= a->lp->d_npartitions)
399 			a->lp->d_npartitions = slot + 1;
400 	}
401 
402 	return SCAN_CONTINUE;
403 }
404 
405 
406 static int
407 validate_label(mbr_args_t *a, uint label_sector)
408 {
409 	struct disklabel *dlp;
410 	char *dlp_lim, *dlp_byte;
411 	int error;
412 
413 	/* Next, dig out disk label */
414 	if (read_sector(a, label_sector, 2)) {
415 		a->msg = "disk label read failed";
416 		return SCAN_ERROR;
417 	}
418 
419 	/* Locate disk label within block and validate */
420 	/*
421 	 * XXX (dsl) This search may be a waste of time, a lot of other i386
422 	 * code assumes the label is at offset LABELOFFSET (=0) in the sector.
423 	 *
424 	 * If we want to support disks from other netbsd ports, then the
425 	 * code should also allow for a shorter label nearer the end of
426 	 * the disk sector, and (IIRC) labels within 8k of the disk start.
427 	 */
428 	dlp = (void *)a->bp->b_data;
429 	dlp_lim = a->bp->b_data + a->bp->b_bcount - sizeof *dlp;
430 	for (;; dlp = (void *)((char *)dlp + sizeof(long))) {
431 		if ((char *)dlp > dlp_lim) {
432 			if (a->action != WRITE_LABEL)
433 				return SCAN_CONTINUE;
434 			/* Write at arch. dependant default location */
435 			dlp_byte = a->bp->b_data + LABELOFFSET;
436 			if (label_sector)
437 				dlp_byte += MBR_LABELSECTOR * a->lp->d_secsize;
438 			else
439 				dlp_byte += LABELSECTOR * a->lp->d_secsize;
440 			dlp = (void *)dlp_byte;
441 			break;
442 		}
443 		if (dlp->d_magic != DISKMAGIC || dlp->d_magic2 != DISKMAGIC)
444 			continue;
445 		if (dlp->d_npartitions > MAXPARTITIONS || dkcksum(dlp) != 0) {
446 			a->msg = "disk label corrupted";
447 			continue;
448 		}
449 		break;
450 	}
451 
452 	switch (a->action) {
453 	case READ_LABEL:
454 		*a->lp = *dlp;
455 		a->label_sector = label_sector;
456 		return SCAN_FOUND;
457 	case UPDATE_LABEL:
458 	case WRITE_LABEL:
459 		*dlp = *a->lp;
460 		a->bp->b_flags &= ~(B_READ|B_DONE);
461 		a->bp->b_flags |= B_WRITE;
462 		(*a->strat)(a->bp);
463 		error = biowait(a->bp);
464 		if (error != 0) {
465 			a->error = error;
466 			a->msg = "disk label write failed";
467 			return SCAN_ERROR;
468 		}
469 		a->written++;
470 		/* Write label to all mbr partitions */
471 		return SCAN_CONTINUE;
472 	default:
473 		return SCAN_ERROR;
474 	}
475 }
476 
477 /*
478  * Check new disk label for sensibility
479  * before setting it.
480  */
481 int
482 setdisklabel(struct disklabel *olp, struct disklabel *nlp, u_long openmask,
483     struct cpu_disklabel *osdep)
484 {
485 	int i;
486 	struct partition *opp, *npp;
487 
488 	/* sanity clause */
489 	if (nlp->d_secpercyl == 0 || nlp->d_secsize == 0
490 		|| (nlp->d_secsize % DEV_BSIZE) != 0)
491 			return (EINVAL);
492 
493 	/* special case to allow disklabel to be invalidated */
494 	if (nlp->d_magic == 0xffffffff) {
495 		*olp = *nlp;
496 		return (0);
497 	}
498 
499 	if (nlp->d_magic != DISKMAGIC || nlp->d_magic2 != DISKMAGIC ||
500 	    dkcksum(nlp) != 0)
501 		return (EINVAL);
502 
503 	/* XXX missing check if other dos partitions will be overwritten */
504 
505 	while (openmask != 0) {
506 		i = ffs(openmask) - 1;
507 		openmask &= ~(1 << i);
508 		if (i > nlp->d_npartitions)
509 			return (EBUSY);
510 		opp = &olp->d_partitions[i];
511 		npp = &nlp->d_partitions[i];
512 		/*
513 		 * Copy internally-set partition information
514 		 * if new label doesn't include it.		XXX
515 		 */
516 		if (npp->p_fstype == FS_UNUSED && opp->p_fstype != FS_UNUSED) {
517 			*npp = *opp;
518 			continue;
519 		}
520 		if (npp->p_offset != opp->p_offset || npp->p_size < opp->p_size)
521 			return (EBUSY);
522 	}
523  	nlp->d_checksum = 0;
524  	nlp->d_checksum = dkcksum(nlp);
525 	*olp = *nlp;
526 	return (0);
527 }
528 
529 
530 /*
531  * Write disk label back to device after modification.
532  */
533 int
534 writedisklabel(dev_t dev, void (*strat)(struct buf *), struct disklabel *lp,
535     struct cpu_disklabel *osdep)
536 {
537 	mbr_args_t a;
538 
539 	memset(&a, 0, sizeof a);
540 	a.lp = lp;
541 	a.strat = strat;
542 
543 	/* get a buffer and initialize it */
544 	a.bp = geteblk(2 * (int)lp->d_secsize);
545 	a.bp->b_dev = dev;
546 
547 	/* osdep => we expect an mbr with label in netbsd ptn */
548 	a.action = osdep != NULL ? WRITE_LABEL : UPDATE_LABEL;
549 
550 	/* Write/update the label to every netbsd mbr partition */
551 	scan_mbr(&a, write_netbsd_label);
552 
553 	/* Old write the label at the start of the volume on disks that
554 	 * don't have a valid mbr (always update an existing one) */
555 	a.action = a.found_mbr ? UPDATE_LABEL : WRITE_LABEL;
556 	validate_label(&a, 0);
557 
558 	if (a.written == 0 && a.error == 0)
559 		a.error = ESRCH;
560 
561 	brelse(a.bp);
562 	return a.error;
563 }
564 
565 static int
566 write_netbsd_label(mbr_args_t *a, mbr_partition_t *dp, int slot, uint ext_base)
567 {
568 	int ptn_base = ext_base + le32toh(dp->mbrp_start);
569 
570 	if (dp->mbrp_type != MBR_PTYPE_NETBSD)
571 		return SCAN_CONTINUE;
572 
573 	return validate_label(a, ptn_base);
574 }
575 
576 
577 /*
578  * Determine the size of the transfer, and make sure it is
579  * within the boundaries of the partition. Adjust transfer
580  * if needed, and signal errors or early completion.
581  */
582 int
583 bounds_check_with_label(struct disk *dk, struct buf *bp, int wlabel)
584 {
585 	struct disklabel *lp = dk->dk_label;
586 	struct partition *p = lp->d_partitions + DISKPART(bp->b_dev);
587 	int labelsector = LABELSECTOR;
588 	int64_t sz;
589 
590 #if RAW_PART == 3
591 	labelsector += lp->d_partitions[2].p_offset;
592 #endif
593 
594 	sz = howmany(bp->b_bcount, lp->d_secsize);
595 
596 	if (bp->b_blkno + sz > p->p_size) {
597 		sz = p->p_size - bp->b_blkno;
598 		if (sz == 0) {
599 			/* If exactly at end of disk, return EOF. */
600 			bp->b_resid = bp->b_bcount;
601 			return (0);
602 		}
603 		if (sz < 0) {
604 			/* If past end of disk, return EINVAL. */
605 			bp->b_error = EINVAL;
606 			goto bad;
607 		}
608 		/* Otherwise, truncate request. */
609 		bp->b_bcount = sz << DEV_BSHIFT;
610 	}
611 
612 	/* Overwriting disk label? */
613 	if (bp->b_blkno + p->p_offset <= labelsector &&
614 	    bp->b_blkno + p->p_offset + sz > labelsector &&
615 	    (bp->b_flags & B_READ) == 0 && !wlabel) {
616 		bp->b_error = EROFS;
617 		goto bad;
618 	}
619 
620 	/* calculate cylinder for disksort to order transfers with */
621 	bp->b_cylinder = (bp->b_blkno + p->p_offset) /
622 	    (lp->d_secsize / DEV_BSIZE) / lp->d_secpercyl;
623 	return (1);
624 
625 bad:
626 	bp->b_flags |= B_ERROR;
627 	return (-1);
628 }
629