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