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