Add 'debug.sizeof.buf' sysctl for determining size of struct buf on a
[dragonfly.git] / sys / kern / subr_disk.c
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.16 2005/08/07 03:17:37 hmp 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(), 
180                             dkmakeunit(dkunit(disk->d_cdev)));
181             LIST_REMOVE(disk, d_list);
182         }
183         if (disk->d_rawsw) {
184             destroy_all_dev(disk->d_rawsw, dkunitmask(), 
185                             dkmakeunit(dkunit(disk->d_rawdev)));
186         }
187         bzero(disk, sizeof(*disk));
188 }
189
190 int
191 disk_dumpcheck(dev_t dev, u_int *count, u_int *blkno, u_int *secsize)
192 {
193         struct disk *dp;
194         struct disklabel *dl;
195         u_int boff;
196
197         dp = dev->si_disk;
198         if (!dp)
199                 return (ENXIO);
200         if (!dp->d_slice)
201                 return (ENXIO);
202         dl = dsgetlabel(dev, dp->d_slice);
203         if (!dl)
204                 return (ENXIO);
205         *count = Maxmem * (PAGE_SIZE / dl->d_secsize);
206         if (dumplo <= LABELSECTOR || 
207             (dumplo + *count > dl->d_partitions[dkpart(dev)].p_size))
208                 return (EINVAL);
209         boff = dl->d_partitions[dkpart(dev)].p_offset +
210             dp->d_slice->dss_slices[dkslice(dev)].ds_offset;
211         *blkno = boff + dumplo;
212         *secsize = dl->d_secsize;
213         return (0);
214         
215 }
216
217 void 
218 disk_invalidate (struct disk *disk)
219 {
220         if (disk->d_slice)
221                 dsgone(&disk->d_slice);
222 }
223
224 struct disk *
225 disk_enumerate(struct disk *disk)
226 {
227         if (!disk)
228                 return (LIST_FIRST(&disklist));
229         else
230                 return (LIST_NEXT(disk, d_list));
231 }
232
233 static 
234 int
235 sysctl_disks(SYSCTL_HANDLER_ARGS)
236 {
237         struct disk *disk;
238         int error, first;
239
240         disk = NULL;
241         first = 1;
242
243         while ((disk = disk_enumerate(disk))) {
244                 if (!first) {
245                         error = SYSCTL_OUT(req, " ", 1);
246                         if (error)
247                                 return error;
248                 } else {
249                         first = 0;
250                 }
251                 error = SYSCTL_OUT(req, disk->d_rawdev->si_name, strlen(disk->d_rawdev->si_name));
252                 if (error)
253                         return error;
254         }
255         error = SYSCTL_OUT(req, "", 1);
256         return error;
257 }
258  
259 SYSCTL_PROC(_kern, OID_AUTO, disks, CTLTYPE_STRING | CTLFLAG_RD, 0, NULL, 
260     sysctl_disks, "A", "names of available disks");
261
262 /*
263  * The port intercept functions
264  */
265 static
266 int
267 disk_putport(lwkt_port_t port, lwkt_msg_t lmsg)
268 {
269         struct disk *disk = (struct disk *)port;
270         cdevallmsg_t msg = (cdevallmsg_t)lmsg;
271         int error;
272
273         switch(msg->am_lmsg.ms_cmd.cm_op) {
274         case CDEV_CMD_OPEN:
275                 error = diskopen(
276                             msg->am_open.msg.dev,
277                             msg->am_open.oflags,
278                             msg->am_open.devtype,
279                             msg->am_open.td);
280                 break;
281         case CDEV_CMD_CLOSE:
282                 error = diskclose(
283                             msg->am_close.msg.dev,
284                             msg->am_close.fflag,
285                             msg->am_close.devtype,
286                             msg->am_close.td);
287                 break;
288         case CDEV_CMD_IOCTL:
289                 error = diskioctl(
290                             msg->am_ioctl.msg.dev,
291                             msg->am_ioctl.cmd,
292                             msg->am_ioctl.data,
293                             msg->am_ioctl.fflag,
294                             msg->am_ioctl.td);
295                 break;
296         case CDEV_CMD_STRATEGY:
297                 diskstrategy(msg->am_strategy.bp);
298                 error = 0;
299                 break;
300         case CDEV_CMD_PSIZE:
301                 msg->am_psize.result = diskpsize(msg->am_psize.msg.dev);
302                 error = 0;      /* XXX */
303                 break;
304         case CDEV_CMD_READ:
305                 error = physio(msg->am_read.msg.dev, 
306                                 msg->am_read.uio, msg->am_read.ioflag);
307                 break;
308         case CDEV_CMD_WRITE:
309                 error = physio(msg->am_write.msg.dev, 
310                                 msg->am_write.uio, msg->am_write.ioflag);
311                 break;
312         case CDEV_CMD_POLL:
313         case CDEV_CMD_KQFILTER:
314                 error = ENODEV;
315         case CDEV_CMD_MMAP:
316                 error = -1;
317                 break;
318         case CDEV_CMD_DUMP:
319                 error = disk_dumpcheck(msg->am_dump.msg.dev,
320                                 &msg->am_dump.count,
321                                 &msg->am_dump.blkno,
322                                 &msg->am_dump.secsize);
323                 if (error == 0) {
324                         msg->am_dump.msg.dev = disk->d_rawdev;
325                         error = lwkt_forwardmsg(disk->d_rawdev->si_port,
326                                                 &msg->am_dump.msg.msg);
327                         printf("error2 %d\n", error);
328                 }
329                 break;
330         default:
331                 error = ENOTSUP;
332                 break;
333         }
334         return(error);
335 }
336
337 /*
338  * When new device entries are instantiated, make sure they inherit our
339  * si_disk structure and block and iosize limits from the raw device.
340  *
341  * This routine is always called synchronously in the context of the 
342  * client.
343  *
344  * XXX The various io and block size constraints are not always initialized
345  * properly by devices.
346  */
347 static
348 int
349 diskclone(dev_t dev)
350 {
351         struct disk *dp;
352
353         dp = dev->si_devsw->d_data;
354         KKASSERT(dp != NULL);
355         dev->si_disk = dp;
356         dev->si_iosize_max = dp->d_rawdev->si_iosize_max;
357         dev->si_bsize_phys = dp->d_rawdev->si_bsize_phys;
358         dev->si_bsize_best = dp->d_rawdev->si_bsize_best;
359         return(0);
360 }
361
362 /*
363  * Open a disk device or partition.
364  */
365 static
366 int
367 diskopen(dev_t dev, int oflags, int devtype, struct thread *td)
368 {
369         struct disk *dp;
370         int error;
371
372         /*
373          * dp can't be NULL here XXX.
374          */
375         error = 0;
376         dp = dev->si_disk;
377         if (dp == NULL)
378                 return (ENXIO);
379
380         /*
381          * Deal with open races
382          */
383         while (dp->d_flags & DISKFLAG_LOCK) {
384                 dp->d_flags |= DISKFLAG_WANTED;
385                 error = tsleep(dp, PCATCH, "diskopen", hz);
386                 if (error)
387                         return (error);
388         }
389         dp->d_flags |= DISKFLAG_LOCK;
390
391         /*
392          * Open the underlying raw device.
393          */
394         if (!dsisopen(dp->d_slice)) {
395 #if 0
396                 if (!pdev->si_iosize_max)
397                         pdev->si_iosize_max = dev->si_iosize_max;
398 #endif
399                 error = dev_dopen(dp->d_rawdev, oflags, devtype, td);
400         }
401
402         /*
403          * Inherit properties from the underlying device now that it is
404          * open.
405          */
406         diskclone(dev);
407
408         if (error)
409                 goto out;
410         
411         error = dsopen(dev, devtype, dp->d_dsflags, &dp->d_slice, &dp->d_label);
412
413         if (!dsisopen(dp->d_slice)) 
414                 dev_dclose(dp->d_rawdev, oflags, devtype, td);
415 out:    
416         dp->d_flags &= ~DISKFLAG_LOCK;
417         if (dp->d_flags & DISKFLAG_WANTED) {
418                 dp->d_flags &= ~DISKFLAG_WANTED;
419                 wakeup(dp);
420         }
421         
422         return(error);
423 }
424
425 /*
426  * Close a disk device or partition
427  */
428 static
429 int
430 diskclose(dev_t dev, int fflag, int devtype, struct thread *td)
431 {
432         struct disk *dp;
433         int error;
434
435         error = 0;
436         dp = dev->si_disk;
437
438         dsclose(dev, devtype, dp->d_slice);
439         if (!dsisopen(dp->d_slice))
440                 error = dev_dclose(dp->d_rawdev, fflag, devtype, td);
441         return (error);
442 }
443
444 /*
445  * Execute strategy routine
446  */
447 static
448 void
449 diskstrategy(struct buf *bp)
450 {
451         struct disk *dp;
452
453         dp = bp->b_dev->si_disk;
454
455         if (dp == NULL) {
456                 bp->b_error = ENXIO;
457                 bp->b_flags |= B_ERROR;
458                 biodone(bp);
459                 return;
460         }
461         KKASSERT(bp->b_dev->si_disk == dp);
462
463         if (dscheck(bp, dp->d_slice) <= 0) {
464                 biodone(bp);
465                 return;
466         }
467         bp->b_dev = dp->d_rawdev;
468         dev_dstrategy(dp->d_rawdev, bp);
469 }
470
471 /*
472  * First execute the ioctl on the disk device, and if it isn't supported 
473  * try running it on the backing device.
474  */
475 static
476 int
477 diskioctl(dev_t dev, u_long cmd, caddr_t data, int fflag, struct thread *td)
478 {
479         struct disk *dp;
480         int error;
481
482         dp = dev->si_disk;
483         if (dp == NULL)
484                 return (ENXIO);
485
486         error = dsioctl(dev, cmd, data, fflag, &dp->d_slice);
487         if (error == ENOIOCTL)
488                 error = dev_dioctl(dp->d_rawdev, cmd, data, fflag, td);
489         return (error);
490 }
491
492 /*
493  *
494  */
495 static
496 int
497 diskpsize(dev_t dev)
498 {
499         struct disk *dp;
500
501         dp = dev->si_disk;
502         if (dp == NULL)
503                 return (-1);
504         return(dssize(dev, &dp->d_slice));
505 #if 0
506         if (dp != dev->si_disk) {
507                 dev->si_drv1 = pdev->si_drv1;
508                 dev->si_drv2 = pdev->si_drv2;
509                 /* XXX: don't set bp->b_dev->si_disk (?) */
510         }
511 #endif
512 }
513
514 SYSCTL_INT(_debug_sizeof, OID_AUTO, disklabel, CTLFLAG_RD, 
515     0, sizeof(struct disklabel), "sizeof(struct disklabel)");
516
517 SYSCTL_INT(_debug_sizeof, OID_AUTO, diskslices, CTLFLAG_RD, 
518     0, sizeof(struct diskslices), "sizeof(struct diskslices)");
519
520 SYSCTL_INT(_debug_sizeof, OID_AUTO, disk, CTLFLAG_RD, 
521     0, sizeof(struct disk), "sizeof(struct disk)");
522
523
524 /*
525  * Seek sort for disks.
526  *
527  * The buf_queue keep two queues, sorted in ascending block order.  The first
528  * queue holds those requests which are positioned after the current block
529  * (in the first request); the second, which starts at queue->switch_point,
530  * holds requests which came in after their block number was passed.  Thus
531  * we implement a one way scan, retracting after reaching the end of the drive
532  * to the first request on the second queue, at which time it becomes the
533  * first queue.
534  *
535  * A one-way scan is natural because of the way UNIX read-ahead blocks are
536  * allocated.
537  */
538 void
539 bufqdisksort(struct buf_queue_head *bufq, struct buf *bp)
540 {
541         struct buf *bq;
542         struct buf *bn;
543         struct buf *be;
544         
545         be = TAILQ_LAST(&bufq->queue, buf_queue);
546         /*
547          * If the queue is empty or we are an
548          * ordered transaction, then it's easy.
549          */
550         if ((bq = bufq_first(bufq)) == NULL || 
551             (bp->b_flags & B_ORDERED) != 0) {
552                 bufq_insert_tail(bufq, bp);
553                 return;
554         } else if (bufq->insert_point != NULL) {
555
556                 /*
557                  * A certain portion of the list is
558                  * "locked" to preserve ordering, so
559                  * we can only insert after the insert
560                  * point.
561                  */
562                 bq = bufq->insert_point;
563         } else {
564
565                 /*
566                  * If we lie before the last removed (currently active)
567                  * request, and are not inserting ourselves into the
568                  * "locked" portion of the list, then we must add ourselves
569                  * to the second request list.
570                  */
571                 if (bp->b_pblkno < bufq->last_pblkno) {
572
573                         bq = bufq->switch_point;
574                         /*
575                          * If we are starting a new secondary list,
576                          * then it's easy.
577                          */
578                         if (bq == NULL) {
579                                 bufq->switch_point = bp;
580                                 bufq_insert_tail(bufq, bp);
581                                 return;
582                         }
583                         /*
584                          * If we lie ahead of the current switch point,
585                          * insert us before the switch point and move
586                          * the switch point.
587                          */
588                         if (bp->b_pblkno < bq->b_pblkno) {
589                                 bufq->switch_point = bp;
590                                 TAILQ_INSERT_BEFORE(bq, bp, b_act);
591                                 return;
592                         }
593                 } else {
594                         if (bufq->switch_point != NULL)
595                                 be = TAILQ_PREV(bufq->switch_point,
596                                                 buf_queue, b_act);
597                         /*
598                          * If we lie between last_pblkno and bq,
599                          * insert before bq.
600                          */
601                         if (bp->b_pblkno < bq->b_pblkno) {
602                                 TAILQ_INSERT_BEFORE(bq, bp, b_act);
603                                 return;
604                         }
605                 }
606         }
607
608         /*
609          * Request is at/after our current position in the list.
610          * Optimize for sequential I/O by seeing if we go at the tail.
611          */
612         if (bp->b_pblkno > be->b_pblkno) {
613                 TAILQ_INSERT_AFTER(&bufq->queue, be, bp, b_act);
614                 return;
615         }
616
617         /* Otherwise, insertion sort */
618         while ((bn = TAILQ_NEXT(bq, b_act)) != NULL) {
619                 
620                 /*
621                  * We want to go after the current request if it is the end
622                  * of the first request list, or if the next request is a
623                  * larger cylinder than our request.
624                  */
625                 if (bn == bufq->switch_point
626                  || bp->b_pblkno < bn->b_pblkno)
627                         break;
628                 bq = bn;
629         }
630         TAILQ_INSERT_AFTER(&bufq->queue, bq, bp, b_act);
631 }
632
633
634 /*
635  * Attempt to read a disk label from a device using the indicated strategy
636  * routine.  The label must be partly set up before this: secpercyl, secsize
637  * and anything required in the strategy routine (e.g., dummy bounds for the
638  * partition containing the label) must be filled in before calling us.
639  * Returns NULL on success and an error string on failure.
640  */
641 char *
642 readdisklabel(dev_t dev, struct disklabel *lp)
643 {
644         struct buf *bp;
645         struct disklabel *dlp;
646         char *msg = NULL;
647
648         bp = geteblk((int)lp->d_secsize);
649         bp->b_dev = dev;
650         bp->b_blkno = LABELSECTOR * ((int)lp->d_secsize/DEV_BSIZE);
651         bp->b_bcount = lp->d_secsize;
652         bp->b_flags &= ~B_INVAL;
653         bp->b_flags |= B_READ;
654         BUF_STRATEGY(bp, 1);
655         if (biowait(bp))
656                 msg = "I/O error";
657         else for (dlp = (struct disklabel *)bp->b_data;
658             dlp <= (struct disklabel *)((char *)bp->b_data +
659             lp->d_secsize - sizeof(*dlp));
660             dlp = (struct disklabel *)((char *)dlp + sizeof(long))) {
661                 if (dlp->d_magic != DISKMAGIC || dlp->d_magic2 != DISKMAGIC) {
662                         if (msg == NULL)
663                                 msg = "no disk label";
664                 } else if (dlp->d_npartitions > MAXPARTITIONS ||
665                            dkcksum(dlp) != 0)
666                         msg = "disk label corrupted";
667                 else {
668                         *lp = *dlp;
669                         msg = NULL;
670                         break;
671                 }
672         }
673         bp->b_flags |= B_INVAL | B_AGE;
674         brelse(bp);
675         return (msg);
676 }
677
678 /*
679  * Check new disk label for sensibility before setting it.
680  */
681 int
682 setdisklabel(struct disklabel *olp, struct disklabel *nlp, u_long openmask)
683 {
684         int i;
685         struct partition *opp, *npp;
686
687         /*
688          * Check it is actually a disklabel we are looking at.
689          */
690         if (nlp->d_magic != DISKMAGIC || nlp->d_magic2 != DISKMAGIC ||
691             dkcksum(nlp) != 0)
692                 return (EINVAL);
693         /*
694          * For each partition that we think is open,
695          */
696         while ((i = ffs((long)openmask)) != 0) {
697                 i--;
698                 /*
699                  * Check it is not changing....
700                  */
701                 openmask &= ~(1 << i);
702                 if (nlp->d_npartitions <= i)
703                         return (EBUSY);
704                 opp = &olp->d_partitions[i];
705                 npp = &nlp->d_partitions[i];
706                 if (npp->p_offset != opp->p_offset || npp->p_size < opp->p_size)
707                         return (EBUSY);
708                 /*
709                  * Copy internally-set partition information
710                  * if new label doesn't include it.             XXX
711                  * (If we are using it then we had better stay the same type)
712                  * This is possibly dubious, as someone else noted (XXX)
713                  */
714                 if (npp->p_fstype == FS_UNUSED && opp->p_fstype != FS_UNUSED) {
715                         npp->p_fstype = opp->p_fstype;
716                         npp->p_fsize = opp->p_fsize;
717                         npp->p_frag = opp->p_frag;
718                         npp->p_cpg = opp->p_cpg;
719                 }
720         }
721         nlp->d_checksum = 0;
722         nlp->d_checksum = dkcksum(nlp);
723         *olp = *nlp;
724         return (0);
725 }
726
727 /*
728  * Write disk label back to device after modification.
729  */
730 int
731 writedisklabel(dev_t dev, struct disklabel *lp)
732 {
733         struct buf *bp;
734         struct disklabel *dlp;
735         int error = 0;
736
737         if (lp->d_partitions[RAW_PART].p_offset != 0)
738                 return (EXDEV);                 /* not quite right */
739         bp = geteblk((int)lp->d_secsize);
740         bp->b_dev = dkmodpart(dev, RAW_PART);
741         bp->b_blkno = LABELSECTOR * ((int)lp->d_secsize/DEV_BSIZE);
742         bp->b_bcount = lp->d_secsize;
743 #if 1
744         /*
745          * We read the label first to see if it's there,
746          * in which case we will put ours at the same offset into the block..
747          * (I think this is stupid [Julian])
748          * Note that you can't write a label out over a corrupted label!
749          * (also stupid.. how do you write the first one? by raw writes?)
750          */
751         bp->b_flags &= ~B_INVAL;
752         bp->b_flags |= B_READ;
753         BUF_STRATEGY(bp, 1);
754         error = biowait(bp);
755         if (error)
756                 goto done;
757         for (dlp = (struct disklabel *)bp->b_data;
758             dlp <= (struct disklabel *)
759               ((char *)bp->b_data + lp->d_secsize - sizeof(*dlp));
760             dlp = (struct disklabel *)((char *)dlp + sizeof(long))) {
761                 if (dlp->d_magic == DISKMAGIC && dlp->d_magic2 == DISKMAGIC &&
762                     dkcksum(dlp) == 0) {
763                         *dlp = *lp;
764                         bp->b_flags &= ~(B_DONE | B_READ);
765                         bp->b_flags |= B_WRITE;
766                         bp->b_dev = dkmodpart(dev, RAW_PART);
767                         BUF_STRATEGY(bp, 1);
768                         error = biowait(bp);
769                         goto done;
770                 }
771         }
772         error = ESRCH;
773 done:
774 #else
775         bzero(bp->b_data, lp->d_secsize);
776         dlp = (struct disklabel *)bp->b_data;
777         *dlp = *lp;
778         bp->b_flags &= ~B_INVAL;
779         bp->b_flags |= B_WRITE;
780         BUF_STRATEGY(bp, 1);
781         error = biowait(bp);
782 #endif
783         bp->b_flags |= B_INVAL | B_AGE;
784         brelse(bp);
785         return (error);
786 }
787
788 /*
789  * Disk error is the preface to plaintive error messages
790  * about failing disk transfers.  It prints messages of the form
791
792 hp0g: hard error reading fsbn 12345 of 12344-12347 (hp0 bn %d cn %d tn %d sn %d)
793
794  * if the offset of the error in the transfer and a disk label
795  * are both available.  blkdone should be -1 if the position of the error
796  * is unknown; the disklabel pointer may be null from drivers that have not
797  * been converted to use them.  The message is printed with printf
798  * if pri is LOG_PRINTF, otherwise it uses log at the specified priority.
799  * The message should be completed (with at least a newline) with printf
800  * or addlog, respectively.  There is no trailing space.
801  */
802 void
803 diskerr(struct buf *bp, dev_t dev, char *what, int pri, 
804         int blkdone, struct disklabel *lp)
805 {
806         int unit = dkunit(dev);
807         int slice = dkslice(dev);
808         int part = dkpart(dev);
809         char partname[2];
810         char *sname;
811         daddr_t sn;
812
813         sname = dsname(dev, unit, slice, part, partname);
814         printf("%s%s: %s %sing fsbn ", sname, partname, what,
815               bp->b_flags & B_READ ? "read" : "writ");
816         sn = bp->b_blkno;
817         if (bp->b_bcount <= DEV_BSIZE) {
818                 printf("%ld", (long)sn);
819         } else {
820                 if (blkdone >= 0) {
821                         sn += blkdone;
822                         printf("%ld of ", (long)sn);
823                 }
824                 printf("%ld-%ld", (long)bp->b_blkno,
825                     (long)(bp->b_blkno + (bp->b_bcount - 1) / DEV_BSIZE));
826         }
827         if (lp && (blkdone >= 0 || bp->b_bcount <= lp->d_secsize)) {
828 #ifdef tahoe
829                 sn *= DEV_BSIZE / lp->d_secsize;                /* XXX */
830 #endif
831                 sn += lp->d_partitions[part].p_offset;
832                 /*
833                  * XXX should add slice offset and not print the slice,
834                  * but we don't know the slice pointer.
835                  * XXX should print bp->b_pblkno so that this will work
836                  * independent of slices, labels and bad sector remapping,
837                  * but some drivers don't set bp->b_pblkno.
838                  */
839                 printf(" (%s bn %ld; cn %ld", sname, (long)sn,
840                     (long)(sn / lp->d_secpercyl));
841                 sn %= (long)lp->d_secpercyl;
842                 printf(" tn %ld sn %ld)", (long)(sn / lp->d_nsectors),
843                     (long)(sn % lp->d_nsectors));
844         }
845 }