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