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