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