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