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