xref: /freebsd/sys/cam/scsi/scsi_da.c (revision b1d046441de9053152c7cf03d6b60d9882687e1b)
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.h>
48 #include <geom/geom_disk.h>
49 #endif /* _KERNEL */
50 
51 #ifndef _KERNEL
52 #include <stdio.h>
53 #include <string.h>
54 #endif /* _KERNEL */
55 
56 #include <cam/cam.h>
57 #include <cam/cam_ccb.h>
58 #include <cam/cam_periph.h>
59 #include <cam/cam_xpt_periph.h>
60 #include <cam/cam_sim.h>
61 
62 #include <cam/scsi/scsi_message.h>
63 
64 #ifndef _KERNEL
65 #include <cam/scsi/scsi_da.h>
66 #endif /* !_KERNEL */
67 
68 #ifdef _KERNEL
69 typedef enum {
70 	DA_STATE_PROBE,
71 	DA_STATE_PROBE2,
72 	DA_STATE_NORMAL
73 } da_state;
74 
75 typedef enum {
76 	DA_FLAG_PACK_INVALID	= 0x001,
77 	DA_FLAG_NEW_PACK	= 0x002,
78 	DA_FLAG_PACK_LOCKED	= 0x004,
79 	DA_FLAG_PACK_REMOVABLE	= 0x008,
80 	DA_FLAG_TAGGED_QUEUING	= 0x010,
81 	DA_FLAG_NEED_OTAG	= 0x020,
82 	DA_FLAG_WENT_IDLE	= 0x040,
83 	DA_FLAG_RETRY_UA	= 0x080,
84 	DA_FLAG_OPEN		= 0x100,
85 	DA_FLAG_SCTX_INIT	= 0x200,
86 	DA_FLAG_CAN_RC16	= 0x400
87 } da_flags;
88 
89 typedef enum {
90 	DA_Q_NONE		= 0x00,
91 	DA_Q_NO_SYNC_CACHE	= 0x01,
92 	DA_Q_NO_6_BYTE		= 0x02,
93 	DA_Q_NO_PREVENT		= 0x04,
94 	DA_Q_4K			= 0x08
95 } da_quirks;
96 
97 typedef enum {
98 	DA_CCB_PROBE		= 0x01,
99 	DA_CCB_PROBE2		= 0x02,
100 	DA_CCB_BUFFER_IO	= 0x03,
101 	DA_CCB_WAITING		= 0x04,
102 	DA_CCB_DUMP		= 0x05,
103 	DA_CCB_DELETE		= 0x06,
104 	DA_CCB_TYPE_MASK	= 0x0F,
105 	DA_CCB_RETRY_UA		= 0x10
106 } da_ccb_state;
107 
108 typedef enum {
109 	DA_DELETE_NONE,
110 	DA_DELETE_DISABLE,
111 	DA_DELETE_ZERO,
112 	DA_DELETE_WS10,
113 	DA_DELETE_WS16,
114 	DA_DELETE_UNMAP,
115 	DA_DELETE_MAX = DA_DELETE_UNMAP
116 } da_delete_methods;
117 
118 static const char *da_delete_method_names[] =
119     { "NONE", "DISABLE", "ZERO", "WS10", "WS16", "UNMAP" };
120 
121 /* Offsets into our private area for storing information */
122 #define ccb_state	ppriv_field0
123 #define ccb_bp		ppriv_ptr1
124 
125 struct disk_params {
126 	u_int8_t  heads;
127 	u_int32_t cylinders;
128 	u_int8_t  secs_per_track;
129 	u_int32_t secsize;	/* Number of bytes/sector */
130 	u_int64_t sectors;	/* total number sectors */
131 	u_int     stripesize;
132 	u_int     stripeoffset;
133 };
134 
135 #define UNMAP_MAX_RANGES	512
136 
137 struct da_softc {
138 	struct	 bio_queue_head bio_queue;
139 	struct	 bio_queue_head delete_queue;
140 	struct	 bio_queue_head delete_run_queue;
141 	SLIST_ENTRY(da_softc) links;
142 	LIST_HEAD(, ccb_hdr) pending_ccbs;
143 	da_state state;
144 	da_flags flags;
145 	da_quirks quirks;
146 	int	 minimum_cmd_size;
147 	int	 error_inject;
148 	int	 ordered_tag_count;
149 	int	 outstanding_cmds;
150 	int	 unmap_max_ranges;
151 	int	 unmap_max_lba;
152 	int	 delete_running;
153 	da_delete_methods	 delete_method;
154 	struct	 disk_params params;
155 	struct	 disk *disk;
156 	union	 ccb saved_ccb;
157 	struct task		sysctl_task;
158 	struct sysctl_ctx_list	sysctl_ctx;
159 	struct sysctl_oid	*sysctl_tree;
160 	struct callout		sendordered_c;
161 	uint64_t wwpn;
162 	uint8_t	 unmap_buf[UNMAP_MAX_RANGES * 16 + 8];
163 };
164 
165 struct da_quirk_entry {
166 	struct scsi_inquiry_pattern inq_pat;
167 	da_quirks quirks;
168 };
169 
170 static const char quantum[] = "QUANTUM";
171 static const char microp[] = "MICROP";
172 
173 static struct da_quirk_entry da_quirk_table[] =
174 {
175 	/* SPI, FC devices */
176 	{
177 		/*
178 		 * Fujitsu M2513A MO drives.
179 		 * Tested devices: M2513A2 firmware versions 1200 & 1300.
180 		 * (dip switch selects whether T_DIRECT or T_OPTICAL device)
181 		 * Reported by: W.Scholten <whs@xs4all.nl>
182 		 */
183 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "FUJITSU", "M2513A", "*"},
184 		/*quirks*/ DA_Q_NO_SYNC_CACHE
185 	},
186 	{
187 		/* See above. */
188 		{T_OPTICAL, SIP_MEDIA_REMOVABLE, "FUJITSU", "M2513A", "*"},
189 		/*quirks*/ DA_Q_NO_SYNC_CACHE
190 	},
191 	{
192 		/*
193 		 * This particular Fujitsu drive doesn't like the
194 		 * synchronize cache command.
195 		 * Reported by: Tom Jackson <toj@gorilla.net>
196 		 */
197 		{T_DIRECT, SIP_MEDIA_FIXED, "FUJITSU", "M2954*", "*"},
198 		/*quirks*/ DA_Q_NO_SYNC_CACHE
199 	},
200 	{
201 		/*
202 		 * This drive doesn't like the synchronize cache command
203 		 * either.  Reported by: Matthew Jacob <mjacob@feral.com>
204 		 * in NetBSD PR kern/6027, August 24, 1998.
205 		 */
206 		{T_DIRECT, SIP_MEDIA_FIXED, microp, "2217*", "*"},
207 		/*quirks*/ DA_Q_NO_SYNC_CACHE
208 	},
209 	{
210 		/*
211 		 * This drive doesn't like the synchronize cache command
212 		 * either.  Reported by: Hellmuth Michaelis (hm@kts.org)
213 		 * (PR 8882).
214 		 */
215 		{T_DIRECT, SIP_MEDIA_FIXED, microp, "2112*", "*"},
216 		/*quirks*/ DA_Q_NO_SYNC_CACHE
217 	},
218 	{
219 		/*
220 		 * Doesn't like the synchronize cache command.
221 		 * Reported by: Blaz Zupan <blaz@gold.amis.net>
222 		 */
223 		{T_DIRECT, SIP_MEDIA_FIXED, "NEC", "D3847*", "*"},
224 		/*quirks*/ DA_Q_NO_SYNC_CACHE
225 	},
226 	{
227 		/*
228 		 * Doesn't like the synchronize cache command.
229 		 * Reported by: Blaz Zupan <blaz@gold.amis.net>
230 		 */
231 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "MAVERICK 540S", "*"},
232 		/*quirks*/ DA_Q_NO_SYNC_CACHE
233 	},
234 	{
235 		/*
236 		 * Doesn't like the synchronize cache command.
237 		 */
238 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "LPS525S", "*"},
239 		/*quirks*/ DA_Q_NO_SYNC_CACHE
240 	},
241 	{
242 		/*
243 		 * Doesn't like the synchronize cache command.
244 		 * Reported by: walter@pelissero.de
245 		 */
246 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "LPS540S", "*"},
247 		/*quirks*/ DA_Q_NO_SYNC_CACHE
248 	},
249 	{
250 		/*
251 		 * Doesn't work correctly with 6 byte reads/writes.
252 		 * Returns illegal request, and points to byte 9 of the
253 		 * 6-byte CDB.
254 		 * Reported by:  Adam McDougall <bsdx@spawnet.com>
255 		 */
256 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 4*", "*"},
257 		/*quirks*/ DA_Q_NO_6_BYTE
258 	},
259 	{
260 		/* See above. */
261 		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 2*", "*"},
262 		/*quirks*/ DA_Q_NO_6_BYTE
263 	},
264 	{
265 		/*
266 		 * Doesn't like the synchronize cache command.
267 		 * Reported by: walter@pelissero.de
268 		 */
269 		{T_DIRECT, SIP_MEDIA_FIXED, "CONNER", "CP3500*", "*"},
270 		/*quirks*/ DA_Q_NO_SYNC_CACHE
271 	},
272 	{
273 		/*
274 		 * The CISS RAID controllers do not support SYNC_CACHE
275 		 */
276 		{T_DIRECT, SIP_MEDIA_FIXED, "COMPAQ", "RAID*", "*"},
277 		/*quirks*/ DA_Q_NO_SYNC_CACHE
278 	},
279 	/* USB mass storage devices supported by umass(4) */
280 	{
281 		/*
282 		 * EXATELECOM (Sigmatel) i-Bead 100/105 USB Flash MP3 Player
283 		 * PR: kern/51675
284 		 */
285 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "EXATEL", "i-BEAD10*", "*"},
286 		/*quirks*/ DA_Q_NO_SYNC_CACHE
287 	},
288 	{
289 		/*
290 		 * Power Quotient Int. (PQI) USB flash key
291 		 * PR: kern/53067
292 		 */
293 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "USB Flash Disk*",
294 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
295 	},
296  	{
297  		/*
298  		 * Creative Nomad MUVO mp3 player (USB)
299  		 * PR: kern/53094
300  		 */
301  		{T_DIRECT, SIP_MEDIA_REMOVABLE, "CREATIVE", "NOMAD_MUVO", "*"},
302  		/*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
303  	},
304 	{
305 		/*
306 		 * Jungsoft NEXDISK USB flash key
307 		 * PR: kern/54737
308 		 */
309 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "JUNGSOFT", "NEXDISK*", "*"},
310 		/*quirks*/ DA_Q_NO_SYNC_CACHE
311 	},
312 	{
313 		/*
314 		 * FreeDik USB Mini Data Drive
315 		 * PR: kern/54786
316 		 */
317 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "FreeDik*", "Mini Data Drive",
318 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
319 	},
320 	{
321 		/*
322 		 * Sigmatel USB Flash MP3 Player
323 		 * PR: kern/57046
324 		 */
325 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "SigmaTel", "MSCN", "*"},
326 		/*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
327 	},
328 	{
329 		/*
330 		 * Neuros USB Digital Audio Computer
331 		 * PR: kern/63645
332 		 */
333 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "NEUROS", "dig. audio comp.",
334 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
335 	},
336 	{
337 		/*
338 		 * SEAGRAND NP-900 MP3 Player
339 		 * PR: kern/64563
340 		 */
341 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "SEAGRAND", "NP-900*", "*"},
342 		/*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
343 	},
344 	{
345 		/*
346 		 * iRiver iFP MP3 player (with UMS Firmware)
347 		 * PR: kern/54881, i386/63941, kern/66124
348 		 */
349 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "iRiver", "iFP*", "*"},
350 		/*quirks*/ DA_Q_NO_SYNC_CACHE
351  	},
352 	{
353 		/*
354 		 * Frontier Labs NEX IA+ Digital Audio Player, rev 1.10/0.01
355 		 * PR: kern/70158
356 		 */
357 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "FL" , "Nex*", "*"},
358 		/*quirks*/ DA_Q_NO_SYNC_CACHE
359 	},
360 	{
361 		/*
362 		 * ZICPlay USB MP3 Player with FM
363 		 * PR: kern/75057
364 		 */
365 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "ACTIONS*" , "USB DISK*", "*"},
366 		/*quirks*/ DA_Q_NO_SYNC_CACHE
367 	},
368 	{
369 		/*
370 		 * TEAC USB floppy mechanisms
371 		 */
372 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "TEAC" , "FD-05*", "*"},
373 		/*quirks*/ DA_Q_NO_SYNC_CACHE
374 	},
375 	{
376 		/*
377 		 * Kingston DataTraveler II+ USB Pen-Drive.
378 		 * Reported by: Pawel Jakub Dawidek <pjd@FreeBSD.org>
379 		 */
380 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston" , "DataTraveler II+",
381 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
382 	},
383 	{
384 		/*
385 		 * Motorola E398 Mobile Phone (TransFlash memory card).
386 		 * Reported by: Wojciech A. Koszek <dunstan@FreeBSD.czest.pl>
387 		 * PR: usb/89889
388 		 */
389 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Motorola" , "Motorola Phone",
390 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
391 	},
392 	{
393 		/*
394 		 * Qware BeatZkey! Pro
395 		 * PR: usb/79164
396 		 */
397 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "GENERIC", "USB DISK DEVICE",
398 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
399 	},
400 	{
401 		/*
402 		 * Time DPA20B 1GB MP3 Player
403 		 * PR: usb/81846
404 		 */
405 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "USB2.0*", "(FS) FLASH DISK*",
406 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
407 	},
408 	{
409 		/*
410 		 * Samsung USB key 128Mb
411 		 * PR: usb/90081
412 		 */
413 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "USB-DISK", "FreeDik-FlashUsb",
414 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
415 	},
416 	{
417 		/*
418 		 * Kingston DataTraveler 2.0 USB Flash memory.
419 		 * PR: usb/89196
420 		 */
421 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston", "DataTraveler 2.0",
422 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
423 	},
424 	{
425 		/*
426 		 * Creative MUVO Slim mp3 player (USB)
427 		 * PR: usb/86131
428 		 */
429 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "CREATIVE", "MuVo Slim",
430 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
431 		},
432 	{
433 		/*
434 		 * United MP5512 Portable MP3 Player (2-in-1 USB DISK/MP3)
435 		 * PR: usb/80487
436 		 */
437 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "MUSIC DISK",
438 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
439 	},
440 	{
441 		/*
442 		 * SanDisk Micro Cruzer 128MB
443 		 * PR: usb/75970
444 		 */
445 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "SanDisk" , "Micro Cruzer",
446 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
447 	},
448 	{
449 		/*
450 		 * TOSHIBA TransMemory USB sticks
451 		 * PR: kern/94660
452 		 */
453 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "TOSHIBA", "TransMemory",
454 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
455 	},
456 	{
457 		/*
458 		 * PNY USB Flash keys
459 		 * PR: usb/75578, usb/72344, usb/65436
460 		 */
461 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "*" , "USB DISK*",
462 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
463 	},
464 	{
465 		/*
466 		 * Genesys 6-in-1 Card Reader
467 		 * PR: usb/94647
468 		 */
469 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "STORAGE DEVICE*",
470 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
471 	},
472 	{
473 		/*
474 		 * Rekam Digital CAMERA
475 		 * PR: usb/98713
476 		 */
477 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "CAMERA*", "4MP-9J6*",
478 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
479 	},
480 	{
481 		/*
482 		 * iRiver H10 MP3 player
483 		 * PR: usb/102547
484 		 */
485 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "iriver", "H10*",
486 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
487 	},
488 	{
489 		/*
490 		 * iRiver U10 MP3 player
491 		 * PR: usb/92306
492 		 */
493 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "iriver", "U10*",
494 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
495 	},
496 	{
497 		/*
498 		 * X-Micro Flash Disk
499 		 * PR: usb/96901
500 		 */
501 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "X-Micro", "Flash Disk",
502 		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
503 	},
504 	{
505 		/*
506 		 * EasyMP3 EM732X USB 2.0 Flash MP3 Player
507 		 * PR: usb/96546
508 		 */
509 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "EM732X", "MP3 Player*",
510 		"1.00"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
511 	},
512 	{
513 		/*
514 		 * Denver MP3 player
515 		 * PR: usb/107101
516 		 */
517 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "DENVER", "MP3 PLAYER",
518 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
519 	},
520 	{
521 		/*
522 		 * Philips USB Key Audio KEY013
523 		 * PR: usb/68412
524 		 */
525 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "PHILIPS", "Key*", "*"},
526 		/*quirks*/ DA_Q_NO_SYNC_CACHE | DA_Q_NO_PREVENT
527 	},
528 	{
529 		/*
530 		 * JNC MP3 Player
531 		 * PR: usb/94439
532 		 */
533 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "JNC*" , "MP3 Player*",
534 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
535 	},
536 	{
537 		/*
538 		 * SAMSUNG MP0402H
539 		 * PR: usb/108427
540 		 */
541 		{T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "MP0402H", "*"},
542 		/*quirks*/ DA_Q_NO_SYNC_CACHE
543 	},
544 	{
545 		/*
546 		 * I/O Magic USB flash - Giga Bank
547 		 * PR: usb/108810
548 		 */
549 		{T_DIRECT, SIP_MEDIA_FIXED, "GS-Magic", "stor*", "*"},
550 		/*quirks*/ DA_Q_NO_SYNC_CACHE
551 	},
552 	{
553 		/*
554 		 * JoyFly 128mb USB Flash Drive
555 		 * PR: 96133
556 		 */
557 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "USB 2.0", "Flash Disk*",
558 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
559 	},
560 	{
561 		/*
562 		 * ChipsBnk usb stick
563 		 * PR: 103702
564 		 */
565 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "ChipsBnk", "USB*",
566 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
567 	},
568 	{
569 		/*
570 		 * Storcase (Kingston) InfoStation IFS FC2/SATA-R 201A
571 		 * PR: 129858
572 		 */
573 		{T_DIRECT, SIP_MEDIA_FIXED, "IFS", "FC2/SATA-R*",
574 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
575 	},
576 	{
577 		/*
578 		 * Samsung YP-U3 mp3-player
579 		 * PR: 125398
580 		 */
581 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Samsung", "YP-U3",
582 		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
583 	},
584 	{
585 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Netac", "OnlyDisk*",
586 		 "2000"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
587 	},
588 	{
589 		/*
590 		 * Sony Cyber-Shot DSC cameras
591 		 * PR: usb/137035
592 		 */
593 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Sony", "Sony DSC", "*"},
594 		/*quirks*/ DA_Q_NO_SYNC_CACHE | DA_Q_NO_PREVENT
595 	},
596 	/* ATA/SATA devices over SAS/USB/... */
597 	{
598 		/* Hitachi Advanced Format (4k) drives */
599 		{ T_DIRECT, SIP_MEDIA_FIXED, "Hitachi", "H??????????E3*", "*" },
600 		/*quirks*/DA_Q_4K
601 	},
602 	{
603 		/* Samsung Advanced Format (4k) drives */
604 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SAMSUNG HD155UI*", "*" },
605 		/*quirks*/DA_Q_4K
606 	},
607 	{
608 		/* Samsung Advanced Format (4k) drives */
609 		{ T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "HD155UI*", "*" },
610 		/*quirks*/DA_Q_4K
611 	},
612 	{
613 		/* Samsung Advanced Format (4k) drives */
614 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SAMSUNG HD204UI*", "*" },
615 		/*quirks*/DA_Q_4K
616 	},
617 	{
618 		/* Samsung Advanced Format (4k) drives */
619 		{ T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "HD204UI*", "*" },
620 		/*quirks*/DA_Q_4K
621 	},
622 	{
623 		/* Seagate Barracuda Green Advanced Format (4k) drives */
624 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST????DL*", "*" },
625 		/*quirks*/DA_Q_4K
626 	},
627 	{
628 		/* Seagate Barracuda Green Advanced Format (4k) drives */
629 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST????DL", "*", "*" },
630 		/*quirks*/DA_Q_4K
631 	},
632 	{
633 		/* Seagate Barracuda Green Advanced Format (4k) drives */
634 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST???DM*", "*" },
635 		/*quirks*/DA_Q_4K
636 	},
637 	{
638 		/* Seagate Barracuda Green Advanced Format (4k) drives */
639 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST???DM*", "*", "*" },
640 		/*quirks*/DA_Q_4K
641 	},
642 	{
643 		/* Seagate Barracuda Green Advanced Format (4k) drives */
644 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST????DM*", "*" },
645 		/*quirks*/DA_Q_4K
646 	},
647 	{
648 		/* Seagate Barracuda Green Advanced Format (4k) drives */
649 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST????DM", "*", "*" },
650 		/*quirks*/DA_Q_4K
651 	},
652 	{
653 		/* Seagate Momentus Advanced Format (4k) drives */
654 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9500423AS*", "*" },
655 		/*quirks*/DA_Q_4K
656 	},
657 	{
658 		/* Seagate Momentus Advanced Format (4k) drives */
659 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST950042", "3AS*", "*" },
660 		/*quirks*/DA_Q_4K
661 	},
662 	{
663 		/* Seagate Momentus Advanced Format (4k) drives */
664 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9500424AS*", "*" },
665 		/*quirks*/DA_Q_4K
666 	},
667 	{
668 		/* Seagate Momentus Advanced Format (4k) drives */
669 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST950042", "4AS*", "*" },
670 		/*quirks*/DA_Q_4K
671 	},
672 	{
673 		/* Seagate Momentus Advanced Format (4k) drives */
674 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9640423AS*", "*" },
675 		/*quirks*/DA_Q_4K
676 	},
677 	{
678 		/* Seagate Momentus Advanced Format (4k) drives */
679 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST964042", "3AS*", "*" },
680 		/*quirks*/DA_Q_4K
681 	},
682 	{
683 		/* Seagate Momentus Advanced Format (4k) drives */
684 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9640424AS*", "*" },
685 		/*quirks*/DA_Q_4K
686 	},
687 	{
688 		/* Seagate Momentus Advanced Format (4k) drives */
689 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST964042", "4AS*", "*" },
690 		/*quirks*/DA_Q_4K
691 	},
692 	{
693 		/* Seagate Momentus Advanced Format (4k) drives */
694 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750420AS*", "*" },
695 		/*quirks*/DA_Q_4K
696 	},
697 	{
698 		/* Seagate Momentus Advanced Format (4k) drives */
699 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "0AS*", "*" },
700 		/*quirks*/DA_Q_4K
701 	},
702 	{
703 		/* Seagate Momentus Advanced Format (4k) drives */
704 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750422AS*", "*" },
705 		/*quirks*/DA_Q_4K
706 	},
707 	{
708 		/* Seagate Momentus Advanced Format (4k) drives */
709 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "2AS*", "*" },
710 		/*quirks*/DA_Q_4K
711 	},
712 	{
713 		/* Seagate Momentus Advanced Format (4k) drives */
714 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750423AS*", "*" },
715 		/*quirks*/DA_Q_4K
716 	},
717 	{
718 		/* Seagate Momentus Advanced Format (4k) drives */
719 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "3AS*", "*" },
720 		/*quirks*/DA_Q_4K
721 	},
722 	{
723 		/* Seagate Momentus Thin Advanced Format (4k) drives */
724 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST???LT*", "*" },
725 		/*quirks*/DA_Q_4K
726 	},
727 	{
728 		/* Seagate Momentus Thin Advanced Format (4k) drives */
729 		{ T_DIRECT, SIP_MEDIA_FIXED, "ST???LT*", "*", "*" },
730 		/*quirks*/DA_Q_4K
731 	},
732 	{
733 		/* WDC Caviar Green Advanced Format (4k) drives */
734 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD????RS*", "*" },
735 		/*quirks*/DA_Q_4K
736 	},
737 	{
738 		/* WDC Caviar Green Advanced Format (4k) drives */
739 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "??RS*", "*" },
740 		/*quirks*/DA_Q_4K
741 	},
742 	{
743 		/* WDC Caviar Green Advanced Format (4k) drives */
744 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD????RX*", "*" },
745 		/*quirks*/DA_Q_4K
746 	},
747 	{
748 		/* WDC Caviar Green Advanced Format (4k) drives */
749 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "??RX*", "*" },
750 		/*quirks*/DA_Q_4K
751 	},
752 	{
753 		/* WDC Caviar Green Advanced Format (4k) drives */
754 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD??????RS*", "*" },
755 		/*quirks*/DA_Q_4K
756 	},
757 	{
758 		/* WDC Caviar Green Advanced Format (4k) drives */
759 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "????RS*", "*" },
760 		/*quirks*/DA_Q_4K
761 	},
762 	{
763 		/* WDC Caviar Green Advanced Format (4k) drives */
764 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD??????RX*", "*" },
765 		/*quirks*/DA_Q_4K
766 	},
767 	{
768 		/* WDC Caviar Green Advanced Format (4k) drives */
769 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "????RX*", "*" },
770 		/*quirks*/DA_Q_4K
771 	},
772 	{
773 		/* WDC Scorpio Black Advanced Format (4k) drives */
774 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD???PKT*", "*" },
775 		/*quirks*/DA_Q_4K
776 	},
777 	{
778 		/* WDC Scorpio Black Advanced Format (4k) drives */
779 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "?PKT*", "*" },
780 		/*quirks*/DA_Q_4K
781 	},
782 	{
783 		/* WDC Scorpio Black Advanced Format (4k) drives */
784 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD?????PKT*", "*" },
785 		/*quirks*/DA_Q_4K
786 	},
787 	{
788 		/* WDC Scorpio Black Advanced Format (4k) drives */
789 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "???PKT*", "*" },
790 		/*quirks*/DA_Q_4K
791 	},
792 	{
793 		/* WDC Scorpio Blue Advanced Format (4k) drives */
794 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD???PVT*", "*" },
795 		/*quirks*/DA_Q_4K
796 	},
797 	{
798 		/* WDC Scorpio Blue Advanced Format (4k) drives */
799 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "?PVT*", "*" },
800 		/*quirks*/DA_Q_4K
801 	},
802 	{
803 		/* WDC Scorpio Blue Advanced Format (4k) drives */
804 		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD?????PVT*", "*" },
805 		/*quirks*/DA_Q_4K
806 	},
807 	{
808 		/* WDC Scorpio Blue Advanced Format (4k) drives */
809 		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "???PVT*", "*" },
810 		/*quirks*/DA_Q_4K
811 	},
812 };
813 
814 static	disk_strategy_t	dastrategy;
815 static	dumper_t	dadump;
816 static	periph_init_t	dainit;
817 static	void		daasync(void *callback_arg, u_int32_t code,
818 				struct cam_path *path, void *arg);
819 static	void		dasysctlinit(void *context, int pending);
820 static	int		dacmdsizesysctl(SYSCTL_HANDLER_ARGS);
821 static	int		dadeletemethodsysctl(SYSCTL_HANDLER_ARGS);
822 static	periph_ctor_t	daregister;
823 static	periph_dtor_t	dacleanup;
824 static	periph_start_t	dastart;
825 static	periph_oninv_t	daoninvalidate;
826 static	void		dadone(struct cam_periph *periph,
827 			       union ccb *done_ccb);
828 static  int		daerror(union ccb *ccb, u_int32_t cam_flags,
829 				u_int32_t sense_flags);
830 static void		daprevent(struct cam_periph *periph, int action);
831 static int		dagetcapacity(struct cam_periph *periph);
832 static void		dasetgeom(struct cam_periph *periph, uint32_t block_len,
833 				  uint64_t maxsector, u_int lbppbe, u_int lalba);
834 static timeout_t	dasendorderedtag;
835 static void		dashutdown(void *arg, int howto);
836 
837 #ifndef DA_DEFAULT_TIMEOUT
838 #define DA_DEFAULT_TIMEOUT 60	/* Timeout in seconds */
839 #endif
840 
841 #ifndef	DA_DEFAULT_RETRY
842 #define	DA_DEFAULT_RETRY	4
843 #endif
844 
845 #ifndef	DA_DEFAULT_SEND_ORDERED
846 #define	DA_DEFAULT_SEND_ORDERED	1
847 #endif
848 
849 
850 static int da_retry_count = DA_DEFAULT_RETRY;
851 static int da_default_timeout = DA_DEFAULT_TIMEOUT;
852 static int da_send_ordered = DA_DEFAULT_SEND_ORDERED;
853 
854 static SYSCTL_NODE(_kern_cam, OID_AUTO, da, CTLFLAG_RD, 0,
855             "CAM Direct Access Disk driver");
856 SYSCTL_INT(_kern_cam_da, OID_AUTO, retry_count, CTLFLAG_RW,
857            &da_retry_count, 0, "Normal I/O retry count");
858 TUNABLE_INT("kern.cam.da.retry_count", &da_retry_count);
859 SYSCTL_INT(_kern_cam_da, OID_AUTO, default_timeout, CTLFLAG_RW,
860            &da_default_timeout, 0, "Normal I/O timeout (in seconds)");
861 TUNABLE_INT("kern.cam.da.default_timeout", &da_default_timeout);
862 SYSCTL_INT(_kern_cam_da, OID_AUTO, da_send_ordered, CTLFLAG_RW,
863            &da_send_ordered, 0, "Send Ordered Tags");
864 TUNABLE_INT("kern.cam.da.da_send_ordered", &da_send_ordered);
865 
866 /*
867  * DA_ORDEREDTAG_INTERVAL determines how often, relative
868  * to the default timeout, we check to see whether an ordered
869  * tagged transaction is appropriate to prevent simple tag
870  * starvation.  Since we'd like to ensure that there is at least
871  * 1/2 of the timeout length left for a starved transaction to
872  * complete after we've sent an ordered tag, we must poll at least
873  * four times in every timeout period.  This takes care of the worst
874  * case where a starved transaction starts during an interval that
875  * meets the requirement "don't send an ordered tag" test so it takes
876  * us two intervals to determine that a tag must be sent.
877  */
878 #ifndef DA_ORDEREDTAG_INTERVAL
879 #define DA_ORDEREDTAG_INTERVAL 4
880 #endif
881 
882 static struct periph_driver dadriver =
883 {
884 	dainit, "da",
885 	TAILQ_HEAD_INITIALIZER(dadriver.units), /* generation */ 0
886 };
887 
888 PERIPHDRIVER_DECLARE(da, dadriver);
889 
890 static MALLOC_DEFINE(M_SCSIDA, "scsi_da", "scsi_da buffers");
891 
892 static int
893 daopen(struct disk *dp)
894 {
895 	struct cam_periph *periph;
896 	struct da_softc *softc;
897 	int unit;
898 	int error;
899 
900 	periph = (struct cam_periph *)dp->d_drv1;
901 	if (periph == NULL) {
902 		return (ENXIO);
903 	}
904 
905 	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
906 		return (ENXIO);
907 	}
908 
909 	cam_periph_lock(periph);
910 	if ((error = cam_periph_hold(periph, PRIBIO|PCATCH)) != 0) {
911 		cam_periph_unlock(periph);
912 		cam_periph_release(periph);
913 		return (error);
914 	}
915 
916 	unit = periph->unit_number;
917 	softc = (struct da_softc *)periph->softc;
918 	softc->flags |= DA_FLAG_OPEN;
919 
920 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
921 	    ("daopen: disk=%s%d (unit %d)\n", dp->d_name, dp->d_unit,
922 	     unit));
923 
924 	if ((softc->flags & DA_FLAG_PACK_INVALID) != 0) {
925 		/* Invalidate our pack information. */
926 		softc->flags &= ~DA_FLAG_PACK_INVALID;
927 	}
928 
929 	error = dagetcapacity(periph);
930 
931 	if (error == 0) {
932 
933 		softc->disk->d_sectorsize = softc->params.secsize;
934 		softc->disk->d_mediasize = softc->params.secsize * (off_t)softc->params.sectors;
935 		softc->disk->d_stripesize = softc->params.stripesize;
936 		softc->disk->d_stripeoffset = softc->params.stripeoffset;
937 		/* XXX: these are not actually "firmware" values, so they may be wrong */
938 		softc->disk->d_fwsectors = softc->params.secs_per_track;
939 		softc->disk->d_fwheads = softc->params.heads;
940 		softc->disk->d_devstat->block_size = softc->params.secsize;
941 		softc->disk->d_devstat->flags &= ~DEVSTAT_BS_UNAVAILABLE;
942 		if (softc->delete_method > DA_DELETE_DISABLE)
943 			softc->disk->d_flags |= DISKFLAG_CANDELETE;
944 		else
945 			softc->disk->d_flags &= ~DISKFLAG_CANDELETE;
946 
947 		if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0 &&
948 		    (softc->quirks & DA_Q_NO_PREVENT) == 0)
949 			daprevent(periph, PR_PREVENT);
950 	} else
951 		softc->flags &= ~DA_FLAG_OPEN;
952 
953 	cam_periph_unhold(periph);
954 	cam_periph_unlock(periph);
955 
956 	if (error != 0) {
957 		cam_periph_release(periph);
958 	}
959 	return (error);
960 }
961 
962 static int
963 daclose(struct disk *dp)
964 {
965 	struct	cam_periph *periph;
966 	struct	da_softc *softc;
967 	int error;
968 
969 	periph = (struct cam_periph *)dp->d_drv1;
970 	if (periph == NULL)
971 		return (0);
972 
973 	cam_periph_lock(periph);
974 	if ((error = cam_periph_hold(periph, PRIBIO)) != 0) {
975 		cam_periph_unlock(periph);
976 		cam_periph_release(periph);
977 		return (0);
978 	}
979 
980 	softc = (struct da_softc *)periph->softc;
981 
982 	if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0
983 	 && (softc->flags & DA_FLAG_PACK_INVALID) == 0) {
984 		union	ccb *ccb;
985 
986 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
987 
988 		scsi_synchronize_cache(&ccb->csio,
989 				       /*retries*/1,
990 				       /*cbfcnp*/dadone,
991 				       MSG_SIMPLE_Q_TAG,
992 				       /*begin_lba*/0,/* Cover the whole disk */
993 				       /*lb_count*/0,
994 				       SSD_FULL_SIZE,
995 				       5 * 60 * 1000);
996 
997 		cam_periph_runccb(ccb, /*error_routine*/NULL, /*cam_flags*/0,
998 				  /*sense_flags*/SF_RETRY_UA,
999 				  softc->disk->d_devstat);
1000 
1001 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1002 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
1003 			     CAM_SCSI_STATUS_ERROR) {
1004 				int asc, ascq;
1005 				int sense_key, error_code;
1006 
1007 				scsi_extract_sense_len(&ccb->csio.sense_data,
1008 				    ccb->csio.sense_len - ccb->csio.sense_resid,
1009 				    &error_code, &sense_key, &asc, &ascq,
1010 				    /*show_errors*/ 1);
1011 				if (sense_key != SSD_KEY_ILLEGAL_REQUEST)
1012 					scsi_sense_print(&ccb->csio);
1013 			} else {
1014 				xpt_print(periph->path, "Synchronize cache "
1015 				    "failed, status == 0x%x, scsi status == "
1016 				    "0x%x\n", ccb->csio.ccb_h.status,
1017 				    ccb->csio.scsi_status);
1018 			}
1019 		}
1020 
1021 		xpt_release_ccb(ccb);
1022 
1023 	}
1024 
1025 	if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0) {
1026 		if ((softc->quirks & DA_Q_NO_PREVENT) == 0)
1027 			daprevent(periph, PR_ALLOW);
1028 		/*
1029 		 * If we've got removeable media, mark the blocksize as
1030 		 * unavailable, since it could change when new media is
1031 		 * inserted.
1032 		 */
1033 		softc->disk->d_devstat->flags |= DEVSTAT_BS_UNAVAILABLE;
1034 	}
1035 
1036 	softc->flags &= ~DA_FLAG_OPEN;
1037 	cam_periph_unhold(periph);
1038 	cam_periph_unlock(periph);
1039 	cam_periph_release(periph);
1040 	return (0);
1041 }
1042 
1043 static void
1044 daschedule(struct cam_periph *periph)
1045 {
1046 	struct da_softc *softc = (struct da_softc *)periph->softc;
1047 	uint32_t prio;
1048 
1049 	/* Check if cam_periph_getccb() was called. */
1050 	prio = periph->immediate_priority;
1051 
1052 	/* Check if we have more work to do. */
1053 	if (bioq_first(&softc->bio_queue) ||
1054 	    (!softc->delete_running && bioq_first(&softc->delete_queue))) {
1055 		prio = CAM_PRIORITY_NORMAL;
1056 	}
1057 
1058 	/* Schedule CCB if any of above is true. */
1059 	if (prio != CAM_PRIORITY_NONE)
1060 		xpt_schedule(periph, prio);
1061 }
1062 
1063 /*
1064  * Actually translate the requested transfer into one the physical driver
1065  * can understand.  The transfer is described by a buf and will include
1066  * only one physical transfer.
1067  */
1068 static void
1069 dastrategy(struct bio *bp)
1070 {
1071 	struct cam_periph *periph;
1072 	struct da_softc *softc;
1073 
1074 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1075 	if (periph == NULL) {
1076 		biofinish(bp, NULL, ENXIO);
1077 		return;
1078 	}
1079 	softc = (struct da_softc *)periph->softc;
1080 
1081 	cam_periph_lock(periph);
1082 
1083 	/*
1084 	 * If the device has been made invalid, error out
1085 	 */
1086 	if ((softc->flags & DA_FLAG_PACK_INVALID)) {
1087 		cam_periph_unlock(periph);
1088 		biofinish(bp, NULL, ENXIO);
1089 		return;
1090 	}
1091 
1092 	/*
1093 	 * Place it in the queue of disk activities for this disk
1094 	 */
1095 	if (bp->bio_cmd == BIO_DELETE) {
1096 		if (bp->bio_bcount == 0)
1097 			biodone(bp);
1098 		else
1099 			bioq_disksort(&softc->delete_queue, bp);
1100 	} else
1101 		bioq_disksort(&softc->bio_queue, bp);
1102 
1103 	/*
1104 	 * Schedule ourselves for performing the work.
1105 	 */
1106 	daschedule(periph);
1107 	cam_periph_unlock(periph);
1108 
1109 	return;
1110 }
1111 
1112 static int
1113 dadump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size_t length)
1114 {
1115 	struct	    cam_periph *periph;
1116 	struct	    da_softc *softc;
1117 	u_int	    secsize;
1118 	struct	    ccb_scsiio csio;
1119 	struct	    disk *dp;
1120 
1121 	dp = arg;
1122 	periph = dp->d_drv1;
1123 	if (periph == NULL)
1124 		return (ENXIO);
1125 	softc = (struct da_softc *)periph->softc;
1126 	cam_periph_lock(periph);
1127 	secsize = softc->params.secsize;
1128 
1129 	if ((softc->flags & DA_FLAG_PACK_INVALID) != 0) {
1130 		cam_periph_unlock(periph);
1131 		return (ENXIO);
1132 	}
1133 
1134 	if (length > 0) {
1135 		xpt_setup_ccb(&csio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1136 		csio.ccb_h.ccb_state = DA_CCB_DUMP;
1137 		scsi_read_write(&csio,
1138 				/*retries*/1,
1139 				dadone,
1140 				MSG_ORDERED_Q_TAG,
1141 				/*read*/FALSE,
1142 				/*byte2*/0,
1143 				/*minimum_cmd_size*/ softc->minimum_cmd_size,
1144 				offset / secsize,
1145 				length / secsize,
1146 				/*data_ptr*/(u_int8_t *) virtual,
1147 				/*dxfer_len*/length,
1148 				/*sense_len*/SSD_FULL_SIZE,
1149 				DA_DEFAULT_TIMEOUT * 1000);
1150 		xpt_polled_action((union ccb *)&csio);
1151 		cam_periph_unlock(periph);
1152 
1153 		if ((csio.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1154 			printf("Aborting dump due to I/O error.\n");
1155 			if ((csio.ccb_h.status & CAM_STATUS_MASK) ==
1156 			     CAM_SCSI_STATUS_ERROR)
1157 				scsi_sense_print(&csio);
1158 			else
1159 				printf("status == 0x%x, scsi status == 0x%x\n",
1160 				       csio.ccb_h.status, csio.scsi_status);
1161 			return(EIO);
1162 		}
1163 		return(0);
1164 	}
1165 
1166 	/*
1167 	 * Sync the disk cache contents to the physical media.
1168 	 */
1169 	if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
1170 
1171 		xpt_setup_ccb(&csio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1172 		csio.ccb_h.ccb_state = DA_CCB_DUMP;
1173 		scsi_synchronize_cache(&csio,
1174 				       /*retries*/1,
1175 				       /*cbfcnp*/dadone,
1176 				       MSG_SIMPLE_Q_TAG,
1177 				       /*begin_lba*/0,/* Cover the whole disk */
1178 				       /*lb_count*/0,
1179 				       SSD_FULL_SIZE,
1180 				       5 * 60 * 1000);
1181 		xpt_polled_action((union ccb *)&csio);
1182 
1183 		if ((csio.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1184 			if ((csio.ccb_h.status & CAM_STATUS_MASK) ==
1185 			     CAM_SCSI_STATUS_ERROR) {
1186 				int asc, ascq;
1187 				int sense_key, error_code;
1188 
1189 				scsi_extract_sense_len(&csio.sense_data,
1190 				    csio.sense_len - csio.sense_resid,
1191 				    &error_code, &sense_key, &asc, &ascq,
1192 				    /*show_errors*/ 1);
1193 				if (sense_key != SSD_KEY_ILLEGAL_REQUEST)
1194 					scsi_sense_print(&csio);
1195 			} else {
1196 				xpt_print(periph->path, "Synchronize cache "
1197 				    "failed, status == 0x%x, scsi status == "
1198 				    "0x%x\n", csio.ccb_h.status,
1199 				    csio.scsi_status);
1200 			}
1201 		}
1202 	}
1203 	cam_periph_unlock(periph);
1204 	return (0);
1205 }
1206 
1207 static int
1208 dagetattr(struct bio *bp)
1209 {
1210 	int ret = -1;
1211 	struct cam_periph *periph;
1212 
1213 	if (bp->bio_disk == NULL || bp->bio_disk->d_drv1 == NULL)
1214 		return ENXIO;
1215 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1216 	if (periph->path == NULL)
1217 		return ENXIO;
1218 
1219 	ret = xpt_getattr(bp->bio_data, bp->bio_length, bp->bio_attribute,
1220 	    periph->path);
1221 	if (ret == 0)
1222 		bp->bio_completed = bp->bio_length;
1223 	return ret;
1224 }
1225 
1226 static void
1227 dainit(void)
1228 {
1229 	cam_status status;
1230 
1231 	/*
1232 	 * Install a global async callback.  This callback will
1233 	 * receive async callbacks like "new device found".
1234 	 */
1235 	status = xpt_register_async(AC_FOUND_DEVICE, daasync, NULL, NULL);
1236 
1237 	if (status != CAM_REQ_CMP) {
1238 		printf("da: Failed to attach master async callback "
1239 		       "due to status 0x%x!\n", status);
1240 	} else if (da_send_ordered) {
1241 
1242 		/* Register our shutdown event handler */
1243 		if ((EVENTHANDLER_REGISTER(shutdown_post_sync, dashutdown,
1244 					   NULL, SHUTDOWN_PRI_DEFAULT)) == NULL)
1245 		    printf("dainit: shutdown event registration failed!\n");
1246 	}
1247 }
1248 
1249 static void
1250 daoninvalidate(struct cam_periph *periph)
1251 {
1252 	struct da_softc *softc;
1253 
1254 	softc = (struct da_softc *)periph->softc;
1255 
1256 	/*
1257 	 * De-register any async callbacks.
1258 	 */
1259 	xpt_register_async(0, daasync, periph, periph->path);
1260 
1261 	softc->flags |= DA_FLAG_PACK_INVALID;
1262 
1263 	/*
1264 	 * Return all queued I/O with ENXIO.
1265 	 * XXX Handle any transactions queued to the card
1266 	 *     with XPT_ABORT_CCB.
1267 	 */
1268 	bioq_flush(&softc->bio_queue, NULL, ENXIO);
1269 	bioq_flush(&softc->delete_queue, NULL, ENXIO);
1270 
1271 	disk_gone(softc->disk);
1272 	xpt_print(periph->path, "lost device - %d outstanding, %d refs\n",
1273 		  softc->outstanding_cmds, periph->refcount);
1274 }
1275 
1276 static void
1277 dacleanup(struct cam_periph *periph)
1278 {
1279 	struct da_softc *softc;
1280 
1281 	softc = (struct da_softc *)periph->softc;
1282 
1283 	xpt_print(periph->path, "removing device entry\n");
1284 	cam_periph_unlock(periph);
1285 
1286 	/*
1287 	 * If we can't free the sysctl tree, oh well...
1288 	 */
1289 	if ((softc->flags & DA_FLAG_SCTX_INIT) != 0
1290 	    && sysctl_ctx_free(&softc->sysctl_ctx) != 0) {
1291 		xpt_print(periph->path, "can't remove sysctl context\n");
1292 	}
1293 
1294 	disk_destroy(softc->disk);
1295 	callout_drain(&softc->sendordered_c);
1296 	free(softc, M_DEVBUF);
1297 	cam_periph_lock(periph);
1298 }
1299 
1300 static void
1301 daasync(void *callback_arg, u_int32_t code,
1302 	struct cam_path *path, void *arg)
1303 {
1304 	struct cam_periph *periph;
1305 
1306 	periph = (struct cam_periph *)callback_arg;
1307 	switch (code) {
1308 	case AC_FOUND_DEVICE:
1309 	{
1310 		struct ccb_getdev *cgd;
1311 		cam_status status;
1312 
1313 		cgd = (struct ccb_getdev *)arg;
1314 		if (cgd == NULL)
1315 			break;
1316 
1317 		if (cgd->protocol != PROTO_SCSI)
1318 			break;
1319 
1320 		if (SID_TYPE(&cgd->inq_data) != T_DIRECT
1321 		    && SID_TYPE(&cgd->inq_data) != T_RBC
1322 		    && SID_TYPE(&cgd->inq_data) != T_OPTICAL)
1323 			break;
1324 
1325 		/*
1326 		 * Allocate a peripheral instance for
1327 		 * this device and start the probe
1328 		 * process.
1329 		 */
1330 		status = cam_periph_alloc(daregister, daoninvalidate,
1331 					  dacleanup, dastart,
1332 					  "da", CAM_PERIPH_BIO,
1333 					  cgd->ccb_h.path, daasync,
1334 					  AC_FOUND_DEVICE, cgd);
1335 
1336 		if (status != CAM_REQ_CMP
1337 		 && status != CAM_REQ_INPROG)
1338 			printf("daasync: Unable to attach to new device "
1339 				"due to status 0x%x\n", status);
1340 		return;
1341 	}
1342 	case AC_ADVINFO_CHANGED:
1343 	{
1344 		uintptr_t buftype;
1345 
1346 		buftype = (uintptr_t)arg;
1347 		if (buftype == CDAI_TYPE_PHYS_PATH) {
1348 			struct da_softc *softc;
1349 
1350 			softc = periph->softc;
1351 			disk_attr_changed(softc->disk, "GEOM::physpath",
1352 					  M_NOWAIT);
1353 		}
1354 		break;
1355 	}
1356 	case AC_SENT_BDR:
1357 	case AC_BUS_RESET:
1358 	{
1359 		struct da_softc *softc;
1360 		struct ccb_hdr *ccbh;
1361 
1362 		softc = (struct da_softc *)periph->softc;
1363 		/*
1364 		 * Don't fail on the expected unit attention
1365 		 * that will occur.
1366 		 */
1367 		softc->flags |= DA_FLAG_RETRY_UA;
1368 		LIST_FOREACH(ccbh, &softc->pending_ccbs, periph_links.le)
1369 			ccbh->ccb_state |= DA_CCB_RETRY_UA;
1370 		break;
1371 	}
1372 	default:
1373 		break;
1374 	}
1375 	cam_periph_async(periph, code, path, arg);
1376 }
1377 
1378 static void
1379 dasysctlinit(void *context, int pending)
1380 {
1381 	struct cam_periph *periph;
1382 	struct da_softc *softc;
1383 	char tmpstr[80], tmpstr2[80];
1384 	struct ccb_trans_settings cts;
1385 
1386 	periph = (struct cam_periph *)context;
1387 	/*
1388 	 * periph was held for us when this task was enqueued
1389 	 */
1390 	if (periph->flags & CAM_PERIPH_INVALID) {
1391 		cam_periph_release(periph);
1392 		return;
1393 	}
1394 
1395 	softc = (struct da_softc *)periph->softc;
1396 	snprintf(tmpstr, sizeof(tmpstr), "CAM DA unit %d", periph->unit_number);
1397 	snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
1398 
1399 	sysctl_ctx_init(&softc->sysctl_ctx);
1400 	softc->flags |= DA_FLAG_SCTX_INIT;
1401 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1402 		SYSCTL_STATIC_CHILDREN(_kern_cam_da), OID_AUTO, tmpstr2,
1403 		CTLFLAG_RD, 0, tmpstr);
1404 	if (softc->sysctl_tree == NULL) {
1405 		printf("dasysctlinit: unable to allocate sysctl tree\n");
1406 		cam_periph_release(periph);
1407 		return;
1408 	}
1409 
1410 	/*
1411 	 * Now register the sysctl handler, so the user can change the value on
1412 	 * the fly.
1413 	 */
1414 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1415 		OID_AUTO, "delete_method", CTLTYPE_STRING | CTLFLAG_RW,
1416 		&softc->delete_method, 0, dadeletemethodsysctl, "A",
1417 		"BIO_DELETE execution method");
1418 	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1419 		OID_AUTO, "minimum_cmd_size", CTLTYPE_INT | CTLFLAG_RW,
1420 		&softc->minimum_cmd_size, 0, dacmdsizesysctl, "I",
1421 		"Minimum CDB size");
1422 
1423 	SYSCTL_ADD_INT(&softc->sysctl_ctx,
1424 		       SYSCTL_CHILDREN(softc->sysctl_tree),
1425 		       OID_AUTO,
1426 		       "error_inject",
1427 		       CTLFLAG_RW,
1428 		       &softc->error_inject,
1429 		       0,
1430 		       "error_inject leaf");
1431 
1432 
1433 	/*
1434 	 * Add some addressing info.
1435 	 */
1436 	memset(&cts, 0, sizeof (cts));
1437 	xpt_setup_ccb(&cts.ccb_h, periph->path, /*priority*/1);
1438 	cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
1439 	cts.type = CTS_TYPE_CURRENT_SETTINGS;
1440 	cam_periph_lock(periph);
1441 	xpt_action((union ccb *)&cts);
1442 	cam_periph_unlock(periph);
1443 	if (cts.ccb_h.status != CAM_REQ_CMP) {
1444 		cam_periph_release(periph);
1445 		return;
1446 	}
1447 	if (cts.protocol == PROTO_SCSI && cts.transport == XPORT_FC) {
1448 		struct ccb_trans_settings_fc *fc = &cts.xport_specific.fc;
1449 		if (fc->valid & CTS_FC_VALID_WWPN) {
1450 			softc->wwpn = fc->wwpn;
1451 			SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
1452 			    SYSCTL_CHILDREN(softc->sysctl_tree),
1453 			    OID_AUTO, "wwpn", CTLFLAG_RD,
1454 			    &softc->wwpn, "World Wide Port Name");
1455 		}
1456 	}
1457 	cam_periph_release(periph);
1458 }
1459 
1460 static int
1461 dacmdsizesysctl(SYSCTL_HANDLER_ARGS)
1462 {
1463 	int error, value;
1464 
1465 	value = *(int *)arg1;
1466 
1467 	error = sysctl_handle_int(oidp, &value, 0, req);
1468 
1469 	if ((error != 0)
1470 	 || (req->newptr == NULL))
1471 		return (error);
1472 
1473 	/*
1474 	 * Acceptable values here are 6, 10, 12 or 16.
1475 	 */
1476 	if (value < 6)
1477 		value = 6;
1478 	else if ((value > 6)
1479 	      && (value <= 10))
1480 		value = 10;
1481 	else if ((value > 10)
1482 	      && (value <= 12))
1483 		value = 12;
1484 	else if (value > 12)
1485 		value = 16;
1486 
1487 	*(int *)arg1 = value;
1488 
1489 	return (0);
1490 }
1491 
1492 static int
1493 dadeletemethodsysctl(SYSCTL_HANDLER_ARGS)
1494 {
1495 	char buf[16];
1496 	int error;
1497 	const char *p;
1498 	int i, value;
1499 
1500 	value = *(int *)arg1;
1501 	if (value < 0 || value > DA_DELETE_MAX)
1502 		p = "UNKNOWN";
1503 	else
1504 		p = da_delete_method_names[value];
1505 	strncpy(buf, p, sizeof(buf));
1506 	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
1507 	if (error != 0 || req->newptr == NULL)
1508 		return (error);
1509 	for (i = 0; i <= DA_DELETE_MAX; i++) {
1510 		if (strcmp(buf, da_delete_method_names[i]) != 0)
1511 			continue;
1512 		*(int *)arg1 = i;
1513 		return (0);
1514 	}
1515 	return (EINVAL);
1516 }
1517 
1518 static cam_status
1519 daregister(struct cam_periph *periph, void *arg)
1520 {
1521 	struct da_softc *softc;
1522 	struct ccb_pathinq cpi;
1523 	struct ccb_getdev *cgd;
1524 	char tmpstr[80];
1525 	caddr_t match;
1526 
1527 	cgd = (struct ccb_getdev *)arg;
1528 	if (periph == NULL) {
1529 		printf("daregister: periph was NULL!!\n");
1530 		return(CAM_REQ_CMP_ERR);
1531 	}
1532 
1533 	if (cgd == NULL) {
1534 		printf("daregister: no getdev CCB, can't register device\n");
1535 		return(CAM_REQ_CMP_ERR);
1536 	}
1537 
1538 	softc = (struct da_softc *)malloc(sizeof(*softc), M_DEVBUF,
1539 	    M_NOWAIT|M_ZERO);
1540 
1541 	if (softc == NULL) {
1542 		printf("daregister: Unable to probe new device. "
1543 		       "Unable to allocate softc\n");
1544 		return(CAM_REQ_CMP_ERR);
1545 	}
1546 
1547 	LIST_INIT(&softc->pending_ccbs);
1548 	softc->state = DA_STATE_PROBE;
1549 	bioq_init(&softc->bio_queue);
1550 	bioq_init(&softc->delete_queue);
1551 	bioq_init(&softc->delete_run_queue);
1552 	if (SID_IS_REMOVABLE(&cgd->inq_data))
1553 		softc->flags |= DA_FLAG_PACK_REMOVABLE;
1554 	if ((cgd->inq_data.flags & SID_CmdQue) != 0)
1555 		softc->flags |= DA_FLAG_TAGGED_QUEUING;
1556 	softc->unmap_max_ranges = UNMAP_MAX_RANGES;
1557 	softc->unmap_max_lba = 1024*1024*2;
1558 
1559 	periph->softc = softc;
1560 
1561 	/*
1562 	 * See if this device has any quirks.
1563 	 */
1564 	match = cam_quirkmatch((caddr_t)&cgd->inq_data,
1565 			       (caddr_t)da_quirk_table,
1566 			       sizeof(da_quirk_table)/sizeof(*da_quirk_table),
1567 			       sizeof(*da_quirk_table), scsi_inquiry_match);
1568 
1569 	if (match != NULL)
1570 		softc->quirks = ((struct da_quirk_entry *)match)->quirks;
1571 	else
1572 		softc->quirks = DA_Q_NONE;
1573 
1574 	/* Check if the SIM does not want 6 byte commands */
1575 	bzero(&cpi, sizeof(cpi));
1576 	xpt_setup_ccb(&cpi.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1577 	cpi.ccb_h.func_code = XPT_PATH_INQ;
1578 	xpt_action((union ccb *)&cpi);
1579 	if (cpi.ccb_h.status == CAM_REQ_CMP && (cpi.hba_misc & PIM_NO_6_BYTE))
1580 		softc->quirks |= DA_Q_NO_6_BYTE;
1581 
1582 	TASK_INIT(&softc->sysctl_task, 0, dasysctlinit, periph);
1583 
1584 	/*
1585 	 * Take an exclusive refcount on the periph while dastart is called
1586 	 * to finish the probe.  The reference will be dropped in dadone at
1587 	 * the end of probe.
1588 	 */
1589 	(void)cam_periph_hold(periph, PRIBIO);
1590 
1591 	/*
1592 	 * Schedule a periodic event to occasionally send an
1593 	 * ordered tag to a device.
1594 	 */
1595 	callout_init_mtx(&softc->sendordered_c, periph->sim->mtx, 0);
1596 	callout_reset(&softc->sendordered_c,
1597 	    (DA_DEFAULT_TIMEOUT * hz) / DA_ORDEREDTAG_INTERVAL,
1598 	    dasendorderedtag, softc);
1599 
1600 	mtx_unlock(periph->sim->mtx);
1601 	/*
1602 	 * RBC devices don't have to support READ(6), only READ(10).
1603 	 */
1604 	if (softc->quirks & DA_Q_NO_6_BYTE || SID_TYPE(&cgd->inq_data) == T_RBC)
1605 		softc->minimum_cmd_size = 10;
1606 	else
1607 		softc->minimum_cmd_size = 6;
1608 
1609 	/*
1610 	 * Load the user's default, if any.
1611 	 */
1612 	snprintf(tmpstr, sizeof(tmpstr), "kern.cam.da.%d.minimum_cmd_size",
1613 		 periph->unit_number);
1614 	TUNABLE_INT_FETCH(tmpstr, &softc->minimum_cmd_size);
1615 
1616 	/*
1617 	 * 6, 10, 12 and 16 are the currently permissible values.
1618 	 */
1619 	if (softc->minimum_cmd_size < 6)
1620 		softc->minimum_cmd_size = 6;
1621 	else if ((softc->minimum_cmd_size > 6)
1622 	      && (softc->minimum_cmd_size <= 10))
1623 		softc->minimum_cmd_size = 10;
1624 	else if ((softc->minimum_cmd_size > 10)
1625 	      && (softc->minimum_cmd_size <= 12))
1626 		softc->minimum_cmd_size = 12;
1627 	else if (softc->minimum_cmd_size > 12)
1628 		softc->minimum_cmd_size = 16;
1629 
1630 	/* Predict whether device may support READ CAPACITY(16). */
1631 	if (SID_ANSI_REV(&cgd->inq_data) >= SCSI_REV_SPC3 ||
1632 	    (SID_ANSI_REV(&cgd->inq_data) >= SCSI_REV_SPC &&
1633 	     (cgd->inq_data.spc3_flags & SPC3_SID_PROTECT))) {
1634 		softc->flags |= DA_FLAG_CAN_RC16;
1635 		softc->state = DA_STATE_PROBE2;
1636 	}
1637 
1638 	/*
1639 	 * Register this media as a disk.
1640 	 */
1641 	softc->disk = disk_alloc();
1642 	softc->disk->d_devstat = devstat_new_entry(periph->periph_name,
1643 			  periph->unit_number, 0,
1644 			  DEVSTAT_BS_UNAVAILABLE,
1645 			  SID_TYPE(&cgd->inq_data) |
1646 			  XPORT_DEVSTAT_TYPE(cpi.transport),
1647 			  DEVSTAT_PRIORITY_DISK);
1648 	softc->disk->d_open = daopen;
1649 	softc->disk->d_close = daclose;
1650 	softc->disk->d_strategy = dastrategy;
1651 	softc->disk->d_dump = dadump;
1652 	softc->disk->d_getattr = dagetattr;
1653 	softc->disk->d_name = "da";
1654 	softc->disk->d_drv1 = periph;
1655 	if (cpi.maxio == 0)
1656 		softc->disk->d_maxsize = DFLTPHYS;	/* traditional default */
1657 	else if (cpi.maxio > MAXPHYS)
1658 		softc->disk->d_maxsize = MAXPHYS;	/* for safety */
1659 	else
1660 		softc->disk->d_maxsize = cpi.maxio;
1661 	softc->disk->d_unit = periph->unit_number;
1662 	softc->disk->d_flags = 0;
1663 	if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0)
1664 		softc->disk->d_flags |= DISKFLAG_CANFLUSHCACHE;
1665 	cam_strvis(softc->disk->d_descr, cgd->inq_data.vendor,
1666 	    sizeof(cgd->inq_data.vendor), sizeof(softc->disk->d_descr));
1667 	strlcat(softc->disk->d_descr, " ", sizeof(softc->disk->d_descr));
1668 	cam_strvis(&softc->disk->d_descr[strlen(softc->disk->d_descr)],
1669 	    cgd->inq_data.product, sizeof(cgd->inq_data.product),
1670 	    sizeof(softc->disk->d_descr) - strlen(softc->disk->d_descr));
1671 	softc->disk->d_hba_vendor = cpi.hba_vendor;
1672 	softc->disk->d_hba_device = cpi.hba_device;
1673 	softc->disk->d_hba_subvendor = cpi.hba_subvendor;
1674 	softc->disk->d_hba_subdevice = cpi.hba_subdevice;
1675 	disk_create(softc->disk, DISK_VERSION);
1676 	mtx_lock(periph->sim->mtx);
1677 
1678 	/*
1679 	 * Add async callbacks for events of interest.
1680 	 * I don't bother checking if this fails as,
1681 	 * in most cases, the system will function just
1682 	 * fine without them and the only alternative
1683 	 * would be to not attach the device on failure.
1684 	 */
1685 	xpt_register_async(AC_SENT_BDR | AC_BUS_RESET
1686 			 | AC_LOST_DEVICE | AC_ADVINFO_CHANGED,
1687 			   daasync, periph, periph->path);
1688 
1689 	/*
1690 	 * Emit an attribute changed notification just in case
1691 	 * physical path information arrived before our async
1692 	 * event handler was registered, but after anyone attaching
1693 	 * to our disk device polled it.
1694 	 */
1695 	disk_attr_changed(softc->disk, "GEOM::physpath", M_NOWAIT);
1696 
1697 	xpt_schedule(periph, CAM_PRIORITY_DEV);
1698 
1699 	return(CAM_REQ_CMP);
1700 }
1701 
1702 static void
1703 dastart(struct cam_periph *periph, union ccb *start_ccb)
1704 {
1705 	struct da_softc *softc;
1706 
1707 	softc = (struct da_softc *)periph->softc;
1708 
1709 	switch (softc->state) {
1710 	case DA_STATE_NORMAL:
1711 	{
1712 		struct bio *bp, *bp1;
1713 		uint8_t tag_code;
1714 
1715 		/* Execute immediate CCB if waiting. */
1716 		if (periph->immediate_priority <= periph->pinfo.priority) {
1717 			CAM_DEBUG_PRINT(CAM_DEBUG_SUBTRACE,
1718 					("queuing for immediate ccb\n"));
1719 			start_ccb->ccb_h.ccb_state = DA_CCB_WAITING;
1720 			SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
1721 					  periph_links.sle);
1722 			periph->immediate_priority = CAM_PRIORITY_NONE;
1723 			wakeup(&periph->ccb_list);
1724 			/* May have more work to do, so ensure we stay scheduled */
1725 			daschedule(periph);
1726 			break;
1727 		}
1728 
1729 		/* Run BIO_DELETE if not running yet. */
1730 		if (!softc->delete_running &&
1731 		    (bp = bioq_first(&softc->delete_queue)) != NULL) {
1732 		    uint64_t lba;
1733 		    u_int count;
1734 
1735 		    if (softc->delete_method == DA_DELETE_UNMAP) {
1736 			uint8_t *buf = softc->unmap_buf;
1737 			uint64_t lastlba = (uint64_t)-1;
1738 			uint32_t lastcount = 0;
1739 			int blocks = 0, off, ranges = 0;
1740 
1741 			softc->delete_running = 1;
1742 			bzero(softc->unmap_buf, sizeof(softc->unmap_buf));
1743 			bp1 = bp;
1744 			do {
1745 				bioq_remove(&softc->delete_queue, bp1);
1746 				if (bp1 != bp)
1747 					bioq_insert_tail(&softc->delete_run_queue, bp1);
1748 				lba = bp1->bio_pblkno;
1749 				count = bp1->bio_bcount / softc->params.secsize;
1750 
1751 				/* Try to extend the previous range. */
1752 				if (lba == lastlba) {
1753 					lastcount += count;
1754 					off = (ranges - 1) * 16 + 8;
1755 					scsi_ulto4b(lastcount, &buf[off + 8]);
1756 				} else if (count > 0) {
1757 					off = ranges * 16 + 8;
1758 					scsi_u64to8b(lba, &buf[off + 0]);
1759 					scsi_ulto4b(count, &buf[off + 8]);
1760 					lastcount = count;
1761 					ranges++;
1762 				}
1763 				blocks += count;
1764 				lastlba = lba + count;
1765 				bp1 = bioq_first(&softc->delete_queue);
1766 				if (bp1 == NULL ||
1767 				    ranges >= softc->unmap_max_ranges ||
1768 				    blocks + bp1->bio_bcount /
1769 				     softc->params.secsize > softc->unmap_max_lba)
1770 					break;
1771 			} while (1);
1772 			scsi_ulto2b(count * 16 + 6, &buf[0]);
1773 			scsi_ulto2b(count * 16, &buf[2]);
1774 
1775 			scsi_unmap(&start_ccb->csio,
1776 					/*retries*/da_retry_count,
1777 					/*cbfcnp*/dadone,
1778 					/*tag_action*/MSG_SIMPLE_Q_TAG,
1779 					/*byte2*/0,
1780 					/*data_ptr*/ buf,
1781 					/*dxfer_len*/ count * 16 + 8,
1782 					/*sense_len*/SSD_FULL_SIZE,
1783 					da_default_timeout * 1000);
1784 			start_ccb->ccb_h.ccb_state = DA_CCB_DELETE;
1785 			goto out;
1786 		    } else if (softc->delete_method == DA_DELETE_ZERO ||
1787 			       softc->delete_method == DA_DELETE_WS10 ||
1788 			       softc->delete_method == DA_DELETE_WS16) {
1789 			softc->delete_running = 1;
1790 			lba = bp->bio_pblkno;
1791 			count = 0;
1792 			bp1 = bp;
1793 			do {
1794 				bioq_remove(&softc->delete_queue, bp1);
1795 				if (bp1 != bp)
1796 					bioq_insert_tail(&softc->delete_run_queue, bp1);
1797 				count += bp1->bio_bcount / softc->params.secsize;
1798 				bp1 = bioq_first(&softc->delete_queue);
1799 				if (bp1 == NULL ||
1800 				    lba + count != bp1->bio_pblkno ||
1801 				    count + bp1->bio_bcount /
1802 				     softc->params.secsize > 0xffff)
1803 					break;
1804 			} while (1);
1805 
1806 			scsi_write_same(&start_ccb->csio,
1807 					/*retries*/da_retry_count,
1808 					/*cbfcnp*/dadone,
1809 					/*tag_action*/MSG_SIMPLE_Q_TAG,
1810 					/*byte2*/softc->delete_method ==
1811 					    DA_DELETE_ZERO ? 0 : SWS_UNMAP,
1812 					softc->delete_method ==
1813 					    DA_DELETE_WS16 ? 16 : 10,
1814 					/*lba*/lba,
1815 					/*block_count*/count,
1816 					/*data_ptr*/ __DECONST(void *,
1817 					    zero_region),
1818 					/*dxfer_len*/ softc->params.secsize,
1819 					/*sense_len*/SSD_FULL_SIZE,
1820 					da_default_timeout * 1000);
1821 			start_ccb->ccb_h.ccb_state = DA_CCB_DELETE;
1822 			goto out;
1823 		    } else {
1824 			bioq_flush(&softc->delete_queue, NULL, 0);
1825 			/* FALLTHROUGH */
1826 		    }
1827 		}
1828 
1829 		/* Run regular command. */
1830 		bp = bioq_takefirst(&softc->bio_queue);
1831 		if (bp == NULL) {
1832 			xpt_release_ccb(start_ccb);
1833 			break;
1834 		}
1835 
1836 		if ((bp->bio_flags & BIO_ORDERED) != 0 ||
1837 		    (softc->flags & DA_FLAG_NEED_OTAG) != 0) {
1838 			softc->flags &= ~DA_FLAG_NEED_OTAG;
1839 			softc->ordered_tag_count++;
1840 			tag_code = MSG_ORDERED_Q_TAG;
1841 		} else {
1842 			tag_code = MSG_SIMPLE_Q_TAG;
1843 		}
1844 
1845 		switch (bp->bio_cmd) {
1846 		case BIO_READ:
1847 		case BIO_WRITE:
1848 			scsi_read_write(&start_ccb->csio,
1849 					/*retries*/da_retry_count,
1850 					/*cbfcnp*/dadone,
1851 					/*tag_action*/tag_code,
1852 					/*read_op*/bp->bio_cmd
1853 						== BIO_READ,
1854 					/*byte2*/0,
1855 					softc->minimum_cmd_size,
1856 					/*lba*/bp->bio_pblkno,
1857 					/*block_count*/bp->bio_bcount /
1858 					softc->params.secsize,
1859 					/*data_ptr*/ bp->bio_data,
1860 					/*dxfer_len*/ bp->bio_bcount,
1861 					/*sense_len*/SSD_FULL_SIZE,
1862 					da_default_timeout * 1000);
1863 			break;
1864 		case BIO_FLUSH:
1865 			/*
1866 			 * BIO_FLUSH doesn't currently communicate
1867 			 * range data, so we synchronize the cache
1868 			 * over the whole disk.  We also force
1869 			 * ordered tag semantics the flush applies
1870 			 * to all previously queued I/O.
1871 			 */
1872 			scsi_synchronize_cache(&start_ccb->csio,
1873 					       /*retries*/1,
1874 					       /*cbfcnp*/dadone,
1875 					       MSG_ORDERED_Q_TAG,
1876 					       /*begin_lba*/0,
1877 					       /*lb_count*/0,
1878 					       SSD_FULL_SIZE,
1879 					       da_default_timeout*1000);
1880 			break;
1881 		}
1882 		start_ccb->ccb_h.ccb_state = DA_CCB_BUFFER_IO;
1883 
1884 out:
1885 		/*
1886 		 * Block out any asyncronous callbacks
1887 		 * while we touch the pending ccb list.
1888 		 */
1889 		LIST_INSERT_HEAD(&softc->pending_ccbs,
1890 				 &start_ccb->ccb_h, periph_links.le);
1891 		softc->outstanding_cmds++;
1892 
1893 		/* We expect a unit attention from this device */
1894 		if ((softc->flags & DA_FLAG_RETRY_UA) != 0) {
1895 			start_ccb->ccb_h.ccb_state |= DA_CCB_RETRY_UA;
1896 			softc->flags &= ~DA_FLAG_RETRY_UA;
1897 		}
1898 
1899 		start_ccb->ccb_h.ccb_bp = bp;
1900 		xpt_action(start_ccb);
1901 
1902 		/* May have more work to do, so ensure we stay scheduled */
1903 		daschedule(periph);
1904 		break;
1905 	}
1906 	case DA_STATE_PROBE:
1907 	{
1908 		struct ccb_scsiio *csio;
1909 		struct scsi_read_capacity_data *rcap;
1910 
1911 		rcap = (struct scsi_read_capacity_data *)
1912 		    malloc(sizeof(*rcap), M_SCSIDA, M_NOWAIT|M_ZERO);
1913 		if (rcap == NULL) {
1914 			printf("dastart: Couldn't malloc read_capacity data\n");
1915 			/* da_free_periph??? */
1916 			break;
1917 		}
1918 		csio = &start_ccb->csio;
1919 		scsi_read_capacity(csio,
1920 				   /*retries*/4,
1921 				   dadone,
1922 				   MSG_SIMPLE_Q_TAG,
1923 				   rcap,
1924 				   SSD_FULL_SIZE,
1925 				   /*timeout*/5000);
1926 		start_ccb->ccb_h.ccb_bp = NULL;
1927 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE;
1928 		xpt_action(start_ccb);
1929 		break;
1930 	}
1931 	case DA_STATE_PROBE2:
1932 	{
1933 		struct ccb_scsiio *csio;
1934 		struct scsi_read_capacity_data_long *rcaplong;
1935 
1936 		rcaplong = (struct scsi_read_capacity_data_long *)
1937 			malloc(sizeof(*rcaplong), M_SCSIDA, M_NOWAIT|M_ZERO);
1938 		if (rcaplong == NULL) {
1939 			printf("dastart: Couldn't malloc read_capacity data\n");
1940 			/* da_free_periph??? */
1941 			break;
1942 		}
1943 		csio = &start_ccb->csio;
1944 		scsi_read_capacity_16(csio,
1945 				      /*retries*/ 4,
1946 				      /*cbfcnp*/ dadone,
1947 				      /*tag_action*/ MSG_SIMPLE_Q_TAG,
1948 				      /*lba*/ 0,
1949 				      /*reladr*/ 0,
1950 				      /*pmi*/ 0,
1951 				      rcaplong,
1952 				      /*sense_len*/ SSD_FULL_SIZE,
1953 				      /*timeout*/ 60000);
1954 		start_ccb->ccb_h.ccb_bp = NULL;
1955 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE2;
1956 		xpt_action(start_ccb);
1957 		break;
1958 	}
1959 	}
1960 }
1961 
1962 static int
1963 cmd6workaround(union ccb *ccb)
1964 {
1965 	struct scsi_rw_6 cmd6;
1966 	struct scsi_rw_10 *cmd10;
1967 	struct da_softc *softc;
1968 	u_int8_t *cdb;
1969 	struct bio *bp;
1970 	int frozen;
1971 
1972 	cdb = ccb->csio.cdb_io.cdb_bytes;
1973 	softc = (struct da_softc *)xpt_path_periph(ccb->ccb_h.path)->softc;
1974 
1975 	if (ccb->ccb_h.ccb_state == DA_CCB_DELETE) {
1976 		if (softc->delete_method == DA_DELETE_UNMAP) {
1977 			xpt_print(ccb->ccb_h.path, "UNMAP is not supported, "
1978 			    "switching to WRITE SAME(16) with UNMAP.\n");
1979 			softc->delete_method = DA_DELETE_WS16;
1980 		} else if (softc->delete_method == DA_DELETE_WS16) {
1981 			xpt_print(ccb->ccb_h.path,
1982 			    "WRITE SAME(16) with UNMAP is not supported, "
1983 			    "disabling BIO_DELETE.\n");
1984 			softc->delete_method = DA_DELETE_DISABLE;
1985 		} else if (softc->delete_method == DA_DELETE_WS10) {
1986 			xpt_print(ccb->ccb_h.path,
1987 			    "WRITE SAME(10) with UNMAP is not supported, "
1988 			    "disabling BIO_DELETE.\n");
1989 			softc->delete_method = DA_DELETE_DISABLE;
1990 		} else if (softc->delete_method == DA_DELETE_ZERO) {
1991 			xpt_print(ccb->ccb_h.path,
1992 			    "WRITE SAME(10) is not supported, "
1993 			    "disabling BIO_DELETE.\n");
1994 			softc->delete_method = DA_DELETE_DISABLE;
1995 		} else
1996 			softc->delete_method = DA_DELETE_DISABLE;
1997 		while ((bp = bioq_takefirst(&softc->delete_run_queue))
1998 		    != NULL)
1999 			bioq_disksort(&softc->delete_queue, bp);
2000 		bioq_insert_tail(&softc->delete_queue,
2001 		    (struct bio *)ccb->ccb_h.ccb_bp);
2002 		ccb->ccb_h.ccb_bp = NULL;
2003 		return (0);
2004 	}
2005 
2006 	/* Translation only possible if CDB is an array and cmd is R/W6 */
2007 	if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0 ||
2008 	    (*cdb != READ_6 && *cdb != WRITE_6))
2009 		return 0;
2010 
2011 	xpt_print(ccb->ccb_h.path, "READ(6)/WRITE(6) not supported, "
2012 	    "increasing minimum_cmd_size to 10.\n");
2013  	softc->minimum_cmd_size = 10;
2014 
2015 	bcopy(cdb, &cmd6, sizeof(struct scsi_rw_6));
2016 	cmd10 = (struct scsi_rw_10 *)cdb;
2017 	cmd10->opcode = (cmd6.opcode == READ_6) ? READ_10 : WRITE_10;
2018 	cmd10->byte2 = 0;
2019 	scsi_ulto4b(scsi_3btoul(cmd6.addr), cmd10->addr);
2020 	cmd10->reserved = 0;
2021 	scsi_ulto2b(cmd6.length, cmd10->length);
2022 	cmd10->control = cmd6.control;
2023 	ccb->csio.cdb_len = sizeof(*cmd10);
2024 
2025 	/* Requeue request, unfreezing queue if necessary */
2026 	frozen = (ccb->ccb_h.status & CAM_DEV_QFRZN) != 0;
2027  	ccb->ccb_h.status = CAM_REQUEUE_REQ;
2028 	xpt_action(ccb);
2029 	if (frozen) {
2030 		cam_release_devq(ccb->ccb_h.path,
2031 				 /*relsim_flags*/0,
2032 				 /*reduction*/0,
2033 				 /*timeout*/0,
2034 				 /*getcount_only*/0);
2035 	}
2036 	return (ERESTART);
2037 }
2038 
2039 static void
2040 dadone(struct cam_periph *periph, union ccb *done_ccb)
2041 {
2042 	struct da_softc *softc;
2043 	struct ccb_scsiio *csio;
2044 	u_int32_t  priority;
2045 
2046 	softc = (struct da_softc *)periph->softc;
2047 	priority = done_ccb->ccb_h.pinfo.priority;
2048 	csio = &done_ccb->csio;
2049 	switch (csio->ccb_h.ccb_state & DA_CCB_TYPE_MASK) {
2050 	case DA_CCB_BUFFER_IO:
2051 	case DA_CCB_DELETE:
2052 	{
2053 		struct bio *bp, *bp1;
2054 
2055 		bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
2056 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2057 			int error;
2058 			int sf;
2059 
2060 			if ((csio->ccb_h.ccb_state & DA_CCB_RETRY_UA) != 0)
2061 				sf = SF_RETRY_UA;
2062 			else
2063 				sf = 0;
2064 
2065 			error = daerror(done_ccb, CAM_RETRY_SELTO, sf);
2066 			if (error == ERESTART) {
2067 				/*
2068 				 * A retry was scheuled, so
2069 				 * just return.
2070 				 */
2071 				return;
2072 			}
2073 			bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
2074 			if (error != 0) {
2075 				int queued_error;
2076 
2077 				/*
2078 				 * return all queued I/O with EIO, so that
2079 				 * the client can retry these I/Os in the
2080 				 * proper order should it attempt to recover.
2081 				 */
2082 				queued_error = EIO;
2083 
2084 				if (error == ENXIO
2085 				 && (softc->flags & DA_FLAG_PACK_INVALID)== 0) {
2086 					/*
2087 					 * Catastrophic error.  Mark our pack as
2088 					 * invalid.
2089 					 */
2090 					/*
2091 					 * XXX See if this is really a media
2092 					 * XXX change first?
2093 					 */
2094 					xpt_print(periph->path,
2095 					    "Invalidating pack\n");
2096 					softc->flags |= DA_FLAG_PACK_INVALID;
2097 					queued_error = ENXIO;
2098 				}
2099 				bioq_flush(&softc->bio_queue, NULL,
2100 					   queued_error);
2101 				if (bp != NULL) {
2102 					bp->bio_error = error;
2103 					bp->bio_resid = bp->bio_bcount;
2104 					bp->bio_flags |= BIO_ERROR;
2105 				}
2106 			} else if (bp != NULL) {
2107 				bp->bio_resid = csio->resid;
2108 				bp->bio_error = 0;
2109 				if (bp->bio_resid != 0)
2110 					bp->bio_flags |= BIO_ERROR;
2111 			}
2112 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
2113 				cam_release_devq(done_ccb->ccb_h.path,
2114 						 /*relsim_flags*/0,
2115 						 /*reduction*/0,
2116 						 /*timeout*/0,
2117 						 /*getcount_only*/0);
2118 		} else if (bp != NULL) {
2119 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
2120 				panic("REQ_CMP with QFRZN");
2121 			bp->bio_resid = csio->resid;
2122 			if (csio->resid > 0)
2123 				bp->bio_flags |= BIO_ERROR;
2124 			if (softc->error_inject != 0) {
2125 				bp->bio_error = softc->error_inject;
2126 				bp->bio_resid = bp->bio_bcount;
2127 				bp->bio_flags |= BIO_ERROR;
2128 				softc->error_inject = 0;
2129 			}
2130 
2131 		}
2132 
2133 		/*
2134 		 * Block out any asyncronous callbacks
2135 		 * while we touch the pending ccb list.
2136 		 */
2137 		LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
2138 		softc->outstanding_cmds--;
2139 		if (softc->outstanding_cmds == 0)
2140 			softc->flags |= DA_FLAG_WENT_IDLE;
2141 
2142 		if ((softc->flags & DA_FLAG_PACK_INVALID) != 0) {
2143 			xpt_print(periph->path, "oustanding %d\n",
2144 				  softc->outstanding_cmds);
2145 		}
2146 
2147 		if ((csio->ccb_h.ccb_state & DA_CCB_TYPE_MASK) ==
2148 		    DA_CCB_DELETE) {
2149 			while ((bp1 = bioq_takefirst(&softc->delete_run_queue))
2150 			    != NULL) {
2151 				bp1->bio_resid = bp->bio_resid;
2152 				bp1->bio_error = bp->bio_error;
2153 				if (bp->bio_flags & BIO_ERROR)
2154 					bp1->bio_flags |= BIO_ERROR;
2155 				biodone(bp1);
2156 			}
2157 			softc->delete_running = 0;
2158 			if (bp != NULL)
2159 				biodone(bp);
2160 			daschedule(periph);
2161 		} else if (bp != NULL)
2162 			biodone(bp);
2163 		break;
2164 	}
2165 	case DA_CCB_PROBE:
2166 	case DA_CCB_PROBE2:
2167 	{
2168 		struct	   scsi_read_capacity_data *rdcap;
2169 		struct     scsi_read_capacity_data_long *rcaplong;
2170 		char	   announce_buf[80];
2171 
2172 		rdcap = NULL;
2173 		rcaplong = NULL;
2174 		if (softc->state == DA_STATE_PROBE)
2175 			rdcap =(struct scsi_read_capacity_data *)csio->data_ptr;
2176 		else
2177 			rcaplong = (struct scsi_read_capacity_data_long *)
2178 				csio->data_ptr;
2179 
2180 		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
2181 			struct disk_params *dp;
2182 			uint32_t block_size;
2183 			uint64_t maxsector;
2184 			u_int lbppbe;	/* LB per physical block exponent. */
2185 			u_int lalba;	/* Lowest aligned LBA. */
2186 
2187 			if (softc->state == DA_STATE_PROBE) {
2188 				block_size = scsi_4btoul(rdcap->length);
2189 				maxsector = scsi_4btoul(rdcap->addr);
2190 				lbppbe = 0;
2191 				lalba = 0;
2192 
2193 				/*
2194 				 * According to SBC-2, if the standard 10
2195 				 * byte READ CAPACITY command returns 2^32,
2196 				 * we should issue the 16 byte version of
2197 				 * the command, since the device in question
2198 				 * has more sectors than can be represented
2199 				 * with the short version of the command.
2200 				 */
2201 				if (maxsector == 0xffffffff) {
2202 					softc->state = DA_STATE_PROBE2;
2203 					free(rdcap, M_SCSIDA);
2204 					xpt_release_ccb(done_ccb);
2205 					xpt_schedule(periph, priority);
2206 					return;
2207 				}
2208 			} else {
2209 				block_size = scsi_4btoul(rcaplong->length);
2210 				maxsector = scsi_8btou64(rcaplong->addr);
2211 				lbppbe = rcaplong->prot_lbppbe & SRC16_LBPPBE;
2212 				lalba = scsi_2btoul(rcaplong->lalba_lbp);
2213 			}
2214 
2215 			/*
2216 			 * Because GEOM code just will panic us if we
2217 			 * give them an 'illegal' value we'll avoid that
2218 			 * here.
2219 			 */
2220 			if (block_size == 0 && maxsector == 0) {
2221 				snprintf(announce_buf, sizeof(announce_buf),
2222 				        "0MB (no media?)");
2223 			} else if (block_size >= MAXPHYS || block_size == 0) {
2224 				xpt_print(periph->path,
2225 				    "unsupportable block size %ju\n",
2226 				    (uintmax_t) block_size);
2227 				announce_buf[0] = '\0';
2228 				cam_periph_invalidate(periph);
2229 			} else {
2230 				dasetgeom(periph, block_size, maxsector,
2231 				    lbppbe, lalba & SRC16_LALBA);
2232 				if ((lalba & SRC16_LBPME) &&
2233 				    softc->delete_method == DA_DELETE_NONE)
2234 					softc->delete_method = DA_DELETE_UNMAP;
2235 				dp = &softc->params;
2236 				snprintf(announce_buf, sizeof(announce_buf),
2237 				        "%juMB (%ju %u byte sectors: %dH %dS/T "
2238                                         "%dC)", (uintmax_t)
2239 	                                (((uintmax_t)dp->secsize *
2240 				        dp->sectors) / (1024*1024)),
2241 			                (uintmax_t)dp->sectors,
2242 				        dp->secsize, dp->heads,
2243                                         dp->secs_per_track, dp->cylinders);
2244 			}
2245 		} else {
2246 			int	error;
2247 
2248 			announce_buf[0] = '\0';
2249 
2250 			/*
2251 			 * Retry any UNIT ATTENTION type errors.  They
2252 			 * are expected at boot.
2253 			 */
2254 			error = daerror(done_ccb, CAM_RETRY_SELTO,
2255 					SF_RETRY_UA|SF_NO_PRINT);
2256 			if (error == ERESTART) {
2257 				/*
2258 				 * A retry was scheuled, so
2259 				 * just return.
2260 				 */
2261 				return;
2262 			} else if (error != 0) {
2263 				struct scsi_sense_data *sense;
2264 				int asc, ascq;
2265 				int sense_key, error_code;
2266 				int have_sense;
2267 				cam_status status;
2268 				struct ccb_getdev cgd;
2269 
2270 				/* Don't wedge this device's queue */
2271 				status = done_ccb->ccb_h.status;
2272 				if ((status & CAM_DEV_QFRZN) != 0)
2273 					cam_release_devq(done_ccb->ccb_h.path,
2274 							 /*relsim_flags*/0,
2275 							 /*reduction*/0,
2276 							 /*timeout*/0,
2277 							 /*getcount_only*/0);
2278 
2279 
2280 				xpt_setup_ccb(&cgd.ccb_h,
2281 					      done_ccb->ccb_h.path,
2282 					      CAM_PRIORITY_NORMAL);
2283 				cgd.ccb_h.func_code = XPT_GDEV_TYPE;
2284 				xpt_action((union ccb *)&cgd);
2285 
2286 				if (((csio->ccb_h.flags & CAM_SENSE_PHYS) != 0)
2287 				 || ((csio->ccb_h.flags & CAM_SENSE_PTR) != 0)
2288 				 || ((status & CAM_AUTOSNS_VALID) == 0))
2289 					have_sense = FALSE;
2290 				else
2291 					have_sense = TRUE;
2292 
2293 				if (have_sense) {
2294 					sense = &csio->sense_data;
2295 					scsi_extract_sense_len(sense,
2296 					    csio->sense_len - csio->sense_resid,
2297 					    &error_code, &sense_key, &asc,
2298 					    &ascq, /*show_errors*/ 1);
2299 				}
2300 				/*
2301 				 * If we tried READ CAPACITY(16) and failed,
2302 				 * fallback to READ CAPACITY(10).
2303 				 */
2304 				if ((softc->state == DA_STATE_PROBE2) &&
2305 				    (softc->flags & DA_FLAG_CAN_RC16) &&
2306 				    (((csio->ccb_h.status & CAM_STATUS_MASK) ==
2307 					CAM_REQ_INVALID) ||
2308 				     ((have_sense) &&
2309 				      (error_code == SSD_CURRENT_ERROR) &&
2310 				      (sense_key == SSD_KEY_ILLEGAL_REQUEST)))) {
2311 					softc->flags &= ~DA_FLAG_CAN_RC16;
2312 					softc->state = DA_STATE_PROBE;
2313 					free(rdcap, M_SCSIDA);
2314 					xpt_release_ccb(done_ccb);
2315 					xpt_schedule(periph, priority);
2316 					return;
2317 				} else
2318 				/*
2319 				 * Attach to anything that claims to be a
2320 				 * direct access or optical disk device,
2321 				 * as long as it doesn't return a "Logical
2322 				 * unit not supported" (0x25) error.
2323 				 */
2324 				if ((have_sense) && (asc != 0x25)
2325 				 && (error_code == SSD_CURRENT_ERROR)) {
2326 					const char *sense_key_desc;
2327 					const char *asc_desc;
2328 
2329 					scsi_sense_desc(sense_key, asc, ascq,
2330 							&cgd.inq_data,
2331 							&sense_key_desc,
2332 							&asc_desc);
2333 					snprintf(announce_buf,
2334 					    sizeof(announce_buf),
2335 						"Attempt to query device "
2336 						"size failed: %s, %s",
2337 						sense_key_desc,
2338 						asc_desc);
2339 				} else {
2340 					if (have_sense)
2341 						scsi_sense_print(
2342 							&done_ccb->csio);
2343 					else {
2344 						xpt_print(periph->path,
2345 						    "got CAM status %#x\n",
2346 						    done_ccb->ccb_h.status);
2347 					}
2348 
2349 					xpt_print(periph->path, "fatal error, "
2350 					    "failed to attach to device\n");
2351 
2352 					/*
2353 					 * Free up resources.
2354 					 */
2355 					cam_periph_invalidate(periph);
2356 				}
2357 			}
2358 		}
2359 		free(csio->data_ptr, M_SCSIDA);
2360 		if (announce_buf[0] != '\0') {
2361 			/*
2362 			 * Create our sysctl variables, now that we know
2363 			 * we have successfully attached.
2364 			 */
2365 			/* increase the refcount */
2366 			if (cam_periph_acquire(periph) == CAM_REQ_CMP) {
2367 				taskqueue_enqueue(taskqueue_thread,
2368 						  &softc->sysctl_task);
2369 				xpt_announce_periph(periph, announce_buf);
2370 			} else {
2371 				xpt_print(periph->path, "fatal error, "
2372 				    "could not acquire reference count\n");
2373 			}
2374 
2375 		}
2376 		softc->state = DA_STATE_NORMAL;
2377 		/*
2378 		 * Since our peripheral may be invalidated by an error
2379 		 * above or an external event, we must release our CCB
2380 		 * before releasing the probe lock on the peripheral.
2381 		 * The peripheral will only go away once the last lock
2382 		 * is removed, and we need it around for the CCB release
2383 		 * operation.
2384 		 */
2385 		xpt_release_ccb(done_ccb);
2386 		cam_periph_unhold(periph);
2387 		return;
2388 	}
2389 	case DA_CCB_WAITING:
2390 	{
2391 		/* Caller will release the CCB */
2392 		wakeup(&done_ccb->ccb_h.cbfcnp);
2393 		return;
2394 	}
2395 	case DA_CCB_DUMP:
2396 		/* No-op.  We're polling */
2397 		return;
2398 	default:
2399 		break;
2400 	}
2401 	xpt_release_ccb(done_ccb);
2402 }
2403 
2404 static int
2405 daerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
2406 {
2407 	struct da_softc	  *softc;
2408 	struct cam_periph *periph;
2409 	int error;
2410 
2411 	periph = xpt_path_periph(ccb->ccb_h.path);
2412 	softc = (struct da_softc *)periph->softc;
2413 
2414  	/*
2415 	 * Automatically detect devices that do not support
2416  	 * READ(6)/WRITE(6) and upgrade to using 10 byte cdbs.
2417  	 */
2418 	error = 0;
2419 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INVALID) {
2420 		error = cmd6workaround(ccb);
2421 	} else if (((ccb->ccb_h.status & CAM_STATUS_MASK) ==
2422 		   CAM_SCSI_STATUS_ERROR)
2423 	 && (ccb->ccb_h.status & CAM_AUTOSNS_VALID)
2424 	 && (ccb->csio.scsi_status == SCSI_STATUS_CHECK_COND)
2425 	 && ((ccb->ccb_h.flags & CAM_SENSE_PHYS) == 0)
2426 	 && ((ccb->ccb_h.flags & CAM_SENSE_PTR) == 0)) {
2427 		int sense_key, error_code, asc, ascq;
2428 
2429  		scsi_extract_sense(&ccb->csio.sense_data,
2430 				   &error_code, &sense_key, &asc, &ascq);
2431 		if (sense_key == SSD_KEY_ILLEGAL_REQUEST)
2432  			error = cmd6workaround(ccb);
2433 	}
2434 	if (error == ERESTART)
2435 		return (ERESTART);
2436 
2437 	/*
2438 	 * XXX
2439 	 * Until we have a better way of doing pack validation,
2440 	 * don't treat UAs as errors.
2441 	 */
2442 	sense_flags |= SF_RETRY_UA;
2443 	return(cam_periph_error(ccb, cam_flags, sense_flags,
2444 				&softc->saved_ccb));
2445 }
2446 
2447 static void
2448 daprevent(struct cam_periph *periph, int action)
2449 {
2450 	struct	da_softc *softc;
2451 	union	ccb *ccb;
2452 	int	error;
2453 
2454 	softc = (struct da_softc *)periph->softc;
2455 
2456 	if (((action == PR_ALLOW)
2457 	  && (softc->flags & DA_FLAG_PACK_LOCKED) == 0)
2458 	 || ((action == PR_PREVENT)
2459 	  && (softc->flags & DA_FLAG_PACK_LOCKED) != 0)) {
2460 		return;
2461 	}
2462 
2463 	ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
2464 
2465 	scsi_prevent(&ccb->csio,
2466 		     /*retries*/1,
2467 		     /*cbcfp*/dadone,
2468 		     MSG_SIMPLE_Q_TAG,
2469 		     action,
2470 		     SSD_FULL_SIZE,
2471 		     5000);
2472 
2473 	error = cam_periph_runccb(ccb, /*error_routine*/NULL, CAM_RETRY_SELTO,
2474 				  SF_RETRY_UA, softc->disk->d_devstat);
2475 
2476 	if (error == 0) {
2477 		if (action == PR_ALLOW)
2478 			softc->flags &= ~DA_FLAG_PACK_LOCKED;
2479 		else
2480 			softc->flags |= DA_FLAG_PACK_LOCKED;
2481 	}
2482 
2483 	xpt_release_ccb(ccb);
2484 }
2485 
2486 static int
2487 dagetcapacity(struct cam_periph *periph)
2488 {
2489 	struct da_softc *softc;
2490 	union ccb *ccb;
2491 	struct scsi_read_capacity_data *rcap;
2492 	struct scsi_read_capacity_data_long *rcaplong;
2493 	uint32_t block_len;
2494 	uint64_t maxsector;
2495 	int error, rc16failed;
2496 	u_int32_t sense_flags;
2497 	u_int lbppbe;	/* Logical blocks per physical block exponent. */
2498 	u_int lalba;	/* Lowest aligned LBA. */
2499 
2500 	softc = (struct da_softc *)periph->softc;
2501 	block_len = 0;
2502 	maxsector = 0;
2503 	lbppbe = 0;
2504 	lalba = 0;
2505 	error = 0;
2506 	rc16failed = 0;
2507 	sense_flags = SF_RETRY_UA;
2508 	if (softc->flags & DA_FLAG_PACK_REMOVABLE)
2509 		sense_flags |= SF_NO_PRINT;
2510 
2511 	/* Do a read capacity */
2512 	rcap = (struct scsi_read_capacity_data *)malloc(sizeof(*rcaplong),
2513 							M_SCSIDA,
2514 							M_NOWAIT | M_ZERO);
2515 	if (rcap == NULL)
2516 		return (ENOMEM);
2517 	rcaplong = (struct scsi_read_capacity_data_long *)rcap;
2518 
2519 	ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
2520 
2521 	/* Try READ CAPACITY(16) first if we think it should work. */
2522 	if (softc->flags & DA_FLAG_CAN_RC16) {
2523 		scsi_read_capacity_16(&ccb->csio,
2524 			      /*retries*/ 4,
2525 			      /*cbfcnp*/ dadone,
2526 			      /*tag_action*/ MSG_SIMPLE_Q_TAG,
2527 			      /*lba*/ 0,
2528 			      /*reladr*/ 0,
2529 			      /*pmi*/ 0,
2530 			      rcaplong,
2531 			      /*sense_len*/ SSD_FULL_SIZE,
2532 			      /*timeout*/ 60000);
2533 		ccb->ccb_h.ccb_bp = NULL;
2534 
2535 		error = cam_periph_runccb(ccb, daerror,
2536 				  /*cam_flags*/CAM_RETRY_SELTO,
2537 				  sense_flags,
2538 				  softc->disk->d_devstat);
2539 		if (error == 0)
2540 			goto rc16ok;
2541 
2542 		/* If we got ILLEGAL REQUEST, do not prefer RC16 any more. */
2543 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
2544 		     CAM_REQ_INVALID) {
2545 			softc->flags &= ~DA_FLAG_CAN_RC16;
2546 		} else if (((ccb->ccb_h.status & CAM_STATUS_MASK) ==
2547 		     CAM_SCSI_STATUS_ERROR) &&
2548 		    (ccb->csio.scsi_status == SCSI_STATUS_CHECK_COND) &&
2549 		    (ccb->ccb_h.status & CAM_AUTOSNS_VALID) &&
2550 		    ((ccb->ccb_h.flags & CAM_SENSE_PHYS) == 0) &&
2551 		    ((ccb->ccb_h.flags & CAM_SENSE_PTR) == 0)) {
2552 			int sense_key, error_code, asc, ascq;
2553 
2554 			scsi_extract_sense(&ccb->csio.sense_data,
2555 				   &error_code, &sense_key, &asc, &ascq);
2556 			if (sense_key == SSD_KEY_ILLEGAL_REQUEST)
2557 				softc->flags &= ~DA_FLAG_CAN_RC16;
2558 		}
2559 		rc16failed = 1;
2560 	}
2561 
2562 	/* Do READ CAPACITY(10). */
2563 	scsi_read_capacity(&ccb->csio,
2564 			   /*retries*/4,
2565 			   /*cbfncp*/dadone,
2566 			   MSG_SIMPLE_Q_TAG,
2567 			   rcap,
2568 			   SSD_FULL_SIZE,
2569 			   /*timeout*/60000);
2570 	ccb->ccb_h.ccb_bp = NULL;
2571 
2572 	error = cam_periph_runccb(ccb, daerror,
2573 				  /*cam_flags*/CAM_RETRY_SELTO,
2574 				  sense_flags,
2575 				  softc->disk->d_devstat);
2576 	if (error == 0) {
2577 		block_len = scsi_4btoul(rcap->length);
2578 		maxsector = scsi_4btoul(rcap->addr);
2579 
2580 		if (maxsector != 0xffffffff || rc16failed)
2581 			goto done;
2582 	} else
2583 		goto done;
2584 
2585 	/* If READ CAPACITY(10) returned overflow, use READ CAPACITY(16) */
2586 	scsi_read_capacity_16(&ccb->csio,
2587 			      /*retries*/ 4,
2588 			      /*cbfcnp*/ dadone,
2589 			      /*tag_action*/ MSG_SIMPLE_Q_TAG,
2590 			      /*lba*/ 0,
2591 			      /*reladr*/ 0,
2592 			      /*pmi*/ 0,
2593 			      rcaplong,
2594 			      /*sense_len*/ SSD_FULL_SIZE,
2595 			      /*timeout*/ 60000);
2596 	ccb->ccb_h.ccb_bp = NULL;
2597 
2598 	error = cam_periph_runccb(ccb, daerror,
2599 				  /*cam_flags*/CAM_RETRY_SELTO,
2600 				  sense_flags,
2601 				  softc->disk->d_devstat);
2602 	if (error == 0) {
2603 rc16ok:
2604 		block_len = scsi_4btoul(rcaplong->length);
2605 		maxsector = scsi_8btou64(rcaplong->addr);
2606 		lbppbe = rcaplong->prot_lbppbe & SRC16_LBPPBE;
2607 		lalba = scsi_2btoul(rcaplong->lalba_lbp);
2608 	}
2609 
2610 done:
2611 
2612 	if (error == 0) {
2613 		if (block_len >= MAXPHYS || block_len == 0) {
2614 			xpt_print(periph->path,
2615 			    "unsupportable block size %ju\n",
2616 			    (uintmax_t) block_len);
2617 			error = EINVAL;
2618 		} else {
2619 			dasetgeom(periph, block_len, maxsector,
2620 			    lbppbe, lalba & SRC16_LALBA);
2621 			if ((lalba & SRC16_LBPME) &&
2622 			    softc->delete_method == DA_DELETE_NONE)
2623 				softc->delete_method = DA_DELETE_UNMAP;
2624 		}
2625 	}
2626 
2627 	xpt_release_ccb(ccb);
2628 
2629 	free(rcap, M_SCSIDA);
2630 
2631 	return (error);
2632 }
2633 
2634 static void
2635 dasetgeom(struct cam_periph *periph, uint32_t block_len, uint64_t maxsector,
2636     u_int lbppbe, u_int lalba)
2637 {
2638 	struct ccb_calc_geometry ccg;
2639 	struct da_softc *softc;
2640 	struct disk_params *dp;
2641 
2642 	softc = (struct da_softc *)periph->softc;
2643 
2644 	dp = &softc->params;
2645 	dp->secsize = block_len;
2646 	dp->sectors = maxsector + 1;
2647 	if (lbppbe > 0) {
2648 		dp->stripesize = block_len << lbppbe;
2649 		dp->stripeoffset = (dp->stripesize - block_len * lalba) %
2650 		    dp->stripesize;
2651 	} else if (softc->quirks & DA_Q_4K) {
2652 		dp->stripesize = 4096;
2653 		dp->stripeoffset = 0;
2654 	} else {
2655 		dp->stripesize = 0;
2656 		dp->stripeoffset = 0;
2657 	}
2658 	/*
2659 	 * Have the controller provide us with a geometry
2660 	 * for this disk.  The only time the geometry
2661 	 * matters is when we boot and the controller
2662 	 * is the only one knowledgeable enough to come
2663 	 * up with something that will make this a bootable
2664 	 * device.
2665 	 */
2666 	xpt_setup_ccb(&ccg.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
2667 	ccg.ccb_h.func_code = XPT_CALC_GEOMETRY;
2668 	ccg.block_size = dp->secsize;
2669 	ccg.volume_size = dp->sectors;
2670 	ccg.heads = 0;
2671 	ccg.secs_per_track = 0;
2672 	ccg.cylinders = 0;
2673 	xpt_action((union ccb*)&ccg);
2674 	if ((ccg.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2675 		/*
2676 		 * We don't know what went wrong here- but just pick
2677 		 * a geometry so we don't have nasty things like divide
2678 		 * by zero.
2679 		 */
2680 		dp->heads = 255;
2681 		dp->secs_per_track = 255;
2682 		dp->cylinders = dp->sectors / (255 * 255);
2683 		if (dp->cylinders == 0) {
2684 			dp->cylinders = 1;
2685 		}
2686 	} else {
2687 		dp->heads = ccg.heads;
2688 		dp->secs_per_track = ccg.secs_per_track;
2689 		dp->cylinders = ccg.cylinders;
2690 	}
2691 }
2692 
2693 static void
2694 dasendorderedtag(void *arg)
2695 {
2696 	struct da_softc *softc = arg;
2697 
2698 	if (da_send_ordered) {
2699 		if ((softc->ordered_tag_count == 0)
2700 		 && ((softc->flags & DA_FLAG_WENT_IDLE) == 0)) {
2701 			softc->flags |= DA_FLAG_NEED_OTAG;
2702 		}
2703 		if (softc->outstanding_cmds > 0)
2704 			softc->flags &= ~DA_FLAG_WENT_IDLE;
2705 
2706 		softc->ordered_tag_count = 0;
2707 	}
2708 	/* Queue us up again */
2709 	callout_reset(&softc->sendordered_c,
2710 	    (DA_DEFAULT_TIMEOUT * hz) / DA_ORDEREDTAG_INTERVAL,
2711 	    dasendorderedtag, softc);
2712 }
2713 
2714 /*
2715  * Step through all DA peripheral drivers, and if the device is still open,
2716  * sync the disk cache to physical media.
2717  */
2718 static void
2719 dashutdown(void * arg, int howto)
2720 {
2721 	struct cam_periph *periph;
2722 	struct da_softc *softc;
2723 
2724 	TAILQ_FOREACH(periph, &dadriver.units, unit_links) {
2725 		union ccb ccb;
2726 
2727 		cam_periph_lock(periph);
2728 		softc = (struct da_softc *)periph->softc;
2729 
2730 		/*
2731 		 * We only sync the cache if the drive is still open, and
2732 		 * if the drive is capable of it..
2733 		 */
2734 		if (((softc->flags & DA_FLAG_OPEN) == 0)
2735 		 || (softc->quirks & DA_Q_NO_SYNC_CACHE)) {
2736 			cam_periph_unlock(periph);
2737 			continue;
2738 		}
2739 
2740 		xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
2741 
2742 		ccb.ccb_h.ccb_state = DA_CCB_DUMP;
2743 		scsi_synchronize_cache(&ccb.csio,
2744 				       /*retries*/1,
2745 				       /*cbfcnp*/dadone,
2746 				       MSG_SIMPLE_Q_TAG,
2747 				       /*begin_lba*/0, /* whole disk */
2748 				       /*lb_count*/0,
2749 				       SSD_FULL_SIZE,
2750 				       60 * 60 * 1000);
2751 
2752 		xpt_polled_action(&ccb);
2753 
2754 		if ((ccb.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2755 			if (((ccb.ccb_h.status & CAM_STATUS_MASK) ==
2756 			     CAM_SCSI_STATUS_ERROR)
2757 			 && (ccb.csio.scsi_status == SCSI_STATUS_CHECK_COND)){
2758 				int error_code, sense_key, asc, ascq;
2759 
2760 				scsi_extract_sense(&ccb.csio.sense_data,
2761 						   &error_code, &sense_key,
2762 						   &asc, &ascq);
2763 
2764 				if (sense_key != SSD_KEY_ILLEGAL_REQUEST)
2765 					scsi_sense_print(&ccb.csio);
2766 			} else {
2767 				xpt_print(periph->path, "Synchronize "
2768 				    "cache failed, status == 0x%x, scsi status "
2769 				    "== 0x%x\n", ccb.ccb_h.status,
2770 				    ccb.csio.scsi_status);
2771 			}
2772 		}
2773 
2774 		if ((ccb.ccb_h.status & CAM_DEV_QFRZN) != 0)
2775 			cam_release_devq(ccb.ccb_h.path,
2776 					 /*relsim_flags*/0,
2777 					 /*reduction*/0,
2778 					 /*timeout*/0,
2779 					 /*getcount_only*/0);
2780 		cam_periph_unlock(periph);
2781 	}
2782 }
2783 
2784 #else /* !_KERNEL */
2785 
2786 /*
2787  * XXX This is only left out of the kernel build to silence warnings.  If,
2788  * for some reason this function is used in the kernel, the ifdefs should
2789  * be moved so it is included both in the kernel and userland.
2790  */
2791 void
2792 scsi_format_unit(struct ccb_scsiio *csio, u_int32_t retries,
2793 		 void (*cbfcnp)(struct cam_periph *, union ccb *),
2794 		 u_int8_t tag_action, u_int8_t byte2, u_int16_t ileave,
2795 		 u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
2796 		 u_int32_t timeout)
2797 {
2798 	struct scsi_format_unit *scsi_cmd;
2799 
2800 	scsi_cmd = (struct scsi_format_unit *)&csio->cdb_io.cdb_bytes;
2801 	scsi_cmd->opcode = FORMAT_UNIT;
2802 	scsi_cmd->byte2 = byte2;
2803 	scsi_ulto2b(ileave, scsi_cmd->interleave);
2804 
2805 	cam_fill_csio(csio,
2806 		      retries,
2807 		      cbfcnp,
2808 		      /*flags*/ (dxfer_len > 0) ? CAM_DIR_OUT : CAM_DIR_NONE,
2809 		      tag_action,
2810 		      data_ptr,
2811 		      dxfer_len,
2812 		      sense_len,
2813 		      sizeof(*scsi_cmd),
2814 		      timeout);
2815 }
2816 
2817 #endif /* _KERNEL */
2818