scsi_da.c revision 271530
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: stable/10/sys/cam/scsi/scsi_da.c 271530 2014-09-13 17:13:04Z mav $");
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 <sys/endian.h>
48#include <sys/proc.h>
49#include <geom/geom.h>
50#include <geom/geom_disk.h>
51#endif /* _KERNEL */
52
53#ifndef _KERNEL
54#include <stdio.h>
55#include <string.h>
56#endif /* _KERNEL */
57
58#include <cam/cam.h>
59#include <cam/cam_ccb.h>
60#include <cam/cam_periph.h>
61#include <cam/cam_xpt_periph.h>
62#include <cam/cam_sim.h>
63
64#include <cam/scsi/scsi_message.h>
65
66#ifndef _KERNEL
67#include <cam/scsi/scsi_da.h>
68#endif /* !_KERNEL */
69
70#ifdef _KERNEL
71typedef enum {
72	DA_STATE_PROBE_RC,
73	DA_STATE_PROBE_RC16,
74	DA_STATE_PROBE_LBP,
75	DA_STATE_PROBE_BLK_LIMITS,
76	DA_STATE_PROBE_BDC,
77	DA_STATE_PROBE_ATA,
78	DA_STATE_NORMAL
79} da_state;
80
81typedef enum {
82	DA_FLAG_PACK_INVALID	= 0x001,
83	DA_FLAG_NEW_PACK	= 0x002,
84	DA_FLAG_PACK_LOCKED	= 0x004,
85	DA_FLAG_PACK_REMOVABLE	= 0x008,
86	DA_FLAG_NEED_OTAG	= 0x020,
87	DA_FLAG_WAS_OTAG	= 0x040,
88	DA_FLAG_RETRY_UA	= 0x080,
89	DA_FLAG_OPEN		= 0x100,
90	DA_FLAG_SCTX_INIT	= 0x200,
91	DA_FLAG_CAN_RC16	= 0x400,
92	DA_FLAG_PROBED		= 0x800,
93	DA_FLAG_DIRTY		= 0x1000,
94	DA_FLAG_ANNOUNCED	= 0x2000
95} da_flags;
96
97typedef enum {
98	DA_Q_NONE		= 0x00,
99	DA_Q_NO_SYNC_CACHE	= 0x01,
100	DA_Q_NO_6_BYTE		= 0x02,
101	DA_Q_NO_PREVENT		= 0x04,
102	DA_Q_4K			= 0x08,
103	DA_Q_NO_RC16		= 0x10,
104	DA_Q_NO_UNMAP		= 0x20
105} da_quirks;
106
107#define DA_Q_BIT_STRING		\
108	"\020"			\
109	"\001NO_SYNC_CACHE"	\
110	"\002NO_6_BYTE"		\
111	"\003NO_PREVENT"	\
112	"\0044K"		\
113	"\005NO_RC16"
114
115typedef enum {
116	DA_CCB_PROBE_RC		= 0x01,
117	DA_CCB_PROBE_RC16	= 0x02,
118	DA_CCB_PROBE_LBP	= 0x03,
119	DA_CCB_PROBE_BLK_LIMITS	= 0x04,
120	DA_CCB_PROBE_BDC	= 0x05,
121	DA_CCB_PROBE_ATA	= 0x06,
122	DA_CCB_BUFFER_IO	= 0x07,
123	DA_CCB_DUMP		= 0x0A,
124	DA_CCB_DELETE		= 0x0B,
125 	DA_CCB_TUR		= 0x0C,
126	DA_CCB_TYPE_MASK	= 0x0F,
127	DA_CCB_RETRY_UA		= 0x10
128} da_ccb_state;
129
130/*
131 * Order here is important for method choice
132 *
133 * We prefer ATA_TRIM as tests run against a Sandforce 2281 SSD attached to
134 * LSI 2008 (mps) controller (FW: v12, Drv: v14) resulted 20% quicker deletes
135 * using ATA_TRIM than the corresponding UNMAP results for a real world mysql
136 * import taking 5mins.
137 *
138 */
139typedef enum {
140	DA_DELETE_NONE,
141	DA_DELETE_DISABLE,
142	DA_DELETE_ATA_TRIM,
143	DA_DELETE_UNMAP,
144	DA_DELETE_WS16,
145	DA_DELETE_WS10,
146	DA_DELETE_ZERO,
147	DA_DELETE_MIN = DA_DELETE_ATA_TRIM,
148	DA_DELETE_MAX = DA_DELETE_ZERO
149} da_delete_methods;
150
151typedef void da_delete_func_t (struct cam_periph *periph, union ccb *ccb,
152			      struct bio *bp);
153static da_delete_func_t da_delete_trim;
154static da_delete_func_t da_delete_unmap;
155static da_delete_func_t da_delete_ws;
156
157static const void * da_delete_functions[] = {
158	NULL,
159	NULL,
160	da_delete_trim,
161	da_delete_unmap,
162	da_delete_ws,
163	da_delete_ws,
164	da_delete_ws
165};
166
167static const char *da_delete_method_names[] =
168    { "NONE", "DISABLE", "ATA_TRIM", "UNMAP", "WS16", "WS10", "ZERO" };
169static const char *da_delete_method_desc[] =
170    { "NONE", "DISABLED", "ATA TRIM", "UNMAP", "WRITE SAME(16) with UNMAP",
171      "WRITE SAME(10) with UNMAP", "ZERO" };
172
173/* Offsets into our private area for storing information */
174#define ccb_state	ppriv_field0
175#define ccb_bp		ppriv_ptr1
176
177struct disk_params {
178	u_int8_t  heads;
179	u_int32_t cylinders;
180	u_int8_t  secs_per_track;
181	u_int32_t secsize;	/* Number of bytes/sector */
182	u_int64_t sectors;	/* total number sectors */
183	u_int     stripesize;
184	u_int     stripeoffset;
185};
186
187#define UNMAP_RANGE_MAX		0xffffffff
188#define UNMAP_HEAD_SIZE		8
189#define UNMAP_RANGE_SIZE	16
190#define UNMAP_MAX_RANGES	2048 /* Protocol Max is 4095 */
191#define UNMAP_BUF_SIZE		((UNMAP_MAX_RANGES * UNMAP_RANGE_SIZE) + \
192				UNMAP_HEAD_SIZE)
193
194#define WS10_MAX_BLKS		0xffff
195#define WS16_MAX_BLKS		0xffffffff
196#define ATA_TRIM_MAX_RANGES	((UNMAP_BUF_SIZE / \
197	(ATA_DSM_RANGE_SIZE * ATA_DSM_BLK_SIZE)) * ATA_DSM_BLK_SIZE)
198
199struct da_softc {
200	struct	 bio_queue_head bio_queue;
201	struct	 bio_queue_head delete_queue;
202	struct	 bio_queue_head delete_run_queue;
203	LIST_HEAD(, ccb_hdr) pending_ccbs;
204	int	 tur;			/* TEST UNIT READY should be sent */
205	int	 refcount;		/* Active xpt_action() calls */
206	da_state state;
207	da_flags flags;
208	da_quirks quirks;
209	int	 sort_io_queue;
210	int	 minimum_cmd_size;
211	int	 error_inject;
212	int	 trim_max_ranges;
213	int	 delete_running;
214	int	 delete_available;	/* Delete methods possibly available */
215	u_int	 maxio;
216	uint32_t		unmap_max_ranges;
217	uint32_t		unmap_max_lba; /* Max LBAs in UNMAP req */
218	uint64_t		ws_max_blks;
219	da_delete_methods	delete_method;
220	da_delete_func_t	*delete_func;
221	struct	 disk_params params;
222	struct	 disk *disk;
223	union	 ccb saved_ccb;
224	struct task		sysctl_task;
225	struct sysctl_ctx_list	sysctl_ctx;
226	struct sysctl_oid	*sysctl_tree;
227	struct callout		sendordered_c;
228	uint64_t wwpn;
229	uint8_t	 unmap_buf[UNMAP_BUF_SIZE];
230	struct scsi_read_capacity_data_long rcaplong;
231	struct callout		mediapoll_c;
232};
233
234#define dadeleteflag(softc, delete_method, enable)			\
235	if (enable) {							\
236		softc->delete_available |= (1 << delete_method);	\
237	} else {							\
238		softc->delete_available &= ~(1 << delete_method);	\
239	}
240
241struct da_quirk_entry {
242	struct scsi_inquiry_pattern inq_pat;
243	da_quirks quirks;
244};
245
246static const char quantum[] = "QUANTUM";
247static const char microp[] = "MICROP";
248
249static struct da_quirk_entry da_quirk_table[] =
250{
251	/* SPI, FC devices */
252	{
253		/*
254		 * Fujitsu M2513A MO drives.
255		 * Tested devices: M2513A2 firmware versions 1200 & 1300.
256		 * (dip switch selects whether T_DIRECT or T_OPTICAL device)
257		 * Reported by: W.Scholten <whs@xs4all.nl>
258		 */
259		{T_DIRECT, SIP_MEDIA_REMOVABLE, "FUJITSU", "M2513A", "*"},
260		/*quirks*/ DA_Q_NO_SYNC_CACHE
261	},
262	{
263		/* See above. */
264		{T_OPTICAL, SIP_MEDIA_REMOVABLE, "FUJITSU", "M2513A", "*"},
265		/*quirks*/ DA_Q_NO_SYNC_CACHE
266	},
267	{
268		/*
269		 * This particular Fujitsu drive doesn't like the
270		 * synchronize cache command.
271		 * Reported by: Tom Jackson <toj@gorilla.net>
272		 */
273		{T_DIRECT, SIP_MEDIA_FIXED, "FUJITSU", "M2954*", "*"},
274		/*quirks*/ DA_Q_NO_SYNC_CACHE
275	},
276	{
277		/*
278		 * This drive doesn't like the synchronize cache command
279		 * either.  Reported by: Matthew Jacob <mjacob@feral.com>
280		 * in NetBSD PR kern/6027, August 24, 1998.
281		 */
282		{T_DIRECT, SIP_MEDIA_FIXED, microp, "2217*", "*"},
283		/*quirks*/ DA_Q_NO_SYNC_CACHE
284	},
285	{
286		/*
287		 * This drive doesn't like the synchronize cache command
288		 * either.  Reported by: Hellmuth Michaelis (hm@kts.org)
289		 * (PR 8882).
290		 */
291		{T_DIRECT, SIP_MEDIA_FIXED, microp, "2112*", "*"},
292		/*quirks*/ DA_Q_NO_SYNC_CACHE
293	},
294	{
295		/*
296		 * Doesn't like the synchronize cache command.
297		 * Reported by: Blaz Zupan <blaz@gold.amis.net>
298		 */
299		{T_DIRECT, SIP_MEDIA_FIXED, "NEC", "D3847*", "*"},
300		/*quirks*/ DA_Q_NO_SYNC_CACHE
301	},
302	{
303		/*
304		 * Doesn't like the synchronize cache command.
305		 * Reported by: Blaz Zupan <blaz@gold.amis.net>
306		 */
307		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "MAVERICK 540S", "*"},
308		/*quirks*/ DA_Q_NO_SYNC_CACHE
309	},
310	{
311		/*
312		 * Doesn't like the synchronize cache command.
313		 */
314		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "LPS525S", "*"},
315		/*quirks*/ DA_Q_NO_SYNC_CACHE
316	},
317	{
318		/*
319		 * Doesn't like the synchronize cache command.
320		 * Reported by: walter@pelissero.de
321		 */
322		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "LPS540S", "*"},
323		/*quirks*/ DA_Q_NO_SYNC_CACHE
324	},
325	{
326		/*
327		 * Doesn't work correctly with 6 byte reads/writes.
328		 * Returns illegal request, and points to byte 9 of the
329		 * 6-byte CDB.
330		 * Reported by:  Adam McDougall <bsdx@spawnet.com>
331		 */
332		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 4*", "*"},
333		/*quirks*/ DA_Q_NO_6_BYTE
334	},
335	{
336		/* See above. */
337		{T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 2*", "*"},
338		/*quirks*/ DA_Q_NO_6_BYTE
339	},
340	{
341		/*
342		 * Doesn't like the synchronize cache command.
343		 * Reported by: walter@pelissero.de
344		 */
345		{T_DIRECT, SIP_MEDIA_FIXED, "CONNER", "CP3500*", "*"},
346		/*quirks*/ DA_Q_NO_SYNC_CACHE
347	},
348	{
349		/*
350		 * The CISS RAID controllers do not support SYNC_CACHE
351		 */
352		{T_DIRECT, SIP_MEDIA_FIXED, "COMPAQ", "RAID*", "*"},
353		/*quirks*/ DA_Q_NO_SYNC_CACHE
354	},
355	{
356		/*
357		 * The STEC SSDs sometimes hang on UNMAP.
358		 */
359		{T_DIRECT, SIP_MEDIA_FIXED, "STEC", "*", "*"},
360		/*quirks*/ DA_Q_NO_UNMAP
361	},
362	/* USB mass storage devices supported by umass(4) */
363	{
364		/*
365		 * EXATELECOM (Sigmatel) i-Bead 100/105 USB Flash MP3 Player
366		 * PR: kern/51675
367		 */
368		{T_DIRECT, SIP_MEDIA_REMOVABLE, "EXATEL", "i-BEAD10*", "*"},
369		/*quirks*/ DA_Q_NO_SYNC_CACHE
370	},
371	{
372		/*
373		 * Power Quotient Int. (PQI) USB flash key
374		 * PR: kern/53067
375		 */
376		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "USB Flash Disk*",
377		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
378	},
379 	{
380 		/*
381 		 * Creative Nomad MUVO mp3 player (USB)
382 		 * PR: kern/53094
383 		 */
384 		{T_DIRECT, SIP_MEDIA_REMOVABLE, "CREATIVE", "NOMAD_MUVO", "*"},
385 		/*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
386 	},
387	{
388		/*
389		 * Jungsoft NEXDISK USB flash key
390		 * PR: kern/54737
391		 */
392		{T_DIRECT, SIP_MEDIA_REMOVABLE, "JUNGSOFT", "NEXDISK*", "*"},
393		/*quirks*/ DA_Q_NO_SYNC_CACHE
394	},
395	{
396		/*
397		 * FreeDik USB Mini Data Drive
398		 * PR: kern/54786
399		 */
400		{T_DIRECT, SIP_MEDIA_REMOVABLE, "FreeDik*", "Mini Data Drive",
401		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
402	},
403	{
404		/*
405		 * Sigmatel USB Flash MP3 Player
406		 * PR: kern/57046
407		 */
408		{T_DIRECT, SIP_MEDIA_REMOVABLE, "SigmaTel", "MSCN", "*"},
409		/*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
410	},
411	{
412		/*
413		 * Neuros USB Digital Audio Computer
414		 * PR: kern/63645
415		 */
416		{T_DIRECT, SIP_MEDIA_REMOVABLE, "NEUROS", "dig. audio comp.",
417		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
418	},
419	{
420		/*
421		 * SEAGRAND NP-900 MP3 Player
422		 * PR: kern/64563
423		 */
424		{T_DIRECT, SIP_MEDIA_REMOVABLE, "SEAGRAND", "NP-900*", "*"},
425		/*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
426	},
427	{
428		/*
429		 * iRiver iFP MP3 player (with UMS Firmware)
430		 * PR: kern/54881, i386/63941, kern/66124
431		 */
432		{T_DIRECT, SIP_MEDIA_REMOVABLE, "iRiver", "iFP*", "*"},
433		/*quirks*/ DA_Q_NO_SYNC_CACHE
434 	},
435	{
436		/*
437		 * Frontier Labs NEX IA+ Digital Audio Player, rev 1.10/0.01
438		 * PR: kern/70158
439		 */
440		{T_DIRECT, SIP_MEDIA_REMOVABLE, "FL" , "Nex*", "*"},
441		/*quirks*/ DA_Q_NO_SYNC_CACHE
442	},
443	{
444		/*
445		 * ZICPlay USB MP3 Player with FM
446		 * PR: kern/75057
447		 */
448		{T_DIRECT, SIP_MEDIA_REMOVABLE, "ACTIONS*" , "USB DISK*", "*"},
449		/*quirks*/ DA_Q_NO_SYNC_CACHE
450	},
451	{
452		/*
453		 * TEAC USB floppy mechanisms
454		 */
455		{T_DIRECT, SIP_MEDIA_REMOVABLE, "TEAC" , "FD-05*", "*"},
456		/*quirks*/ DA_Q_NO_SYNC_CACHE
457	},
458	{
459		/*
460		 * Kingston DataTraveler II+ USB Pen-Drive.
461		 * Reported by: Pawel Jakub Dawidek <pjd@FreeBSD.org>
462		 */
463		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston" , "DataTraveler II+",
464		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
465	},
466	{
467		/*
468		 * USB DISK Pro PMAP
469		 * Reported by: jhs
470		 * PR: usb/96381
471		 */
472		{T_DIRECT, SIP_MEDIA_REMOVABLE, " ", "USB DISK Pro", "PMAP"},
473		/*quirks*/ DA_Q_NO_SYNC_CACHE
474	},
475	{
476		/*
477		 * Motorola E398 Mobile Phone (TransFlash memory card).
478		 * Reported by: Wojciech A. Koszek <dunstan@FreeBSD.czest.pl>
479		 * PR: usb/89889
480		 */
481		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Motorola" , "Motorola Phone",
482		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
483	},
484	{
485		/*
486		 * Qware BeatZkey! Pro
487		 * PR: usb/79164
488		 */
489		{T_DIRECT, SIP_MEDIA_REMOVABLE, "GENERIC", "USB DISK DEVICE",
490		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
491	},
492	{
493		/*
494		 * Time DPA20B 1GB MP3 Player
495		 * PR: usb/81846
496		 */
497		{T_DIRECT, SIP_MEDIA_REMOVABLE, "USB2.0*", "(FS) FLASH DISK*",
498		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
499	},
500	{
501		/*
502		 * Samsung USB key 128Mb
503		 * PR: usb/90081
504		 */
505		{T_DIRECT, SIP_MEDIA_REMOVABLE, "USB-DISK", "FreeDik-FlashUsb",
506		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
507	},
508	{
509		/*
510		 * Kingston DataTraveler 2.0 USB Flash memory.
511		 * PR: usb/89196
512		 */
513		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston", "DataTraveler 2.0",
514		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
515	},
516	{
517		/*
518		 * Creative MUVO Slim mp3 player (USB)
519		 * PR: usb/86131
520		 */
521		{T_DIRECT, SIP_MEDIA_REMOVABLE, "CREATIVE", "MuVo Slim",
522		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
523		},
524	{
525		/*
526		 * United MP5512 Portable MP3 Player (2-in-1 USB DISK/MP3)
527		 * PR: usb/80487
528		 */
529		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "MUSIC DISK",
530		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
531	},
532	{
533		/*
534		 * SanDisk Micro Cruzer 128MB
535		 * PR: usb/75970
536		 */
537		{T_DIRECT, SIP_MEDIA_REMOVABLE, "SanDisk" , "Micro Cruzer",
538		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
539	},
540	{
541		/*
542		 * TOSHIBA TransMemory USB sticks
543		 * PR: kern/94660
544		 */
545		{T_DIRECT, SIP_MEDIA_REMOVABLE, "TOSHIBA", "TransMemory",
546		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
547	},
548	{
549		/*
550		 * PNY USB Flash keys
551		 * PR: usb/75578, usb/72344, usb/65436
552		 */
553		{T_DIRECT, SIP_MEDIA_REMOVABLE, "*" , "USB DISK*",
554		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
555	},
556	{
557		/*
558		 * Genesys 6-in-1 Card Reader
559		 * PR: usb/94647
560		 */
561		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "STORAGE DEVICE*",
562		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
563	},
564	{
565		/*
566		 * Rekam Digital CAMERA
567		 * PR: usb/98713
568		 */
569		{T_DIRECT, SIP_MEDIA_REMOVABLE, "CAMERA*", "4MP-9J6*",
570		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
571	},
572	{
573		/*
574		 * iRiver H10 MP3 player
575		 * PR: usb/102547
576		 */
577		{T_DIRECT, SIP_MEDIA_REMOVABLE, "iriver", "H10*",
578		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
579	},
580	{
581		/*
582		 * iRiver U10 MP3 player
583		 * PR: usb/92306
584		 */
585		{T_DIRECT, SIP_MEDIA_REMOVABLE, "iriver", "U10*",
586		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
587	},
588	{
589		/*
590		 * X-Micro Flash Disk
591		 * PR: usb/96901
592		 */
593		{T_DIRECT, SIP_MEDIA_REMOVABLE, "X-Micro", "Flash Disk",
594		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
595	},
596	{
597		/*
598		 * EasyMP3 EM732X USB 2.0 Flash MP3 Player
599		 * PR: usb/96546
600		 */
601		{T_DIRECT, SIP_MEDIA_REMOVABLE, "EM732X", "MP3 Player*",
602		"1.00"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
603	},
604	{
605		/*
606		 * Denver MP3 player
607		 * PR: usb/107101
608		 */
609		{T_DIRECT, SIP_MEDIA_REMOVABLE, "DENVER", "MP3 PLAYER",
610		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
611	},
612	{
613		/*
614		 * Philips USB Key Audio KEY013
615		 * PR: usb/68412
616		 */
617		{T_DIRECT, SIP_MEDIA_REMOVABLE, "PHILIPS", "Key*", "*"},
618		/*quirks*/ DA_Q_NO_SYNC_CACHE | DA_Q_NO_PREVENT
619	},
620	{
621		/*
622		 * JNC MP3 Player
623		 * PR: usb/94439
624		 */
625		{T_DIRECT, SIP_MEDIA_REMOVABLE, "JNC*" , "MP3 Player*",
626		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
627	},
628	{
629		/*
630		 * SAMSUNG MP0402H
631		 * PR: usb/108427
632		 */
633		{T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "MP0402H", "*"},
634		/*quirks*/ DA_Q_NO_SYNC_CACHE
635	},
636	{
637		/*
638		 * I/O Magic USB flash - Giga Bank
639		 * PR: usb/108810
640		 */
641		{T_DIRECT, SIP_MEDIA_FIXED, "GS-Magic", "stor*", "*"},
642		/*quirks*/ DA_Q_NO_SYNC_CACHE
643	},
644	{
645		/*
646		 * JoyFly 128mb USB Flash Drive
647		 * PR: 96133
648		 */
649		{T_DIRECT, SIP_MEDIA_REMOVABLE, "USB 2.0", "Flash Disk*",
650		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
651	},
652	{
653		/*
654		 * ChipsBnk usb stick
655		 * PR: 103702
656		 */
657		{T_DIRECT, SIP_MEDIA_REMOVABLE, "ChipsBnk", "USB*",
658		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
659	},
660	{
661		/*
662		 * Storcase (Kingston) InfoStation IFS FC2/SATA-R 201A
663		 * PR: 129858
664		 */
665		{T_DIRECT, SIP_MEDIA_FIXED, "IFS", "FC2/SATA-R*",
666		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
667	},
668	{
669		/*
670		 * Samsung YP-U3 mp3-player
671		 * PR: 125398
672		 */
673		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Samsung", "YP-U3",
674		 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
675	},
676	{
677		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Netac", "OnlyDisk*",
678		 "2000"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
679	},
680	{
681		/*
682		 * Sony Cyber-Shot DSC cameras
683		 * PR: usb/137035
684		 */
685		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Sony", "Sony DSC", "*"},
686		/*quirks*/ DA_Q_NO_SYNC_CACHE | DA_Q_NO_PREVENT
687	},
688	{
689		{T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston", "DataTraveler G3",
690		 "1.00"}, /*quirks*/ DA_Q_NO_PREVENT
691	},
692	{
693		/* At least several Transcent USB sticks lie on RC16. */
694		{T_DIRECT, SIP_MEDIA_REMOVABLE, "JetFlash", "Transcend*",
695		 "*"}, /*quirks*/ DA_Q_NO_RC16
696	},
697	/* ATA/SATA devices over SAS/USB/... */
698	{
699		/* Hitachi Advanced Format (4k) drives */
700		{ T_DIRECT, SIP_MEDIA_FIXED, "Hitachi", "H??????????E3*", "*" },
701		/*quirks*/DA_Q_4K
702	},
703	{
704		/* Samsung Advanced Format (4k) drives */
705		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SAMSUNG HD155UI*", "*" },
706		/*quirks*/DA_Q_4K
707	},
708	{
709		/* Samsung Advanced Format (4k) drives */
710		{ T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "HD155UI*", "*" },
711		/*quirks*/DA_Q_4K
712	},
713	{
714		/* Samsung Advanced Format (4k) drives */
715		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SAMSUNG HD204UI*", "*" },
716		/*quirks*/DA_Q_4K
717	},
718	{
719		/* Samsung Advanced Format (4k) drives */
720		{ T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "HD204UI*", "*" },
721		/*quirks*/DA_Q_4K
722	},
723	{
724		/* Seagate Barracuda Green Advanced Format (4k) drives */
725		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST????DL*", "*" },
726		/*quirks*/DA_Q_4K
727	},
728	{
729		/* Seagate Barracuda Green Advanced Format (4k) drives */
730		{ T_DIRECT, SIP_MEDIA_FIXED, "ST????DL", "*", "*" },
731		/*quirks*/DA_Q_4K
732	},
733	{
734		/* Seagate Barracuda Green Advanced Format (4k) drives */
735		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST???DM*", "*" },
736		/*quirks*/DA_Q_4K
737	},
738	{
739		/* Seagate Barracuda Green Advanced Format (4k) drives */
740		{ T_DIRECT, SIP_MEDIA_FIXED, "ST???DM*", "*", "*" },
741		/*quirks*/DA_Q_4K
742	},
743	{
744		/* Seagate Barracuda Green Advanced Format (4k) drives */
745		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST????DM*", "*" },
746		/*quirks*/DA_Q_4K
747	},
748	{
749		/* Seagate Barracuda Green Advanced Format (4k) drives */
750		{ T_DIRECT, SIP_MEDIA_FIXED, "ST????DM", "*", "*" },
751		/*quirks*/DA_Q_4K
752	},
753	{
754		/* Seagate Momentus Advanced Format (4k) drives */
755		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9500423AS*", "*" },
756		/*quirks*/DA_Q_4K
757	},
758	{
759		/* Seagate Momentus Advanced Format (4k) drives */
760		{ T_DIRECT, SIP_MEDIA_FIXED, "ST950042", "3AS*", "*" },
761		/*quirks*/DA_Q_4K
762	},
763	{
764		/* Seagate Momentus Advanced Format (4k) drives */
765		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9500424AS*", "*" },
766		/*quirks*/DA_Q_4K
767	},
768	{
769		/* Seagate Momentus Advanced Format (4k) drives */
770		{ T_DIRECT, SIP_MEDIA_FIXED, "ST950042", "4AS*", "*" },
771		/*quirks*/DA_Q_4K
772	},
773	{
774		/* Seagate Momentus Advanced Format (4k) drives */
775		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9640423AS*", "*" },
776		/*quirks*/DA_Q_4K
777	},
778	{
779		/* Seagate Momentus Advanced Format (4k) drives */
780		{ T_DIRECT, SIP_MEDIA_FIXED, "ST964042", "3AS*", "*" },
781		/*quirks*/DA_Q_4K
782	},
783	{
784		/* Seagate Momentus Advanced Format (4k) drives */
785		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9640424AS*", "*" },
786		/*quirks*/DA_Q_4K
787	},
788	{
789		/* Seagate Momentus Advanced Format (4k) drives */
790		{ T_DIRECT, SIP_MEDIA_FIXED, "ST964042", "4AS*", "*" },
791		/*quirks*/DA_Q_4K
792	},
793	{
794		/* Seagate Momentus Advanced Format (4k) drives */
795		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750420AS*", "*" },
796		/*quirks*/DA_Q_4K
797	},
798	{
799		/* Seagate Momentus Advanced Format (4k) drives */
800		{ T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "0AS*", "*" },
801		/*quirks*/DA_Q_4K
802	},
803	{
804		/* Seagate Momentus Advanced Format (4k) drives */
805		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750422AS*", "*" },
806		/*quirks*/DA_Q_4K
807	},
808	{
809		/* Seagate Momentus Advanced Format (4k) drives */
810		{ T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "2AS*", "*" },
811		/*quirks*/DA_Q_4K
812	},
813	{
814		/* Seagate Momentus Advanced Format (4k) drives */
815		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750423AS*", "*" },
816		/*quirks*/DA_Q_4K
817	},
818	{
819		/* Seagate Momentus Advanced Format (4k) drives */
820		{ T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "3AS*", "*" },
821		/*quirks*/DA_Q_4K
822	},
823	{
824		/* Seagate Momentus Thin Advanced Format (4k) drives */
825		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST???LT*", "*" },
826		/*quirks*/DA_Q_4K
827	},
828	{
829		/* Seagate Momentus Thin Advanced Format (4k) drives */
830		{ T_DIRECT, SIP_MEDIA_FIXED, "ST???LT*", "*", "*" },
831		/*quirks*/DA_Q_4K
832	},
833	{
834		/* WDC Caviar Green Advanced Format (4k) drives */
835		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD????RS*", "*" },
836		/*quirks*/DA_Q_4K
837	},
838	{
839		/* WDC Caviar Green Advanced Format (4k) drives */
840		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "??RS*", "*" },
841		/*quirks*/DA_Q_4K
842	},
843	{
844		/* WDC Caviar Green Advanced Format (4k) drives */
845		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD????RX*", "*" },
846		/*quirks*/DA_Q_4K
847	},
848	{
849		/* WDC Caviar Green Advanced Format (4k) drives */
850		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "??RX*", "*" },
851		/*quirks*/DA_Q_4K
852	},
853	{
854		/* WDC Caviar Green Advanced Format (4k) drives */
855		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD??????RS*", "*" },
856		/*quirks*/DA_Q_4K
857	},
858	{
859		/* WDC Caviar Green Advanced Format (4k) drives */
860		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "????RS*", "*" },
861		/*quirks*/DA_Q_4K
862	},
863	{
864		/* WDC Caviar Green Advanced Format (4k) drives */
865		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD??????RX*", "*" },
866		/*quirks*/DA_Q_4K
867	},
868	{
869		/* WDC Caviar Green Advanced Format (4k) drives */
870		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "????RX*", "*" },
871		/*quirks*/DA_Q_4K
872	},
873	{
874		/* WDC Scorpio Black Advanced Format (4k) drives */
875		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD???PKT*", "*" },
876		/*quirks*/DA_Q_4K
877	},
878	{
879		/* WDC Scorpio Black Advanced Format (4k) drives */
880		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "?PKT*", "*" },
881		/*quirks*/DA_Q_4K
882	},
883	{
884		/* WDC Scorpio Black Advanced Format (4k) drives */
885		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD?????PKT*", "*" },
886		/*quirks*/DA_Q_4K
887	},
888	{
889		/* WDC Scorpio Black Advanced Format (4k) drives */
890		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "???PKT*", "*" },
891		/*quirks*/DA_Q_4K
892	},
893	{
894		/* WDC Scorpio Blue Advanced Format (4k) drives */
895		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD???PVT*", "*" },
896		/*quirks*/DA_Q_4K
897	},
898	{
899		/* WDC Scorpio Blue Advanced Format (4k) drives */
900		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "?PVT*", "*" },
901		/*quirks*/DA_Q_4K
902	},
903	{
904		/* WDC Scorpio Blue Advanced Format (4k) drives */
905		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD?????PVT*", "*" },
906		/*quirks*/DA_Q_4K
907	},
908	{
909		/* WDC Scorpio Blue Advanced Format (4k) drives */
910		{ T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "???PVT*", "*" },
911		/*quirks*/DA_Q_4K
912	},
913	{
914		/*
915		 * Olympus FE-210 camera
916		 */
917		{T_DIRECT, SIP_MEDIA_REMOVABLE, "OLYMPUS", "FE210*",
918		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
919	},
920	{
921		/*
922		 * LG UP3S MP3 player
923		 */
924		{T_DIRECT, SIP_MEDIA_REMOVABLE, "LG", "UP3S",
925		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
926	},
927	{
928		/*
929		 * Laser MP3-2GA13 MP3 player
930		 */
931		{T_DIRECT, SIP_MEDIA_REMOVABLE, "USB 2.0", "(HS) Flash Disk",
932		"*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
933	},
934	{
935		/*
936		 * LaCie external 250GB Hard drive des by Porsche
937		 * Submitted by: Ben Stuyts <ben@altesco.nl>
938		 * PR: 121474
939		 */
940		{T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "HM250JI", "*"},
941		/*quirks*/ DA_Q_NO_SYNC_CACHE
942	},
943	/* SATA SSDs */
944	{
945		/*
946		 * Corsair Force 2 SSDs
947		 * 4k optimised & trim only works in 4k requests + 4k aligned
948		 */
949		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "Corsair CSSD-F*", "*" },
950		/*quirks*/DA_Q_4K
951	},
952	{
953		/*
954		 * Corsair Force 3 SSDs
955		 * 4k optimised & trim only works in 4k requests + 4k aligned
956		 */
957		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "Corsair Force 3*", "*" },
958		/*quirks*/DA_Q_4K
959	},
960        {
961		/*
962		 * Corsair Neutron GTX SSDs
963		 * 4k optimised & trim only works in 4k requests + 4k aligned
964		 */
965		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair Neutron GTX*", "*" },
966		/*quirks*/DA_Q_4K
967	},
968	{
969		/*
970		 * Corsair Force GT & GS SSDs
971		 * 4k optimised & trim only works in 4k requests + 4k aligned
972		 */
973		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "Corsair Force G*", "*" },
974		/*quirks*/DA_Q_4K
975	},
976	{
977		/*
978		 * Crucial M4 SSDs
979		 * 4k optimised & trim only works in 4k requests + 4k aligned
980		 */
981		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "M4-CT???M4SSD2*", "*" },
982		/*quirks*/DA_Q_4K
983	},
984	{
985		/*
986		 * Crucial RealSSD C300 SSDs
987		 * 4k optimised
988		 */
989		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "C300-CTFDDAC???MAG*",
990		"*" }, /*quirks*/DA_Q_4K
991	},
992	{
993		/*
994		 * Intel 320 Series SSDs
995		 * 4k optimised & trim only works in 4k requests + 4k aligned
996		 */
997		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "INTEL SSDSA2CW*", "*" },
998		/*quirks*/DA_Q_4K
999	},
1000	{
1001		/*
1002		 * Intel 330 Series SSDs
1003		 * 4k optimised & trim only works in 4k requests + 4k aligned
1004		 */
1005		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "INTEL SSDSC2CT*", "*" },
1006		/*quirks*/DA_Q_4K
1007	},
1008	{
1009		/*
1010		 * Intel 510 Series SSDs
1011		 * 4k optimised & trim only works in 4k requests + 4k aligned
1012		 */
1013		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "INTEL SSDSC2MH*", "*" },
1014		/*quirks*/DA_Q_4K
1015	},
1016	{
1017		/*
1018		 * Intel 520 Series SSDs
1019		 * 4k optimised & trim only works in 4k requests + 4k aligned
1020		 */
1021		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "INTEL SSDSC2BW*", "*" },
1022		/*quirks*/DA_Q_4K
1023	},
1024	{
1025		/*
1026		 * Intel X25-M Series SSDs
1027		 * 4k optimised & trim only works in 4k requests + 4k aligned
1028		 */
1029		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "INTEL SSDSA2M*", "*" },
1030		/*quirks*/DA_Q_4K
1031	},
1032	{
1033		/*
1034		 * Kingston E100 Series SSDs
1035		 * 4k optimised & trim only works in 4k requests + 4k aligned
1036		 */
1037		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "KINGSTON SE100S3*", "*" },
1038		/*quirks*/DA_Q_4K
1039	},
1040	{
1041		/*
1042		 * Kingston HyperX 3k SSDs
1043		 * 4k optimised & trim only works in 4k requests + 4k aligned
1044		 */
1045		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "KINGSTON SH103S3*", "*" },
1046		/*quirks*/DA_Q_4K
1047	},
1048	{
1049		/*
1050		 * Marvell SSDs (entry taken from OpenSolaris)
1051		 * 4k optimised & trim only works in 4k requests + 4k aligned
1052		 */
1053		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "MARVELL SD88SA02*", "*" },
1054		/*quirks*/DA_Q_4K
1055	},
1056	{
1057		/*
1058		 * OCZ Agility 2 SSDs
1059		 * 4k optimised & trim only works in 4k requests + 4k aligned
1060		 */
1061		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-AGILITY2*", "*" },
1062		/*quirks*/DA_Q_4K
1063	},
1064	{
1065		/*
1066		 * OCZ Agility 3 SSDs
1067		 * 4k optimised & trim only works in 4k requests + 4k aligned
1068		 */
1069		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "OCZ-AGILITY3*", "*" },
1070		/*quirks*/DA_Q_4K
1071	},
1072	{
1073		/*
1074		 * OCZ Deneva R Series SSDs
1075		 * 4k optimised & trim only works in 4k requests + 4k aligned
1076		 */
1077		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "DENRSTE251M45*", "*" },
1078		/*quirks*/DA_Q_4K
1079	},
1080	{
1081		/*
1082		 * OCZ Vertex 2 SSDs (inc pro series)
1083		 * 4k optimised & trim only works in 4k requests + 4k aligned
1084		 */
1085		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "OCZ?VERTEX2*", "*" },
1086		/*quirks*/DA_Q_4K
1087	},
1088	{
1089		/*
1090		 * OCZ Vertex 3 SSDs
1091		 * 4k optimised & trim only works in 4k requests + 4k aligned
1092		 */
1093		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "OCZ-VERTEX3*", "*" },
1094		/*quirks*/DA_Q_4K
1095	},
1096	{
1097		/*
1098		 * OCZ Vertex 4 SSDs
1099		 * 4k optimised & trim only works in 4k requests + 4k aligned
1100		 */
1101		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "OCZ-VERTEX4*", "*" },
1102		/*quirks*/DA_Q_4K
1103	},
1104	{
1105		/*
1106		 * Samsung 830 Series SSDs
1107		 * 4k optimised & trim only works in 4k requests + 4k aligned
1108		 */
1109		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SAMSUNG SSD 830 Series*", "*" },
1110		/*quirks*/DA_Q_4K
1111	},
1112	{
1113		/*
1114		 * Samsung 840 SSDs
1115		 * 4k optimised & trim only works in 4k requests + 4k aligned
1116		 */
1117		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "Samsung SSD 840*", "*" },
1118		/*quirks*/DA_Q_4K
1119	},
1120	{
1121		/*
1122		 * SuperTalent TeraDrive CT SSDs
1123		 * 4k optimised & trim only works in 4k requests + 4k aligned
1124		 */
1125		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "FTM??CT25H*", "*" },
1126		/*quirks*/DA_Q_4K
1127	},
1128	{
1129		/*
1130		 * XceedIOPS SATA SSDs
1131		 * 4k optimised
1132		 */
1133		{ T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SG9XCS2D*", "*" },
1134		/*quirks*/DA_Q_4K
1135	},
1136};
1137
1138static	disk_strategy_t	dastrategy;
1139static	dumper_t	dadump;
1140static	periph_init_t	dainit;
1141static	void		daasync(void *callback_arg, u_int32_t code,
1142				struct cam_path *path, void *arg);
1143static	void		dasysctlinit(void *context, int pending);
1144static	int		dacmdsizesysctl(SYSCTL_HANDLER_ARGS);
1145static	int		dadeletemethodsysctl(SYSCTL_HANDLER_ARGS);
1146static	int		dadeletemaxsysctl(SYSCTL_HANDLER_ARGS);
1147static	void		dadeletemethodset(struct da_softc *softc,
1148					  da_delete_methods delete_method);
1149static	off_t		dadeletemaxsize(struct da_softc *softc,
1150					da_delete_methods delete_method);
1151static	void		dadeletemethodchoose(struct da_softc *softc,
1152					     da_delete_methods default_method);
1153static	void		daprobedone(struct cam_periph *periph, union ccb *ccb);
1154
1155static	periph_ctor_t	daregister;
1156static	periph_dtor_t	dacleanup;
1157static	periph_start_t	dastart;
1158static	periph_oninv_t	daoninvalidate;
1159static	void		dadone(struct cam_periph *periph,
1160			       union ccb *done_ccb);
1161static  int		daerror(union ccb *ccb, u_int32_t cam_flags,
1162				u_int32_t sense_flags);
1163static void		daprevent(struct cam_periph *periph, int action);
1164static void		dareprobe(struct cam_periph *periph);
1165static void		dasetgeom(struct cam_periph *periph, uint32_t block_len,
1166				  uint64_t maxsector,
1167				  struct scsi_read_capacity_data_long *rcaplong,
1168				  size_t rcap_size);
1169static timeout_t	dasendorderedtag;
1170static void		dashutdown(void *arg, int howto);
1171static timeout_t	damediapoll;
1172
1173#ifndef	DA_DEFAULT_POLL_PERIOD
1174#define	DA_DEFAULT_POLL_PERIOD	3
1175#endif
1176
1177#ifndef DA_DEFAULT_TIMEOUT
1178#define DA_DEFAULT_TIMEOUT 60	/* Timeout in seconds */
1179#endif
1180
1181#ifndef	DA_DEFAULT_RETRY
1182#define	DA_DEFAULT_RETRY	4
1183#endif
1184
1185#ifndef	DA_DEFAULT_SEND_ORDERED
1186#define	DA_DEFAULT_SEND_ORDERED	1
1187#endif
1188
1189#define DA_SIO (softc->sort_io_queue >= 0 ? \
1190    softc->sort_io_queue : cam_sort_io_queues)
1191
1192static int da_poll_period = DA_DEFAULT_POLL_PERIOD;
1193static int da_retry_count = DA_DEFAULT_RETRY;
1194static int da_default_timeout = DA_DEFAULT_TIMEOUT;
1195static int da_send_ordered = DA_DEFAULT_SEND_ORDERED;
1196
1197static SYSCTL_NODE(_kern_cam, OID_AUTO, da, CTLFLAG_RD, 0,
1198            "CAM Direct Access Disk driver");
1199SYSCTL_INT(_kern_cam_da, OID_AUTO, poll_period, CTLFLAG_RW,
1200           &da_poll_period, 0, "Media polling period in seconds");
1201TUNABLE_INT("kern.cam.da.poll_period", &da_poll_period);
1202SYSCTL_INT(_kern_cam_da, OID_AUTO, retry_count, CTLFLAG_RW,
1203           &da_retry_count, 0, "Normal I/O retry count");
1204TUNABLE_INT("kern.cam.da.retry_count", &da_retry_count);
1205SYSCTL_INT(_kern_cam_da, OID_AUTO, default_timeout, CTLFLAG_RW,
1206           &da_default_timeout, 0, "Normal I/O timeout (in seconds)");
1207TUNABLE_INT("kern.cam.da.default_timeout", &da_default_timeout);
1208SYSCTL_INT(_kern_cam_da, OID_AUTO, send_ordered, CTLFLAG_RW,
1209           &da_send_ordered, 0, "Send Ordered Tags");
1210TUNABLE_INT("kern.cam.da.send_ordered", &da_send_ordered);
1211
1212/*
1213 * DA_ORDEREDTAG_INTERVAL determines how often, relative
1214 * to the default timeout, we check to see whether an ordered
1215 * tagged transaction is appropriate to prevent simple tag
1216 * starvation.  Since we'd like to ensure that there is at least
1217 * 1/2 of the timeout length left for a starved transaction to
1218 * complete after we've sent an ordered tag, we must poll at least
1219 * four times in every timeout period.  This takes care of the worst
1220 * case where a starved transaction starts during an interval that
1221 * meets the requirement "don't send an ordered tag" test so it takes
1222 * us two intervals to determine that a tag must be sent.
1223 */
1224#ifndef DA_ORDEREDTAG_INTERVAL
1225#define DA_ORDEREDTAG_INTERVAL 4
1226#endif
1227
1228static struct periph_driver dadriver =
1229{
1230	dainit, "da",
1231	TAILQ_HEAD_INITIALIZER(dadriver.units), /* generation */ 0
1232};
1233
1234PERIPHDRIVER_DECLARE(da, dadriver);
1235
1236static MALLOC_DEFINE(M_SCSIDA, "scsi_da", "scsi_da buffers");
1237
1238static int
1239daopen(struct disk *dp)
1240{
1241	struct cam_periph *periph;
1242	struct da_softc *softc;
1243	int error;
1244
1245	periph = (struct cam_periph *)dp->d_drv1;
1246	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
1247		return (ENXIO);
1248	}
1249
1250	cam_periph_lock(periph);
1251	if ((error = cam_periph_hold(periph, PRIBIO|PCATCH)) != 0) {
1252		cam_periph_unlock(periph);
1253		cam_periph_release(periph);
1254		return (error);
1255	}
1256
1257	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
1258	    ("daopen\n"));
1259
1260	softc = (struct da_softc *)periph->softc;
1261	dareprobe(periph);
1262
1263	/* Wait for the disk size update.  */
1264	error = cam_periph_sleep(periph, &softc->disk->d_mediasize, PRIBIO,
1265	    "dareprobe", 0);
1266	if (error != 0)
1267		xpt_print(periph->path, "unable to retrieve capacity data\n");
1268
1269	if (periph->flags & CAM_PERIPH_INVALID)
1270		error = ENXIO;
1271
1272	if (error == 0 && (softc->flags & DA_FLAG_PACK_REMOVABLE) != 0 &&
1273	    (softc->quirks & DA_Q_NO_PREVENT) == 0)
1274		daprevent(periph, PR_PREVENT);
1275
1276	if (error == 0) {
1277		softc->flags &= ~DA_FLAG_PACK_INVALID;
1278		softc->flags |= DA_FLAG_OPEN;
1279	}
1280
1281	cam_periph_unhold(periph);
1282	cam_periph_unlock(periph);
1283
1284	if (error != 0)
1285		cam_periph_release(periph);
1286
1287	return (error);
1288}
1289
1290static int
1291daclose(struct disk *dp)
1292{
1293	struct	cam_periph *periph;
1294	struct	da_softc *softc;
1295	union	ccb *ccb;
1296	int error;
1297
1298	periph = (struct cam_periph *)dp->d_drv1;
1299	softc = (struct da_softc *)periph->softc;
1300	cam_periph_lock(periph);
1301	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
1302	    ("daclose\n"));
1303
1304	if (cam_periph_hold(periph, PRIBIO) == 0) {
1305
1306		/* Flush disk cache. */
1307		if ((softc->flags & DA_FLAG_DIRTY) != 0 &&
1308		    (softc->quirks & DA_Q_NO_SYNC_CACHE) == 0 &&
1309		    (softc->flags & DA_FLAG_PACK_INVALID) == 0) {
1310			ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1311			scsi_synchronize_cache(&ccb->csio, /*retries*/1,
1312			    /*cbfcnp*/dadone, MSG_SIMPLE_Q_TAG,
1313			    /*begin_lba*/0, /*lb_count*/0, SSD_FULL_SIZE,
1314			    5 * 60 * 1000);
1315			error = cam_periph_runccb(ccb, daerror, /*cam_flags*/0,
1316			    /*sense_flags*/SF_RETRY_UA | SF_QUIET_IR,
1317			    softc->disk->d_devstat);
1318			if (error == 0)
1319				softc->flags &= ~DA_FLAG_DIRTY;
1320			xpt_release_ccb(ccb);
1321		}
1322
1323		/* Allow medium removal. */
1324		if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0 &&
1325		    (softc->quirks & DA_Q_NO_PREVENT) == 0)
1326			daprevent(periph, PR_ALLOW);
1327
1328		cam_periph_unhold(periph);
1329	}
1330
1331	/*
1332	 * If we've got removeable media, mark the blocksize as
1333	 * unavailable, since it could change when new media is
1334	 * inserted.
1335	 */
1336	if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0)
1337		softc->disk->d_devstat->flags |= DEVSTAT_BS_UNAVAILABLE;
1338
1339	softc->flags &= ~DA_FLAG_OPEN;
1340	while (softc->refcount != 0)
1341		cam_periph_sleep(periph, &softc->refcount, PRIBIO, "daclose", 1);
1342	cam_periph_unlock(periph);
1343	cam_periph_release(periph);
1344	return (0);
1345}
1346
1347static void
1348daschedule(struct cam_periph *periph)
1349{
1350	struct da_softc *softc = (struct da_softc *)periph->softc;
1351
1352	if (softc->state != DA_STATE_NORMAL)
1353		return;
1354
1355	/* Check if we have more work to do. */
1356	if (bioq_first(&softc->bio_queue) ||
1357	    (!softc->delete_running && bioq_first(&softc->delete_queue)) ||
1358	    softc->tur) {
1359		xpt_schedule(periph, CAM_PRIORITY_NORMAL);
1360	}
1361}
1362
1363/*
1364 * Actually translate the requested transfer into one the physical driver
1365 * can understand.  The transfer is described by a buf and will include
1366 * only one physical transfer.
1367 */
1368static void
1369dastrategy(struct bio *bp)
1370{
1371	struct cam_periph *periph;
1372	struct da_softc *softc;
1373
1374	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1375	softc = (struct da_softc *)periph->softc;
1376
1377	cam_periph_lock(periph);
1378
1379	/*
1380	 * If the device has been made invalid, error out
1381	 */
1382	if ((softc->flags & DA_FLAG_PACK_INVALID)) {
1383		cam_periph_unlock(periph);
1384		biofinish(bp, NULL, ENXIO);
1385		return;
1386	}
1387
1388	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dastrategy(%p)\n", bp));
1389
1390	/*
1391	 * Place it in the queue of disk activities for this disk
1392	 */
1393	if (bp->bio_cmd == BIO_DELETE) {
1394		bioq_disksort(&softc->delete_queue, bp);
1395	} else if (DA_SIO) {
1396		bioq_disksort(&softc->bio_queue, bp);
1397	} else {
1398		bioq_insert_tail(&softc->bio_queue, bp);
1399	}
1400
1401	/*
1402	 * Schedule ourselves for performing the work.
1403	 */
1404	daschedule(periph);
1405	cam_periph_unlock(periph);
1406
1407	return;
1408}
1409
1410static int
1411dadump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size_t length)
1412{
1413	struct	    cam_periph *periph;
1414	struct	    da_softc *softc;
1415	u_int	    secsize;
1416	struct	    ccb_scsiio csio;
1417	struct	    disk *dp;
1418	int	    error = 0;
1419
1420	dp = arg;
1421	periph = dp->d_drv1;
1422	softc = (struct da_softc *)periph->softc;
1423	cam_periph_lock(periph);
1424	secsize = softc->params.secsize;
1425
1426	if ((softc->flags & DA_FLAG_PACK_INVALID) != 0) {
1427		cam_periph_unlock(periph);
1428		return (ENXIO);
1429	}
1430
1431	if (length > 0) {
1432		xpt_setup_ccb(&csio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1433		csio.ccb_h.ccb_state = DA_CCB_DUMP;
1434		scsi_read_write(&csio,
1435				/*retries*/0,
1436				dadone,
1437				MSG_ORDERED_Q_TAG,
1438				/*read*/SCSI_RW_WRITE,
1439				/*byte2*/0,
1440				/*minimum_cmd_size*/ softc->minimum_cmd_size,
1441				offset / secsize,
1442				length / secsize,
1443				/*data_ptr*/(u_int8_t *) virtual,
1444				/*dxfer_len*/length,
1445				/*sense_len*/SSD_FULL_SIZE,
1446				da_default_timeout * 1000);
1447		xpt_polled_action((union ccb *)&csio);
1448
1449		error = cam_periph_error((union ccb *)&csio,
1450		    0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
1451		if ((csio.ccb_h.status & CAM_DEV_QFRZN) != 0)
1452			cam_release_devq(csio.ccb_h.path, /*relsim_flags*/0,
1453			    /*reduction*/0, /*timeout*/0, /*getcount_only*/0);
1454		if (error != 0)
1455			printf("Aborting dump due to I/O error.\n");
1456		cam_periph_unlock(periph);
1457		return (error);
1458	}
1459
1460	/*
1461	 * Sync the disk cache contents to the physical media.
1462	 */
1463	if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
1464
1465		xpt_setup_ccb(&csio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1466		csio.ccb_h.ccb_state = DA_CCB_DUMP;
1467		scsi_synchronize_cache(&csio,
1468				       /*retries*/0,
1469				       /*cbfcnp*/dadone,
1470				       MSG_SIMPLE_Q_TAG,
1471				       /*begin_lba*/0,/* Cover the whole disk */
1472				       /*lb_count*/0,
1473				       SSD_FULL_SIZE,
1474				       5 * 60 * 1000);
1475		xpt_polled_action((union ccb *)&csio);
1476
1477		error = cam_periph_error((union ccb *)&csio,
1478		    0, SF_NO_RECOVERY | SF_NO_RETRY | SF_QUIET_IR, NULL);
1479		if ((csio.ccb_h.status & CAM_DEV_QFRZN) != 0)
1480			cam_release_devq(csio.ccb_h.path, /*relsim_flags*/0,
1481			    /*reduction*/0, /*timeout*/0, /*getcount_only*/0);
1482		if (error != 0)
1483			xpt_print(periph->path, "Synchronize cache failed\n");
1484	}
1485	cam_periph_unlock(periph);
1486	return (error);
1487}
1488
1489static int
1490dagetattr(struct bio *bp)
1491{
1492	int ret;
1493	struct cam_periph *periph;
1494
1495	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1496	cam_periph_lock(periph);
1497	ret = xpt_getattr(bp->bio_data, bp->bio_length, bp->bio_attribute,
1498	    periph->path);
1499	cam_periph_unlock(periph);
1500	if (ret == 0)
1501		bp->bio_completed = bp->bio_length;
1502	return ret;
1503}
1504
1505static void
1506dainit(void)
1507{
1508	cam_status status;
1509
1510	/*
1511	 * Install a global async callback.  This callback will
1512	 * receive async callbacks like "new device found".
1513	 */
1514	status = xpt_register_async(AC_FOUND_DEVICE, daasync, NULL, NULL);
1515
1516	if (status != CAM_REQ_CMP) {
1517		printf("da: Failed to attach master async callback "
1518		       "due to status 0x%x!\n", status);
1519	} else if (da_send_ordered) {
1520
1521		/* Register our shutdown event handler */
1522		if ((EVENTHANDLER_REGISTER(shutdown_post_sync, dashutdown,
1523					   NULL, SHUTDOWN_PRI_DEFAULT)) == NULL)
1524		    printf("dainit: shutdown event registration failed!\n");
1525	}
1526}
1527
1528/*
1529 * Callback from GEOM, called when it has finished cleaning up its
1530 * resources.
1531 */
1532static void
1533dadiskgonecb(struct disk *dp)
1534{
1535	struct cam_periph *periph;
1536
1537	periph = (struct cam_periph *)dp->d_drv1;
1538	cam_periph_release(periph);
1539}
1540
1541static void
1542daoninvalidate(struct cam_periph *periph)
1543{
1544	struct da_softc *softc;
1545
1546	softc = (struct da_softc *)periph->softc;
1547
1548	/*
1549	 * De-register any async callbacks.
1550	 */
1551	xpt_register_async(0, daasync, periph, periph->path);
1552
1553	softc->flags |= DA_FLAG_PACK_INVALID;
1554
1555	/*
1556	 * Return all queued I/O with ENXIO.
1557	 * XXX Handle any transactions queued to the card
1558	 *     with XPT_ABORT_CCB.
1559	 */
1560	bioq_flush(&softc->bio_queue, NULL, ENXIO);
1561	bioq_flush(&softc->delete_queue, NULL, ENXIO);
1562
1563	/*
1564	 * Tell GEOM that we've gone away, we'll get a callback when it is
1565	 * done cleaning up its resources.
1566	 */
1567	disk_gone(softc->disk);
1568}
1569
1570static void
1571dacleanup(struct cam_periph *periph)
1572{
1573	struct da_softc *softc;
1574
1575	softc = (struct da_softc *)periph->softc;
1576
1577	cam_periph_unlock(periph);
1578
1579	/*
1580	 * If we can't free the sysctl tree, oh well...
1581	 */
1582	if ((softc->flags & DA_FLAG_SCTX_INIT) != 0
1583	    && sysctl_ctx_free(&softc->sysctl_ctx) != 0) {
1584		xpt_print(periph->path, "can't remove sysctl context\n");
1585	}
1586
1587	callout_drain(&softc->mediapoll_c);
1588	disk_destroy(softc->disk);
1589	callout_drain(&softc->sendordered_c);
1590	free(softc, M_DEVBUF);
1591	cam_periph_lock(periph);
1592}
1593
1594static void
1595daasync(void *callback_arg, u_int32_t code,
1596	struct cam_path *path, void *arg)
1597{
1598	struct cam_periph *periph;
1599	struct da_softc *softc;
1600
1601	periph = (struct cam_periph *)callback_arg;
1602	switch (code) {
1603	case AC_FOUND_DEVICE:
1604	{
1605		struct ccb_getdev *cgd;
1606		cam_status status;
1607
1608		cgd = (struct ccb_getdev *)arg;
1609		if (cgd == NULL)
1610			break;
1611
1612		if (cgd->protocol != PROTO_SCSI)
1613			break;
1614
1615		if (SID_TYPE(&cgd->inq_data) != T_DIRECT
1616		    && SID_TYPE(&cgd->inq_data) != T_RBC
1617		    && SID_TYPE(&cgd->inq_data) != T_OPTICAL)
1618			break;
1619
1620		/*
1621		 * Allocate a peripheral instance for
1622		 * this device and start the probe
1623		 * process.
1624		 */
1625		status = cam_periph_alloc(daregister, daoninvalidate,
1626					  dacleanup, dastart,
1627					  "da", CAM_PERIPH_BIO,
1628					  path, daasync,
1629					  AC_FOUND_DEVICE, cgd);
1630
1631		if (status != CAM_REQ_CMP
1632		 && status != CAM_REQ_INPROG)
1633			printf("daasync: Unable to attach to new device "
1634				"due to status 0x%x\n", status);
1635		return;
1636	}
1637	case AC_ADVINFO_CHANGED:
1638	{
1639		uintptr_t buftype;
1640
1641		buftype = (uintptr_t)arg;
1642		if (buftype == CDAI_TYPE_PHYS_PATH) {
1643			struct da_softc *softc;
1644
1645			softc = periph->softc;
1646			disk_attr_changed(softc->disk, "GEOM::physpath",
1647					  M_NOWAIT);
1648		}
1649		break;
1650	}
1651	case AC_UNIT_ATTENTION:
1652	{
1653		union ccb *ccb;
1654		int error_code, sense_key, asc, ascq;
1655
1656		softc = (struct da_softc *)periph->softc;
1657		ccb = (union ccb *)arg;
1658
1659		/*
1660		 * Handle all UNIT ATTENTIONs except our own,
1661		 * as they will be handled by daerror().
1662		 */
1663		if (xpt_path_periph(ccb->ccb_h.path) != periph &&
1664		    scsi_extract_sense_ccb(ccb,
1665		     &error_code, &sense_key, &asc, &ascq)) {
1666			if (asc == 0x2A && ascq == 0x09) {
1667				xpt_print(ccb->ccb_h.path,
1668				    "Capacity data has changed\n");
1669				softc->flags &= ~DA_FLAG_PROBED;
1670				dareprobe(periph);
1671			} else if (asc == 0x28 && ascq == 0x00) {
1672				softc->flags &= ~DA_FLAG_PROBED;
1673				disk_media_changed(softc->disk, M_NOWAIT);
1674			} else if (asc == 0x3F && ascq == 0x03) {
1675				xpt_print(ccb->ccb_h.path,
1676				    "INQUIRY data has changed\n");
1677				softc->flags &= ~DA_FLAG_PROBED;
1678				dareprobe(periph);
1679			}
1680		}
1681		cam_periph_async(periph, code, path, arg);
1682		break;
1683	}
1684	case AC_SCSI_AEN:
1685		softc = (struct da_softc *)periph->softc;
1686		if (!softc->tur) {
1687			if (cam_periph_acquire(periph) == CAM_REQ_CMP) {
1688				softc->tur = 1;
1689				daschedule(periph);
1690			}
1691		}
1692		/* FALLTHROUGH */
1693	case AC_SENT_BDR:
1694	case AC_BUS_RESET:
1695	{
1696		struct ccb_hdr *ccbh;
1697
1698		softc = (struct da_softc *)periph->softc;
1699		/*
1700		 * Don't fail on the expected unit attention
1701		 * that will occur.
1702		 */
1703		softc->flags |= DA_FLAG_RETRY_UA;
1704		LIST_FOREACH(ccbh, &softc->pending_ccbs, periph_links.le)
1705			ccbh->ccb_state |= DA_CCB_RETRY_UA;
1706		break;
1707	}
1708	default:
1709		break;
1710	}
1711	cam_periph_async(periph, code, path, arg);
1712}
1713
1714static void
1715dasysctlinit(void *context, int pending)
1716{
1717	struct cam_periph *periph;
1718	struct da_softc *softc;
1719	char tmpstr[80], tmpstr2[80];
1720	struct ccb_trans_settings cts;
1721
1722	periph = (struct cam_periph *)context;
1723	/*
1724	 * periph was held for us when this task was enqueued
1725	 */
1726	if (periph->flags & CAM_PERIPH_INVALID) {
1727		cam_periph_release(periph);
1728		return;
1729	}
1730
1731	softc = (struct da_softc *)periph->softc;
1732	snprintf(tmpstr, sizeof(tmpstr), "CAM DA unit %d", periph->unit_number);
1733	snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
1734
1735	sysctl_ctx_init(&softc->sysctl_ctx);
1736	softc->flags |= DA_FLAG_SCTX_INIT;
1737	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1738		SYSCTL_STATIC_CHILDREN(_kern_cam_da), OID_AUTO, tmpstr2,
1739		CTLFLAG_RD, 0, tmpstr);
1740	if (softc->sysctl_tree == NULL) {
1741		printf("dasysctlinit: unable to allocate sysctl tree\n");
1742		cam_periph_release(periph);
1743		return;
1744	}
1745
1746	/*
1747	 * Now register the sysctl handler, so the user can change the value on
1748	 * the fly.
1749	 */
1750	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1751		OID_AUTO, "delete_method", CTLTYPE_STRING | CTLFLAG_RW,
1752		softc, 0, dadeletemethodsysctl, "A",
1753		"BIO_DELETE execution method");
1754	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1755		OID_AUTO, "delete_max", CTLTYPE_U64 | CTLFLAG_RW,
1756		softc, 0, dadeletemaxsysctl, "Q",
1757		"Maximum BIO_DELETE size");
1758	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1759		OID_AUTO, "minimum_cmd_size", CTLTYPE_INT | CTLFLAG_RW,
1760		&softc->minimum_cmd_size, 0, dacmdsizesysctl, "I",
1761		"Minimum CDB size");
1762	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1763		OID_AUTO, "sort_io_queue", CTLFLAG_RW, &softc->sort_io_queue, 0,
1764		"Sort IO queue to try and optimise disk access patterns");
1765
1766	SYSCTL_ADD_INT(&softc->sysctl_ctx,
1767		       SYSCTL_CHILDREN(softc->sysctl_tree),
1768		       OID_AUTO,
1769		       "error_inject",
1770		       CTLFLAG_RW,
1771		       &softc->error_inject,
1772		       0,
1773		       "error_inject leaf");
1774
1775
1776	/*
1777	 * Add some addressing info.
1778	 */
1779	memset(&cts, 0, sizeof (cts));
1780	xpt_setup_ccb(&cts.ccb_h, periph->path, CAM_PRIORITY_NONE);
1781	cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
1782	cts.type = CTS_TYPE_CURRENT_SETTINGS;
1783	cam_periph_lock(periph);
1784	xpt_action((union ccb *)&cts);
1785	cam_periph_unlock(periph);
1786	if (cts.ccb_h.status != CAM_REQ_CMP) {
1787		cam_periph_release(periph);
1788		return;
1789	}
1790	if (cts.protocol == PROTO_SCSI && cts.transport == XPORT_FC) {
1791		struct ccb_trans_settings_fc *fc = &cts.xport_specific.fc;
1792		if (fc->valid & CTS_FC_VALID_WWPN) {
1793			softc->wwpn = fc->wwpn;
1794			SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
1795			    SYSCTL_CHILDREN(softc->sysctl_tree),
1796			    OID_AUTO, "wwpn", CTLFLAG_RD,
1797			    &softc->wwpn, "World Wide Port Name");
1798		}
1799	}
1800	cam_periph_release(periph);
1801}
1802
1803static int
1804dadeletemaxsysctl(SYSCTL_HANDLER_ARGS)
1805{
1806	int error;
1807	uint64_t value;
1808	struct da_softc *softc;
1809
1810	softc = (struct da_softc *)arg1;
1811
1812	value = softc->disk->d_delmaxsize;
1813	error = sysctl_handle_64(oidp, &value, 0, req);
1814	if ((error != 0) || (req->newptr == NULL))
1815		return (error);
1816
1817	/* only accept values smaller than the calculated value */
1818	if (value > dadeletemaxsize(softc, softc->delete_method)) {
1819		return (EINVAL);
1820	}
1821	softc->disk->d_delmaxsize = value;
1822
1823	return (0);
1824}
1825
1826static int
1827dacmdsizesysctl(SYSCTL_HANDLER_ARGS)
1828{
1829	int error, value;
1830
1831	value = *(int *)arg1;
1832
1833	error = sysctl_handle_int(oidp, &value, 0, req);
1834
1835	if ((error != 0)
1836	 || (req->newptr == NULL))
1837		return (error);
1838
1839	/*
1840	 * Acceptable values here are 6, 10, 12 or 16.
1841	 */
1842	if (value < 6)
1843		value = 6;
1844	else if ((value > 6)
1845	      && (value <= 10))
1846		value = 10;
1847	else if ((value > 10)
1848	      && (value <= 12))
1849		value = 12;
1850	else if (value > 12)
1851		value = 16;
1852
1853	*(int *)arg1 = value;
1854
1855	return (0);
1856}
1857
1858static void
1859dadeletemethodset(struct da_softc *softc, da_delete_methods delete_method)
1860{
1861
1862
1863	softc->delete_method = delete_method;
1864	softc->disk->d_delmaxsize = dadeletemaxsize(softc, delete_method);
1865	softc->delete_func = da_delete_functions[delete_method];
1866
1867	if (softc->delete_method > DA_DELETE_DISABLE)
1868		softc->disk->d_flags |= DISKFLAG_CANDELETE;
1869	else
1870		softc->disk->d_flags &= ~DISKFLAG_CANDELETE;
1871}
1872
1873static off_t
1874dadeletemaxsize(struct da_softc *softc, da_delete_methods delete_method)
1875{
1876	off_t sectors;
1877
1878	switch(delete_method) {
1879	case DA_DELETE_UNMAP:
1880		sectors = (off_t)softc->unmap_max_lba;
1881		break;
1882	case DA_DELETE_ATA_TRIM:
1883		sectors = (off_t)ATA_DSM_RANGE_MAX * softc->trim_max_ranges;
1884		break;
1885	case DA_DELETE_WS16:
1886		sectors = (off_t)min(softc->ws_max_blks, WS16_MAX_BLKS);
1887		break;
1888	case DA_DELETE_ZERO:
1889	case DA_DELETE_WS10:
1890		sectors = (off_t)min(softc->ws_max_blks, WS10_MAX_BLKS);
1891		break;
1892	default:
1893		return 0;
1894	}
1895
1896	return (off_t)softc->params.secsize *
1897	    min(sectors, (off_t)softc->params.sectors);
1898}
1899
1900static void
1901daprobedone(struct cam_periph *periph, union ccb *ccb)
1902{
1903	struct da_softc *softc;
1904
1905	softc = (struct da_softc *)periph->softc;
1906
1907	dadeletemethodchoose(softc, DA_DELETE_NONE);
1908
1909	if (bootverbose && (softc->flags & DA_FLAG_ANNOUNCED) == 0) {
1910		char buf[80];
1911		int i, sep;
1912
1913		snprintf(buf, sizeof(buf), "Delete methods: <");
1914		sep = 0;
1915		for (i = DA_DELETE_MIN; i <= DA_DELETE_MAX; i++) {
1916			if (softc->delete_available & (1 << i)) {
1917				if (sep) {
1918					strlcat(buf, ",", sizeof(buf));
1919				} else {
1920				    sep = 1;
1921				}
1922				strlcat(buf, da_delete_method_names[i],
1923				    sizeof(buf));
1924				if (i == softc->delete_method) {
1925					strlcat(buf, "(*)", sizeof(buf));
1926				}
1927			}
1928		}
1929		if (sep == 0) {
1930			if (softc->delete_method == DA_DELETE_NONE)
1931				strlcat(buf, "NONE(*)", sizeof(buf));
1932			else
1933				strlcat(buf, "DISABLED(*)", sizeof(buf));
1934		}
1935		strlcat(buf, ">", sizeof(buf));
1936		printf("%s%d: %s\n", periph->periph_name,
1937		    periph->unit_number, buf);
1938	}
1939
1940	/*
1941	 * Since our peripheral may be invalidated by an error
1942	 * above or an external event, we must release our CCB
1943	 * before releasing the probe lock on the peripheral.
1944	 * The peripheral will only go away once the last lock
1945	 * is removed, and we need it around for the CCB release
1946	 * operation.
1947	 */
1948	xpt_release_ccb(ccb);
1949	softc->state = DA_STATE_NORMAL;
1950	softc->flags |= DA_FLAG_PROBED;
1951	daschedule(periph);
1952	wakeup(&softc->disk->d_mediasize);
1953	if ((softc->flags & DA_FLAG_ANNOUNCED) == 0) {
1954		softc->flags |= DA_FLAG_ANNOUNCED;
1955		cam_periph_unhold(periph);
1956	} else
1957		cam_periph_release_locked(periph);
1958}
1959
1960static void
1961dadeletemethodchoose(struct da_softc *softc, da_delete_methods default_method)
1962{
1963	int i, delete_method;
1964
1965	delete_method = default_method;
1966
1967	/*
1968	 * Use the pre-defined order to choose the best
1969	 * performing delete.
1970	 */
1971	for (i = DA_DELETE_MIN; i <= DA_DELETE_MAX; i++) {
1972		if (softc->delete_available & (1 << i)) {
1973			dadeletemethodset(softc, i);
1974			return;
1975		}
1976	}
1977	dadeletemethodset(softc, delete_method);
1978}
1979
1980static int
1981dadeletemethodsysctl(SYSCTL_HANDLER_ARGS)
1982{
1983	char buf[16];
1984	const char *p;
1985	struct da_softc *softc;
1986	int i, error, methods, value;
1987
1988	softc = (struct da_softc *)arg1;
1989
1990	value = softc->delete_method;
1991	if (value < 0 || value > DA_DELETE_MAX)
1992		p = "UNKNOWN";
1993	else
1994		p = da_delete_method_names[value];
1995	strncpy(buf, p, sizeof(buf));
1996	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
1997	if (error != 0 || req->newptr == NULL)
1998		return (error);
1999	methods = softc->delete_available | (1 << DA_DELETE_DISABLE);
2000	for (i = 0; i <= DA_DELETE_MAX; i++) {
2001		if (!(methods & (1 << i)) ||
2002		    strcmp(buf, da_delete_method_names[i]) != 0)
2003			continue;
2004		dadeletemethodset(softc, i);
2005		return (0);
2006	}
2007	return (EINVAL);
2008}
2009
2010static cam_status
2011daregister(struct cam_periph *periph, void *arg)
2012{
2013	struct da_softc *softc;
2014	struct ccb_pathinq cpi;
2015	struct ccb_getdev *cgd;
2016	char tmpstr[80];
2017	caddr_t match;
2018
2019	cgd = (struct ccb_getdev *)arg;
2020	if (cgd == NULL) {
2021		printf("daregister: no getdev CCB, can't register device\n");
2022		return(CAM_REQ_CMP_ERR);
2023	}
2024
2025	softc = (struct da_softc *)malloc(sizeof(*softc), M_DEVBUF,
2026	    M_NOWAIT|M_ZERO);
2027
2028	if (softc == NULL) {
2029		printf("daregister: Unable to probe new device. "
2030		       "Unable to allocate softc\n");
2031		return(CAM_REQ_CMP_ERR);
2032	}
2033
2034	LIST_INIT(&softc->pending_ccbs);
2035	softc->state = DA_STATE_PROBE_RC;
2036	bioq_init(&softc->bio_queue);
2037	bioq_init(&softc->delete_queue);
2038	bioq_init(&softc->delete_run_queue);
2039	if (SID_IS_REMOVABLE(&cgd->inq_data))
2040		softc->flags |= DA_FLAG_PACK_REMOVABLE;
2041	softc->unmap_max_ranges = UNMAP_MAX_RANGES;
2042	softc->unmap_max_lba = UNMAP_RANGE_MAX;
2043	softc->ws_max_blks = WS16_MAX_BLKS;
2044	softc->trim_max_ranges = ATA_TRIM_MAX_RANGES;
2045	softc->sort_io_queue = -1;
2046
2047	periph->softc = softc;
2048
2049	/*
2050	 * See if this device has any quirks.
2051	 */
2052	match = cam_quirkmatch((caddr_t)&cgd->inq_data,
2053			       (caddr_t)da_quirk_table,
2054			       sizeof(da_quirk_table)/sizeof(*da_quirk_table),
2055			       sizeof(*da_quirk_table), scsi_inquiry_match);
2056
2057	if (match != NULL)
2058		softc->quirks = ((struct da_quirk_entry *)match)->quirks;
2059	else
2060		softc->quirks = DA_Q_NONE;
2061
2062	/* Check if the SIM does not want 6 byte commands */
2063	bzero(&cpi, sizeof(cpi));
2064	xpt_setup_ccb(&cpi.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
2065	cpi.ccb_h.func_code = XPT_PATH_INQ;
2066	xpt_action((union ccb *)&cpi);
2067	if (cpi.ccb_h.status == CAM_REQ_CMP && (cpi.hba_misc & PIM_NO_6_BYTE))
2068		softc->quirks |= DA_Q_NO_6_BYTE;
2069
2070	TASK_INIT(&softc->sysctl_task, 0, dasysctlinit, periph);
2071
2072	/*
2073	 * Take an exclusive refcount on the periph while dastart is called
2074	 * to finish the probe.  The reference will be dropped in dadone at
2075	 * the end of probe.
2076	 */
2077	(void)cam_periph_hold(periph, PRIBIO);
2078
2079	/*
2080	 * Schedule a periodic event to occasionally send an
2081	 * ordered tag to a device.
2082	 */
2083	callout_init_mtx(&softc->sendordered_c, cam_periph_mtx(periph), 0);
2084	callout_reset(&softc->sendordered_c,
2085	    (da_default_timeout * hz) / DA_ORDEREDTAG_INTERVAL,
2086	    dasendorderedtag, softc);
2087
2088	cam_periph_unlock(periph);
2089	/*
2090	 * RBC devices don't have to support READ(6), only READ(10).
2091	 */
2092	if (softc->quirks & DA_Q_NO_6_BYTE || SID_TYPE(&cgd->inq_data) == T_RBC)
2093		softc->minimum_cmd_size = 10;
2094	else
2095		softc->minimum_cmd_size = 6;
2096
2097	/*
2098	 * Load the user's default, if any.
2099	 */
2100	snprintf(tmpstr, sizeof(tmpstr), "kern.cam.da.%d.minimum_cmd_size",
2101		 periph->unit_number);
2102	TUNABLE_INT_FETCH(tmpstr, &softc->minimum_cmd_size);
2103
2104	/*
2105	 * 6, 10, 12 and 16 are the currently permissible values.
2106	 */
2107	if (softc->minimum_cmd_size < 6)
2108		softc->minimum_cmd_size = 6;
2109	else if ((softc->minimum_cmd_size > 6)
2110	      && (softc->minimum_cmd_size <= 10))
2111		softc->minimum_cmd_size = 10;
2112	else if ((softc->minimum_cmd_size > 10)
2113	      && (softc->minimum_cmd_size <= 12))
2114		softc->minimum_cmd_size = 12;
2115	else if (softc->minimum_cmd_size > 12)
2116		softc->minimum_cmd_size = 16;
2117
2118	/* Predict whether device may support READ CAPACITY(16). */
2119	if (SID_ANSI_REV(&cgd->inq_data) >= SCSI_REV_SPC3 &&
2120	    (softc->quirks & DA_Q_NO_RC16) == 0) {
2121		softc->flags |= DA_FLAG_CAN_RC16;
2122		softc->state = DA_STATE_PROBE_RC16;
2123	}
2124
2125	/*
2126	 * Register this media as a disk.
2127	 */
2128	softc->disk = disk_alloc();
2129	softc->disk->d_devstat = devstat_new_entry(periph->periph_name,
2130			  periph->unit_number, 0,
2131			  DEVSTAT_BS_UNAVAILABLE,
2132			  SID_TYPE(&cgd->inq_data) |
2133			  XPORT_DEVSTAT_TYPE(cpi.transport),
2134			  DEVSTAT_PRIORITY_DISK);
2135	softc->disk->d_open = daopen;
2136	softc->disk->d_close = daclose;
2137	softc->disk->d_strategy = dastrategy;
2138	softc->disk->d_dump = dadump;
2139	softc->disk->d_getattr = dagetattr;
2140	softc->disk->d_gone = dadiskgonecb;
2141	softc->disk->d_name = "da";
2142	softc->disk->d_drv1 = periph;
2143	if (cpi.maxio == 0)
2144		softc->maxio = DFLTPHYS;	/* traditional default */
2145	else if (cpi.maxio > MAXPHYS)
2146		softc->maxio = MAXPHYS;		/* for safety */
2147	else
2148		softc->maxio = cpi.maxio;
2149	softc->disk->d_maxsize = softc->maxio;
2150	softc->disk->d_unit = periph->unit_number;
2151	softc->disk->d_flags = DISKFLAG_DIRECT_COMPLETION;
2152	if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0)
2153		softc->disk->d_flags |= DISKFLAG_CANFLUSHCACHE;
2154	if ((cpi.hba_misc & PIM_UNMAPPED) != 0)
2155		softc->disk->d_flags |= DISKFLAG_UNMAPPED_BIO;
2156	cam_strvis(softc->disk->d_descr, cgd->inq_data.vendor,
2157	    sizeof(cgd->inq_data.vendor), sizeof(softc->disk->d_descr));
2158	strlcat(softc->disk->d_descr, " ", sizeof(softc->disk->d_descr));
2159	cam_strvis(&softc->disk->d_descr[strlen(softc->disk->d_descr)],
2160	    cgd->inq_data.product, sizeof(cgd->inq_data.product),
2161	    sizeof(softc->disk->d_descr) - strlen(softc->disk->d_descr));
2162	softc->disk->d_hba_vendor = cpi.hba_vendor;
2163	softc->disk->d_hba_device = cpi.hba_device;
2164	softc->disk->d_hba_subvendor = cpi.hba_subvendor;
2165	softc->disk->d_hba_subdevice = cpi.hba_subdevice;
2166
2167	/*
2168	 * Acquire a reference to the periph before we register with GEOM.
2169	 * We'll release this reference once GEOM calls us back (via
2170	 * dadiskgonecb()) telling us that our provider has been freed.
2171	 */
2172	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
2173		xpt_print(periph->path, "%s: lost periph during "
2174			  "registration!\n", __func__);
2175		cam_periph_lock(periph);
2176		return (CAM_REQ_CMP_ERR);
2177	}
2178
2179	disk_create(softc->disk, DISK_VERSION);
2180	cam_periph_lock(periph);
2181
2182	/*
2183	 * Add async callbacks for events of interest.
2184	 * I don't bother checking if this fails as,
2185	 * in most cases, the system will function just
2186	 * fine without them and the only alternative
2187	 * would be to not attach the device on failure.
2188	 */
2189	xpt_register_async(AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE |
2190	    AC_ADVINFO_CHANGED | AC_SCSI_AEN | AC_UNIT_ATTENTION,
2191	    daasync, periph, periph->path);
2192
2193	/*
2194	 * Emit an attribute changed notification just in case
2195	 * physical path information arrived before our async
2196	 * event handler was registered, but after anyone attaching
2197	 * to our disk device polled it.
2198	 */
2199	disk_attr_changed(softc->disk, "GEOM::physpath", M_NOWAIT);
2200
2201	/*
2202	 * Schedule a periodic media polling events.
2203	 */
2204	callout_init_mtx(&softc->mediapoll_c, cam_periph_mtx(periph), 0);
2205	if ((softc->flags & DA_FLAG_PACK_REMOVABLE) &&
2206	    (cgd->inq_flags & SID_AEN) == 0 &&
2207	    da_poll_period != 0)
2208		callout_reset(&softc->mediapoll_c, da_poll_period * hz,
2209		    damediapoll, periph);
2210
2211	xpt_schedule(periph, CAM_PRIORITY_DEV);
2212
2213	return(CAM_REQ_CMP);
2214}
2215
2216static void
2217dastart(struct cam_periph *periph, union ccb *start_ccb)
2218{
2219	struct da_softc *softc;
2220
2221	softc = (struct da_softc *)periph->softc;
2222
2223	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dastart\n"));
2224
2225skipstate:
2226	switch (softc->state) {
2227	case DA_STATE_NORMAL:
2228	{
2229		struct bio *bp;
2230		uint8_t tag_code;
2231
2232		/* Run BIO_DELETE if not running yet. */
2233		if (!softc->delete_running &&
2234		    (bp = bioq_first(&softc->delete_queue)) != NULL) {
2235			if (softc->delete_func != NULL) {
2236				softc->delete_func(periph, start_ccb, bp);
2237				goto out;
2238			} else {
2239				bioq_flush(&softc->delete_queue, NULL, 0);
2240				/* FALLTHROUGH */
2241			}
2242		}
2243
2244		/* Run regular command. */
2245		bp = bioq_takefirst(&softc->bio_queue);
2246		if (bp == NULL) {
2247			if (softc->tur) {
2248				softc->tur = 0;
2249				scsi_test_unit_ready(&start_ccb->csio,
2250				     /*retries*/ da_retry_count,
2251				     dadone,
2252				     MSG_SIMPLE_Q_TAG,
2253				     SSD_FULL_SIZE,
2254				     da_default_timeout * 1000);
2255				start_ccb->ccb_h.ccb_bp = NULL;
2256				start_ccb->ccb_h.ccb_state = DA_CCB_TUR;
2257				xpt_action(start_ccb);
2258			} else
2259				xpt_release_ccb(start_ccb);
2260			break;
2261		}
2262		if (softc->tur) {
2263			softc->tur = 0;
2264			cam_periph_release_locked(periph);
2265		}
2266
2267		if ((bp->bio_flags & BIO_ORDERED) != 0 ||
2268		    (softc->flags & DA_FLAG_NEED_OTAG) != 0) {
2269			softc->flags &= ~DA_FLAG_NEED_OTAG;
2270			softc->flags |= DA_FLAG_WAS_OTAG;
2271			tag_code = MSG_ORDERED_Q_TAG;
2272		} else {
2273			tag_code = MSG_SIMPLE_Q_TAG;
2274		}
2275
2276		switch (bp->bio_cmd) {
2277		case BIO_WRITE:
2278			softc->flags |= DA_FLAG_DIRTY;
2279			/* FALLTHROUGH */
2280		case BIO_READ:
2281			scsi_read_write(&start_ccb->csio,
2282					/*retries*/da_retry_count,
2283					/*cbfcnp*/dadone,
2284					/*tag_action*/tag_code,
2285					/*read_op*/(bp->bio_cmd == BIO_READ ?
2286					SCSI_RW_READ : SCSI_RW_WRITE) |
2287					((bp->bio_flags & BIO_UNMAPPED) != 0 ?
2288					SCSI_RW_BIO : 0),
2289					/*byte2*/0,
2290					softc->minimum_cmd_size,
2291					/*lba*/bp->bio_pblkno,
2292					/*block_count*/bp->bio_bcount /
2293					softc->params.secsize,
2294					/*data_ptr*/ (bp->bio_flags &
2295					BIO_UNMAPPED) != 0 ? (void *)bp :
2296					bp->bio_data,
2297					/*dxfer_len*/ bp->bio_bcount,
2298					/*sense_len*/SSD_FULL_SIZE,
2299					da_default_timeout * 1000);
2300			break;
2301		case BIO_FLUSH:
2302			/*
2303			 * BIO_FLUSH doesn't currently communicate
2304			 * range data, so we synchronize the cache
2305			 * over the whole disk.  We also force
2306			 * ordered tag semantics the flush applies
2307			 * to all previously queued I/O.
2308			 */
2309			scsi_synchronize_cache(&start_ccb->csio,
2310					       /*retries*/1,
2311					       /*cbfcnp*/dadone,
2312					       MSG_ORDERED_Q_TAG,
2313					       /*begin_lba*/0,
2314					       /*lb_count*/0,
2315					       SSD_FULL_SIZE,
2316					       da_default_timeout*1000);
2317			break;
2318		}
2319		start_ccb->ccb_h.ccb_state = DA_CCB_BUFFER_IO;
2320		start_ccb->ccb_h.flags |= CAM_UNLOCKED;
2321
2322out:
2323		LIST_INSERT_HEAD(&softc->pending_ccbs,
2324				 &start_ccb->ccb_h, periph_links.le);
2325
2326		/* We expect a unit attention from this device */
2327		if ((softc->flags & DA_FLAG_RETRY_UA) != 0) {
2328			start_ccb->ccb_h.ccb_state |= DA_CCB_RETRY_UA;
2329			softc->flags &= ~DA_FLAG_RETRY_UA;
2330		}
2331
2332		start_ccb->ccb_h.ccb_bp = bp;
2333		softc->refcount++;
2334		cam_periph_unlock(periph);
2335		xpt_action(start_ccb);
2336		cam_periph_lock(periph);
2337		softc->refcount--;
2338
2339		/* May have more work to do, so ensure we stay scheduled */
2340		daschedule(periph);
2341		break;
2342	}
2343	case DA_STATE_PROBE_RC:
2344	{
2345		struct scsi_read_capacity_data *rcap;
2346
2347		rcap = (struct scsi_read_capacity_data *)
2348		    malloc(sizeof(*rcap), M_SCSIDA, M_NOWAIT|M_ZERO);
2349		if (rcap == NULL) {
2350			printf("dastart: Couldn't malloc read_capacity data\n");
2351			/* da_free_periph??? */
2352			break;
2353		}
2354		scsi_read_capacity(&start_ccb->csio,
2355				   /*retries*/da_retry_count,
2356				   dadone,
2357				   MSG_SIMPLE_Q_TAG,
2358				   rcap,
2359				   SSD_FULL_SIZE,
2360				   /*timeout*/5000);
2361		start_ccb->ccb_h.ccb_bp = NULL;
2362		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_RC;
2363		xpt_action(start_ccb);
2364		break;
2365	}
2366	case DA_STATE_PROBE_RC16:
2367	{
2368		struct scsi_read_capacity_data_long *rcaplong;
2369
2370		rcaplong = (struct scsi_read_capacity_data_long *)
2371			malloc(sizeof(*rcaplong), M_SCSIDA, M_NOWAIT|M_ZERO);
2372		if (rcaplong == NULL) {
2373			printf("dastart: Couldn't malloc read_capacity data\n");
2374			/* da_free_periph??? */
2375			break;
2376		}
2377		scsi_read_capacity_16(&start_ccb->csio,
2378				      /*retries*/ da_retry_count,
2379				      /*cbfcnp*/ dadone,
2380				      /*tag_action*/ MSG_SIMPLE_Q_TAG,
2381				      /*lba*/ 0,
2382				      /*reladr*/ 0,
2383				      /*pmi*/ 0,
2384				      /*rcap_buf*/ (uint8_t *)rcaplong,
2385				      /*rcap_buf_len*/ sizeof(*rcaplong),
2386				      /*sense_len*/ SSD_FULL_SIZE,
2387				      /*timeout*/ da_default_timeout * 1000);
2388		start_ccb->ccb_h.ccb_bp = NULL;
2389		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_RC16;
2390		xpt_action(start_ccb);
2391		break;
2392	}
2393	case DA_STATE_PROBE_LBP:
2394	{
2395		struct scsi_vpd_logical_block_prov *lbp;
2396
2397		if (!scsi_vpd_supported_page(periph, SVPD_LBP)) {
2398			/*
2399			 * If we get here we don't support any SBC-3 delete
2400			 * methods with UNMAP as the Logical Block Provisioning
2401			 * VPD page support is required for devices which
2402			 * support it according to T10/1799-D Revision 31
2403			 * however older revisions of the spec don't mandate
2404			 * this so we currently don't remove these methods
2405			 * from the available set.
2406			 */
2407			softc->state = DA_STATE_PROBE_BLK_LIMITS;
2408			goto skipstate;
2409		}
2410
2411		lbp = (struct scsi_vpd_logical_block_prov *)
2412			malloc(sizeof(*lbp), M_SCSIDA, M_NOWAIT|M_ZERO);
2413
2414		if (lbp == NULL) {
2415			printf("dastart: Couldn't malloc lbp data\n");
2416			/* da_free_periph??? */
2417			break;
2418		}
2419
2420		scsi_inquiry(&start_ccb->csio,
2421			     /*retries*/da_retry_count,
2422			     /*cbfcnp*/dadone,
2423			     /*tag_action*/MSG_SIMPLE_Q_TAG,
2424			     /*inq_buf*/(u_int8_t *)lbp,
2425			     /*inq_len*/sizeof(*lbp),
2426			     /*evpd*/TRUE,
2427			     /*page_code*/SVPD_LBP,
2428			     /*sense_len*/SSD_MIN_SIZE,
2429			     /*timeout*/da_default_timeout * 1000);
2430		start_ccb->ccb_h.ccb_bp = NULL;
2431		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_LBP;
2432		xpt_action(start_ccb);
2433		break;
2434	}
2435	case DA_STATE_PROBE_BLK_LIMITS:
2436	{
2437		struct scsi_vpd_block_limits *block_limits;
2438
2439		if (!scsi_vpd_supported_page(periph, SVPD_BLOCK_LIMITS)) {
2440			/* Not supported skip to next probe */
2441			softc->state = DA_STATE_PROBE_BDC;
2442			goto skipstate;
2443		}
2444
2445		block_limits = (struct scsi_vpd_block_limits *)
2446			malloc(sizeof(*block_limits), M_SCSIDA, M_NOWAIT|M_ZERO);
2447
2448		if (block_limits == NULL) {
2449			printf("dastart: Couldn't malloc block_limits data\n");
2450			/* da_free_periph??? */
2451			break;
2452		}
2453
2454		scsi_inquiry(&start_ccb->csio,
2455			     /*retries*/da_retry_count,
2456			     /*cbfcnp*/dadone,
2457			     /*tag_action*/MSG_SIMPLE_Q_TAG,
2458			     /*inq_buf*/(u_int8_t *)block_limits,
2459			     /*inq_len*/sizeof(*block_limits),
2460			     /*evpd*/TRUE,
2461			     /*page_code*/SVPD_BLOCK_LIMITS,
2462			     /*sense_len*/SSD_MIN_SIZE,
2463			     /*timeout*/da_default_timeout * 1000);
2464		start_ccb->ccb_h.ccb_bp = NULL;
2465		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_BLK_LIMITS;
2466		xpt_action(start_ccb);
2467		break;
2468	}
2469	case DA_STATE_PROBE_BDC:
2470	{
2471		struct scsi_vpd_block_characteristics *bdc;
2472
2473		if (!scsi_vpd_supported_page(periph, SVPD_BDC)) {
2474			softc->state = DA_STATE_PROBE_ATA;
2475			goto skipstate;
2476		}
2477
2478		bdc = (struct scsi_vpd_block_characteristics *)
2479			malloc(sizeof(*bdc), M_SCSIDA, M_NOWAIT|M_ZERO);
2480
2481		if (bdc == NULL) {
2482			printf("dastart: Couldn't malloc bdc data\n");
2483			/* da_free_periph??? */
2484			break;
2485		}
2486
2487		scsi_inquiry(&start_ccb->csio,
2488			     /*retries*/da_retry_count,
2489			     /*cbfcnp*/dadone,
2490			     /*tag_action*/MSG_SIMPLE_Q_TAG,
2491			     /*inq_buf*/(u_int8_t *)bdc,
2492			     /*inq_len*/sizeof(*bdc),
2493			     /*evpd*/TRUE,
2494			     /*page_code*/SVPD_BDC,
2495			     /*sense_len*/SSD_MIN_SIZE,
2496			     /*timeout*/da_default_timeout * 1000);
2497		start_ccb->ccb_h.ccb_bp = NULL;
2498		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_BDC;
2499		xpt_action(start_ccb);
2500		break;
2501	}
2502	case DA_STATE_PROBE_ATA:
2503	{
2504		struct ata_params *ata_params;
2505
2506		if (!scsi_vpd_supported_page(periph, SVPD_ATA_INFORMATION)) {
2507			daprobedone(periph, start_ccb);
2508			break;
2509		}
2510
2511		ata_params = (struct ata_params*)
2512			malloc(sizeof(*ata_params), M_SCSIDA, M_NOWAIT|M_ZERO);
2513
2514		if (ata_params == NULL) {
2515			printf("dastart: Couldn't malloc ata_params data\n");
2516			/* da_free_periph??? */
2517			break;
2518		}
2519
2520		scsi_ata_identify(&start_ccb->csio,
2521				  /*retries*/da_retry_count,
2522				  /*cbfcnp*/dadone,
2523                                  /*tag_action*/MSG_SIMPLE_Q_TAG,
2524				  /*data_ptr*/(u_int8_t *)ata_params,
2525				  /*dxfer_len*/sizeof(*ata_params),
2526				  /*sense_len*/SSD_FULL_SIZE,
2527				  /*timeout*/da_default_timeout * 1000);
2528		start_ccb->ccb_h.ccb_bp = NULL;
2529		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_ATA;
2530		xpt_action(start_ccb);
2531		break;
2532	}
2533	}
2534}
2535
2536/*
2537 * In each of the methods below, while its the caller's
2538 * responsibility to ensure the request will fit into a
2539 * single device request, we might have changed the delete
2540 * method due to the device incorrectly advertising either
2541 * its supported methods or limits.
2542 *
2543 * To prevent this causing further issues we validate the
2544 * against the methods limits, and warn which would
2545 * otherwise be unnecessary.
2546 */
2547static void
2548da_delete_unmap(struct cam_periph *periph, union ccb *ccb, struct bio *bp)
2549{
2550	struct da_softc *softc = (struct da_softc *)periph->softc;;
2551	struct bio *bp1;
2552	uint8_t *buf = softc->unmap_buf;
2553	uint64_t lba, lastlba = (uint64_t)-1;
2554	uint64_t totalcount = 0;
2555	uint64_t count;
2556	uint32_t lastcount = 0, c;
2557	uint32_t off, ranges = 0;
2558
2559	/*
2560	 * Currently this doesn't take the UNMAP
2561	 * Granularity and Granularity Alignment
2562	 * fields into account.
2563	 *
2564	 * This could result in both unoptimal unmap
2565	 * requests as as well as UNMAP calls unmapping
2566	 * fewer LBA's than requested.
2567	 */
2568
2569	softc->delete_running = 1;
2570	bzero(softc->unmap_buf, sizeof(softc->unmap_buf));
2571	bp1 = bp;
2572	do {
2573		bioq_remove(&softc->delete_queue, bp1);
2574		if (bp1 != bp)
2575			bioq_insert_tail(&softc->delete_run_queue, bp1);
2576		lba = bp1->bio_pblkno;
2577		count = bp1->bio_bcount / softc->params.secsize;
2578
2579		/* Try to extend the previous range. */
2580		if (lba == lastlba) {
2581			c = omin(count, UNMAP_RANGE_MAX - lastcount);
2582			lastcount += c;
2583			off = ((ranges - 1) * UNMAP_RANGE_SIZE) +
2584			      UNMAP_HEAD_SIZE;
2585			scsi_ulto4b(lastcount, &buf[off + 8]);
2586			count -= c;
2587			lba +=c;
2588			totalcount += c;
2589		}
2590
2591		while (count > 0) {
2592			c = omin(count, UNMAP_RANGE_MAX);
2593			if (totalcount + c > softc->unmap_max_lba ||
2594			    ranges >= softc->unmap_max_ranges) {
2595				xpt_print(periph->path,
2596				    "%s issuing short delete %ld > %ld"
2597				    "|| %d >= %d",
2598				    da_delete_method_desc[softc->delete_method],
2599				    totalcount + c, softc->unmap_max_lba,
2600				    ranges, softc->unmap_max_ranges);
2601				break;
2602			}
2603			off = (ranges * UNMAP_RANGE_SIZE) + UNMAP_HEAD_SIZE;
2604			scsi_u64to8b(lba, &buf[off + 0]);
2605			scsi_ulto4b(c, &buf[off + 8]);
2606			lba += c;
2607			totalcount += c;
2608			ranges++;
2609			count -= c;
2610			lastcount = c;
2611		}
2612		lastlba = lba;
2613		bp1 = bioq_first(&softc->delete_queue);
2614		if (bp1 == NULL || ranges >= softc->unmap_max_ranges ||
2615		    totalcount + bp1->bio_bcount /
2616		    softc->params.secsize > softc->unmap_max_lba)
2617			break;
2618	} while (1);
2619	scsi_ulto2b(ranges * 16 + 6, &buf[0]);
2620	scsi_ulto2b(ranges * 16, &buf[2]);
2621
2622	scsi_unmap(&ccb->csio,
2623		   /*retries*/da_retry_count,
2624		   /*cbfcnp*/dadone,
2625		   /*tag_action*/MSG_SIMPLE_Q_TAG,
2626		   /*byte2*/0,
2627		   /*data_ptr*/ buf,
2628		   /*dxfer_len*/ ranges * 16 + 8,
2629		   /*sense_len*/SSD_FULL_SIZE,
2630		   da_default_timeout * 1000);
2631	ccb->ccb_h.ccb_state = DA_CCB_DELETE;
2632	ccb->ccb_h.flags |= CAM_UNLOCKED;
2633}
2634
2635static void
2636da_delete_trim(struct cam_periph *periph, union ccb *ccb, struct bio *bp)
2637{
2638	struct da_softc *softc = (struct da_softc *)periph->softc;
2639	struct bio *bp1;
2640	uint8_t *buf = softc->unmap_buf;
2641	uint64_t lastlba = (uint64_t)-1;
2642	uint64_t count;
2643	uint64_t lba;
2644	uint32_t lastcount = 0, c, requestcount;
2645	int ranges = 0, off, block_count;
2646
2647	softc->delete_running = 1;
2648	bzero(softc->unmap_buf, sizeof(softc->unmap_buf));
2649	bp1 = bp;
2650	do {
2651		bioq_remove(&softc->delete_queue, bp1);
2652		if (bp1 != bp)
2653			bioq_insert_tail(&softc->delete_run_queue, bp1);
2654		lba = bp1->bio_pblkno;
2655		count = bp1->bio_bcount / softc->params.secsize;
2656		requestcount = count;
2657
2658		/* Try to extend the previous range. */
2659		if (lba == lastlba) {
2660			c = min(count, ATA_DSM_RANGE_MAX - lastcount);
2661			lastcount += c;
2662			off = (ranges - 1) * 8;
2663			buf[off + 6] = lastcount & 0xff;
2664			buf[off + 7] = (lastcount >> 8) & 0xff;
2665			count -= c;
2666			lba += c;
2667		}
2668
2669		while (count > 0) {
2670			c = min(count, ATA_DSM_RANGE_MAX);
2671			off = ranges * 8;
2672
2673			buf[off + 0] = lba & 0xff;
2674			buf[off + 1] = (lba >> 8) & 0xff;
2675			buf[off + 2] = (lba >> 16) & 0xff;
2676			buf[off + 3] = (lba >> 24) & 0xff;
2677			buf[off + 4] = (lba >> 32) & 0xff;
2678			buf[off + 5] = (lba >> 40) & 0xff;
2679			buf[off + 6] = c & 0xff;
2680			buf[off + 7] = (c >> 8) & 0xff;
2681			lba += c;
2682			ranges++;
2683			count -= c;
2684			lastcount = c;
2685			if (count != 0 && ranges == softc->trim_max_ranges) {
2686				xpt_print(periph->path,
2687				    "%s issuing short delete %ld > %ld\n",
2688				    da_delete_method_desc[softc->delete_method],
2689				    requestcount,
2690				    (softc->trim_max_ranges - ranges) *
2691				    ATA_DSM_RANGE_MAX);
2692				break;
2693			}
2694		}
2695		lastlba = lba;
2696		bp1 = bioq_first(&softc->delete_queue);
2697		if (bp1 == NULL || bp1->bio_bcount / softc->params.secsize >
2698		    (softc->trim_max_ranges - ranges) * ATA_DSM_RANGE_MAX)
2699			break;
2700	} while (1);
2701
2702	block_count = (ranges + ATA_DSM_BLK_RANGES - 1) / ATA_DSM_BLK_RANGES;
2703	scsi_ata_trim(&ccb->csio,
2704		      /*retries*/da_retry_count,
2705		      /*cbfcnp*/dadone,
2706		      /*tag_action*/MSG_SIMPLE_Q_TAG,
2707		      block_count,
2708		      /*data_ptr*/buf,
2709		      /*dxfer_len*/block_count * ATA_DSM_BLK_SIZE,
2710		      /*sense_len*/SSD_FULL_SIZE,
2711		      da_default_timeout * 1000);
2712	ccb->ccb_h.ccb_state = DA_CCB_DELETE;
2713	ccb->ccb_h.flags |= CAM_UNLOCKED;
2714}
2715
2716/*
2717 * We calculate ws_max_blks here based off d_delmaxsize instead
2718 * of using softc->ws_max_blks as it is absolute max for the
2719 * device not the protocol max which may well be lower.
2720 */
2721static void
2722da_delete_ws(struct cam_periph *periph, union ccb *ccb, struct bio *bp)
2723{
2724	struct da_softc *softc;
2725	struct bio *bp1;
2726	uint64_t ws_max_blks;
2727	uint64_t lba;
2728	uint64_t count; /* forward compat with WS32 */
2729
2730	softc = (struct da_softc *)periph->softc;
2731	ws_max_blks = softc->disk->d_delmaxsize / softc->params.secsize;
2732	softc->delete_running = 1;
2733	lba = bp->bio_pblkno;
2734	count = 0;
2735	bp1 = bp;
2736	do {
2737		bioq_remove(&softc->delete_queue, bp1);
2738		if (bp1 != bp)
2739			bioq_insert_tail(&softc->delete_run_queue, bp1);
2740		count += bp1->bio_bcount / softc->params.secsize;
2741		if (count > ws_max_blks) {
2742			xpt_print(periph->path,
2743			    "%s issuing short delete %ld > %ld\n",
2744			    da_delete_method_desc[softc->delete_method],
2745			    count, ws_max_blks);
2746			count = min(count, ws_max_blks);
2747			break;
2748		}
2749		bp1 = bioq_first(&softc->delete_queue);
2750		if (bp1 == NULL || lba + count != bp1->bio_pblkno ||
2751		    count + bp1->bio_bcount /
2752		    softc->params.secsize > ws_max_blks)
2753			break;
2754	} while (1);
2755
2756	scsi_write_same(&ccb->csio,
2757			/*retries*/da_retry_count,
2758			/*cbfcnp*/dadone,
2759			/*tag_action*/MSG_SIMPLE_Q_TAG,
2760			/*byte2*/softc->delete_method ==
2761			    DA_DELETE_ZERO ? 0 : SWS_UNMAP,
2762			softc->delete_method == DA_DELETE_WS16 ? 16 : 10,
2763			/*lba*/lba,
2764			/*block_count*/count,
2765			/*data_ptr*/ __DECONST(void *, zero_region),
2766			/*dxfer_len*/ softc->params.secsize,
2767			/*sense_len*/SSD_FULL_SIZE,
2768			da_default_timeout * 1000);
2769	ccb->ccb_h.ccb_state = DA_CCB_DELETE;
2770	ccb->ccb_h.flags |= CAM_UNLOCKED;
2771}
2772
2773static int
2774cmd6workaround(union ccb *ccb)
2775{
2776	struct scsi_rw_6 cmd6;
2777	struct scsi_rw_10 *cmd10;
2778	struct da_softc *softc;
2779	u_int8_t *cdb;
2780	struct bio *bp;
2781	int frozen;
2782
2783	cdb = ccb->csio.cdb_io.cdb_bytes;
2784	softc = (struct da_softc *)xpt_path_periph(ccb->ccb_h.path)->softc;
2785
2786	if (ccb->ccb_h.ccb_state == DA_CCB_DELETE) {
2787		da_delete_methods old_method = softc->delete_method;
2788
2789		/*
2790		 * Typically there are two reasons for failure here
2791		 * 1. Delete method was detected as supported but isn't
2792		 * 2. Delete failed due to invalid params e.g. too big
2793		 *
2794		 * While we will attempt to choose an alternative delete method
2795		 * this may result in short deletes if the existing delete
2796		 * requests from geom are big for the new method choosen.
2797		 *
2798		 * This method assumes that the error which triggered this
2799		 * will not retry the io otherwise a panic will occur
2800		 */
2801		dadeleteflag(softc, old_method, 0);
2802		dadeletemethodchoose(softc, DA_DELETE_DISABLE);
2803		if (softc->delete_method == DA_DELETE_DISABLE)
2804			xpt_print(ccb->ccb_h.path,
2805				  "%s failed, disabling BIO_DELETE\n",
2806				  da_delete_method_desc[old_method]);
2807		else
2808			xpt_print(ccb->ccb_h.path,
2809				  "%s failed, switching to %s BIO_DELETE\n",
2810				  da_delete_method_desc[old_method],
2811				  da_delete_method_desc[softc->delete_method]);
2812
2813		while ((bp = bioq_takefirst(&softc->delete_run_queue)) != NULL)
2814			bioq_disksort(&softc->delete_queue, bp);
2815		bioq_disksort(&softc->delete_queue,
2816		    (struct bio *)ccb->ccb_h.ccb_bp);
2817		ccb->ccb_h.ccb_bp = NULL;
2818		return (0);
2819	}
2820
2821	/* Detect unsupported PREVENT ALLOW MEDIUM REMOVAL. */
2822	if ((ccb->ccb_h.flags & CAM_CDB_POINTER) == 0 &&
2823	    (*cdb == PREVENT_ALLOW) &&
2824	    (softc->quirks & DA_Q_NO_PREVENT) == 0) {
2825		if (bootverbose)
2826			xpt_print(ccb->ccb_h.path,
2827			    "PREVENT ALLOW MEDIUM REMOVAL not supported.\n");
2828		softc->quirks |= DA_Q_NO_PREVENT;
2829		return (0);
2830	}
2831
2832	/* Detect unsupported SYNCHRONIZE CACHE(10). */
2833	if ((ccb->ccb_h.flags & CAM_CDB_POINTER) == 0 &&
2834	    (*cdb == SYNCHRONIZE_CACHE) &&
2835	    (softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
2836		if (bootverbose)
2837			xpt_print(ccb->ccb_h.path,
2838			    "SYNCHRONIZE CACHE(10) not supported.\n");
2839		softc->quirks |= DA_Q_NO_SYNC_CACHE;
2840		softc->disk->d_flags &= ~DISKFLAG_CANFLUSHCACHE;
2841		return (0);
2842	}
2843
2844	/* Translation only possible if CDB is an array and cmd is R/W6 */
2845	if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0 ||
2846	    (*cdb != READ_6 && *cdb != WRITE_6))
2847		return 0;
2848
2849	xpt_print(ccb->ccb_h.path, "READ(6)/WRITE(6) not supported, "
2850	    "increasing minimum_cmd_size to 10.\n");
2851 	softc->minimum_cmd_size = 10;
2852
2853	bcopy(cdb, &cmd6, sizeof(struct scsi_rw_6));
2854	cmd10 = (struct scsi_rw_10 *)cdb;
2855	cmd10->opcode = (cmd6.opcode == READ_6) ? READ_10 : WRITE_10;
2856	cmd10->byte2 = 0;
2857	scsi_ulto4b(scsi_3btoul(cmd6.addr), cmd10->addr);
2858	cmd10->reserved = 0;
2859	scsi_ulto2b(cmd6.length, cmd10->length);
2860	cmd10->control = cmd6.control;
2861	ccb->csio.cdb_len = sizeof(*cmd10);
2862
2863	/* Requeue request, unfreezing queue if necessary */
2864	frozen = (ccb->ccb_h.status & CAM_DEV_QFRZN) != 0;
2865 	ccb->ccb_h.status = CAM_REQUEUE_REQ;
2866	xpt_action(ccb);
2867	if (frozen) {
2868		cam_release_devq(ccb->ccb_h.path,
2869				 /*relsim_flags*/0,
2870				 /*reduction*/0,
2871				 /*timeout*/0,
2872				 /*getcount_only*/0);
2873	}
2874	return (ERESTART);
2875}
2876
2877static void
2878dadone(struct cam_periph *periph, union ccb *done_ccb)
2879{
2880	struct da_softc *softc;
2881	struct ccb_scsiio *csio;
2882	u_int32_t  priority;
2883	da_ccb_state state;
2884
2885	softc = (struct da_softc *)periph->softc;
2886	priority = done_ccb->ccb_h.pinfo.priority;
2887
2888	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dadone\n"));
2889
2890	csio = &done_ccb->csio;
2891	state = csio->ccb_h.ccb_state & DA_CCB_TYPE_MASK;
2892	switch (state) {
2893	case DA_CCB_BUFFER_IO:
2894	case DA_CCB_DELETE:
2895	{
2896		struct bio *bp, *bp1;
2897
2898		cam_periph_lock(periph);
2899		bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
2900		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2901			int error;
2902			int sf;
2903
2904			if ((csio->ccb_h.ccb_state & DA_CCB_RETRY_UA) != 0)
2905				sf = SF_RETRY_UA;
2906			else
2907				sf = 0;
2908
2909			error = daerror(done_ccb, CAM_RETRY_SELTO, sf);
2910			if (error == ERESTART) {
2911				/*
2912				 * A retry was scheduled, so
2913				 * just return.
2914				 */
2915				cam_periph_unlock(periph);
2916				return;
2917			}
2918			bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
2919			if (error != 0) {
2920				int queued_error;
2921
2922				/*
2923				 * return all queued I/O with EIO, so that
2924				 * the client can retry these I/Os in the
2925				 * proper order should it attempt to recover.
2926				 */
2927				queued_error = EIO;
2928
2929				if (error == ENXIO
2930				 && (softc->flags & DA_FLAG_PACK_INVALID)== 0) {
2931					/*
2932					 * Catastrophic error.  Mark our pack as
2933					 * invalid.
2934					 */
2935					/*
2936					 * XXX See if this is really a media
2937					 * XXX change first?
2938					 */
2939					xpt_print(periph->path,
2940					    "Invalidating pack\n");
2941					softc->flags |= DA_FLAG_PACK_INVALID;
2942					queued_error = ENXIO;
2943				}
2944				bioq_flush(&softc->bio_queue, NULL,
2945					   queued_error);
2946				if (bp != NULL) {
2947					bp->bio_error = error;
2948					bp->bio_resid = bp->bio_bcount;
2949					bp->bio_flags |= BIO_ERROR;
2950				}
2951			} else if (bp != NULL) {
2952				if (state == DA_CCB_DELETE)
2953					bp->bio_resid = 0;
2954				else
2955					bp->bio_resid = csio->resid;
2956				bp->bio_error = 0;
2957				if (bp->bio_resid != 0)
2958					bp->bio_flags |= BIO_ERROR;
2959			}
2960			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
2961				cam_release_devq(done_ccb->ccb_h.path,
2962						 /*relsim_flags*/0,
2963						 /*reduction*/0,
2964						 /*timeout*/0,
2965						 /*getcount_only*/0);
2966		} else if (bp != NULL) {
2967			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
2968				panic("REQ_CMP with QFRZN");
2969			if (state == DA_CCB_DELETE)
2970				bp->bio_resid = 0;
2971			else
2972				bp->bio_resid = csio->resid;
2973			if (csio->resid > 0)
2974				bp->bio_flags |= BIO_ERROR;
2975			if (softc->error_inject != 0) {
2976				bp->bio_error = softc->error_inject;
2977				bp->bio_resid = bp->bio_bcount;
2978				bp->bio_flags |= BIO_ERROR;
2979				softc->error_inject = 0;
2980			}
2981		}
2982
2983		LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
2984		if (LIST_EMPTY(&softc->pending_ccbs))
2985			softc->flags |= DA_FLAG_WAS_OTAG;
2986
2987		xpt_release_ccb(done_ccb);
2988		if (state == DA_CCB_DELETE) {
2989			TAILQ_HEAD(, bio) queue;
2990
2991			TAILQ_INIT(&queue);
2992			TAILQ_CONCAT(&queue, &softc->delete_run_queue.queue, bio_queue);
2993			softc->delete_run_queue.insert_point = NULL;
2994			softc->delete_running = 0;
2995			daschedule(periph);
2996			cam_periph_unlock(periph);
2997			while ((bp1 = TAILQ_FIRST(&queue)) != NULL) {
2998				TAILQ_REMOVE(&queue, bp1, bio_queue);
2999				bp1->bio_error = bp->bio_error;
3000				if (bp->bio_flags & BIO_ERROR) {
3001					bp1->bio_flags |= BIO_ERROR;
3002					bp1->bio_resid = bp1->bio_bcount;
3003				} else
3004					bp1->bio_resid = 0;
3005				biodone(bp1);
3006			}
3007		} else
3008			cam_periph_unlock(periph);
3009		if (bp != NULL)
3010			biodone(bp);
3011		return;
3012	}
3013	case DA_CCB_PROBE_RC:
3014	case DA_CCB_PROBE_RC16:
3015	{
3016		struct	   scsi_read_capacity_data *rdcap;
3017		struct     scsi_read_capacity_data_long *rcaplong;
3018		char	   announce_buf[80];
3019		int	   lbp;
3020
3021		lbp = 0;
3022		rdcap = NULL;
3023		rcaplong = NULL;
3024		if (state == DA_CCB_PROBE_RC)
3025			rdcap =(struct scsi_read_capacity_data *)csio->data_ptr;
3026		else
3027			rcaplong = (struct scsi_read_capacity_data_long *)
3028				csio->data_ptr;
3029
3030		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3031			struct disk_params *dp;
3032			uint32_t block_size;
3033			uint64_t maxsector;
3034			u_int lbppbe;	/* LB per physical block exponent. */
3035			u_int lalba;	/* Lowest aligned LBA. */
3036
3037			if (state == DA_CCB_PROBE_RC) {
3038				block_size = scsi_4btoul(rdcap->length);
3039				maxsector = scsi_4btoul(rdcap->addr);
3040				lbppbe = 0;
3041				lalba = 0;
3042
3043				/*
3044				 * According to SBC-2, if the standard 10
3045				 * byte READ CAPACITY command returns 2^32,
3046				 * we should issue the 16 byte version of
3047				 * the command, since the device in question
3048				 * has more sectors than can be represented
3049				 * with the short version of the command.
3050				 */
3051				if (maxsector == 0xffffffff) {
3052					free(rdcap, M_SCSIDA);
3053					xpt_release_ccb(done_ccb);
3054					softc->state = DA_STATE_PROBE_RC16;
3055					xpt_schedule(periph, priority);
3056					return;
3057				}
3058			} else {
3059				block_size = scsi_4btoul(rcaplong->length);
3060				maxsector = scsi_8btou64(rcaplong->addr);
3061				lbppbe = rcaplong->prot_lbppbe & SRC16_LBPPBE;
3062				lalba = scsi_2btoul(rcaplong->lalba_lbp);
3063			}
3064
3065			/*
3066			 * Because GEOM code just will panic us if we
3067			 * give them an 'illegal' value we'll avoid that
3068			 * here.
3069			 */
3070			if (block_size == 0 && maxsector == 0) {
3071				block_size = 512;
3072				maxsector = -1;
3073			}
3074			if (block_size >= MAXPHYS || block_size == 0) {
3075				xpt_print(periph->path,
3076				    "unsupportable block size %ju\n",
3077				    (uintmax_t) block_size);
3078				announce_buf[0] = '\0';
3079				cam_periph_invalidate(periph);
3080			} else {
3081				/*
3082				 * We pass rcaplong into dasetgeom(),
3083				 * because it will only use it if it is
3084				 * non-NULL.
3085				 */
3086				dasetgeom(periph, block_size, maxsector,
3087					  rcaplong, sizeof(*rcaplong));
3088				lbp = (lalba & SRC16_LBPME_A);
3089				dp = &softc->params;
3090				snprintf(announce_buf, sizeof(announce_buf),
3091				        "%juMB (%ju %u byte sectors: %dH %dS/T "
3092                                        "%dC)", (uintmax_t)
3093	                                (((uintmax_t)dp->secsize *
3094				        dp->sectors) / (1024*1024)),
3095			                (uintmax_t)dp->sectors,
3096				        dp->secsize, dp->heads,
3097                                        dp->secs_per_track, dp->cylinders);
3098			}
3099		} else {
3100			int	error;
3101
3102			announce_buf[0] = '\0';
3103
3104			/*
3105			 * Retry any UNIT ATTENTION type errors.  They
3106			 * are expected at boot.
3107			 */
3108			error = daerror(done_ccb, CAM_RETRY_SELTO,
3109					SF_RETRY_UA|SF_NO_PRINT);
3110			if (error == ERESTART) {
3111				/*
3112				 * A retry was scheuled, so
3113				 * just return.
3114				 */
3115				return;
3116			} else if (error != 0) {
3117				int asc, ascq;
3118				int sense_key, error_code;
3119				int have_sense;
3120				cam_status status;
3121				struct ccb_getdev cgd;
3122
3123				/* Don't wedge this device's queue */
3124				status = done_ccb->ccb_h.status;
3125				if ((status & CAM_DEV_QFRZN) != 0)
3126					cam_release_devq(done_ccb->ccb_h.path,
3127							 /*relsim_flags*/0,
3128							 /*reduction*/0,
3129							 /*timeout*/0,
3130							 /*getcount_only*/0);
3131
3132
3133				xpt_setup_ccb(&cgd.ccb_h,
3134					      done_ccb->ccb_h.path,
3135					      CAM_PRIORITY_NORMAL);
3136				cgd.ccb_h.func_code = XPT_GDEV_TYPE;
3137				xpt_action((union ccb *)&cgd);
3138
3139				if (scsi_extract_sense_ccb(done_ccb,
3140				    &error_code, &sense_key, &asc, &ascq))
3141					have_sense = TRUE;
3142				else
3143					have_sense = FALSE;
3144
3145				/*
3146				 * If we tried READ CAPACITY(16) and failed,
3147				 * fallback to READ CAPACITY(10).
3148				 */
3149				if ((state == DA_CCB_PROBE_RC16) &&
3150				    (softc->flags & DA_FLAG_CAN_RC16) &&
3151				    (((csio->ccb_h.status & CAM_STATUS_MASK) ==
3152					CAM_REQ_INVALID) ||
3153				     ((have_sense) &&
3154				      (error_code == SSD_CURRENT_ERROR) &&
3155				      (sense_key == SSD_KEY_ILLEGAL_REQUEST)))) {
3156					softc->flags &= ~DA_FLAG_CAN_RC16;
3157					free(rdcap, M_SCSIDA);
3158					xpt_release_ccb(done_ccb);
3159					softc->state = DA_STATE_PROBE_RC;
3160					xpt_schedule(periph, priority);
3161					return;
3162				} else
3163				/*
3164				 * Attach to anything that claims to be a
3165				 * direct access or optical disk device,
3166				 * as long as it doesn't return a "Logical
3167				 * unit not supported" (0x25) error.
3168				 */
3169				if ((have_sense) && (asc != 0x25)
3170				 && (error_code == SSD_CURRENT_ERROR)) {
3171					const char *sense_key_desc;
3172					const char *asc_desc;
3173
3174					dasetgeom(periph, 512, -1, NULL, 0);
3175					scsi_sense_desc(sense_key, asc, ascq,
3176							&cgd.inq_data,
3177							&sense_key_desc,
3178							&asc_desc);
3179					snprintf(announce_buf,
3180					    sizeof(announce_buf),
3181						"Attempt to query device "
3182						"size failed: %s, %s",
3183						sense_key_desc,
3184						asc_desc);
3185				} else {
3186					if (have_sense)
3187						scsi_sense_print(
3188							&done_ccb->csio);
3189					else {
3190						xpt_print(periph->path,
3191						    "got CAM status %#x\n",
3192						    done_ccb->ccb_h.status);
3193					}
3194
3195					xpt_print(periph->path, "fatal error, "
3196					    "failed to attach to device\n");
3197
3198					/*
3199					 * Free up resources.
3200					 */
3201					cam_periph_invalidate(periph);
3202				}
3203			}
3204		}
3205		free(csio->data_ptr, M_SCSIDA);
3206		if (announce_buf[0] != '\0' &&
3207		    ((softc->flags & DA_FLAG_ANNOUNCED) == 0)) {
3208			/*
3209			 * Create our sysctl variables, now that we know
3210			 * we have successfully attached.
3211			 */
3212			/* increase the refcount */
3213			if (cam_periph_acquire(periph) == CAM_REQ_CMP) {
3214				taskqueue_enqueue(taskqueue_thread,
3215						  &softc->sysctl_task);
3216				xpt_announce_periph(periph, announce_buf);
3217				xpt_announce_quirks(periph, softc->quirks,
3218				    DA_Q_BIT_STRING);
3219			} else {
3220				xpt_print(periph->path, "fatal error, "
3221				    "could not acquire reference count\n");
3222			}
3223		}
3224
3225		/* We already probed the device. */
3226		if (softc->flags & DA_FLAG_PROBED) {
3227			daprobedone(periph, done_ccb);
3228			return;
3229		}
3230
3231		/* Ensure re-probe doesn't see old delete. */
3232		softc->delete_available = 0;
3233		if (lbp && (softc->quirks & DA_Q_NO_UNMAP) == 0) {
3234			/*
3235			 * Based on older SBC-3 spec revisions
3236			 * any of the UNMAP methods "may" be
3237			 * available via LBP given this flag so
3238			 * we flag all of them as availble and
3239			 * then remove those which further
3240			 * probes confirm aren't available
3241			 * later.
3242			 *
3243			 * We could also check readcap(16) p_type
3244			 * flag to exclude one or more invalid
3245			 * write same (X) types here
3246			 */
3247			dadeleteflag(softc, DA_DELETE_WS16, 1);
3248			dadeleteflag(softc, DA_DELETE_WS10, 1);
3249			dadeleteflag(softc, DA_DELETE_ZERO, 1);
3250			dadeleteflag(softc, DA_DELETE_UNMAP, 1);
3251
3252			xpt_release_ccb(done_ccb);
3253			softc->state = DA_STATE_PROBE_LBP;
3254			xpt_schedule(periph, priority);
3255			return;
3256		}
3257
3258		xpt_release_ccb(done_ccb);
3259		softc->state = DA_STATE_PROBE_BDC;
3260		xpt_schedule(periph, priority);
3261		return;
3262	}
3263	case DA_CCB_PROBE_LBP:
3264	{
3265		struct scsi_vpd_logical_block_prov *lbp;
3266
3267		lbp = (struct scsi_vpd_logical_block_prov *)csio->data_ptr;
3268
3269		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3270			/*
3271			 * T10/1799-D Revision 31 states at least one of these
3272			 * must be supported but we don't currently enforce this.
3273			 */
3274			dadeleteflag(softc, DA_DELETE_WS16,
3275				     (lbp->flags & SVPD_LBP_WS16));
3276			dadeleteflag(softc, DA_DELETE_WS10,
3277				     (lbp->flags & SVPD_LBP_WS10));
3278			dadeleteflag(softc, DA_DELETE_ZERO,
3279				     (lbp->flags & SVPD_LBP_WS10));
3280			dadeleteflag(softc, DA_DELETE_UNMAP,
3281				     (lbp->flags & SVPD_LBP_UNMAP));
3282		} else {
3283			int error;
3284			error = daerror(done_ccb, CAM_RETRY_SELTO,
3285					SF_RETRY_UA|SF_NO_PRINT);
3286			if (error == ERESTART)
3287				return;
3288			else if (error != 0) {
3289				if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
3290					/* Don't wedge this device's queue */
3291					cam_release_devq(done_ccb->ccb_h.path,
3292							 /*relsim_flags*/0,
3293							 /*reduction*/0,
3294							 /*timeout*/0,
3295							 /*getcount_only*/0);
3296				}
3297
3298				/*
3299				 * Failure indicates we don't support any SBC-3
3300				 * delete methods with UNMAP
3301				 */
3302			}
3303		}
3304
3305		free(lbp, M_SCSIDA);
3306		xpt_release_ccb(done_ccb);
3307		softc->state = DA_STATE_PROBE_BLK_LIMITS;
3308		xpt_schedule(periph, priority);
3309		return;
3310	}
3311	case DA_CCB_PROBE_BLK_LIMITS:
3312	{
3313		struct scsi_vpd_block_limits *block_limits;
3314
3315		block_limits = (struct scsi_vpd_block_limits *)csio->data_ptr;
3316
3317		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3318			uint32_t max_txfer_len = scsi_4btoul(
3319				block_limits->max_txfer_len);
3320			uint32_t max_unmap_lba_cnt = scsi_4btoul(
3321				block_limits->max_unmap_lba_cnt);
3322			uint32_t max_unmap_blk_cnt = scsi_4btoul(
3323				block_limits->max_unmap_blk_cnt);
3324			uint64_t ws_max_blks = scsi_8btou64(
3325				block_limits->max_write_same_length);
3326
3327			if (max_txfer_len != 0) {
3328				softc->disk->d_maxsize = MIN(softc->maxio,
3329				    (off_t)max_txfer_len * softc->params.secsize);
3330			}
3331
3332			/*
3333			 * We should already support UNMAP but we check lba
3334			 * and block count to be sure
3335			 */
3336			if (max_unmap_lba_cnt != 0x00L &&
3337			    max_unmap_blk_cnt != 0x00L) {
3338				softc->unmap_max_lba = max_unmap_lba_cnt;
3339				softc->unmap_max_ranges = min(max_unmap_blk_cnt,
3340					UNMAP_MAX_RANGES);
3341			} else {
3342				/*
3343				 * Unexpected UNMAP limits which means the
3344				 * device doesn't actually support UNMAP
3345				 */
3346				dadeleteflag(softc, DA_DELETE_UNMAP, 0);
3347			}
3348
3349			if (ws_max_blks != 0x00L)
3350				softc->ws_max_blks = ws_max_blks;
3351		} else {
3352			int error;
3353			error = daerror(done_ccb, CAM_RETRY_SELTO,
3354					SF_RETRY_UA|SF_NO_PRINT);
3355			if (error == ERESTART)
3356				return;
3357			else if (error != 0) {
3358				if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
3359					/* Don't wedge this device's queue */
3360					cam_release_devq(done_ccb->ccb_h.path,
3361							 /*relsim_flags*/0,
3362							 /*reduction*/0,
3363							 /*timeout*/0,
3364							 /*getcount_only*/0);
3365				}
3366
3367				/*
3368				 * Failure here doesn't mean UNMAP is not
3369				 * supported as this is an optional page.
3370				 */
3371				softc->unmap_max_lba = 1;
3372				softc->unmap_max_ranges = 1;
3373			}
3374		}
3375
3376		free(block_limits, M_SCSIDA);
3377		xpt_release_ccb(done_ccb);
3378		softc->state = DA_STATE_PROBE_BDC;
3379		xpt_schedule(periph, priority);
3380		return;
3381	}
3382	case DA_CCB_PROBE_BDC:
3383	{
3384		struct scsi_vpd_block_characteristics *bdc;
3385
3386		bdc = (struct scsi_vpd_block_characteristics *)csio->data_ptr;
3387
3388		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3389			/*
3390			 * Disable queue sorting for non-rotational media
3391			 * by default.
3392			 */
3393			u_int old_rate = softc->disk->d_rotation_rate;
3394
3395			softc->disk->d_rotation_rate =
3396				scsi_2btoul(bdc->medium_rotation_rate);
3397			if (softc->disk->d_rotation_rate ==
3398			    SVPD_BDC_RATE_NON_ROTATING) {
3399				softc->sort_io_queue = 0;
3400			}
3401			if (softc->disk->d_rotation_rate != old_rate) {
3402				disk_attr_changed(softc->disk,
3403				    "GEOM::rotation_rate", M_NOWAIT);
3404			}
3405		} else {
3406			int error;
3407			error = daerror(done_ccb, CAM_RETRY_SELTO,
3408					SF_RETRY_UA|SF_NO_PRINT);
3409			if (error == ERESTART)
3410				return;
3411			else if (error != 0) {
3412				if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
3413					/* Don't wedge this device's queue */
3414					cam_release_devq(done_ccb->ccb_h.path,
3415							 /*relsim_flags*/0,
3416							 /*reduction*/0,
3417							 /*timeout*/0,
3418							 /*getcount_only*/0);
3419				}
3420			}
3421		}
3422
3423		free(bdc, M_SCSIDA);
3424		xpt_release_ccb(done_ccb);
3425		softc->state = DA_STATE_PROBE_ATA;
3426		xpt_schedule(periph, priority);
3427		return;
3428	}
3429	case DA_CCB_PROBE_ATA:
3430	{
3431		int i;
3432		struct ata_params *ata_params;
3433		int16_t *ptr;
3434
3435		ata_params = (struct ata_params *)csio->data_ptr;
3436		ptr = (uint16_t *)ata_params;
3437
3438		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3439			uint16_t old_rate;
3440
3441			for (i = 0; i < sizeof(*ata_params) / 2; i++)
3442				ptr[i] = le16toh(ptr[i]);
3443			if (ata_params->support_dsm & ATA_SUPPORT_DSM_TRIM &&
3444			    (softc->quirks & DA_Q_NO_UNMAP) == 0) {
3445				dadeleteflag(softc, DA_DELETE_ATA_TRIM, 1);
3446				if (ata_params->max_dsm_blocks != 0)
3447					softc->trim_max_ranges = min(
3448					  softc->trim_max_ranges,
3449					  ata_params->max_dsm_blocks *
3450					  ATA_DSM_BLK_RANGES);
3451			}
3452			/*
3453			 * Disable queue sorting for non-rotational media
3454			 * by default.
3455			 */
3456			old_rate = softc->disk->d_rotation_rate;
3457			softc->disk->d_rotation_rate =
3458			    ata_params->media_rotation_rate;
3459			if (softc->disk->d_rotation_rate ==
3460			    ATA_RATE_NON_ROTATING) {
3461				softc->sort_io_queue = 0;
3462			}
3463
3464			if (softc->disk->d_rotation_rate != old_rate) {
3465				disk_attr_changed(softc->disk,
3466				    "GEOM::rotation_rate", M_NOWAIT);
3467			}
3468		} else {
3469			int error;
3470			error = daerror(done_ccb, CAM_RETRY_SELTO,
3471					SF_RETRY_UA|SF_NO_PRINT);
3472			if (error == ERESTART)
3473				return;
3474			else if (error != 0) {
3475				if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
3476					/* Don't wedge this device's queue */
3477					cam_release_devq(done_ccb->ccb_h.path,
3478							 /*relsim_flags*/0,
3479							 /*reduction*/0,
3480							 /*timeout*/0,
3481							 /*getcount_only*/0);
3482				}
3483			}
3484		}
3485
3486		free(ata_params, M_SCSIDA);
3487		daprobedone(periph, done_ccb);
3488		return;
3489	}
3490	case DA_CCB_DUMP:
3491		/* No-op.  We're polling */
3492		return;
3493	case DA_CCB_TUR:
3494	{
3495		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3496
3497			if (daerror(done_ccb, CAM_RETRY_SELTO,
3498			    SF_RETRY_UA | SF_NO_RECOVERY | SF_NO_PRINT) ==
3499			    ERESTART)
3500				return;
3501			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
3502				cam_release_devq(done_ccb->ccb_h.path,
3503						 /*relsim_flags*/0,
3504						 /*reduction*/0,
3505						 /*timeout*/0,
3506						 /*getcount_only*/0);
3507		}
3508		xpt_release_ccb(done_ccb);
3509		cam_periph_release_locked(periph);
3510		return;
3511	}
3512	default:
3513		break;
3514	}
3515	xpt_release_ccb(done_ccb);
3516}
3517
3518static void
3519dareprobe(struct cam_periph *periph)
3520{
3521	struct da_softc	  *softc;
3522	cam_status status;
3523
3524	softc = (struct da_softc *)periph->softc;
3525
3526	/* Probe in progress; don't interfere. */
3527	if (softc->state != DA_STATE_NORMAL)
3528		return;
3529
3530	status = cam_periph_acquire(periph);
3531	KASSERT(status == CAM_REQ_CMP,
3532	    ("dareprobe: cam_periph_acquire failed"));
3533
3534	if (softc->flags & DA_FLAG_CAN_RC16)
3535		softc->state = DA_STATE_PROBE_RC16;
3536	else
3537		softc->state = DA_STATE_PROBE_RC;
3538
3539	xpt_schedule(periph, CAM_PRIORITY_DEV);
3540}
3541
3542static int
3543daerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
3544{
3545	struct da_softc	  *softc;
3546	struct cam_periph *periph;
3547	int error, error_code, sense_key, asc, ascq;
3548
3549	periph = xpt_path_periph(ccb->ccb_h.path);
3550	softc = (struct da_softc *)periph->softc;
3551
3552 	/*
3553	 * Automatically detect devices that do not support
3554 	 * READ(6)/WRITE(6) and upgrade to using 10 byte cdbs.
3555 	 */
3556	error = 0;
3557	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INVALID) {
3558		error = cmd6workaround(ccb);
3559	} else if (scsi_extract_sense_ccb(ccb,
3560	    &error_code, &sense_key, &asc, &ascq)) {
3561		if (sense_key == SSD_KEY_ILLEGAL_REQUEST)
3562 			error = cmd6workaround(ccb);
3563		/*
3564		 * If the target replied with CAPACITY DATA HAS CHANGED UA,
3565		 * query the capacity and notify upper layers.
3566		 */
3567		else if (sense_key == SSD_KEY_UNIT_ATTENTION &&
3568		    asc == 0x2A && ascq == 0x09) {
3569			xpt_print(periph->path, "Capacity data has changed\n");
3570			softc->flags &= ~DA_FLAG_PROBED;
3571			dareprobe(periph);
3572			sense_flags |= SF_NO_PRINT;
3573		} else if (sense_key == SSD_KEY_UNIT_ATTENTION &&
3574		    asc == 0x28 && ascq == 0x00) {
3575			softc->flags &= ~DA_FLAG_PROBED;
3576			disk_media_changed(softc->disk, M_NOWAIT);
3577		} else if (sense_key == SSD_KEY_UNIT_ATTENTION &&
3578		    asc == 0x3F && ascq == 0x03) {
3579			xpt_print(periph->path, "INQUIRY data has changed\n");
3580			softc->flags &= ~DA_FLAG_PROBED;
3581			dareprobe(periph);
3582			sense_flags |= SF_NO_PRINT;
3583		} else if (sense_key == SSD_KEY_NOT_READY &&
3584		    asc == 0x3a && (softc->flags & DA_FLAG_PACK_INVALID) == 0) {
3585			softc->flags |= DA_FLAG_PACK_INVALID;
3586			disk_media_gone(softc->disk, M_NOWAIT);
3587		}
3588	}
3589	if (error == ERESTART)
3590		return (ERESTART);
3591
3592	/*
3593	 * XXX
3594	 * Until we have a better way of doing pack validation,
3595	 * don't treat UAs as errors.
3596	 */
3597	sense_flags |= SF_RETRY_UA;
3598	return(cam_periph_error(ccb, cam_flags, sense_flags,
3599				&softc->saved_ccb));
3600}
3601
3602static void
3603damediapoll(void *arg)
3604{
3605	struct cam_periph *periph = arg;
3606	struct da_softc *softc = periph->softc;
3607
3608	if (!softc->tur && LIST_EMPTY(&softc->pending_ccbs)) {
3609		if (cam_periph_acquire(periph) == CAM_REQ_CMP) {
3610			softc->tur = 1;
3611			daschedule(periph);
3612		}
3613	}
3614	/* Queue us up again */
3615	if (da_poll_period != 0)
3616		callout_schedule(&softc->mediapoll_c, da_poll_period * hz);
3617}
3618
3619static void
3620daprevent(struct cam_periph *periph, int action)
3621{
3622	struct	da_softc *softc;
3623	union	ccb *ccb;
3624	int	error;
3625
3626	softc = (struct da_softc *)periph->softc;
3627
3628	if (((action == PR_ALLOW)
3629	  && (softc->flags & DA_FLAG_PACK_LOCKED) == 0)
3630	 || ((action == PR_PREVENT)
3631	  && (softc->flags & DA_FLAG_PACK_LOCKED) != 0)) {
3632		return;
3633	}
3634
3635	ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3636
3637	scsi_prevent(&ccb->csio,
3638		     /*retries*/1,
3639		     /*cbcfp*/dadone,
3640		     MSG_SIMPLE_Q_TAG,
3641		     action,
3642		     SSD_FULL_SIZE,
3643		     5000);
3644
3645	error = cam_periph_runccb(ccb, daerror, CAM_RETRY_SELTO,
3646	    SF_RETRY_UA | SF_NO_PRINT, softc->disk->d_devstat);
3647
3648	if (error == 0) {
3649		if (action == PR_ALLOW)
3650			softc->flags &= ~DA_FLAG_PACK_LOCKED;
3651		else
3652			softc->flags |= DA_FLAG_PACK_LOCKED;
3653	}
3654
3655	xpt_release_ccb(ccb);
3656}
3657
3658static void
3659dasetgeom(struct cam_periph *periph, uint32_t block_len, uint64_t maxsector,
3660	  struct scsi_read_capacity_data_long *rcaplong, size_t rcap_len)
3661{
3662	struct ccb_calc_geometry ccg;
3663	struct da_softc *softc;
3664	struct disk_params *dp;
3665	u_int lbppbe, lalba;
3666	int error;
3667
3668	softc = (struct da_softc *)periph->softc;
3669
3670	dp = &softc->params;
3671	dp->secsize = block_len;
3672	dp->sectors = maxsector + 1;
3673	if (rcaplong != NULL) {
3674		lbppbe = rcaplong->prot_lbppbe & SRC16_LBPPBE;
3675		lalba = scsi_2btoul(rcaplong->lalba_lbp);
3676		lalba &= SRC16_LALBA_A;
3677	} else {
3678		lbppbe = 0;
3679		lalba = 0;
3680	}
3681
3682	if (lbppbe > 0) {
3683		dp->stripesize = block_len << lbppbe;
3684		dp->stripeoffset = (dp->stripesize - block_len * lalba) %
3685		    dp->stripesize;
3686	} else if (softc->quirks & DA_Q_4K) {
3687		dp->stripesize = 4096;
3688		dp->stripeoffset = 0;
3689	} else {
3690		dp->stripesize = 0;
3691		dp->stripeoffset = 0;
3692	}
3693	/*
3694	 * Have the controller provide us with a geometry
3695	 * for this disk.  The only time the geometry
3696	 * matters is when we boot and the controller
3697	 * is the only one knowledgeable enough to come
3698	 * up with something that will make this a bootable
3699	 * device.
3700	 */
3701	xpt_setup_ccb(&ccg.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
3702	ccg.ccb_h.func_code = XPT_CALC_GEOMETRY;
3703	ccg.block_size = dp->secsize;
3704	ccg.volume_size = dp->sectors;
3705	ccg.heads = 0;
3706	ccg.secs_per_track = 0;
3707	ccg.cylinders = 0;
3708	xpt_action((union ccb*)&ccg);
3709	if ((ccg.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3710		/*
3711		 * We don't know what went wrong here- but just pick
3712		 * a geometry so we don't have nasty things like divide
3713		 * by zero.
3714		 */
3715		dp->heads = 255;
3716		dp->secs_per_track = 255;
3717		dp->cylinders = dp->sectors / (255 * 255);
3718		if (dp->cylinders == 0) {
3719			dp->cylinders = 1;
3720		}
3721	} else {
3722		dp->heads = ccg.heads;
3723		dp->secs_per_track = ccg.secs_per_track;
3724		dp->cylinders = ccg.cylinders;
3725	}
3726
3727	/*
3728	 * If the user supplied a read capacity buffer, and if it is
3729	 * different than the previous buffer, update the data in the EDT.
3730	 * If it's the same, we don't bother.  This avoids sending an
3731	 * update every time someone opens this device.
3732	 */
3733	if ((rcaplong != NULL)
3734	 && (bcmp(rcaplong, &softc->rcaplong,
3735		  min(sizeof(softc->rcaplong), rcap_len)) != 0)) {
3736		struct ccb_dev_advinfo cdai;
3737
3738		xpt_setup_ccb(&cdai.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
3739		cdai.ccb_h.func_code = XPT_DEV_ADVINFO;
3740		cdai.buftype = CDAI_TYPE_RCAPLONG;
3741		cdai.flags |= CDAI_FLAG_STORE;
3742		cdai.bufsiz = rcap_len;
3743		cdai.buf = (uint8_t *)rcaplong;
3744		xpt_action((union ccb *)&cdai);
3745		if ((cdai.ccb_h.status & CAM_DEV_QFRZN) != 0)
3746			cam_release_devq(cdai.ccb_h.path, 0, 0, 0, FALSE);
3747		if (cdai.ccb_h.status != CAM_REQ_CMP) {
3748			xpt_print(periph->path, "%s: failed to set read "
3749				  "capacity advinfo\n", __func__);
3750			/* Use cam_error_print() to decode the status */
3751			cam_error_print((union ccb *)&cdai, CAM_ESF_CAM_STATUS,
3752					CAM_EPF_ALL);
3753		} else {
3754			bcopy(rcaplong, &softc->rcaplong,
3755			      min(sizeof(softc->rcaplong), rcap_len));
3756		}
3757	}
3758
3759	softc->disk->d_sectorsize = softc->params.secsize;
3760	softc->disk->d_mediasize = softc->params.secsize * (off_t)softc->params.sectors;
3761	softc->disk->d_stripesize = softc->params.stripesize;
3762	softc->disk->d_stripeoffset = softc->params.stripeoffset;
3763	/* XXX: these are not actually "firmware" values, so they may be wrong */
3764	softc->disk->d_fwsectors = softc->params.secs_per_track;
3765	softc->disk->d_fwheads = softc->params.heads;
3766	softc->disk->d_devstat->block_size = softc->params.secsize;
3767	softc->disk->d_devstat->flags &= ~DEVSTAT_BS_UNAVAILABLE;
3768
3769	error = disk_resize(softc->disk, M_NOWAIT);
3770	if (error != 0)
3771		xpt_print(periph->path, "disk_resize(9) failed, error = %d\n", error);
3772}
3773
3774static void
3775dasendorderedtag(void *arg)
3776{
3777	struct da_softc *softc = arg;
3778
3779	if (da_send_ordered) {
3780		if (!LIST_EMPTY(&softc->pending_ccbs)) {
3781			if ((softc->flags & DA_FLAG_WAS_OTAG) == 0)
3782				softc->flags |= DA_FLAG_NEED_OTAG;
3783			softc->flags &= ~DA_FLAG_WAS_OTAG;
3784		}
3785	}
3786	/* Queue us up again */
3787	callout_reset(&softc->sendordered_c,
3788	    (da_default_timeout * hz) / DA_ORDEREDTAG_INTERVAL,
3789	    dasendorderedtag, softc);
3790}
3791
3792/*
3793 * Step through all DA peripheral drivers, and if the device is still open,
3794 * sync the disk cache to physical media.
3795 */
3796static void
3797dashutdown(void * arg, int howto)
3798{
3799	struct cam_periph *periph;
3800	struct da_softc *softc;
3801	union ccb *ccb;
3802	int error;
3803
3804	CAM_PERIPH_FOREACH(periph, &dadriver) {
3805		softc = (struct da_softc *)periph->softc;
3806		if (SCHEDULER_STOPPED()) {
3807			/* If we paniced with the lock held, do not recurse. */
3808			if (!cam_periph_owned(periph) &&
3809			    (softc->flags & DA_FLAG_OPEN)) {
3810				dadump(softc->disk, NULL, 0, 0, 0);
3811			}
3812			continue;
3813		}
3814		cam_periph_lock(periph);
3815
3816		/*
3817		 * We only sync the cache if the drive is still open, and
3818		 * if the drive is capable of it..
3819		 */
3820		if (((softc->flags & DA_FLAG_OPEN) == 0)
3821		 || (softc->quirks & DA_Q_NO_SYNC_CACHE)) {
3822			cam_periph_unlock(periph);
3823			continue;
3824		}
3825
3826		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3827		scsi_synchronize_cache(&ccb->csio,
3828				       /*retries*/0,
3829				       /*cbfcnp*/dadone,
3830				       MSG_SIMPLE_Q_TAG,
3831				       /*begin_lba*/0, /* whole disk */
3832				       /*lb_count*/0,
3833				       SSD_FULL_SIZE,
3834				       60 * 60 * 1000);
3835
3836		error = cam_periph_runccb(ccb, daerror, /*cam_flags*/0,
3837		    /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY | SF_QUIET_IR,
3838		    softc->disk->d_devstat);
3839		if (error != 0)
3840			xpt_print(periph->path, "Synchronize cache failed\n");
3841		xpt_release_ccb(ccb);
3842		cam_periph_unlock(periph);
3843	}
3844}
3845
3846#else /* !_KERNEL */
3847
3848/*
3849 * XXX This is only left out of the kernel build to silence warnings.  If,
3850 * for some reason this function is used in the kernel, the ifdefs should
3851 * be moved so it is included both in the kernel and userland.
3852 */
3853void
3854scsi_format_unit(struct ccb_scsiio *csio, u_int32_t retries,
3855		 void (*cbfcnp)(struct cam_periph *, union ccb *),
3856		 u_int8_t tag_action, u_int8_t byte2, u_int16_t ileave,
3857		 u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
3858		 u_int32_t timeout)
3859{
3860	struct scsi_format_unit *scsi_cmd;
3861
3862	scsi_cmd = (struct scsi_format_unit *)&csio->cdb_io.cdb_bytes;
3863	scsi_cmd->opcode = FORMAT_UNIT;
3864	scsi_cmd->byte2 = byte2;
3865	scsi_ulto2b(ileave, scsi_cmd->interleave);
3866
3867	cam_fill_csio(csio,
3868		      retries,
3869		      cbfcnp,
3870		      /*flags*/ (dxfer_len > 0) ? CAM_DIR_OUT : CAM_DIR_NONE,
3871		      tag_action,
3872		      data_ptr,
3873		      dxfer_len,
3874		      sense_len,
3875		      sizeof(*scsi_cmd),
3876		      timeout);
3877}
3878
3879void
3880scsi_sanitize(struct ccb_scsiio *csio, u_int32_t retries,
3881	      void (*cbfcnp)(struct cam_periph *, union ccb *),
3882	      u_int8_t tag_action, u_int8_t byte2, u_int16_t control,
3883	      u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
3884	      u_int32_t timeout)
3885{
3886	struct scsi_sanitize *scsi_cmd;
3887
3888	scsi_cmd = (struct scsi_sanitize *)&csio->cdb_io.cdb_bytes;
3889	scsi_cmd->opcode = SANITIZE;
3890	scsi_cmd->byte2 = byte2;
3891	scsi_cmd->control = control;
3892	scsi_ulto2b(dxfer_len, scsi_cmd->length);
3893
3894	cam_fill_csio(csio,
3895		      retries,
3896		      cbfcnp,
3897		      /*flags*/ (dxfer_len > 0) ? CAM_DIR_OUT : CAM_DIR_NONE,
3898		      tag_action,
3899		      data_ptr,
3900		      dxfer_len,
3901		      sense_len,
3902		      sizeof(*scsi_cmd),
3903		      timeout);
3904}
3905
3906#endif /* _KERNEL */
3907