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