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