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