xref: /dragonfly/sys/bus/cam/scsi/scsi_da.c (revision 7bc7e232)
1 /*
2  * Implementation of SCSI Direct Access Peripheral driver for CAM.
3  *
4  * Copyright (c) 1997 Justin T. Gibbs.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions, and the following disclaimer,
12  *    without modification, immediately at the beginning of the file.
13  * 2. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
20  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD: src/sys/cam/scsi/scsi_da.c,v 1.42.2.46 2003/10/21 22:18:19 thomas Exp $
29  * $DragonFly: src/sys/bus/cam/scsi/scsi_da.c,v 1.47 2007/11/24 19:41:39 pavalos Exp $
30  */
31 
32 #ifdef _KERNEL
33 #include "opt_hw_wdog.h"
34 #endif /* _KERNEL */
35 
36 #include <sys/param.h>
37 #include <sys/bootmaj.h>
38 
39 #ifdef _KERNEL
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
42 #include <sys/buf.h>
43 #include <sys/sysctl.h>
44 #include <sys/taskqueue.h>
45 #endif /* _KERNEL */
46 
47 #include <sys/devicestat.h>
48 #include <sys/conf.h>
49 #ifdef _KERNEL
50 #include <sys/disk.h>
51 #include <sys/dtype.h>
52 #include <sys/eventhandler.h>
53 #include <sys/malloc.h>
54 #include <sys/cons.h>
55 #include <sys/proc.h>
56 #endif
57 #include <sys/buf2.h>
58 #ifdef _KERNEL
59 #include <sys/thread2.h>
60 #endif
61 
62 #include <machine/md_var.h>
63 
64 #ifdef _KERNEL
65 #include <vm/vm.h>
66 #include <vm/pmap.h>
67 #endif
68 
69 #ifndef _KERNEL
70 #include <stdio.h>
71 #include <string.h>
72 #endif /* _KERNEL */
73 
74 #include "../cam.h"
75 #include "../cam_ccb.h"
76 #include "../cam_extend.h"
77 #include "../cam_periph.h"
78 #include "../cam_xpt_periph.h"
79 
80 #include "scsi_message.h"
81 
82 #ifndef _KERNEL
83 #include "scsi_da.h"
84 #endif /* !_KERNEL */
85 
86 #ifdef _KERNEL
87 typedef enum {
88 	DA_STATE_PROBE,
89 	DA_STATE_PROBE2,
90 	DA_STATE_NORMAL
91 } da_state;
92 
93 typedef enum {
94 	DA_FLAG_PACK_INVALID	= 0x001,
95 	DA_FLAG_NEW_PACK	= 0x002,
96 	DA_FLAG_PACK_LOCKED	= 0x004,
97 	DA_FLAG_PACK_REMOVABLE	= 0x008,
98 	DA_FLAG_TAGGED_QUEUING	= 0x010,
99 	DA_FLAG_NEED_OTAG	= 0x020,
100 	DA_FLAG_WENT_IDLE	= 0x040,
101 	DA_FLAG_RETRY_UA	= 0x080,
102 	DA_FLAG_OPEN		= 0x100,
103 	DA_FLAG_SCTX_INIT	= 0x200
104 } da_flags;
105 
106 typedef enum {
107 	DA_Q_NONE		= 0x00,
108 	DA_Q_NO_SYNC_CACHE	= 0x01,
109 	DA_Q_NO_6_BYTE		= 0x02,
110 	DA_Q_NO_PREVENT		= 0x04
111 } da_quirks;
112 
113 typedef enum {
114 	DA_CCB_PROBE		= 0x01,
115 	DA_CCB_PROBE2		= 0x02,
116 	DA_CCB_BUFFER_IO	= 0x03,
117 	DA_CCB_WAITING		= 0x04,
118 	DA_CCB_DUMP		= 0x05,
119 	DA_CCB_TYPE_MASK	= 0x0F,
120 	DA_CCB_RETRY_UA		= 0x10
121 } da_ccb_state;
122 
123 /* Offsets into our private area for storing information */
124 #define ccb_state	ppriv_field0
125 #define ccb_bio		ppriv_ptr1
126 
127 struct disk_params {
128 	u_int8_t  heads;
129 	u_int32_t cylinders;
130 	u_int8_t  secs_per_track;
131 	u_int32_t secsize;	/* Number of bytes/sector */
132 	u_int64_t sectors;	/* total number sectors */
133 };
134 
135 struct da_softc {
136 	struct	 bio_queue_head bio_queue;
137 	struct	 devstat device_stats;
138 	SLIST_ENTRY(da_softc) links;
139 	LIST_HEAD(, ccb_hdr) pending_ccbs;
140 	da_state state;
141 	da_flags flags;
142 	da_quirks quirks;
143 	int	 minimum_cmd_size;
144 	int	 ordered_tag_count;
145 	struct	 disk_params params;
146 	struct	 disk disk;
147 	union	 ccb saved_ccb;
148 	struct task		sysctl_task;
149 	struct sysctl_ctx_list	sysctl_ctx;
150 	struct sysctl_oid	*sysctl_tree;
151 };
152 
153 struct da_quirk_entry {
154 	struct scsi_inquiry_pattern inq_pat;
155 	da_quirks quirks;
156 };
157 
158 static const char quantum[] = "QUANTUM";
159 static const char microp[] = "MICROP";
160 
161 static struct da_quirk_entry da_quirk_table[] =
162 {
163 	/* SPI, FC devices */
164 	{
165 		/*
166 		 * Fujitsu M2513A MO drives.
167 		 * Tested devices: M2513A2 firmware versions 1200 & 1300.
168 		 * (dip switch selects whether T_DIRECT or T_OPTICAL device)
169 		 * Reported by: W.Scholten <whs@xs4all.nl>
170 		 */
171 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "FUJITSU", "M2513A", "*"},
172 		/*quirks*/ DA_Q_NO_SYNC_CACHE
173 	},
174 	{
175 		/* See above. */
176 		{T_OPTICAL, SIP_MEDIA_REMOVABLE, "FUJITSU", "M2513A", "*"},
177 		/*quirks*/ DA_Q_NO_SYNC_CACHE
178 	},
179 	{
180 		/*
181 		 * This particular Fujitsu drive doesn't like the
182 		 * synchronize cache command.
183 		 * Reported by: Tom Jackson <toj@gorilla.net>
184 		 */
185 		{T_DIRECT, SIP_MEDIA_FIXED, "FUJITSU", "M2954*", "*"},
186 		/*quirks*/ DA_Q_NO_SYNC_CACHE
187 
188 	},
189 	{
190 		/*
191 		 * This drive doesn't like the synchronize cache command
192 		 * either.  Reported by: Matthew Jacob <mjacob@feral.com>
193 		 * in NetBSD PR kern/6027, August 24, 1998.
194 		 */
195 		{T_DIRECT, SIP_MEDIA_FIXED, microp, "2217*", "*"},
196 		/*quirks*/ DA_Q_NO_SYNC_CACHE
197 	},
198 	{
199 		/*
200 		 * This drive doesn't like the synchronize cache command
201 		 * either.  Reported by: Hellmuth Michaelis (hm@kts.org)
202 		 * (PR 8882).
203 		 */
204 		{T_DIRECT, SIP_MEDIA_FIXED, microp, "2112*", "*"},
205 		/*quirks*/ DA_Q_NO_SYNC_CACHE
206 	},
207 	{
208 		/*
209 		 * Doesn't like the synchronize cache command.
210 		 * Reported by: Blaz Zupan <blaz@gold.amis.net>
211 		 */
212 		{T_DIRECT, SIP_MEDIA_FIXED, "NEC", "D3847*", "*"},
213 		/*quirks*/ DA_Q_NO_SYNC_CACHE
214 	},
215 	{
216 		/*
217 		 * Doesn't like the synchronize cache command.
218 		 */
219 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "MAVERICK 540S", "*"},
220 		/*quirks*/ DA_Q_NO_SYNC_CACHE
221 	},
222 	{
223 		/*
224 		 * Doesn't like the synchronize cache command.
225 		 */
226 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "LPS525S", "*"},
227 		/*quirks*/ DA_Q_NO_SYNC_CACHE
228 	},
229 	{
230 		/*
231 		 * Doesn't work correctly with 6 byte reads/writes.
232 		 * Returns illegal request, and points to byte 9 of the
233 		 * 6-byte CDB.
234 		 * Reported by:  Adam McDougall <bsdx@spawnet.com>
235 		 */
236 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 4*", "*"},
237 		/*quirks*/ DA_Q_NO_6_BYTE
238 	},
239 	{
240 		/* See above. */
241 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 2*", "*"},
242 		/*quirks*/ DA_Q_NO_6_BYTE
243 	},
244 	/* XXX USB floppy quirks temporarily enabled for 4.9R */
245 	/* USB floppy devices supported by umass(4) */
246 	{
247 		/*
248 		 * This USB floppy drive uses the UFI command set. This
249 		 * command set is a derivative of the ATAPI command set and
250 		 * does not support READ_6 commands only READ_10. It also does
251 		 * not support sync cache (0x35).
252 		 */
253 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Y-E DATA", "USB-FDU", "*"},
254 		/*quirks*/ DA_Q_NO_SYNC_CACHE
255 	},
256 	{
257 		/* Another USB floppy */
258 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "MATSHITA", "FDD CF-VFDU*","*"},
259 		/*quirks*/ DA_Q_NO_SYNC_CACHE
260 	},
261 	{
262 		/*
263 		 * The vendor, product and version strings coming from the
264 		 * controller are null terminated instead of being padded with
265 		 * spaces. The trailing wildcard character '*' is required.
266 		 */
267 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "SMSC*", "USB FDC*","*"},
268 		/*quirks*/ DA_Q_NO_SYNC_CACHE
269 	},
270 	{
271 		/*
272 		 * SmartDisk (Mitsumi) USB floppy drive
273 		 * PR: kern/50226
274 		 */
275 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "MITSUMI", "USB FDD", "*"},
276 		/*quirks*/ DA_Q_NO_SYNC_CACHE
277 	},
278 	{
279 		/*
280 		 * The CISS RAID controllers do not support SYNC_CACHE
281 		 */
282 		{T_DIRECT, SIP_MEDIA_FIXED, "COMPAQ", "RAID*", "*"},
283 		/*quirks*/ DA_Q_NO_SYNC_CACHE
284 	},
285 #ifdef DA_OLD_QUIRKS
286 	/* USB mass storage devices supported by umass(4) */
287 	{
288 		/*
289 		 * Sony Memory Stick adapter MSAC-US1 and
290 		 * Sony PCG-C1VJ Internal Memory Stick Slot (MSC-U01).
291 		 * Make all sony MS* products use this quirk.
292 		 */
293 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Sony", "MS*", "*"},
294 		/*quirks*/ DA_Q_NO_SYNC_CACHE
295 	},
296 	{
297 		/*
298 		 * Sony Memory Stick adapter for the CLIE series
299 		 * of PalmOS PDA's
300 		 */
301 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Sony", "CLIE*", "*"},
302 		/*quirks*/ DA_Q_NO_SYNC_CACHE
303 	},
304 	{
305 		/*
306 		 * Intelligent Stick USB disk-on-key
307 		 * PR: kern/53005
308 		 */
309 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "USB Card",
310 		 "IntelligentStick*", "*"},
311 		/*quirks*/ DA_Q_NO_SYNC_CACHE
312 	},
313 	{
314 		/*
315 		 * Sony DSC cameras (DSC-S30, DSC-S50, DSC-S70)
316 		 */
317 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Sony", "Sony DSC", "*"},
318 		/*quirks*/ DA_Q_NO_SYNC_CACHE
319 	},
320 	{
321 		/*
322 		 * Microtech USB CameraMate
323 		 */
324 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "eUSB    Compact*",
325 		 "Compact Flash*", "*"},
326 		/*quirks*/ DA_Q_NO_SYNC_CACHE
327 	},
328 	{
329 		/*
330 		 * Olympus digital cameras (C-3040ZOOM, C-2040ZOOM, C-1)
331 		 */
332 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "OLYMPUS", "C-*", "*"},
333 		/*quirks*/ DA_Q_NO_SYNC_CACHE
334 	},
335 	{
336 		/*
337 		 * Olympus digital cameras (E-100RS, E-10).
338 		 */
339 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "OLYMPUS", "E-*", "*"},
340 		/*quirks*/ DA_Q_NO_SYNC_CACHE
341 	},
342 	{
343 		/*
344 		 * KingByte Pen Drives
345 		 */
346 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "NO BRAND", "PEN DRIVE", "*"},
347 		/*quirks*/ DA_Q_NO_SYNC_CACHE
348  	},
349 	{
350 		/*
351 		 * iRiver iFP MP3 player (with UMS Firmware)
352 		 * PR: kern/54881, i386/63941, kern/66124
353 		 */
354 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "iRiver", "iFP*", "*"},
355 		/*quirks*/ DA_Q_NO_SYNC_CACHE
356  	},
357 	{
358 		/*
359 		 * Frontier Labs NEX IA+ Digital Audio Player, rev 1.10/0.01
360 		 * PR: kern/70158
361 		 */
362 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "FL" , "NexIA+*", "*"},
363 		/*quirks*/ DA_Q_NO_SYNC_CACHE
364 	},
365  	{
366 		/*
367 		 * FujiFilm Camera
368 		 */
369  		{T_DIRECT, SIP_MEDIA_REMOVABLE, "FUJIFILMUSB-DRIVEUNIT",
370 		 "USB-DRIVEUNIT", "*"},
371  		/*quirks*/ DA_Q_NO_SYNC_CACHE
372  	},
373 	{
374 		/*
375 		 * Minolta Dimage E203
376 		 */
377 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "MINOLTA", "DiMAGE E203", "*"},
378 		/*quirks*/ DA_Q_NO_SYNC_CACHE
379 	},
380 	{
381 		/*
382 		 * Apacer HandyDrive
383 		 * PR: kern/43627
384 		 */
385 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Apacer", "HandyDrive", "*"},
386 		/*quirks*/ DA_Q_NO_SYNC_CACHE
387 	},
388 	{
389 		/*
390 		 * Daisy Technology PhotoClip on Zoran chip
391 		 * PR: kern/43580
392 		 */
393 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "ZORAN", "COACH", "*"},
394 		/*quirks*/ DA_Q_NO_SYNC_CACHE
395 	},
396 	{
397 		/*
398 		 * Sony USB Key-Storage
399 		 * PR: kern/46386
400 		 */
401 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Sony", "Storage Media", "*"},
402 		/*quirks*/ DA_Q_NO_SYNC_CACHE
403 	},
404 #endif /* DA_OLD_QUIRKS */
405 	{
406 		/*
407 		 * EXATELECOM (Sigmatel) i-Bead 100/105 USB Flash MP3 Player
408 		 * PR: kern/51675
409 		 */
410 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "EXATEL", "i-BEAD10*", "*"},
411 		/*quirks*/ DA_Q_NO_SYNC_CACHE
412 	},
413 	{
414 		/*
415 		 * Jungsoft NEXDISK USB flash key
416 		 * PR: kern/54737
417 		 */
418 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "JUNGSOFT", "NEXDISK*", "*"},
419 		/*quirks*/ DA_Q_NO_SYNC_CACHE
420 	},
421 	{
422 		/*
423 		 * Creative Nomad MUVO mp3 player (USB)
424 		 * PR: kern/53094
425 		 */
426 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "CREATIVE", "NOMAD_MUVO", "*"},
427 		/*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
428 	},
429 };
430 
431 static	d_open_t	daopen;
432 static	d_close_t	daclose;
433 static	d_strategy_t	dastrategy;
434 static	d_ioctl_t	daioctl;
435 static	d_dump_t	dadump;
436 static	periph_init_t	dainit;
437 static	void		daasync(void *callback_arg, u_int32_t code,
438 				struct cam_path *path, void *arg);
439 static	int		dacmdsizesysctl(SYSCTL_HANDLER_ARGS);
440 static	periph_ctor_t	daregister;
441 static	periph_dtor_t	dacleanup;
442 static	periph_start_t	dastart;
443 static	periph_oninv_t	daoninvalidate;
444 static	void		dadone(struct cam_periph *periph,
445 			       union ccb *done_ccb);
446 static  int		daerror(union ccb *ccb, u_int32_t cam_flags,
447 				u_int32_t sense_flags);
448 static void		daprevent(struct cam_periph *periph, int action);
449 static int		dagetcapacity(struct cam_periph *periph);
450 static void		dasetgeom(struct cam_periph *periph, uint32_t block_len,
451 				  uint64_t maxsector);
452 
453 static timeout_t	dasendorderedtag;
454 static void		dashutdown(void *arg, int howto);
455 
456 #ifndef DA_DEFAULT_TIMEOUT
457 #define DA_DEFAULT_TIMEOUT 60	/* Timeout in seconds */
458 #endif
459 
460 #ifndef	DA_DEFAULT_RETRY
461 #define	DA_DEFAULT_RETRY	4
462 #endif
463 
464 static int da_retry_count = DA_DEFAULT_RETRY;
465 static int da_default_timeout = DA_DEFAULT_TIMEOUT;
466 static struct callout dasendorderedtag_ch;
467 
468 SYSCTL_NODE(_kern_cam, OID_AUTO, da, CTLFLAG_RD, 0,
469             "CAM Direct Access Disk driver");
470 SYSCTL_INT(_kern_cam_da, OID_AUTO, retry_count, CTLFLAG_RW,
471            &da_retry_count, 0, "Normal I/O retry count");
472 TUNABLE_INT("kern.cam.da.retry_count", &da_retry_count);
473 SYSCTL_INT(_kern_cam_da, OID_AUTO, default_timeout, CTLFLAG_RW,
474            &da_default_timeout, 0, "Normal I/O timeout (in seconds)");
475 TUNABLE_INT("kern.cam.da.default_timeout", &da_default_timeout);
476 
477 /*
478  * DA_ORDEREDTAG_INTERVAL determines how often, relative
479  * to the default timeout, we check to see whether an ordered
480  * tagged transaction is appropriate to prevent simple tag
481  * starvation.  Since we'd like to ensure that there is at least
482  * 1/2 of the timeout length left for a starved transaction to
483  * complete after we've sent an ordered tag, we must poll at least
484  * four times in every timeout period.  This takes care of the worst
485  * case where a starved transaction starts during an interval that
486  * meets the requirement "don't send an ordered tag" test so it takes
487  * us two intervals to determine that a tag must be sent.
488  */
489 #ifndef DA_ORDEREDTAG_INTERVAL
490 #define DA_ORDEREDTAG_INTERVAL 4
491 #endif
492 
493 static struct periph_driver dadriver =
494 {
495 	dainit, "da",
496 	TAILQ_HEAD_INITIALIZER(dadriver.units), /* generation */ 0
497 };
498 
499 PERIPHDRIVER_DECLARE(da, dadriver);
500 
501 /* For 2.2-stable support */
502 #ifndef D_DISK
503 #define D_DISK 0
504 #endif
505 
506 static struct dev_ops da_ops = {
507 	{ "da", DA_CDEV_MAJOR, D_DISK },
508 	.d_open =	daopen,
509 	.d_close =	daclose,
510 	.d_read =	physread,
511 	.d_write =	physwrite,
512 	.d_ioctl =	daioctl,
513 	.d_strategy =	dastrategy,
514 	.d_dump =	dadump
515 };
516 
517 static SLIST_HEAD(,da_softc) softc_list;
518 static struct extend_array *daperiphs;
519 
520 static int
521 daopen(struct dev_open_args *ap)
522 {
523 	cdev_t dev = ap->a_head.a_dev;
524 	struct cam_periph *periph;
525 	struct da_softc *softc;
526 	struct disk_info info;
527 	int unit;
528 	int error;
529 
530 	unit = dkunit(dev);
531 	crit_enter();
532 	periph = cam_extend_get(daperiphs, unit);
533 	if (periph == NULL) {
534 		crit_exit();
535 		return (ENXIO);
536 	}
537 
538 	softc = (struct da_softc *)periph->softc;
539 
540 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
541 	    ("daopen: dev=%s (unit %d)\n", devtoname(dev),
542 	     unit));
543 
544 	if ((error = cam_periph_lock(periph, PCATCH)) != 0) {
545 		crit_exit();
546 		return (error); /* error code from tsleep */
547 	}
548 
549 	if ((softc->flags & DA_FLAG_OPEN) == 0) {
550 		if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
551 			crit_exit();
552 			return(ENXIO);
553 		}
554 		softc->flags |= DA_FLAG_OPEN;
555 	}
556 
557 	if ((softc->flags & DA_FLAG_PACK_INVALID) != 0) {
558 		/* Invalidate our pack information. */
559 		disk_invalidate(&softc->disk);
560 		softc->flags &= ~DA_FLAG_PACK_INVALID;
561 	}
562 	crit_exit();
563 
564 	error = dagetcapacity(periph);
565 
566 #if 0
567 	/* Do a read capacity */
568 	{
569 		struct scsi_read_capacity_data *rcap;
570 		union  ccb *ccb;
571 
572 		rcap = kmalloc(sizeof(*rcap), M_TEMP, M_INTWAIT | M_ZERO);
573 
574 		ccb = cam_periph_getccb(periph, /*priority*/1);
575 		scsi_read_capacity(&ccb->csio,
576 				   /*retries*/1,
577 				   /*cbfncp*/dadone,
578 				   MSG_SIMPLE_Q_TAG,
579 				   rcap,
580 				   SSD_FULL_SIZE,
581 				   /*timeout*/60000);
582 		ccb->ccb_h.ccb_bio = NULL;
583 
584 		error = cam_periph_runccb(ccb, daerror, /*cam_flags*/0,
585 					  /*sense_flags*/SF_RETRY_UA |
586 							 SF_RETRY_SELTO,
587 					  &softc->device_stats);
588 
589 		xpt_release_ccb(ccb);
590 
591 		if (error == 0) {
592 			dasetgeom(periph, rcap);
593 		}
594 
595 		kfree(rcap, M_TEMP);
596 	}
597 #endif
598 
599 	if (error == 0) {
600 		struct ccb_getdev cgd;
601 
602 		/* Build disk information structure */
603 		bzero(&info, sizeof(info));
604 		info.d_type = DTYPE_SCSI;
605 
606 		/*
607 		 * Grab the inquiry data to get the vendor and product names.
608 		 * Put them in the typename and packname for the label.
609 		 */
610 		xpt_setup_ccb(&cgd.ccb_h, periph->path, /*priority*/ 1);
611 		cgd.ccb_h.func_code = XPT_GDEV_TYPE;
612 		xpt_action((union ccb *)&cgd);
613 
614 #if 0
615 		strncpy(label->d_typename, cgd.inq_data.vendor,
616 			min(SID_VENDOR_SIZE, sizeof(label->d_typename)));
617 		strncpy(label->d_packname, cgd.inq_data.product,
618 			min(SID_PRODUCT_SIZE, sizeof(label->d_packname)));
619 #endif
620 
621 		/*
622 		 * Mandatory fields
623 		 */
624 		info.d_media_blksize = softc->params.secsize;
625 		info.d_media_blocks = softc->params.sectors;
626 		info.d_media_size = 0;
627 
628 		/*
629 		 * Optional fields
630 		 */
631 		info.d_secpertrack = softc->params.secs_per_track;
632 		info.d_nheads = softc->params.heads;
633 		info.d_ncylinders = softc->params.cylinders;
634 		info.d_secpercyl = softc->params.heads *
635 				   softc->params.secs_per_track;
636 		disk_setdiskinfo(&softc->disk, &info);
637 
638 		/*
639 		 * Check to see whether or not the blocksize is set yet.
640 		 * If it isn't, set it and then clear the blocksize
641 		 * unavailable flag for the device statistics.
642 		 */
643 		if ((softc->device_stats.flags & DEVSTAT_BS_UNAVAILABLE) != 0){
644 			softc->device_stats.block_size = softc->params.secsize;
645 			softc->device_stats.flags &= ~DEVSTAT_BS_UNAVAILABLE;
646 		}
647 	}
648 
649 	if (error == 0) {
650 		if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0 &&
651 		    (softc->quirks & DA_Q_NO_PREVENT) == 0)
652 			daprevent(periph, PR_PREVENT);
653 	} else {
654 		softc->flags &= ~DA_FLAG_OPEN;
655 		cam_periph_release(periph);
656 	}
657 	cam_periph_unlock(periph);
658 	return (error);
659 }
660 
661 static int
662 daclose(struct dev_close_args *ap)
663 {
664 	cdev_t dev = ap->a_head.a_dev;
665 	struct	cam_periph *periph;
666 	struct	da_softc *softc;
667 	int	unit;
668 	int	error;
669 
670 	unit = dkunit(dev);
671 	periph = cam_extend_get(daperiphs, unit);
672 	if (periph == NULL)
673 		return (ENXIO);
674 
675 	softc = (struct da_softc *)periph->softc;
676 
677 	if ((error = cam_periph_lock(periph, 0)) != 0) {
678 		return (error); /* error code from tsleep */
679 	}
680 
681 	if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
682 		union	ccb *ccb;
683 
684 		ccb = cam_periph_getccb(periph, /*priority*/1);
685 
686 		scsi_synchronize_cache(&ccb->csio,
687 				       /*retries*/1,
688 				       /*cbfcnp*/dadone,
689 				       MSG_SIMPLE_Q_TAG,
690 				       /*begin_lba*/0,/* Cover the whole disk */
691 				       /*lb_count*/0,
692 				       SSD_FULL_SIZE,
693 				       5 * 60 * 1000);
694 
695 		cam_periph_runccb(ccb, /*error_routine*/NULL, /*cam_flags*/0,
696 				  /*sense_flags*/SF_RETRY_UA,
697 				  &softc->device_stats);
698 
699 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
700 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
701 			     CAM_SCSI_STATUS_ERROR) {
702 				int asc, ascq;
703 				int sense_key, error_code;
704 
705 				scsi_extract_sense(&ccb->csio.sense_data,
706 						   &error_code,
707 						   &sense_key,
708 						   &asc, &ascq);
709 				if (sense_key != SSD_KEY_ILLEGAL_REQUEST)
710 					scsi_sense_print(&ccb->csio);
711 			} else {
712 				xpt_print_path(periph->path);
713 				kprintf("Synchronize cache failed, status "
714 				       "== 0x%x, scsi status == 0x%x\n",
715 				       ccb->csio.ccb_h.status,
716 				       ccb->csio.scsi_status);
717 			}
718 		}
719 
720 		if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
721 			cam_release_devq(ccb->ccb_h.path,
722 					 /*relsim_flags*/0,
723 					 /*reduction*/0,
724 					 /*timeout*/0,
725 					 /*getcount_only*/0);
726 
727 		xpt_release_ccb(ccb);
728 
729 	}
730 
731 	if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0) {
732 		if ((softc->quirks & DA_Q_NO_PREVENT) == 0)
733 			daprevent(periph, PR_ALLOW);
734 		/*
735 		 * If we've got removeable media, mark the blocksize as
736 		 * unavailable, since it could change when new media is
737 		 * inserted.
738 		 */
739 		softc->device_stats.flags |= DEVSTAT_BS_UNAVAILABLE;
740 	}
741 
742 	/*
743 	 * Don't compound any ref counting software bugs with more.
744 	 */
745 	if (softc->flags & DA_FLAG_OPEN) {
746 		softc->flags &= ~DA_FLAG_OPEN;
747 		cam_periph_release(periph);
748 	} else {
749 		xpt_print_path(periph->path);
750 		kprintf("daclose() called on an already closed device!\n");
751 	}
752 	cam_periph_unlock(periph);
753 	return (0);
754 }
755 
756 /*
757  * Actually translate the requested transfer into one the physical driver
758  * can understand.  The transfer is described by a buf and will include
759  * only one physical transfer.
760  */
761 static int
762 dastrategy(struct dev_strategy_args *ap)
763 {
764 	cdev_t dev = ap->a_head.a_dev;
765 	struct bio *bio = ap->a_bio;
766 	struct buf *bp = bio->bio_buf;
767 	struct cam_periph *periph;
768 	struct da_softc *softc;
769 	u_int  unit;
770 	u_int  part;
771 
772 	unit = dkunit(dev);
773 	part = dkpart(dev);
774 	periph = cam_extend_get(daperiphs, unit);
775 	if (periph == NULL) {
776 		bp->b_error = ENXIO;
777 		goto bad;
778 	}
779 	softc = (struct da_softc *)periph->softc;
780 #if 0
781 	/*
782 	 * check it's not too big a transfer for our adapter
783 	 */
784 	scsi_minphys(bp, &sd_switch);
785 #endif
786 
787 	/*
788 	 * Mask interrupts so that the pack cannot be invalidated until
789 	 * after we are in the queue.  Otherwise, we might not properly
790 	 * clean up one of the buffers.
791 	 */
792 	crit_enter();
793 
794 	/*
795 	 * If the device has been made invalid, error out
796 	 */
797 	if ((softc->flags & DA_FLAG_PACK_INVALID)) {
798 		crit_exit();
799 		bp->b_error = ENXIO;
800 		goto bad;
801 	}
802 
803 	/*
804 	 * Place it in the queue of disk activities for this disk
805 	 */
806 	bioqdisksort(&softc->bio_queue, bio);
807 
808 	crit_exit();
809 
810 	/*
811 	 * Schedule ourselves for performing the work.
812 	 */
813 	xpt_schedule(periph, /* XXX priority */1);
814 
815 	return(0);
816 bad:
817 	bp->b_flags |= B_ERROR;
818 
819 	/*
820 	 * Correctly set the buf to indicate a completed xfer
821 	 */
822 	bp->b_resid = bp->b_bcount;
823 	biodone(bio);
824 	return(0);
825 }
826 
827 /* For 2.2-stable support */
828 #ifndef ENOIOCTL
829 #define ENOIOCTL -1
830 #endif
831 
832 static int
833 daioctl(struct dev_ioctl_args *ap)
834 {
835 	cdev_t dev = ap->a_head.a_dev;
836 	struct cam_periph *periph;
837 	struct da_softc *softc;
838 	int unit;
839 	int error;
840 
841 	unit = dkunit(dev);
842 	periph = cam_extend_get(daperiphs, unit);
843 	if (periph == NULL)
844 		return (ENXIO);
845 
846 	softc = (struct da_softc *)periph->softc;
847 
848 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("daioctl\n"));
849 
850 	if ((error = cam_periph_lock(periph, PCATCH)) != 0) {
851 		return (error); /* error code from tsleep */
852 	}
853 
854 	error = cam_periph_ioctl(periph, ap->a_cmd, ap->a_data, daerror);
855 
856 	cam_periph_unlock(periph);
857 
858 	return (error);
859 }
860 
861 static int
862 dadump(struct dev_dump_args *ap)
863 {
864 	cdev_t dev = ap->a_head.a_dev;
865 	struct	    cam_periph *periph;
866 	struct	    da_softc *softc;
867 	u_int	    unit;
868 	long	    blkcnt;
869 	vm_paddr_t  addr;
870 	struct	    ccb_scsiio csio;
871 	int         dumppages = MAXDUMPPGS;
872 	int         i;
873 
874 	/* toss any characters present prior to dump */
875 	while (cncheckc() != -1)
876 		;
877 
878 	unit = dkunit(dev);
879 	periph = cam_extend_get(daperiphs, unit);
880 	if (periph == NULL) {
881 		return (ENXIO);
882 	}
883 	softc = (struct da_softc *)periph->softc;
884 
885 	if ((softc->flags & DA_FLAG_PACK_INVALID) != 0)
886 		return (ENXIO);
887 
888 	addr = 0;	/* starting address */
889 	blkcnt = howmany(PAGE_SIZE, ap->a_secsize);
890 
891 	while (ap->a_count > 0) {
892 		caddr_t va = NULL;
893 
894 		if ((ap->a_count / blkcnt) < dumppages)
895 			dumppages = ap->a_count / blkcnt;
896 
897 		for (i = 0; i < dumppages; ++i) {
898 			vm_paddr_t a = addr + (i * PAGE_SIZE);
899 			if (is_physical_memory(a))
900 				va = pmap_kenter_temporary(trunc_page(a), i);
901 			else
902 				va = pmap_kenter_temporary(trunc_page(0), i);
903 		}
904 
905 		xpt_setup_ccb(&csio.ccb_h, periph->path, /*priority*/1);
906 		csio.ccb_h.ccb_state = DA_CCB_DUMP;
907 		scsi_read_write(&csio,
908 				/*retries*/1,
909 				dadone,
910 				MSG_ORDERED_Q_TAG,
911 				/*read*/FALSE,
912 				/*byte2*/0,
913 				/*minimum_cmd_size*/ softc->minimum_cmd_size,
914 				ap->a_blkno,
915 				blkcnt * dumppages,
916 				/*data_ptr*/(u_int8_t *) va,
917 				/*dxfer_len*/blkcnt * ap->a_secsize * dumppages,
918 				/*sense_len*/SSD_FULL_SIZE,
919 				DA_DEFAULT_TIMEOUT * 1000);
920 		xpt_polled_action((union ccb *)&csio);
921 
922 		if ((csio.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
923 			kprintf("Aborting dump due to I/O error.\n");
924 			if ((csio.ccb_h.status & CAM_STATUS_MASK) ==
925 			     CAM_SCSI_STATUS_ERROR)
926 				scsi_sense_print(&csio);
927 			else
928 				kprintf("status == 0x%x, scsi status == 0x%x\n",
929 				       csio.ccb_h.status, csio.scsi_status);
930 			return(EIO);
931 		}
932 
933 		if (dumpstatus(addr, (off_t)ap->a_count * softc->params.secsize) < 0)
934 			return (EINTR);
935 
936 		/* update block count */
937 		ap->a_count -= blkcnt * dumppages;
938 		ap->a_blkno += blkcnt * dumppages;
939 		addr += PAGE_SIZE * dumppages;
940 	}
941 
942 	/*
943 	 * Sync the disk cache contents to the physical media.
944 	 */
945 	if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
946 
947 		xpt_setup_ccb(&csio.ccb_h, periph->path, /*priority*/1);
948 		csio.ccb_h.ccb_state = DA_CCB_DUMP;
949 		scsi_synchronize_cache(&csio,
950 				       /*retries*/1,
951 				       /*cbfcnp*/dadone,
952 				       MSG_SIMPLE_Q_TAG,
953 				       /*begin_lba*/0,/* Cover the whole disk */
954 				       /*lb_count*/0,
955 				       SSD_FULL_SIZE,
956 				       5 * 60 * 1000);
957 		xpt_polled_action((union ccb *)&csio);
958 
959 		if ((csio.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
960 			if ((csio.ccb_h.status & CAM_STATUS_MASK) ==
961 			     CAM_SCSI_STATUS_ERROR) {
962 				int asc, ascq;
963 				int sense_key, error_code;
964 
965 				scsi_extract_sense(&csio.sense_data,
966 						   &error_code,
967 						   &sense_key,
968 						   &asc, &ascq);
969 				if (sense_key != SSD_KEY_ILLEGAL_REQUEST)
970 					scsi_sense_print(&csio);
971 			} else {
972 				xpt_print_path(periph->path);
973 				kprintf("Synchronize cache failed, status "
974 				       "== 0x%x, scsi status == 0x%x\n",
975 				       csio.ccb_h.status, csio.scsi_status);
976 			}
977 		}
978 	}
979 	return (0);
980 }
981 
982 static void
983 dainit(void)
984 {
985 	cam_status status;
986 	struct cam_path *path;
987 
988 	/*
989 	 * Create our extend array for storing the devices we attach to.
990 	 */
991 	daperiphs = cam_extend_new();
992 	SLIST_INIT(&softc_list);
993 	if (daperiphs == NULL) {
994 		kprintf("da: Failed to alloc extend array!\n");
995 		return;
996 	}
997 
998 	callout_init(&dasendorderedtag_ch);
999 
1000 	/*
1001 	 * Install a global async callback.  This callback will
1002 	 * receive async callbacks like "new device found".
1003 	 */
1004 	status = xpt_create_path(&path, /*periph*/NULL, CAM_XPT_PATH_ID,
1005 				 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
1006 
1007 	if (status == CAM_REQ_CMP) {
1008 		struct ccb_setasync csa;
1009 
1010                 xpt_setup_ccb(&csa.ccb_h, path, /*priority*/5);
1011                 csa.ccb_h.func_code = XPT_SASYNC_CB;
1012                 csa.event_enable = AC_FOUND_DEVICE;
1013                 csa.callback = daasync;
1014                 csa.callback_arg = NULL;
1015                 xpt_action((union ccb *)&csa);
1016 		status = csa.ccb_h.status;
1017                 xpt_free_path(path);
1018         }
1019 
1020 	if (status != CAM_REQ_CMP) {
1021 		kprintf("da: Failed to attach master async callback "
1022 		       "due to status 0x%x!\n", status);
1023 	} else {
1024 
1025 		/*
1026 		 * Schedule a periodic event to occasionally send an
1027 		 * ordered tag to a device.
1028 		 */
1029 		callout_reset(&dasendorderedtag_ch,
1030 		    (DA_DEFAULT_TIMEOUT * hz) / DA_ORDEREDTAG_INTERVAL,
1031 		    dasendorderedtag, NULL);
1032 
1033 		/* Register our shutdown event handler */
1034 		if ((EVENTHANDLER_REGISTER(shutdown_post_sync, dashutdown,
1035 					   NULL, SHUTDOWN_PRI_DEFAULT)) == NULL)
1036 		    kprintf("dainit: shutdown event registration failed!\n");
1037 	}
1038 }
1039 
1040 static void
1041 daoninvalidate(struct cam_periph *periph)
1042 {
1043 	struct da_softc *softc;
1044 	struct bio *q_bio;
1045 	struct buf *q_bp;
1046 	struct ccb_setasync csa;
1047 
1048 	softc = (struct da_softc *)periph->softc;
1049 
1050 	/*
1051 	 * De-register any async callbacks.
1052 	 */
1053 	xpt_setup_ccb(&csa.ccb_h, periph->path,
1054 		      /* priority */ 5);
1055 	csa.ccb_h.func_code = XPT_SASYNC_CB;
1056 	csa.event_enable = 0;
1057 	csa.callback = daasync;
1058 	csa.callback_arg = periph;
1059 	xpt_action((union ccb *)&csa);
1060 
1061 	softc->flags |= DA_FLAG_PACK_INVALID;
1062 
1063 	/*
1064 	 * Use a critical section to keep the buffer queue from being
1065 	 * modified while we traverse it.
1066 	 */
1067 	crit_enter();
1068 
1069 	/*
1070 	 * Return all queued I/O with ENXIO.
1071 	 * XXX Handle any transactions queued to the card
1072 	 *     with XPT_ABORT_CCB.
1073 	 */
1074 	while ((q_bio = bioq_first(&softc->bio_queue)) != NULL){
1075 		bioq_remove(&softc->bio_queue, q_bio);
1076 		q_bp = q_bio->bio_buf;
1077 		q_bp->b_resid = q_bp->b_bcount;
1078 		q_bp->b_error = ENXIO;
1079 		q_bp->b_flags |= B_ERROR;
1080 		biodone(q_bio);
1081 	}
1082 	crit_exit();
1083 
1084 	SLIST_REMOVE(&softc_list, softc, da_softc, links);
1085 
1086 	xpt_print_path(periph->path);
1087 	kprintf("lost device\n");
1088 }
1089 
1090 static void
1091 dacleanup(struct cam_periph *periph)
1092 {
1093 	struct da_softc *softc;
1094 
1095 	softc = (struct da_softc *)periph->softc;
1096 
1097 	devstat_remove_entry(&softc->device_stats);
1098 	cam_extend_release(daperiphs, periph->unit_number);
1099 	xpt_print_path(periph->path);
1100 	kprintf("removing device entry\n");
1101 	/*
1102 	 * If we can't free the sysctl tree, oh well...
1103 	 */
1104 	if ((softc->flags & DA_FLAG_SCTX_INIT) != 0
1105 	    && sysctl_ctx_free(&softc->sysctl_ctx) != 0) {
1106 		xpt_print_path(periph->path);
1107 		kprintf("can't remove sysctl context\n");
1108 	}
1109 	if (softc->disk.d_rawdev) {
1110 		disk_destroy(&softc->disk);
1111 	}
1112 	kfree(softc, M_DEVBUF);
1113 }
1114 
1115 static void
1116 daasync(void *callback_arg, u_int32_t code,
1117 	struct cam_path *path, void *arg)
1118 {
1119 	struct cam_periph *periph;
1120 
1121 	periph = (struct cam_periph *)callback_arg;
1122 	switch (code) {
1123 	case AC_FOUND_DEVICE:
1124 	{
1125 		struct ccb_getdev *cgd;
1126 		cam_status status;
1127 
1128 		cgd = (struct ccb_getdev *)arg;
1129 		if (cgd == NULL)
1130 			break;
1131 
1132 		if (SID_TYPE(&cgd->inq_data) != T_DIRECT
1133 		    && SID_TYPE(&cgd->inq_data) != T_RBC
1134 		    && SID_TYPE(&cgd->inq_data) != T_OPTICAL)
1135 			break;
1136 
1137 		/*
1138 		 * Allocate a peripheral instance for
1139 		 * this device and start the probe
1140 		 * process.
1141 		 */
1142 		status = cam_periph_alloc(daregister, daoninvalidate,
1143 					  dacleanup, dastart,
1144 					  "da", CAM_PERIPH_BIO,
1145 					  cgd->ccb_h.path, daasync,
1146 					  AC_FOUND_DEVICE, cgd);
1147 
1148 		if (status != CAM_REQ_CMP
1149 		 && status != CAM_REQ_INPROG)
1150 			kprintf("daasync: Unable to attach to new device "
1151 				"due to status 0x%x\n", status);
1152 		break;
1153 	}
1154 	case AC_SENT_BDR:
1155 	case AC_BUS_RESET:
1156 	{
1157 		struct da_softc *softc;
1158 		struct ccb_hdr *ccbh;
1159 
1160 		softc = (struct da_softc *)periph->softc;
1161 		crit_enter();
1162 		/*
1163 		 * Don't fail on the expected unit attention
1164 		 * that will occur.
1165 		 */
1166 		softc->flags |= DA_FLAG_RETRY_UA;
1167 		LIST_FOREACH(ccbh, &softc->pending_ccbs, periph_links.le)
1168 			ccbh->ccb_state |= DA_CCB_RETRY_UA;
1169 		crit_exit();
1170 		/* FALLTHROUGH*/
1171 	}
1172 	default:
1173 		cam_periph_async(periph, code, path, arg);
1174 		break;
1175 	}
1176 }
1177 
1178 static void
1179 dasysctlinit(void *context, int pending)
1180 {
1181 	struct cam_periph *periph;
1182 	struct da_softc *softc;
1183 	char tmpstr[80], tmpstr2[80];
1184 
1185 	periph = (struct cam_periph *)context;
1186 	softc = (struct da_softc *)periph->softc;
1187 
1188 	ksnprintf(tmpstr, sizeof(tmpstr), "CAM DA unit %d", periph->unit_number);
1189 	ksnprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
1190 
1191 	sysctl_ctx_init(&softc->sysctl_ctx);
1192 	softc->flags |= DA_FLAG_SCTX_INIT;
1193 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1194 		SYSCTL_STATIC_CHILDREN(_kern_cam_da), OID_AUTO, tmpstr2,
1195 		CTLFLAG_RD, 0, tmpstr);
1196 	if (softc->sysctl_tree == NULL) {
1197 		kprintf("dasysctlinit: unable to allocate sysctl tree\n");
1198 		return;
1199 	}
1200 
1201 	/*
1202 	 * Now register the sysctl handler, so the user can the value on
1203 	 * the fly.
1204 	 */
1205 	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1206 		OID_AUTO, "minimum_cmd_size", CTLTYPE_INT | CTLFLAG_RW,
1207 		&softc->minimum_cmd_size, 0, dacmdsizesysctl, "I",
1208 		"Minimum CDB size");
1209 }
1210 
1211 static int
1212 dacmdsizesysctl(SYSCTL_HANDLER_ARGS)
1213 {
1214 	int error, value;
1215 
1216 	value = *(int *)arg1;
1217 
1218 	error = sysctl_handle_int(oidp, &value, 0, req);
1219 
1220 	if ((error != 0)
1221 	 || (req->newptr == NULL))
1222 		return (error);
1223 
1224 	/*
1225 	 * Acceptable values here are 6, 10 or 12, or 16.
1226 	 */
1227 	if (value < 6)
1228 		value = 6;
1229 	else if ((value > 6)
1230 	      && (value <= 10))
1231 		value = 10;
1232 	else if ((value > 10)
1233 	      && (value <= 12))
1234 		value = 12;
1235 	else if (value > 12)
1236 		value = 16;
1237 
1238 	*(int *)arg1 = value;
1239 
1240 	return (0);
1241 }
1242 
1243 static cam_status
1244 daregister(struct cam_periph *periph, void *arg)
1245 {
1246 	struct da_softc *softc;
1247 	struct ccb_setasync csa;
1248 	struct ccb_pathinq cpi;
1249 	struct ccb_getdev *cgd;
1250 	char tmpstr[80];
1251 	caddr_t match;
1252 
1253 	cgd = (struct ccb_getdev *)arg;
1254 	if (periph == NULL) {
1255 		kprintf("daregister: periph was NULL!!\n");
1256 		return(CAM_REQ_CMP_ERR);
1257 	}
1258 
1259 	if (cgd == NULL) {
1260 		kprintf("daregister: no getdev CCB, can't register device\n");
1261 		return(CAM_REQ_CMP_ERR);
1262 	}
1263 
1264 	softc = kmalloc(sizeof(*softc), M_DEVBUF, M_INTWAIT | M_ZERO);
1265 	LIST_INIT(&softc->pending_ccbs);
1266 	softc->state = DA_STATE_PROBE;
1267 	bioq_init(&softc->bio_queue);
1268 	if (SID_IS_REMOVABLE(&cgd->inq_data))
1269 		softc->flags |= DA_FLAG_PACK_REMOVABLE;
1270 	if ((cgd->inq_data.flags & SID_CmdQue) != 0)
1271 		softc->flags |= DA_FLAG_TAGGED_QUEUING;
1272 
1273 	periph->softc = softc;
1274 
1275 	cam_extend_set(daperiphs, periph->unit_number, periph);
1276 
1277 	/*
1278 	 * See if this device has any quirks.
1279 	 */
1280 	match = cam_quirkmatch((caddr_t)&cgd->inq_data,
1281 			       (caddr_t)da_quirk_table,
1282 			       sizeof(da_quirk_table)/sizeof(*da_quirk_table),
1283 			       sizeof(*da_quirk_table), scsi_inquiry_match);
1284 
1285 	if (match != NULL)
1286 		softc->quirks = ((struct da_quirk_entry *)match)->quirks;
1287 	else
1288 		softc->quirks = DA_Q_NONE;
1289 
1290 	TASK_INIT(&softc->sysctl_task, 0, dasysctlinit, periph);
1291 
1292 	/* Check if the SIM does not want 6 byte commands */
1293 	xpt_setup_ccb(&cpi.ccb_h, periph->path, /*priority*/1);
1294 	cpi.ccb_h.func_code = XPT_PATH_INQ;
1295 	xpt_action((union ccb *)&cpi);
1296 	if (cpi.ccb_h.status == CAM_REQ_CMP && (cpi.hba_misc & PIM_NO_6_BYTE))
1297 		softc->quirks |= DA_Q_NO_6_BYTE;
1298 
1299 	/*
1300 	 * RBC devices don't have to support READ(6), only READ(10).
1301 	 */
1302 	if (softc->quirks & DA_Q_NO_6_BYTE || SID_TYPE(&cgd->inq_data) == T_RBC)
1303 		softc->minimum_cmd_size = 10;
1304 	else
1305 		softc->minimum_cmd_size = 6;
1306 
1307 	/*
1308 	 * Load the user's default, if any.
1309 	 */
1310 	ksnprintf(tmpstr, sizeof(tmpstr), "kern.cam.da.%d.minimum_cmd_size",
1311 		 periph->unit_number);
1312 	TUNABLE_INT_FETCH(tmpstr, &softc->minimum_cmd_size);
1313 
1314 	/*
1315 	 * 6, 10, 12, and 16 are the currently permissible values.
1316 	 */
1317 	if (softc->minimum_cmd_size < 6)
1318 		softc->minimum_cmd_size = 6;
1319 	else if ((softc->minimum_cmd_size > 6)
1320 	      && (softc->minimum_cmd_size <= 10))
1321 		softc->minimum_cmd_size = 10;
1322 	else if ((softc->minimum_cmd_size > 10)
1323 	      && (softc->minimum_cmd_size <= 12))
1324 		softc->minimum_cmd_size = 12;
1325 	else if (softc->minimum_cmd_size > 12)
1326 		softc->minimum_cmd_size = 16;
1327 
1328 	/*
1329 	 * Block our timeout handler while we
1330 	 * add this softc to the dev list.
1331 	 */
1332 	crit_enter();
1333 	SLIST_INSERT_HEAD(&softc_list, softc, links);
1334 	crit_exit();
1335 
1336 	/*
1337 	 * The DA driver supports a blocksize, but
1338 	 * we don't know the blocksize until we do
1339 	 * a read capacity.  So, set a flag to
1340 	 * indicate that the blocksize is
1341 	 * unavailable right now.  We'll clear the
1342 	 * flag as soon as we've done a read capacity.
1343 	 */
1344 	devstat_add_entry(&softc->device_stats, "da",
1345 			  periph->unit_number, 0,
1346 	  		  DEVSTAT_BS_UNAVAILABLE,
1347 			  SID_TYPE(&cgd->inq_data) | DEVSTAT_TYPE_IF_SCSI,
1348 			  DEVSTAT_PRIORITY_DISK);
1349 
1350 	/*
1351 	 * Register this media as a disk
1352 	 */
1353 	disk_create(periph->unit_number, &softc->disk, &da_ops);
1354 	softc->disk.d_rawdev->si_iosize_max = MAXPHYS;
1355 
1356 	/*
1357 	 * Add async callbacks for bus reset and
1358 	 * bus device reset calls.  I don't bother
1359 	 * checking if this fails as, in most cases,
1360 	 * the system will function just fine without
1361 	 * them and the only alternative would be to
1362 	 * not attach the device on failure.
1363 	 */
1364 	xpt_setup_ccb(&csa.ccb_h, periph->path, /*priority*/5);
1365 	csa.ccb_h.func_code = XPT_SASYNC_CB;
1366 	csa.event_enable = AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE;
1367 	csa.callback = daasync;
1368 	csa.callback_arg = periph;
1369 	xpt_action((union ccb *)&csa);
1370 	/*
1371 	 * Lock this peripheral until we are setup.
1372 	 * This first call can't block
1373 	 */
1374 	cam_periph_lock(periph, 0);
1375 	xpt_schedule(periph, /*priority*/5);
1376 
1377 	return(CAM_REQ_CMP);
1378 }
1379 
1380 static void
1381 dastart(struct cam_periph *periph, union ccb *start_ccb)
1382 {
1383 	struct da_softc *softc;
1384 
1385 	softc = (struct da_softc *)periph->softc;
1386 
1387 
1388 	switch (softc->state) {
1389 	case DA_STATE_NORMAL:
1390 	{
1391 		/* Pull a buffer from the queue and get going on it */
1392 		struct bio *bio;
1393 		struct buf *bp;
1394 
1395 		/*
1396 		 * See if there is a buf with work for us to do..
1397 		 */
1398 		crit_enter();
1399 		bio = bioq_first(&softc->bio_queue);
1400 		if (periph->immediate_priority <= periph->pinfo.priority) {
1401 			CAM_DEBUG_PRINT(CAM_DEBUG_SUBTRACE,
1402 					("queuing for immediate ccb\n"));
1403 			start_ccb->ccb_h.ccb_state = DA_CCB_WAITING;
1404 			SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
1405 					  periph_links.sle);
1406 			periph->immediate_priority = CAM_PRIORITY_NONE;
1407 			crit_exit();
1408 			wakeup(&periph->ccb_list);
1409 		} else if (bio == NULL) {
1410 			crit_exit();
1411 			xpt_release_ccb(start_ccb);
1412 		} else {
1413 			u_int8_t tag_code;
1414 
1415 			bioq_remove(&softc->bio_queue, bio);
1416 			bp = bio->bio_buf;
1417 
1418 			devstat_start_transaction(&softc->device_stats);
1419 
1420 			if ((bp->b_flags & B_ORDERED) != 0
1421 			 || (softc->flags & DA_FLAG_NEED_OTAG) != 0) {
1422 				softc->flags &= ~DA_FLAG_NEED_OTAG;
1423 				softc->ordered_tag_count++;
1424 				tag_code = MSG_ORDERED_Q_TAG;
1425 			} else {
1426 				tag_code = MSG_SIMPLE_Q_TAG;
1427 			}
1428 
1429 			KKASSERT(bio->bio_offset % softc->params.secsize == 0);
1430 
1431 			scsi_read_write(&start_ccb->csio,
1432 					/*retries*/da_retry_count,
1433 					dadone,
1434 					tag_code,
1435 					(bp->b_cmd == BUF_CMD_READ),
1436 					/*byte2*/0,
1437 					softc->minimum_cmd_size,
1438 					bio->bio_offset / softc->params.secsize,
1439 					bp->b_bcount / softc->params.secsize,
1440 					bp->b_data,
1441 					bp->b_bcount,
1442 					/*sense_len*/SSD_FULL_SIZE,
1443 					da_default_timeout * 1000);
1444 			start_ccb->ccb_h.ccb_state = DA_CCB_BUFFER_IO;
1445 
1446 			/*
1447 			 * Block out any asyncronous callbacks
1448 			 * while we touch the pending ccb list.
1449 			 */
1450 			LIST_INSERT_HEAD(&softc->pending_ccbs,
1451 					 &start_ccb->ccb_h, periph_links.le);
1452 
1453 			/* We expect a unit attention from this device */
1454 			if ((softc->flags & DA_FLAG_RETRY_UA) != 0) {
1455 				start_ccb->ccb_h.ccb_state |= DA_CCB_RETRY_UA;
1456 				softc->flags &= ~DA_FLAG_RETRY_UA;
1457 			}
1458 
1459 			start_ccb->ccb_h.ccb_bio = bio;
1460 			bio = bioq_first(&softc->bio_queue);
1461 			crit_exit();
1462 
1463 			xpt_action(start_ccb);
1464 		}
1465 
1466 		if (bio != NULL) {
1467 			/* Have more work to do, so ensure we stay scheduled */
1468 			xpt_schedule(periph, /* XXX priority */1);
1469 		}
1470 		break;
1471 	}
1472 	case DA_STATE_PROBE:
1473 	{
1474 		struct ccb_scsiio *csio;
1475 		struct scsi_read_capacity_data *rcap;
1476 
1477 		rcap = kmalloc(sizeof(*rcap), M_TEMP, M_INTWAIT | M_ZERO);
1478 		csio = &start_ccb->csio;
1479 		scsi_read_capacity(csio,
1480 				   /*retries*/4,
1481 				   dadone,
1482 				   MSG_SIMPLE_Q_TAG,
1483 				   rcap,
1484 				   SSD_FULL_SIZE,
1485 				   /*timeout*/5000);
1486 		start_ccb->ccb_h.ccb_bio = NULL;
1487 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE;
1488 		xpt_action(start_ccb);
1489 		break;
1490 	}
1491 	case DA_STATE_PROBE2:
1492 	{
1493 		struct ccb_scsiio *csio;
1494 		struct scsi_read_capacity_data_long *rcaplong;
1495 
1496 		rcaplong = (struct scsi_read_capacity_data_long *)
1497 		kmalloc(sizeof(*rcaplong), M_TEMP, M_INTWAIT);
1498 		if (rcaplong == NULL) {
1499 			kprintf("dastart: Couldn't allocate read_capacity\n");
1500 			/* da_free_periph??? */
1501 			break;
1502 		}
1503 		csio = &start_ccb->csio;
1504 		scsi_read_capacity_16(csio,
1505 				    /*retries*/ 4,
1506 				    /*cbfcnp*/ dadone,
1507 				    /*tag_action*/ MSG_SIMPLE_Q_TAG,
1508 				    /*lba*/ 0,
1509 				    /*reladr*/ 0,
1510 				    /*pmi*/ 0,
1511 				    rcaplong,
1512 				    /*sense_len*/ SSD_FULL_SIZE,
1513 				    /*timeout*/ 60000);
1514 		start_ccb->ccb_h.ccb_bio = NULL;
1515 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE2;
1516 		xpt_action(start_ccb);
1517 		break;
1518 	}
1519 	}
1520 }
1521 
1522 static int
1523 cmd6workaround(union ccb *ccb)
1524 {
1525 	struct scsi_rw_6 cmd6;
1526 	struct scsi_rw_10 *cmd10;
1527 	struct da_softc *softc;
1528 	u_int8_t *cdb;
1529 	int frozen;
1530 
1531 	cdb = ccb->csio.cdb_io.cdb_bytes;
1532 
1533 	/* Translation only possible if CDB is an array and cmd is R/W6 */
1534 	if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0 ||
1535 	    (*cdb != READ_6 && *cdb != WRITE_6))
1536 		return 0;
1537 
1538 	xpt_print_path(ccb->ccb_h.path);
1539  	kprintf("READ(6)/WRITE(6) not supported, "
1540 	       "increasing minimum_cmd_size to 10.\n");
1541  	softc = (struct da_softc *)xpt_path_periph(ccb->ccb_h.path)->softc;
1542 	softc->minimum_cmd_size = 10;
1543 
1544 	bcopy(cdb, &cmd6, sizeof(struct scsi_rw_6));
1545 	cmd10 = (struct scsi_rw_10 *)cdb;
1546 	cmd10->opcode = (cmd6.opcode == READ_6) ? READ_10 : WRITE_10;
1547 	cmd10->byte2 = 0;
1548 	scsi_ulto4b(scsi_3btoul(cmd6.addr), cmd10->addr);
1549 	cmd10->reserved = 0;
1550 	scsi_ulto2b(cmd6.length, cmd10->length);
1551 	cmd10->control = cmd6.control;
1552 	ccb->csio.cdb_len = sizeof(*cmd10);
1553 
1554 	/* Requeue request, unfreezing queue if necessary */
1555 	frozen = (ccb->ccb_h.status & CAM_DEV_QFRZN) != 0;
1556  	ccb->ccb_h.status = CAM_REQUEUE_REQ;
1557 	xpt_action(ccb);
1558 	if (frozen) {
1559 		cam_release_devq(ccb->ccb_h.path,
1560 				 /*relsim_flags*/0,
1561 				 /*reduction*/0,
1562 				 /*timeout*/0,
1563 				 /*getcount_only*/0);
1564 	}
1565 	return (ERESTART);
1566 }
1567 
1568 static void
1569 dadone(struct cam_periph *periph, union ccb *done_ccb)
1570 {
1571 	struct da_softc *softc;
1572 	struct ccb_scsiio *csio;
1573 
1574 	softc = (struct da_softc *)periph->softc;
1575 	csio = &done_ccb->csio;
1576 	switch (csio->ccb_h.ccb_state & DA_CCB_TYPE_MASK) {
1577 	case DA_CCB_BUFFER_IO:
1578 	{
1579 		struct buf *bp;
1580 		struct bio *bio;
1581 
1582 		bio = (struct bio *)done_ccb->ccb_h.ccb_bio;
1583 		bp = bio->bio_buf;
1584 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1585 			int error;
1586 			int sf;
1587 
1588 			if ((csio->ccb_h.ccb_state & DA_CCB_RETRY_UA) != 0)
1589 				sf = SF_RETRY_UA;
1590 			else
1591 				sf = 0;
1592 
1593 			error = daerror(done_ccb, CAM_RETRY_SELTO, sf);
1594 			if (error == ERESTART) {
1595 				/*
1596 				 * A retry was scheuled, so
1597 				 * just return.
1598 				 */
1599 				return;
1600 			}
1601 			if (error != 0) {
1602 				struct bio *q_bio;
1603 				struct buf *q_bp;
1604 
1605 				crit_enter();
1606 
1607 				if (error == ENXIO) {
1608 					/*
1609 					 * Catastrophic error.  Mark our pack as
1610 					 * invalid.
1611 					 */
1612 					/* XXX See if this is really a media
1613 					 *     change first.
1614 					 */
1615 					xpt_print_path(periph->path);
1616 					kprintf("Invalidating pack\n");
1617 					softc->flags |= DA_FLAG_PACK_INVALID;
1618 				}
1619 
1620 				/*
1621 				 * return all queued I/O with EIO, so that
1622 				 * the client can retry these I/Os in the
1623 				 * proper order should it attempt to recover.
1624 				 */
1625 				while ((q_bio = bioq_first(&softc->bio_queue))
1626 					!= NULL) {
1627 					bioq_remove(&softc->bio_queue, q_bio);
1628 					q_bp = q_bio->bio_buf;
1629 					q_bp->b_resid = q_bp->b_bcount;
1630 					q_bp->b_error = EIO;
1631 					q_bp->b_flags |= B_ERROR;
1632 					biodone(q_bio);
1633 				}
1634 				crit_exit();
1635 				bp->b_error = error;
1636 				bp->b_resid = bp->b_bcount;
1637 				bp->b_flags |= B_ERROR;
1638 			} else {
1639 				bp->b_resid = csio->resid;
1640 				bp->b_error = 0;
1641 				if (bp->b_resid != 0)
1642 					bp->b_flags |= B_ERROR;
1643 			}
1644 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1645 				cam_release_devq(done_ccb->ccb_h.path,
1646 						 /*relsim_flags*/0,
1647 						 /*reduction*/0,
1648 						 /*timeout*/0,
1649 						 /*getcount_only*/0);
1650 		} else {
1651 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1652 				panic("REQ_CMP with QFRZN");
1653 			bp->b_resid = csio->resid;
1654 			if (csio->resid > 0)
1655 				bp->b_flags |= B_ERROR;
1656 		}
1657 
1658 		/*
1659 		 * Block out any asyncronous callbacks
1660 		 * while we touch the pending ccb list.
1661 		 */
1662 		crit_enter();
1663 		LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
1664 		crit_exit();
1665 
1666 		if (softc->device_stats.busy_count == 0)
1667 			softc->flags |= DA_FLAG_WENT_IDLE;
1668 
1669 		devstat_end_transaction_buf(&softc->device_stats, bp);
1670 		biodone(bio);
1671 		break;
1672 	}
1673 	case DA_CCB_PROBE:
1674 	case DA_CCB_PROBE2:
1675 	{
1676 		struct	   scsi_read_capacity_data *rdcap;
1677 		struct     scsi_read_capacity_data_long *rcaplong;
1678 		char	   announce_buf[80];
1679 
1680 		rdcap = NULL;
1681 		rcaplong = NULL;
1682 		if (softc->state == DA_STATE_PROBE)
1683 			rdcap =(struct scsi_read_capacity_data *)csio->data_ptr;
1684 		else
1685 			rcaplong = (struct scsi_read_capacity_data_long *)
1686 				    csio->data_ptr;
1687 
1688 		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1689 			struct disk_params *dp;
1690 			uint32_t block_size;
1691 			uint64_t maxsector;
1692 
1693 			if (softc->state == DA_STATE_PROBE) {
1694 				block_size = scsi_4btoul(rdcap->length);
1695 				maxsector = scsi_4btoul(rdcap->addr);
1696 
1697 				/*
1698 				 * According to SBC-2, if the standard 10
1699 				 * byte READ CAPACITY command returns 2^32,
1700 				 * we should issue the 16 byte version of
1701 				 * the command, since the device in question
1702 				 * has more sectors than can be represented
1703 				 * with the short version of the command.
1704 				 */
1705 				if (maxsector == 0xffffffff) {
1706 					softc->state = DA_STATE_PROBE2;
1707 					kfree(rdcap, M_TEMP);
1708 					xpt_release_ccb(done_ccb);
1709 					xpt_schedule(periph, /*priority*/5);
1710 					return;
1711 				}
1712 			} else {
1713 				block_size = scsi_4btoul(rcaplong->length);
1714 				maxsector = scsi_8btou64(rcaplong->addr);
1715 			}
1716 			dasetgeom(periph, block_size, maxsector);
1717 			dp = &softc->params;
1718 			ksnprintf(announce_buf, sizeof(announce_buf),
1719 				"%juMB (%ju %u byte sectors: %dH %dS/T %dC)",
1720 				(uintmax_t) (((uintmax_t)dp->secsize *
1721 				dp->sectors) / (1024*1024)),
1722 				(uintmax_t)dp->sectors,
1723 				dp->secsize, dp->heads, dp->secs_per_track,
1724 				dp->cylinders);
1725 		} else {
1726 			int	error;
1727 
1728 			announce_buf[0] = '\0';
1729 
1730 			/*
1731 			 * Retry any UNIT ATTENTION type errors.  They
1732 			 * are expected at boot.
1733 			 */
1734 			error = daerror(done_ccb, CAM_RETRY_SELTO,
1735 					SF_RETRY_UA|SF_NO_PRINT);
1736 			if (error == ERESTART) {
1737 				/*
1738 				 * A retry was scheuled, so
1739 				 * just return.
1740 				 */
1741 				return;
1742 			} else if (error != 0) {
1743 				struct scsi_sense_data *sense;
1744 				int asc, ascq;
1745 				int sense_key, error_code;
1746 				int have_sense;
1747 				cam_status status;
1748 				struct ccb_getdev cgd;
1749 
1750 				/* Don't wedge this device's queue */
1751 				status = done_ccb->ccb_h.status;
1752 				if ((status & CAM_DEV_QFRZN) != 0)
1753 					cam_release_devq(done_ccb->ccb_h.path,
1754 							 /*relsim_flags*/0,
1755 							 /*reduction*/0,
1756 							 /*timeout*/0,
1757 							 /*getcount_only*/0);
1758 
1759 
1760 				xpt_setup_ccb(&cgd.ccb_h,
1761 					      done_ccb->ccb_h.path,
1762 					      /* priority */ 1);
1763 				cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1764 				xpt_action((union ccb *)&cgd);
1765 
1766 				if (((csio->ccb_h.flags & CAM_SENSE_PHYS) != 0)
1767 				 || ((csio->ccb_h.flags & CAM_SENSE_PTR) != 0)
1768 				 || ((status & CAM_AUTOSNS_VALID) == 0))
1769 					have_sense = FALSE;
1770 				else
1771 					have_sense = TRUE;
1772 
1773 				if (have_sense) {
1774 					sense = &csio->sense_data;
1775 					scsi_extract_sense(sense, &error_code,
1776 							   &sense_key,
1777 							   &asc, &ascq);
1778 				}
1779 				/*
1780 				 * Attach to anything that claims to be a
1781 				 * direct access or optical disk device,
1782 				 * as long as it doesn't return a "Logical
1783 				 * unit not supported" (0x25) error.
1784 				 */
1785 				if ((have_sense) && (asc != 0x25)
1786 				 && (error_code == SSD_CURRENT_ERROR)) {
1787 					const char *sense_key_desc;
1788 					const char *asc_desc;
1789 
1790 					scsi_sense_desc(sense_key, asc, ascq,
1791 							&cgd.inq_data,
1792 							&sense_key_desc,
1793 							&asc_desc);
1794 					ksnprintf(announce_buf,
1795 					    sizeof(announce_buf),
1796 						"Attempt to query device "
1797 						"size failed: %s, %s",
1798 						sense_key_desc,
1799 						asc_desc);
1800 				} else {
1801 					if (have_sense)
1802 						scsi_sense_print(
1803 							&done_ccb->csio);
1804 					else {
1805 						xpt_print_path(periph->path);
1806 						kprintf("got CAM status %#x\n",
1807 						       done_ccb->ccb_h.status);
1808 					}
1809 
1810 					xpt_print_path(periph->path);
1811 					kprintf("fatal error, failed"
1812 					       " to attach to device\n");
1813 
1814 					/*
1815 					 * Free up resources.
1816 					 */
1817 					cam_periph_invalidate(periph);
1818 				}
1819 			}
1820 		}
1821 		kfree(csio->data_ptr, M_TEMP);
1822 		if (announce_buf[0] != '\0') {
1823 			xpt_announce_periph(periph, announce_buf);
1824 			/*
1825 			 * Create our sysctl variables, now that we know
1826 			 * we have successfully attached.
1827 			 */
1828 			taskqueue_enqueue(taskqueue_thread[mycpuid],
1829 			    &softc->sysctl_task);
1830 		}
1831 		softc->state = DA_STATE_NORMAL;
1832 		/*
1833 		 * Since our peripheral may be invalidated by an error
1834 		 * above or an external event, we must release our CCB
1835 		 * before releasing the probe lock on the peripheral.
1836 		 * The peripheral will only go away once the last lock
1837 		 * is removed, and we need it around for the CCB release
1838 		 * operation.
1839 		 */
1840 		xpt_release_ccb(done_ccb);
1841 		cam_periph_unlock(periph);
1842 		return;
1843 	}
1844 	case DA_CCB_WAITING:
1845 	{
1846 		/* Caller will release the CCB */
1847 		wakeup(&done_ccb->ccb_h.cbfcnp);
1848 		return;
1849 	}
1850 	case DA_CCB_DUMP:
1851 		/* No-op.  We're polling */
1852 		return;
1853 	default:
1854 		break;
1855 	}
1856 	xpt_release_ccb(done_ccb);
1857 }
1858 
1859 static int
1860 daerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
1861 {
1862 	struct da_softc	  *softc;
1863 	struct cam_periph *periph;
1864 	int error;
1865 
1866 	periph = xpt_path_periph(ccb->ccb_h.path);
1867 	softc = (struct da_softc *)periph->softc;
1868 
1869  	/*
1870 	 * Automatically detect devices that do not support
1871  	 * READ(6)/WRITE(6) and upgrade to using 10 byte cdbs.
1872  	 */
1873 	error = 0;
1874 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INVALID) {
1875 		error = cmd6workaround(ccb);
1876 	} else if (((ccb->ccb_h.status & CAM_STATUS_MASK) ==
1877 		   CAM_SCSI_STATUS_ERROR)
1878 	 && (ccb->ccb_h.status & CAM_AUTOSNS_VALID)
1879 	 && (ccb->csio.scsi_status == SCSI_STATUS_CHECK_COND)
1880 	 && ((ccb->ccb_h.flags & CAM_SENSE_PHYS) == 0)
1881 	 && ((ccb->ccb_h.flags & CAM_SENSE_PTR) == 0)) {
1882 		int sense_key, error_code, asc, ascq;
1883 
1884  		scsi_extract_sense(&ccb->csio.sense_data,
1885 				   &error_code, &sense_key, &asc, &ascq);
1886 		if (sense_key == SSD_KEY_ILLEGAL_REQUEST)
1887  			error = cmd6workaround(ccb);
1888 	}
1889 	if (error == ERESTART)
1890 		return (ERESTART);
1891 
1892 	/*
1893 	 * XXX
1894 	 * Until we have a better way of doing pack validation,
1895 	 * don't treat UAs as errors.
1896 	 */
1897 	sense_flags |= SF_RETRY_UA;
1898 	return(cam_periph_error(ccb, cam_flags, sense_flags,
1899 				&softc->saved_ccb));
1900 }
1901 
1902 static void
1903 daprevent(struct cam_periph *periph, int action)
1904 {
1905 	struct	da_softc *softc;
1906 	union	ccb *ccb;
1907 	int	error;
1908 
1909 	softc = (struct da_softc *)periph->softc;
1910 
1911 	if (((action == PR_ALLOW)
1912 	  && (softc->flags & DA_FLAG_PACK_LOCKED) == 0)
1913 	 || ((action == PR_PREVENT)
1914 	  && (softc->flags & DA_FLAG_PACK_LOCKED) != 0)) {
1915 		return;
1916 	}
1917 
1918 	ccb = cam_periph_getccb(periph, /*priority*/1);
1919 
1920 	scsi_prevent(&ccb->csio,
1921 		     /*retries*/1,
1922 		     /*cbcfp*/dadone,
1923 		     MSG_SIMPLE_Q_TAG,
1924 		     action,
1925 		     SSD_FULL_SIZE,
1926 		     5000);
1927 
1928 	error = cam_periph_runccb(ccb, /*error_routine*/NULL, CAM_RETRY_SELTO,
1929 				  SF_RETRY_UA, &softc->device_stats);
1930 
1931 	if (error == 0) {
1932 		if (action == PR_ALLOW)
1933 			softc->flags &= ~DA_FLAG_PACK_LOCKED;
1934 		else
1935 			softc->flags |= DA_FLAG_PACK_LOCKED;
1936 	}
1937 
1938 	xpt_release_ccb(ccb);
1939 }
1940 
1941 static int
1942 dagetcapacity(struct cam_periph *periph)
1943 {
1944 	struct da_softc *softc;
1945 	union ccb *ccb;
1946 	struct scsi_read_capacity_data *rcap;
1947 	struct scsi_read_capacity_data_long *rcaplong;
1948 	uint32_t block_len;
1949 	uint64_t maxsector;
1950 	int error;
1951 
1952 	softc = (struct da_softc *)periph->softc;
1953 	block_len = 0;
1954 	maxsector = 0;
1955 	error = 0;
1956 
1957 	/* Do a read capacity */
1958 	rcap = (void *)kmalloc(sizeof(*rcaplong), M_TEMP, M_INTWAIT);
1959 
1960 	ccb = cam_periph_getccb(periph, /*priority*/1);
1961 	scsi_read_capacity(&ccb->csio,
1962 			   /*retries*/4,
1963 			   /*cbfncp*/dadone,
1964 			   MSG_SIMPLE_Q_TAG,
1965 			   rcap,
1966 			   SSD_FULL_SIZE,
1967 			   /*timeout*/60000);
1968 	ccb->ccb_h.ccb_bio = NULL;
1969 
1970 	error = cam_periph_runccb(ccb, daerror,
1971 				  /*cam_flags*/CAM_RETRY_SELTO,
1972 				  /*sense_flags*/SF_RETRY_UA,
1973 				  &softc->device_stats);
1974 
1975 	if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1976 		cam_release_devq(ccb->ccb_h.path,
1977 				 /*relsim_flags*/0,
1978 				 /*reduction*/0,
1979 				 /*timeout*/0,
1980 				 /*getcount_only*/0);
1981 
1982 	if (error == 0) {
1983 		block_len = scsi_4btoul(rcap->length);
1984 		maxsector = scsi_4btoul(rcap->addr);
1985 
1986 		if (maxsector != 0xffffffff)
1987 			goto done;
1988 	} else
1989 		goto done;
1990 
1991 	rcaplong = (struct scsi_read_capacity_data_long *)rcap;
1992 
1993 	scsi_read_capacity_16(&ccb->csio,
1994 			      /*retries*/ 4,
1995 			      /*cbfcnp*/ dadone,
1996 			      /*tag_action*/ MSG_SIMPLE_Q_TAG,
1997 			      /*lba*/ 0,
1998 			      /*reladr*/ 0,
1999 			      /*pmi*/ 0,
2000 			      rcaplong,
2001 			      /*sense_len*/ SSD_FULL_SIZE,
2002 			      /*timeout*/ 60000);
2003 	ccb->ccb_h.ccb_bio = NULL;
2004 
2005 	error = cam_periph_runccb(ccb, daerror,
2006 				  /*cam_flags*/CAM_RETRY_SELTO,
2007 				  /*sense_flags*/SF_RETRY_UA,
2008 				  &softc->device_stats);
2009 
2010 	if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
2011 		cam_release_devq(ccb->ccb_h.path,
2012 				 /*relsim_flags*/0,
2013 				 /*reduction*/0,
2014 				 /*timeout*/0,
2015 				 /*getcount_only*/0);
2016 
2017 	if (error == 0) {
2018 		block_len = scsi_4btoul(rcaplong->length);
2019 		maxsector = scsi_8btou64(rcaplong->addr);
2020 	}
2021 
2022 done:
2023 
2024 	if (error == 0)
2025 		dasetgeom(periph, block_len, maxsector);
2026 
2027 	xpt_release_ccb(ccb);
2028 
2029 	kfree(rcap, M_TEMP);
2030 
2031 	return (error);
2032 }
2033 
2034 static void
2035 dasetgeom(struct cam_periph *periph, uint32_t block_len, uint64_t maxsector)
2036 {
2037 	struct ccb_calc_geometry ccg;
2038 	struct da_softc *softc;
2039 	struct disk_params *dp;
2040 
2041 	softc = (struct da_softc *)periph->softc;
2042 
2043 	dp = &softc->params;
2044 	dp->secsize = block_len;
2045 	dp->sectors = maxsector + 1;
2046 	/*
2047 	 * Have the controller provide us with a geometry
2048 	 * for this disk.  The only time the geometry
2049 	 * matters is when we boot and the controller
2050 	 * is the only one knowledgeable enough to come
2051 	 * up with something that will make this a bootable
2052 	 * device.
2053 	 */
2054 	xpt_setup_ccb(&ccg.ccb_h, periph->path, /*priority*/1);
2055 	ccg.ccb_h.func_code = XPT_CALC_GEOMETRY;
2056 	ccg.block_size = dp->secsize;
2057 	ccg.volume_size = dp->sectors;
2058 	ccg.heads = 0;
2059 	ccg.secs_per_track = 0;
2060 	ccg.cylinders = 0;
2061 	xpt_action((union ccb*)&ccg);
2062 	dp->heads = ccg.heads;
2063 	dp->secs_per_track = ccg.secs_per_track;
2064 	dp->cylinders = ccg.cylinders;
2065 }
2066 
2067 static void
2068 dasendorderedtag(void *arg)
2069 {
2070 	struct da_softc *softc;
2071 
2072 	for (softc = SLIST_FIRST(&softc_list);
2073 	     softc != NULL;
2074 	     softc = SLIST_NEXT(softc, links)) {
2075 		crit_enter();
2076 		if ((softc->ordered_tag_count == 0)
2077 		 && ((softc->flags & DA_FLAG_WENT_IDLE) == 0)) {
2078 			softc->flags |= DA_FLAG_NEED_OTAG;
2079 		}
2080 		if (softc->device_stats.busy_count > 0)
2081 			softc->flags &= ~DA_FLAG_WENT_IDLE;
2082 
2083 		softc->ordered_tag_count = 0;
2084 		crit_exit();
2085 	}
2086 	/* Queue us up again */
2087 	callout_reset(&dasendorderedtag_ch,
2088 	    (da_default_timeout * hz) / DA_ORDEREDTAG_INTERVAL,
2089 	    dasendorderedtag, NULL);
2090 }
2091 
2092 /*
2093  * Step through all DA peripheral drivers, and if the device is still open,
2094  * sync the disk cache to physical media.
2095  */
2096 static void
2097 dashutdown(void * arg, int howto)
2098 {
2099 	struct cam_periph *periph;
2100 	struct da_softc *softc;
2101 
2102 	TAILQ_FOREACH(periph, &dadriver.units, unit_links) {
2103 		union ccb ccb;
2104 
2105 		softc = (struct da_softc *)periph->softc;
2106 
2107 		/*
2108 		 * We only sync the cache if the drive is still open, and
2109 		 * if the drive is capable of it..
2110 		 */
2111 		if (((softc->flags & DA_FLAG_OPEN) == 0)
2112 		 || (softc->quirks & DA_Q_NO_SYNC_CACHE))
2113 			continue;
2114 
2115 		xpt_setup_ccb(&ccb.ccb_h, periph->path, /*priority*/1);
2116 
2117 		ccb.ccb_h.ccb_state = DA_CCB_DUMP;
2118 		scsi_synchronize_cache(&ccb.csio,
2119 				       /*retries*/1,
2120 				       /*cbfcnp*/dadone,
2121 				       MSG_SIMPLE_Q_TAG,
2122 				       /*begin_lba*/0, /* whole disk */
2123 				       /*lb_count*/0,
2124 				       SSD_FULL_SIZE,
2125 				       60 * 60 * 1000);
2126 
2127 		xpt_polled_action(&ccb);
2128 
2129 		if ((ccb.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2130 			if (((ccb.ccb_h.status & CAM_STATUS_MASK) ==
2131 			     CAM_SCSI_STATUS_ERROR)
2132 			 && (ccb.csio.scsi_status == SCSI_STATUS_CHECK_COND)){
2133 				int error_code, sense_key, asc, ascq;
2134 
2135 				scsi_extract_sense(&ccb.csio.sense_data,
2136 						   &error_code, &sense_key,
2137 						   &asc, &ascq);
2138 
2139 				if (sense_key != SSD_KEY_ILLEGAL_REQUEST)
2140 					scsi_sense_print(&ccb.csio);
2141 			} else {
2142 				xpt_print_path(periph->path);
2143 				kprintf("Synchronize cache failed, status "
2144 				       "== 0x%x, scsi status == 0x%x\n",
2145 				       ccb.ccb_h.status, ccb.csio.scsi_status);
2146 			}
2147 		}
2148 
2149 		if ((ccb.ccb_h.status & CAM_DEV_QFRZN) != 0)
2150 			cam_release_devq(ccb.ccb_h.path,
2151 					 /*relsim_flags*/0,
2152 					 /*reduction*/0,
2153 					 /*timeout*/0,
2154 					 /*getcount_only*/0);
2155 
2156 	}
2157 }
2158 
2159 #else /* !_KERNEL */
2160 
2161 /*
2162  * XXX This is only left out of the kernel build to silence warnings.  If,
2163  * for some reason this function is used in the kernel, the ifdefs should
2164  * be moved so it is included both in the kernel and userland.
2165  */
2166 void
2167 scsi_format_unit(struct ccb_scsiio *csio, u_int32_t retries,
2168 		 void (*cbfcnp)(struct cam_periph *, union ccb *),
2169 		 u_int8_t tag_action, u_int8_t byte2, u_int16_t ileave,
2170 		 u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
2171 		 u_int32_t timeout)
2172 {
2173 	struct scsi_format_unit *scsi_cmd;
2174 
2175 	scsi_cmd = (struct scsi_format_unit *)&csio->cdb_io.cdb_bytes;
2176 	scsi_cmd->opcode = FORMAT_UNIT;
2177 	scsi_cmd->byte2 = byte2;
2178 	scsi_ulto2b(ileave, scsi_cmd->interleave);
2179 
2180 	cam_fill_csio(csio,
2181 		      retries,
2182 		      cbfcnp,
2183 		      /*flags*/ (dxfer_len > 0) ? CAM_DIR_OUT : CAM_DIR_NONE,
2184 		      tag_action,
2185 		      data_ptr,
2186 		      dxfer_len,
2187 		      sense_len,
2188 		      sizeof(*scsi_cmd),
2189 		      timeout);
2190 }
2191 
2192 #endif /* _KERNEL */
2193