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