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