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