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