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