xref: /dragonfly/sys/kern/subr_disk.c (revision 43b4d1bd)
1 /*
2  * Copyright (c) 2003,2004 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
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  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  * ----------------------------------------------------------------------------
35  * "THE BEER-WARE LICENSE" (Revision 42):
36  * <phk@FreeBSD.ORG> wrote this file.  As long as you retain this notice you
37  * can do whatever you want with this stuff. If we meet some day, and you think
38  * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
39  * ----------------------------------------------------------------------------
40  *
41  * Copyright (c) 1982, 1986, 1988, 1993
42  *	The Regents of the University of California.  All rights reserved.
43  * (c) UNIX System Laboratories, Inc.
44  * All or some portions of this file are derived from material licensed
45  * to the University of California by American Telephone and Telegraph
46  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
47  * the permission of UNIX System Laboratories, Inc.
48  *
49  * Redistribution and use in source and binary forms, with or without
50  * modification, are permitted provided that the following conditions
51  * are met:
52  * 1. Redistributions of source code must retain the above copyright
53  *    notice, this list of conditions and the following disclaimer.
54  * 2. Redistributions in binary form must reproduce the above copyright
55  *    notice, this list of conditions and the following disclaimer in the
56  *    documentation and/or other materials provided with the distribution.
57  * 3. All advertising materials mentioning features or use of this software
58  *    must display the following acknowledgement:
59  *	This product includes software developed by the University of
60  *	California, Berkeley and its contributors.
61  * 4. Neither the name of the University nor the names of its contributors
62  *    may be used to endorse or promote products derived from this software
63  *    without specific prior written permission.
64  *
65  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
66  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
67  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
68  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
69  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
70  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
71  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
72  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
73  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
74  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
75  * SUCH DAMAGE.
76  *
77  *	@(#)ufs_disksubr.c	8.5 (Berkeley) 1/21/94
78  * $FreeBSD: src/sys/kern/subr_disk.c,v 1.20.2.6 2001/10/05 07:14:57 peter Exp $
79  * $FreeBSD: src/sys/ufs/ufs/ufs_disksubr.c,v 1.44.2.3 2001/03/05 05:42:19 obrien Exp $
80  * $DragonFly: src/sys/kern/subr_disk.c,v 1.13 2004/07/16 05:51:10 dillon Exp $
81  */
82 
83 #include <sys/param.h>
84 #include <sys/systm.h>
85 #include <sys/kernel.h>
86 #include <sys/proc.h>
87 #include <sys/sysctl.h>
88 #include <sys/buf.h>
89 #include <sys/conf.h>
90 #include <sys/disklabel.h>
91 #include <sys/diskslice.h>
92 #include <sys/disk.h>
93 #include <sys/malloc.h>
94 #include <sys/sysctl.h>
95 #include <machine/md_var.h>
96 #include <sys/ctype.h>
97 #include <sys/syslog.h>
98 #include <sys/device.h>
99 #include <sys/msgport.h>
100 #include <sys/msgport2.h>
101 #include <sys/buf2.h>
102 
103 static MALLOC_DEFINE(M_DISK, "disk", "disk data");
104 
105 static d_strategy_t diskstrategy;
106 static d_open_t diskopen;
107 static d_close_t diskclose;
108 static d_ioctl_t diskioctl;
109 static d_psize_t diskpsize;
110 static d_clone_t diskclone;
111 static int disk_putport(lwkt_port_t port, lwkt_msg_t msg);
112 
113 static LIST_HEAD(, disk) disklist = LIST_HEAD_INITIALIZER(&disklist);
114 
115 /*
116  * Create a slice and unit managed disk.
117  *
118  * Our port layer will be responsible for assigning pblkno and handling
119  * high level partition operations, then forwarding the requests to the
120  * raw device.
121  *
122  * The raw device (based on rawsw) is returned to the caller, NOT the
123  * slice and unit managed cdev.  The caller typically sets various
124  * driver parameters and IO limits on the returned rawdev which we must
125  * inherit when our managed device is opened.
126  */
127 dev_t
128 disk_create(int unit, struct disk *dp, int flags, struct cdevsw *rawsw)
129 {
130 	dev_t rawdev;
131 	struct cdevsw *devsw;
132 
133 	/*
134 	 * Create the raw backing device
135 	 */
136 	compile_devsw(rawsw);
137 	rawdev = make_dev(rawsw, dkmakeminor(unit, WHOLE_DISK_SLICE, RAW_PART),
138 			    UID_ROOT, GID_OPERATOR, 0640,
139 			    "%s%d", rawsw->d_name, unit);
140 
141 	/*
142 	 * Initialize our intercept port
143 	 */
144 	bzero(dp, sizeof(*dp));
145 	lwkt_initport(&dp->d_port, NULL);
146 	dp->d_port.mp_putport = disk_putport;
147 	dp->d_rawsw = rawsw;
148 
149 	/*
150 	 * We install a custom cdevsw rather then the passed cdevsw,
151 	 * and save our disk structure in d_data so we can get at it easily
152 	 * without any complex cloning code.
153 	 */
154 	devsw = cdevsw_add_override(rawdev, dkunitmask(), dkmakeunit(unit));
155 	devsw->d_port = &dp->d_port;
156 	devsw->d_data = dp;
157 	devsw->d_clone = diskclone;
158 	dp->d_devsw = devsw;
159 	dp->d_rawdev = rawdev;
160 	dp->d_cdev = make_dev(devsw,
161 			    dkmakeminor(unit, WHOLE_DISK_SLICE, RAW_PART),
162 			    UID_ROOT, GID_OPERATOR, 0640,
163 			    "%s%d", devsw->d_name, unit);
164 
165 	dp->d_dsflags = flags;
166 	LIST_INSERT_HEAD(&disklist, dp, d_list);
167 	return (dp->d_rawdev);
168 }
169 
170 /*
171  * This routine is called when an adapter detaches.  The higher level
172  * managed disk device is destroyed while the lower level raw device is
173  * released.
174  */
175 void
176 disk_destroy(struct disk *disk)
177 {
178 	if (disk->d_devsw) {
179 	    cdevsw_remove(disk->d_devsw, dkunitmask(), dkunit(disk->d_cdev));
180 	    LIST_REMOVE(disk, d_list);
181 	}
182 	if (disk->d_rawsw)
183 	    destroy_all_dev(disk->d_rawsw, dkunitmask(), dkunit(disk->d_rawdev));
184 	bzero(disk, sizeof(*disk));
185 }
186 
187 int
188 disk_dumpcheck(dev_t dev, u_int *count, u_int *blkno, u_int *secsize)
189 {
190 	struct disk *dp;
191 	struct disklabel *dl;
192 	u_int boff;
193 
194 	dp = dev->si_disk;
195 	if (!dp)
196 		return (ENXIO);
197 	if (!dp->d_slice)
198 		return (ENXIO);
199 	dl = dsgetlabel(dev, dp->d_slice);
200 	if (!dl)
201 		return (ENXIO);
202 	*count = Maxmem * (PAGE_SIZE / dl->d_secsize);
203 	if (dumplo <= LABELSECTOR ||
204 	    (dumplo + *count > dl->d_partitions[dkpart(dev)].p_size))
205 		return (EINVAL);
206 	boff = dl->d_partitions[dkpart(dev)].p_offset +
207 	    dp->d_slice->dss_slices[dkslice(dev)].ds_offset;
208 	*blkno = boff + dumplo;
209 	*secsize = dl->d_secsize;
210 	return (0);
211 
212 }
213 
214 void
215 disk_invalidate (struct disk *disk)
216 {
217 	if (disk->d_slice)
218 		dsgone(&disk->d_slice);
219 }
220 
221 struct disk *
222 disk_enumerate(struct disk *disk)
223 {
224 	if (!disk)
225 		return (LIST_FIRST(&disklist));
226 	else
227 		return (LIST_NEXT(disk, d_list));
228 }
229 
230 static
231 int
232 sysctl_disks(SYSCTL_HANDLER_ARGS)
233 {
234 	struct disk *disk;
235 	int error, first;
236 
237 	disk = NULL;
238 	first = 1;
239 
240 	while ((disk = disk_enumerate(disk))) {
241 		if (!first) {
242 			error = SYSCTL_OUT(req, " ", 1);
243 			if (error)
244 				return error;
245 		} else {
246 			first = 0;
247 		}
248 		error = SYSCTL_OUT(req, disk->d_rawdev->si_name, strlen(disk->d_rawdev->si_name));
249 		if (error)
250 			return error;
251 	}
252 	error = SYSCTL_OUT(req, "", 1);
253 	return error;
254 }
255 
256 SYSCTL_PROC(_kern, OID_AUTO, disks, CTLTYPE_STRING | CTLFLAG_RD, 0, NULL,
257     sysctl_disks, "A", "names of available disks");
258 
259 /*
260  * The port intercept functions
261  */
262 static
263 int
264 disk_putport(lwkt_port_t port, lwkt_msg_t lmsg)
265 {
266 	struct disk *disk = (struct disk *)port;
267 	cdevallmsg_t msg = (cdevallmsg_t)lmsg;
268 	int error;
269 
270 	switch(msg->am_lmsg.ms_cmd.cm_op) {
271 	case CDEV_CMD_OPEN:
272 		error = diskopen(
273 			    msg->am_open.msg.dev,
274 			    msg->am_open.oflags,
275 			    msg->am_open.devtype,
276 			    msg->am_open.td);
277 		break;
278 	case CDEV_CMD_CLOSE:
279 		error = diskclose(
280 			    msg->am_close.msg.dev,
281 			    msg->am_close.fflag,
282 			    msg->am_close.devtype,
283 			    msg->am_close.td);
284 		break;
285 	case CDEV_CMD_IOCTL:
286 		error = diskioctl(
287 			    msg->am_ioctl.msg.dev,
288 			    msg->am_ioctl.cmd,
289 			    msg->am_ioctl.data,
290 			    msg->am_ioctl.fflag,
291 			    msg->am_ioctl.td);
292 		break;
293 	case CDEV_CMD_STRATEGY:
294 		diskstrategy(msg->am_strategy.bp);
295 		error = 0;
296 		break;
297 	case CDEV_CMD_PSIZE:
298 		msg->am_psize.result = diskpsize(msg->am_psize.msg.dev);
299 		error = 0;      /* XXX */
300 		break;
301 	case CDEV_CMD_READ:
302 		error = physio(msg->am_read.msg.dev,
303 				msg->am_read.uio, msg->am_read.ioflag);
304 		break;
305 	case CDEV_CMD_WRITE:
306 		error = physio(msg->am_write.msg.dev,
307 				msg->am_write.uio, msg->am_write.ioflag);
308 		break;
309 	case CDEV_CMD_POLL:
310 	case CDEV_CMD_KQFILTER:
311 		error = ENODEV;
312 	case CDEV_CMD_MMAP:
313 		error = -1;
314 		break;
315 	case CDEV_CMD_DUMP:
316 		error = disk_dumpcheck(msg->am_dump.msg.dev,
317 				&msg->am_dump.count,
318 				&msg->am_dump.blkno,
319 				&msg->am_dump.secsize);
320 		if (error == 0) {
321 			msg->am_dump.msg.dev = disk->d_rawdev;
322 			error = lwkt_forwardmsg(disk->d_rawdev->si_port,
323 						&msg->am_dump.msg.msg);
324 			printf("error2 %d\n", error);
325 		}
326 		break;
327 	default:
328 		error = ENOTSUP;
329 		break;
330 	}
331 	return(error);
332 }
333 
334 /*
335  * When new device entries are instantiated, make sure they inherit our
336  * si_disk structure and block and iosize limits from the raw device.
337  *
338  * This routine is always called synchronously in the context of the
339  * client.
340  *
341  * XXX The various io and block size constraints are not always initialized
342  * properly by devices.
343  */
344 static
345 int
346 diskclone(dev_t dev)
347 {
348 	struct disk *dp;
349 
350 	dp = dev->si_devsw->d_data;
351 	KKASSERT(dp != NULL);
352 	dev->si_disk = dp;
353 	dev->si_iosize_max = dp->d_rawdev->si_iosize_max;
354 	dev->si_bsize_phys = dp->d_rawdev->si_bsize_phys;
355 	dev->si_bsize_best = dp->d_rawdev->si_bsize_best;
356 	return(0);
357 }
358 
359 /*
360  * Open a disk device or partition.
361  */
362 static
363 int
364 diskopen(dev_t dev, int oflags, int devtype, struct thread *td)
365 {
366 	struct disk *dp;
367 	int error;
368 
369 	/*
370 	 * dp can't be NULL here XXX.
371 	 */
372 	error = 0;
373 	dp = dev->si_disk;
374 	if (dp == NULL)
375 		return (ENXIO);
376 
377 	/*
378 	 * Deal with open races
379 	 */
380 	while (dp->d_flags & DISKFLAG_LOCK) {
381 		dp->d_flags |= DISKFLAG_WANTED;
382 		error = tsleep(dp, PCATCH, "diskopen", hz);
383 		if (error)
384 			return (error);
385 	}
386 	dp->d_flags |= DISKFLAG_LOCK;
387 
388 	/*
389 	 * Open the underlying raw device.
390 	 */
391 	if (!dsisopen(dp->d_slice)) {
392 #if 0
393 		if (!pdev->si_iosize_max)
394 			pdev->si_iosize_max = dev->si_iosize_max;
395 #endif
396 		error = dev_dopen(dp->d_rawdev, oflags, devtype, td);
397 	}
398 
399 	/*
400 	 * Inherit properties from the underlying device now that it is
401 	 * open.
402 	 */
403 	diskclone(dev);
404 
405 	if (error)
406 		goto out;
407 
408 	error = dsopen(dev, devtype, dp->d_dsflags, &dp->d_slice, &dp->d_label);
409 
410 	if (!dsisopen(dp->d_slice))
411 		dev_dclose(dp->d_rawdev, oflags, devtype, td);
412 out:
413 	dp->d_flags &= ~DISKFLAG_LOCK;
414 	if (dp->d_flags & DISKFLAG_WANTED) {
415 		dp->d_flags &= ~DISKFLAG_WANTED;
416 		wakeup(dp);
417 	}
418 
419 	return(error);
420 }
421 
422 /*
423  * Close a disk device or partition
424  */
425 static
426 int
427 diskclose(dev_t dev, int fflag, int devtype, struct thread *td)
428 {
429 	struct disk *dp;
430 	int error;
431 
432 	error = 0;
433 	dp = dev->si_disk;
434 
435 	dsclose(dev, devtype, dp->d_slice);
436 	if (!dsisopen(dp->d_slice))
437 		error = dev_dclose(dp->d_rawdev, fflag, devtype, td);
438 	return (error);
439 }
440 
441 /*
442  * Execute strategy routine
443  */
444 static
445 void
446 diskstrategy(struct buf *bp)
447 {
448 	struct disk *dp;
449 
450 	dp = bp->b_dev->si_disk;
451 
452 	if (dp == NULL) {
453 		bp->b_error = ENXIO;
454 		bp->b_flags |= B_ERROR;
455 		biodone(bp);
456 		return;
457 	}
458 	KKASSERT(bp->b_dev->si_disk == dp);
459 
460 	if (dscheck(bp, dp->d_slice) <= 0) {
461 		biodone(bp);
462 		return;
463 	}
464 	bp->b_dev = dp->d_rawdev;
465 	dev_dstrategy(dp->d_rawdev, bp);
466 }
467 
468 /*
469  * First execute the ioctl on the disk device, and if it isn't supported
470  * try running it on the backing device.
471  */
472 static
473 int
474 diskioctl(dev_t dev, u_long cmd, caddr_t data, int fflag, struct thread *td)
475 {
476 	struct disk *dp;
477 	int error;
478 
479 	dp = dev->si_disk;
480 	if (dp == NULL)
481 		return (ENXIO);
482 
483 	error = dsioctl(dev, cmd, data, fflag, &dp->d_slice);
484 	if (error == ENOIOCTL)
485 		error = dev_dioctl(dp->d_rawdev, cmd, data, fflag, td);
486 	return (error);
487 }
488 
489 /*
490  *
491  */
492 static
493 int
494 diskpsize(dev_t dev)
495 {
496 	struct disk *dp;
497 
498 	dp = dev->si_disk;
499 	if (dp == NULL)
500 		return (-1);
501 	return(dssize(dev, &dp->d_slice));
502 #if 0
503 	if (dp != dev->si_disk) {
504 		dev->si_drv1 = pdev->si_drv1;
505 		dev->si_drv2 = pdev->si_drv2;
506 		/* XXX: don't set bp->b_dev->si_disk (?) */
507 	}
508 #endif
509 }
510 
511 SYSCTL_DECL(_debug_sizeof);
512 
513 SYSCTL_INT(_debug_sizeof, OID_AUTO, disklabel, CTLFLAG_RD,
514     0, sizeof(struct disklabel), "sizeof(struct disklabel)");
515 
516 SYSCTL_INT(_debug_sizeof, OID_AUTO, diskslices, CTLFLAG_RD,
517     0, sizeof(struct diskslices), "sizeof(struct diskslices)");
518 
519 SYSCTL_INT(_debug_sizeof, OID_AUTO, disk, CTLFLAG_RD,
520     0, sizeof(struct disk), "sizeof(struct disk)");
521 
522 
523 /*
524  * Seek sort for disks.
525  *
526  * The buf_queue keep two queues, sorted in ascending block order.  The first
527  * queue holds those requests which are positioned after the current block
528  * (in the first request); the second, which starts at queue->switch_point,
529  * holds requests which came in after their block number was passed.  Thus
530  * we implement a one way scan, retracting after reaching the end of the drive
531  * to the first request on the second queue, at which time it becomes the
532  * first queue.
533  *
534  * A one-way scan is natural because of the way UNIX read-ahead blocks are
535  * allocated.
536  */
537 void
538 bufqdisksort(struct buf_queue_head *bufq, struct buf *bp)
539 {
540 	struct buf *bq;
541 	struct buf *bn;
542 	struct buf *be;
543 
544 	be = TAILQ_LAST(&bufq->queue, buf_queue);
545 	/*
546 	 * If the queue is empty or we are an
547 	 * ordered transaction, then it's easy.
548 	 */
549 	if ((bq = bufq_first(bufq)) == NULL ||
550 	    (bp->b_flags & B_ORDERED) != 0) {
551 		bufq_insert_tail(bufq, bp);
552 		return;
553 	} else if (bufq->insert_point != NULL) {
554 
555 		/*
556 		 * A certain portion of the list is
557 		 * "locked" to preserve ordering, so
558 		 * we can only insert after the insert
559 		 * point.
560 		 */
561 		bq = bufq->insert_point;
562 	} else {
563 
564 		/*
565 		 * If we lie before the last removed (currently active)
566 		 * request, and are not inserting ourselves into the
567 		 * "locked" portion of the list, then we must add ourselves
568 		 * to the second request list.
569 		 */
570 		if (bp->b_pblkno < bufq->last_pblkno) {
571 
572 			bq = bufq->switch_point;
573 			/*
574 			 * If we are starting a new secondary list,
575 			 * then it's easy.
576 			 */
577 			if (bq == NULL) {
578 				bufq->switch_point = bp;
579 				bufq_insert_tail(bufq, bp);
580 				return;
581 			}
582 			/*
583 			 * If we lie ahead of the current switch point,
584 			 * insert us before the switch point and move
585 			 * the switch point.
586 			 */
587 			if (bp->b_pblkno < bq->b_pblkno) {
588 				bufq->switch_point = bp;
589 				TAILQ_INSERT_BEFORE(bq, bp, b_act);
590 				return;
591 			}
592 		} else {
593 			if (bufq->switch_point != NULL)
594 				be = TAILQ_PREV(bufq->switch_point,
595 						buf_queue, b_act);
596 			/*
597 			 * If we lie between last_pblkno and bq,
598 			 * insert before bq.
599 			 */
600 			if (bp->b_pblkno < bq->b_pblkno) {
601 				TAILQ_INSERT_BEFORE(bq, bp, b_act);
602 				return;
603 			}
604 		}
605 	}
606 
607 	/*
608 	 * Request is at/after our current position in the list.
609 	 * Optimize for sequential I/O by seeing if we go at the tail.
610 	 */
611 	if (bp->b_pblkno > be->b_pblkno) {
612 		TAILQ_INSERT_AFTER(&bufq->queue, be, bp, b_act);
613 		return;
614 	}
615 
616 	/* Otherwise, insertion sort */
617 	while ((bn = TAILQ_NEXT(bq, b_act)) != NULL) {
618 
619 		/*
620 		 * We want to go after the current request if it is the end
621 		 * of the first request list, or if the next request is a
622 		 * larger cylinder than our request.
623 		 */
624 		if (bn == bufq->switch_point
625 		 || bp->b_pblkno < bn->b_pblkno)
626 			break;
627 		bq = bn;
628 	}
629 	TAILQ_INSERT_AFTER(&bufq->queue, bq, bp, b_act);
630 }
631 
632 
633 /*
634  * Attempt to read a disk label from a device using the indicated strategy
635  * routine.  The label must be partly set up before this: secpercyl, secsize
636  * and anything required in the strategy routine (e.g., dummy bounds for the
637  * partition containing the label) must be filled in before calling us.
638  * Returns NULL on success and an error string on failure.
639  */
640 char *
641 readdisklabel(dev_t dev, struct disklabel *lp)
642 {
643 	struct buf *bp;
644 	struct disklabel *dlp;
645 	char *msg = NULL;
646 
647 	bp = geteblk((int)lp->d_secsize);
648 	bp->b_dev = dev;
649 	bp->b_blkno = LABELSECTOR * ((int)lp->d_secsize/DEV_BSIZE);
650 	bp->b_bcount = lp->d_secsize;
651 	bp->b_flags &= ~B_INVAL;
652 	bp->b_flags |= B_READ;
653 	BUF_STRATEGY(bp, 1);
654 	if (biowait(bp))
655 		msg = "I/O error";
656 	else for (dlp = (struct disklabel *)bp->b_data;
657 	    dlp <= (struct disklabel *)((char *)bp->b_data +
658 	    lp->d_secsize - sizeof(*dlp));
659 	    dlp = (struct disklabel *)((char *)dlp + sizeof(long))) {
660 		if (dlp->d_magic != DISKMAGIC || dlp->d_magic2 != DISKMAGIC) {
661 			if (msg == NULL)
662 				msg = "no disk label";
663 		} else if (dlp->d_npartitions > MAXPARTITIONS ||
664 			   dkcksum(dlp) != 0)
665 			msg = "disk label corrupted";
666 		else {
667 			*lp = *dlp;
668 			msg = NULL;
669 			break;
670 		}
671 	}
672 	bp->b_flags |= B_INVAL | B_AGE;
673 	brelse(bp);
674 	return (msg);
675 }
676 
677 /*
678  * Check new disk label for sensibility before setting it.
679  */
680 int
681 setdisklabel(struct disklabel *olp, struct disklabel *nlp, u_long openmask)
682 {
683 	int i;
684 	struct partition *opp, *npp;
685 
686 	/*
687 	 * Check it is actually a disklabel we are looking at.
688 	 */
689 	if (nlp->d_magic != DISKMAGIC || nlp->d_magic2 != DISKMAGIC ||
690 	    dkcksum(nlp) != 0)
691 		return (EINVAL);
692 	/*
693 	 * For each partition that we think is open,
694 	 */
695 	while ((i = ffs((long)openmask)) != 0) {
696 		i--;
697 		/*
698 	 	 * Check it is not changing....
699 	 	 */
700 		openmask &= ~(1 << i);
701 		if (nlp->d_npartitions <= i)
702 			return (EBUSY);
703 		opp = &olp->d_partitions[i];
704 		npp = &nlp->d_partitions[i];
705 		if (npp->p_offset != opp->p_offset || npp->p_size < opp->p_size)
706 			return (EBUSY);
707 		/*
708 		 * Copy internally-set partition information
709 		 * if new label doesn't include it.		XXX
710 		 * (If we are using it then we had better stay the same type)
711 		 * This is possibly dubious, as someone else noted (XXX)
712 		 */
713 		if (npp->p_fstype == FS_UNUSED && opp->p_fstype != FS_UNUSED) {
714 			npp->p_fstype = opp->p_fstype;
715 			npp->p_fsize = opp->p_fsize;
716 			npp->p_frag = opp->p_frag;
717 			npp->p_cpg = opp->p_cpg;
718 		}
719 	}
720  	nlp->d_checksum = 0;
721  	nlp->d_checksum = dkcksum(nlp);
722 	*olp = *nlp;
723 	return (0);
724 }
725 
726 /*
727  * Write disk label back to device after modification.
728  */
729 int
730 writedisklabel(dev_t dev, struct disklabel *lp)
731 {
732 	struct buf *bp;
733 	struct disklabel *dlp;
734 	int error = 0;
735 
736 	if (lp->d_partitions[RAW_PART].p_offset != 0)
737 		return (EXDEV);			/* not quite right */
738 	bp = geteblk((int)lp->d_secsize);
739 	bp->b_dev = dkmodpart(dev, RAW_PART);
740 	bp->b_blkno = LABELSECTOR * ((int)lp->d_secsize/DEV_BSIZE);
741 	bp->b_bcount = lp->d_secsize;
742 #if 1
743 	/*
744 	 * We read the label first to see if it's there,
745 	 * in which case we will put ours at the same offset into the block..
746 	 * (I think this is stupid [Julian])
747 	 * Note that you can't write a label out over a corrupted label!
748 	 * (also stupid.. how do you write the first one? by raw writes?)
749 	 */
750 	bp->b_flags &= ~B_INVAL;
751 	bp->b_flags |= B_READ;
752 	BUF_STRATEGY(bp, 1);
753 	error = biowait(bp);
754 	if (error)
755 		goto done;
756 	for (dlp = (struct disklabel *)bp->b_data;
757 	    dlp <= (struct disklabel *)
758 	      ((char *)bp->b_data + lp->d_secsize - sizeof(*dlp));
759 	    dlp = (struct disklabel *)((char *)dlp + sizeof(long))) {
760 		if (dlp->d_magic == DISKMAGIC && dlp->d_magic2 == DISKMAGIC &&
761 		    dkcksum(dlp) == 0) {
762 			*dlp = *lp;
763 			bp->b_flags &= ~(B_DONE | B_READ);
764 			bp->b_flags |= B_WRITE;
765 			bp->b_dev = dkmodpart(dev, RAW_PART);
766 #ifdef __alpha__
767 			alpha_fix_srm_checksum(bp);
768 #endif
769 			BUF_STRATEGY(bp, 1);
770 			error = biowait(bp);
771 			goto done;
772 		}
773 	}
774 	error = ESRCH;
775 done:
776 #else
777 	bzero(bp->b_data, lp->d_secsize);
778 	dlp = (struct disklabel *)bp->b_data;
779 	*dlp = *lp;
780 	bp->b_flags &= ~B_INVAL;
781 	bp->b_flags |= B_WRITE;
782 	BUF_STRATEGY(bp, 1);
783 	error = biowait(bp);
784 #endif
785 	bp->b_flags |= B_INVAL | B_AGE;
786 	brelse(bp);
787 	return (error);
788 }
789 
790 /*
791  * Disk error is the preface to plaintive error messages
792  * about failing disk transfers.  It prints messages of the form
793 
794 hp0g: hard error reading fsbn 12345 of 12344-12347 (hp0 bn %d cn %d tn %d sn %d)
795 
796  * if the offset of the error in the transfer and a disk label
797  * are both available.  blkdone should be -1 if the position of the error
798  * is unknown; the disklabel pointer may be null from drivers that have not
799  * been converted to use them.  The message is printed with printf
800  * if pri is LOG_PRINTF, otherwise it uses log at the specified priority.
801  * The message should be completed (with at least a newline) with printf
802  * or addlog, respectively.  There is no trailing space.
803  */
804 void
805 diskerr(struct buf *bp, dev_t dev, char *what, int pri,
806 	int blkdone, struct disklabel *lp)
807 {
808 	int unit = dkunit(dev);
809 	int slice = dkslice(dev);
810 	int part = dkpart(dev);
811 	char partname[2];
812 	char *sname;
813 	daddr_t sn;
814 
815 	sname = dsname(dev, unit, slice, part, partname);
816 	printf("%s%s: %s %sing fsbn ", sname, partname, what,
817 	      bp->b_flags & B_READ ? "read" : "writ");
818 	sn = bp->b_blkno;
819 	if (bp->b_bcount <= DEV_BSIZE) {
820 		printf("%ld", (long)sn);
821 	} else {
822 		if (blkdone >= 0) {
823 			sn += blkdone;
824 			printf("%ld of ", (long)sn);
825 		}
826 		printf("%ld-%ld", (long)bp->b_blkno,
827 		    (long)(bp->b_blkno + (bp->b_bcount - 1) / DEV_BSIZE));
828 	}
829 	if (lp && (blkdone >= 0 || bp->b_bcount <= lp->d_secsize)) {
830 #ifdef tahoe
831 		sn *= DEV_BSIZE / lp->d_secsize;		/* XXX */
832 #endif
833 		sn += lp->d_partitions[part].p_offset;
834 		/*
835 		 * XXX should add slice offset and not print the slice,
836 		 * but we don't know the slice pointer.
837 		 * XXX should print bp->b_pblkno so that this will work
838 		 * independent of slices, labels and bad sector remapping,
839 		 * but some drivers don't set bp->b_pblkno.
840 		 */
841 		printf(" (%s bn %ld; cn %ld", sname, (long)sn,
842 		    (long)(sn / lp->d_secpercyl));
843 		sn %= (long)lp->d_secpercyl;
844 		printf(" tn %ld sn %ld)", (long)(sn / lp->d_nsectors),
845 		    (long)(sn % lp->d_nsectors));
846 	}
847 }
848