xref: /freebsd/sys/cam/scsi/scsi_da.c (revision f856af0466c076beef4ea9b15d088e1119a945b8)
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 static	disk_strategy_t	dastrategy;
472 static	dumper_t	dadump;
473 static	periph_init_t	dainit;
474 static	void		daasync(void *callback_arg, u_int32_t code,
475 				struct cam_path *path, void *arg);
476 static	void		dasysctlinit(void *context, int pending);
477 static	int		dacmdsizesysctl(SYSCTL_HANDLER_ARGS);
478 static	periph_ctor_t	daregister;
479 static	periph_dtor_t	dacleanup;
480 static	periph_start_t	dastart;
481 static	periph_oninv_t	daoninvalidate;
482 static	void		dadone(struct cam_periph *periph,
483 			       union ccb *done_ccb);
484 static  int		daerror(union ccb *ccb, u_int32_t cam_flags,
485 				u_int32_t sense_flags);
486 static void		daprevent(struct cam_periph *periph, int action);
487 static int		dagetcapacity(struct cam_periph *periph);
488 static void		dasetgeom(struct cam_periph *periph, uint32_t block_len,
489 				  uint64_t maxsector);
490 static timeout_t	dasendorderedtag;
491 static void		dashutdown(void *arg, int howto);
492 
493 #ifndef DA_DEFAULT_TIMEOUT
494 #define DA_DEFAULT_TIMEOUT 60	/* Timeout in seconds */
495 #endif
496 
497 #ifndef	DA_DEFAULT_RETRY
498 #define	DA_DEFAULT_RETRY	4
499 #endif
500 
501 #ifndef	DA_DEFAULT_SEND_ORDERED
502 #define	DA_DEFAULT_SEND_ORDERED	1
503 #endif
504 
505 
506 static int da_retry_count = DA_DEFAULT_RETRY;
507 static int da_default_timeout = DA_DEFAULT_TIMEOUT;
508 static int da_send_ordered = DA_DEFAULT_SEND_ORDERED;
509 
510 SYSCTL_NODE(_kern_cam, OID_AUTO, da, CTLFLAG_RD, 0,
511             "CAM Direct Access Disk driver");
512 SYSCTL_INT(_kern_cam_da, OID_AUTO, retry_count, CTLFLAG_RW,
513            &da_retry_count, 0, "Normal I/O retry count");
514 TUNABLE_INT("kern.cam.da.retry_count", &da_retry_count);
515 SYSCTL_INT(_kern_cam_da, OID_AUTO, default_timeout, CTLFLAG_RW,
516            &da_default_timeout, 0, "Normal I/O timeout (in seconds)");
517 TUNABLE_INT("kern.cam.da.default_timeout", &da_default_timeout);
518 SYSCTL_INT(_kern_cam_da, OID_AUTO, da_send_ordered, CTLFLAG_RW,
519            &da_send_ordered, 0, "Send Ordered Tags");
520 TUNABLE_INT("kern.cam.da.da_send_ordered", &da_send_ordered);
521 
522 /*
523  * DA_ORDEREDTAG_INTERVAL determines how often, relative
524  * to the default timeout, we check to see whether an ordered
525  * tagged transaction is appropriate to prevent simple tag
526  * starvation.  Since we'd like to ensure that there is at least
527  * 1/2 of the timeout length left for a starved transaction to
528  * complete after we've sent an ordered tag, we must poll at least
529  * four times in every timeout period.  This takes care of the worst
530  * case where a starved transaction starts during an interval that
531  * meets the requirement "don't send an ordered tag" test so it takes
532  * us two intervals to determine that a tag must be sent.
533  */
534 #ifndef DA_ORDEREDTAG_INTERVAL
535 #define DA_ORDEREDTAG_INTERVAL 4
536 #endif
537 
538 static struct periph_driver dadriver =
539 {
540 	dainit, "da",
541 	TAILQ_HEAD_INITIALIZER(dadriver.units), /* generation */ 0
542 };
543 
544 PERIPHDRIVER_DECLARE(da, dadriver);
545 
546 static SLIST_HEAD(,da_softc) softc_list;
547 
548 static int
549 daopen(struct disk *dp)
550 {
551 	struct cam_periph *periph;
552 	struct da_softc *softc;
553 	int unit;
554 	int error;
555 	int s;
556 
557 	s = splsoftcam();
558 	periph = (struct cam_periph *)dp->d_drv1;
559 	if (periph == NULL) {
560 		splx(s);
561 		return (ENXIO);
562 	}
563 	unit = periph->unit_number;
564 
565 	softc = (struct da_softc *)periph->softc;
566 
567 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
568 	    ("daopen: disk=%s%d (unit %d)\n", dp->d_name, dp->d_unit,
569 	     unit));
570 
571 	if ((error = cam_periph_lock(periph, PRIBIO|PCATCH)) != 0)
572 		return (error); /* error code from tsleep */
573 
574 	if (cam_periph_acquire(periph) != CAM_REQ_CMP)
575 		return(ENXIO);
576 	softc->flags |= DA_FLAG_OPEN;
577 
578 	if ((softc->flags & DA_FLAG_PACK_INVALID) != 0) {
579 		/* Invalidate our pack information. */
580 		softc->flags &= ~DA_FLAG_PACK_INVALID;
581 	}
582 	splx(s);
583 
584 	error = dagetcapacity(periph);
585 
586 	if (error == 0) {
587 
588 		softc->disk->d_sectorsize = softc->params.secsize;
589 		softc->disk->d_mediasize = softc->params.secsize * (off_t)softc->params.sectors;
590 		/* XXX: these are not actually "firmware" values, so they may be wrong */
591 		softc->disk->d_fwsectors = softc->params.secs_per_track;
592 		softc->disk->d_fwheads = softc->params.heads;
593 		softc->disk->d_devstat->block_size = softc->params.secsize;
594 		softc->disk->d_devstat->flags &= ~DEVSTAT_BS_UNAVAILABLE;
595 	}
596 
597 	if (error == 0) {
598 		if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0 &&
599 		    (softc->quirks & DA_Q_NO_PREVENT) == 0)
600 			daprevent(periph, PR_PREVENT);
601 	} else {
602 		softc->flags &= ~DA_FLAG_OPEN;
603 		cam_periph_release(periph);
604 	}
605 	cam_periph_unlock(periph);
606 	return (error);
607 }
608 
609 static int
610 daclose(struct disk *dp)
611 {
612 	struct	cam_periph *periph;
613 	struct	da_softc *softc;
614 	int	error;
615 
616 	periph = (struct cam_periph *)dp->d_drv1;
617 	if (periph == NULL)
618 		return (ENXIO);
619 
620 	softc = (struct da_softc *)periph->softc;
621 
622 	if ((error = cam_periph_lock(periph, PRIBIO)) != 0) {
623 		return (error); /* error code from tsleep */
624 	}
625 
626 	if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
627 		union	ccb *ccb;
628 
629 		ccb = cam_periph_getccb(periph, /*priority*/1);
630 
631 		scsi_synchronize_cache(&ccb->csio,
632 				       /*retries*/1,
633 				       /*cbfcnp*/dadone,
634 				       MSG_SIMPLE_Q_TAG,
635 				       /*begin_lba*/0,/* Cover the whole disk */
636 				       /*lb_count*/0,
637 				       SSD_FULL_SIZE,
638 				       5 * 60 * 1000);
639 
640 		cam_periph_runccb(ccb, /*error_routine*/NULL, /*cam_flags*/0,
641 				  /*sense_flags*/SF_RETRY_UA,
642 				  softc->disk->d_devstat);
643 
644 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
645 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
646 			     CAM_SCSI_STATUS_ERROR) {
647 				int asc, ascq;
648 				int sense_key, error_code;
649 
650 				scsi_extract_sense(&ccb->csio.sense_data,
651 						   &error_code,
652 						   &sense_key,
653 						   &asc, &ascq);
654 				if (sense_key != SSD_KEY_ILLEGAL_REQUEST)
655 					scsi_sense_print(&ccb->csio);
656 			} else {
657 				xpt_print(periph->path, "Synchronize cache "
658 				    "failed, status == 0x%x, scsi status == "
659 				    "0x%x\n", ccb->csio.ccb_h.status,
660 				    ccb->csio.scsi_status);
661 			}
662 		}
663 
664 		if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
665 			cam_release_devq(ccb->ccb_h.path,
666 					 /*relsim_flags*/0,
667 					 /*reduction*/0,
668 					 /*timeout*/0,
669 					 /*getcount_only*/0);
670 
671 		xpt_release_ccb(ccb);
672 
673 	}
674 
675 	if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0) {
676 		if ((softc->quirks & DA_Q_NO_PREVENT) == 0)
677 			daprevent(periph, PR_ALLOW);
678 		/*
679 		 * If we've got removeable media, mark the blocksize as
680 		 * unavailable, since it could change when new media is
681 		 * inserted.
682 		 */
683 		softc->disk->d_devstat->flags |= DEVSTAT_BS_UNAVAILABLE;
684 	}
685 
686 	softc->flags &= ~DA_FLAG_OPEN;
687 	cam_periph_unlock(periph);
688 	cam_periph_release(periph);
689 	return (0);
690 }
691 
692 /*
693  * Actually translate the requested transfer into one the physical driver
694  * can understand.  The transfer is described by a buf and will include
695  * only one physical transfer.
696  */
697 static void
698 dastrategy(struct bio *bp)
699 {
700 	struct cam_periph *periph;
701 	struct da_softc *softc;
702 	int    s;
703 
704 	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
705 	if (periph == NULL) {
706 		biofinish(bp, NULL, ENXIO);
707 		return;
708 	}
709 	softc = (struct da_softc *)periph->softc;
710 #if 0
711 	/*
712 	 * check it's not too big a transfer for our adapter
713 	 */
714 	scsi_minphys(bp,&sd_switch);
715 #endif
716 
717 	/*
718 	 * Mask interrupts so that the pack cannot be invalidated until
719 	 * after we are in the queue.  Otherwise, we might not properly
720 	 * clean up one of the buffers.
721 	 */
722 	s = splbio();
723 
724 	/*
725 	 * If the device has been made invalid, error out
726 	 */
727 	if ((softc->flags & DA_FLAG_PACK_INVALID)) {
728 		splx(s);
729 		biofinish(bp, NULL, ENXIO);
730 		return;
731 	}
732 
733 	/*
734 	 * Place it in the queue of disk activities for this disk
735 	 */
736 	bioq_disksort(&softc->bio_queue, bp);
737 
738 	splx(s);
739 
740 	/*
741 	 * Schedule ourselves for performing the work.
742 	 */
743 	xpt_schedule(periph, /* XXX priority */1);
744 
745 	return;
746 }
747 
748 static int
749 dadump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size_t length)
750 {
751 	struct	    cam_periph *periph;
752 	struct	    da_softc *softc;
753 	u_int	    secsize;
754 	struct	    ccb_scsiio csio;
755 	struct	    disk *dp;
756 
757 	dp = arg;
758 	periph = dp->d_drv1;
759 	if (periph == NULL)
760 		return (ENXIO);
761 	softc = (struct da_softc *)periph->softc;
762 	secsize = softc->params.secsize;
763 
764 	if ((softc->flags & DA_FLAG_PACK_INVALID) != 0)
765 		return (ENXIO);
766 
767 	if (length > 0) {
768 		xpt_setup_ccb(&csio.ccb_h, periph->path, /*priority*/1);
769 		csio.ccb_h.ccb_state = DA_CCB_DUMP;
770 		scsi_read_write(&csio,
771 				/*retries*/1,
772 				dadone,
773 				MSG_ORDERED_Q_TAG,
774 				/*read*/FALSE,
775 				/*byte2*/0,
776 				/*minimum_cmd_size*/ softc->minimum_cmd_size,
777 				offset / secsize,
778 				length / secsize,
779 				/*data_ptr*/(u_int8_t *) virtual,
780 				/*dxfer_len*/length,
781 				/*sense_len*/SSD_FULL_SIZE,
782 				DA_DEFAULT_TIMEOUT * 1000);
783 		xpt_polled_action((union ccb *)&csio);
784 
785 		if ((csio.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
786 			printf("Aborting dump due to I/O error.\n");
787 			if ((csio.ccb_h.status & CAM_STATUS_MASK) ==
788 			     CAM_SCSI_STATUS_ERROR)
789 				scsi_sense_print(&csio);
790 			else
791 				printf("status == 0x%x, scsi status == 0x%x\n",
792 				       csio.ccb_h.status, csio.scsi_status);
793 			return(EIO);
794 		}
795 		return(0);
796 	}
797 
798 	/*
799 	 * Sync the disk cache contents to the physical media.
800 	 */
801 	if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
802 
803 		xpt_setup_ccb(&csio.ccb_h, periph->path, /*priority*/1);
804 		csio.ccb_h.ccb_state = DA_CCB_DUMP;
805 		scsi_synchronize_cache(&csio,
806 				       /*retries*/1,
807 				       /*cbfcnp*/dadone,
808 				       MSG_SIMPLE_Q_TAG,
809 				       /*begin_lba*/0,/* Cover the whole disk */
810 				       /*lb_count*/0,
811 				       SSD_FULL_SIZE,
812 				       5 * 60 * 1000);
813 		xpt_polled_action((union ccb *)&csio);
814 
815 		if ((csio.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
816 			if ((csio.ccb_h.status & CAM_STATUS_MASK) ==
817 			     CAM_SCSI_STATUS_ERROR) {
818 				int asc, ascq;
819 				int sense_key, error_code;
820 
821 				scsi_extract_sense(&csio.sense_data,
822 						   &error_code,
823 						   &sense_key,
824 						   &asc, &ascq);
825 				if (sense_key != SSD_KEY_ILLEGAL_REQUEST)
826 					scsi_sense_print(&csio);
827 			} else {
828 				xpt_print(periph->path, "Synchronize cache "
829 				    "failed, status == 0x%x, scsi status == "
830 				    "0x%x\n", csio.ccb_h.status,
831 				    csio.scsi_status);
832 			}
833 		}
834 	}
835 	return (0);
836 }
837 
838 static void
839 dainit(void)
840 {
841 	cam_status status;
842 	struct cam_path *path;
843 
844 	SLIST_INIT(&softc_list);
845 
846 	/*
847 	 * Install a global async callback.  This callback will
848 	 * receive async callbacks like "new device found".
849 	 */
850 	status = xpt_create_path(&path, /*periph*/NULL, CAM_XPT_PATH_ID,
851 				 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
852 
853 	if (status == CAM_REQ_CMP) {
854 		struct ccb_setasync csa;
855 
856                 xpt_setup_ccb(&csa.ccb_h, path, /*priority*/5);
857                 csa.ccb_h.func_code = XPT_SASYNC_CB;
858                 csa.event_enable = AC_FOUND_DEVICE;
859                 csa.callback = daasync;
860                 csa.callback_arg = NULL;
861                 xpt_action((union ccb *)&csa);
862 		status = csa.ccb_h.status;
863                 xpt_free_path(path);
864         }
865 
866 	if (status != CAM_REQ_CMP) {
867 		printf("da: Failed to attach master async callback "
868 		       "due to status 0x%x!\n", status);
869 	} else if (da_send_ordered) {
870 
871 		/*
872 		 * Schedule a periodic event to occasionally send an
873 		 * ordered tag to a device.
874 		 */
875 		timeout(dasendorderedtag, NULL,
876 			(DA_DEFAULT_TIMEOUT * hz) / DA_ORDEREDTAG_INTERVAL);
877 
878 		/* Register our shutdown event handler */
879 		if ((EVENTHANDLER_REGISTER(shutdown_post_sync, dashutdown,
880 					   NULL, SHUTDOWN_PRI_DEFAULT)) == NULL)
881 		    printf("dainit: shutdown event registration failed!\n");
882 	}
883 }
884 
885 static void
886 daoninvalidate(struct cam_periph *periph)
887 {
888 	int s;
889 	struct da_softc *softc;
890 	struct ccb_setasync csa;
891 
892 	softc = (struct da_softc *)periph->softc;
893 
894 	/*
895 	 * De-register any async callbacks.
896 	 */
897 	xpt_setup_ccb(&csa.ccb_h, periph->path,
898 		      /* priority */ 5);
899 	csa.ccb_h.func_code = XPT_SASYNC_CB;
900 	csa.event_enable = 0;
901 	csa.callback = daasync;
902 	csa.callback_arg = periph;
903 	xpt_action((union ccb *)&csa);
904 
905 	softc->flags |= DA_FLAG_PACK_INVALID;
906 
907 	/*
908 	 * Although the oninvalidate() routines are always called at
909 	 * splsoftcam, we need to be at splbio() here to keep the buffer
910 	 * queue from being modified while we traverse it.
911 	 */
912 	s = splbio();
913 
914 	/*
915 	 * Return all queued I/O with ENXIO.
916 	 * XXX Handle any transactions queued to the card
917 	 *     with XPT_ABORT_CCB.
918 	 */
919 	bioq_flush(&softc->bio_queue, NULL, ENXIO);
920 	splx(s);
921 
922 	SLIST_REMOVE(&softc_list, softc, da_softc, links);
923 
924 	disk_gone(softc->disk);
925 	xpt_print(periph->path, "lost device\n");
926 }
927 
928 static void
929 dacleanup(struct cam_periph *periph)
930 {
931 	struct da_softc *softc;
932 
933 	softc = (struct da_softc *)periph->softc;
934 
935 	xpt_print(periph->path, "removing device entry\n");
936 	/*
937 	 * If we can't free the sysctl tree, oh well...
938 	 */
939 	if ((softc->flags & DA_FLAG_SCTX_INIT) != 0
940 	    && sysctl_ctx_free(&softc->sysctl_ctx) != 0) {
941 		xpt_print(periph->path, "can't remove sysctl context\n");
942 	}
943 	disk_destroy(softc->disk);
944 	free(softc, M_DEVBUF);
945 }
946 
947 static void
948 daasync(void *callback_arg, u_int32_t code,
949 	struct cam_path *path, void *arg)
950 {
951 	struct cam_periph *periph;
952 
953 	periph = (struct cam_periph *)callback_arg;
954 	switch (code) {
955 	case AC_FOUND_DEVICE:
956 	{
957 		struct ccb_getdev *cgd;
958 		cam_status status;
959 
960 		cgd = (struct ccb_getdev *)arg;
961 		if (cgd == NULL)
962 			break;
963 
964 		if (SID_TYPE(&cgd->inq_data) != T_DIRECT
965 		    && SID_TYPE(&cgd->inq_data) != T_RBC
966 		    && SID_TYPE(&cgd->inq_data) != T_OPTICAL)
967 			break;
968 
969 		/*
970 		 * Allocate a peripheral instance for
971 		 * this device and start the probe
972 		 * process.
973 		 */
974 		status = cam_periph_alloc(daregister, daoninvalidate,
975 					  dacleanup, dastart,
976 					  "da", CAM_PERIPH_BIO,
977 					  cgd->ccb_h.path, daasync,
978 					  AC_FOUND_DEVICE, cgd);
979 
980 		if (status != CAM_REQ_CMP
981 		 && status != CAM_REQ_INPROG)
982 			printf("daasync: Unable to attach to new device "
983 				"due to status 0x%x\n", status);
984 		break;
985 	}
986 	case AC_SENT_BDR:
987 	case AC_BUS_RESET:
988 	{
989 		struct da_softc *softc;
990 		struct ccb_hdr *ccbh;
991 		int s;
992 
993 		softc = (struct da_softc *)periph->softc;
994 		s = splsoftcam();
995 		/*
996 		 * Don't fail on the expected unit attention
997 		 * that will occur.
998 		 */
999 		softc->flags |= DA_FLAG_RETRY_UA;
1000 		LIST_FOREACH(ccbh, &softc->pending_ccbs, periph_links.le)
1001 			ccbh->ccb_state |= DA_CCB_RETRY_UA;
1002 		splx(s);
1003 		/* FALLTHROUGH*/
1004 	}
1005 	default:
1006 		cam_periph_async(periph, code, path, arg);
1007 		break;
1008 	}
1009 }
1010 
1011 static void
1012 dasysctlinit(void *context, int pending)
1013 {
1014 	struct cam_periph *periph;
1015 	struct da_softc *softc;
1016 	char tmpstr[80], tmpstr2[80];
1017 
1018 	periph = (struct cam_periph *)context;
1019 	softc = (struct da_softc *)periph->softc;
1020 
1021 	snprintf(tmpstr, sizeof(tmpstr), "CAM DA unit %d", periph->unit_number);
1022 	snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
1023 
1024 	mtx_lock(&Giant);
1025 	sysctl_ctx_init(&softc->sysctl_ctx);
1026 	softc->flags |= DA_FLAG_SCTX_INIT;
1027 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1028 		SYSCTL_STATIC_CHILDREN(_kern_cam_da), OID_AUTO, tmpstr2,
1029 		CTLFLAG_RD, 0, tmpstr);
1030 	if (softc->sysctl_tree == NULL) {
1031 		printf("dasysctlinit: unable to allocate sysctl tree\n");
1032 		mtx_unlock(&Giant);
1033 		return;
1034 	}
1035 
1036 	/*
1037 	 * Now register the sysctl handler, so the user can the value on
1038 	 * the fly.
1039 	 */
1040 	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1041 		OID_AUTO, "minimum_cmd_size", CTLTYPE_INT | CTLFLAG_RW,
1042 		&softc->minimum_cmd_size, 0, dacmdsizesysctl, "I",
1043 		"Minimum CDB size");
1044 
1045 	mtx_unlock(&Giant);
1046 }
1047 
1048 static int
1049 dacmdsizesysctl(SYSCTL_HANDLER_ARGS)
1050 {
1051 	int error, value;
1052 
1053 	value = *(int *)arg1;
1054 
1055 	error = sysctl_handle_int(oidp, &value, 0, req);
1056 
1057 	if ((error != 0)
1058 	 || (req->newptr == NULL))
1059 		return (error);
1060 
1061 	/*
1062 	 * Acceptable values here are 6, 10, 12 or 16.
1063 	 */
1064 	if (value < 6)
1065 		value = 6;
1066 	else if ((value > 6)
1067 	      && (value <= 10))
1068 		value = 10;
1069 	else if ((value > 10)
1070 	      && (value <= 12))
1071 		value = 12;
1072 	else if (value > 12)
1073 		value = 16;
1074 
1075 	*(int *)arg1 = value;
1076 
1077 	return (0);
1078 }
1079 
1080 static cam_status
1081 daregister(struct cam_periph *periph, void *arg)
1082 {
1083 	int s;
1084 	struct da_softc *softc;
1085 	struct ccb_setasync csa;
1086 	struct ccb_pathinq cpi;
1087 	struct ccb_getdev *cgd;
1088 	char tmpstr[80];
1089 	caddr_t match;
1090 
1091 	cgd = (struct ccb_getdev *)arg;
1092 	if (periph == NULL) {
1093 		printf("daregister: periph was NULL!!\n");
1094 		return(CAM_REQ_CMP_ERR);
1095 	}
1096 
1097 	if (cgd == NULL) {
1098 		printf("daregister: no getdev CCB, can't register device\n");
1099 		return(CAM_REQ_CMP_ERR);
1100 	}
1101 
1102 	softc = (struct da_softc *)malloc(sizeof(*softc), M_DEVBUF,
1103 	    M_NOWAIT|M_ZERO);
1104 
1105 	if (softc == NULL) {
1106 		printf("daregister: Unable to probe new device. "
1107 		       "Unable to allocate softc\n");
1108 		return(CAM_REQ_CMP_ERR);
1109 	}
1110 
1111 	LIST_INIT(&softc->pending_ccbs);
1112 	softc->state = DA_STATE_PROBE;
1113 	bioq_init(&softc->bio_queue);
1114 	if (SID_IS_REMOVABLE(&cgd->inq_data))
1115 		softc->flags |= DA_FLAG_PACK_REMOVABLE;
1116 	if ((cgd->inq_data.flags & SID_CmdQue) != 0)
1117 		softc->flags |= DA_FLAG_TAGGED_QUEUING;
1118 
1119 	periph->softc = softc;
1120 
1121 	/*
1122 	 * See if this device has any quirks.
1123 	 */
1124 	match = cam_quirkmatch((caddr_t)&cgd->inq_data,
1125 			       (caddr_t)da_quirk_table,
1126 			       sizeof(da_quirk_table)/sizeof(*da_quirk_table),
1127 			       sizeof(*da_quirk_table), scsi_inquiry_match);
1128 
1129 	if (match != NULL)
1130 		softc->quirks = ((struct da_quirk_entry *)match)->quirks;
1131 	else
1132 		softc->quirks = DA_Q_NONE;
1133 
1134 	/* Check if the SIM does not want 6 byte commands */
1135 	xpt_setup_ccb(&cpi.ccb_h, periph->path, /*priority*/1);
1136 	cpi.ccb_h.func_code = XPT_PATH_INQ;
1137 	xpt_action((union ccb *)&cpi);
1138 	if (cpi.ccb_h.status == CAM_REQ_CMP && (cpi.hba_misc & PIM_NO_6_BYTE))
1139 		softc->quirks |= DA_Q_NO_6_BYTE;
1140 
1141 	TASK_INIT(&softc->sysctl_task, 0, dasysctlinit, periph);
1142 
1143 	/*
1144 	 * RBC devices don't have to support READ(6), only READ(10).
1145 	 */
1146 	if (softc->quirks & DA_Q_NO_6_BYTE || SID_TYPE(&cgd->inq_data) == T_RBC)
1147 		softc->minimum_cmd_size = 10;
1148 	else
1149 		softc->minimum_cmd_size = 6;
1150 
1151 	/*
1152 	 * Load the user's default, if any.
1153 	 */
1154 	snprintf(tmpstr, sizeof(tmpstr), "kern.cam.da.%d.minimum_cmd_size",
1155 		 periph->unit_number);
1156 	TUNABLE_INT_FETCH(tmpstr, &softc->minimum_cmd_size);
1157 
1158 	/*
1159 	 * 6, 10, 12 and 16 are the currently permissible values.
1160 	 */
1161 	if (softc->minimum_cmd_size < 6)
1162 		softc->minimum_cmd_size = 6;
1163 	else if ((softc->minimum_cmd_size > 6)
1164 	      && (softc->minimum_cmd_size <= 10))
1165 		softc->minimum_cmd_size = 10;
1166 	else if ((softc->minimum_cmd_size > 10)
1167 	      && (softc->minimum_cmd_size <= 12))
1168 		softc->minimum_cmd_size = 12;
1169 	else if (softc->minimum_cmd_size > 12)
1170 		softc->minimum_cmd_size = 16;
1171 
1172 	/*
1173 	 * Block our timeout handler while we
1174 	 * add this softc to the dev list.
1175 	 */
1176 	s = splsoftclock();
1177 	SLIST_INSERT_HEAD(&softc_list, softc, links);
1178 	splx(s);
1179 
1180 	/*
1181 	 * Register this media as a disk
1182 	 */
1183 
1184 	softc->disk = disk_alloc();
1185 	softc->disk->d_open = daopen;
1186 	softc->disk->d_close = daclose;
1187 	softc->disk->d_strategy = dastrategy;
1188 	softc->disk->d_dump = dadump;
1189 	softc->disk->d_name = "da";
1190 	softc->disk->d_drv1 = periph;
1191 	softc->disk->d_maxsize = DFLTPHYS; /* XXX: probably not arbitrary */
1192 	softc->disk->d_unit = periph->unit_number;
1193 	softc->disk->d_flags = DISKFLAG_NEEDSGIANT;
1194 	if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0)
1195 		softc->disk->d_flags |= DISKFLAG_CANFLUSHCACHE;
1196 	disk_create(softc->disk, DISK_VERSION);
1197 
1198 	/*
1199 	 * Add async callbacks for bus reset and
1200 	 * bus device reset calls.  I don't bother
1201 	 * checking if this fails as, in most cases,
1202 	 * the system will function just fine without
1203 	 * them and the only alternative would be to
1204 	 * not attach the device on failure.
1205 	 */
1206 	xpt_setup_ccb(&csa.ccb_h, periph->path, /*priority*/5);
1207 	csa.ccb_h.func_code = XPT_SASYNC_CB;
1208 	csa.event_enable = AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE;
1209 	csa.callback = daasync;
1210 	csa.callback_arg = periph;
1211 	xpt_action((union ccb *)&csa);
1212 	/*
1213 	 * Lock this peripheral until we are setup.
1214 	 * This first call can't block
1215 	 */
1216 	(void)cam_periph_lock(periph, PRIBIO);
1217 	xpt_schedule(periph, /*priority*/5);
1218 
1219 	return(CAM_REQ_CMP);
1220 }
1221 
1222 static void
1223 dastart(struct cam_periph *periph, union ccb *start_ccb)
1224 {
1225 	struct da_softc *softc;
1226 
1227 	softc = (struct da_softc *)periph->softc;
1228 
1229 
1230 	switch (softc->state) {
1231 	case DA_STATE_NORMAL:
1232 	{
1233 		/* Pull a buffer from the queue and get going on it */
1234 		struct bio *bp;
1235 		int s;
1236 
1237 		/*
1238 		 * See if there is a buf with work for us to do..
1239 		 */
1240 		s = splbio();
1241 		bp = bioq_first(&softc->bio_queue);
1242 		if (periph->immediate_priority <= periph->pinfo.priority) {
1243 			CAM_DEBUG_PRINT(CAM_DEBUG_SUBTRACE,
1244 					("queuing for immediate ccb\n"));
1245 			start_ccb->ccb_h.ccb_state = DA_CCB_WAITING;
1246 			SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
1247 					  periph_links.sle);
1248 			periph->immediate_priority = CAM_PRIORITY_NONE;
1249 			splx(s);
1250 			wakeup(&periph->ccb_list);
1251 		} else if (bp == NULL) {
1252 			splx(s);
1253 			xpt_release_ccb(start_ccb);
1254 		} else {
1255 			int oldspl;
1256 			u_int8_t tag_code;
1257 
1258 			bioq_remove(&softc->bio_queue, bp);
1259 
1260 			if ((softc->flags & DA_FLAG_NEED_OTAG) != 0) {
1261 				softc->flags &= ~DA_FLAG_NEED_OTAG;
1262 				softc->ordered_tag_count++;
1263 				tag_code = MSG_ORDERED_Q_TAG;
1264 			} else {
1265 				tag_code = MSG_SIMPLE_Q_TAG;
1266 			}
1267 			switch (bp->bio_cmd) {
1268 			case BIO_READ:
1269 			case BIO_WRITE:
1270 				scsi_read_write(&start_ccb->csio,
1271 						/*retries*/da_retry_count,
1272 						/*cbfcnp*/dadone,
1273 						/*tag_action*/tag_code,
1274 						/*read_op*/bp->bio_cmd == BIO_READ,
1275 						/*byte2*/0,
1276 						softc->minimum_cmd_size,
1277 						/*lba*/bp->bio_pblkno,
1278 						/*block_count*/bp->bio_bcount /
1279 						softc->params.secsize,
1280 						/*data_ptr*/ bp->bio_data,
1281 						/*dxfer_len*/ bp->bio_bcount,
1282 						/*sense_len*/SSD_FULL_SIZE,
1283 						/*timeout*/da_default_timeout*1000);
1284 				break;
1285 			case BIO_FLUSH:
1286 				scsi_synchronize_cache(&start_ccb->csio,
1287 						       /*retries*/1,
1288 						       /*cbfcnp*/dadone,
1289 						       MSG_SIMPLE_Q_TAG,
1290 						       /*begin_lba*/0,/* Cover the whole disk */
1291 						       /*lb_count*/0,
1292 						       SSD_FULL_SIZE,
1293 						       /*timeout*/da_default_timeout*1000);
1294 				break;
1295 			}
1296 			start_ccb->ccb_h.ccb_state = DA_CCB_BUFFER_IO;
1297 
1298 			/*
1299 			 * Block out any asyncronous callbacks
1300 			 * while we touch the pending ccb list.
1301 			 */
1302 			oldspl = splcam();
1303 			LIST_INSERT_HEAD(&softc->pending_ccbs,
1304 					 &start_ccb->ccb_h, periph_links.le);
1305 			softc->outstanding_cmds++;
1306 			splx(oldspl);
1307 
1308 			/* We expect a unit attention from this device */
1309 			if ((softc->flags & DA_FLAG_RETRY_UA) != 0) {
1310 				start_ccb->ccb_h.ccb_state |= DA_CCB_RETRY_UA;
1311 				softc->flags &= ~DA_FLAG_RETRY_UA;
1312 			}
1313 
1314 			start_ccb->ccb_h.ccb_bp = bp;
1315 			bp = bioq_first(&softc->bio_queue);
1316 			splx(s);
1317 
1318 			xpt_action(start_ccb);
1319 		}
1320 
1321 		if (bp != NULL) {
1322 			/* Have more work to do, so ensure we stay scheduled */
1323 			xpt_schedule(periph, /* XXX priority */1);
1324 		}
1325 		break;
1326 	}
1327 	case DA_STATE_PROBE:
1328 	{
1329 		struct ccb_scsiio *csio;
1330 		struct scsi_read_capacity_data *rcap;
1331 
1332 		rcap = (struct scsi_read_capacity_data *)malloc(sizeof(*rcap),
1333 								M_TEMP,
1334 								M_NOWAIT);
1335 		if (rcap == NULL) {
1336 			printf("dastart: Couldn't malloc read_capacity data\n");
1337 			/* da_free_periph??? */
1338 			break;
1339 		}
1340 		csio = &start_ccb->csio;
1341 		scsi_read_capacity(csio,
1342 				   /*retries*/4,
1343 				   dadone,
1344 				   MSG_SIMPLE_Q_TAG,
1345 				   rcap,
1346 				   SSD_FULL_SIZE,
1347 				   /*timeout*/5000);
1348 		start_ccb->ccb_h.ccb_bp = NULL;
1349 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE;
1350 		xpt_action(start_ccb);
1351 		break;
1352 	}
1353 	case DA_STATE_PROBE2:
1354 	{
1355 		struct ccb_scsiio *csio;
1356 		struct scsi_read_capacity_data_long *rcaplong;
1357 
1358 		rcaplong = (struct scsi_read_capacity_data_long *)
1359 			malloc(sizeof(*rcaplong), M_TEMP, M_NOWAIT);
1360 		if (rcaplong == NULL) {
1361 			printf("dastart: Couldn't malloc read_capacity data\n");
1362 			/* da_free_periph??? */
1363 			break;
1364 		}
1365 		csio = &start_ccb->csio;
1366 		scsi_read_capacity_16(csio,
1367 				      /*retries*/ 4,
1368 				      /*cbfcnp*/ dadone,
1369 				      /*tag_action*/ MSG_SIMPLE_Q_TAG,
1370 				      /*lba*/ 0,
1371 				      /*reladr*/ 0,
1372 				      /*pmi*/ 0,
1373 				      rcaplong,
1374 				      /*sense_len*/ SSD_FULL_SIZE,
1375 				      /*timeout*/ 60000);
1376 		start_ccb->ccb_h.ccb_bp = NULL;
1377 		start_ccb->ccb_h.ccb_state = DA_CCB_PROBE2;
1378 		xpt_action(start_ccb);
1379 		break;
1380 	}
1381 	}
1382 }
1383 
1384 static int
1385 cmd6workaround(union ccb *ccb)
1386 {
1387 	struct scsi_rw_6 cmd6;
1388 	struct scsi_rw_10 *cmd10;
1389 	struct da_softc *softc;
1390 	u_int8_t *cdb;
1391 	int frozen;
1392 
1393 	cdb = ccb->csio.cdb_io.cdb_bytes;
1394 
1395 	/* Translation only possible if CDB is an array and cmd is R/W6 */
1396 	if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0 ||
1397 	    (*cdb != READ_6 && *cdb != WRITE_6))
1398 		return 0;
1399 
1400 	xpt_print(ccb->ccb_h.path, "READ(6)/WRITE(6) not supported, "
1401 	    "increasing minimum_cmd_size to 10.\n");
1402  	softc = (struct da_softc *)xpt_path_periph(ccb->ccb_h.path)->softc;
1403 	softc->minimum_cmd_size = 10;
1404 
1405 	bcopy(cdb, &cmd6, sizeof(struct scsi_rw_6));
1406 	cmd10 = (struct scsi_rw_10 *)cdb;
1407 	cmd10->opcode = (cmd6.opcode == READ_6) ? READ_10 : WRITE_10;
1408 	cmd10->byte2 = 0;
1409 	scsi_ulto4b(scsi_3btoul(cmd6.addr), cmd10->addr);
1410 	cmd10->reserved = 0;
1411 	scsi_ulto2b(cmd6.length, cmd10->length);
1412 	cmd10->control = cmd6.control;
1413 	ccb->csio.cdb_len = sizeof(*cmd10);
1414 
1415 	/* Requeue request, unfreezing queue if necessary */
1416 	frozen = (ccb->ccb_h.status & CAM_DEV_QFRZN) != 0;
1417  	ccb->ccb_h.status = CAM_REQUEUE_REQ;
1418 	xpt_action(ccb);
1419 	if (frozen) {
1420 		cam_release_devq(ccb->ccb_h.path,
1421 				 /*relsim_flags*/0,
1422 				 /*reduction*/0,
1423 				 /*timeout*/0,
1424 				 /*getcount_only*/0);
1425 	}
1426 	return (ERESTART);
1427 }
1428 
1429 static void
1430 dadone(struct cam_periph *periph, union ccb *done_ccb)
1431 {
1432 	struct da_softc *softc;
1433 	struct ccb_scsiio *csio;
1434 
1435 	softc = (struct da_softc *)periph->softc;
1436 	csio = &done_ccb->csio;
1437 	switch (csio->ccb_h.ccb_state & DA_CCB_TYPE_MASK) {
1438 	case DA_CCB_BUFFER_IO:
1439 	{
1440 		struct bio *bp;
1441 		int    oldspl;
1442 
1443 		bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
1444 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1445 			int error;
1446 			int s;
1447 			int sf;
1448 
1449 			if ((csio->ccb_h.ccb_state & DA_CCB_RETRY_UA) != 0)
1450 				sf = SF_RETRY_UA;
1451 			else
1452 				sf = 0;
1453 
1454 			error = daerror(done_ccb, CAM_RETRY_SELTO, sf);
1455 			if (error == ERESTART) {
1456 				/*
1457 				 * A retry was scheuled, so
1458 				 * just return.
1459 				 */
1460 				return;
1461 			}
1462 			if (error != 0) {
1463 
1464 				s = splbio();
1465 
1466 				if (error == ENXIO) {
1467 					/*
1468 					 * Catastrophic error.  Mark our pack as
1469 					 * invalid.
1470 					 */
1471 					/*
1472 					 * XXX See if this is really a media
1473 					 * XXX change first?
1474 					 */
1475 					xpt_print(periph->path,
1476 					    "Invalidating pack\n");
1477 					softc->flags |= DA_FLAG_PACK_INVALID;
1478 				}
1479 
1480 				/*
1481 				 * return all queued I/O with EIO, so that
1482 				 * the client can retry these I/Os in the
1483 				 * proper order should it attempt to recover.
1484 				 */
1485 				bioq_flush(&softc->bio_queue, NULL, EIO);
1486 				splx(s);
1487 				bp->bio_error = error;
1488 				bp->bio_resid = bp->bio_bcount;
1489 				bp->bio_flags |= BIO_ERROR;
1490 			} else {
1491 				bp->bio_resid = csio->resid;
1492 				bp->bio_error = 0;
1493 				if (bp->bio_resid != 0)
1494 					bp->bio_flags |= BIO_ERROR;
1495 			}
1496 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1497 				cam_release_devq(done_ccb->ccb_h.path,
1498 						 /*relsim_flags*/0,
1499 						 /*reduction*/0,
1500 						 /*timeout*/0,
1501 						 /*getcount_only*/0);
1502 		} else {
1503 			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1504 				panic("REQ_CMP with QFRZN");
1505 			bp->bio_resid = csio->resid;
1506 			if (csio->resid > 0)
1507 				bp->bio_flags |= BIO_ERROR;
1508 		}
1509 
1510 		/*
1511 		 * Block out any asyncronous callbacks
1512 		 * while we touch the pending ccb list.
1513 		 */
1514 		oldspl = splcam();
1515 		LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
1516 		softc->outstanding_cmds--;
1517 		if (softc->outstanding_cmds == 0)
1518 			softc->flags |= DA_FLAG_WENT_IDLE;
1519 		splx(oldspl);
1520 
1521 		biodone(bp);
1522 		break;
1523 	}
1524 	case DA_CCB_PROBE:
1525 	case DA_CCB_PROBE2:
1526 	{
1527 		struct	   scsi_read_capacity_data *rdcap;
1528 		struct     scsi_read_capacity_data_long *rcaplong;
1529 		char	   announce_buf[80];
1530 
1531 		rdcap = NULL;
1532 		rcaplong = NULL;
1533 		if (softc->state == DA_STATE_PROBE)
1534 			rdcap =(struct scsi_read_capacity_data *)csio->data_ptr;
1535 		else
1536 			rcaplong = (struct scsi_read_capacity_data_long *)
1537 				csio->data_ptr;
1538 
1539 		if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1540 			struct disk_params *dp;
1541 			uint32_t block_size;
1542 			uint64_t maxsector;
1543 
1544 			if (softc->state == DA_STATE_PROBE) {
1545 				block_size = scsi_4btoul(rdcap->length);
1546 				maxsector = scsi_4btoul(rdcap->addr);
1547 
1548 				/*
1549 				 * According to SBC-2, if the standard 10
1550 				 * byte READ CAPACITY command returns 2^32,
1551 				 * we should issue the 16 byte version of
1552 				 * the command, since the device in question
1553 				 * has more sectors than can be represented
1554 				 * with the short version of the command.
1555 				 */
1556 				if (maxsector == 0xffffffff) {
1557 					softc->state = DA_STATE_PROBE2;
1558 					free(rdcap, M_TEMP);
1559 					xpt_release_ccb(done_ccb);
1560 					xpt_schedule(periph, /*priority*/5);
1561 					return;
1562 				}
1563 			} else {
1564 				block_size = scsi_4btoul(rcaplong->length);
1565 				maxsector = scsi_8btou64(rcaplong->addr);
1566 			}
1567 
1568 			/*
1569 			 * Because GEOM code just will panic us if we
1570 			 * give them an 'illegal' value we'll avoid that
1571 			 * here.
1572 			 */
1573 			if (block_size >= MAXPHYS || block_size == 0) {
1574 				xpt_print(periph->path,
1575 				    "unsupportable block size %ju\n",
1576 				    (uintmax_t) block_size);
1577 				announce_buf[0] = '\0';
1578 				cam_periph_invalidate(periph);
1579 			} else {
1580 				dasetgeom(periph, block_size, maxsector);
1581 				dp = &softc->params;
1582 				snprintf(announce_buf, sizeof(announce_buf),
1583 				        "%juMB (%ju %u byte sectors: %dH %dS/T "
1584                                         "%dC)", (uintmax_t)
1585 	                                (((uintmax_t)dp->secsize *
1586 				        dp->sectors) / (1024*1024)),
1587 			                (uintmax_t)dp->sectors,
1588 				        dp->secsize, dp->heads,
1589                                         dp->secs_per_track, dp->cylinders);
1590 			}
1591 		} else {
1592 			int	error;
1593 
1594 			announce_buf[0] = '\0';
1595 
1596 			/*
1597 			 * Retry any UNIT ATTENTION type errors.  They
1598 			 * are expected at boot.
1599 			 */
1600 			error = daerror(done_ccb, CAM_RETRY_SELTO,
1601 					SF_RETRY_UA|SF_NO_PRINT);
1602 			if (error == ERESTART) {
1603 				/*
1604 				 * A retry was scheuled, so
1605 				 * just return.
1606 				 */
1607 				return;
1608 			} else if (error != 0) {
1609 				struct scsi_sense_data *sense;
1610 				int asc, ascq;
1611 				int sense_key, error_code;
1612 				int have_sense;
1613 				cam_status status;
1614 				struct ccb_getdev cgd;
1615 
1616 				/* Don't wedge this device's queue */
1617 				status = done_ccb->ccb_h.status;
1618 				if ((status & CAM_DEV_QFRZN) != 0)
1619 					cam_release_devq(done_ccb->ccb_h.path,
1620 							 /*relsim_flags*/0,
1621 							 /*reduction*/0,
1622 							 /*timeout*/0,
1623 							 /*getcount_only*/0);
1624 
1625 
1626 				xpt_setup_ccb(&cgd.ccb_h,
1627 					      done_ccb->ccb_h.path,
1628 					      /* priority */ 1);
1629 				cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1630 				xpt_action((union ccb *)&cgd);
1631 
1632 				if (((csio->ccb_h.flags & CAM_SENSE_PHYS) != 0)
1633 				 || ((csio->ccb_h.flags & CAM_SENSE_PTR) != 0)
1634 				 || ((status & CAM_AUTOSNS_VALID) == 0))
1635 					have_sense = FALSE;
1636 				else
1637 					have_sense = TRUE;
1638 
1639 				if (have_sense) {
1640 					sense = &csio->sense_data;
1641 					scsi_extract_sense(sense, &error_code,
1642 							   &sense_key,
1643 							   &asc, &ascq);
1644 				}
1645 				/*
1646 				 * Attach to anything that claims to be a
1647 				 * direct access or optical disk device,
1648 				 * as long as it doesn't return a "Logical
1649 				 * unit not supported" (0x25) error.
1650 				 */
1651 				if ((have_sense) && (asc != 0x25)
1652 				 && (error_code == SSD_CURRENT_ERROR)) {
1653 					const char *sense_key_desc;
1654 					const char *asc_desc;
1655 
1656 					scsi_sense_desc(sense_key, asc, ascq,
1657 							&cgd.inq_data,
1658 							&sense_key_desc,
1659 							&asc_desc);
1660 					snprintf(announce_buf,
1661 					    sizeof(announce_buf),
1662 						"Attempt to query device "
1663 						"size failed: %s, %s",
1664 						sense_key_desc,
1665 						asc_desc);
1666 				} else {
1667 					if (have_sense)
1668 						scsi_sense_print(
1669 							&done_ccb->csio);
1670 					else {
1671 						xpt_print(periph->path,
1672 						    "got CAM status %#x\n",
1673 						    done_ccb->ccb_h.status);
1674 					}
1675 
1676 					xpt_print(periph->path, "fatal error, "
1677 					    "failed to attach to device\n");
1678 
1679 					/*
1680 					 * Free up resources.
1681 					 */
1682 					cam_periph_invalidate(periph);
1683 				}
1684 			}
1685 		}
1686 		free(csio->data_ptr, M_TEMP);
1687 		if (announce_buf[0] != '\0') {
1688 			xpt_announce_periph(periph, announce_buf);
1689 			/*
1690 			 * Create our sysctl variables, now that we know
1691 			 * we have successfully attached.
1692 			 */
1693 			taskqueue_enqueue(taskqueue_thread,&softc->sysctl_task);
1694 		}
1695 		softc->state = DA_STATE_NORMAL;
1696 		/*
1697 		 * Since our peripheral may be invalidated by an error
1698 		 * above or an external event, we must release our CCB
1699 		 * before releasing the probe lock on the peripheral.
1700 		 * The peripheral will only go away once the last lock
1701 		 * is removed, and we need it around for the CCB release
1702 		 * operation.
1703 		 */
1704 		xpt_release_ccb(done_ccb);
1705 		cam_periph_unlock(periph);
1706 		return;
1707 	}
1708 	case DA_CCB_WAITING:
1709 	{
1710 		/* Caller will release the CCB */
1711 		wakeup(&done_ccb->ccb_h.cbfcnp);
1712 		return;
1713 	}
1714 	case DA_CCB_DUMP:
1715 		/* No-op.  We're polling */
1716 		return;
1717 	default:
1718 		break;
1719 	}
1720 	xpt_release_ccb(done_ccb);
1721 }
1722 
1723 static int
1724 daerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
1725 {
1726 	struct da_softc	  *softc;
1727 	struct cam_periph *periph;
1728 	int error;
1729 
1730 	periph = xpt_path_periph(ccb->ccb_h.path);
1731 	softc = (struct da_softc *)periph->softc;
1732 
1733  	/*
1734 	 * Automatically detect devices that do not support
1735  	 * READ(6)/WRITE(6) and upgrade to using 10 byte cdbs.
1736  	 */
1737 	error = 0;
1738 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INVALID) {
1739 		error = cmd6workaround(ccb);
1740 	} else if (((ccb->ccb_h.status & CAM_STATUS_MASK) ==
1741 		   CAM_SCSI_STATUS_ERROR)
1742 	 && (ccb->ccb_h.status & CAM_AUTOSNS_VALID)
1743 	 && (ccb->csio.scsi_status == SCSI_STATUS_CHECK_COND)
1744 	 && ((ccb->ccb_h.flags & CAM_SENSE_PHYS) == 0)
1745 	 && ((ccb->ccb_h.flags & CAM_SENSE_PTR) == 0)) {
1746 		int sense_key, error_code, asc, ascq;
1747 
1748  		scsi_extract_sense(&ccb->csio.sense_data,
1749 				   &error_code, &sense_key, &asc, &ascq);
1750 		if (sense_key == SSD_KEY_ILLEGAL_REQUEST)
1751  			error = cmd6workaround(ccb);
1752 	}
1753 	if (error == ERESTART)
1754 		return (ERESTART);
1755 
1756 	/*
1757 	 * XXX
1758 	 * Until we have a better way of doing pack validation,
1759 	 * don't treat UAs as errors.
1760 	 */
1761 	sense_flags |= SF_RETRY_UA;
1762 	return(cam_periph_error(ccb, cam_flags, sense_flags,
1763 				&softc->saved_ccb));
1764 }
1765 
1766 static void
1767 daprevent(struct cam_periph *periph, int action)
1768 {
1769 	struct	da_softc *softc;
1770 	union	ccb *ccb;
1771 	int	error;
1772 
1773 	softc = (struct da_softc *)periph->softc;
1774 
1775 	if (((action == PR_ALLOW)
1776 	  && (softc->flags & DA_FLAG_PACK_LOCKED) == 0)
1777 	 || ((action == PR_PREVENT)
1778 	  && (softc->flags & DA_FLAG_PACK_LOCKED) != 0)) {
1779 		return;
1780 	}
1781 
1782 	ccb = cam_periph_getccb(periph, /*priority*/1);
1783 
1784 	scsi_prevent(&ccb->csio,
1785 		     /*retries*/1,
1786 		     /*cbcfp*/dadone,
1787 		     MSG_SIMPLE_Q_TAG,
1788 		     action,
1789 		     SSD_FULL_SIZE,
1790 		     5000);
1791 
1792 	error = cam_periph_runccb(ccb, /*error_routine*/NULL, CAM_RETRY_SELTO,
1793 				  SF_RETRY_UA, softc->disk->d_devstat);
1794 
1795 	if (error == 0) {
1796 		if (action == PR_ALLOW)
1797 			softc->flags &= ~DA_FLAG_PACK_LOCKED;
1798 		else
1799 			softc->flags |= DA_FLAG_PACK_LOCKED;
1800 	}
1801 
1802 	xpt_release_ccb(ccb);
1803 }
1804 
1805 static int
1806 dagetcapacity(struct cam_periph *periph)
1807 {
1808 	struct da_softc *softc;
1809 	union ccb *ccb;
1810 	struct scsi_read_capacity_data *rcap;
1811 	struct scsi_read_capacity_data_long *rcaplong;
1812 	uint32_t block_len;
1813 	uint64_t maxsector;
1814 	int error;
1815 
1816 	softc = (struct da_softc *)periph->softc;
1817 	block_len = 0;
1818 	maxsector = 0;
1819 	error = 0;
1820 
1821 	/* Do a read capacity */
1822 	rcap = (struct scsi_read_capacity_data *)malloc(sizeof(*rcaplong),
1823 							M_TEMP,
1824 							M_WAITOK);
1825 
1826 	ccb = cam_periph_getccb(periph, /*priority*/1);
1827 	scsi_read_capacity(&ccb->csio,
1828 			   /*retries*/4,
1829 			   /*cbfncp*/dadone,
1830 			   MSG_SIMPLE_Q_TAG,
1831 			   rcap,
1832 			   SSD_FULL_SIZE,
1833 			   /*timeout*/60000);
1834 	ccb->ccb_h.ccb_bp = NULL;
1835 
1836 	error = cam_periph_runccb(ccb, daerror,
1837 				  /*cam_flags*/CAM_RETRY_SELTO,
1838 				  /*sense_flags*/SF_RETRY_UA,
1839 				  softc->disk->d_devstat);
1840 
1841 	if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1842 		cam_release_devq(ccb->ccb_h.path,
1843 				 /*relsim_flags*/0,
1844 				 /*reduction*/0,
1845 				 /*timeout*/0,
1846 				 /*getcount_only*/0);
1847 
1848 	if (error == 0) {
1849 		block_len = scsi_4btoul(rcap->length);
1850 		maxsector = scsi_4btoul(rcap->addr);
1851 
1852 		if (maxsector != 0xffffffff)
1853 			goto done;
1854 	} else
1855 		goto done;
1856 
1857 	rcaplong = (struct scsi_read_capacity_data_long *)rcap;
1858 
1859 	scsi_read_capacity_16(&ccb->csio,
1860 			      /*retries*/ 4,
1861 			      /*cbfcnp*/ dadone,
1862 			      /*tag_action*/ MSG_SIMPLE_Q_TAG,
1863 			      /*lba*/ 0,
1864 			      /*reladr*/ 0,
1865 			      /*pmi*/ 0,
1866 			      rcaplong,
1867 			      /*sense_len*/ SSD_FULL_SIZE,
1868 			      /*timeout*/ 60000);
1869 	ccb->ccb_h.ccb_bp = NULL;
1870 
1871 	error = cam_periph_runccb(ccb, daerror,
1872 				  /*cam_flags*/CAM_RETRY_SELTO,
1873 				  /*sense_flags*/SF_RETRY_UA,
1874 				  softc->disk->d_devstat);
1875 
1876 	if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1877 		cam_release_devq(ccb->ccb_h.path,
1878 				 /*relsim_flags*/0,
1879 				 /*reduction*/0,
1880 				 /*timeout*/0,
1881 				 /*getcount_only*/0);
1882 
1883 	if (error == 0) {
1884 		block_len = scsi_4btoul(rcaplong->length);
1885 		maxsector = scsi_8btou64(rcaplong->addr);
1886 	}
1887 
1888 done:
1889 
1890 	if (error == 0)
1891 		dasetgeom(periph, block_len, maxsector);
1892 
1893 	xpt_release_ccb(ccb);
1894 
1895 	free(rcap, M_TEMP);
1896 
1897 	return (error);
1898 }
1899 
1900 static void
1901 dasetgeom(struct cam_periph *periph, uint32_t block_len, uint64_t maxsector)
1902 {
1903 	struct ccb_calc_geometry ccg;
1904 	struct da_softc *softc;
1905 	struct disk_params *dp;
1906 
1907 	softc = (struct da_softc *)periph->softc;
1908 
1909 	dp = &softc->params;
1910 	dp->secsize = block_len;
1911 	dp->sectors = maxsector + 1;
1912 	/*
1913 	 * Have the controller provide us with a geometry
1914 	 * for this disk.  The only time the geometry
1915 	 * matters is when we boot and the controller
1916 	 * is the only one knowledgeable enough to come
1917 	 * up with something that will make this a bootable
1918 	 * device.
1919 	 */
1920 	xpt_setup_ccb(&ccg.ccb_h, periph->path, /*priority*/1);
1921 	ccg.ccb_h.func_code = XPT_CALC_GEOMETRY;
1922 	ccg.block_size = dp->secsize;
1923 	ccg.volume_size = dp->sectors;
1924 	ccg.heads = 0;
1925 	ccg.secs_per_track = 0;
1926 	ccg.cylinders = 0;
1927 	xpt_action((union ccb*)&ccg);
1928 	if ((ccg.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1929 		/*
1930 		 * We don't know what went wrong here- but just pick
1931 		 * a geometry so we don't have nasty things like divide
1932 		 * by zero.
1933 		 */
1934 		dp->heads = 255;
1935 		dp->secs_per_track = 255;
1936 		dp->cylinders = dp->sectors / (255 * 255);
1937 		if (dp->cylinders == 0) {
1938 			dp->cylinders = 1;
1939 		}
1940 	} else {
1941 		dp->heads = ccg.heads;
1942 		dp->secs_per_track = ccg.secs_per_track;
1943 		dp->cylinders = ccg.cylinders;
1944 	}
1945 }
1946 
1947 static void
1948 dasendorderedtag(void *arg)
1949 {
1950 	struct da_softc *softc;
1951 	int s;
1952 	if (da_send_ordered) {
1953 		for (softc = SLIST_FIRST(&softc_list);
1954 		     softc != NULL;
1955 		     softc = SLIST_NEXT(softc, links)) {
1956 			s = splsoftcam();
1957 			if ((softc->ordered_tag_count == 0)
1958 			 && ((softc->flags & DA_FLAG_WENT_IDLE) == 0)) {
1959 				softc->flags |= DA_FLAG_NEED_OTAG;
1960 			}
1961 			if (softc->outstanding_cmds > 0)
1962 				softc->flags &= ~DA_FLAG_WENT_IDLE;
1963 
1964 			softc->ordered_tag_count = 0;
1965 			splx(s);
1966 		}
1967 		/* Queue us up again */
1968 		timeout(dasendorderedtag, NULL,
1969 			(da_default_timeout * hz) / DA_ORDEREDTAG_INTERVAL);
1970 	}
1971 }
1972 
1973 /*
1974  * Step through all DA peripheral drivers, and if the device is still open,
1975  * sync the disk cache to physical media.
1976  */
1977 static void
1978 dashutdown(void * arg, int howto)
1979 {
1980 	struct cam_periph *periph;
1981 	struct da_softc *softc;
1982 
1983 	TAILQ_FOREACH(periph, &dadriver.units, unit_links) {
1984 		union ccb ccb;
1985 		softc = (struct da_softc *)periph->softc;
1986 
1987 		/*
1988 		 * We only sync the cache if the drive is still open, and
1989 		 * if the drive is capable of it..
1990 		 */
1991 		if (((softc->flags & DA_FLAG_OPEN) == 0)
1992 		 || (softc->quirks & DA_Q_NO_SYNC_CACHE))
1993 			continue;
1994 
1995 		xpt_setup_ccb(&ccb.ccb_h, periph->path, /*priority*/1);
1996 
1997 		ccb.ccb_h.ccb_state = DA_CCB_DUMP;
1998 		scsi_synchronize_cache(&ccb.csio,
1999 				       /*retries*/1,
2000 				       /*cbfcnp*/dadone,
2001 				       MSG_SIMPLE_Q_TAG,
2002 				       /*begin_lba*/0, /* whole disk */
2003 				       /*lb_count*/0,
2004 				       SSD_FULL_SIZE,
2005 				       60 * 60 * 1000);
2006 
2007 		xpt_polled_action(&ccb);
2008 
2009 		if ((ccb.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2010 			if (((ccb.ccb_h.status & CAM_STATUS_MASK) ==
2011 			     CAM_SCSI_STATUS_ERROR)
2012 			 && (ccb.csio.scsi_status == SCSI_STATUS_CHECK_COND)){
2013 				int error_code, sense_key, asc, ascq;
2014 
2015 				scsi_extract_sense(&ccb.csio.sense_data,
2016 						   &error_code, &sense_key,
2017 						   &asc, &ascq);
2018 
2019 				if (sense_key != SSD_KEY_ILLEGAL_REQUEST)
2020 					scsi_sense_print(&ccb.csio);
2021 			} else {
2022 				xpt_print(periph->path, "Synchronize "
2023 				    "cache failed, status == 0x%x, scsi status "
2024 				    "== 0x%x\n", ccb.ccb_h.status,
2025 				    ccb.csio.scsi_status);
2026 			}
2027 		}
2028 
2029 		if ((ccb.ccb_h.status & CAM_DEV_QFRZN) != 0)
2030 			cam_release_devq(ccb.ccb_h.path,
2031 					 /*relsim_flags*/0,
2032 					 /*reduction*/0,
2033 					 /*timeout*/0,
2034 					 /*getcount_only*/0);
2035 
2036 	}
2037 }
2038 
2039 #else /* !_KERNEL */
2040 
2041 /*
2042  * XXX This is only left out of the kernel build to silence warnings.  If,
2043  * for some reason this function is used in the kernel, the ifdefs should
2044  * be moved so it is included both in the kernel and userland.
2045  */
2046 void
2047 scsi_format_unit(struct ccb_scsiio *csio, u_int32_t retries,
2048 		 void (*cbfcnp)(struct cam_periph *, union ccb *),
2049 		 u_int8_t tag_action, u_int8_t byte2, u_int16_t ileave,
2050 		 u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
2051 		 u_int32_t timeout)
2052 {
2053 	struct scsi_format_unit *scsi_cmd;
2054 
2055 	scsi_cmd = (struct scsi_format_unit *)&csio->cdb_io.cdb_bytes;
2056 	scsi_cmd->opcode = FORMAT_UNIT;
2057 	scsi_cmd->byte2 = byte2;
2058 	scsi_ulto2b(ileave, scsi_cmd->interleave);
2059 
2060 	cam_fill_csio(csio,
2061 		      retries,
2062 		      cbfcnp,
2063 		      /*flags*/ (dxfer_len > 0) ? CAM_DIR_OUT : CAM_DIR_NONE,
2064 		      tag_action,
2065 		      data_ptr,
2066 		      dxfer_len,
2067 		      sense_len,
2068 		      sizeof(*scsi_cmd),
2069 		      timeout);
2070 }
2071 
2072 #endif /* _KERNEL */
2073