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