]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/cam/scsi/scsi_da.c
MFC 320694
[FreeBSD/stable/9.git] / sys / 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
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31
32 #include <sys/param.h>
33
34 #ifdef _KERNEL
35 #include <sys/systm.h>
36 #include <sys/kernel.h>
37 #include <sys/bio.h>
38 #include <sys/sysctl.h>
39 #include <sys/taskqueue.h>
40 #include <sys/lock.h>
41 #include <sys/mutex.h>
42 #include <sys/conf.h>
43 #include <sys/devicestat.h>
44 #include <sys/eventhandler.h>
45 #include <sys/malloc.h>
46 #include <sys/cons.h>
47 #include <sys/endian.h>
48 #include <sys/proc.h>
49 #include <geom/geom.h>
50 #include <geom/geom_disk.h>
51 #endif /* _KERNEL */
52
53 #ifndef _KERNEL
54 #include <stdio.h>
55 #include <string.h>
56 #endif /* _KERNEL */
57
58 #include <cam/cam.h>
59 #include <cam/cam_ccb.h>
60 #include <cam/cam_periph.h>
61 #include <cam/cam_xpt_periph.h>
62 #include <cam/cam_sim.h>
63
64 #include <cam/scsi/scsi_message.h>
65
66 #ifndef _KERNEL 
67 #include <cam/scsi/scsi_da.h>
68 #endif /* !_KERNEL */
69
70 #ifdef _KERNEL
71 typedef enum {
72         DA_STATE_PROBE_RC,
73         DA_STATE_PROBE_RC16,
74         DA_STATE_PROBE_LBP,
75         DA_STATE_PROBE_BLK_LIMITS,
76         DA_STATE_PROBE_BDC,
77         DA_STATE_PROBE_ATA,
78         DA_STATE_NORMAL
79 } da_state;
80
81 typedef enum {
82         DA_FLAG_PACK_INVALID    = 0x001,
83         DA_FLAG_NEW_PACK        = 0x002,
84         DA_FLAG_PACK_LOCKED     = 0x004,
85         DA_FLAG_PACK_REMOVABLE  = 0x008,
86         DA_FLAG_NEED_OTAG       = 0x020,
87         DA_FLAG_WAS_OTAG        = 0x040,
88         DA_FLAG_RETRY_UA        = 0x080,
89         DA_FLAG_OPEN            = 0x100,
90         DA_FLAG_SCTX_INIT       = 0x200,
91         DA_FLAG_CAN_RC16        = 0x400,
92         DA_FLAG_PROBED          = 0x800,
93         DA_FLAG_DIRTY           = 0x1000,
94         DA_FLAG_ANNOUNCED       = 0x2000
95 } da_flags;
96
97 typedef enum {
98         DA_Q_NONE               = 0x00,
99         DA_Q_NO_SYNC_CACHE      = 0x01,
100         DA_Q_NO_6_BYTE          = 0x02,
101         DA_Q_NO_PREVENT         = 0x04,
102         DA_Q_4K                 = 0x08,
103         DA_Q_NO_RC16            = 0x10,
104         DA_Q_NO_UNMAP           = 0x20,
105         DA_Q_RETRY_BUSY         = 0x40
106 } da_quirks;
107
108 #define DA_Q_BIT_STRING         \
109         "\020"                  \
110         "\001NO_SYNC_CACHE"     \
111         "\002NO_6_BYTE"         \
112         "\003NO_PREVENT"        \
113         "\0044K"                \
114         "\005NO_RC16"           \
115         "\006NO_UNMAP"          \
116         "\007RETRY_BUSY"
117
118 typedef enum {
119         DA_CCB_PROBE_RC         = 0x01,
120         DA_CCB_PROBE_RC16       = 0x02,
121         DA_CCB_PROBE_LBP        = 0x03,
122         DA_CCB_PROBE_BLK_LIMITS = 0x04,
123         DA_CCB_PROBE_BDC        = 0x05,
124         DA_CCB_PROBE_ATA        = 0x06,
125         DA_CCB_BUFFER_IO        = 0x07,
126         DA_CCB_WAITING          = 0x08,
127         DA_CCB_DUMP             = 0x0A,
128         DA_CCB_DELETE           = 0x0B,
129         DA_CCB_TUR              = 0x0C,
130         DA_CCB_TYPE_MASK        = 0x0F,
131         DA_CCB_RETRY_UA         = 0x10
132 } da_ccb_state;
133
134 /*
135  * Order here is important for method choice
136  *
137  * We prefer ATA_TRIM as tests run against a Sandforce 2281 SSD attached to
138  * LSI 2008 (mps) controller (FW: v12, Drv: v14) resulted 20% quicker deletes
139  * using ATA_TRIM than the corresponding UNMAP results for a real world mysql
140  * import taking 5mins.
141  *
142  */
143 typedef enum {
144         DA_DELETE_NONE,
145         DA_DELETE_DISABLE,
146         DA_DELETE_ATA_TRIM,
147         DA_DELETE_UNMAP,
148         DA_DELETE_WS16,
149         DA_DELETE_WS10,
150         DA_DELETE_ZERO,
151         DA_DELETE_MIN = DA_DELETE_ATA_TRIM,
152         DA_DELETE_MAX = DA_DELETE_ZERO
153 } da_delete_methods;
154
155 typedef void da_delete_func_t (struct cam_periph *periph, union ccb *ccb,
156                               struct bio *bp);
157 static da_delete_func_t da_delete_trim;
158 static da_delete_func_t da_delete_unmap;
159 static da_delete_func_t da_delete_ws;
160
161 static const void * da_delete_functions[] = {
162         NULL,
163         NULL,
164         da_delete_trim,
165         da_delete_unmap,
166         da_delete_ws,
167         da_delete_ws,
168         da_delete_ws
169 };
170
171 static const char *da_delete_method_names[] =
172     { "NONE", "DISABLE", "ATA_TRIM", "UNMAP", "WS16", "WS10", "ZERO" };
173 static const char *da_delete_method_desc[] =
174     { "NONE", "DISABLED", "ATA TRIM", "UNMAP", "WRITE SAME(16) with UNMAP",
175       "WRITE SAME(10) with UNMAP", "ZERO" };
176
177 /* Offsets into our private area for storing information */
178 #define ccb_state       ppriv_field0
179 #define ccb_bp          ppriv_ptr1
180
181 struct disk_params {
182         u_int8_t  heads;
183         u_int32_t cylinders;
184         u_int8_t  secs_per_track;
185         u_int32_t secsize;      /* Number of bytes/sector */
186         u_int64_t sectors;      /* total number sectors */
187         u_int     stripesize;
188         u_int     stripeoffset;
189 };
190
191 #define UNMAP_RANGE_MAX         0xffffffff
192 #define UNMAP_HEAD_SIZE         8
193 #define UNMAP_RANGE_SIZE        16
194 #define UNMAP_MAX_RANGES        2048 /* Protocol Max is 4095 */
195 #define UNMAP_BUF_SIZE          ((UNMAP_MAX_RANGES * UNMAP_RANGE_SIZE) + \
196                                 UNMAP_HEAD_SIZE)
197
198 #define WS10_MAX_BLKS           0xffff
199 #define WS16_MAX_BLKS           0xffffffff
200 #define ATA_TRIM_MAX_RANGES     ((UNMAP_BUF_SIZE / \
201         (ATA_DSM_RANGE_SIZE * ATA_DSM_BLK_SIZE)) * ATA_DSM_BLK_SIZE)
202
203 struct da_softc {
204         struct   bio_queue_head bio_queue;
205         struct   bio_queue_head delete_queue;
206         struct   bio_queue_head delete_run_queue;
207         LIST_HEAD(, ccb_hdr) pending_ccbs;
208         int      tur;                   /* TEST UNIT READY should be sent */
209         int      refcount;              /* Active xpt_action() calls */
210         da_state state;
211         da_flags flags; 
212         da_quirks quirks;
213         int      sort_io_queue;
214         int      minimum_cmd_size;
215         int      error_inject;
216         int      trim_max_ranges;
217         int      delete_running;
218         int      delete_available;      /* Delete methods possibly available */
219         u_int    maxio;
220         uint32_t                unmap_max_ranges;
221         uint32_t                unmap_max_lba; /* Max LBAs in UNMAP req */
222         uint64_t                ws_max_blks;
223         da_delete_methods       delete_method;
224         da_delete_func_t        *delete_func;
225         struct   disk_params params;
226         struct   disk *disk;
227         union    ccb saved_ccb;
228         struct task             sysctl_task;
229         struct sysctl_ctx_list  sysctl_ctx;
230         struct sysctl_oid       *sysctl_tree;
231         struct callout          sendordered_c;
232         uint64_t wwpn;
233         uint8_t  unmap_buf[UNMAP_BUF_SIZE];
234         struct scsi_read_capacity_data_long rcaplong;
235         struct callout          mediapoll_c;
236 };
237
238 #define dadeleteflag(softc, delete_method, enable)                      \
239         if (enable) {                                                   \
240                 softc->delete_available |= (1 << delete_method);        \
241         } else {                                                        \
242                 softc->delete_available &= ~(1 << delete_method);       \
243         }
244
245 struct da_quirk_entry {
246         struct scsi_inquiry_pattern inq_pat;
247         da_quirks quirks;
248 };
249
250 static const char quantum[] = "QUANTUM";
251 static const char microp[] = "MICROP";
252
253 static struct da_quirk_entry da_quirk_table[] =
254 {
255         /* SPI, FC devices */
256         {
257                 /*
258                  * Fujitsu M2513A MO drives.
259                  * Tested devices: M2513A2 firmware versions 1200 & 1300.
260                  * (dip switch selects whether T_DIRECT or T_OPTICAL device)
261                  * Reported by: W.Scholten <whs@xs4all.nl>
262                  */
263                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "FUJITSU", "M2513A", "*"},
264                 /*quirks*/ DA_Q_NO_SYNC_CACHE
265         },
266         {
267                 /* See above. */
268                 {T_OPTICAL, SIP_MEDIA_REMOVABLE, "FUJITSU", "M2513A", "*"},
269                 /*quirks*/ DA_Q_NO_SYNC_CACHE
270         },
271         {
272                 /*
273                  * This particular Fujitsu drive doesn't like the
274                  * synchronize cache command.
275                  * Reported by: Tom Jackson <toj@gorilla.net>
276                  */
277                 {T_DIRECT, SIP_MEDIA_FIXED, "FUJITSU", "M2954*", "*"},
278                 /*quirks*/ DA_Q_NO_SYNC_CACHE
279         },
280         {
281                 /*
282                  * This drive doesn't like the synchronize cache command
283                  * either.  Reported by: Matthew Jacob <mjacob@feral.com>
284                  * in NetBSD PR kern/6027, August 24, 1998.
285                  */
286                 {T_DIRECT, SIP_MEDIA_FIXED, microp, "2217*", "*"},
287                 /*quirks*/ DA_Q_NO_SYNC_CACHE
288         },
289         {
290                 /*
291                  * This drive doesn't like the synchronize cache command
292                  * either.  Reported by: Hellmuth Michaelis (hm@kts.org)
293                  * (PR 8882).
294                  */
295                 {T_DIRECT, SIP_MEDIA_FIXED, microp, "2112*", "*"},
296                 /*quirks*/ DA_Q_NO_SYNC_CACHE
297         },
298         {
299                 /*
300                  * Doesn't like the synchronize cache command.
301                  * Reported by: Blaz Zupan <blaz@gold.amis.net>
302                  */
303                 {T_DIRECT, SIP_MEDIA_FIXED, "NEC", "D3847*", "*"},
304                 /*quirks*/ DA_Q_NO_SYNC_CACHE
305         },
306         {
307                 /*
308                  * Doesn't like the synchronize cache command.
309                  * Reported by: Blaz Zupan <blaz@gold.amis.net>
310                  */
311                 {T_DIRECT, SIP_MEDIA_FIXED, quantum, "MAVERICK 540S", "*"},
312                 /*quirks*/ DA_Q_NO_SYNC_CACHE
313         },
314         {
315                 /*
316                  * Doesn't like the synchronize cache command.
317                  */
318                 {T_DIRECT, SIP_MEDIA_FIXED, quantum, "LPS525S", "*"},
319                 /*quirks*/ DA_Q_NO_SYNC_CACHE
320         },
321         {
322                 /*
323                  * Doesn't like the synchronize cache command.
324                  * Reported by: walter@pelissero.de
325                  */
326                 {T_DIRECT, SIP_MEDIA_FIXED, quantum, "LPS540S", "*"},
327                 /*quirks*/ DA_Q_NO_SYNC_CACHE
328         },
329         {
330                 /*
331                  * Doesn't work correctly with 6 byte reads/writes.
332                  * Returns illegal request, and points to byte 9 of the
333                  * 6-byte CDB.
334                  * Reported by:  Adam McDougall <bsdx@spawnet.com>
335                  */
336                 {T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 4*", "*"},
337                 /*quirks*/ DA_Q_NO_6_BYTE
338         },
339         {
340                 /* See above. */
341                 {T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 2*", "*"},
342                 /*quirks*/ DA_Q_NO_6_BYTE
343         },
344         {
345                 /*
346                  * Doesn't like the synchronize cache command.
347                  * Reported by: walter@pelissero.de
348                  */
349                 {T_DIRECT, SIP_MEDIA_FIXED, "CONNER", "CP3500*", "*"},
350                 /*quirks*/ DA_Q_NO_SYNC_CACHE
351         },
352         {
353                 /*
354                  * The CISS RAID controllers do not support SYNC_CACHE
355                  */
356                 {T_DIRECT, SIP_MEDIA_FIXED, "COMPAQ", "RAID*", "*"},
357                 /*quirks*/ DA_Q_NO_SYNC_CACHE
358         },
359         {
360                 /*
361                  * The STEC SSDs sometimes hang on UNMAP.
362                  */
363                 {T_DIRECT, SIP_MEDIA_FIXED, "STEC", "*", "*"},
364                 /*quirks*/ DA_Q_NO_UNMAP
365         },
366         {
367                 /*
368                  * VMware returns BUSY status when storage has transient
369                  * connectivity problems, so better wait.
370                  */
371                 {T_DIRECT, SIP_MEDIA_FIXED, "VMware", "Virtual disk", "*"},
372                 /*quirks*/ DA_Q_RETRY_BUSY
373         },
374         /* USB mass storage devices supported by umass(4) */
375         {
376                 /*
377                  * EXATELECOM (Sigmatel) i-Bead 100/105 USB Flash MP3 Player
378                  * PR: kern/51675
379                  */
380                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "EXATEL", "i-BEAD10*", "*"},
381                 /*quirks*/ DA_Q_NO_SYNC_CACHE
382         },
383         {
384                 /*
385                  * Power Quotient Int. (PQI) USB flash key
386                  * PR: kern/53067
387                  */
388                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "USB Flash Disk*",
389                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
390         },
391         {
392                 /*
393                  * Creative Nomad MUVO mp3 player (USB)
394                  * PR: kern/53094
395                  */
396                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "CREATIVE", "NOMAD_MUVO", "*"},
397                 /*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
398         },
399         {
400                 /*
401                  * Jungsoft NEXDISK USB flash key
402                  * PR: kern/54737
403                  */
404                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "JUNGSOFT", "NEXDISK*", "*"},
405                 /*quirks*/ DA_Q_NO_SYNC_CACHE
406         },
407         {
408                 /*
409                  * FreeDik USB Mini Data Drive
410                  * PR: kern/54786
411                  */
412                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "FreeDik*", "Mini Data Drive",
413                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
414         },
415         {
416                 /*
417                  * Sigmatel USB Flash MP3 Player
418                  * PR: kern/57046
419                  */
420                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "SigmaTel", "MSCN", "*"},
421                 /*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
422         },
423         {
424                 /*
425                  * Neuros USB Digital Audio Computer
426                  * PR: kern/63645
427                  */
428                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "NEUROS", "dig. audio comp.",
429                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
430         },
431         {
432                 /*
433                  * SEAGRAND NP-900 MP3 Player
434                  * PR: kern/64563
435                  */
436                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "SEAGRAND", "NP-900*", "*"},
437                 /*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
438         },
439         {
440                 /*
441                  * iRiver iFP MP3 player (with UMS Firmware)
442                  * PR: kern/54881, i386/63941, kern/66124
443                  */
444                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "iRiver", "iFP*", "*"},
445                 /*quirks*/ DA_Q_NO_SYNC_CACHE
446         },
447         {
448                 /*
449                  * Frontier Labs NEX IA+ Digital Audio Player, rev 1.10/0.01
450                  * PR: kern/70158
451                  */
452                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "FL" , "Nex*", "*"},
453                 /*quirks*/ DA_Q_NO_SYNC_CACHE
454         },
455         {
456                 /*
457                  * ZICPlay USB MP3 Player with FM
458                  * PR: kern/75057
459                  */
460                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "ACTIONS*" , "USB DISK*", "*"},
461                 /*quirks*/ DA_Q_NO_SYNC_CACHE
462         },
463         {
464                 /*
465                  * TEAC USB floppy mechanisms
466                  */
467                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "TEAC" , "FD-05*", "*"},
468                 /*quirks*/ DA_Q_NO_SYNC_CACHE
469         },
470         {
471                 /*
472                  * Kingston DataTraveler II+ USB Pen-Drive.
473                  * Reported by: Pawel Jakub Dawidek <pjd@FreeBSD.org>
474                  */
475                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston" , "DataTraveler II+",
476                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
477         },
478         {
479                 /*
480                  * USB DISK Pro PMAP
481                  * Reported by: jhs
482                  * PR: usb/96381
483                  */
484                 {T_DIRECT, SIP_MEDIA_REMOVABLE, " ", "USB DISK Pro", "PMAP"},
485                 /*quirks*/ DA_Q_NO_SYNC_CACHE
486         },
487         {
488                 /*
489                  * Motorola E398 Mobile Phone (TransFlash memory card).
490                  * Reported by: Wojciech A. Koszek <dunstan@FreeBSD.czest.pl>
491                  * PR: usb/89889
492                  */
493                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Motorola" , "Motorola Phone",
494                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
495         },
496         {
497                 /*
498                  * Qware BeatZkey! Pro
499                  * PR: usb/79164
500                  */
501                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "GENERIC", "USB DISK DEVICE",
502                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
503         },
504         {
505                 /*
506                  * Time DPA20B 1GB MP3 Player
507                  * PR: usb/81846
508                  */
509                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "USB2.0*", "(FS) FLASH DISK*",
510                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
511         },
512         {
513                 /*
514                  * Samsung USB key 128Mb
515                  * PR: usb/90081
516                  */
517                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "USB-DISK", "FreeDik-FlashUsb",
518                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
519         },
520         {
521                 /*
522                  * Kingston DataTraveler 2.0 USB Flash memory.
523                  * PR: usb/89196
524                  */
525                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston", "DataTraveler 2.0",
526                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
527         },
528         {
529                 /*
530                  * Creative MUVO Slim mp3 player (USB)
531                  * PR: usb/86131
532                  */
533                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "CREATIVE", "MuVo Slim",
534                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
535                 },
536         {
537                 /*
538                  * United MP5512 Portable MP3 Player (2-in-1 USB DISK/MP3)
539                  * PR: usb/80487
540                  */
541                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "MUSIC DISK",
542                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
543         },
544         {
545                 /*
546                  * SanDisk Micro Cruzer 128MB
547                  * PR: usb/75970
548                  */
549                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "SanDisk" , "Micro Cruzer",
550                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
551         },
552         {
553                 /*
554                  * TOSHIBA TransMemory USB sticks
555                  * PR: kern/94660
556                  */
557                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "TOSHIBA", "TransMemory",
558                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
559         },
560         {
561                 /*
562                  * PNY USB 3.0 Flash Drives
563                 */
564                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "PNY", "USB 3.0 FD*",
565                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE | DA_Q_NO_RC16
566         },
567         {
568                 /*
569                  * PNY USB Flash keys
570                  * PR: usb/75578, usb/72344, usb/65436 
571                  */
572                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "*" , "USB DISK*",
573                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
574         },
575         {
576                 /*
577                  * Genesys 6-in-1 Card Reader
578                  * PR: usb/94647
579                  */
580                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "STORAGE DEVICE*",
581                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
582         },
583         {
584                 /*
585                  * Rekam Digital CAMERA
586                  * PR: usb/98713
587                  */
588                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "CAMERA*", "4MP-9J6*",
589                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
590         },
591         {
592                 /*
593                  * iRiver H10 MP3 player
594                  * PR: usb/102547
595                  */
596                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "iriver", "H10*",
597                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
598         },
599         {
600                 /*
601                  * iRiver U10 MP3 player
602                  * PR: usb/92306
603                  */
604                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "iriver", "U10*",
605                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
606         },
607         {
608                 /*
609                  * X-Micro Flash Disk
610                  * PR: usb/96901
611                  */
612                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "X-Micro", "Flash Disk",
613                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
614         },
615         {
616                 /*
617                  * EasyMP3 EM732X USB 2.0 Flash MP3 Player
618                  * PR: usb/96546
619                  */
620                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "EM732X", "MP3 Player*",
621                 "1.00"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
622         },
623         {
624                 /*
625                  * Denver MP3 player
626                  * PR: usb/107101
627                  */
628                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "DENVER", "MP3 PLAYER",
629                  "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
630         },
631         {
632                 /*
633                  * Philips USB Key Audio KEY013
634                  * PR: usb/68412
635                  */
636                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "PHILIPS", "Key*", "*"},
637                 /*quirks*/ DA_Q_NO_SYNC_CACHE | DA_Q_NO_PREVENT
638         },
639         {
640                 /*
641                  * JNC MP3 Player
642                  * PR: usb/94439
643                  */
644                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "JNC*" , "MP3 Player*",
645                  "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
646         },
647         {
648                 /*
649                  * SAMSUNG MP0402H
650                  * PR: usb/108427
651                  */
652                 {T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "MP0402H", "*"},
653                 /*quirks*/ DA_Q_NO_SYNC_CACHE
654         },
655         {
656                 /*
657                  * I/O Magic USB flash - Giga Bank
658                  * PR: usb/108810
659                  */
660                 {T_DIRECT, SIP_MEDIA_FIXED, "GS-Magic", "stor*", "*"},
661                 /*quirks*/ DA_Q_NO_SYNC_CACHE
662         },
663         {
664                 /*
665                  * JoyFly 128mb USB Flash Drive
666                  * PR: 96133
667                  */
668                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "USB 2.0", "Flash Disk*",
669                  "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
670         },
671         {
672                 /*
673                  * ChipsBnk usb stick
674                  * PR: 103702
675                  */
676                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "ChipsBnk", "USB*",
677                  "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
678         },
679         {
680                 /*
681                  * Storcase (Kingston) InfoStation IFS FC2/SATA-R 201A
682                  * PR: 129858
683                  */
684                 {T_DIRECT, SIP_MEDIA_FIXED, "IFS", "FC2/SATA-R*",
685                  "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
686         },
687         {
688                 /*
689                  * Samsung YP-U3 mp3-player
690                  * PR: 125398
691                  */
692                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Samsung", "YP-U3",
693                  "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
694         },
695         {
696                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Netac", "OnlyDisk*",
697                  "2000"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
698         },
699         {
700                 /*
701                  * Sony Cyber-Shot DSC cameras
702                  * PR: usb/137035
703                  */
704                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Sony", "Sony DSC", "*"},
705                 /*quirks*/ DA_Q_NO_SYNC_CACHE | DA_Q_NO_PREVENT
706         },
707         {
708                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston", "DataTraveler G3",
709                  "1.00"}, /*quirks*/ DA_Q_NO_PREVENT
710         },
711         {
712                 /* At least several Transcent USB sticks lie on RC16. */
713                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "JetFlash", "Transcend*",
714                  "*"}, /*quirks*/ DA_Q_NO_RC16
715         },
716         /* ATA/SATA devices over SAS/USB/... */
717         {
718                 /* Hitachi Advanced Format (4k) drives */
719                 { T_DIRECT, SIP_MEDIA_FIXED, "Hitachi", "H??????????E3*", "*" },
720                 /*quirks*/DA_Q_4K
721         },
722         {
723                 /* Samsung Advanced Format (4k) drives */
724                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SAMSUNG HD155UI*", "*" },
725                 /*quirks*/DA_Q_4K
726         },
727         {
728                 /* Samsung Advanced Format (4k) drives */
729                 { T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "HD155UI*", "*" },
730                 /*quirks*/DA_Q_4K
731         },
732         {
733                 /* Samsung Advanced Format (4k) drives */
734                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SAMSUNG HD204UI*", "*" },
735                 /*quirks*/DA_Q_4K
736         },
737         {
738                 /* Samsung Advanced Format (4k) drives */
739                 { T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "HD204UI*", "*" },
740                 /*quirks*/DA_Q_4K
741         },
742         {
743                 /* Seagate Barracuda Green Advanced Format (4k) drives */
744                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST????DL*", "*" },
745                 /*quirks*/DA_Q_4K
746         },
747         {
748                 /* Seagate Barracuda Green Advanced Format (4k) drives */
749                 { T_DIRECT, SIP_MEDIA_FIXED, "ST????DL", "*", "*" },
750                 /*quirks*/DA_Q_4K
751         },
752         {
753                 /* Seagate Barracuda Green Advanced Format (4k) drives */
754                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST???DM*", "*" },
755                 /*quirks*/DA_Q_4K
756         },
757         {
758                 /* Seagate Barracuda Green Advanced Format (4k) drives */
759                 { T_DIRECT, SIP_MEDIA_FIXED, "ST???DM*", "*", "*" },
760                 /*quirks*/DA_Q_4K
761         },
762         {
763                 /* Seagate Barracuda Green Advanced Format (4k) drives */
764                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST????DM*", "*" },
765                 /*quirks*/DA_Q_4K
766         },
767         {
768                 /* Seagate Barracuda Green Advanced Format (4k) drives */
769                 { T_DIRECT, SIP_MEDIA_FIXED, "ST????DM", "*", "*" },
770                 /*quirks*/DA_Q_4K
771         },
772         {
773                 /* Seagate Momentus Advanced Format (4k) drives */
774                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9500423AS*", "*" },
775                 /*quirks*/DA_Q_4K
776         },
777         {
778                 /* Seagate Momentus Advanced Format (4k) drives */
779                 { T_DIRECT, SIP_MEDIA_FIXED, "ST950042", "3AS*", "*" },
780                 /*quirks*/DA_Q_4K
781         },
782         {
783                 /* Seagate Momentus Advanced Format (4k) drives */
784                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9500424AS*", "*" },
785                 /*quirks*/DA_Q_4K
786         },
787         {
788                 /* Seagate Momentus Advanced Format (4k) drives */
789                 { T_DIRECT, SIP_MEDIA_FIXED, "ST950042", "4AS*", "*" },
790                 /*quirks*/DA_Q_4K
791         },
792         {
793                 /* Seagate Momentus Advanced Format (4k) drives */
794                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9640423AS*", "*" },
795                 /*quirks*/DA_Q_4K
796         },
797         {
798                 /* Seagate Momentus Advanced Format (4k) drives */
799                 { T_DIRECT, SIP_MEDIA_FIXED, "ST964042", "3AS*", "*" },
800                 /*quirks*/DA_Q_4K
801         },
802         {
803                 /* Seagate Momentus Advanced Format (4k) drives */
804                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9640424AS*", "*" },
805                 /*quirks*/DA_Q_4K
806         },
807         {
808                 /* Seagate Momentus Advanced Format (4k) drives */
809                 { T_DIRECT, SIP_MEDIA_FIXED, "ST964042", "4AS*", "*" },
810                 /*quirks*/DA_Q_4K
811         },
812         {
813                 /* Seagate Momentus Advanced Format (4k) drives */
814                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750420AS*", "*" },
815                 /*quirks*/DA_Q_4K
816         },
817         {
818                 /* Seagate Momentus Advanced Format (4k) drives */
819                 { T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "0AS*", "*" },
820                 /*quirks*/DA_Q_4K
821         },
822         {
823                 /* Seagate Momentus Advanced Format (4k) drives */
824                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750422AS*", "*" },
825                 /*quirks*/DA_Q_4K
826         },
827         {
828                 /* Seagate Momentus Advanced Format (4k) drives */
829                 { T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "2AS*", "*" },
830                 /*quirks*/DA_Q_4K
831         },
832         {
833                 /* Seagate Momentus Advanced Format (4k) drives */
834                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750423AS*", "*" },
835                 /*quirks*/DA_Q_4K
836         },
837         {
838                 /* Seagate Momentus Advanced Format (4k) drives */
839                 { T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "3AS*", "*" },
840                 /*quirks*/DA_Q_4K
841         },
842         {
843                 /* Seagate Momentus Thin Advanced Format (4k) drives */
844                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST???LT*", "*" },
845                 /*quirks*/DA_Q_4K
846         },
847         {
848                 /* Seagate Momentus Thin Advanced Format (4k) drives */
849                 { T_DIRECT, SIP_MEDIA_FIXED, "ST???LT*", "*", "*" },
850                 /*quirks*/DA_Q_4K
851         },
852         {
853                 /* WDC Caviar Green Advanced Format (4k) drives */
854                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD????RS*", "*" },
855                 /*quirks*/DA_Q_4K
856         },
857         {
858                 /* WDC Caviar Green Advanced Format (4k) drives */
859                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "??RS*", "*" },
860                 /*quirks*/DA_Q_4K
861         },
862         {
863                 /* WDC Caviar Green Advanced Format (4k) drives */
864                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD????RX*", "*" },
865                 /*quirks*/DA_Q_4K
866         },
867         {
868                 /* WDC Caviar Green Advanced Format (4k) drives */
869                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "??RX*", "*" },
870                 /*quirks*/DA_Q_4K
871         },
872         {
873                 /* WDC Caviar Green Advanced Format (4k) drives */
874                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD??????RS*", "*" },
875                 /*quirks*/DA_Q_4K
876         },
877         {
878                 /* WDC Caviar Green Advanced Format (4k) drives */
879                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "????RS*", "*" },
880                 /*quirks*/DA_Q_4K
881         },
882         {
883                 /* WDC Caviar Green Advanced Format (4k) drives */
884                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD??????RX*", "*" },
885                 /*quirks*/DA_Q_4K
886         },
887         {
888                 /* WDC Caviar Green Advanced Format (4k) drives */
889                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "????RX*", "*" },
890                 /*quirks*/DA_Q_4K
891         },
892         {
893                 /* WDC Scorpio Black Advanced Format (4k) drives */
894                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD???PKT*", "*" },
895                 /*quirks*/DA_Q_4K
896         },
897         {
898                 /* WDC Scorpio Black Advanced Format (4k) drives */
899                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "?PKT*", "*" },
900                 /*quirks*/DA_Q_4K
901         },
902         {
903                 /* WDC Scorpio Black Advanced Format (4k) drives */
904                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD?????PKT*", "*" },
905                 /*quirks*/DA_Q_4K
906         },
907         {
908                 /* WDC Scorpio Black Advanced Format (4k) drives */
909                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "???PKT*", "*" },
910                 /*quirks*/DA_Q_4K
911         },
912         {
913                 /* WDC Scorpio Blue Advanced Format (4k) drives */
914                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD???PVT*", "*" },
915                 /*quirks*/DA_Q_4K
916         },
917         {
918                 /* WDC Scorpio Blue Advanced Format (4k) drives */
919                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "?PVT*", "*" },
920                 /*quirks*/DA_Q_4K
921         },
922         {
923                 /* WDC Scorpio Blue Advanced Format (4k) drives */
924                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD?????PVT*", "*" },
925                 /*quirks*/DA_Q_4K
926         },
927         {
928                 /* WDC Scorpio Blue Advanced Format (4k) drives */
929                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "???PVT*", "*" },
930                 /*quirks*/DA_Q_4K
931         },
932         {
933                 /*
934                  * Olympus FE-210 camera
935                  */
936                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "OLYMPUS", "FE210*",
937                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
938         },
939         {
940                 /*
941                  * LG UP3S MP3 player
942                  */
943                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "LG", "UP3S",
944                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
945         },
946         {
947                 /*
948                  * Laser MP3-2GA13 MP3 player
949                  */
950                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "USB 2.0", "(HS) Flash Disk",
951                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
952         },
953         {
954                 /*
955                  * LaCie external 250GB Hard drive des by Porsche
956                  * Submitted by: Ben Stuyts <ben@altesco.nl>
957                  * PR: 121474
958                  */
959                 {T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "HM250JI", "*"},
960                 /*quirks*/ DA_Q_NO_SYNC_CACHE
961         },
962         /* SATA SSDs */
963         {
964                 /*
965                  * Corsair Force 2 SSDs
966                  * 4k optimised & trim only works in 4k requests + 4k aligned
967                  */
968                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "Corsair CSSD-F*", "*" },
969                 /*quirks*/DA_Q_4K
970         },
971         {
972                 /*
973                  * Corsair Force 3 SSDs
974                  * 4k optimised & trim only works in 4k requests + 4k aligned
975                  */
976                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "Corsair Force 3*", "*" },
977                 /*quirks*/DA_Q_4K
978         },
979         {
980                 /*
981                  * Corsair Neutron GTX SSDs
982                  * 4k optimised & trim only works in 4k requests + 4k aligned
983                  */
984                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair Neutron GTX*", "*" },
985                 /*quirks*/DA_Q_4K
986         },
987         {
988                 /*
989                  * Corsair Force GT SSDs
990                  * 4k optimised & trim only works in 4k requests + 4k aligned
991                  */
992                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "Corsair Force GT*", "*" },
993                 /*quirks*/DA_Q_4K
994         },
995         {
996                 /*
997                  * Crucial M4 SSDs
998                  * 4k optimised & trim only works in 4k requests + 4k aligned
999                  */
1000                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "M4-CT???M4SSD2*", "*" },
1001                 /*quirks*/DA_Q_4K
1002         },
1003         {
1004                 /*
1005                  * Crucial RealSSD C300 SSDs
1006                  * 4k optimised
1007                  */
1008                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "C300-CTFDDAC???MAG*",
1009                 "*" }, /*quirks*/DA_Q_4K
1010         },
1011         {
1012                 /*
1013                  * Intel 320 Series SSDs
1014                  * 4k optimised & trim only works in 4k requests + 4k aligned
1015                  */
1016                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "INTEL SSDSA2CW*", "*" },
1017                 /*quirks*/DA_Q_4K
1018         },
1019         {
1020                 /*
1021                  * Intel 330 Series SSDs
1022                  * 4k optimised & trim only works in 4k requests + 4k aligned
1023                  */
1024                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "INTEL SSDSC2CT*", "*" },
1025                 /*quirks*/DA_Q_4K
1026         },
1027         {
1028                 /*
1029                  * Intel 510 Series SSDs
1030                  * 4k optimised & trim only works in 4k requests + 4k aligned
1031                  */
1032                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "INTEL SSDSC2MH*", "*" },
1033                 /*quirks*/DA_Q_4K
1034         },
1035         {
1036                 /*
1037                  * Intel 520 Series SSDs
1038                  * 4k optimised & trim only works in 4k requests + 4k aligned
1039                  */
1040                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "INTEL SSDSC2BW*", "*" },
1041                 /*quirks*/DA_Q_4K
1042         },
1043         {
1044                 /*
1045                  * Intel X25-M Series SSDs
1046                  * 4k optimised & trim only works in 4k requests + 4k aligned
1047                  */
1048                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "INTEL SSDSA2M*", "*" },
1049                 /*quirks*/DA_Q_4K
1050         },
1051         {
1052                 /*
1053                  * Kingston E100 Series SSDs
1054                  * 4k optimised & trim only works in 4k requests + 4k aligned
1055                  */
1056                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "KINGSTON SE100S3*", "*" },
1057                 /*quirks*/DA_Q_4K
1058         },
1059         {
1060                 /*
1061                  * Kingston HyperX 3k SSDs
1062                  * 4k optimised & trim only works in 4k requests + 4k aligned
1063                  */
1064                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "KINGSTON SH103S3*", "*" },
1065                 /*quirks*/DA_Q_4K
1066         },
1067         {
1068                 /*
1069                  * Marvell SSDs (entry taken from OpenSolaris)
1070                  * 4k optimised & trim only works in 4k requests + 4k aligned
1071                  */
1072                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "MARVELL SD88SA02*", "*" },
1073                 /*quirks*/DA_Q_4K
1074         },
1075         {
1076                 /*
1077                  * OCZ Agility 2 SSDs
1078                  * 4k optimised & trim only works in 4k requests + 4k aligned
1079                  */
1080                 { T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-AGILITY2*", "*" },
1081                 /*quirks*/DA_Q_4K
1082         },
1083         {
1084                 /*
1085                  * OCZ Agility 3 SSDs
1086                  * 4k optimised & trim only works in 4k requests + 4k aligned
1087                  */
1088                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "OCZ-AGILITY3*", "*" },
1089                 /*quirks*/DA_Q_4K
1090         },
1091         {
1092                 /*
1093                  * OCZ Deneva R Series SSDs
1094                  * 4k optimised & trim only works in 4k requests + 4k aligned
1095                  */
1096                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "DENRSTE251M45*", "*" },
1097                 /*quirks*/DA_Q_4K
1098         },
1099         {
1100                 /*
1101                  * OCZ Vertex 2 SSDs (inc pro series)
1102                  * 4k optimised & trim only works in 4k requests + 4k aligned
1103                  */
1104                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "OCZ?VERTEX2*", "*" },
1105                 /*quirks*/DA_Q_4K
1106         },
1107         {
1108                 /*
1109                  * OCZ Vertex 3 SSDs
1110                  * 4k optimised & trim only works in 4k requests + 4k aligned
1111                  */
1112                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "OCZ-VERTEX3*", "*" },
1113                 /*quirks*/DA_Q_4K
1114         },
1115         {
1116                 /*
1117                  * OCZ Vertex 4 SSDs
1118                  * 4k optimised & trim only works in 4k requests + 4k aligned
1119                  */
1120                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "OCZ-VERTEX4*", "*" },
1121                 /*quirks*/DA_Q_4K
1122         },
1123         {
1124                 /*
1125                  * Samsung 830 Series SSDs
1126                  * 4k optimised & trim only works in 4k requests + 4k aligned
1127                  */
1128                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SAMSUNG SSD 830 Series*", "*" },
1129                 /*quirks*/DA_Q_4K
1130         },
1131         {
1132                 /*
1133                  * SuperTalent TeraDrive CT SSDs
1134                  * 4k optimised & trim only works in 4k requests + 4k aligned
1135                  */
1136                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "FTM??CT25H*", "*" },
1137                 /*quirks*/DA_Q_4K
1138         },
1139         {
1140                 /*
1141                  * XceedIOPS SATA SSDs
1142                  * 4k optimised
1143                  */
1144                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SG9XCS2D*", "*" },
1145                 /*quirks*/DA_Q_4K
1146         },
1147         {
1148                 /*
1149                  * Hama Innostor USB-Stick 
1150                  */
1151                 { T_DIRECT, SIP_MEDIA_REMOVABLE, "Innostor", "Innostor*", "*" }, 
1152                 /*quirks*/DA_Q_NO_RC16
1153         },
1154 };
1155
1156 static  disk_strategy_t dastrategy;
1157 static  dumper_t        dadump;
1158 static  periph_init_t   dainit;
1159 static  void            daasync(void *callback_arg, u_int32_t code,
1160                                 struct cam_path *path, void *arg);
1161 static  void            dasysctlinit(void *context, int pending);
1162 static  int             dacmdsizesysctl(SYSCTL_HANDLER_ARGS);
1163 static  int             dadeletemethodsysctl(SYSCTL_HANDLER_ARGS);
1164 static  int             dadeletemaxsysctl(SYSCTL_HANDLER_ARGS);
1165 static  void            dadeletemethodset(struct da_softc *softc,
1166                                           da_delete_methods delete_method);
1167 static  off_t           dadeletemaxsize(struct da_softc *softc,
1168                                         da_delete_methods delete_method);
1169 static  void            dadeletemethodchoose(struct da_softc *softc,
1170                                              da_delete_methods default_method);
1171 static  void            daprobedone(struct cam_periph *periph, union ccb *ccb);
1172
1173 static  periph_ctor_t   daregister;
1174 static  periph_dtor_t   dacleanup;
1175 static  periph_start_t  dastart;
1176 static  periph_oninv_t  daoninvalidate;
1177 static  void            dadone(struct cam_periph *periph,
1178                                union ccb *done_ccb);
1179 static  int             daerror(union ccb *ccb, u_int32_t cam_flags,
1180                                 u_int32_t sense_flags);
1181 static void             daprevent(struct cam_periph *periph, int action);
1182 static void             dareprobe(struct cam_periph *periph);
1183 static void             dasetgeom(struct cam_periph *periph, uint32_t block_len,
1184                                   uint64_t maxsector,
1185                                   struct scsi_read_capacity_data_long *rcaplong,
1186                                   size_t rcap_size);
1187 static timeout_t        dasendorderedtag;
1188 static void             dashutdown(void *arg, int howto);
1189 static timeout_t        damediapoll;
1190
1191 #ifndef DA_DEFAULT_POLL_PERIOD
1192 #define DA_DEFAULT_POLL_PERIOD  3
1193 #endif
1194
1195 #ifndef DA_DEFAULT_TIMEOUT
1196 #define DA_DEFAULT_TIMEOUT 60   /* Timeout in seconds */
1197 #endif
1198
1199 #ifndef DA_DEFAULT_RETRY
1200 #define DA_DEFAULT_RETRY        4
1201 #endif
1202
1203 #ifndef DA_DEFAULT_SEND_ORDERED
1204 #define DA_DEFAULT_SEND_ORDERED 1
1205 #endif
1206
1207 #define DA_SIO (softc->sort_io_queue >= 0 ? \
1208     softc->sort_io_queue : cam_sort_io_queues)
1209
1210 static int da_poll_period = DA_DEFAULT_POLL_PERIOD;
1211 static int da_retry_count = DA_DEFAULT_RETRY;
1212 static int da_default_timeout = DA_DEFAULT_TIMEOUT;
1213 static int da_send_ordered = DA_DEFAULT_SEND_ORDERED;
1214
1215 static SYSCTL_NODE(_kern_cam, OID_AUTO, da, CTLFLAG_RD, 0,
1216             "CAM Direct Access Disk driver");
1217 SYSCTL_INT(_kern_cam_da, OID_AUTO, poll_period, CTLFLAG_RW,
1218            &da_poll_period, 0, "Media polling period in seconds");
1219 TUNABLE_INT("kern.cam.da.poll_period", &da_poll_period);
1220 SYSCTL_INT(_kern_cam_da, OID_AUTO, retry_count, CTLFLAG_RW,
1221            &da_retry_count, 0, "Normal I/O retry count");
1222 TUNABLE_INT("kern.cam.da.retry_count", &da_retry_count);
1223 SYSCTL_INT(_kern_cam_da, OID_AUTO, default_timeout, CTLFLAG_RW,
1224            &da_default_timeout, 0, "Normal I/O timeout (in seconds)");
1225 TUNABLE_INT("kern.cam.da.default_timeout", &da_default_timeout);
1226 SYSCTL_INT(_kern_cam_da, OID_AUTO, send_ordered, CTLFLAG_RW,
1227            &da_send_ordered, 0, "Send Ordered Tags");
1228 TUNABLE_INT("kern.cam.da.send_ordered", &da_send_ordered);
1229
1230 /*
1231  * DA_ORDEREDTAG_INTERVAL determines how often, relative
1232  * to the default timeout, we check to see whether an ordered
1233  * tagged transaction is appropriate to prevent simple tag
1234  * starvation.  Since we'd like to ensure that there is at least
1235  * 1/2 of the timeout length left for a starved transaction to
1236  * complete after we've sent an ordered tag, we must poll at least
1237  * four times in every timeout period.  This takes care of the worst
1238  * case where a starved transaction starts during an interval that
1239  * meets the requirement "don't send an ordered tag" test so it takes
1240  * us two intervals to determine that a tag must be sent.
1241  */
1242 #ifndef DA_ORDEREDTAG_INTERVAL
1243 #define DA_ORDEREDTAG_INTERVAL 4
1244 #endif
1245
1246 static struct periph_driver dadriver =
1247 {
1248         dainit, "da",
1249         TAILQ_HEAD_INITIALIZER(dadriver.units), /* generation */ 0
1250 };
1251
1252 PERIPHDRIVER_DECLARE(da, dadriver);
1253
1254 static MALLOC_DEFINE(M_SCSIDA, "scsi_da", "scsi_da buffers");
1255
1256 static int
1257 daopen(struct disk *dp)
1258 {
1259         struct cam_periph *periph;
1260         struct da_softc *softc;
1261         int error;
1262
1263         periph = (struct cam_periph *)dp->d_drv1;
1264         if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
1265                 return (ENXIO);
1266         }
1267
1268         cam_periph_lock(periph);
1269         if ((error = cam_periph_hold(periph, PRIBIO|PCATCH)) != 0) {
1270                 cam_periph_unlock(periph);
1271                 cam_periph_release(periph);
1272                 return (error);
1273         }
1274
1275         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
1276             ("daopen\n"));
1277
1278         softc = (struct da_softc *)periph->softc;
1279         dareprobe(periph);
1280
1281         /* Wait for the disk size update.  */
1282         error = cam_periph_sleep(periph, &softc->disk->d_mediasize, PRIBIO,
1283             "dareprobe", 0);
1284         if (error != 0)
1285                 xpt_print(periph->path, "unable to retrieve capacity data\n");
1286
1287         if (periph->flags & CAM_PERIPH_INVALID)
1288                 error = ENXIO;
1289
1290         if (error == 0 && (softc->flags & DA_FLAG_PACK_REMOVABLE) != 0 &&
1291             (softc->quirks & DA_Q_NO_PREVENT) == 0)
1292                 daprevent(periph, PR_PREVENT);
1293
1294         if (error == 0) {
1295                 softc->flags &= ~DA_FLAG_PACK_INVALID;
1296                 softc->flags |= DA_FLAG_OPEN;
1297         }
1298
1299         cam_periph_unhold(periph);
1300         cam_periph_unlock(periph);
1301
1302         if (error != 0)
1303                 cam_periph_release(periph);
1304
1305         return (error);
1306 }
1307
1308 static int
1309 daclose(struct disk *dp)
1310 {
1311         struct  cam_periph *periph;
1312         struct  da_softc *softc;
1313         int error;
1314
1315         periph = (struct cam_periph *)dp->d_drv1;
1316         cam_periph_lock(periph);
1317         if (cam_periph_hold(periph, PRIBIO) != 0) {
1318                 cam_periph_unlock(periph);
1319                 cam_periph_release(periph);
1320                 return (0);
1321         }
1322
1323         softc = (struct da_softc *)periph->softc;
1324
1325         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
1326             ("daclose\n"));
1327
1328         if ((softc->flags & DA_FLAG_DIRTY) != 0 &&
1329             (softc->quirks & DA_Q_NO_SYNC_CACHE) == 0 &&
1330             (softc->flags & DA_FLAG_PACK_INVALID) == 0) {
1331                 union   ccb *ccb;
1332
1333                 ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1334
1335                 scsi_synchronize_cache(&ccb->csio,
1336                                        /*retries*/1,
1337                                        /*cbfcnp*/dadone,
1338                                        MSG_SIMPLE_Q_TAG,
1339                                        /*begin_lba*/0,/* Cover the whole disk */
1340                                        /*lb_count*/0,
1341                                        SSD_FULL_SIZE,
1342                                        5 * 60 * 1000);
1343
1344                 error = cam_periph_runccb(ccb, daerror, /*cam_flags*/0,
1345                                   /*sense_flags*/SF_RETRY_UA | SF_QUIET_IR,
1346                                   softc->disk->d_devstat);
1347                 if (error == 0)
1348                         softc->flags &= ~DA_FLAG_DIRTY;
1349                 xpt_release_ccb(ccb);
1350
1351         }
1352
1353         if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0) {
1354                 if ((softc->quirks & DA_Q_NO_PREVENT) == 0)
1355                         daprevent(periph, PR_ALLOW);
1356                 /*
1357                  * If we've got removeable media, mark the blocksize as
1358                  * unavailable, since it could change when new media is
1359                  * inserted.
1360                  */
1361                 softc->disk->d_devstat->flags |= DEVSTAT_BS_UNAVAILABLE;
1362         }
1363
1364         softc->flags &= ~DA_FLAG_OPEN;
1365         cam_periph_unhold(periph);
1366         cam_periph_unlock(periph);
1367         cam_periph_release(periph);
1368         return (0);     
1369 }
1370
1371 static void
1372 daschedule(struct cam_periph *periph)
1373 {
1374         struct da_softc *softc = (struct da_softc *)periph->softc;
1375         uint32_t prio;
1376
1377         if (softc->state != DA_STATE_NORMAL)
1378                 return;
1379
1380         /* Check if cam_periph_getccb() was called. */
1381         prio = periph->immediate_priority;
1382
1383         /* Check if we have more work to do. */
1384         if (bioq_first(&softc->bio_queue) ||
1385             (!softc->delete_running && bioq_first(&softc->delete_queue)) ||
1386             softc->tur) {
1387                 prio = CAM_PRIORITY_NORMAL;
1388         }
1389
1390         /* Schedule CCB if any of above is true. */
1391         if (prio != CAM_PRIORITY_NONE)
1392                 xpt_schedule(periph, prio);
1393 }
1394
1395 /*
1396  * Actually translate the requested transfer into one the physical driver
1397  * can understand.  The transfer is described by a buf and will include
1398  * only one physical transfer.
1399  */
1400 static void
1401 dastrategy(struct bio *bp)
1402 {
1403         struct cam_periph *periph;
1404         struct da_softc *softc;
1405         
1406         periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1407         softc = (struct da_softc *)periph->softc;
1408
1409         cam_periph_lock(periph);
1410
1411         /*
1412          * If the device has been made invalid, error out
1413          */
1414         if ((softc->flags & DA_FLAG_PACK_INVALID)) {
1415                 cam_periph_unlock(periph);
1416                 biofinish(bp, NULL, ENXIO);
1417                 return;
1418         }
1419
1420         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dastrategy(%p)\n", bp));
1421
1422         /*
1423          * Place it in the queue of disk activities for this disk
1424          */
1425         if (bp->bio_cmd == BIO_DELETE) {
1426                 if (bp->bio_bcount == 0)
1427                         biodone(bp);
1428                 else if (DA_SIO)
1429                         bioq_disksort(&softc->delete_queue, bp);
1430                 else
1431                         bioq_insert_tail(&softc->delete_queue, bp);
1432         } else if (DA_SIO) {
1433                 bioq_disksort(&softc->bio_queue, bp);
1434         } else {
1435                 bioq_insert_tail(&softc->bio_queue, bp);
1436         }
1437
1438         /*
1439          * Schedule ourselves for performing the work.
1440          */
1441         daschedule(periph);
1442         cam_periph_unlock(periph);
1443
1444         return;
1445 }
1446
1447 static int
1448 dadump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size_t length)
1449 {
1450         struct      cam_periph *periph;
1451         struct      da_softc *softc;
1452         u_int       secsize;
1453         struct      ccb_scsiio csio;
1454         struct      disk *dp;
1455         int         error = 0;
1456
1457         dp = arg;
1458         periph = dp->d_drv1;
1459         softc = (struct da_softc *)periph->softc;
1460         cam_periph_lock(periph);
1461         secsize = softc->params.secsize;
1462         
1463         if ((softc->flags & DA_FLAG_PACK_INVALID) != 0) {
1464                 cam_periph_unlock(periph);
1465                 return (ENXIO);
1466         }
1467
1468         if (length > 0) {
1469                 xpt_setup_ccb(&csio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1470                 csio.ccb_h.ccb_state = DA_CCB_DUMP;
1471                 scsi_read_write(&csio,
1472                                 /*retries*/0,
1473                                 dadone,
1474                                 MSG_ORDERED_Q_TAG,
1475                                 /*read*/SCSI_RW_WRITE,
1476                                 /*byte2*/0,
1477                                 /*minimum_cmd_size*/ softc->minimum_cmd_size,
1478                                 offset / secsize,
1479                                 length / secsize,
1480                                 /*data_ptr*/(u_int8_t *) virtual,
1481                                 /*dxfer_len*/length,
1482                                 /*sense_len*/SSD_FULL_SIZE,
1483                                 da_default_timeout * 1000);
1484                 xpt_polled_action((union ccb *)&csio);
1485
1486                 error = cam_periph_error((union ccb *)&csio,
1487                     0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
1488                 if ((csio.ccb_h.status & CAM_DEV_QFRZN) != 0)
1489                         cam_release_devq(csio.ccb_h.path, /*relsim_flags*/0,
1490                             /*reduction*/0, /*timeout*/0, /*getcount_only*/0);
1491                 if (error != 0)
1492                         printf("Aborting dump due to I/O error.\n");
1493                 cam_periph_unlock(periph);
1494                 return (error);
1495         }
1496                 
1497         /*
1498          * Sync the disk cache contents to the physical media.
1499          */
1500         if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
1501
1502                 xpt_setup_ccb(&csio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1503                 csio.ccb_h.ccb_state = DA_CCB_DUMP;
1504                 scsi_synchronize_cache(&csio,
1505                                        /*retries*/0,
1506                                        /*cbfcnp*/dadone,
1507                                        MSG_SIMPLE_Q_TAG,
1508                                        /*begin_lba*/0,/* Cover the whole disk */
1509                                        /*lb_count*/0,
1510                                        SSD_FULL_SIZE,
1511                                        5 * 60 * 1000);
1512                 xpt_polled_action((union ccb *)&csio);
1513
1514                 error = cam_periph_error((union ccb *)&csio,
1515                     0, SF_NO_RECOVERY | SF_NO_RETRY | SF_QUIET_IR, NULL);
1516                 if ((csio.ccb_h.status & CAM_DEV_QFRZN) != 0)
1517                         cam_release_devq(csio.ccb_h.path, /*relsim_flags*/0,
1518                             /*reduction*/0, /*timeout*/0, /*getcount_only*/0);
1519                 if (error != 0)
1520                         xpt_print(periph->path, "Synchronize cache failed\n");
1521         }
1522         cam_periph_unlock(periph);
1523         return (error);
1524 }
1525
1526 static int
1527 dagetattr(struct bio *bp)
1528 {
1529         int ret;
1530         struct cam_periph *periph;
1531
1532         periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1533         cam_periph_lock(periph);
1534         ret = xpt_getattr(bp->bio_data, bp->bio_length, bp->bio_attribute,
1535             periph->path);
1536         cam_periph_unlock(periph);
1537         if (ret == 0)
1538                 bp->bio_completed = bp->bio_length;
1539         return ret;
1540 }
1541
1542 static void
1543 dainit(void)
1544 {
1545         cam_status status;
1546
1547         /*
1548          * Install a global async callback.  This callback will
1549          * receive async callbacks like "new device found".
1550          */
1551         status = xpt_register_async(AC_FOUND_DEVICE, daasync, NULL, NULL);
1552
1553         if (status != CAM_REQ_CMP) {
1554                 printf("da: Failed to attach master async callback "
1555                        "due to status 0x%x!\n", status);
1556         } else if (da_send_ordered) {
1557
1558                 /* Register our shutdown event handler */
1559                 if ((EVENTHANDLER_REGISTER(shutdown_post_sync, dashutdown, 
1560                                            NULL, SHUTDOWN_PRI_DEFAULT)) == NULL)
1561                     printf("dainit: shutdown event registration failed!\n");
1562         }
1563 }
1564
1565 /*
1566  * Callback from GEOM, called when it has finished cleaning up its
1567  * resources.
1568  */
1569 static void
1570 dadiskgonecb(struct disk *dp)
1571 {
1572         struct cam_periph *periph;
1573
1574         periph = (struct cam_periph *)dp->d_drv1;
1575         cam_periph_release(periph);
1576 }
1577
1578 static void
1579 daoninvalidate(struct cam_periph *periph)
1580 {
1581         struct da_softc *softc;
1582
1583         softc = (struct da_softc *)periph->softc;
1584
1585         /*
1586          * De-register any async callbacks.
1587          */
1588         xpt_register_async(0, daasync, periph, periph->path);
1589
1590         softc->flags |= DA_FLAG_PACK_INVALID;
1591
1592         /*
1593          * Return all queued I/O with ENXIO.
1594          * XXX Handle any transactions queued to the card
1595          *     with XPT_ABORT_CCB.
1596          */
1597         bioq_flush(&softc->bio_queue, NULL, ENXIO);
1598         bioq_flush(&softc->delete_queue, NULL, ENXIO);
1599
1600         /*
1601          * Tell GEOM that we've gone away, we'll get a callback when it is
1602          * done cleaning up its resources.
1603          */
1604         disk_gone(softc->disk);
1605 }
1606
1607 static void
1608 dacleanup(struct cam_periph *periph)
1609 {
1610         struct da_softc *softc;
1611
1612         softc = (struct da_softc *)periph->softc;
1613
1614         cam_periph_unlock(periph);
1615
1616         /*
1617          * If we can't free the sysctl tree, oh well...
1618          */
1619         if ((softc->flags & DA_FLAG_SCTX_INIT) != 0
1620             && sysctl_ctx_free(&softc->sysctl_ctx) != 0) {
1621                 xpt_print(periph->path, "can't remove sysctl context\n");
1622         }
1623
1624         callout_drain(&softc->mediapoll_c);
1625         disk_destroy(softc->disk);
1626         callout_drain(&softc->sendordered_c);
1627         free(softc, M_DEVBUF);
1628         cam_periph_lock(periph);
1629 }
1630
1631 static void
1632 daasync(void *callback_arg, u_int32_t code,
1633         struct cam_path *path, void *arg)
1634 {
1635         struct cam_periph *periph;
1636         struct da_softc *softc;
1637
1638         periph = (struct cam_periph *)callback_arg;
1639         switch (code) {
1640         case AC_FOUND_DEVICE:
1641         {
1642                 struct ccb_getdev *cgd;
1643                 cam_status status;
1644  
1645                 cgd = (struct ccb_getdev *)arg;
1646                 if (cgd == NULL)
1647                         break;
1648
1649                 if (cgd->protocol != PROTO_SCSI)
1650                         break;
1651
1652                 if (SID_TYPE(&cgd->inq_data) != T_DIRECT
1653                     && SID_TYPE(&cgd->inq_data) != T_RBC
1654                     && SID_TYPE(&cgd->inq_data) != T_OPTICAL)
1655                         break;
1656
1657                 /*
1658                  * Allocate a peripheral instance for
1659                  * this device and start the probe
1660                  * process.
1661                  */
1662                 status = cam_periph_alloc(daregister, daoninvalidate,
1663                                           dacleanup, dastart,
1664                                           "da", CAM_PERIPH_BIO,
1665                                           cgd->ccb_h.path, daasync,
1666                                           AC_FOUND_DEVICE, cgd);
1667
1668                 if (status != CAM_REQ_CMP
1669                  && status != CAM_REQ_INPROG)
1670                         printf("daasync: Unable to attach to new device "
1671                                 "due to status 0x%x\n", status);
1672                 return;
1673         }
1674         case AC_ADVINFO_CHANGED:
1675         {
1676                 uintptr_t buftype;
1677
1678                 buftype = (uintptr_t)arg;
1679                 if (buftype == CDAI_TYPE_PHYS_PATH) {
1680                         struct da_softc *softc;
1681
1682                         softc = periph->softc;
1683                         disk_attr_changed(softc->disk, "GEOM::physpath",
1684                                           M_NOWAIT);
1685                 }
1686                 break;
1687         }
1688         case AC_UNIT_ATTENTION:
1689         {
1690                 union ccb *ccb;
1691                 int error_code, sense_key, asc, ascq;
1692
1693                 softc = (struct da_softc *)periph->softc;
1694                 ccb = (union ccb *)arg;
1695
1696                 /*
1697                  * Handle all UNIT ATTENTIONs except our own,
1698                  * as they will be handled by daerror().
1699                  */
1700                 if (xpt_path_periph(ccb->ccb_h.path) != periph &&
1701                     scsi_extract_sense_ccb(ccb,
1702                      &error_code, &sense_key, &asc, &ascq)) {
1703                         if (asc == 0x2A && ascq == 0x09) {
1704                                 xpt_print(ccb->ccb_h.path,
1705                                     "Capacity data has changed\n");
1706                                 softc->flags &= ~DA_FLAG_PROBED;
1707                                 dareprobe(periph);
1708                         } else if (asc == 0x28 && ascq == 0x00) {
1709                                 softc->flags &= ~DA_FLAG_PROBED;
1710                                 disk_media_changed(softc->disk, M_NOWAIT);
1711                         } else if (asc == 0x3F && ascq == 0x03) {
1712                                 xpt_print(ccb->ccb_h.path,
1713                                     "INQUIRY data has changed\n");
1714                                 softc->flags &= ~DA_FLAG_PROBED;
1715                                 dareprobe(periph);
1716                         }
1717                 }
1718                 cam_periph_async(periph, code, path, arg);
1719                 break;
1720         }
1721         case AC_SCSI_AEN:
1722                 softc = (struct da_softc *)periph->softc;
1723                 if (!softc->tur) {
1724                         if (cam_periph_acquire(periph) == CAM_REQ_CMP) {
1725                                 softc->tur = 1;
1726                                 daschedule(periph);
1727                         }
1728                 }
1729                 /* FALLTHROUGH */
1730         case AC_SENT_BDR:
1731         case AC_BUS_RESET:
1732         {
1733                 struct ccb_hdr *ccbh;
1734
1735                 softc = (struct da_softc *)periph->softc;
1736                 /*
1737                  * Don't fail on the expected unit attention
1738                  * that will occur.
1739                  */
1740                 softc->flags |= DA_FLAG_RETRY_UA;
1741                 LIST_FOREACH(ccbh, &softc->pending_ccbs, periph_links.le)
1742                         ccbh->ccb_state |= DA_CCB_RETRY_UA;
1743                 break;
1744         }
1745         default:
1746                 break;
1747         }
1748         cam_periph_async(periph, code, path, arg);
1749 }
1750
1751 static void
1752 dasysctlinit(void *context, int pending)
1753 {
1754         struct cam_periph *periph;
1755         struct da_softc *softc;
1756         char tmpstr[80], tmpstr2[80];
1757         struct ccb_trans_settings cts;
1758
1759         periph = (struct cam_periph *)context;
1760         /*
1761          * periph was held for us when this task was enqueued
1762          */
1763         if (periph->flags & CAM_PERIPH_INVALID) {
1764                 cam_periph_release(periph);
1765                 return;
1766         }
1767
1768         softc = (struct da_softc *)periph->softc;
1769         snprintf(tmpstr, sizeof(tmpstr), "CAM DA unit %d", periph->unit_number);
1770         snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
1771
1772         sysctl_ctx_init(&softc->sysctl_ctx);
1773         softc->flags |= DA_FLAG_SCTX_INIT;
1774         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1775                 SYSCTL_STATIC_CHILDREN(_kern_cam_da), OID_AUTO, tmpstr2,
1776                 CTLFLAG_RD, 0, tmpstr);
1777         if (softc->sysctl_tree == NULL) {
1778                 printf("dasysctlinit: unable to allocate sysctl tree\n");
1779                 cam_periph_release(periph);
1780                 return;
1781         }
1782
1783         /*
1784          * Now register the sysctl handler, so the user can change the value on
1785          * the fly.
1786          */
1787         SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1788                 OID_AUTO, "delete_method", CTLTYPE_STRING | CTLFLAG_RW,
1789                 softc, 0, dadeletemethodsysctl, "A",
1790                 "BIO_DELETE execution method");
1791         SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1792                 OID_AUTO, "delete_max", CTLTYPE_U64 | CTLFLAG_RW,
1793                 softc, 0, dadeletemaxsysctl, "Q",
1794                 "Maximum BIO_DELETE size");
1795         SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1796                 OID_AUTO, "minimum_cmd_size", CTLTYPE_INT | CTLFLAG_RW,
1797                 &softc->minimum_cmd_size, 0, dacmdsizesysctl, "I",
1798                 "Minimum CDB size");
1799         SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1800                 OID_AUTO, "sort_io_queue", CTLFLAG_RW, &softc->sort_io_queue, 0,
1801                 "Sort IO queue to try and optimise disk access patterns");
1802
1803         SYSCTL_ADD_INT(&softc->sysctl_ctx,
1804                        SYSCTL_CHILDREN(softc->sysctl_tree),
1805                        OID_AUTO,
1806                        "error_inject",
1807                        CTLFLAG_RW,
1808                        &softc->error_inject,
1809                        0,
1810                        "error_inject leaf");
1811
1812
1813         /*
1814          * Add some addressing info.
1815          */
1816         memset(&cts, 0, sizeof (cts));
1817         xpt_setup_ccb(&cts.ccb_h, periph->path, CAM_PRIORITY_NONE);
1818         cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
1819         cts.type = CTS_TYPE_CURRENT_SETTINGS;
1820         cam_periph_lock(periph);
1821         xpt_action((union ccb *)&cts);
1822         cam_periph_unlock(periph);
1823         if (cts.ccb_h.status != CAM_REQ_CMP) {
1824                 cam_periph_release(periph);
1825                 return;
1826         }
1827         if (cts.protocol == PROTO_SCSI && cts.transport == XPORT_FC) {
1828                 struct ccb_trans_settings_fc *fc = &cts.xport_specific.fc;
1829                 if (fc->valid & CTS_FC_VALID_WWPN) {
1830                         softc->wwpn = fc->wwpn;
1831                         SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
1832                             SYSCTL_CHILDREN(softc->sysctl_tree),
1833                             OID_AUTO, "wwpn", CTLFLAG_RD,
1834                             &softc->wwpn, "World Wide Port Name");
1835                 }
1836         }
1837         cam_periph_release(periph);
1838 }
1839
1840 static int
1841 dadeletemaxsysctl(SYSCTL_HANDLER_ARGS)
1842 {
1843         int error;
1844         uint64_t value;
1845         struct da_softc *softc;
1846
1847         softc = (struct da_softc *)arg1;
1848
1849         value = softc->disk->d_delmaxsize;
1850         error = sysctl_handle_64(oidp, &value, 0, req);
1851         if ((error != 0) || (req->newptr == NULL))
1852                 return (error);
1853
1854         /* only accept values smaller than the calculated value */
1855         if (value > dadeletemaxsize(softc, softc->delete_method)) {
1856                 return (EINVAL);
1857         }
1858         softc->disk->d_delmaxsize = value;
1859
1860         return (0);
1861 }
1862
1863 static int
1864 dacmdsizesysctl(SYSCTL_HANDLER_ARGS)
1865 {
1866         int error, value;
1867
1868         value = *(int *)arg1;
1869
1870         error = sysctl_handle_int(oidp, &value, 0, req);
1871
1872         if ((error != 0)
1873          || (req->newptr == NULL))
1874                 return (error);
1875
1876         /*
1877          * Acceptable values here are 6, 10, 12 or 16.
1878          */
1879         if (value < 6)
1880                 value = 6;
1881         else if ((value > 6)
1882               && (value <= 10))
1883                 value = 10;
1884         else if ((value > 10)
1885               && (value <= 12))
1886                 value = 12;
1887         else if (value > 12)
1888                 value = 16;
1889
1890         *(int *)arg1 = value;
1891
1892         return (0);
1893 }
1894
1895 static void
1896 dadeletemethodset(struct da_softc *softc, da_delete_methods delete_method)
1897 {
1898
1899
1900         softc->delete_method = delete_method;
1901         softc->disk->d_delmaxsize = dadeletemaxsize(softc, delete_method);
1902         softc->delete_func = da_delete_functions[delete_method];
1903
1904         if (softc->delete_method > DA_DELETE_DISABLE)
1905                 softc->disk->d_flags |= DISKFLAG_CANDELETE;
1906         else
1907                 softc->disk->d_flags &= ~DISKFLAG_CANDELETE;
1908 }
1909
1910 static off_t
1911 dadeletemaxsize(struct da_softc *softc, da_delete_methods delete_method)
1912 {
1913         off_t sectors;
1914
1915         switch(delete_method) {
1916         case DA_DELETE_UNMAP:
1917                 sectors = (off_t)softc->unmap_max_lba;
1918                 break;
1919         case DA_DELETE_ATA_TRIM:
1920                 sectors = (off_t)ATA_DSM_RANGE_MAX * softc->trim_max_ranges;
1921                 break;
1922         case DA_DELETE_WS16:
1923                 sectors = omin(softc->ws_max_blks, WS16_MAX_BLKS);
1924                 break;
1925         case DA_DELETE_ZERO:
1926         case DA_DELETE_WS10:
1927                 sectors = omin(softc->ws_max_blks, WS10_MAX_BLKS);
1928                 break;
1929         default:
1930                 return 0;
1931         }
1932
1933         return (off_t)softc->params.secsize *
1934             omin(sectors, softc->params.sectors);
1935 }
1936
1937 static void
1938 daprobedone(struct cam_periph *periph, union ccb *ccb)
1939 {
1940         struct da_softc *softc;
1941
1942         softc = (struct da_softc *)periph->softc;
1943
1944         dadeletemethodchoose(softc, DA_DELETE_NONE);
1945
1946         if (bootverbose && (softc->flags & DA_FLAG_ANNOUNCED) == 0) {
1947                 char buf[80];
1948                 int i, sep;
1949
1950                 snprintf(buf, sizeof(buf), "Delete methods: <");
1951                 sep = 0;
1952                 for (i = DA_DELETE_MIN; i <= DA_DELETE_MAX; i++) {
1953                         if (softc->delete_available & (1 << i)) {
1954                                 if (sep) {
1955                                         strlcat(buf, ",", sizeof(buf));
1956                                 } else {
1957                                     sep = 1;
1958                                 }
1959                                 strlcat(buf, da_delete_method_names[i],
1960                                     sizeof(buf));
1961                                 if (i == softc->delete_method) {
1962                                         strlcat(buf, "(*)", sizeof(buf));
1963                                 }
1964                         }
1965                 }
1966                 if (sep == 0) {
1967                         if (softc->delete_method == DA_DELETE_NONE) 
1968                                 strlcat(buf, "NONE(*)", sizeof(buf));
1969                         else
1970                                 strlcat(buf, "DISABLED(*)", sizeof(buf));
1971                 }
1972                 strlcat(buf, ">", sizeof(buf));
1973                 printf("%s%d: %s\n", periph->periph_name,
1974                     periph->unit_number, buf);
1975         }
1976
1977         /*
1978          * Since our peripheral may be invalidated by an error
1979          * above or an external event, we must release our CCB
1980          * before releasing the probe lock on the peripheral.
1981          * The peripheral will only go away once the last lock
1982          * is removed, and we need it around for the CCB release
1983          * operation.
1984          */
1985         xpt_release_ccb(ccb);
1986         softc->state = DA_STATE_NORMAL;
1987         softc->flags |= DA_FLAG_PROBED;
1988         daschedule(periph);
1989         wakeup(&softc->disk->d_mediasize);
1990         if ((softc->flags & DA_FLAG_ANNOUNCED) == 0) {
1991                 softc->flags |= DA_FLAG_ANNOUNCED;
1992                 cam_periph_unhold(periph);
1993         } else
1994                 cam_periph_release_locked(periph);
1995 }
1996
1997 static void
1998 dadeletemethodchoose(struct da_softc *softc, da_delete_methods default_method)
1999 {
2000         int i, delete_method;
2001
2002         delete_method = default_method;
2003
2004         /*
2005          * Use the pre-defined order to choose the best
2006          * performing delete.
2007          */
2008         for (i = DA_DELETE_MIN; i <= DA_DELETE_MAX; i++) {
2009                 if (softc->delete_available & (1 << i)) {
2010                         dadeletemethodset(softc, i);
2011                         return;
2012                 }
2013         }
2014         dadeletemethodset(softc, delete_method);
2015 }
2016
2017 static int
2018 dadeletemethodsysctl(SYSCTL_HANDLER_ARGS)
2019 {
2020         char buf[16];
2021         const char *p;
2022         struct da_softc *softc;
2023         int i, error, methods, value;
2024
2025         softc = (struct da_softc *)arg1;
2026
2027         value = softc->delete_method;
2028         if (value < 0 || value > DA_DELETE_MAX)
2029                 p = "UNKNOWN";
2030         else
2031                 p = da_delete_method_names[value];
2032         strncpy(buf, p, sizeof(buf));
2033         error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
2034         if (error != 0 || req->newptr == NULL)
2035                 return (error);
2036         methods = softc->delete_available | (1 << DA_DELETE_DISABLE);
2037         for (i = 0; i <= DA_DELETE_MAX; i++) {
2038                 if (!(methods & (1 << i)) ||
2039                     strcmp(buf, da_delete_method_names[i]) != 0)
2040                         continue;
2041                 dadeletemethodset(softc, i);
2042                 return (0);
2043         }
2044         return (EINVAL);
2045 }
2046
2047 static cam_status
2048 daregister(struct cam_periph *periph, void *arg)
2049 {
2050         struct da_softc *softc;
2051         struct ccb_pathinq cpi;
2052         struct ccb_getdev *cgd;
2053         char tmpstr[80];
2054         caddr_t match;
2055
2056         cgd = (struct ccb_getdev *)arg;
2057         if (cgd == NULL) {
2058                 printf("daregister: no getdev CCB, can't register device\n");
2059                 return(CAM_REQ_CMP_ERR);
2060         }
2061
2062         softc = (struct da_softc *)malloc(sizeof(*softc), M_DEVBUF,
2063             M_NOWAIT|M_ZERO);
2064
2065         if (softc == NULL) {
2066                 printf("daregister: Unable to probe new device. "
2067                        "Unable to allocate softc\n");                           
2068                 return(CAM_REQ_CMP_ERR);
2069         }
2070
2071         LIST_INIT(&softc->pending_ccbs);
2072         softc->state = DA_STATE_PROBE_RC;
2073         bioq_init(&softc->bio_queue);
2074         bioq_init(&softc->delete_queue);
2075         bioq_init(&softc->delete_run_queue);
2076         if (SID_IS_REMOVABLE(&cgd->inq_data))
2077                 softc->flags |= DA_FLAG_PACK_REMOVABLE;
2078         softc->unmap_max_ranges = UNMAP_MAX_RANGES;
2079         softc->unmap_max_lba = UNMAP_RANGE_MAX;
2080         softc->ws_max_blks = WS16_MAX_BLKS;
2081         softc->trim_max_ranges = ATA_TRIM_MAX_RANGES;
2082         softc->sort_io_queue = -1;
2083
2084         periph->softc = softc;
2085
2086         /*
2087          * See if this device has any quirks.
2088          */
2089         match = cam_quirkmatch((caddr_t)&cgd->inq_data,
2090                                (caddr_t)da_quirk_table,
2091                                sizeof(da_quirk_table)/sizeof(*da_quirk_table),
2092                                sizeof(*da_quirk_table), scsi_inquiry_match);
2093
2094         if (match != NULL)
2095                 softc->quirks = ((struct da_quirk_entry *)match)->quirks;
2096         else
2097                 softc->quirks = DA_Q_NONE;
2098
2099         /* Check if the SIM does not want 6 byte commands */
2100         bzero(&cpi, sizeof(cpi));
2101         xpt_setup_ccb(&cpi.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
2102         cpi.ccb_h.func_code = XPT_PATH_INQ;
2103         xpt_action((union ccb *)&cpi);
2104         if (cpi.ccb_h.status == CAM_REQ_CMP && (cpi.hba_misc & PIM_NO_6_BYTE))
2105                 softc->quirks |= DA_Q_NO_6_BYTE;
2106
2107         TASK_INIT(&softc->sysctl_task, 0, dasysctlinit, periph);
2108
2109         /*
2110          * Take an exclusive refcount on the periph while dastart is called
2111          * to finish the probe.  The reference will be dropped in dadone at
2112          * the end of probe.
2113          */
2114         (void)cam_periph_hold(periph, PRIBIO);
2115
2116         /*
2117          * Schedule a periodic event to occasionally send an
2118          * ordered tag to a device.
2119          */
2120         callout_init_mtx(&softc->sendordered_c, periph->sim->mtx, 0);
2121         callout_reset(&softc->sendordered_c,
2122             (da_default_timeout * hz) / DA_ORDEREDTAG_INTERVAL,
2123             dasendorderedtag, softc);
2124
2125         cam_periph_unlock(periph);
2126         /*
2127          * RBC devices don't have to support READ(6), only READ(10).
2128          */
2129         if (softc->quirks & DA_Q_NO_6_BYTE || SID_TYPE(&cgd->inq_data) == T_RBC)
2130                 softc->minimum_cmd_size = 10;
2131         else
2132                 softc->minimum_cmd_size = 6;
2133
2134         /*
2135          * Load the user's default, if any.
2136          */
2137         snprintf(tmpstr, sizeof(tmpstr), "kern.cam.da.%d.minimum_cmd_size",
2138                  periph->unit_number);
2139         TUNABLE_INT_FETCH(tmpstr, &softc->minimum_cmd_size);
2140
2141         /*
2142          * 6, 10, 12 and 16 are the currently permissible values.
2143          */
2144         if (softc->minimum_cmd_size < 6)
2145                 softc->minimum_cmd_size = 6;
2146         else if ((softc->minimum_cmd_size > 6)
2147               && (softc->minimum_cmd_size <= 10))
2148                 softc->minimum_cmd_size = 10;
2149         else if ((softc->minimum_cmd_size > 10)
2150               && (softc->minimum_cmd_size <= 12))
2151                 softc->minimum_cmd_size = 12;
2152         else if (softc->minimum_cmd_size > 12)
2153                 softc->minimum_cmd_size = 16;
2154
2155         /* Predict whether device may support READ CAPACITY(16). */
2156         if (SID_ANSI_REV(&cgd->inq_data) >= SCSI_REV_SPC3 &&
2157             (softc->quirks & DA_Q_NO_RC16) == 0) {
2158                 softc->flags |= DA_FLAG_CAN_RC16;
2159                 softc->state = DA_STATE_PROBE_RC16;
2160         }
2161
2162         /*
2163          * Register this media as a disk.
2164          */
2165         softc->disk = disk_alloc();
2166         softc->disk->d_devstat = devstat_new_entry(periph->periph_name,
2167                           periph->unit_number, 0,
2168                           DEVSTAT_BS_UNAVAILABLE,
2169                           SID_TYPE(&cgd->inq_data) |
2170                           XPORT_DEVSTAT_TYPE(cpi.transport),
2171                           DEVSTAT_PRIORITY_DISK);
2172         softc->disk->d_open = daopen;
2173         softc->disk->d_close = daclose;
2174         softc->disk->d_strategy = dastrategy;
2175         softc->disk->d_dump = dadump;
2176         softc->disk->d_getattr = dagetattr;
2177         softc->disk->d_gone = dadiskgonecb;
2178         softc->disk->d_name = "da";
2179         softc->disk->d_drv1 = periph;
2180         if (cpi.maxio == 0)
2181                 softc->maxio = DFLTPHYS;        /* traditional default */
2182         else if (cpi.maxio > MAXPHYS)
2183                 softc->maxio = MAXPHYS;         /* for safety */
2184         else
2185                 softc->maxio = cpi.maxio;
2186         softc->disk->d_maxsize = softc->maxio;
2187         softc->disk->d_unit = periph->unit_number;
2188         softc->disk->d_flags = 0;
2189         if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0)
2190                 softc->disk->d_flags |= DISKFLAG_CANFLUSHCACHE;
2191         if ((cpi.hba_misc & PIM_UNMAPPED) != 0)
2192                 softc->disk->d_flags |= DISKFLAG_UNMAPPED_BIO;
2193         cam_strvis(softc->disk->d_descr, cgd->inq_data.vendor,
2194             sizeof(cgd->inq_data.vendor), sizeof(softc->disk->d_descr));
2195         strlcat(softc->disk->d_descr, " ", sizeof(softc->disk->d_descr));
2196         cam_strvis(&softc->disk->d_descr[strlen(softc->disk->d_descr)],
2197             cgd->inq_data.product, sizeof(cgd->inq_data.product),
2198             sizeof(softc->disk->d_descr) - strlen(softc->disk->d_descr));
2199         softc->disk->d_hba_vendor = cpi.hba_vendor;
2200         softc->disk->d_hba_device = cpi.hba_device;
2201         softc->disk->d_hba_subvendor = cpi.hba_subvendor;
2202         softc->disk->d_hba_subdevice = cpi.hba_subdevice;
2203
2204         /*
2205          * Acquire a reference to the periph before we register with GEOM.
2206          * We'll release this reference once GEOM calls us back (via
2207          * dadiskgonecb()) telling us that our provider has been freed.
2208          */
2209         if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
2210                 xpt_print(periph->path, "%s: lost periph during "
2211                           "registration!\n", __func__);
2212                 cam_periph_lock(periph);
2213                 return (CAM_REQ_CMP_ERR);
2214         }
2215
2216         disk_create(softc->disk, DISK_VERSION);
2217         cam_periph_lock(periph);
2218
2219         /*
2220          * Add async callbacks for events of interest.
2221          * I don't bother checking if this fails as,
2222          * in most cases, the system will function just
2223          * fine without them and the only alternative
2224          * would be to not attach the device on failure.
2225          */
2226         xpt_register_async(AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE |
2227             AC_ADVINFO_CHANGED | AC_SCSI_AEN | AC_UNIT_ATTENTION,
2228             daasync, periph, periph->path);
2229
2230         /*
2231          * Emit an attribute changed notification just in case 
2232          * physical path information arrived before our async
2233          * event handler was registered, but after anyone attaching
2234          * to our disk device polled it.
2235          */
2236         disk_attr_changed(softc->disk, "GEOM::physpath", M_NOWAIT);
2237
2238         /*
2239          * Schedule a periodic media polling events.
2240          */
2241         callout_init_mtx(&softc->mediapoll_c, periph->sim->mtx, 0);
2242         if ((softc->flags & DA_FLAG_PACK_REMOVABLE) &&
2243             (cgd->inq_flags & SID_AEN) == 0 &&
2244             da_poll_period != 0)
2245                 callout_reset(&softc->mediapoll_c, da_poll_period * hz,
2246                     damediapoll, periph);
2247
2248         xpt_schedule(periph, CAM_PRIORITY_DEV);
2249
2250         return(CAM_REQ_CMP);
2251 }
2252
2253 static void
2254 dastart(struct cam_periph *periph, union ccb *start_ccb)
2255 {
2256         struct da_softc *softc;
2257
2258         softc = (struct da_softc *)periph->softc;
2259
2260         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dastart\n"));
2261
2262 skipstate:
2263         switch (softc->state) {
2264         case DA_STATE_NORMAL:
2265         {
2266                 struct bio *bp;
2267                 uint8_t tag_code;
2268
2269                 /* Execute immediate CCB if waiting. */
2270                 if (periph->immediate_priority <= periph->pinfo.priority) {
2271                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
2272                                         ("queuing for immediate ccb\n"));
2273                         start_ccb->ccb_h.ccb_state = DA_CCB_WAITING;
2274                         SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
2275                                           periph_links.sle);
2276                         periph->immediate_priority = CAM_PRIORITY_NONE;
2277                         wakeup(&periph->ccb_list);
2278                         /* May have more work to do, so ensure we stay scheduled */
2279                         daschedule(periph);
2280                         break;
2281                 }
2282
2283                 /* Run BIO_DELETE if not running yet. */
2284                 if (!softc->delete_running &&
2285                     (bp = bioq_first(&softc->delete_queue)) != NULL) {
2286                         if (softc->delete_func != NULL) {
2287                                 softc->delete_func(periph, start_ccb, bp);
2288                                 goto out;
2289                         } else {
2290                                 bioq_flush(&softc->delete_queue, NULL, 0);
2291                                 /* FALLTHROUGH */
2292                         }
2293                 }
2294
2295                 /* Run regular command. */
2296                 bp = bioq_takefirst(&softc->bio_queue);
2297                 if (bp == NULL) {
2298                         if (softc->tur) {
2299                                 softc->tur = 0;
2300                                 scsi_test_unit_ready(&start_ccb->csio,
2301                                      /*retries*/ da_retry_count,
2302                                      dadone,
2303                                      MSG_SIMPLE_Q_TAG,
2304                                      SSD_FULL_SIZE,
2305                                      da_default_timeout * 1000);
2306                                 start_ccb->ccb_h.ccb_bp = NULL;
2307                                 start_ccb->ccb_h.ccb_state = DA_CCB_TUR;
2308                                 xpt_action(start_ccb);
2309                         } else
2310                                 xpt_release_ccb(start_ccb);
2311                         break;
2312                 }
2313                 if (softc->tur) {
2314                         softc->tur = 0;
2315                         cam_periph_release_locked(periph);
2316                 }
2317
2318                 if ((bp->bio_flags & BIO_ORDERED) != 0 ||
2319                     (softc->flags & DA_FLAG_NEED_OTAG) != 0) {
2320                         softc->flags &= ~DA_FLAG_NEED_OTAG;
2321                         softc->flags |= DA_FLAG_WAS_OTAG;
2322                         tag_code = MSG_ORDERED_Q_TAG;
2323                 } else {
2324                         tag_code = MSG_SIMPLE_Q_TAG;
2325                 }
2326
2327                 switch (bp->bio_cmd) {
2328                 case BIO_WRITE:
2329                         softc->flags |= DA_FLAG_DIRTY;
2330                         /* FALLTHROUGH */
2331                 case BIO_READ:
2332                         scsi_read_write(&start_ccb->csio,
2333                                         /*retries*/da_retry_count,
2334                                         /*cbfcnp*/dadone,
2335                                         /*tag_action*/tag_code,
2336                                         /*read_op*/(bp->bio_cmd == BIO_READ ?
2337                                         SCSI_RW_READ : SCSI_RW_WRITE) |
2338                                         ((bp->bio_flags & BIO_UNMAPPED) != 0 ?
2339                                         SCSI_RW_BIO : 0),
2340                                         /*byte2*/0,
2341                                         softc->minimum_cmd_size,
2342                                         /*lba*/bp->bio_pblkno,
2343                                         /*block_count*/bp->bio_bcount /
2344                                         softc->params.secsize,
2345                                         /*data_ptr*/ (bp->bio_flags &
2346                                         BIO_UNMAPPED) != 0 ? (void *)bp :
2347                                         bp->bio_data,
2348                                         /*dxfer_len*/ bp->bio_bcount,
2349                                         /*sense_len*/SSD_FULL_SIZE,
2350                                         da_default_timeout * 1000);
2351                         break;
2352                 case BIO_FLUSH:
2353                         /*
2354                          * BIO_FLUSH doesn't currently communicate
2355                          * range data, so we synchronize the cache
2356                          * over the whole disk.  We also force
2357                          * ordered tag semantics the flush applies
2358                          * to all previously queued I/O.
2359                          */
2360                         scsi_synchronize_cache(&start_ccb->csio,
2361                                                /*retries*/1,
2362                                                /*cbfcnp*/dadone,
2363                                                MSG_ORDERED_Q_TAG,
2364                                                /*begin_lba*/0,
2365                                                /*lb_count*/0,
2366                                                SSD_FULL_SIZE,
2367                                                da_default_timeout*1000);
2368                         break;
2369                 }
2370                 start_ccb->ccb_h.ccb_state = DA_CCB_BUFFER_IO;
2371
2372 out:
2373                 LIST_INSERT_HEAD(&softc->pending_ccbs,
2374                                  &start_ccb->ccb_h, periph_links.le);
2375
2376                 /* We expect a unit attention from this device */
2377                 if ((softc->flags & DA_FLAG_RETRY_UA) != 0) {
2378                         start_ccb->ccb_h.ccb_state |= DA_CCB_RETRY_UA;
2379                         softc->flags &= ~DA_FLAG_RETRY_UA;
2380                 }
2381
2382                 start_ccb->ccb_h.ccb_bp = bp;
2383                 xpt_action(start_ccb);
2384
2385                 /* May have more work to do, so ensure we stay scheduled */
2386                 daschedule(periph);
2387                 break;
2388         }
2389         case DA_STATE_PROBE_RC:
2390         {
2391                 struct scsi_read_capacity_data *rcap;
2392
2393                 rcap = (struct scsi_read_capacity_data *)
2394                     malloc(sizeof(*rcap), M_SCSIDA, M_NOWAIT|M_ZERO);
2395                 if (rcap == NULL) {
2396                         printf("dastart: Couldn't malloc read_capacity data\n");
2397                         /* da_free_periph??? */
2398                         break;
2399                 }
2400                 scsi_read_capacity(&start_ccb->csio,
2401                                    /*retries*/da_retry_count,
2402                                    dadone,
2403                                    MSG_SIMPLE_Q_TAG,
2404                                    rcap,
2405                                    SSD_FULL_SIZE,
2406                                    /*timeout*/5000);
2407                 start_ccb->ccb_h.ccb_bp = NULL;
2408                 start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_RC;
2409                 xpt_action(start_ccb);
2410                 break;
2411         }
2412         case DA_STATE_PROBE_RC16:
2413         {
2414                 struct scsi_read_capacity_data_long *rcaplong;
2415
2416                 rcaplong = (struct scsi_read_capacity_data_long *)
2417                         malloc(sizeof(*rcaplong), M_SCSIDA, M_NOWAIT|M_ZERO);
2418                 if (rcaplong == NULL) {
2419                         printf("dastart: Couldn't malloc read_capacity data\n");
2420                         /* da_free_periph??? */
2421                         break;
2422                 }
2423                 scsi_read_capacity_16(&start_ccb->csio,
2424                                       /*retries*/ da_retry_count,
2425                                       /*cbfcnp*/ dadone,
2426                                       /*tag_action*/ MSG_SIMPLE_Q_TAG,
2427                                       /*lba*/ 0,
2428                                       /*reladr*/ 0,
2429                                       /*pmi*/ 0,
2430                                       rcaplong,
2431                                       /*sense_len*/ SSD_FULL_SIZE,
2432                                       /*timeout*/ da_default_timeout * 1000);
2433                 start_ccb->ccb_h.ccb_bp = NULL;
2434                 start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_RC16;
2435                 xpt_action(start_ccb);
2436                 break;
2437         }
2438         case DA_STATE_PROBE_LBP:
2439         {
2440                 struct scsi_vpd_logical_block_prov *lbp;
2441
2442                 if (!scsi_vpd_supported_page(periph, SVPD_LBP)) {
2443                         /*
2444                          * If we get here we don't support any SBC-3 delete
2445                          * methods with UNMAP as the Logical Block Provisioning
2446                          * VPD page support is required for devices which
2447                          * support it according to T10/1799-D Revision 31
2448                          * however older revisions of the spec don't mandate
2449                          * this so we currently don't remove these methods
2450                          * from the available set.
2451                          */
2452                         softc->state = DA_STATE_PROBE_BLK_LIMITS;
2453                         goto skipstate;
2454                 }
2455
2456                 lbp = (struct scsi_vpd_logical_block_prov *)
2457                         malloc(sizeof(*lbp), M_SCSIDA, M_NOWAIT|M_ZERO);
2458
2459                 if (lbp == NULL) {
2460                         printf("dastart: Couldn't malloc lbp data\n");
2461                         /* da_free_periph??? */
2462                         break;
2463                 }
2464
2465                 scsi_inquiry(&start_ccb->csio,
2466                              /*retries*/da_retry_count,
2467                              /*cbfcnp*/dadone,
2468                              /*tag_action*/MSG_SIMPLE_Q_TAG,
2469                              /*inq_buf*/(u_int8_t *)lbp,
2470                              /*inq_len*/sizeof(*lbp),
2471                              /*evpd*/TRUE,
2472                              /*page_code*/SVPD_LBP,
2473                              /*sense_len*/SSD_MIN_SIZE,
2474                              /*timeout*/da_default_timeout * 1000);
2475                 start_ccb->ccb_h.ccb_bp = NULL;
2476                 start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_LBP;
2477                 xpt_action(start_ccb);
2478                 break;
2479         }
2480         case DA_STATE_PROBE_BLK_LIMITS:
2481         {
2482                 struct scsi_vpd_block_limits *block_limits;
2483
2484                 if (!scsi_vpd_supported_page(periph, SVPD_BLOCK_LIMITS)) {
2485                         /* Not supported skip to next probe */
2486                         softc->state = DA_STATE_PROBE_BDC;
2487                         goto skipstate;
2488                 }
2489
2490                 block_limits = (struct scsi_vpd_block_limits *)
2491                         malloc(sizeof(*block_limits), M_SCSIDA, M_NOWAIT|M_ZERO);
2492
2493                 if (block_limits == NULL) {
2494                         printf("dastart: Couldn't malloc block_limits data\n");
2495                         /* da_free_periph??? */
2496                         break;
2497                 }
2498
2499                 scsi_inquiry(&start_ccb->csio,
2500                              /*retries*/da_retry_count,
2501                              /*cbfcnp*/dadone,
2502                              /*tag_action*/MSG_SIMPLE_Q_TAG,
2503                              /*inq_buf*/(u_int8_t *)block_limits,
2504                              /*inq_len*/sizeof(*block_limits),
2505                              /*evpd*/TRUE,
2506                              /*page_code*/SVPD_BLOCK_LIMITS,
2507                              /*sense_len*/SSD_MIN_SIZE,
2508                              /*timeout*/da_default_timeout * 1000);
2509                 start_ccb->ccb_h.ccb_bp = NULL;
2510                 start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_BLK_LIMITS;
2511                 xpt_action(start_ccb);
2512                 break;
2513         }
2514         case DA_STATE_PROBE_BDC:
2515         {
2516                 struct scsi_vpd_block_characteristics *bdc;
2517
2518                 if (!scsi_vpd_supported_page(periph, SVPD_BDC)) {
2519                         softc->state = DA_STATE_PROBE_ATA;
2520                         goto skipstate;
2521                 }
2522
2523                 bdc = (struct scsi_vpd_block_characteristics *)
2524                         malloc(sizeof(*bdc), M_SCSIDA, M_NOWAIT|M_ZERO);
2525
2526                 if (bdc == NULL) {
2527                         printf("dastart: Couldn't malloc bdc data\n");
2528                         /* da_free_periph??? */
2529                         break;
2530                 }
2531
2532                 scsi_inquiry(&start_ccb->csio,
2533                              /*retries*/da_retry_count,
2534                              /*cbfcnp*/dadone,
2535                              /*tag_action*/MSG_SIMPLE_Q_TAG,
2536                              /*inq_buf*/(u_int8_t *)bdc,
2537                              /*inq_len*/sizeof(*bdc),
2538                              /*evpd*/TRUE,
2539                              /*page_code*/SVPD_BDC,
2540                              /*sense_len*/SSD_MIN_SIZE,
2541                              /*timeout*/da_default_timeout * 1000);
2542                 start_ccb->ccb_h.ccb_bp = NULL;
2543                 start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_BDC;
2544                 xpt_action(start_ccb);
2545                 break;
2546         }
2547         case DA_STATE_PROBE_ATA:
2548         {
2549                 struct ata_params *ata_params;
2550
2551                 if (!scsi_vpd_supported_page(periph, SVPD_ATA_INFORMATION)) {
2552                         daprobedone(periph, start_ccb);
2553                         break;
2554                 }
2555
2556                 ata_params = (struct ata_params*)
2557                         malloc(sizeof(*ata_params), M_SCSIDA, M_NOWAIT|M_ZERO);
2558
2559                 if (ata_params == NULL) {
2560                         printf("dastart: Couldn't malloc ata_params data\n");
2561                         /* da_free_periph??? */
2562                         break;
2563                 }
2564
2565                 scsi_ata_identify(&start_ccb->csio,
2566                                   /*retries*/da_retry_count,
2567                                   /*cbfcnp*/dadone,
2568                                   /*tag_action*/MSG_SIMPLE_Q_TAG,
2569                                   /*data_ptr*/(u_int8_t *)ata_params,
2570                                   /*dxfer_len*/sizeof(*ata_params),
2571                                   /*sense_len*/SSD_FULL_SIZE,
2572                                   /*timeout*/da_default_timeout * 1000);
2573                 start_ccb->ccb_h.ccb_bp = NULL;
2574                 start_ccb->ccb_h.ccb_state = DA_CCB_PROBE_ATA;
2575                 xpt_action(start_ccb);
2576                 break;
2577         }
2578         }
2579 }
2580
2581 /*
2582  * In each of the methods below, while its the caller's
2583  * responsibility to ensure the request will fit into a
2584  * single device request, we might have changed the delete
2585  * method due to the device incorrectly advertising either
2586  * its supported methods or limits.
2587  * 
2588  * To prevent this causing further issues we validate the
2589  * against the methods limits, and warn which would
2590  * otherwise be unnecessary.
2591  */
2592 static void
2593 da_delete_unmap(struct cam_periph *periph, union ccb *ccb, struct bio *bp)
2594 {
2595         struct da_softc *softc = (struct da_softc *)periph->softc;;
2596         struct bio *bp1;
2597         uint8_t *buf = softc->unmap_buf;
2598         uint64_t lba, lastlba = (uint64_t)-1;
2599         uint64_t totalcount = 0;
2600         uint64_t count;
2601         uint32_t lastcount = 0, c;
2602         uint32_t off, ranges = 0;
2603
2604         /*
2605          * Currently this doesn't take the UNMAP
2606          * Granularity and Granularity Alignment
2607          * fields into account.
2608          *
2609          * This could result in both unoptimal unmap
2610          * requests as as well as UNMAP calls unmapping
2611          * fewer LBA's than requested.
2612          */
2613
2614         softc->delete_running = 1;
2615         bzero(softc->unmap_buf, sizeof(softc->unmap_buf));
2616         bp1 = bp;
2617         do {
2618                 bioq_remove(&softc->delete_queue, bp1);
2619                 if (bp1 != bp)
2620                         bioq_insert_tail(&softc->delete_run_queue, bp1);
2621                 lba = bp1->bio_pblkno;
2622                 count = bp1->bio_bcount / softc->params.secsize;
2623
2624                 /* Try to extend the previous range. */
2625                 if (lba == lastlba) {
2626                         c = omin(count, UNMAP_RANGE_MAX - lastcount);
2627                         lastcount += c;
2628                         off = ((ranges - 1) * UNMAP_RANGE_SIZE) +
2629                               UNMAP_HEAD_SIZE;
2630                         scsi_ulto4b(lastcount, &buf[off + 8]);
2631                         count -= c;
2632                         lba +=c;
2633                         totalcount += c;
2634                 }
2635
2636                 while (count > 0) {
2637                         c = omin(count, UNMAP_RANGE_MAX);
2638                         if (totalcount + c > softc->unmap_max_lba ||
2639                             ranges >= softc->unmap_max_ranges) {
2640                                 xpt_print(periph->path,
2641                                     "%s issuing short delete %ld > %ld"
2642                                     "|| %d >= %d",
2643                                     da_delete_method_desc[softc->delete_method],
2644                                     totalcount + c, softc->unmap_max_lba,
2645                                     ranges, softc->unmap_max_ranges);
2646                                 break;
2647                         }
2648                         off = (ranges * UNMAP_RANGE_SIZE) + UNMAP_HEAD_SIZE;
2649                         scsi_u64to8b(lba, &buf[off + 0]);
2650                         scsi_ulto4b(c, &buf[off + 8]);
2651                         lba += c;
2652                         totalcount += c;
2653                         ranges++;
2654                         count -= c;
2655                         lastcount = c;
2656                 }
2657                 lastlba = lba;
2658                 bp1 = bioq_first(&softc->delete_queue);
2659                 if (bp1 == NULL || ranges >= softc->unmap_max_ranges ||
2660                     totalcount + bp1->bio_bcount /
2661                     softc->params.secsize > softc->unmap_max_lba)
2662                         break;
2663         } while (1);
2664         scsi_ulto2b(ranges * 16 + 6, &buf[0]);
2665         scsi_ulto2b(ranges * 16, &buf[2]);
2666
2667         scsi_unmap(&ccb->csio,
2668                    /*retries*/da_retry_count,
2669                    /*cbfcnp*/dadone,
2670                    /*tag_action*/MSG_SIMPLE_Q_TAG,
2671                    /*byte2*/0,
2672                    /*data_ptr*/ buf,
2673                    /*dxfer_len*/ ranges * 16 + 8,
2674                    /*sense_len*/SSD_FULL_SIZE,
2675                    da_default_timeout * 1000);
2676         ccb->ccb_h.ccb_state = DA_CCB_DELETE;
2677 }
2678
2679 static void
2680 da_delete_trim(struct cam_periph *periph, union ccb *ccb, struct bio *bp)
2681 {
2682         struct da_softc *softc = (struct da_softc *)periph->softc;
2683         struct bio *bp1;
2684         uint8_t *buf = softc->unmap_buf;
2685         uint64_t lastlba = (uint64_t)-1;
2686         uint64_t count;
2687         uint64_t lba;
2688         uint32_t lastcount = 0, c, requestcount;
2689         int ranges = 0, off, block_count;
2690
2691         softc->delete_running = 1;
2692         bzero(softc->unmap_buf, sizeof(softc->unmap_buf));
2693         bp1 = bp;
2694         do {
2695                 bioq_remove(&softc->delete_queue, bp1);
2696                 if (bp1 != bp)
2697                         bioq_insert_tail(&softc->delete_run_queue, bp1);
2698                 lba = bp1->bio_pblkno;
2699                 count = bp1->bio_bcount / softc->params.secsize;
2700                 requestcount = count;
2701
2702                 /* Try to extend the previous range. */
2703                 if (lba == lastlba) {
2704                         c = omin(count, ATA_DSM_RANGE_MAX - lastcount);
2705                         lastcount += c;
2706                         off = (ranges - 1) * 8;
2707                         buf[off + 6] = lastcount & 0xff;
2708                         buf[off + 7] = (lastcount >> 8) & 0xff;
2709                         count -= c;
2710                         lba += c;
2711                 }
2712
2713                 while (count > 0) {
2714                         c = omin(count, ATA_DSM_RANGE_MAX);
2715                         off = ranges * 8;
2716
2717                         buf[off + 0] = lba & 0xff;
2718                         buf[off + 1] = (lba >> 8) & 0xff;
2719                         buf[off + 2] = (lba >> 16) & 0xff;
2720                         buf[off + 3] = (lba >> 24) & 0xff;
2721                         buf[off + 4] = (lba >> 32) & 0xff;
2722                         buf[off + 5] = (lba >> 40) & 0xff;
2723                         buf[off + 6] = c & 0xff;
2724                         buf[off + 7] = (c >> 8) & 0xff;
2725                         lba += c;
2726                         ranges++;
2727                         count -= c;
2728                         lastcount = c;
2729                         if (count != 0 && ranges == softc->trim_max_ranges) {
2730                                 xpt_print(periph->path,
2731                                     "%s issuing short delete %ld > %ld\n",
2732                                     da_delete_method_desc[softc->delete_method],
2733                                     requestcount,
2734                                     (softc->trim_max_ranges - ranges) *
2735                                     ATA_DSM_RANGE_MAX);
2736                                 break;
2737                         }
2738                 }
2739                 lastlba = lba;
2740                 bp1 = bioq_first(&softc->delete_queue);
2741                 if (bp1 == NULL || bp1->bio_bcount / softc->params.secsize >
2742                     (softc->trim_max_ranges - ranges) * ATA_DSM_RANGE_MAX)
2743                         break;
2744         } while (1);
2745
2746         block_count = (ranges + ATA_DSM_BLK_RANGES - 1) / ATA_DSM_BLK_RANGES;
2747         scsi_ata_trim(&ccb->csio,
2748                       /*retries*/da_retry_count,
2749                       /*cbfcnp*/dadone,
2750                       /*tag_action*/MSG_SIMPLE_Q_TAG,
2751                       block_count,
2752                       /*data_ptr*/buf,
2753                       /*dxfer_len*/block_count * ATA_DSM_BLK_SIZE,
2754                       /*sense_len*/SSD_FULL_SIZE,
2755                       da_default_timeout * 1000);
2756         ccb->ccb_h.ccb_state = DA_CCB_DELETE;
2757 }
2758
2759 /*
2760  * We calculate ws_max_blks here based off d_delmaxsize instead
2761  * of using softc->ws_max_blks as it is absolute max for the
2762  * device not the protocol max which may well be lower.
2763  */
2764 static void
2765 da_delete_ws(struct cam_periph *periph, union ccb *ccb, struct bio *bp)
2766 {
2767         struct da_softc *softc;
2768         struct bio *bp1;
2769         uint64_t ws_max_blks;
2770         uint64_t lba;
2771         uint64_t count; /* forward compat with WS32 */
2772
2773         softc = (struct da_softc *)periph->softc;
2774         ws_max_blks = softc->disk->d_delmaxsize / softc->params.secsize;
2775         softc->delete_running = 1;
2776         lba = bp->bio_pblkno;
2777         count = 0;
2778         bp1 = bp;
2779         do {
2780                 bioq_remove(&softc->delete_queue, bp1);
2781                 if (bp1 != bp)
2782                         bioq_insert_tail(&softc->delete_run_queue, bp1);
2783                 count += bp1->bio_bcount / softc->params.secsize;
2784                 if (count > ws_max_blks) {
2785                         xpt_print(periph->path,
2786                             "%s issuing short delete %ld > %ld\n",
2787                             da_delete_method_desc[softc->delete_method],
2788                             count, ws_max_blks);
2789                         count = omin(count, ws_max_blks);
2790                         break;
2791                 }
2792                 bp1 = bioq_first(&softc->delete_queue);
2793                 if (bp1 == NULL || lba + count != bp1->bio_pblkno ||
2794                     count + bp1->bio_bcount /
2795                     softc->params.secsize > ws_max_blks)
2796                         break;
2797         } while (1);
2798
2799         scsi_write_same(&ccb->csio,
2800                         /*retries*/da_retry_count,
2801                         /*cbfcnp*/dadone,
2802                         /*tag_action*/MSG_SIMPLE_Q_TAG,
2803                         /*byte2*/softc->delete_method ==
2804                             DA_DELETE_ZERO ? 0 : SWS_UNMAP,
2805                         softc->delete_method == DA_DELETE_WS16 ? 16 : 10,
2806                         /*lba*/lba,
2807                         /*block_count*/count,
2808                         /*data_ptr*/ __DECONST(void *, zero_region),
2809                         /*dxfer_len*/ softc->params.secsize,
2810                         /*sense_len*/SSD_FULL_SIZE,
2811                         da_default_timeout * 1000);
2812         ccb->ccb_h.ccb_state = DA_CCB_DELETE;
2813 }
2814
2815 static int
2816 cmd6workaround(union ccb *ccb)
2817 {
2818         struct scsi_rw_6 cmd6;
2819         struct scsi_rw_10 *cmd10;
2820         struct da_softc *softc;
2821         u_int8_t *cdb;
2822         struct bio *bp;
2823         int frozen;
2824
2825         cdb = ccb->csio.cdb_io.cdb_bytes;
2826         softc = (struct da_softc *)xpt_path_periph(ccb->ccb_h.path)->softc;
2827
2828         if (ccb->ccb_h.ccb_state == DA_CCB_DELETE) {
2829                 da_delete_methods old_method = softc->delete_method;
2830
2831                 /*
2832                  * Typically there are two reasons for failure here
2833                  * 1. Delete method was detected as supported but isn't
2834                  * 2. Delete failed due to invalid params e.g. too big
2835                  *
2836                  * While we will attempt to choose an alternative delete method
2837                  * this may result in short deletes if the existing delete
2838                  * requests from geom are big for the new method choosen.
2839                  *
2840                  * This method assumes that the error which triggered this
2841                  * will not retry the io otherwise a panic will occur
2842                  */
2843                 dadeleteflag(softc, old_method, 0);
2844                 dadeletemethodchoose(softc, DA_DELETE_DISABLE);
2845                 if (softc->delete_method == DA_DELETE_DISABLE)
2846                         xpt_print(ccb->ccb_h.path,
2847                                   "%s failed, disabling BIO_DELETE\n",
2848                                   da_delete_method_desc[old_method]);
2849                 else
2850                         xpt_print(ccb->ccb_h.path,
2851                                   "%s failed, switching to %s BIO_DELETE\n",
2852                                   da_delete_method_desc[old_method],
2853                                   da_delete_method_desc[softc->delete_method]);
2854
2855                 if (DA_SIO) {
2856                         while ((bp = bioq_takefirst(&softc->delete_run_queue))
2857                             != NULL)
2858                                 bioq_disksort(&softc->delete_queue, bp);
2859                 } else {
2860                         while ((bp = bioq_takefirst(&softc->delete_run_queue))
2861                             != NULL)
2862                                 bioq_insert_tail(&softc->delete_queue, bp);
2863                 }
2864                 bioq_insert_tail(&softc->delete_queue,
2865                     (struct bio *)ccb->ccb_h.ccb_bp);
2866                 ccb->ccb_h.ccb_bp = NULL;
2867                 return (0);
2868         }
2869
2870         /* Detect unsupported PREVENT ALLOW MEDIUM REMOVAL. */
2871         if ((ccb->ccb_h.flags & CAM_CDB_POINTER) == 0 &&
2872             (*cdb == PREVENT_ALLOW) &&
2873             (softc->quirks & DA_Q_NO_PREVENT) == 0) {
2874                 if (bootverbose)
2875                         xpt_print(ccb->ccb_h.path,
2876                             "PREVENT ALLOW MEDIUM REMOVAL not supported.\n");
2877                 softc->quirks |= DA_Q_NO_PREVENT;
2878                 return (0);
2879         }
2880
2881         /* Detect unsupported SYNCHRONIZE CACHE(10). */
2882         if ((ccb->ccb_h.flags & CAM_CDB_POINTER) == 0 &&
2883             (*cdb == SYNCHRONIZE_CACHE) &&
2884             (softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
2885                 if (bootverbose)
2886                         xpt_print(ccb->ccb_h.path,
2887                             "SYNCHRONIZE CACHE(10) not supported.\n");
2888                 softc->quirks |= DA_Q_NO_SYNC_CACHE;
2889                 softc->disk->d_flags &= ~DISKFLAG_CANFLUSHCACHE;
2890                 return (0);
2891         }
2892
2893         /* Translation only possible if CDB is an array and cmd is R/W6 */
2894         if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0 ||
2895             (*cdb != READ_6 && *cdb != WRITE_6))
2896                 return 0;
2897
2898         xpt_print(ccb->ccb_h.path, "READ(6)/WRITE(6) not supported, "
2899             "increasing minimum_cmd_size to 10.\n");
2900         softc->minimum_cmd_size = 10;
2901
2902         bcopy(cdb, &cmd6, sizeof(struct scsi_rw_6));
2903         cmd10 = (struct scsi_rw_10 *)cdb;
2904         cmd10->opcode = (cmd6.opcode == READ_6) ? READ_10 : WRITE_10;
2905         cmd10->byte2 = 0;
2906         scsi_ulto4b(scsi_3btoul(cmd6.addr), cmd10->addr);
2907         cmd10->reserved = 0;
2908         scsi_ulto2b(cmd6.length, cmd10->length);
2909         cmd10->control = cmd6.control;
2910         ccb->csio.cdb_len = sizeof(*cmd10);
2911
2912         /* Requeue request, unfreezing queue if necessary */
2913         frozen = (ccb->ccb_h.status & CAM_DEV_QFRZN) != 0;
2914         ccb->ccb_h.status = CAM_REQUEUE_REQ;
2915         xpt_action(ccb);
2916         if (frozen) {
2917                 cam_release_devq(ccb->ccb_h.path,
2918                                  /*relsim_flags*/0,
2919                                  /*reduction*/0,
2920                                  /*timeout*/0,
2921                                  /*getcount_only*/0);
2922         }
2923         return (ERESTART);
2924 }
2925
2926 static void
2927 dadone(struct cam_periph *periph, union ccb *done_ccb)
2928 {
2929         struct da_softc *softc;
2930         struct ccb_scsiio *csio;
2931         u_int32_t  priority;
2932         da_ccb_state state;
2933
2934         softc = (struct da_softc *)periph->softc;
2935         priority = done_ccb->ccb_h.pinfo.priority;
2936
2937         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dadone\n"));
2938
2939         csio = &done_ccb->csio;
2940         state = csio->ccb_h.ccb_state & DA_CCB_TYPE_MASK;
2941         switch (state) {
2942         case DA_CCB_BUFFER_IO:
2943         case DA_CCB_DELETE:
2944         {
2945                 struct bio *bp, *bp1;
2946
2947                 bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
2948                 if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2949                         int error;
2950                         int sf;
2951
2952                         if ((csio->ccb_h.ccb_state & DA_CCB_RETRY_UA) != 0)
2953                                 sf = SF_RETRY_UA;
2954                         else
2955                                 sf = 0;
2956
2957                         error = daerror(done_ccb, CAM_RETRY_SELTO, sf);
2958                         if (error == ERESTART) {
2959                                 /*
2960                                  * A retry was scheduled, so
2961                                  * just return.
2962                                  */
2963                                 return;
2964                         }
2965                         bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
2966                         if (error != 0) {
2967                                 int queued_error;
2968
2969                                 /*
2970                                  * return all queued I/O with EIO, so that
2971                                  * the client can retry these I/Os in the
2972                                  * proper order should it attempt to recover.
2973                                  */
2974                                 queued_error = EIO;
2975
2976                                 if (error == ENXIO
2977                                  && (softc->flags & DA_FLAG_PACK_INVALID)== 0) {
2978                                         /*
2979                                          * Catastrophic error.  Mark our pack as
2980                                          * invalid.
2981                                          */
2982                                         /*
2983                                          * XXX See if this is really a media
2984                                          * XXX change first?
2985                                          */
2986                                         xpt_print(periph->path,
2987                                             "Invalidating pack\n");
2988                                         softc->flags |= DA_FLAG_PACK_INVALID;
2989                                         queued_error = ENXIO;
2990                                 }
2991                                 bioq_flush(&softc->bio_queue, NULL,
2992                                            queued_error);
2993                                 if (bp != NULL) {
2994                                         bp->bio_error = error;
2995                                         bp->bio_resid = bp->bio_bcount;
2996                                         bp->bio_flags |= BIO_ERROR;
2997                                 }
2998                         } else if (bp != NULL) {
2999                                 if (state == DA_CCB_DELETE)
3000                                         bp->bio_resid = 0;
3001                                 else
3002                                         bp->bio_resid = csio->resid;
3003                                 bp->bio_error = 0;
3004                                 if (bp->bio_resid != 0)
3005                                         bp->bio_flags |= BIO_ERROR;
3006                         }
3007                         if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
3008                                 cam_release_devq(done_ccb->ccb_h.path,
3009                                                  /*relsim_flags*/0,
3010                                                  /*reduction*/0,
3011                                                  /*timeout*/0,
3012                                                  /*getcount_only*/0);
3013                 } else if (bp != NULL) {
3014                         if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
3015                                 panic("REQ_CMP with QFRZN");
3016                         if (state == DA_CCB_DELETE)
3017                                 bp->bio_resid = 0;
3018                         else
3019                                 bp->bio_resid = csio->resid;
3020                         if (csio->resid > 0)
3021                                 bp->bio_flags |= BIO_ERROR;
3022                         if (softc->error_inject != 0) {
3023                                 bp->bio_error = softc->error_inject;
3024                                 bp->bio_resid = bp->bio_bcount;
3025                                 bp->bio_flags |= BIO_ERROR;
3026                                 softc->error_inject = 0;
3027                         }
3028                 }
3029
3030                 LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
3031                 if (LIST_EMPTY(&softc->pending_ccbs))
3032                         softc->flags |= DA_FLAG_WAS_OTAG;
3033
3034                 if (state == DA_CCB_DELETE) {
3035                         while ((bp1 = bioq_takefirst(&softc->delete_run_queue))
3036                             != NULL) {
3037                                 bp1->bio_error = bp->bio_error;
3038                                 if (bp->bio_flags & BIO_ERROR) {
3039                                         bp1->bio_flags |= BIO_ERROR;
3040                                         bp1->bio_resid = bp1->bio_bcount;
3041                                 } else
3042                                         bp1->bio_resid = 0;
3043                                 biodone(bp1);
3044                         }
3045                         softc->delete_running = 0;
3046                         if (bp != NULL)
3047                                 biodone(bp);
3048                         daschedule(periph);
3049                 } else if (bp != NULL)
3050                         biodone(bp);
3051                 break;
3052         }
3053         case DA_CCB_PROBE_RC:
3054         case DA_CCB_PROBE_RC16:
3055         {
3056                 struct     scsi_read_capacity_data *rdcap;
3057                 struct     scsi_read_capacity_data_long *rcaplong;
3058                 char       announce_buf[80];
3059                 int        lbp;
3060
3061                 lbp = 0;
3062                 rdcap = NULL;
3063                 rcaplong = NULL;
3064                 if (state == DA_CCB_PROBE_RC)
3065                         rdcap =(struct scsi_read_capacity_data *)csio->data_ptr;
3066                 else
3067                         rcaplong = (struct scsi_read_capacity_data_long *)
3068                                 csio->data_ptr;
3069
3070                 if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3071                         struct disk_params *dp;
3072                         uint32_t block_size;
3073                         uint64_t maxsector;
3074                         u_int lbppbe;   /* LB per physical block exponent. */
3075                         u_int lalba;    /* Lowest aligned LBA. */
3076
3077                         if (state == DA_CCB_PROBE_RC) {
3078                                 block_size = scsi_4btoul(rdcap->length);
3079                                 maxsector = scsi_4btoul(rdcap->addr);
3080                                 lbppbe = 0;
3081                                 lalba = 0;
3082
3083                                 /*
3084                                  * According to SBC-2, if the standard 10
3085                                  * byte READ CAPACITY command returns 2^32,
3086                                  * we should issue the 16 byte version of
3087                                  * the command, since the device in question
3088                                  * has more sectors than can be represented
3089                                  * with the short version of the command.
3090                                  */
3091                                 if (maxsector == 0xffffffff) {
3092                                         free(rdcap, M_SCSIDA);
3093                                         xpt_release_ccb(done_ccb);
3094                                         softc->state = DA_STATE_PROBE_RC16;
3095                                         xpt_schedule(periph, priority);
3096                                         return;
3097                                 }
3098                         } else {
3099                                 block_size = scsi_4btoul(rcaplong->length);
3100                                 maxsector = scsi_8btou64(rcaplong->addr);
3101                                 lbppbe = rcaplong->prot_lbppbe & SRC16_LBPPBE;
3102                                 lalba = scsi_2btoul(rcaplong->lalba_lbp);
3103                         }
3104
3105                         /*
3106                          * Because GEOM code just will panic us if we
3107                          * give them an 'illegal' value we'll avoid that
3108                          * here.
3109                          */
3110                         if (block_size == 0) {
3111                                 block_size = 512;
3112                                 if (maxsector == 0)
3113                                         maxsector = -1;
3114                         }
3115                         if (block_size >= MAXPHYS) {
3116                                 xpt_print(periph->path,
3117                                     "unsupportable block size %ju\n",
3118                                     (uintmax_t) block_size);
3119                                 announce_buf[0] = '\0';
3120                                 cam_periph_invalidate(periph);
3121                         } else {
3122                                 /*
3123                                  * We pass rcaplong into dasetgeom(),
3124                                  * because it will only use it if it is
3125                                  * non-NULL.
3126                                  */
3127                                 dasetgeom(periph, block_size, maxsector,
3128                                           rcaplong, sizeof(*rcaplong));
3129                                 lbp = (lalba & SRC16_LBPME_A);
3130                                 dp = &softc->params;
3131                                 snprintf(announce_buf, sizeof(announce_buf),
3132                                         "%juMB (%ju %u byte sectors: %dH %dS/T "
3133                                         "%dC)", (uintmax_t)
3134                                         (((uintmax_t)dp->secsize *
3135                                         dp->sectors) / (1024*1024)),
3136                                         (uintmax_t)dp->sectors,
3137                                         dp->secsize, dp->heads,
3138                                         dp->secs_per_track, dp->cylinders);
3139                         }
3140                 } else {
3141                         int     error;
3142
3143                         announce_buf[0] = '\0';
3144
3145                         /*
3146                          * Retry any UNIT ATTENTION type errors.  They
3147                          * are expected at boot.
3148                          */
3149                         error = daerror(done_ccb, CAM_RETRY_SELTO,
3150                                         SF_RETRY_UA|SF_NO_PRINT);
3151                         if (error == ERESTART) {
3152                                 /*
3153                                  * A retry was scheuled, so
3154                                  * just return.
3155                                  */
3156                                 return;
3157                         } else if (error != 0) {
3158                                 int asc, ascq;
3159                                 int sense_key, error_code;
3160                                 int have_sense;
3161                                 cam_status status;
3162                                 struct ccb_getdev cgd;
3163
3164                                 /* Don't wedge this device's queue */
3165                                 status = done_ccb->ccb_h.status;
3166                                 if ((status & CAM_DEV_QFRZN) != 0)
3167                                         cam_release_devq(done_ccb->ccb_h.path,
3168                                                          /*relsim_flags*/0,
3169                                                          /*reduction*/0,
3170                                                          /*timeout*/0,
3171                                                          /*getcount_only*/0);
3172
3173
3174                                 xpt_setup_ccb(&cgd.ccb_h, 
3175                                               done_ccb->ccb_h.path,
3176                                               CAM_PRIORITY_NORMAL);
3177                                 cgd.ccb_h.func_code = XPT_GDEV_TYPE;
3178                                 xpt_action((union ccb *)&cgd);
3179
3180                                 if (scsi_extract_sense_ccb(done_ccb,
3181                                     &error_code, &sense_key, &asc, &ascq))
3182                                         have_sense = TRUE;
3183                                 else
3184                                         have_sense = FALSE;
3185
3186                                 /*
3187                                  * If we tried READ CAPACITY(16) and failed,
3188                                  * fallback to READ CAPACITY(10).
3189                                  */
3190                                 if ((state == DA_CCB_PROBE_RC16) &&
3191                                     (softc->flags & DA_FLAG_CAN_RC16) &&
3192                                     (((csio->ccb_h.status & CAM_STATUS_MASK) ==
3193                                         CAM_REQ_INVALID) ||
3194                                      ((have_sense) &&
3195                                       (error_code == SSD_CURRENT_ERROR) &&
3196                                       (sense_key == SSD_KEY_ILLEGAL_REQUEST)))) {
3197                                         softc->flags &= ~DA_FLAG_CAN_RC16;
3198                                         free(rdcap, M_SCSIDA);
3199                                         xpt_release_ccb(done_ccb);
3200                                         softc->state = DA_STATE_PROBE_RC;
3201                                         xpt_schedule(periph, priority);
3202                                         return;
3203                                 } else
3204                                 /*
3205                                  * Attach to anything that claims to be a
3206                                  * direct access or optical disk device,
3207                                  * as long as it doesn't return a "Logical
3208                                  * unit not supported" (0x25) error.
3209                                  */
3210                                 if ((have_sense) && (asc != 0x25)
3211                                  && (error_code == SSD_CURRENT_ERROR)) {
3212                                         const char *sense_key_desc;
3213                                         const char *asc_desc;
3214
3215                                         dasetgeom(periph, 512, -1, NULL, 0);
3216                                         scsi_sense_desc(sense_key, asc, ascq,
3217                                                         &cgd.inq_data,
3218                                                         &sense_key_desc,
3219                                                         &asc_desc);
3220                                         snprintf(announce_buf,
3221                                             sizeof(announce_buf),
3222                                                 "Attempt to query device "
3223                                                 "size failed: %s, %s",
3224                                                 sense_key_desc,
3225                                                 asc_desc);
3226                                 } else { 
3227                                         if (have_sense)
3228                                                 scsi_sense_print(
3229                                                         &done_ccb->csio);
3230                                         else {
3231                                                 xpt_print(periph->path,
3232                                                     "got CAM status %#x\n",
3233                                                     done_ccb->ccb_h.status);
3234                                         }
3235
3236                                         xpt_print(periph->path, "fatal error, "
3237                                             "failed to attach to device\n");
3238
3239                                         /*
3240                                          * Free up resources.
3241                                          */
3242                                         cam_periph_invalidate(periph);
3243                                 } 
3244                         }
3245                 }
3246                 free(csio->data_ptr, M_SCSIDA);
3247                 if (announce_buf[0] != '\0' &&
3248                     ((softc->flags & DA_FLAG_ANNOUNCED) == 0)) {
3249                         /*
3250                          * Create our sysctl variables, now that we know
3251                          * we have successfully attached.
3252                          */
3253                         /* increase the refcount */
3254                         if (cam_periph_acquire(periph) == CAM_REQ_CMP) {
3255                                 taskqueue_enqueue(taskqueue_thread,
3256                                                   &softc->sysctl_task);
3257                                 xpt_announce_periph(periph, announce_buf);
3258                                 xpt_announce_quirks(periph, softc->quirks,
3259                                     DA_Q_BIT_STRING);
3260                         } else {
3261                                 xpt_print(periph->path, "fatal error, "
3262                                     "could not acquire reference count\n");
3263                         }
3264                 }
3265
3266                 /* We already probed the device. */
3267                 if (softc->flags & DA_FLAG_PROBED) {
3268                         daprobedone(periph, done_ccb);
3269                         return;
3270                 }
3271
3272                 /* Ensure re-probe doesn't see old delete. */
3273                 softc->delete_available = 0;
3274                 if (lbp && (softc->quirks & DA_Q_NO_UNMAP) == 0) {
3275                         /*
3276                          * Based on older SBC-3 spec revisions
3277                          * any of the UNMAP methods "may" be
3278                          * available via LBP given this flag so
3279                          * we flag all of them as availble and
3280                          * then remove those which further
3281                          * probes confirm aren't available
3282                          * later.
3283                          *
3284                          * We could also check readcap(16) p_type
3285                          * flag to exclude one or more invalid
3286                          * write same (X) types here
3287                          */
3288                         dadeleteflag(softc, DA_DELETE_WS16, 1);
3289                         dadeleteflag(softc, DA_DELETE_WS10, 1);
3290                         dadeleteflag(softc, DA_DELETE_ZERO, 1);
3291                         dadeleteflag(softc, DA_DELETE_UNMAP, 1);
3292
3293                         xpt_release_ccb(done_ccb);
3294                         softc->state = DA_STATE_PROBE_LBP;
3295                         xpt_schedule(periph, priority);
3296                         return;
3297                 }
3298
3299                 xpt_release_ccb(done_ccb);
3300                 softc->state = DA_STATE_PROBE_BDC;
3301                 xpt_schedule(periph, priority);
3302                 return;
3303         }
3304         case DA_CCB_PROBE_LBP:
3305         {
3306                 struct scsi_vpd_logical_block_prov *lbp;
3307
3308                 lbp = (struct scsi_vpd_logical_block_prov *)csio->data_ptr;
3309
3310                 if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3311                         /*
3312                          * T10/1799-D Revision 31 states at least one of these
3313                          * must be supported but we don't currently enforce this.
3314                          */
3315                         dadeleteflag(softc, DA_DELETE_WS16,
3316                                      (lbp->flags & SVPD_LBP_WS16));
3317                         dadeleteflag(softc, DA_DELETE_WS10,
3318                                      (lbp->flags & SVPD_LBP_WS10));
3319                         dadeleteflag(softc, DA_DELETE_ZERO,
3320                                      (lbp->flags & SVPD_LBP_WS10));
3321                         dadeleteflag(softc, DA_DELETE_UNMAP,
3322                                      (lbp->flags & SVPD_LBP_UNMAP));
3323                 } else {
3324                         int error;
3325                         error = daerror(done_ccb, CAM_RETRY_SELTO,
3326                                         SF_RETRY_UA|SF_NO_PRINT);
3327                         if (error == ERESTART)
3328                                 return;
3329                         else if (error != 0) {
3330                                 if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
3331                                         /* Don't wedge this device's queue */
3332                                         cam_release_devq(done_ccb->ccb_h.path,
3333                                                          /*relsim_flags*/0,
3334                                                          /*reduction*/0,
3335                                                          /*timeout*/0,
3336                                                          /*getcount_only*/0);
3337                                 }
3338
3339                                 /*
3340                                  * Failure indicates we don't support any SBC-3
3341                                  * delete methods with UNMAP
3342                                  */
3343                         }
3344                 }
3345
3346                 free(lbp, M_SCSIDA);
3347                 xpt_release_ccb(done_ccb);
3348                 softc->state = DA_STATE_PROBE_BLK_LIMITS;
3349                 xpt_schedule(periph, priority);
3350                 return;
3351         }
3352         case DA_CCB_PROBE_BLK_LIMITS:
3353         {
3354                 struct scsi_vpd_block_limits *block_limits;
3355
3356                 block_limits = (struct scsi_vpd_block_limits *)csio->data_ptr;
3357
3358                 if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3359                         uint32_t max_txfer_len = scsi_4btoul(
3360                                 block_limits->max_txfer_len);
3361                         uint32_t max_unmap_lba_cnt = scsi_4btoul(
3362                                 block_limits->max_unmap_lba_cnt);
3363                         uint32_t max_unmap_blk_cnt = scsi_4btoul(
3364                                 block_limits->max_unmap_blk_cnt);
3365                         uint64_t ws_max_blks = scsi_8btou64(
3366                                 block_limits->max_write_same_length);
3367
3368                         if (max_txfer_len != 0) {
3369                                 softc->disk->d_maxsize = MIN(softc->maxio,
3370                                     (off_t)max_txfer_len * softc->params.secsize);
3371                         }
3372
3373                         /*
3374                          * We should already support UNMAP but we check lba
3375                          * and block count to be sure
3376                          */
3377                         if (max_unmap_lba_cnt != 0x00L &&
3378                             max_unmap_blk_cnt != 0x00L) {
3379                                 softc->unmap_max_lba = max_unmap_lba_cnt;
3380                                 softc->unmap_max_ranges = min(max_unmap_blk_cnt,
3381                                         UNMAP_MAX_RANGES);
3382                         } else {
3383                                 /*
3384                                  * Unexpected UNMAP limits which means the
3385                                  * device doesn't actually support UNMAP
3386                                  */
3387                                 dadeleteflag(softc, DA_DELETE_UNMAP, 0);
3388                         }
3389
3390                         if (ws_max_blks != 0x00L)
3391                                 softc->ws_max_blks = ws_max_blks;
3392                 } else {
3393                         int error;
3394                         error = daerror(done_ccb, CAM_RETRY_SELTO,
3395                                         SF_RETRY_UA|SF_NO_PRINT);
3396                         if (error == ERESTART)
3397                                 return;
3398                         else if (error != 0) {
3399                                 if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
3400                                         /* Don't wedge this device's queue */
3401                                         cam_release_devq(done_ccb->ccb_h.path,
3402                                                          /*relsim_flags*/0,
3403                                                          /*reduction*/0,
3404                                                          /*timeout*/0,
3405                                                          /*getcount_only*/0);
3406                                 }
3407
3408                                 /*
3409                                  * Failure here doesn't mean UNMAP is not
3410                                  * supported as this is an optional page.
3411                                  */
3412                                 softc->unmap_max_lba = 1;
3413                                 softc->unmap_max_ranges = 1;
3414                         }
3415                 }
3416
3417                 free(block_limits, M_SCSIDA);
3418                 xpt_release_ccb(done_ccb);
3419                 softc->state = DA_STATE_PROBE_BDC;
3420                 xpt_schedule(periph, priority);
3421                 return;
3422         }
3423         case DA_CCB_PROBE_BDC:
3424         {
3425                 struct scsi_vpd_block_characteristics *bdc;
3426
3427                 bdc = (struct scsi_vpd_block_characteristics *)csio->data_ptr;
3428
3429                 if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3430                         /*
3431                          * Disable queue sorting for non-rotational media
3432                          * by default.
3433                          */
3434                         if (scsi_2btoul(bdc->medium_rotation_rate) ==
3435                             SVPD_BDC_RATE_NONE_ROTATING)
3436                                 softc->sort_io_queue = 0;
3437                 } else {
3438                         int error;
3439                         error = daerror(done_ccb, CAM_RETRY_SELTO,
3440                                         SF_RETRY_UA|SF_NO_PRINT);
3441                         if (error == ERESTART)
3442                                 return;
3443                         else if (error != 0) {
3444                                 if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
3445                                         /* Don't wedge this device's queue */
3446                                         cam_release_devq(done_ccb->ccb_h.path,
3447                                                          /*relsim_flags*/0,
3448                                                          /*reduction*/0,
3449                                                          /*timeout*/0,
3450                                                          /*getcount_only*/0);
3451                                 }
3452                         }
3453                 }
3454
3455                 free(bdc, M_SCSIDA);
3456                 xpt_release_ccb(done_ccb);
3457                 softc->state = DA_STATE_PROBE_ATA;
3458                 xpt_schedule(periph, priority);
3459                 return;
3460         }
3461         case DA_CCB_PROBE_ATA:
3462         {
3463                 int i;
3464                 struct ata_params *ata_params;
3465                 int16_t *ptr;
3466
3467                 ata_params = (struct ata_params *)csio->data_ptr;
3468                 ptr = (uint16_t *)ata_params;
3469
3470                 if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
3471                         for (i = 0; i < sizeof(*ata_params) / 2; i++)
3472                                 ptr[i] = le16toh(ptr[i]);
3473                         if (ata_params->support_dsm & ATA_SUPPORT_DSM_TRIM &&
3474                             (softc->quirks & DA_Q_NO_UNMAP) == 0) {
3475                                 dadeleteflag(softc, DA_DELETE_ATA_TRIM, 1);
3476                                 if (ata_params->max_dsm_blocks != 0)
3477                                         softc->trim_max_ranges = min(
3478                                           softc->trim_max_ranges,
3479                                           ata_params->max_dsm_blocks *
3480                                           ATA_DSM_BLK_RANGES);
3481                         }
3482                         /*
3483                          * Disable queue sorting for non-rotational media
3484                          * by default.
3485                          */
3486                         if (ata_params->media_rotation_rate == 1)
3487                                 softc->sort_io_queue = 0;
3488                 } else {
3489                         int error;
3490                         error = daerror(done_ccb, CAM_RETRY_SELTO,
3491                                         SF_RETRY_UA|SF_NO_PRINT);
3492                         if (error == ERESTART)
3493                                 return;
3494                         else if (error != 0) {
3495                                 if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
3496                                         /* Don't wedge this device's queue */
3497                                         cam_release_devq(done_ccb->ccb_h.path,
3498                                                          /*relsim_flags*/0,
3499                                                          /*reduction*/0,
3500                                                          /*timeout*/0,
3501                                                          /*getcount_only*/0);
3502                                 }
3503                         }
3504                 }
3505
3506                 free(ata_params, M_SCSIDA);
3507                 daprobedone(periph, done_ccb);
3508                 return;
3509         }
3510         case DA_CCB_WAITING:
3511         {
3512                 /* Caller will release the CCB */
3513                 wakeup(&done_ccb->ccb_h.cbfcnp);
3514                 return;
3515         }
3516         case DA_CCB_DUMP:
3517                 /* No-op.  We're polling */
3518                 return;
3519         case DA_CCB_TUR:
3520         {
3521                 if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3522
3523                         if (daerror(done_ccb, CAM_RETRY_SELTO,
3524                             SF_RETRY_UA | SF_NO_RECOVERY | SF_NO_PRINT) ==
3525                             ERESTART)
3526                                 return;
3527                         if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
3528                                 cam_release_devq(done_ccb->ccb_h.path,
3529                                                  /*relsim_flags*/0,
3530                                                  /*reduction*/0,
3531                                                  /*timeout*/0,
3532                                                  /*getcount_only*/0);
3533                 }
3534                 xpt_release_ccb(done_ccb);
3535                 cam_periph_release_locked(periph);
3536                 return;
3537         }
3538         default:
3539                 break;
3540         }
3541         xpt_release_ccb(done_ccb);
3542 }
3543
3544 static void
3545 dareprobe(struct cam_periph *periph)
3546 {
3547         struct da_softc   *softc;
3548         cam_status status;
3549
3550         softc = (struct da_softc *)periph->softc;
3551
3552         /* Probe in progress; don't interfere. */
3553         if (softc->state != DA_STATE_NORMAL)
3554                 return;
3555
3556         status = cam_periph_acquire(periph);
3557         KASSERT(status == CAM_REQ_CMP,
3558             ("dareprobe: cam_periph_acquire failed"));
3559
3560         if (softc->flags & DA_FLAG_CAN_RC16)
3561                 softc->state = DA_STATE_PROBE_RC16;
3562         else
3563                 softc->state = DA_STATE_PROBE_RC;
3564
3565         xpt_schedule(periph, CAM_PRIORITY_DEV);
3566 }
3567
3568 static int
3569 daerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
3570 {
3571         struct da_softc   *softc;
3572         struct cam_periph *periph;
3573         int error, error_code, sense_key, asc, ascq;
3574
3575         periph = xpt_path_periph(ccb->ccb_h.path);
3576         softc = (struct da_softc *)periph->softc;
3577
3578         /*
3579          * Automatically detect devices that do not support
3580          * READ(6)/WRITE(6) and upgrade to using 10 byte cdbs.
3581          */
3582         error = 0;
3583         if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INVALID) {
3584                 error = cmd6workaround(ccb);
3585         } else if (scsi_extract_sense_ccb(ccb,
3586             &error_code, &sense_key, &asc, &ascq)) {
3587                 if (sense_key == SSD_KEY_ILLEGAL_REQUEST)
3588                         error = cmd6workaround(ccb);
3589                 /*
3590                  * If the target replied with CAPACITY DATA HAS CHANGED UA,
3591                  * query the capacity and notify upper layers.
3592                  */
3593                 else if (sense_key == SSD_KEY_UNIT_ATTENTION &&
3594                     asc == 0x2A && ascq == 0x09) {
3595                         xpt_print(periph->path, "Capacity data has changed\n");
3596                         softc->flags &= ~DA_FLAG_PROBED;
3597                         dareprobe(periph);
3598                         sense_flags |= SF_NO_PRINT;
3599                 } else if (sense_key == SSD_KEY_UNIT_ATTENTION &&
3600                     asc == 0x28 && ascq == 0x00) {
3601                         softc->flags &= ~DA_FLAG_PROBED;
3602                         disk_media_changed(softc->disk, M_NOWAIT);
3603                 } else if (sense_key == SSD_KEY_UNIT_ATTENTION &&
3604                     asc == 0x3F && ascq == 0x03) {
3605                         xpt_print(periph->path, "INQUIRY data has changed\n");
3606                         softc->flags &= ~DA_FLAG_PROBED;
3607                         dareprobe(periph);
3608                         sense_flags |= SF_NO_PRINT;
3609                 } else if (sense_key == SSD_KEY_NOT_READY &&
3610                     asc == 0x3a && (softc->flags & DA_FLAG_PACK_INVALID) == 0) {
3611                         softc->flags |= DA_FLAG_PACK_INVALID;
3612                         disk_media_gone(softc->disk, M_NOWAIT);
3613                 }
3614         }
3615         if (error == ERESTART)
3616                 return (ERESTART);
3617
3618         /*
3619          * XXX
3620          * Until we have a better way of doing pack validation,
3621          * don't treat UAs as errors.
3622          */
3623         sense_flags |= SF_RETRY_UA;
3624
3625         if (softc->quirks & DA_Q_RETRY_BUSY)
3626                 sense_flags |= SF_RETRY_BUSY;
3627         return(cam_periph_error(ccb, cam_flags, sense_flags,
3628                                 &softc->saved_ccb));
3629 }
3630
3631 static void
3632 damediapoll(void *arg)
3633 {
3634         struct cam_periph *periph = arg;
3635         struct da_softc *softc = periph->softc;
3636
3637         if (!softc->tur && LIST_EMPTY(&softc->pending_ccbs)) {
3638                 if (cam_periph_acquire(periph) == CAM_REQ_CMP) {
3639                         softc->tur = 1;
3640                         daschedule(periph);
3641                 }
3642         }
3643         /* Queue us up again */
3644         if (da_poll_period != 0)
3645                 callout_schedule(&softc->mediapoll_c, da_poll_period * hz);
3646 }
3647
3648 static void
3649 daprevent(struct cam_periph *periph, int action)
3650 {
3651         struct  da_softc *softc;
3652         union   ccb *ccb;               
3653         int     error;
3654                 
3655         softc = (struct da_softc *)periph->softc;
3656
3657         if (((action == PR_ALLOW)
3658           && (softc->flags & DA_FLAG_PACK_LOCKED) == 0)
3659          || ((action == PR_PREVENT)
3660           && (softc->flags & DA_FLAG_PACK_LOCKED) != 0)) {
3661                 return;
3662         }
3663
3664         ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3665
3666         scsi_prevent(&ccb->csio,
3667                      /*retries*/1,
3668                      /*cbcfp*/dadone,
3669                      MSG_SIMPLE_Q_TAG,
3670                      action,
3671                      SSD_FULL_SIZE,
3672                      5000);
3673
3674         error = cam_periph_runccb(ccb, daerror, CAM_RETRY_SELTO,
3675             SF_RETRY_UA | SF_NO_PRINT, softc->disk->d_devstat);
3676
3677         if (error == 0) {
3678                 if (action == PR_ALLOW)
3679                         softc->flags &= ~DA_FLAG_PACK_LOCKED;
3680                 else
3681                         softc->flags |= DA_FLAG_PACK_LOCKED;
3682         }
3683
3684         xpt_release_ccb(ccb);
3685 }
3686
3687 static void
3688 dasetgeom(struct cam_periph *periph, uint32_t block_len, uint64_t maxsector,
3689           struct scsi_read_capacity_data_long *rcaplong, size_t rcap_len)
3690 {
3691         struct ccb_calc_geometry ccg;
3692         struct da_softc *softc;
3693         struct disk_params *dp;
3694         u_int lbppbe, lalba;
3695
3696         softc = (struct da_softc *)periph->softc;
3697
3698         dp = &softc->params;
3699         dp->secsize = block_len;
3700         dp->sectors = maxsector + 1;
3701         if (rcaplong != NULL) {
3702                 lbppbe = rcaplong->prot_lbppbe & SRC16_LBPPBE;
3703                 lalba = scsi_2btoul(rcaplong->lalba_lbp);
3704                 lalba &= SRC16_LALBA_A;
3705         } else {
3706                 lbppbe = 0;
3707                 lalba = 0;
3708         }
3709
3710         if (lbppbe > 0) {
3711                 dp->stripesize = block_len << lbppbe;
3712                 dp->stripeoffset = (dp->stripesize - block_len * lalba) %
3713                     dp->stripesize;
3714         } else if (softc->quirks & DA_Q_4K) {
3715                 dp->stripesize = 4096;
3716                 dp->stripeoffset = 0;
3717         } else {
3718                 dp->stripesize = 0;
3719                 dp->stripeoffset = 0;
3720         }
3721         /*
3722          * Have the controller provide us with a geometry
3723          * for this disk.  The only time the geometry
3724          * matters is when we boot and the controller
3725          * is the only one knowledgeable enough to come
3726          * up with something that will make this a bootable
3727          * device.
3728          */
3729         xpt_setup_ccb(&ccg.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
3730         ccg.ccb_h.func_code = XPT_CALC_GEOMETRY;
3731         ccg.block_size = dp->secsize;
3732         ccg.volume_size = dp->sectors;
3733         ccg.heads = 0;
3734         ccg.secs_per_track = 0;
3735         ccg.cylinders = 0;
3736         xpt_action((union ccb*)&ccg);
3737         if ((ccg.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3738                 /*
3739                  * We don't know what went wrong here- but just pick
3740                  * a geometry so we don't have nasty things like divide
3741                  * by zero.
3742                  */
3743                 dp->heads = 255;
3744                 dp->secs_per_track = 255;
3745                 dp->cylinders = dp->sectors / (255 * 255);
3746                 if (dp->cylinders == 0) {
3747                         dp->cylinders = 1;
3748                 }
3749         } else {
3750                 dp->heads = ccg.heads;
3751                 dp->secs_per_track = ccg.secs_per_track;
3752                 dp->cylinders = ccg.cylinders;
3753         }
3754
3755         /*
3756          * If the user supplied a read capacity buffer, and if it is
3757          * different than the previous buffer, update the data in the EDT.
3758          * If it's the same, we don't bother.  This avoids sending an
3759          * update every time someone opens this device.
3760          */
3761         if ((rcaplong != NULL)
3762          && (bcmp(rcaplong, &softc->rcaplong,
3763                   min(sizeof(softc->rcaplong), rcap_len)) != 0)) {
3764                 struct ccb_dev_advinfo cdai;
3765
3766                 xpt_setup_ccb(&cdai.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
3767                 cdai.ccb_h.func_code = XPT_DEV_ADVINFO;
3768                 cdai.buftype = CDAI_TYPE_RCAPLONG;
3769                 cdai.flags |= CDAI_FLAG_STORE;
3770                 cdai.bufsiz = rcap_len;
3771                 cdai.buf = (uint8_t *)rcaplong;
3772                 xpt_action((union ccb *)&cdai);
3773                 if ((cdai.ccb_h.status & CAM_DEV_QFRZN) != 0)
3774                         cam_release_devq(cdai.ccb_h.path, 0, 0, 0, FALSE);
3775                 if (cdai.ccb_h.status != CAM_REQ_CMP) {
3776                         xpt_print(periph->path, "%s: failed to set read "
3777                                   "capacity advinfo\n", __func__);
3778                         /* Use cam_error_print() to decode the status */
3779                         cam_error_print((union ccb *)&cdai, CAM_ESF_CAM_STATUS,
3780                                         CAM_EPF_ALL);
3781                 } else {
3782                         bcopy(rcaplong, &softc->rcaplong,
3783                               min(sizeof(softc->rcaplong), rcap_len));
3784                 }
3785         }
3786
3787         softc->disk->d_sectorsize = softc->params.secsize;
3788         softc->disk->d_mediasize = softc->params.secsize * (off_t)softc->params.sectors;
3789         softc->disk->d_stripesize = softc->params.stripesize;
3790         softc->disk->d_stripeoffset = softc->params.stripeoffset;
3791         /* XXX: these are not actually "firmware" values, so they may be wrong */
3792         softc->disk->d_fwsectors = softc->params.secs_per_track;
3793         softc->disk->d_fwheads = softc->params.heads;
3794         softc->disk->d_devstat->block_size = softc->params.secsize;
3795         softc->disk->d_devstat->flags &= ~DEVSTAT_BS_UNAVAILABLE;
3796 }
3797
3798 static void
3799 dasendorderedtag(void *arg)
3800 {
3801         struct da_softc *softc = arg;
3802
3803         if (da_send_ordered) {
3804                 if (!LIST_EMPTY(&softc->pending_ccbs)) {
3805                         if ((softc->flags & DA_FLAG_WAS_OTAG) == 0)
3806                                 softc->flags |= DA_FLAG_NEED_OTAG;
3807                         softc->flags &= ~DA_FLAG_WAS_OTAG;
3808                 }
3809         }
3810         /* Queue us up again */
3811         callout_reset(&softc->sendordered_c,
3812             (da_default_timeout * hz) / DA_ORDEREDTAG_INTERVAL,
3813             dasendorderedtag, softc);
3814 }
3815
3816 /*
3817  * Step through all DA peripheral drivers, and if the device is still open,
3818  * sync the disk cache to physical media.
3819  */
3820 static void
3821 dashutdown(void * arg, int howto)
3822 {
3823         struct cam_periph *periph;
3824         struct da_softc *softc;
3825         union ccb *ccb;
3826         int error;
3827
3828         CAM_PERIPH_FOREACH(periph, &dadriver) {
3829                 softc = (struct da_softc *)periph->softc;
3830                 if (SCHEDULER_STOPPED()) {
3831                         /* If we paniced with the lock held, do not recurse. */
3832                         if (!cam_periph_owned(periph) &&
3833                             (softc->flags & DA_FLAG_OPEN)) {
3834                                 dadump(softc->disk, NULL, 0, 0, 0);
3835                         }
3836                         continue;
3837                 }
3838                 cam_periph_lock(periph);
3839
3840                 /*
3841                  * We only sync the cache if the drive is still open, and
3842                  * if the drive is capable of it..
3843                  */
3844                 if (((softc->flags & DA_FLAG_OPEN) == 0)
3845                  || (softc->quirks & DA_Q_NO_SYNC_CACHE)) {
3846                         cam_periph_unlock(periph);
3847                         continue;
3848                 }
3849
3850                 ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3851                 scsi_synchronize_cache(&ccb->csio,
3852                                        /*retries*/0,
3853                                        /*cbfcnp*/dadone,
3854                                        MSG_SIMPLE_Q_TAG,
3855                                        /*begin_lba*/0, /* whole disk */
3856                                        /*lb_count*/0,
3857                                        SSD_FULL_SIZE,
3858                                        60 * 60 * 1000);
3859
3860                 error = cam_periph_runccb(ccb, daerror, /*cam_flags*/0,
3861                     /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY | SF_QUIET_IR,
3862                     softc->disk->d_devstat);
3863                 if (error != 0)
3864                         xpt_print(periph->path, "Synchronize cache failed\n");
3865                 xpt_release_ccb(ccb);
3866                 cam_periph_unlock(periph);
3867         }
3868 }
3869
3870 #else /* !_KERNEL */
3871
3872 /*
3873  * XXX This is only left out of the kernel build to silence warnings.  If,
3874  * for some reason this function is used in the kernel, the ifdefs should
3875  * be moved so it is included both in the kernel and userland.
3876  */
3877 void
3878 scsi_format_unit(struct ccb_scsiio *csio, u_int32_t retries,
3879                  void (*cbfcnp)(struct cam_periph *, union ccb *),
3880                  u_int8_t tag_action, u_int8_t byte2, u_int16_t ileave,
3881                  u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
3882                  u_int32_t timeout)
3883 {
3884         struct scsi_format_unit *scsi_cmd;
3885
3886         scsi_cmd = (struct scsi_format_unit *)&csio->cdb_io.cdb_bytes;
3887         scsi_cmd->opcode = FORMAT_UNIT;
3888         scsi_cmd->byte2 = byte2;
3889         scsi_ulto2b(ileave, scsi_cmd->interleave);
3890
3891         cam_fill_csio(csio,
3892                       retries,
3893                       cbfcnp,
3894                       /*flags*/ (dxfer_len > 0) ? CAM_DIR_OUT : CAM_DIR_NONE,
3895                       tag_action,
3896                       data_ptr,
3897                       dxfer_len,
3898                       sense_len,
3899                       sizeof(*scsi_cmd),
3900                       timeout);
3901 }
3902
3903 void
3904 scsi_sanitize(struct ccb_scsiio *csio, u_int32_t retries,
3905               void (*cbfcnp)(struct cam_periph *, union ccb *),
3906               u_int8_t tag_action, u_int8_t byte2, u_int16_t control,
3907               u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
3908               u_int32_t timeout)
3909 {
3910         struct scsi_sanitize *scsi_cmd;
3911
3912         scsi_cmd = (struct scsi_sanitize *)&csio->cdb_io.cdb_bytes;
3913         scsi_cmd->opcode = SANITIZE;
3914         scsi_cmd->byte2 = byte2;
3915         scsi_cmd->control = control;
3916         scsi_ulto2b(dxfer_len, scsi_cmd->length);
3917
3918         cam_fill_csio(csio,
3919                       retries,
3920                       cbfcnp,
3921                       /*flags*/ (dxfer_len > 0) ? CAM_DIR_OUT : CAM_DIR_NONE,
3922                       tag_action,
3923                       data_ptr,
3924                       dxfer_len,
3925                       sense_len,
3926                       sizeof(*scsi_cmd),
3927                       timeout);
3928 }
3929
3930 #endif /* _KERNEL */