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