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