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