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