6167227ddd3b74fbaf539cdc4a27c084ab6c1764
[dragonfly.git] / sys / kern / subr_disk.c
1 /*
2  * Copyright (c) 2003,2004,2009 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  * and Alex Hornung <ahornung@gmail.com>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  * 3. Neither the name of The DragonFly Project nor the names of its
19  *    contributors may be used to endorse or promote products derived
20  *    from this software without specific, prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
26  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  * ----------------------------------------------------------------------------
36  * "THE BEER-WARE LICENSE" (Revision 42):
37  * <phk@FreeBSD.ORG> wrote this file.  As long as you retain this notice you
38  * can do whatever you want with this stuff. If we meet some day, and you think
39  * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
40  * ----------------------------------------------------------------------------
41  *
42  * Copyright (c) 1982, 1986, 1988, 1993
43  *      The Regents of the University of California.  All rights reserved.
44  * (c) UNIX System Laboratories, Inc.
45  * All or some portions of this file are derived from material licensed
46  * to the University of California by American Telephone and Telegraph
47  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
48  * the permission of UNIX System Laboratories, Inc.
49  *
50  * Redistribution and use in source and binary forms, with or without
51  * modification, are permitted provided that the following conditions
52  * are met:
53  * 1. Redistributions of source code must retain the above copyright
54  *    notice, this list of conditions and the following disclaimer.
55  * 2. Redistributions in binary form must reproduce the above copyright
56  *    notice, this list of conditions and the following disclaimer in the
57  *    documentation and/or other materials provided with the distribution.
58  * 3. All advertising materials mentioning features or use of this software
59  *    must display the following acknowledgement:
60  *      This product includes software developed by the University of
61  *      California, Berkeley and its contributors.
62  * 4. Neither the name of the University nor the names of its contributors
63  *    may be used to endorse or promote products derived from this software
64  *    without specific prior written permission.
65  *
66  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
67  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
68  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
69  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
70  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
71  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
72  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
73  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
74  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
75  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
76  * SUCH DAMAGE.
77  *
78  *      @(#)ufs_disksubr.c      8.5 (Berkeley) 1/21/94
79  * $FreeBSD: src/sys/kern/subr_disk.c,v 1.20.2.6 2001/10/05 07:14:57 peter Exp $
80  * $FreeBSD: src/sys/ufs/ufs/ufs_disksubr.c,v 1.44.2.3 2001/03/05 05:42:19 obrien 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/disklabel32.h>
92 #include <sys/disklabel64.h>
93 #include <sys/diskslice.h>
94 #include <sys/diskmbr.h>
95 #include <sys/disk.h>
96 #include <sys/kerneldump.h>
97 #include <sys/malloc.h>
98 #include <machine/md_var.h>
99 #include <sys/ctype.h>
100 #include <sys/syslog.h>
101 #include <sys/device.h>
102 #include <sys/msgport.h>
103 #include <sys/devfs.h>
104 #include <sys/thread.h>
105 #include <sys/dsched.h>
106 #include <sys/queue.h>
107 #include <sys/lock.h>
108 #include <sys/udev.h>
109 #include <sys/uuid.h>
110
111 #include <sys/buf2.h>
112 #include <sys/mplock2.h>
113 #include <sys/msgport2.h>
114 #include <sys/thread2.h>
115
116 static MALLOC_DEFINE(M_DISK, "disk", "disk data");
117 static int disk_debug_enable = 0;
118
119 static void disk_msg_autofree_reply(lwkt_port_t, lwkt_msg_t);
120 static void disk_msg_core(void *);
121 static int disk_probe_slice(struct disk *dp, cdev_t dev, int slice, int reprobe);
122 static void disk_probe(struct disk *dp, int reprobe);
123 static void _setdiskinfo(struct disk *disk, struct disk_info *info);
124 static void bioqwritereorder(struct bio_queue_head *bioq);
125 static void disk_cleanserial(char *serno);
126 static int disk_debug(int, char *, ...) __printflike(2, 3);
127 static cdev_t _disk_create_named(const char *name, int unit, struct disk *dp,
128     struct dev_ops *raw_ops, int clone);
129
130 static d_open_t diskopen;
131 static d_close_t diskclose;
132 static d_ioctl_t diskioctl;
133 static d_strategy_t diskstrategy;
134 static d_psize_t diskpsize;
135 static d_dump_t diskdump;
136
137 static LIST_HEAD(, disk) disklist = LIST_HEAD_INITIALIZER(&disklist);
138 static struct lwkt_token disklist_token;
139
140 static struct dev_ops disk_ops = {
141         { "disk", 0, D_DISK | D_MPSAFE | D_TRACKCLOSE },
142         .d_open = diskopen,
143         .d_close = diskclose,
144         .d_read = physread,
145         .d_write = physwrite,
146         .d_ioctl = diskioctl,
147         .d_strategy = diskstrategy,
148         .d_dump = diskdump,
149         .d_psize = diskpsize,
150 };
151
152 static struct objcache  *disk_msg_cache;
153
154 struct objcache_malloc_args disk_msg_malloc_args = {
155         sizeof(struct disk_msg), M_DISK };
156
157 static struct lwkt_port disk_dispose_port;
158 static struct lwkt_port disk_msg_port;
159
160 static int
161 disk_debug(int level, char *fmt, ...)
162 {
163         __va_list ap;
164
165         __va_start(ap, fmt);
166         if (level <= disk_debug_enable)
167                 kvprintf(fmt, ap);
168         __va_end(ap);
169
170         return 0;
171 }
172
173 static int
174 disk_probe_slice(struct disk *dp, cdev_t dev, int slice, int reprobe)
175 {
176         struct disk_info *info = &dp->d_info;
177         struct diskslice *sp = &dp->d_slice->dss_slices[slice];
178         disklabel_ops_t ops;
179         struct partinfo part;
180         const char *msg;
181         char uuid_buf[128];
182         cdev_t ndev;
183         int sno;
184         u_int i;
185
186         disk_debug(2, "disk_probe_slice (begin): %s (%s)\n",
187                    dev->si_name, dp->d_cdev->si_name);
188
189         sno = slice ? slice - 1 : 0;
190
191         ops = &disklabel32_ops;
192         msg = ops->op_readdisklabel(dev, sp, &sp->ds_label, info);
193         if (msg && !strcmp(msg, "no disk label")) {
194                 ops = &disklabel64_ops;
195                 msg = ops->op_readdisklabel(dev, sp, &sp->ds_label, info);
196         }
197
198         if (msg == NULL) {
199                 if (slice != WHOLE_DISK_SLICE)
200                         ops->op_adjust_label_reserved(dp->d_slice, slice, sp);
201                 else
202                         sp->ds_reserved = 0;
203
204                 sp->ds_ops = ops;
205                 for (i = 0; i < ops->op_getnumparts(sp->ds_label); i++) {
206                         ops->op_loadpartinfo(sp->ds_label, i, &part);
207                         if (part.fstype) {
208                                 if (reprobe &&
209                                     (ndev = devfs_find_device_by_name("%s%c",
210                                                 dev->si_name, 'a' + i))
211                                 ) {
212                                         /*
213                                          * Device already exists and
214                                          * is still valid.
215                                          */
216                                         ndev->si_flags |= SI_REPROBE_TEST;
217
218                                         /*
219                                          * Destroy old UUID alias
220                                          */
221                                         destroy_dev_alias(ndev, "part-by-uuid/*");
222
223                                         /* Create UUID alias */
224                                         if (!kuuid_is_nil(&part.storage_uuid)) {
225                                                 snprintf_uuid(uuid_buf,
226                                                     sizeof(uuid_buf),
227                                                     &part.storage_uuid);
228                                                 make_dev_alias(ndev,
229                                                     "part-by-uuid/%s",
230                                                     uuid_buf);
231                                                 udev_dict_set_cstr(ndev, "uuid", uuid_buf);
232                                         }
233                                 } else {
234                                         ndev = make_dev_covering(&disk_ops, dp->d_rawdev->si_ops,
235                                                 dkmakeminor(dkunit(dp->d_cdev),
236                                                             slice, i),
237                                                 UID_ROOT, GID_OPERATOR, 0640,
238                                                 "%s%c", dev->si_name, 'a'+ i);
239                                         ndev->si_parent = dev;
240                                         ndev->si_iosize_max = dev->si_iosize_max;
241                                         ndev->si_disk = dp;
242                                         udev_dict_set_cstr(ndev, "subsystem", "disk");
243                                         /* Inherit parent's disk type */
244                                         if (dp->d_disktype) {
245                                                 udev_dict_set_cstr(ndev, "disk-type",
246                                                     __DECONST(char *, dp->d_disktype));
247                                         }
248
249                                         /* Create serno alias */
250                                         if (dp->d_info.d_serialno) {
251                                                 make_dev_alias(ndev,
252                                                     "serno/%s.s%d%c",
253                                                     dp->d_info.d_serialno,
254                                                     sno, 'a' + i);
255                                         }
256
257                                         /* Create UUID alias */
258                                         if (!kuuid_is_nil(&part.storage_uuid)) {
259                                                 snprintf_uuid(uuid_buf,
260                                                     sizeof(uuid_buf),
261                                                     &part.storage_uuid);
262                                                 make_dev_alias(ndev,
263                                                     "part-by-uuid/%s",
264                                                     uuid_buf);
265                                                 udev_dict_set_cstr(ndev, "uuid", uuid_buf);
266                                         }
267                                         ndev->si_flags |= SI_REPROBE_TEST;
268                                 }
269                         }
270                 }
271         } else if (info->d_dsflags & DSO_COMPATLABEL) {
272                 msg = NULL;
273                 if (sp->ds_size >= 0x100000000ULL)
274                         ops = &disklabel64_ops;
275                 else
276                         ops = &disklabel32_ops;
277                 sp->ds_label = ops->op_clone_label(info, sp);
278         } else {
279                 if (sp->ds_type == DOSPTYP_386BSD || /* XXX */
280                     sp->ds_type == DOSPTYP_NETBSD ||
281                     sp->ds_type == DOSPTYP_OPENBSD) {
282                         log(LOG_WARNING, "%s: cannot find label (%s)\n",
283                             dev->si_name, msg);
284                 }
285
286                 if (sp->ds_label.opaque != NULL && sp->ds_ops != NULL) {
287                         /* Clear out old label - it's not around anymore */
288                         disk_debug(2,
289                             "disk_probe_slice: clear out old diskabel on %s\n",
290                             dev->si_name);
291
292                         sp->ds_ops->op_freedisklabel(&sp->ds_label);
293                         sp->ds_ops = NULL;
294                 }
295         }
296
297         if (msg == NULL) {
298                 sp->ds_wlabel = FALSE;
299         }
300
301         return (msg ? EINVAL : 0);
302 }
303
304 /*
305  * This routine is only called for newly minted drives or to reprobe
306  * a drive with no open slices.  disk_probe_slice() is called directly
307  * when reprobing partition changes within slices.
308  */
309 static void
310 disk_probe(struct disk *dp, int reprobe)
311 {
312         struct disk_info *info = &dp->d_info;
313         cdev_t dev = dp->d_cdev;
314         cdev_t ndev;
315         int error, i, sno;
316         struct diskslices *osp;
317         struct diskslice *sp;
318         char uuid_buf[128];
319
320         KKASSERT (info->d_media_blksize != 0);
321
322         osp = dp->d_slice;
323         dp->d_slice = dsmakeslicestruct(BASE_SLICE, info);
324         disk_debug(1, "disk_probe (begin): %s\n", dp->d_cdev->si_name);
325
326         error = mbrinit(dev, info, &(dp->d_slice));
327         if (error) {
328                 dsgone(&osp);
329                 return;
330         }
331
332         for (i = 0; i < dp->d_slice->dss_nslices; i++) {
333                 /*
334                  * Ignore the whole-disk slice, it has already been created.
335                  */
336                 if (i == WHOLE_DISK_SLICE)
337                         continue;
338
339 #if 1
340                 /*
341                  * Ignore the compatibility slice s0 if it's a device mapper
342                  * volume.
343                  */
344                 if ((i == COMPATIBILITY_SLICE) &&
345                     (info->d_dsflags & DSO_DEVICEMAPPER))
346                         continue;
347 #endif
348
349                 sp = &dp->d_slice->dss_slices[i];
350
351                 /*
352                  * Handle s0.  s0 is a compatibility slice if there are no
353                  * other slices and it has not otherwise been set up, else
354                  * we ignore it.
355                  */
356                 if (i == COMPATIBILITY_SLICE) {
357                         sno = 0;
358                         if (sp->ds_type == 0 &&
359                             dp->d_slice->dss_nslices == BASE_SLICE) {
360                                 sp->ds_size = info->d_media_blocks;
361                                 sp->ds_reserved = 0;
362                         }
363                 } else {
364                         sno = i - 1;
365                         sp->ds_reserved = 0;
366                 }
367
368                 /*
369                  * Ignore 0-length slices
370                  */
371                 if (sp->ds_size == 0)
372                         continue;
373
374                 if (reprobe &&
375                     (ndev = devfs_find_device_by_name("%ss%d",
376                                                       dev->si_name, sno))) {
377                         /*
378                          * Device already exists and is still valid
379                          */
380                         ndev->si_flags |= SI_REPROBE_TEST;
381
382                         /*
383                          * Destroy old UUID alias
384                          */
385                         destroy_dev_alias(ndev, "slice-by-uuid/*");
386
387                         /* Create UUID alias */
388                         if (!kuuid_is_nil(&sp->ds_stor_uuid)) {
389                                 snprintf_uuid(uuid_buf, sizeof(uuid_buf),
390                                     &sp->ds_stor_uuid);
391                                 make_dev_alias(ndev, "slice-by-uuid/%s",
392                                     uuid_buf);
393                         }
394                 } else {
395                         /*
396                          * Else create new device
397                          */
398                         ndev = make_dev_covering(&disk_ops, dp->d_rawdev->si_ops,
399                                         dkmakewholeslice(dkunit(dev), i),
400                                         UID_ROOT, GID_OPERATOR, 0640,
401                                         (info->d_dsflags & DSO_DEVICEMAPPER)?
402                                         "%s.s%d" : "%ss%d", dev->si_name, sno);
403                         ndev->si_parent = dev;
404                         ndev->si_iosize_max = dev->si_iosize_max;
405                         udev_dict_set_cstr(ndev, "subsystem", "disk");
406                         /* Inherit parent's disk type */
407                         if (dp->d_disktype) {
408                                 udev_dict_set_cstr(ndev, "disk-type",
409                                     __DECONST(char *, dp->d_disktype));
410                         }
411
412                         /* Create serno alias */
413                         if (dp->d_info.d_serialno) {
414                                 make_dev_alias(ndev, "serno/%s.s%d",
415                                                dp->d_info.d_serialno, sno);
416                         }
417
418                         /* Create UUID alias */
419                         if (!kuuid_is_nil(&sp->ds_stor_uuid)) {
420                                 snprintf_uuid(uuid_buf, sizeof(uuid_buf),
421                                     &sp->ds_stor_uuid);
422                                 make_dev_alias(ndev, "slice-by-uuid/%s",
423                                     uuid_buf);
424                         }
425
426                         ndev->si_disk = dp;
427                         ndev->si_flags |= SI_REPROBE_TEST;
428                 }
429                 sp->ds_dev = ndev;
430
431                 /*
432                  * Probe appropriate slices for a disklabel
433                  *
434                  * XXX slice type 1 used by our gpt probe code.
435                  * XXX slice type 0 used by mbr compat slice.
436                  */
437                 if (sp->ds_type == DOSPTYP_386BSD ||
438                     sp->ds_type == DOSPTYP_NETBSD ||
439                     sp->ds_type == DOSPTYP_OPENBSD ||
440                     sp->ds_type == 0 ||
441                     sp->ds_type == 1) {
442                         if (dp->d_slice->dss_first_bsd_slice == 0)
443                                 dp->d_slice->dss_first_bsd_slice = i;
444                         disk_probe_slice(dp, ndev, i, reprobe);
445                 }
446         }
447         dsgone(&osp);
448         disk_debug(1, "disk_probe (end): %s\n", dp->d_cdev->si_name);
449 }
450
451
452 static void
453 disk_msg_core(void *arg)
454 {
455         struct disk     *dp;
456         struct diskslice *sp;
457         disk_msg_t msg;
458         int run;
459
460         lwkt_gettoken(&disklist_token);
461         lwkt_initport_thread(&disk_msg_port, curthread);
462         wakeup(curthread);      /* synchronous startup */
463         lwkt_reltoken(&disklist_token);
464
465         get_mplock();   /* not mpsafe yet? */
466         run = 1;
467
468         while (run) {
469                 msg = (disk_msg_t)lwkt_waitport(&disk_msg_port, 0);
470
471                 switch (msg->hdr.u.ms_result) {
472                 case DISK_DISK_PROBE:
473                         dp = (struct disk *)msg->load;
474                         disk_debug(1,
475                                     "DISK_DISK_PROBE: %s\n",
476                                         dp->d_cdev->si_name);
477                         disk_iocom_update(dp);
478                         disk_probe(dp, 0);
479                         break;
480                 case DISK_DISK_DESTROY:
481                         dp = (struct disk *)msg->load;
482                         disk_debug(1,
483                                     "DISK_DISK_DESTROY: %s\n",
484                                         dp->d_cdev->si_name);
485                         disk_iocom_uninit(dp);
486                         devfs_destroy_related(dp->d_cdev);
487                         destroy_dev(dp->d_cdev);
488                         destroy_only_dev(dp->d_rawdev);
489
490                         lwkt_gettoken(&disklist_token);
491                         while (dp->d_refs)
492                                 tsleep(&dp->d_refs, 0, "diskdel", hz / 10);
493                         LIST_REMOVE(dp, d_list);
494                         lwkt_reltoken(&disklist_token);
495
496                         if (dp->d_info.d_serialno) {
497                                 kfree(dp->d_info.d_serialno, M_TEMP);
498                                 dp->d_info.d_serialno = NULL;
499                         }
500                         break;
501                 case DISK_UNPROBE:
502                         dp = (struct disk *)msg->load;
503                         disk_debug(1,
504                                     "DISK_DISK_UNPROBE: %s\n",
505                                         dp->d_cdev->si_name);
506                         devfs_destroy_related(dp->d_cdev);
507                         break;
508                 case DISK_SLICE_REPROBE:
509                         dp = (struct disk *)msg->load;
510                         sp = (struct diskslice *)msg->load2;
511                         devfs_clr_related_flag(sp->ds_dev,
512                                                 SI_REPROBE_TEST);
513                         disk_debug(1,
514                                     "DISK_SLICE_REPROBE: %s\n",
515                                     sp->ds_dev->si_name);
516                         disk_probe_slice(dp, sp->ds_dev,
517                                          dkslice(sp->ds_dev), 1);
518                         devfs_destroy_related_without_flag(
519                                         sp->ds_dev, SI_REPROBE_TEST);
520                         break;
521                 case DISK_DISK_REPROBE:
522                         dp = (struct disk *)msg->load;
523                         devfs_clr_related_flag(dp->d_cdev, SI_REPROBE_TEST);
524                         disk_debug(1,
525                                     "DISK_DISK_REPROBE: %s\n",
526                                     dp->d_cdev->si_name);
527                         disk_probe(dp, 1);
528                         devfs_destroy_related_without_flag(
529                                         dp->d_cdev, SI_REPROBE_TEST);
530                         break;
531                 case DISK_SYNC:
532                         disk_debug(1, "DISK_SYNC\n");
533                         break;
534                 default:
535                         devfs_debug(DEVFS_DEBUG_WARNING,
536                                     "disk_msg_core: unknown message "
537                                     "received at core\n");
538                         break;
539                 }
540                 lwkt_replymsg(&msg->hdr, 0);
541         }
542         lwkt_exit();
543 }
544
545
546 /*
547  * Acts as a message drain. Any message that is replied to here gets
548  * destroyed and the memory freed.
549  */
550 static void
551 disk_msg_autofree_reply(lwkt_port_t port, lwkt_msg_t msg)
552 {
553         objcache_put(disk_msg_cache, msg);
554 }
555
556
557 void
558 disk_msg_send(uint32_t cmd, void *load, void *load2)
559 {
560         disk_msg_t disk_msg;
561         lwkt_port_t port = &disk_msg_port;
562
563         disk_msg = objcache_get(disk_msg_cache, M_WAITOK);
564
565         lwkt_initmsg(&disk_msg->hdr, &disk_dispose_port, 0);
566
567         disk_msg->hdr.u.ms_result = cmd;
568         disk_msg->load = load;
569         disk_msg->load2 = load2;
570         KKASSERT(port);
571         lwkt_sendmsg(port, &disk_msg->hdr);
572 }
573
574 void
575 disk_msg_send_sync(uint32_t cmd, void *load, void *load2)
576 {
577         struct lwkt_port rep_port;
578         disk_msg_t disk_msg;
579         lwkt_port_t port;
580
581         disk_msg = objcache_get(disk_msg_cache, M_WAITOK);
582         port = &disk_msg_port;
583
584         /* XXX could probably use curthread's built-in msgport */
585         lwkt_initport_thread(&rep_port, curthread);
586         lwkt_initmsg(&disk_msg->hdr, &rep_port, 0);
587
588         disk_msg->hdr.u.ms_result = cmd;
589         disk_msg->load = load;
590         disk_msg->load2 = load2;
591
592         lwkt_sendmsg(port, &disk_msg->hdr);
593         lwkt_waitmsg(&disk_msg->hdr, 0);
594         objcache_put(disk_msg_cache, disk_msg);
595 }
596
597 /*
598  * Create a raw device for the dev_ops template (which is returned).  Also
599  * create a slice and unit managed disk and overload the user visible
600  * device space with it.
601  *
602  * NOTE: The returned raw device is NOT a slice and unit managed device.
603  * It is an actual raw device representing the raw disk as specified by
604  * the passed dev_ops.  The disk layer not only returns such a raw device,
605  * it also uses it internally when passing (modified) commands through.
606  */
607 cdev_t
608 disk_create(int unit, struct disk *dp, struct dev_ops *raw_ops)
609 {
610         return _disk_create_named(NULL, unit, dp, raw_ops, 0);
611 }
612
613 cdev_t
614 disk_create_clone(int unit, struct disk *dp,
615                   struct dev_ops *raw_ops)
616 {
617         return _disk_create_named(NULL, unit, dp, raw_ops, 1);
618 }
619
620 cdev_t
621 disk_create_named(const char *name, int unit, struct disk *dp,
622                   struct dev_ops *raw_ops)
623 {
624         return _disk_create_named(name, unit, dp, raw_ops, 0);
625 }
626
627 cdev_t
628 disk_create_named_clone(const char *name, int unit, struct disk *dp,
629                         struct dev_ops *raw_ops)
630 {
631         return _disk_create_named(name, unit, dp, raw_ops, 1);
632 }
633
634 static cdev_t
635 _disk_create_named(const char *name, int unit, struct disk *dp,
636                    struct dev_ops *raw_ops, int clone)
637 {
638         cdev_t rawdev;
639
640         disk_debug(1, "disk_create (begin): %s%d\n", name, unit);
641
642         if (name) {
643                 rawdev = make_only_dev(raw_ops, dkmakewholedisk(unit),
644                     UID_ROOT, GID_OPERATOR, 0640, "%s", name);
645         } else {
646                 rawdev = make_only_dev(raw_ops, dkmakewholedisk(unit),
647                     UID_ROOT, GID_OPERATOR, 0640,
648                     "%s%d", raw_ops->head.name, unit);
649         }
650
651         bzero(dp, sizeof(*dp));
652
653         dp->d_rawdev = rawdev;
654         dp->d_raw_ops = raw_ops;
655         dp->d_dev_ops = &disk_ops;
656
657         if (name) {
658                 if (clone) {
659                         dp->d_cdev = make_only_dev_covering(
660                                         &disk_ops, dp->d_rawdev->si_ops,
661                                         dkmakewholedisk(unit),
662                                         UID_ROOT, GID_OPERATOR, 0640,
663                                         "%s", name);
664                 } else {
665                         dp->d_cdev = make_dev_covering(
666                                         &disk_ops, dp->d_rawdev->si_ops,
667                                         dkmakewholedisk(unit),
668                                         UID_ROOT, GID_OPERATOR, 0640,
669                                         "%s", name);
670                 }
671         } else {
672                 if (clone) {
673                         dp->d_cdev = make_only_dev_covering(
674                                         &disk_ops, dp->d_rawdev->si_ops,
675                                         dkmakewholedisk(unit),
676                                         UID_ROOT, GID_OPERATOR, 0640,
677                                         "%s%d", raw_ops->head.name, unit);
678                 } else {
679                         dp->d_cdev = make_dev_covering(
680                                         &disk_ops, dp->d_rawdev->si_ops,
681                                         dkmakewholedisk(unit),
682                                         UID_ROOT, GID_OPERATOR, 0640,
683                                         "%s%d", raw_ops->head.name, unit);
684                 }
685         }
686
687         udev_dict_set_cstr(dp->d_cdev, "subsystem", "disk");
688         dp->d_cdev->si_disk = dp;
689
690         if (name)
691                 dsched_disk_create_callback(dp, name, unit);
692         else
693                 dsched_disk_create_callback(dp, raw_ops->head.name, unit);
694
695         lwkt_gettoken(&disklist_token);
696         LIST_INSERT_HEAD(&disklist, dp, d_list);
697         lwkt_reltoken(&disklist_token);
698
699         disk_iocom_init(dp);
700
701         disk_debug(1, "disk_create (end): %s%d\n",
702                    (name != NULL)?(name):(raw_ops->head.name), unit);
703
704         return (dp->d_rawdev);
705 }
706
707 int
708 disk_setdisktype(struct disk *disk, const char *type)
709 {
710         int error;
711
712         KKASSERT(disk != NULL);
713
714         disk->d_disktype = type;
715         error = udev_dict_set_cstr(disk->d_cdev, "disk-type",
716                                    __DECONST(char *, type));
717         return error;
718 }
719
720 int
721 disk_getopencount(struct disk *disk)
722 {
723         return disk->d_opencount;
724 }
725
726 static void
727 _setdiskinfo(struct disk *disk, struct disk_info *info)
728 {
729         char *oldserialno;
730
731         oldserialno = disk->d_info.d_serialno;
732         bcopy(info, &disk->d_info, sizeof(disk->d_info));
733         info = &disk->d_info;
734
735         disk_debug(1, "_setdiskinfo: %s\n", disk->d_cdev->si_name);
736
737         /*
738          * The serial number is duplicated so the caller can throw
739          * their copy away.
740          */
741         if (info->d_serialno && info->d_serialno[0] &&
742             (info->d_serialno[0] != ' ' || strlen(info->d_serialno) > 1)) {
743                 info->d_serialno = kstrdup(info->d_serialno, M_TEMP);
744                 disk_cleanserial(info->d_serialno);
745                 if (disk->d_cdev) {
746                         make_dev_alias(disk->d_cdev, "serno/%s",
747                                        info->d_serialno);
748                 }
749         } else {
750                 info->d_serialno = NULL;
751         }
752         if (oldserialno)
753                 kfree(oldserialno, M_TEMP);
754
755         dsched_disk_update_callback(disk, info);
756
757         /*
758          * The caller may set d_media_size or d_media_blocks and we
759          * calculate the other.
760          */
761         KKASSERT(info->d_media_size == 0 || info->d_media_blocks == 0);
762         if (info->d_media_size == 0 && info->d_media_blocks) {
763                 info->d_media_size = (u_int64_t)info->d_media_blocks *
764                                      info->d_media_blksize;
765         } else if (info->d_media_size && info->d_media_blocks == 0 &&
766                    info->d_media_blksize) {
767                 info->d_media_blocks = info->d_media_size /
768                                        info->d_media_blksize;
769         }
770
771         /*
772          * The si_* fields for rawdev are not set until after the
773          * disk_create() call, so someone using the cooked version
774          * of the raw device (i.e. da0s0) will not get the right
775          * si_iosize_max unless we fix it up here.
776          */
777         if (disk->d_cdev && disk->d_rawdev &&
778             disk->d_cdev->si_iosize_max == 0) {
779                 disk->d_cdev->si_iosize_max = disk->d_rawdev->si_iosize_max;
780                 disk->d_cdev->si_bsize_phys = disk->d_rawdev->si_bsize_phys;
781                 disk->d_cdev->si_bsize_best = disk->d_rawdev->si_bsize_best;
782         }
783
784         /* Add the serial number to the udev_dictionary */
785         if (info->d_serialno)
786                 udev_dict_set_cstr(disk->d_cdev, "serno", info->d_serialno);
787 }
788
789 /*
790  * Disk drivers must call this routine when media parameters are available
791  * or have changed.
792  */
793 void
794 disk_setdiskinfo(struct disk *disk, struct disk_info *info)
795 {
796         _setdiskinfo(disk, info);
797         disk_msg_send(DISK_DISK_PROBE, disk, NULL);
798         disk_debug(1, "disk_setdiskinfo: sent probe for %s\n",
799                    disk->d_cdev->si_name);
800 }
801
802 void
803 disk_setdiskinfo_sync(struct disk *disk, struct disk_info *info)
804 {
805         _setdiskinfo(disk, info);
806         disk_msg_send_sync(DISK_DISK_PROBE, disk, NULL);
807         disk_debug(1, "disk_setdiskinfo_sync: sent probe for %s\n",
808                    disk->d_cdev->si_name);
809 }
810
811 /*
812  * This routine is called when an adapter detaches.  The higher level
813  * managed disk device is destroyed while the lower level raw device is
814  * released.
815  */
816 void
817 disk_destroy(struct disk *disk)
818 {
819         dsched_disk_destroy_callback(disk);
820         disk_msg_send_sync(DISK_DISK_DESTROY, disk, NULL);
821         return;
822 }
823
824 int
825 disk_dumpcheck(cdev_t dev, u_int64_t *size,
826                u_int64_t *blkno, u_int32_t *secsize)
827 {
828         struct partinfo pinfo;
829         int error;
830
831         bzero(&pinfo, sizeof(pinfo));
832         error = dev_dioctl(dev, DIOCGPART, (void *)&pinfo, 0,
833                            proc0.p_ucred, NULL);
834         if (error)
835                 return (error);
836
837         if (pinfo.media_blksize == 0)
838                 return (ENXIO);
839
840         if (blkno) /* XXX: make sure this reserved stuff is right */
841                 *blkno = pinfo.reserved_blocks +
842                         pinfo.media_offset / pinfo.media_blksize;
843         if (secsize)
844                 *secsize = pinfo.media_blksize;
845         if (size)
846                 *size = (pinfo.media_blocks - pinfo.reserved_blocks);
847
848         return (0);
849 }
850
851 int
852 disk_dumpconf(cdev_t dev, u_int onoff)
853 {
854         struct dumperinfo di;
855         u_int64_t       size, blkno;
856         u_int32_t       secsize;
857         int error;
858
859         if (!onoff)
860                 return set_dumper(NULL);
861
862         error = disk_dumpcheck(dev, &size, &blkno, &secsize);
863
864         if (error)
865                 return ENXIO;
866
867         bzero(&di, sizeof(struct dumperinfo));
868         di.dumper = diskdump;
869         di.priv = dev;
870         di.blocksize = secsize;
871         di.maxiosize = dev->si_iosize_max;
872         di.mediaoffset = blkno * DEV_BSIZE;
873         di.mediasize = size * DEV_BSIZE;
874
875         return set_dumper(&di);
876 }
877
878 void
879 disk_unprobe(struct disk *disk)
880 {
881         if (disk == NULL)
882                 return;
883
884         disk_msg_send_sync(DISK_UNPROBE, disk, NULL);
885 }
886
887 void
888 disk_invalidate (struct disk *disk)
889 {
890         dsgone(&disk->d_slice);
891 }
892
893 /*
894  * Enumerate disks, pass a marker and an initial NULL dp to initialize,
895  * then loop with the previously returned dp.
896  *
897  * The returned dp will be referenced, preventing its destruction.  When
898  * you pass the returned dp back into the loop the ref is dropped.
899  *
900  * WARNING: If terminating your loop early you must call
901  *          disk_enumerate_stop().
902  */
903 struct disk *
904 disk_enumerate(struct disk *marker, struct disk *dp)
905 {
906         lwkt_gettoken(&disklist_token);
907         if (dp) {
908                 --dp->d_refs;
909                 dp = LIST_NEXT(marker, d_list);
910                 LIST_REMOVE(marker, d_list);
911         } else {
912                 bzero(marker, sizeof(*marker));
913                 marker->d_flags = DISKFLAG_MARKER;
914                 dp = LIST_FIRST(&disklist);
915         }
916         while (dp) {
917                 if ((dp->d_flags & DISKFLAG_MARKER) == 0)
918                         break;
919                 dp = LIST_NEXT(dp, d_list);
920         }
921         if (dp) {
922                 ++dp->d_refs;
923                 LIST_INSERT_AFTER(dp, marker, d_list);
924         }
925         lwkt_reltoken(&disklist_token);
926         return (dp);
927 }
928
929 /*
930  * Terminate an enumeration early.  Do not call this function if the
931  * enumeration ended normally.  dp can be NULL, indicating that you
932  * wish to retain the ref count on dp.
933  *
934  * This function removes the marker.
935  */
936 void
937 disk_enumerate_stop(struct disk *marker, struct disk *dp)
938 {
939         lwkt_gettoken(&disklist_token);
940         LIST_REMOVE(marker, d_list);
941         if (dp)
942                 --dp->d_refs;
943         lwkt_reltoken(&disklist_token);
944 }
945
946 static
947 int
948 sysctl_disks(SYSCTL_HANDLER_ARGS)
949 {
950         struct disk marker;
951         struct disk *dp;
952         int error, first;
953
954         first = 1;
955         error = 0;
956         dp = NULL;
957
958         while ((dp = disk_enumerate(&marker, dp))) {
959                 if (!first) {
960                         error = SYSCTL_OUT(req, " ", 1);
961                         if (error) {
962                                 disk_enumerate_stop(&marker, dp);
963                                 break;
964                         }
965                 } else {
966                         first = 0;
967                 }
968                 error = SYSCTL_OUT(req, dp->d_rawdev->si_name,
969                                    strlen(dp->d_rawdev->si_name));
970                 if (error) {
971                         disk_enumerate_stop(&marker, dp);
972                         break;
973                 }
974         }
975         if (error == 0)
976                 error = SYSCTL_OUT(req, "", 1);
977         return error;
978 }
979
980 SYSCTL_PROC(_kern, OID_AUTO, disks, CTLTYPE_STRING | CTLFLAG_RD, NULL, 0,
981     sysctl_disks, "A", "names of available disks");
982
983 /*
984  * Open a disk device or partition.
985  */
986 static
987 int
988 diskopen(struct dev_open_args *ap)
989 {
990         cdev_t dev = ap->a_head.a_dev;
991         struct disk *dp;
992         int error;
993
994         /*
995          * dp can't be NULL here XXX.
996          *
997          * d_slice will be NULL if setdiskinfo() has not been called yet.
998          * setdiskinfo() is typically called whether the disk is present
999          * or not (e.g. CD), but the base disk device is created first
1000          * and there may be a race.
1001          */
1002         dp = dev->si_disk;
1003         if (dp == NULL || dp->d_slice == NULL)
1004                 return (ENXIO);
1005         error = 0;
1006
1007         /*
1008          * Deal with open races
1009          */
1010         get_mplock();
1011         while (dp->d_flags & DISKFLAG_LOCK) {
1012                 dp->d_flags |= DISKFLAG_WANTED;
1013                 error = tsleep(dp, PCATCH, "diskopen", hz);
1014                 if (error) {
1015                         rel_mplock();
1016                         return (error);
1017                 }
1018         }
1019         dp->d_flags |= DISKFLAG_LOCK;
1020
1021         /*
1022          * Open the underlying raw device.
1023          */
1024         if (!dsisopen(dp->d_slice)) {
1025 #if 0
1026                 if (!pdev->si_iosize_max)
1027                         pdev->si_iosize_max = dev->si_iosize_max;
1028 #endif
1029                 error = dev_dopen(dp->d_rawdev, ap->a_oflags,
1030                                   ap->a_devtype, ap->a_cred);
1031         }
1032
1033         if (error)
1034                 goto out;
1035         error = dsopen(dev, ap->a_devtype, dp->d_info.d_dsflags,
1036                        &dp->d_slice, &dp->d_info);
1037         if (!dsisopen(dp->d_slice)) {
1038                 dev_dclose(dp->d_rawdev, ap->a_oflags, ap->a_devtype);
1039         }
1040 out:
1041         dp->d_flags &= ~DISKFLAG_LOCK;
1042         if (dp->d_flags & DISKFLAG_WANTED) {
1043                 dp->d_flags &= ~DISKFLAG_WANTED;
1044                 wakeup(dp);
1045         }
1046         rel_mplock();
1047
1048         KKASSERT(dp->d_opencount >= 0);
1049         /* If the open was successful, bump open count */
1050         if (error == 0)
1051                 atomic_add_int(&dp->d_opencount, 1);
1052
1053         return(error);
1054 }
1055
1056 /*
1057  * Close a disk device or partition
1058  */
1059 static
1060 int
1061 diskclose(struct dev_close_args *ap)
1062 {
1063         cdev_t dev = ap->a_head.a_dev;
1064         struct disk *dp;
1065         int error;
1066         int lcount;
1067
1068         error = 0;
1069         dp = dev->si_disk;
1070
1071         /*
1072          * The cdev_t represents the disk/slice/part.  The shared
1073          * dp structure governs all cdevs associated with the disk.
1074          *
1075          * As a safety only close the underlying raw device on the last
1076          * close the disk device if our tracking of the slices/partitions
1077          * also indicates nothing is open.
1078          */
1079         KKASSERT(dp->d_opencount >= 1);
1080         lcount = atomic_fetchadd_int(&dp->d_opencount, -1);
1081
1082         get_mplock();
1083         dsclose(dev, ap->a_devtype, dp->d_slice);
1084         if (lcount <= 1 && !dsisopen(dp->d_slice)) {
1085                 error = dev_dclose(dp->d_rawdev, ap->a_fflag, ap->a_devtype);
1086         }
1087         rel_mplock();
1088         return (error);
1089 }
1090
1091 /*
1092  * First execute the ioctl on the disk device, and if it isn't supported
1093  * try running it on the backing device.
1094  */
1095 static
1096 int
1097 diskioctl(struct dev_ioctl_args *ap)
1098 {
1099         cdev_t dev = ap->a_head.a_dev;
1100         struct disk *dp;
1101         int error;
1102         u_int u;
1103
1104         dp = dev->si_disk;
1105         if (dp == NULL)
1106                 return (ENXIO);
1107
1108         devfs_debug(DEVFS_DEBUG_DEBUG,
1109                     "diskioctl: cmd is: %lx (name: %s)\n",
1110                     ap->a_cmd, dev->si_name);
1111         devfs_debug(DEVFS_DEBUG_DEBUG,
1112                     "diskioctl: &dp->d_slice is: %p, %p\n",
1113                     &dp->d_slice, dp->d_slice);
1114
1115         if (ap->a_cmd == DIOCGKERNELDUMP) {
1116                 u = *(u_int *)ap->a_data;
1117                 return disk_dumpconf(dev, u);
1118         }
1119
1120         if (ap->a_cmd == DIOCRECLUSTER && dev == dp->d_cdev) {
1121                 error = disk_iocom_ioctl(dp, ap->a_cmd, ap->a_data);
1122                 return error;
1123         }
1124
1125         if (&dp->d_slice == NULL || dp->d_slice == NULL ||
1126             ((dp->d_info.d_dsflags & DSO_DEVICEMAPPER) &&
1127              dkslice(dev) == WHOLE_DISK_SLICE)) {
1128                 error = ENOIOCTL;
1129         } else {
1130                 get_mplock();
1131                 error = dsioctl(dev, ap->a_cmd, ap->a_data, ap->a_fflag,
1132                                 &dp->d_slice, &dp->d_info);
1133                 rel_mplock();
1134         }
1135
1136         if (error == ENOIOCTL) {
1137                 error = dev_dioctl(dp->d_rawdev, ap->a_cmd, ap->a_data,
1138                                    ap->a_fflag, ap->a_cred, NULL);
1139         }
1140         return (error);
1141 }
1142
1143 /*
1144  * Execute strategy routine
1145  */
1146 static
1147 int
1148 diskstrategy(struct dev_strategy_args *ap)
1149 {
1150         cdev_t dev = ap->a_head.a_dev;
1151         struct bio *bio = ap->a_bio;
1152         struct bio *nbio;
1153         struct disk *dp;
1154
1155         dp = dev->si_disk;
1156
1157         if (dp == NULL) {
1158                 bio->bio_buf->b_error = ENXIO;
1159                 bio->bio_buf->b_flags |= B_ERROR;
1160                 biodone(bio);
1161                 return(0);
1162         }
1163         KKASSERT(dev->si_disk == dp);
1164
1165         /*
1166          * The dscheck() function will also transform the slice relative
1167          * block number i.e. bio->bio_offset into a block number that can be
1168          * passed directly to the underlying raw device.  If dscheck()
1169          * returns NULL it will have handled the bio for us (e.g. EOF
1170          * or error due to being beyond the device size).
1171          */
1172         if ((nbio = dscheck(dev, bio, dp->d_slice)) != NULL) {
1173                 dsched_queue(dp, nbio);
1174         } else {
1175                 biodone(bio);
1176         }
1177         return(0);
1178 }
1179
1180 /*
1181  * Return the partition size in ?blocks?
1182  */
1183 static
1184 int
1185 diskpsize(struct dev_psize_args *ap)
1186 {
1187         cdev_t dev = ap->a_head.a_dev;
1188         struct disk *dp;
1189
1190         dp = dev->si_disk;
1191         if (dp == NULL)
1192                 return(ENODEV);
1193
1194         ap->a_result = dssize(dev, &dp->d_slice);
1195
1196         if ((ap->a_result == -1) &&
1197            (dp->d_info.d_dsflags & DSO_RAWPSIZE)) {
1198                 ap->a_head.a_dev = dp->d_rawdev;
1199                 return dev_doperate(&ap->a_head);
1200         }
1201         return(0);
1202 }
1203
1204 int
1205 diskdump(struct dev_dump_args *ap)
1206 {
1207         cdev_t dev = ap->a_head.a_dev;
1208         struct disk *dp = dev->si_disk;
1209         u_int64_t size, offset;
1210         int error;
1211
1212         error = disk_dumpcheck(dev, &size, &ap->a_blkno, &ap->a_secsize);
1213         /* XXX: this should probably go in disk_dumpcheck somehow */
1214         if (ap->a_length != 0) {
1215                 size *= DEV_BSIZE;
1216                 offset = ap->a_blkno * DEV_BSIZE;
1217                 if ((ap->a_offset < offset) ||
1218                     (ap->a_offset + ap->a_length - offset > size)) {
1219                         kprintf("Attempt to write outside dump "
1220                                 "device boundaries.\n");
1221                         error = ENOSPC;
1222                 }
1223         }
1224
1225         if (error == 0) {
1226                 ap->a_head.a_dev = dp->d_rawdev;
1227                 error = dev_doperate(&ap->a_head);
1228         }
1229
1230         return(error);
1231 }
1232
1233
1234 SYSCTL_INT(_debug_sizeof, OID_AUTO, diskslices, CTLFLAG_RD,
1235            0, sizeof(struct diskslices), "sizeof(struct diskslices)");
1236
1237 SYSCTL_INT(_debug_sizeof, OID_AUTO, disk, CTLFLAG_RD,
1238            0, sizeof(struct disk), "sizeof(struct disk)");
1239
1240 /*
1241  * Reorder interval for burst write allowance and minor write
1242  * allowance.
1243  *
1244  * We always want to trickle some writes in to make use of the
1245  * disk's zone cache.  Bursting occurs on a longer interval and only
1246  * runningbufspace is well over the hirunningspace limit.
1247  */
1248 int bioq_reorder_burst_interval = 60;   /* should be multiple of minor */
1249 SYSCTL_INT(_kern, OID_AUTO, bioq_reorder_burst_interval,
1250            CTLFLAG_RW, &bioq_reorder_burst_interval, 0, "");
1251 int bioq_reorder_minor_interval = 5;
1252 SYSCTL_INT(_kern, OID_AUTO, bioq_reorder_minor_interval,
1253            CTLFLAG_RW, &bioq_reorder_minor_interval, 0, "");
1254
1255 int bioq_reorder_burst_bytes = 3000000;
1256 SYSCTL_INT(_kern, OID_AUTO, bioq_reorder_burst_bytes,
1257            CTLFLAG_RW, &bioq_reorder_burst_bytes, 0, "");
1258 int bioq_reorder_minor_bytes = 262144;
1259 SYSCTL_INT(_kern, OID_AUTO, bioq_reorder_minor_bytes,
1260            CTLFLAG_RW, &bioq_reorder_minor_bytes, 0, "");
1261
1262
1263 /*
1264  * Order I/Os.  Generally speaking this code is designed to make better
1265  * use of drive zone caches.  A drive zone cache can typically track linear
1266  * reads or writes for around 16 zones simultaniously.
1267  *
1268  * Read prioritization issues:  It is possible for hundreds of megabytes worth
1269  * of writes to be queued asynchronously.  This creates a huge bottleneck
1270  * for reads which reduce read bandwidth to a trickle.
1271  *
1272  * To solve this problem we generally reorder reads before writes.
1273  *
1274  * However, a large number of random reads can also starve writes and
1275  * make poor use of the drive zone cache so we allow writes to trickle
1276  * in every N reads.
1277  */
1278 void
1279 bioqdisksort(struct bio_queue_head *bioq, struct bio *bio)
1280 {
1281         /*
1282          * The BIO wants to be ordered.  Adding to the tail also
1283          * causes transition to be set to NULL, forcing the ordering
1284          * of all prior I/O's.
1285          */
1286         if (bio->bio_buf->b_flags & B_ORDERED) {
1287                 bioq_insert_tail(bioq, bio);
1288                 return;
1289         }
1290
1291         switch(bio->bio_buf->b_cmd) {
1292         case BUF_CMD_READ:
1293                 if (bioq->transition) {
1294                         /*
1295                          * Insert before the first write.  Bleedover writes
1296                          * based on reorder intervals to prevent starvation.
1297                          */
1298                         TAILQ_INSERT_BEFORE(bioq->transition, bio, bio_act);
1299                         ++bioq->reorder;
1300                         if (bioq->reorder % bioq_reorder_minor_interval == 0) {
1301                                 bioqwritereorder(bioq);
1302                                 if (bioq->reorder >=
1303                                     bioq_reorder_burst_interval) {
1304                                         bioq->reorder = 0;
1305                                 }
1306                         }
1307                 } else {
1308                         /*
1309                          * No writes queued (or ordering was forced),
1310                          * insert at tail.
1311                          */
1312                         TAILQ_INSERT_TAIL(&bioq->queue, bio, bio_act);
1313                 }
1314                 break;
1315         case BUF_CMD_WRITE:
1316                 /*
1317                  * Writes are always appended.  If no writes were previously
1318                  * queued or an ordered tail insertion occured the transition
1319                  * field will be NULL.
1320                  */
1321                 TAILQ_INSERT_TAIL(&bioq->queue, bio, bio_act);
1322                 if (bioq->transition == NULL)
1323                         bioq->transition = bio;
1324                 break;
1325         default:
1326                 /*
1327                  * All other request types are forced to be ordered.
1328                  */
1329                 bioq_insert_tail(bioq, bio);
1330                 break;
1331         }
1332 }
1333
1334 /*
1335  * Move the read-write transition point to prevent reads from
1336  * completely starving our writes.  This brings a number of writes into
1337  * the fold every N reads.
1338  *
1339  * We bring a few linear writes into the fold on a minor interval
1340  * and we bring a non-linear burst of writes into the fold on a major
1341  * interval.  Bursting only occurs if runningbufspace is really high
1342  * (typically from syncs, fsyncs, or HAMMER flushes).
1343  */
1344 static
1345 void
1346 bioqwritereorder(struct bio_queue_head *bioq)
1347 {
1348         struct bio *bio;
1349         off_t next_offset;
1350         size_t left;
1351         size_t n;
1352         int check_off;
1353
1354         if (bioq->reorder < bioq_reorder_burst_interval ||
1355             !buf_runningbufspace_severe()) {
1356                 left = (size_t)bioq_reorder_minor_bytes;
1357                 check_off = 1;
1358         } else {
1359                 left = (size_t)bioq_reorder_burst_bytes;
1360                 check_off = 0;
1361         }
1362
1363         next_offset = bioq->transition->bio_offset;
1364         while ((bio = bioq->transition) != NULL &&
1365                (check_off == 0 || next_offset == bio->bio_offset)
1366         ) {
1367                 n = bio->bio_buf->b_bcount;
1368                 next_offset = bio->bio_offset + n;
1369                 bioq->transition = TAILQ_NEXT(bio, bio_act);
1370                 if (left < n)
1371                         break;
1372                 left -= n;
1373         }
1374 }
1375
1376 /*
1377  * Bounds checking against the media size, used for the raw partition.
1378  * secsize, mediasize and b_blkno must all be the same units.
1379  * Possibly this has to be DEV_BSIZE (512).
1380  */
1381 int
1382 bounds_check_with_mediasize(struct bio *bio, int secsize, uint64_t mediasize)
1383 {
1384         struct buf *bp = bio->bio_buf;
1385         int64_t sz;
1386
1387         sz = howmany(bp->b_bcount, secsize);
1388
1389         if (bio->bio_offset/DEV_BSIZE + sz > mediasize) {
1390                 sz = mediasize - bio->bio_offset/DEV_BSIZE;
1391                 if (sz == 0) {
1392                         /* If exactly at end of disk, return EOF. */
1393                         bp->b_resid = bp->b_bcount;
1394                         return 0;
1395                 }
1396                 if (sz < 0) {
1397                         /* If past end of disk, return EINVAL. */
1398                         bp->b_error = EINVAL;
1399                         return 0;
1400                 }
1401                 /* Otherwise, truncate request. */
1402                 bp->b_bcount = sz * secsize;
1403         }
1404
1405         return 1;
1406 }
1407
1408 /*
1409  * Disk error is the preface to plaintive error messages
1410  * about failing disk transfers.  It prints messages of the form
1411
1412 hp0g: hard error reading fsbn 12345 of 12344-12347 (hp0 bn %d cn %d tn %d sn %d)
1413
1414  * if the offset of the error in the transfer and a disk label
1415  * are both available.  blkdone should be -1 if the position of the error
1416  * is unknown; the disklabel pointer may be null from drivers that have not
1417  * been converted to use them.  The message is printed with kprintf
1418  * if pri is LOG_PRINTF, otherwise it uses log at the specified priority.
1419  * The message should be completed (with at least a newline) with kprintf
1420  * or log(-1, ...), respectively.  There is no trailing space.
1421  */
1422 void
1423 diskerr(struct bio *bio, cdev_t dev, const char *what, int pri, int donecnt)
1424 {
1425         struct buf *bp = bio->bio_buf;
1426         const char *term;
1427
1428         switch(bp->b_cmd) {
1429         case BUF_CMD_READ:
1430                 term = "read";
1431                 break;
1432         case BUF_CMD_WRITE:
1433                 term = "write";
1434                 break;
1435         default:
1436                 term = "access";
1437                 break;
1438         }
1439         kprintf("%s: %s %sing ", dev->si_name, what, term);
1440         kprintf("offset %012llx for %d",
1441                 (long long)bio->bio_offset,
1442                 bp->b_bcount);
1443
1444         if (donecnt)
1445                 kprintf(" (%d bytes completed)", donecnt);
1446 }
1447
1448 /*
1449  * Locate a disk device
1450  */
1451 cdev_t
1452 disk_locate(const char *devname)
1453 {
1454         return devfs_find_device_by_name("%s", devname);
1455 }
1456
1457 void
1458 disk_config(void *arg)
1459 {
1460         disk_msg_send_sync(DISK_SYNC, NULL, NULL);
1461 }
1462
1463 static void
1464 disk_init(void)
1465 {
1466         struct thread* td_core;
1467
1468         disk_msg_cache = objcache_create("disk-msg-cache", 0, 0,
1469                                          NULL, NULL, NULL,
1470                                          objcache_malloc_alloc,
1471                                          objcache_malloc_free,
1472                                          &disk_msg_malloc_args);
1473
1474         lwkt_token_init(&disklist_token, "disks");
1475
1476         /*
1477          * Initialize the reply-only port which acts as a message drain
1478          */
1479         lwkt_initport_replyonly(&disk_dispose_port, disk_msg_autofree_reply);
1480
1481         lwkt_gettoken(&disklist_token);
1482         lwkt_create(disk_msg_core, /*args*/NULL, &td_core, NULL,
1483                     0, -1, "disk_msg_core");
1484         tsleep(td_core, 0, "diskcore", 0);
1485         lwkt_reltoken(&disklist_token);
1486 }
1487
1488 static void
1489 disk_uninit(void)
1490 {
1491         objcache_destroy(disk_msg_cache);
1492 }
1493
1494 /*
1495  * Clean out illegal characters in serial numbers.
1496  */
1497 static void
1498 disk_cleanserial(char *serno)
1499 {
1500         char c;
1501
1502         while ((c = *serno) != 0) {
1503                 if (c >= 'a' && c <= 'z')
1504                         ;
1505                 else if (c >= 'A' && c <= 'Z')
1506                         ;
1507                 else if (c >= '0' && c <= '9')
1508                         ;
1509                 else if (c == '-' || c == '@' || c == '+' || c == '.')
1510                         ;
1511                 else
1512                         c = '_';
1513                 *serno++= c;
1514         }
1515 }
1516
1517 TUNABLE_INT("kern.disk_debug", &disk_debug_enable);
1518 SYSCTL_INT(_kern, OID_AUTO, disk_debug, CTLFLAG_RW, &disk_debug_enable,
1519            0, "Enable subr_disk debugging");
1520
1521 SYSINIT(disk_register, SI_SUB_PRE_DRIVERS, SI_ORDER_FIRST, disk_init, NULL);
1522 SYSUNINIT(disk_register, SI_SUB_PRE_DRIVERS, SI_ORDER_ANY, disk_uninit, NULL);