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