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