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