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