]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/cam/scsi/scsi_da.c
MFC r241485:
[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 <geom/geom.h>
48 #include <geom/geom_disk.h>
49 #endif /* _KERNEL */
50
51 #ifndef _KERNEL
52 #include <stdio.h>
53 #include <string.h>
54 #endif /* _KERNEL */
55
56 #include <cam/cam.h>
57 #include <cam/cam_ccb.h>
58 #include <cam/cam_periph.h>
59 #include <cam/cam_xpt_periph.h>
60 #include <cam/cam_sim.h>
61
62 #include <cam/scsi/scsi_message.h>
63
64 #ifndef _KERNEL 
65 #include <cam/scsi/scsi_da.h>
66 #endif /* !_KERNEL */
67
68 #ifdef _KERNEL
69 typedef enum {
70         DA_STATE_PROBE,
71         DA_STATE_PROBE2,
72         DA_STATE_NORMAL
73 } da_state;
74
75 typedef enum {
76         DA_FLAG_PACK_INVALID    = 0x001,
77         DA_FLAG_NEW_PACK        = 0x002,
78         DA_FLAG_PACK_LOCKED     = 0x004,
79         DA_FLAG_PACK_REMOVABLE  = 0x008,
80         DA_FLAG_NEED_OTAG       = 0x020,
81         DA_FLAG_WENT_IDLE       = 0x040,
82         DA_FLAG_RETRY_UA        = 0x080,
83         DA_FLAG_OPEN            = 0x100,
84         DA_FLAG_SCTX_INIT       = 0x200,
85         DA_FLAG_CAN_RC16        = 0x400
86 } da_flags;
87
88 typedef enum {
89         DA_Q_NONE               = 0x00,
90         DA_Q_NO_SYNC_CACHE      = 0x01,
91         DA_Q_NO_6_BYTE          = 0x02,
92         DA_Q_NO_PREVENT         = 0x04,
93         DA_Q_4K                 = 0x08
94 } da_quirks;
95
96 typedef enum {
97         DA_CCB_PROBE            = 0x01,
98         DA_CCB_PROBE2           = 0x02,
99         DA_CCB_BUFFER_IO        = 0x03,
100         DA_CCB_WAITING          = 0x04,
101         DA_CCB_DUMP             = 0x05,
102         DA_CCB_DELETE           = 0x06,
103         DA_CCB_TYPE_MASK        = 0x0F,
104         DA_CCB_RETRY_UA         = 0x10
105 } da_ccb_state;
106
107 typedef enum {
108         DA_DELETE_NONE,
109         DA_DELETE_DISABLE,
110         DA_DELETE_ZERO,
111         DA_DELETE_WS10,
112         DA_DELETE_WS16,
113         DA_DELETE_UNMAP,
114         DA_DELETE_MAX = DA_DELETE_UNMAP
115 } da_delete_methods;
116
117 static const char *da_delete_method_names[] =
118     { "NONE", "DISABLE", "ZERO", "WS10", "WS16", "UNMAP" };
119
120 /* Offsets into our private area for storing information */
121 #define ccb_state       ppriv_field0
122 #define ccb_bp          ppriv_ptr1
123
124 struct disk_params {
125         u_int8_t  heads;
126         u_int32_t cylinders;
127         u_int8_t  secs_per_track;
128         u_int32_t secsize;      /* Number of bytes/sector */
129         u_int64_t sectors;      /* total number sectors */
130         u_int     stripesize;
131         u_int     stripeoffset;
132 };
133
134 #define UNMAP_MAX_RANGES        512
135
136 struct da_softc {
137         struct   bio_queue_head bio_queue;
138         struct   bio_queue_head delete_queue;
139         struct   bio_queue_head delete_run_queue;
140         SLIST_ENTRY(da_softc) links;
141         LIST_HEAD(, ccb_hdr) pending_ccbs;
142         da_state state;
143         da_flags flags; 
144         da_quirks quirks;
145         int      minimum_cmd_size;
146         int      error_inject;
147         int      ordered_tag_count;
148         int      outstanding_cmds;
149         int      unmap_max_ranges;
150         int      unmap_max_lba;
151         int      delete_running;
152         da_delete_methods        delete_method;
153         struct   disk_params params;
154         struct   disk *disk;
155         union    ccb saved_ccb;
156         struct task             sysctl_task;
157         struct sysctl_ctx_list  sysctl_ctx;
158         struct sysctl_oid       *sysctl_tree;
159         struct callout          sendordered_c;
160         uint64_t wwpn;
161         uint8_t  unmap_buf[UNMAP_MAX_RANGES * 16 + 8];
162 };
163
164 struct da_quirk_entry {
165         struct scsi_inquiry_pattern inq_pat;
166         da_quirks quirks;
167 };
168
169 static const char quantum[] = "QUANTUM";
170 static const char microp[] = "MICROP";
171
172 static struct da_quirk_entry da_quirk_table[] =
173 {
174         /* SPI, FC devices */
175         {
176                 /*
177                  * Fujitsu M2513A MO drives.
178                  * Tested devices: M2513A2 firmware versions 1200 & 1300.
179                  * (dip switch selects whether T_DIRECT or T_OPTICAL device)
180                  * Reported by: W.Scholten <whs@xs4all.nl>
181                  */
182                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "FUJITSU", "M2513A", "*"},
183                 /*quirks*/ DA_Q_NO_SYNC_CACHE
184         },
185         {
186                 /* See above. */
187                 {T_OPTICAL, SIP_MEDIA_REMOVABLE, "FUJITSU", "M2513A", "*"},
188                 /*quirks*/ DA_Q_NO_SYNC_CACHE
189         },
190         {
191                 /*
192                  * This particular Fujitsu drive doesn't like the
193                  * synchronize cache command.
194                  * Reported by: Tom Jackson <toj@gorilla.net>
195                  */
196                 {T_DIRECT, SIP_MEDIA_FIXED, "FUJITSU", "M2954*", "*"},
197                 /*quirks*/ DA_Q_NO_SYNC_CACHE
198         },
199         {
200                 /*
201                  * This drive doesn't like the synchronize cache command
202                  * either.  Reported by: Matthew Jacob <mjacob@feral.com>
203                  * in NetBSD PR kern/6027, August 24, 1998.
204                  */
205                 {T_DIRECT, SIP_MEDIA_FIXED, microp, "2217*", "*"},
206                 /*quirks*/ DA_Q_NO_SYNC_CACHE
207         },
208         {
209                 /*
210                  * This drive doesn't like the synchronize cache command
211                  * either.  Reported by: Hellmuth Michaelis (hm@kts.org)
212                  * (PR 8882).
213                  */
214                 {T_DIRECT, SIP_MEDIA_FIXED, microp, "2112*", "*"},
215                 /*quirks*/ DA_Q_NO_SYNC_CACHE
216         },
217         {
218                 /*
219                  * Doesn't like the synchronize cache command.
220                  * Reported by: Blaz Zupan <blaz@gold.amis.net>
221                  */
222                 {T_DIRECT, SIP_MEDIA_FIXED, "NEC", "D3847*", "*"},
223                 /*quirks*/ DA_Q_NO_SYNC_CACHE
224         },
225         {
226                 /*
227                  * Doesn't like the synchronize cache command.
228                  * Reported by: Blaz Zupan <blaz@gold.amis.net>
229                  */
230                 {T_DIRECT, SIP_MEDIA_FIXED, quantum, "MAVERICK 540S", "*"},
231                 /*quirks*/ DA_Q_NO_SYNC_CACHE
232         },
233         {
234                 /*
235                  * Doesn't like the synchronize cache command.
236                  */
237                 {T_DIRECT, SIP_MEDIA_FIXED, quantum, "LPS525S", "*"},
238                 /*quirks*/ DA_Q_NO_SYNC_CACHE
239         },
240         {
241                 /*
242                  * Doesn't like the synchronize cache command.
243                  * Reported by: walter@pelissero.de
244                  */
245                 {T_DIRECT, SIP_MEDIA_FIXED, quantum, "LPS540S", "*"},
246                 /*quirks*/ DA_Q_NO_SYNC_CACHE
247         },
248         {
249                 /*
250                  * Doesn't work correctly with 6 byte reads/writes.
251                  * Returns illegal request, and points to byte 9 of the
252                  * 6-byte CDB.
253                  * Reported by:  Adam McDougall <bsdx@spawnet.com>
254                  */
255                 {T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 4*", "*"},
256                 /*quirks*/ DA_Q_NO_6_BYTE
257         },
258         {
259                 /* See above. */
260                 {T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 2*", "*"},
261                 /*quirks*/ DA_Q_NO_6_BYTE
262         },
263         {
264                 /*
265                  * Doesn't like the synchronize cache command.
266                  * Reported by: walter@pelissero.de
267                  */
268                 {T_DIRECT, SIP_MEDIA_FIXED, "CONNER", "CP3500*", "*"},
269                 /*quirks*/ DA_Q_NO_SYNC_CACHE
270         },
271         {
272                 /*
273                  * The CISS RAID controllers do not support SYNC_CACHE
274                  */
275                 {T_DIRECT, SIP_MEDIA_FIXED, "COMPAQ", "RAID*", "*"},
276                 /*quirks*/ DA_Q_NO_SYNC_CACHE
277         },
278         /* USB mass storage devices supported by umass(4) */
279         {
280                 /*
281                  * EXATELECOM (Sigmatel) i-Bead 100/105 USB Flash MP3 Player
282                  * PR: kern/51675
283                  */
284                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "EXATEL", "i-BEAD10*", "*"},
285                 /*quirks*/ DA_Q_NO_SYNC_CACHE
286         },
287         {
288                 /*
289                  * Power Quotient Int. (PQI) USB flash key
290                  * PR: kern/53067
291                  */
292                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "USB Flash Disk*",
293                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
294         },
295         {
296                 /*
297                  * Creative Nomad MUVO mp3 player (USB)
298                  * PR: kern/53094
299                  */
300                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "CREATIVE", "NOMAD_MUVO", "*"},
301                 /*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
302         },
303         {
304                 /*
305                  * Jungsoft NEXDISK USB flash key
306                  * PR: kern/54737
307                  */
308                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "JUNGSOFT", "NEXDISK*", "*"},
309                 /*quirks*/ DA_Q_NO_SYNC_CACHE
310         },
311         {
312                 /*
313                  * FreeDik USB Mini Data Drive
314                  * PR: kern/54786
315                  */
316                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "FreeDik*", "Mini Data Drive",
317                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
318         },
319         {
320                 /*
321                  * Sigmatel USB Flash MP3 Player
322                  * PR: kern/57046
323                  */
324                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "SigmaTel", "MSCN", "*"},
325                 /*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
326         },
327         {
328                 /*
329                  * Neuros USB Digital Audio Computer
330                  * PR: kern/63645
331                  */
332                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "NEUROS", "dig. audio comp.",
333                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
334         },
335         {
336                 /*
337                  * SEAGRAND NP-900 MP3 Player
338                  * PR: kern/64563
339                  */
340                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "SEAGRAND", "NP-900*", "*"},
341                 /*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
342         },
343         {
344                 /*
345                  * iRiver iFP MP3 player (with UMS Firmware)
346                  * PR: kern/54881, i386/63941, kern/66124
347                  */
348                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "iRiver", "iFP*", "*"},
349                 /*quirks*/ DA_Q_NO_SYNC_CACHE
350         },
351         {
352                 /*
353                  * Frontier Labs NEX IA+ Digital Audio Player, rev 1.10/0.01
354                  * PR: kern/70158
355                  */
356                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "FL" , "Nex*", "*"},
357                 /*quirks*/ DA_Q_NO_SYNC_CACHE
358         },
359         {
360                 /*
361                  * ZICPlay USB MP3 Player with FM
362                  * PR: kern/75057
363                  */
364                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "ACTIONS*" , "USB DISK*", "*"},
365                 /*quirks*/ DA_Q_NO_SYNC_CACHE
366         },
367         {
368                 /*
369                  * TEAC USB floppy mechanisms
370                  */
371                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "TEAC" , "FD-05*", "*"},
372                 /*quirks*/ DA_Q_NO_SYNC_CACHE
373         },
374         {
375                 /*
376                  * Kingston DataTraveler II+ USB Pen-Drive.
377                  * Reported by: Pawel Jakub Dawidek <pjd@FreeBSD.org>
378                  */
379                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston" , "DataTraveler II+",
380                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
381         },
382         {
383                 /*
384                  * USB DISK Pro PMAP
385                  * Reported by: jhs
386                  * PR: usb/96381
387                  */
388                 {T_DIRECT, SIP_MEDIA_REMOVABLE, " ", "USB DISK Pro", "PMAP"},
389                 /*quirks*/ DA_Q_NO_SYNC_CACHE
390         },
391         {
392                 /*
393                  * Motorola E398 Mobile Phone (TransFlash memory card).
394                  * Reported by: Wojciech A. Koszek <dunstan@FreeBSD.czest.pl>
395                  * PR: usb/89889
396                  */
397                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Motorola" , "Motorola Phone",
398                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
399         },
400         {
401                 /*
402                  * Qware BeatZkey! Pro
403                  * PR: usb/79164
404                  */
405                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "GENERIC", "USB DISK DEVICE",
406                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
407         },
408         {
409                 /*
410                  * Time DPA20B 1GB MP3 Player
411                  * PR: usb/81846
412                  */
413                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "USB2.0*", "(FS) FLASH DISK*",
414                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
415         },
416         {
417                 /*
418                  * Samsung USB key 128Mb
419                  * PR: usb/90081
420                  */
421                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "USB-DISK", "FreeDik-FlashUsb",
422                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
423         },
424         {
425                 /*
426                  * Kingston DataTraveler 2.0 USB Flash memory.
427                  * PR: usb/89196
428                  */
429                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Kingston", "DataTraveler 2.0",
430                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
431         },
432         {
433                 /*
434                  * Creative MUVO Slim mp3 player (USB)
435                  * PR: usb/86131
436                  */
437                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "CREATIVE", "MuVo Slim",
438                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE|DA_Q_NO_PREVENT
439                 },
440         {
441                 /*
442                  * United MP5512 Portable MP3 Player (2-in-1 USB DISK/MP3)
443                  * PR: usb/80487
444                  */
445                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "MUSIC DISK",
446                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
447         },
448         {
449                 /*
450                  * SanDisk Micro Cruzer 128MB
451                  * PR: usb/75970
452                  */
453                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "SanDisk" , "Micro Cruzer",
454                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
455         },
456         {
457                 /*
458                  * TOSHIBA TransMemory USB sticks
459                  * PR: kern/94660
460                  */
461                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "TOSHIBA", "TransMemory",
462                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
463         },
464         {
465                 /*
466                  * PNY USB Flash keys
467                  * PR: usb/75578, usb/72344, usb/65436 
468                  */
469                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "*" , "USB DISK*",
470                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
471         },
472         {
473                 /*
474                  * Genesys 6-in-1 Card Reader
475                  * PR: usb/94647
476                  */
477                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic*", "STORAGE DEVICE*",
478                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
479         },
480         {
481                 /*
482                  * Rekam Digital CAMERA
483                  * PR: usb/98713
484                  */
485                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "CAMERA*", "4MP-9J6*",
486                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
487         },
488         {
489                 /*
490                  * iRiver H10 MP3 player
491                  * PR: usb/102547
492                  */
493                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "iriver", "H10*",
494                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
495         },
496         {
497                 /*
498                  * iRiver U10 MP3 player
499                  * PR: usb/92306
500                  */
501                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "iriver", "U10*",
502                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
503         },
504         {
505                 /*
506                  * X-Micro Flash Disk
507                  * PR: usb/96901
508                  */
509                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "X-Micro", "Flash Disk",
510                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
511         },
512         {
513                 /*
514                  * EasyMP3 EM732X USB 2.0 Flash MP3 Player
515                  * PR: usb/96546
516                  */
517                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "EM732X", "MP3 Player*",
518                 "1.00"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
519         },
520         {
521                 /*
522                  * Denver MP3 player
523                  * PR: usb/107101
524                  */
525                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "DENVER", "MP3 PLAYER",
526                  "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
527         },
528         {
529                 /*
530                  * Philips USB Key Audio KEY013
531                  * PR: usb/68412
532                  */
533                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "PHILIPS", "Key*", "*"},
534                 /*quirks*/ DA_Q_NO_SYNC_CACHE | DA_Q_NO_PREVENT
535         },
536         {
537                 /*
538                  * JNC MP3 Player
539                  * PR: usb/94439
540                  */
541                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "JNC*" , "MP3 Player*",
542                  "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
543         },
544         {
545                 /*
546                  * SAMSUNG MP0402H
547                  * PR: usb/108427
548                  */
549                 {T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "MP0402H", "*"},
550                 /*quirks*/ DA_Q_NO_SYNC_CACHE
551         },
552         {
553                 /*
554                  * I/O Magic USB flash - Giga Bank
555                  * PR: usb/108810
556                  */
557                 {T_DIRECT, SIP_MEDIA_FIXED, "GS-Magic", "stor*", "*"},
558                 /*quirks*/ DA_Q_NO_SYNC_CACHE
559         },
560         {
561                 /*
562                  * JoyFly 128mb USB Flash Drive
563                  * PR: 96133
564                  */
565                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "USB 2.0", "Flash Disk*",
566                  "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
567         },
568         {
569                 /*
570                  * ChipsBnk usb stick
571                  * PR: 103702
572                  */
573                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "ChipsBnk", "USB*",
574                  "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
575         },
576         {
577                 /*
578                  * Storcase (Kingston) InfoStation IFS FC2/SATA-R 201A
579                  * PR: 129858
580                  */
581                 {T_DIRECT, SIP_MEDIA_FIXED, "IFS", "FC2/SATA-R*",
582                  "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
583         },
584         {
585                 /*
586                  * Samsung YP-U3 mp3-player
587                  * PR: 125398
588                  */
589                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Samsung", "YP-U3",
590                  "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
591         },
592         {
593                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Netac", "OnlyDisk*",
594                  "2000"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
595         },
596         {
597                 /*
598                  * Sony Cyber-Shot DSC cameras
599                  * PR: usb/137035
600                  */
601                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Sony", "Sony DSC", "*"},
602                 /*quirks*/ DA_Q_NO_SYNC_CACHE | DA_Q_NO_PREVENT
603         },
604         /* ATA/SATA devices over SAS/USB/... */
605         {
606                 /* Hitachi Advanced Format (4k) drives */
607                 { T_DIRECT, SIP_MEDIA_FIXED, "Hitachi", "H??????????E3*", "*" },
608                 /*quirks*/DA_Q_4K
609         },
610         {
611                 /* Samsung Advanced Format (4k) drives */
612                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SAMSUNG HD155UI*", "*" },
613                 /*quirks*/DA_Q_4K
614         },
615         {
616                 /* Samsung Advanced Format (4k) drives */
617                 { T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "HD155UI*", "*" },
618                 /*quirks*/DA_Q_4K
619         },
620         {
621                 /* Samsung Advanced Format (4k) drives */
622                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "SAMSUNG HD204UI*", "*" },
623                 /*quirks*/DA_Q_4K
624         },
625         {
626                 /* Samsung Advanced Format (4k) drives */
627                 { T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "HD204UI*", "*" },
628                 /*quirks*/DA_Q_4K
629         },
630         {
631                 /* Seagate Barracuda Green Advanced Format (4k) drives */
632                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST????DL*", "*" },
633                 /*quirks*/DA_Q_4K
634         },
635         {
636                 /* Seagate Barracuda Green Advanced Format (4k) drives */
637                 { T_DIRECT, SIP_MEDIA_FIXED, "ST????DL", "*", "*" },
638                 /*quirks*/DA_Q_4K
639         },
640         {
641                 /* Seagate Barracuda Green Advanced Format (4k) drives */
642                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST???DM*", "*" },
643                 /*quirks*/DA_Q_4K
644         },
645         {
646                 /* Seagate Barracuda Green Advanced Format (4k) drives */
647                 { T_DIRECT, SIP_MEDIA_FIXED, "ST???DM*", "*", "*" },
648                 /*quirks*/DA_Q_4K
649         },
650         {
651                 /* Seagate Barracuda Green Advanced Format (4k) drives */
652                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST????DM*", "*" },
653                 /*quirks*/DA_Q_4K
654         },
655         {
656                 /* Seagate Barracuda Green Advanced Format (4k) drives */
657                 { T_DIRECT, SIP_MEDIA_FIXED, "ST????DM", "*", "*" },
658                 /*quirks*/DA_Q_4K
659         },
660         {
661                 /* Seagate Momentus Advanced Format (4k) drives */
662                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9500423AS*", "*" },
663                 /*quirks*/DA_Q_4K
664         },
665         {
666                 /* Seagate Momentus Advanced Format (4k) drives */
667                 { T_DIRECT, SIP_MEDIA_FIXED, "ST950042", "3AS*", "*" },
668                 /*quirks*/DA_Q_4K
669         },
670         {
671                 /* Seagate Momentus Advanced Format (4k) drives */
672                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9500424AS*", "*" },
673                 /*quirks*/DA_Q_4K
674         },
675         {
676                 /* Seagate Momentus Advanced Format (4k) drives */
677                 { T_DIRECT, SIP_MEDIA_FIXED, "ST950042", "4AS*", "*" },
678                 /*quirks*/DA_Q_4K
679         },
680         {
681                 /* Seagate Momentus Advanced Format (4k) drives */
682                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9640423AS*", "*" },
683                 /*quirks*/DA_Q_4K
684         },
685         {
686                 /* Seagate Momentus Advanced Format (4k) drives */
687                 { T_DIRECT, SIP_MEDIA_FIXED, "ST964042", "3AS*", "*" },
688                 /*quirks*/DA_Q_4K
689         },
690         {
691                 /* Seagate Momentus Advanced Format (4k) drives */
692                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9640424AS*", "*" },
693                 /*quirks*/DA_Q_4K
694         },
695         {
696                 /* Seagate Momentus Advanced Format (4k) drives */
697                 { T_DIRECT, SIP_MEDIA_FIXED, "ST964042", "4AS*", "*" },
698                 /*quirks*/DA_Q_4K
699         },
700         {
701                 /* Seagate Momentus Advanced Format (4k) drives */
702                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750420AS*", "*" },
703                 /*quirks*/DA_Q_4K
704         },
705         {
706                 /* Seagate Momentus Advanced Format (4k) drives */
707                 { T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "0AS*", "*" },
708                 /*quirks*/DA_Q_4K
709         },
710         {
711                 /* Seagate Momentus Advanced Format (4k) drives */
712                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750422AS*", "*" },
713                 /*quirks*/DA_Q_4K
714         },
715         {
716                 /* Seagate Momentus Advanced Format (4k) drives */
717                 { T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "2AS*", "*" },
718                 /*quirks*/DA_Q_4K
719         },
720         {
721                 /* Seagate Momentus Advanced Format (4k) drives */
722                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST9750423AS*", "*" },
723                 /*quirks*/DA_Q_4K
724         },
725         {
726                 /* Seagate Momentus Advanced Format (4k) drives */
727                 { T_DIRECT, SIP_MEDIA_FIXED, "ST975042", "3AS*", "*" },
728                 /*quirks*/DA_Q_4K
729         },
730         {
731                 /* Seagate Momentus Thin Advanced Format (4k) drives */
732                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "ST???LT*", "*" },
733                 /*quirks*/DA_Q_4K
734         },
735         {
736                 /* Seagate Momentus Thin Advanced Format (4k) drives */
737                 { T_DIRECT, SIP_MEDIA_FIXED, "ST???LT*", "*", "*" },
738                 /*quirks*/DA_Q_4K
739         },
740         {
741                 /* WDC Caviar Green Advanced Format (4k) drives */
742                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD????RS*", "*" },
743                 /*quirks*/DA_Q_4K
744         },
745         {
746                 /* WDC Caviar Green Advanced Format (4k) drives */
747                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "??RS*", "*" },
748                 /*quirks*/DA_Q_4K
749         },
750         {
751                 /* WDC Caviar Green Advanced Format (4k) drives */
752                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD????RX*", "*" },
753                 /*quirks*/DA_Q_4K
754         },
755         {
756                 /* WDC Caviar Green Advanced Format (4k) drives */
757                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "??RX*", "*" },
758                 /*quirks*/DA_Q_4K
759         },
760         {
761                 /* WDC Caviar Green Advanced Format (4k) drives */
762                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD??????RS*", "*" },
763                 /*quirks*/DA_Q_4K
764         },
765         {
766                 /* WDC Caviar Green Advanced Format (4k) drives */
767                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "????RS*", "*" },
768                 /*quirks*/DA_Q_4K
769         },
770         {
771                 /* WDC Caviar Green Advanced Format (4k) drives */
772                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD??????RX*", "*" },
773                 /*quirks*/DA_Q_4K
774         },
775         {
776                 /* WDC Caviar Green Advanced Format (4k) drives */
777                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "????RX*", "*" },
778                 /*quirks*/DA_Q_4K
779         },
780         {
781                 /* WDC Scorpio Black Advanced Format (4k) drives */
782                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD???PKT*", "*" },
783                 /*quirks*/DA_Q_4K
784         },
785         {
786                 /* WDC Scorpio Black Advanced Format (4k) drives */
787                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "?PKT*", "*" },
788                 /*quirks*/DA_Q_4K
789         },
790         {
791                 /* WDC Scorpio Black Advanced Format (4k) drives */
792                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD?????PKT*", "*" },
793                 /*quirks*/DA_Q_4K
794         },
795         {
796                 /* WDC Scorpio Black Advanced Format (4k) drives */
797                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "???PKT*", "*" },
798                 /*quirks*/DA_Q_4K
799         },
800         {
801                 /* WDC Scorpio Blue Advanced Format (4k) drives */
802                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD???PVT*", "*" },
803                 /*quirks*/DA_Q_4K
804         },
805         {
806                 /* WDC Scorpio Blue Advanced Format (4k) drives */
807                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "?PVT*", "*" },
808                 /*quirks*/DA_Q_4K
809         },
810         {
811                 /* WDC Scorpio Blue Advanced Format (4k) drives */
812                 { T_DIRECT, SIP_MEDIA_FIXED, "ATA", "WDC WD?????PVT*", "*" },
813                 /*quirks*/DA_Q_4K
814         },
815         {
816                 /* WDC Scorpio Blue Advanced Format (4k) drives */
817                 { T_DIRECT, SIP_MEDIA_FIXED, "WDC WD??", "???PVT*", "*" },
818                 /*quirks*/DA_Q_4K
819         },
820         {
821                 /*
822                  * Olympus FE-210 camera
823                  */
824                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "OLYMPUS", "FE210*",
825                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
826         },
827         {
828                 /*
829                  * LG UP3S MP3 player
830                  */
831                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "LG", "UP3S",
832                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
833         },
834         {
835                 /*
836                  * Laser MP3-2GA13 MP3 player
837                  */
838                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "USB 2.0", "(HS) Flash Disk",
839                 "*"}, /*quirks*/ DA_Q_NO_SYNC_CACHE
840         },
841         {
842                 /*
843                  * LaCie external 250GB Hard drive des by Porsche
844                  * Submitted by: Ben Stuyts <ben@altesco.nl>
845                  * PR: 121474
846                  */
847                 {T_DIRECT, SIP_MEDIA_FIXED, "SAMSUNG", "HM250JI", "*"},
848                 /*quirks*/ DA_Q_NO_SYNC_CACHE
849         },
850 };
851
852 static  disk_strategy_t dastrategy;
853 static  dumper_t        dadump;
854 static  periph_init_t   dainit;
855 static  void            daasync(void *callback_arg, u_int32_t code,
856                                 struct cam_path *path, void *arg);
857 static  void            dasysctlinit(void *context, int pending);
858 static  int             dacmdsizesysctl(SYSCTL_HANDLER_ARGS);
859 static  int             dadeletemethodsysctl(SYSCTL_HANDLER_ARGS);
860 static  periph_ctor_t   daregister;
861 static  periph_dtor_t   dacleanup;
862 static  periph_start_t  dastart;
863 static  periph_oninv_t  daoninvalidate;
864 static  void            dadone(struct cam_periph *periph,
865                                union ccb *done_ccb);
866 static  int             daerror(union ccb *ccb, u_int32_t cam_flags,
867                                 u_int32_t sense_flags);
868 static void             daprevent(struct cam_periph *periph, int action);
869 static int              dagetcapacity(struct cam_periph *periph);
870 static void             dasetgeom(struct cam_periph *periph, uint32_t block_len,
871                                   uint64_t maxsector, u_int lbppbe, u_int lalba);
872 static timeout_t        dasendorderedtag;
873 static void             dashutdown(void *arg, int howto);
874
875 #ifndef DA_DEFAULT_TIMEOUT
876 #define DA_DEFAULT_TIMEOUT 60   /* Timeout in seconds */
877 #endif
878
879 #ifndef DA_DEFAULT_RETRY
880 #define DA_DEFAULT_RETRY        4
881 #endif
882
883 #ifndef DA_DEFAULT_SEND_ORDERED
884 #define DA_DEFAULT_SEND_ORDERED 1
885 #endif
886
887
888 static int da_retry_count = DA_DEFAULT_RETRY;
889 static int da_default_timeout = DA_DEFAULT_TIMEOUT;
890 static int da_send_ordered = DA_DEFAULT_SEND_ORDERED;
891
892 SYSCTL_NODE(_kern_cam, OID_AUTO, da, CTLFLAG_RD, 0,
893             "CAM Direct Access Disk driver");
894 SYSCTL_INT(_kern_cam_da, OID_AUTO, retry_count, CTLFLAG_RW,
895            &da_retry_count, 0, "Normal I/O retry count");
896 TUNABLE_INT("kern.cam.da.retry_count", &da_retry_count);
897 SYSCTL_INT(_kern_cam_da, OID_AUTO, default_timeout, CTLFLAG_RW,
898            &da_default_timeout, 0, "Normal I/O timeout (in seconds)");
899 TUNABLE_INT("kern.cam.da.default_timeout", &da_default_timeout);
900 SYSCTL_INT(_kern_cam_da, OID_AUTO, da_send_ordered, CTLFLAG_RW,
901            &da_send_ordered, 0, "Send Ordered Tags");
902 TUNABLE_INT("kern.cam.da.da_send_ordered", &da_send_ordered);
903
904 /*
905  * DA_ORDEREDTAG_INTERVAL determines how often, relative
906  * to the default timeout, we check to see whether an ordered
907  * tagged transaction is appropriate to prevent simple tag
908  * starvation.  Since we'd like to ensure that there is at least
909  * 1/2 of the timeout length left for a starved transaction to
910  * complete after we've sent an ordered tag, we must poll at least
911  * four times in every timeout period.  This takes care of the worst
912  * case where a starved transaction starts during an interval that
913  * meets the requirement "don't send an ordered tag" test so it takes
914  * us two intervals to determine that a tag must be sent.
915  */
916 #ifndef DA_ORDEREDTAG_INTERVAL
917 #define DA_ORDEREDTAG_INTERVAL 4
918 #endif
919
920 static struct periph_driver dadriver =
921 {
922         dainit, "da",
923         TAILQ_HEAD_INITIALIZER(dadriver.units), /* generation */ 0
924 };
925
926 PERIPHDRIVER_DECLARE(da, dadriver);
927
928 MALLOC_DEFINE(M_SCSIDA, "scsi_da", "scsi_da buffers");
929
930 static int
931 daopen(struct disk *dp)
932 {
933         struct cam_periph *periph;
934         struct da_softc *softc;
935         int unit;
936         int error;
937
938         periph = (struct cam_periph *)dp->d_drv1;
939         if (periph == NULL) {
940                 return (ENXIO); 
941         }
942
943         if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
944                 return (ENXIO);
945         }
946
947         cam_periph_lock(periph);
948         if ((error = cam_periph_hold(periph, PRIBIO|PCATCH)) != 0) {
949                 cam_periph_unlock(periph);
950                 cam_periph_release(periph);
951                 return (error);
952         }
953
954         unit = periph->unit_number;
955         softc = (struct da_softc *)periph->softc;
956         softc->flags |= DA_FLAG_OPEN;
957
958         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
959             ("daopen\n"));
960
961         if ((softc->flags & DA_FLAG_PACK_INVALID) != 0) {
962                 /* Invalidate our pack information. */
963                 softc->flags &= ~DA_FLAG_PACK_INVALID;
964         }
965
966         error = dagetcapacity(periph);
967
968         if (error == 0) {
969
970                 softc->disk->d_sectorsize = softc->params.secsize;
971                 softc->disk->d_mediasize = softc->params.secsize * (off_t)softc->params.sectors;
972                 softc->disk->d_stripesize = softc->params.stripesize;
973                 softc->disk->d_stripeoffset = softc->params.stripeoffset;
974                 /* XXX: these are not actually "firmware" values, so they may be wrong */
975                 softc->disk->d_fwsectors = softc->params.secs_per_track;
976                 softc->disk->d_fwheads = softc->params.heads;
977                 softc->disk->d_devstat->block_size = softc->params.secsize;
978                 softc->disk->d_devstat->flags &= ~DEVSTAT_BS_UNAVAILABLE;
979                 if (softc->delete_method > DA_DELETE_DISABLE)
980                         softc->disk->d_flags |= DISKFLAG_CANDELETE;
981                 else
982                         softc->disk->d_flags &= ~DISKFLAG_CANDELETE;
983
984                 if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0 &&
985                     (softc->quirks & DA_Q_NO_PREVENT) == 0)
986                         daprevent(periph, PR_PREVENT);
987         } else
988                 softc->flags &= ~DA_FLAG_OPEN;
989
990         cam_periph_unhold(periph);
991         cam_periph_unlock(periph);
992
993         if (error != 0) {
994                 cam_periph_release(periph);
995         }
996         return (error);
997 }
998
999 static int
1000 daclose(struct disk *dp)
1001 {
1002         struct  cam_periph *periph;
1003         struct  da_softc *softc;
1004
1005         periph = (struct cam_periph *)dp->d_drv1;
1006         if (periph == NULL)
1007                 return (0);     
1008
1009         cam_periph_lock(periph);
1010         if (cam_periph_hold(periph, PRIBIO) != 0) {
1011                 cam_periph_unlock(periph);
1012                 cam_periph_release(periph);
1013                 return (0);
1014         }
1015
1016         softc = (struct da_softc *)periph->softc;
1017
1018         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
1019             ("daclose\n"));
1020
1021         if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0
1022          && (softc->flags & DA_FLAG_PACK_INVALID) == 0) {
1023                 union   ccb *ccb;
1024
1025                 ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1026
1027                 scsi_synchronize_cache(&ccb->csio,
1028                                        /*retries*/1,
1029                                        /*cbfcnp*/dadone,
1030                                        MSG_SIMPLE_Q_TAG,
1031                                        /*begin_lba*/0,/* Cover the whole disk */
1032                                        /*lb_count*/0,
1033                                        SSD_FULL_SIZE,
1034                                        5 * 60 * 1000);
1035
1036                 cam_periph_runccb(ccb, daerror, /*cam_flags*/0,
1037                                   /*sense_flags*/SF_RETRY_UA | SF_QUIET_IR,
1038                                   softc->disk->d_devstat);
1039                 xpt_release_ccb(ccb);
1040
1041         }
1042
1043         if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0) {
1044                 if ((softc->quirks & DA_Q_NO_PREVENT) == 0)
1045                         daprevent(periph, PR_ALLOW);
1046                 /*
1047                  * If we've got removeable media, mark the blocksize as
1048                  * unavailable, since it could change when new media is
1049                  * inserted.
1050                  */
1051                 softc->disk->d_devstat->flags |= DEVSTAT_BS_UNAVAILABLE;
1052         }
1053
1054         softc->flags &= ~DA_FLAG_OPEN;
1055         cam_periph_unhold(periph);
1056         cam_periph_unlock(periph);
1057         cam_periph_release(periph);
1058         return (0);     
1059 }
1060
1061 static void
1062 daschedule(struct cam_periph *periph)
1063 {
1064         struct da_softc *softc = (struct da_softc *)periph->softc;
1065         uint32_t prio;
1066
1067         /* Check if cam_periph_getccb() was called. */
1068         prio = periph->immediate_priority;
1069
1070         /* Check if we have more work to do. */
1071         if (bioq_first(&softc->bio_queue) ||
1072             (!softc->delete_running && bioq_first(&softc->delete_queue))) {
1073                 prio = CAM_PRIORITY_NORMAL;
1074         }
1075
1076         /* Schedule CCB if any of above is true. */
1077         if (prio != CAM_PRIORITY_NONE)
1078                 xpt_schedule(periph, prio);
1079 }
1080
1081 /*
1082  * Actually translate the requested transfer into one the physical driver
1083  * can understand.  The transfer is described by a buf and will include
1084  * only one physical transfer.
1085  */
1086 static void
1087 dastrategy(struct bio *bp)
1088 {
1089         struct cam_periph *periph;
1090         struct da_softc *softc;
1091         
1092         periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1093         if (periph == NULL) {
1094                 biofinish(bp, NULL, ENXIO);
1095                 return;
1096         }
1097         softc = (struct da_softc *)periph->softc;
1098
1099         cam_periph_lock(periph);
1100
1101         /*
1102          * If the device has been made invalid, error out
1103          */
1104         if ((softc->flags & DA_FLAG_PACK_INVALID)) {
1105                 cam_periph_unlock(periph);
1106                 biofinish(bp, NULL, ENXIO);
1107                 return;
1108         }
1109
1110         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dastrategy(%p)\n", bp));
1111
1112         /*
1113          * Place it in the queue of disk activities for this disk
1114          */
1115         if (bp->bio_cmd == BIO_DELETE) {
1116                 if (bp->bio_bcount == 0)
1117                         biodone(bp);
1118                 else
1119                         bioq_disksort(&softc->delete_queue, bp);
1120         } else
1121                 bioq_disksort(&softc->bio_queue, bp);
1122
1123         /*
1124          * Schedule ourselves for performing the work.
1125          */
1126         daschedule(periph);
1127         cam_periph_unlock(periph);
1128
1129         return;
1130 }
1131
1132 static int
1133 dadump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size_t length)
1134 {
1135         struct      cam_periph *periph;
1136         struct      da_softc *softc;
1137         u_int       secsize;
1138         struct      ccb_scsiio csio;
1139         struct      disk *dp;
1140         int         error = 0;
1141
1142         dp = arg;
1143         periph = dp->d_drv1;
1144         if (periph == NULL)
1145                 return (ENXIO);
1146         softc = (struct da_softc *)periph->softc;
1147         cam_periph_lock(periph);
1148         secsize = softc->params.secsize;
1149         
1150         if ((softc->flags & DA_FLAG_PACK_INVALID) != 0) {
1151                 cam_periph_unlock(periph);
1152                 return (ENXIO);
1153         }
1154
1155         if (length > 0) {
1156                 xpt_setup_ccb(&csio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1157                 csio.ccb_h.ccb_state = DA_CCB_DUMP;
1158                 scsi_read_write(&csio,
1159                                 /*retries*/0,
1160                                 dadone,
1161                                 MSG_ORDERED_Q_TAG,
1162                                 /*read*/FALSE,
1163                                 /*byte2*/0,
1164                                 /*minimum_cmd_size*/ softc->minimum_cmd_size,
1165                                 offset / secsize,
1166                                 length / secsize,
1167                                 /*data_ptr*/(u_int8_t *) virtual,
1168                                 /*dxfer_len*/length,
1169                                 /*sense_len*/SSD_FULL_SIZE,
1170                                 da_default_timeout * 1000);
1171                 xpt_polled_action((union ccb *)&csio);
1172
1173                 error = cam_periph_error((union ccb *)&csio,
1174                     0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
1175                 if ((csio.ccb_h.status & CAM_DEV_QFRZN) != 0)
1176                         cam_release_devq(csio.ccb_h.path, /*relsim_flags*/0,
1177                             /*reduction*/0, /*timeout*/0, /*getcount_only*/0);
1178                 if (error != 0)
1179                         printf("Aborting dump due to I/O error.\n");
1180                 cam_periph_unlock(periph);
1181                 return (error);
1182         }
1183                 
1184         /*
1185          * Sync the disk cache contents to the physical media.
1186          */
1187         if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
1188
1189                 xpt_setup_ccb(&csio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1190                 csio.ccb_h.ccb_state = DA_CCB_DUMP;
1191                 scsi_synchronize_cache(&csio,
1192                                        /*retries*/0,
1193                                        /*cbfcnp*/dadone,
1194                                        MSG_SIMPLE_Q_TAG,
1195                                        /*begin_lba*/0,/* Cover the whole disk */
1196                                        /*lb_count*/0,
1197                                        SSD_FULL_SIZE,
1198                                        5 * 60 * 1000);
1199                 xpt_polled_action((union ccb *)&csio);
1200
1201                 error = cam_periph_error((union ccb *)&csio,
1202                     0, SF_NO_RECOVERY | SF_NO_RETRY | SF_QUIET_IR, NULL);
1203                 if ((csio.ccb_h.status & CAM_DEV_QFRZN) != 0)
1204                         cam_release_devq(csio.ccb_h.path, /*relsim_flags*/0,
1205                             /*reduction*/0, /*timeout*/0, /*getcount_only*/0);
1206                 if (error != 0)
1207                         xpt_print(periph->path, "Synchronize cache failed\n");
1208         }
1209         cam_periph_unlock(periph);
1210         return (error);
1211 }
1212
1213 static int
1214 dagetattr(struct bio *bp)
1215 {
1216         int ret;
1217         struct cam_periph *periph;
1218
1219         periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1220         if (periph == NULL)
1221                 return (ENXIO);
1222
1223         cam_periph_lock(periph);
1224         ret = xpt_getattr(bp->bio_data, bp->bio_length, bp->bio_attribute,
1225             periph->path);
1226         cam_periph_unlock(periph);
1227         if (ret == 0)
1228                 bp->bio_completed = bp->bio_length;
1229         return ret;
1230 }
1231
1232 static void
1233 dainit(void)
1234 {
1235         cam_status status;
1236
1237         /*
1238          * Install a global async callback.  This callback will
1239          * receive async callbacks like "new device found".
1240          */
1241         status = xpt_register_async(AC_FOUND_DEVICE, daasync, NULL, NULL);
1242
1243         if (status != CAM_REQ_CMP) {
1244                 printf("da: Failed to attach master async callback "
1245                        "due to status 0x%x!\n", status);
1246         } else if (da_send_ordered) {
1247
1248                 /* Register our shutdown event handler */
1249                 if ((EVENTHANDLER_REGISTER(shutdown_post_sync, dashutdown, 
1250                                            NULL, SHUTDOWN_PRI_DEFAULT)) == NULL)
1251                     printf("dainit: shutdown event registration failed!\n");
1252         }
1253 }
1254
1255 /*
1256  * Callback from GEOM, called when it has finished cleaning up its
1257  * resources.
1258  */
1259 static void
1260 dadiskgonecb(struct disk *dp)
1261 {
1262         struct cam_periph *periph;
1263
1264         periph = (struct cam_periph *)dp->d_drv1;
1265
1266         cam_periph_release(periph);
1267 }
1268
1269 static void
1270 daoninvalidate(struct cam_periph *periph)
1271 {
1272         struct da_softc *softc;
1273
1274         softc = (struct da_softc *)periph->softc;
1275
1276         /*
1277          * De-register any async callbacks.
1278          */
1279         xpt_register_async(0, daasync, periph, periph->path);
1280
1281         softc->flags |= DA_FLAG_PACK_INVALID;
1282
1283         /*
1284          * Return all queued I/O with ENXIO.
1285          * XXX Handle any transactions queued to the card
1286          *     with XPT_ABORT_CCB.
1287          */
1288         bioq_flush(&softc->bio_queue, NULL, ENXIO);
1289         bioq_flush(&softc->delete_queue, NULL, ENXIO);
1290
1291         /*
1292          * Tell GEOM that we've gone away, we'll get a callback when it is
1293          * done cleaning up its resources.
1294          */
1295         disk_gone(softc->disk);
1296
1297         xpt_print(periph->path, "lost device - %d outstanding, %d refs\n",
1298                   softc->outstanding_cmds, periph->refcount);
1299 }
1300
1301 static void
1302 dacleanup(struct cam_periph *periph)
1303 {
1304         struct da_softc *softc;
1305
1306         softc = (struct da_softc *)periph->softc;
1307
1308         xpt_print(periph->path, "removing device entry\n");
1309         cam_periph_unlock(periph);
1310
1311         /*
1312          * If we can't free the sysctl tree, oh well...
1313          */
1314         if ((softc->flags & DA_FLAG_SCTX_INIT) != 0
1315             && sysctl_ctx_free(&softc->sysctl_ctx) != 0) {
1316                 xpt_print(periph->path, "can't remove sysctl context\n");
1317         }
1318
1319         disk_destroy(softc->disk);
1320         callout_drain(&softc->sendordered_c);
1321         free(softc, M_DEVBUF);
1322         cam_periph_lock(periph);
1323 }
1324
1325 static void
1326 daasync(void *callback_arg, u_int32_t code,
1327         struct cam_path *path, void *arg)
1328 {
1329         struct cam_periph *periph;
1330
1331         periph = (struct cam_periph *)callback_arg;
1332         switch (code) {
1333         case AC_FOUND_DEVICE:
1334         {
1335                 struct ccb_getdev *cgd;
1336                 cam_status status;
1337  
1338                 cgd = (struct ccb_getdev *)arg;
1339                 if (cgd == NULL)
1340                         break;
1341
1342                 if (cgd->protocol != PROTO_SCSI)
1343                         break;
1344
1345                 if (SID_TYPE(&cgd->inq_data) != T_DIRECT
1346                     && SID_TYPE(&cgd->inq_data) != T_RBC
1347                     && SID_TYPE(&cgd->inq_data) != T_OPTICAL)
1348                         break;
1349
1350                 /*
1351                  * Allocate a peripheral instance for
1352                  * this device and start the probe
1353                  * process.
1354                  */
1355                 status = cam_periph_alloc(daregister, daoninvalidate,
1356                                           dacleanup, dastart,
1357                                           "da", CAM_PERIPH_BIO,
1358                                           cgd->ccb_h.path, daasync,
1359                                           AC_FOUND_DEVICE, cgd);
1360
1361                 if (status != CAM_REQ_CMP
1362                  && status != CAM_REQ_INPROG)
1363                         printf("daasync: Unable to attach to new device "
1364                                 "due to status 0x%x\n", status);
1365                 return;
1366         }
1367         case AC_ADVINFO_CHANGED:
1368         {
1369                 uintptr_t buftype;
1370
1371                 buftype = (uintptr_t)arg;
1372                 if (buftype == CDAI_TYPE_PHYS_PATH) {
1373                         struct da_softc *softc;
1374
1375                         softc = periph->softc;
1376                         disk_attr_changed(softc->disk, "GEOM::physpath",
1377                                           M_NOWAIT);
1378                 }
1379                 break;
1380         }
1381         case AC_SENT_BDR:
1382         case AC_BUS_RESET:
1383         {
1384                 struct da_softc *softc;
1385                 struct ccb_hdr *ccbh;
1386
1387                 softc = (struct da_softc *)periph->softc;
1388                 /*
1389                  * Don't fail on the expected unit attention
1390                  * that will occur.
1391                  */
1392                 softc->flags |= DA_FLAG_RETRY_UA;
1393                 LIST_FOREACH(ccbh, &softc->pending_ccbs, periph_links.le)
1394                         ccbh->ccb_state |= DA_CCB_RETRY_UA;
1395                 break;
1396         }
1397         default:
1398                 break;
1399         }
1400         cam_periph_async(periph, code, path, arg);
1401 }
1402
1403 static void
1404 dasysctlinit(void *context, int pending)
1405 {
1406         struct cam_periph *periph;
1407         struct da_softc *softc;
1408         char tmpstr[80], tmpstr2[80];
1409         struct ccb_trans_settings cts;
1410
1411         periph = (struct cam_periph *)context;
1412         /*
1413          * periph was held for us when this task was enqueued
1414          */
1415         if (periph->flags & CAM_PERIPH_INVALID) {
1416                 cam_periph_release(periph);
1417                 return;
1418         }
1419
1420         softc = (struct da_softc *)periph->softc;
1421         snprintf(tmpstr, sizeof(tmpstr), "CAM DA unit %d", periph->unit_number);
1422         snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
1423
1424         sysctl_ctx_init(&softc->sysctl_ctx);
1425         softc->flags |= DA_FLAG_SCTX_INIT;
1426         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1427                 SYSCTL_STATIC_CHILDREN(_kern_cam_da), OID_AUTO, tmpstr2,
1428                 CTLFLAG_RD, 0, tmpstr);
1429         if (softc->sysctl_tree == NULL) {
1430                 printf("dasysctlinit: unable to allocate sysctl tree\n");
1431                 cam_periph_release(periph);
1432                 return;
1433         }
1434
1435         /*
1436          * Now register the sysctl handler, so the user can change the value on
1437          * the fly.
1438          */
1439         SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1440                 OID_AUTO, "delete_method", CTLTYPE_STRING | CTLFLAG_RW,
1441                 &softc->delete_method, 0, dadeletemethodsysctl, "A",
1442                 "BIO_DELETE execution method");
1443         SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1444                 OID_AUTO, "minimum_cmd_size", CTLTYPE_INT | CTLFLAG_RW,
1445                 &softc->minimum_cmd_size, 0, dacmdsizesysctl, "I",
1446                 "Minimum CDB size");
1447
1448         SYSCTL_ADD_INT(&softc->sysctl_ctx,
1449                        SYSCTL_CHILDREN(softc->sysctl_tree),
1450                        OID_AUTO,
1451                        "error_inject",
1452                        CTLFLAG_RW,
1453                        &softc->error_inject,
1454                        0,
1455                        "error_inject leaf");
1456
1457
1458         /*
1459          * Add some addressing info.
1460          */
1461         memset(&cts, 0, sizeof (cts));
1462         xpt_setup_ccb(&cts.ccb_h, periph->path, /*priority*/1);
1463         cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
1464         cts.type = CTS_TYPE_CURRENT_SETTINGS;
1465         cam_periph_lock(periph);
1466         xpt_action((union ccb *)&cts);
1467         cam_periph_unlock(periph);
1468         if (cts.ccb_h.status != CAM_REQ_CMP) {
1469                 cam_periph_release(periph);
1470                 return;
1471         }
1472         if (cts.protocol == PROTO_SCSI && cts.transport == XPORT_FC) {
1473                 struct ccb_trans_settings_fc *fc = &cts.xport_specific.fc;
1474                 if (fc->valid & CTS_FC_VALID_WWPN) {
1475                         softc->wwpn = fc->wwpn;
1476                         SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
1477                             SYSCTL_CHILDREN(softc->sysctl_tree),
1478                             OID_AUTO, "wwpn", CTLFLAG_RD,
1479                             &softc->wwpn, "World Wide Port Name");
1480                 }
1481         }
1482         cam_periph_release(periph);
1483 }
1484
1485 static int
1486 dacmdsizesysctl(SYSCTL_HANDLER_ARGS)
1487 {
1488         int error, value;
1489
1490         value = *(int *)arg1;
1491
1492         error = sysctl_handle_int(oidp, &value, 0, req);
1493
1494         if ((error != 0)
1495          || (req->newptr == NULL))
1496                 return (error);
1497
1498         /*
1499          * Acceptable values here are 6, 10, 12 or 16.
1500          */
1501         if (value < 6)
1502                 value = 6;
1503         else if ((value > 6)
1504               && (value <= 10))
1505                 value = 10;
1506         else if ((value > 10)
1507               && (value <= 12))
1508                 value = 12;
1509         else if (value > 12)
1510                 value = 16;
1511
1512         *(int *)arg1 = value;
1513
1514         return (0);
1515 }
1516
1517 static int
1518 dadeletemethodsysctl(SYSCTL_HANDLER_ARGS)
1519 {
1520         char buf[16];
1521         int error;
1522         const char *p;
1523         int i, value;
1524
1525         value = *(int *)arg1;
1526         if (value < 0 || value > DA_DELETE_MAX)
1527                 p = "UNKNOWN";
1528         else
1529                 p = da_delete_method_names[value];
1530         strncpy(buf, p, sizeof(buf));
1531         error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
1532         if (error != 0 || req->newptr == NULL)
1533                 return (error);
1534         for (i = 0; i <= DA_DELETE_MAX; i++) {
1535                 if (strcmp(buf, da_delete_method_names[i]) != 0)
1536                         continue;
1537                 *(int *)arg1 = i;
1538                 return (0);
1539         }
1540         return (EINVAL);
1541 }
1542
1543 static cam_status
1544 daregister(struct cam_periph *periph, void *arg)
1545 {
1546         struct da_softc *softc;
1547         struct ccb_pathinq cpi;
1548         struct ccb_getdev *cgd;
1549         char tmpstr[80];
1550         caddr_t match;
1551
1552         cgd = (struct ccb_getdev *)arg;
1553         if (cgd == NULL) {
1554                 printf("daregister: no getdev CCB, can't register device\n");
1555                 return(CAM_REQ_CMP_ERR);
1556         }
1557
1558         softc = (struct da_softc *)malloc(sizeof(*softc), M_DEVBUF,
1559             M_NOWAIT|M_ZERO);
1560
1561         if (softc == NULL) {
1562                 printf("daregister: Unable to probe new device. "
1563                        "Unable to allocate softc\n");                           
1564                 return(CAM_REQ_CMP_ERR);
1565         }
1566
1567         LIST_INIT(&softc->pending_ccbs);
1568         softc->state = DA_STATE_PROBE;
1569         bioq_init(&softc->bio_queue);
1570         bioq_init(&softc->delete_queue);
1571         bioq_init(&softc->delete_run_queue);
1572         if (SID_IS_REMOVABLE(&cgd->inq_data))
1573                 softc->flags |= DA_FLAG_PACK_REMOVABLE;
1574         softc->unmap_max_ranges = UNMAP_MAX_RANGES;
1575         softc->unmap_max_lba = 1024*1024*2;
1576
1577         periph->softc = softc;
1578
1579         /*
1580          * See if this device has any quirks.
1581          */
1582         match = cam_quirkmatch((caddr_t)&cgd->inq_data,
1583                                (caddr_t)da_quirk_table,
1584                                sizeof(da_quirk_table)/sizeof(*da_quirk_table),
1585                                sizeof(*da_quirk_table), scsi_inquiry_match);
1586
1587         if (match != NULL)
1588                 softc->quirks = ((struct da_quirk_entry *)match)->quirks;
1589         else
1590                 softc->quirks = DA_Q_NONE;
1591
1592         /* Check if the SIM does not want 6 byte commands */
1593         bzero(&cpi, sizeof(cpi));
1594         xpt_setup_ccb(&cpi.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1595         cpi.ccb_h.func_code = XPT_PATH_INQ;
1596         xpt_action((union ccb *)&cpi);
1597         if (cpi.ccb_h.status == CAM_REQ_CMP && (cpi.hba_misc & PIM_NO_6_BYTE))
1598                 softc->quirks |= DA_Q_NO_6_BYTE;
1599
1600         TASK_INIT(&softc->sysctl_task, 0, dasysctlinit, periph);
1601
1602         /*
1603          * Take an exclusive refcount on the periph while dastart is called
1604          * to finish the probe.  The reference will be dropped in dadone at
1605          * the end of probe.
1606          */
1607         (void)cam_periph_hold(periph, PRIBIO);
1608
1609         /*
1610          * Schedule a periodic event to occasionally send an
1611          * ordered tag to a device.
1612          */
1613         callout_init_mtx(&softc->sendordered_c, periph->sim->mtx, 0);
1614         callout_reset(&softc->sendordered_c,
1615             (da_default_timeout * hz) / DA_ORDEREDTAG_INTERVAL,
1616             dasendorderedtag, softc);
1617
1618         mtx_unlock(periph->sim->mtx);
1619         /*
1620          * RBC devices don't have to support READ(6), only READ(10).
1621          */
1622         if (softc->quirks & DA_Q_NO_6_BYTE || SID_TYPE(&cgd->inq_data) == T_RBC)
1623                 softc->minimum_cmd_size = 10;
1624         else
1625                 softc->minimum_cmd_size = 6;
1626
1627         /*
1628          * Load the user's default, if any.
1629          */
1630         snprintf(tmpstr, sizeof(tmpstr), "kern.cam.da.%d.minimum_cmd_size",
1631                  periph->unit_number);
1632         TUNABLE_INT_FETCH(tmpstr, &softc->minimum_cmd_size);
1633
1634         /*
1635          * 6, 10, 12 and 16 are the currently permissible values.
1636          */
1637         if (softc->minimum_cmd_size < 6)
1638                 softc->minimum_cmd_size = 6;
1639         else if ((softc->minimum_cmd_size > 6)
1640               && (softc->minimum_cmd_size <= 10))
1641                 softc->minimum_cmd_size = 10;
1642         else if ((softc->minimum_cmd_size > 10)
1643               && (softc->minimum_cmd_size <= 12))
1644                 softc->minimum_cmd_size = 12;
1645         else if (softc->minimum_cmd_size > 12)
1646                 softc->minimum_cmd_size = 16;
1647
1648         /* Predict whether device may support READ CAPACITY(16). */
1649         if (SID_ANSI_REV(&cgd->inq_data) >= SCSI_REV_SPC3) {
1650                 softc->flags |= DA_FLAG_CAN_RC16;
1651                 softc->state = DA_STATE_PROBE2;
1652         }
1653
1654         /*
1655          * Register this media as a disk.
1656          */
1657         softc->disk = disk_alloc();
1658         softc->disk->d_devstat = devstat_new_entry(periph->periph_name,
1659                           periph->unit_number, 0,
1660                           DEVSTAT_BS_UNAVAILABLE,
1661                           SID_TYPE(&cgd->inq_data) |
1662                           XPORT_DEVSTAT_TYPE(cpi.transport),
1663                           DEVSTAT_PRIORITY_DISK);
1664         softc->disk->d_open = daopen;
1665         softc->disk->d_close = daclose;
1666         softc->disk->d_strategy = dastrategy;
1667         softc->disk->d_dump = dadump;
1668         softc->disk->d_getattr = dagetattr;
1669         softc->disk->d_gone = dadiskgonecb;
1670         softc->disk->d_name = "da";
1671         softc->disk->d_drv1 = periph;
1672         if (cpi.maxio == 0)
1673                 softc->disk->d_maxsize = DFLTPHYS;      /* traditional default */
1674         else if (cpi.maxio > MAXPHYS)
1675                 softc->disk->d_maxsize = MAXPHYS;       /* for safety */
1676         else
1677                 softc->disk->d_maxsize = cpi.maxio;
1678         softc->disk->d_unit = periph->unit_number;
1679         softc->disk->d_flags = 0;
1680         if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0)
1681                 softc->disk->d_flags |= DISKFLAG_CANFLUSHCACHE;
1682         cam_strvis(softc->disk->d_descr, cgd->inq_data.vendor,
1683             sizeof(cgd->inq_data.vendor), sizeof(softc->disk->d_descr));
1684         strlcat(softc->disk->d_descr, " ", sizeof(softc->disk->d_descr));
1685         cam_strvis(&softc->disk->d_descr[strlen(softc->disk->d_descr)],
1686             cgd->inq_data.product, sizeof(cgd->inq_data.product),
1687             sizeof(softc->disk->d_descr) - strlen(softc->disk->d_descr));
1688         softc->disk->d_hba_vendor = cpi.hba_vendor;
1689         softc->disk->d_hba_device = cpi.hba_device;
1690         softc->disk->d_hba_subvendor = cpi.hba_subvendor;
1691         softc->disk->d_hba_subdevice = cpi.hba_subdevice;
1692
1693         /*
1694          * Acquire a reference to the periph before we register with GEOM.
1695          * We'll release this reference once GEOM calls us back (via
1696          * dadiskgonecb()) telling us that our provider has been freed.
1697          */
1698         if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
1699                 xpt_print(periph->path, "%s: lost periph during "
1700                           "registration!\n", __func__);
1701                 mtx_lock(periph->sim->mtx);
1702                 return (CAM_REQ_CMP_ERR);
1703         }
1704
1705         disk_create(softc->disk, DISK_VERSION);
1706         mtx_lock(periph->sim->mtx);
1707
1708         /*
1709          * Add async callbacks for events of interest.
1710          * I don't bother checking if this fails as,
1711          * in most cases, the system will function just
1712          * fine without them and the only alternative
1713          * would be to not attach the device on failure.
1714          */
1715         xpt_register_async(AC_SENT_BDR | AC_BUS_RESET
1716                          | AC_LOST_DEVICE | AC_ADVINFO_CHANGED,
1717                            daasync, periph, periph->path);
1718
1719         /*
1720          * Emit an attribute changed notification just in case 
1721          * physical path information arrived before our async
1722          * event handler was registered, but after anyone attaching
1723          * to our disk device polled it.
1724          */
1725         disk_attr_changed(softc->disk, "GEOM::physpath", M_NOWAIT);
1726
1727         xpt_schedule(periph, CAM_PRIORITY_DEV);
1728
1729         return(CAM_REQ_CMP);
1730 }
1731
1732 static void
1733 dastart(struct cam_periph *periph, union ccb *start_ccb)
1734 {
1735         struct da_softc *softc;
1736
1737         softc = (struct da_softc *)periph->softc;
1738
1739         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dastart\n"));
1740
1741         switch (softc->state) {
1742         case DA_STATE_NORMAL:
1743         {
1744                 struct bio *bp, *bp1;
1745                 uint8_t tag_code;
1746
1747                 /* Execute immediate CCB if waiting. */
1748                 if (periph->immediate_priority <= periph->pinfo.priority) {
1749                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE,
1750                                         ("queuing for immediate ccb\n"));
1751                         start_ccb->ccb_h.ccb_state = DA_CCB_WAITING;
1752                         SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
1753                                           periph_links.sle);
1754                         periph->immediate_priority = CAM_PRIORITY_NONE;
1755                         wakeup(&periph->ccb_list);
1756                         /* May have more work to do, so ensure we stay scheduled */
1757                         daschedule(periph);
1758                         break;
1759                 }
1760
1761                 /* Run BIO_DELETE if not running yet. */
1762                 if (!softc->delete_running &&
1763                     (bp = bioq_first(&softc->delete_queue)) != NULL) {
1764                     uint64_t lba;
1765                     u_int count;
1766
1767                     if (softc->delete_method == DA_DELETE_UNMAP) {
1768                         uint8_t *buf = softc->unmap_buf;
1769                         uint64_t lastlba = (uint64_t)-1;
1770                         uint32_t lastcount = 0;
1771                         int blocks = 0, off, ranges = 0;
1772
1773                         softc->delete_running = 1;
1774                         bzero(softc->unmap_buf, sizeof(softc->unmap_buf));
1775                         bp1 = bp;
1776                         do {
1777                                 bioq_remove(&softc->delete_queue, bp1);
1778                                 if (bp1 != bp)
1779                                         bioq_insert_tail(&softc->delete_run_queue, bp1);
1780                                 lba = bp1->bio_pblkno;
1781                                 count = bp1->bio_bcount / softc->params.secsize;
1782
1783                                 /* Try to extend the previous range. */
1784                                 if (lba == lastlba) {
1785                                         lastcount += count;
1786                                         off = (ranges - 1) * 16 + 8;
1787                                         scsi_ulto4b(lastcount, &buf[off + 8]);
1788                                 } else if (count > 0) {
1789                                         off = ranges * 16 + 8;
1790                                         scsi_u64to8b(lba, &buf[off + 0]);
1791                                         scsi_ulto4b(count, &buf[off + 8]);
1792                                         lastcount = count;
1793                                         ranges++;
1794                                 }
1795                                 blocks += count;
1796                                 lastlba = lba + count;
1797                                 bp1 = bioq_first(&softc->delete_queue);
1798                                 if (bp1 == NULL ||
1799                                     ranges >= softc->unmap_max_ranges ||
1800                                     blocks + bp1->bio_bcount /
1801                                      softc->params.secsize > softc->unmap_max_lba)
1802                                         break;
1803                         } while (1);
1804                         scsi_ulto2b(ranges * 16 + 6, &buf[0]);
1805                         scsi_ulto2b(ranges * 16, &buf[2]);
1806
1807                         scsi_unmap(&start_ccb->csio,
1808                                         /*retries*/da_retry_count,
1809                                         /*cbfcnp*/dadone,
1810                                         /*tag_action*/MSG_SIMPLE_Q_TAG,
1811                                         /*byte2*/0,
1812                                         /*data_ptr*/ buf,
1813                                         /*dxfer_len*/ ranges * 16 + 8,
1814                                         /*sense_len*/SSD_FULL_SIZE,
1815                                         da_default_timeout * 1000);
1816                         start_ccb->ccb_h.ccb_state = DA_CCB_DELETE;
1817                         goto out;
1818                     } else if (softc->delete_method == DA_DELETE_ZERO ||
1819                                softc->delete_method == DA_DELETE_WS10 ||
1820                                softc->delete_method == DA_DELETE_WS16) {
1821                         softc->delete_running = 1;
1822                         lba = bp->bio_pblkno;
1823                         count = 0;
1824                         bp1 = bp;
1825                         do {
1826                                 bioq_remove(&softc->delete_queue, bp1);
1827                                 if (bp1 != bp)
1828                                         bioq_insert_tail(&softc->delete_run_queue, bp1);
1829                                 count += bp1->bio_bcount / softc->params.secsize;
1830                                 bp1 = bioq_first(&softc->delete_queue);
1831                                 if (bp1 == NULL ||
1832                                     lba + count != bp1->bio_pblkno ||
1833                                     count + bp1->bio_bcount /
1834                                      softc->params.secsize > 0xffff)
1835                                         break;
1836                         } while (1);
1837
1838                         scsi_write_same(&start_ccb->csio,
1839                                         /*retries*/da_retry_count,
1840                                         /*cbfcnp*/dadone,
1841                                         /*tag_action*/MSG_SIMPLE_Q_TAG,
1842                                         /*byte2*/softc->delete_method ==
1843                                             DA_DELETE_ZERO ? 0 : SWS_UNMAP,
1844                                         softc->delete_method ==
1845                                             DA_DELETE_WS16 ? 16 : 10,
1846                                         /*lba*/lba,
1847                                         /*block_count*/count,
1848                                         /*data_ptr*/ __DECONST(void *,
1849                                             zero_region),
1850                                         /*dxfer_len*/ softc->params.secsize,
1851                                         /*sense_len*/SSD_FULL_SIZE,
1852                                         da_default_timeout * 1000);
1853                         start_ccb->ccb_h.ccb_state = DA_CCB_DELETE;
1854                         goto out;
1855                     } else {
1856                         bioq_flush(&softc->delete_queue, NULL, 0);
1857                         /* FALLTHROUGH */
1858                     }
1859                 }
1860
1861                 /* Run regular command. */
1862                 bp = bioq_takefirst(&softc->bio_queue);
1863                 if (bp == NULL) {
1864                         xpt_release_ccb(start_ccb);
1865                         break;
1866                 }
1867
1868                 if ((bp->bio_flags & BIO_ORDERED) != 0 ||
1869                     (softc->flags & DA_FLAG_NEED_OTAG) != 0) {
1870                         softc->flags &= ~DA_FLAG_NEED_OTAG;
1871                         softc->ordered_tag_count++;
1872                         tag_code = MSG_ORDERED_Q_TAG;
1873                 } else {
1874                         tag_code = MSG_SIMPLE_Q_TAG;
1875                 }
1876
1877                 switch (bp->bio_cmd) {
1878                 case BIO_READ:
1879                 case BIO_WRITE:
1880                         scsi_read_write(&start_ccb->csio,
1881                                         /*retries*/da_retry_count,
1882                                         /*cbfcnp*/dadone,
1883                                         /*tag_action*/tag_code,
1884                                         /*read_op*/bp->bio_cmd
1885                                                 == BIO_READ,
1886                                         /*byte2*/0,
1887                                         softc->minimum_cmd_size,
1888                                         /*lba*/bp->bio_pblkno,
1889                                         /*block_count*/bp->bio_bcount /
1890                                         softc->params.secsize,
1891                                         /*data_ptr*/ bp->bio_data,
1892                                         /*dxfer_len*/ bp->bio_bcount,
1893                                         /*sense_len*/SSD_FULL_SIZE,
1894                                         da_default_timeout * 1000);
1895                         break;
1896                 case BIO_FLUSH:
1897                         /*
1898                          * BIO_FLUSH doesn't currently communicate
1899                          * range data, so we synchronize the cache
1900                          * over the whole disk.  We also force
1901                          * ordered tag semantics the flush applies
1902                          * to all previously queued I/O.
1903                          */
1904                         scsi_synchronize_cache(&start_ccb->csio,
1905                                                /*retries*/1,
1906                                                /*cbfcnp*/dadone,
1907                                                MSG_ORDERED_Q_TAG,
1908                                                /*begin_lba*/0,
1909                                                /*lb_count*/0,
1910                                                SSD_FULL_SIZE,
1911                                                da_default_timeout*1000);
1912                         break;
1913                 }
1914                 start_ccb->ccb_h.ccb_state = DA_CCB_BUFFER_IO;
1915
1916 out:
1917                 /*
1918                  * Block out any asyncronous callbacks
1919                  * while we touch the pending ccb list.
1920                  */
1921                 LIST_INSERT_HEAD(&softc->pending_ccbs,
1922                                  &start_ccb->ccb_h, periph_links.le);
1923                 softc->outstanding_cmds++;
1924
1925                 /* We expect a unit attention from this device */
1926                 if ((softc->flags & DA_FLAG_RETRY_UA) != 0) {
1927                         start_ccb->ccb_h.ccb_state |= DA_CCB_RETRY_UA;
1928                         softc->flags &= ~DA_FLAG_RETRY_UA;
1929                 }
1930
1931                 start_ccb->ccb_h.ccb_bp = bp;
1932                 xpt_action(start_ccb);
1933
1934                 /* May have more work to do, so ensure we stay scheduled */
1935                 daschedule(periph);
1936                 break;
1937         }
1938         case DA_STATE_PROBE:
1939         {
1940                 struct ccb_scsiio *csio;
1941                 struct scsi_read_capacity_data *rcap;
1942
1943                 rcap = (struct scsi_read_capacity_data *)
1944                     malloc(sizeof(*rcap), M_SCSIDA, M_NOWAIT|M_ZERO);
1945                 if (rcap == NULL) {
1946                         printf("dastart: Couldn't malloc read_capacity data\n");
1947                         /* da_free_periph??? */
1948                         break;
1949                 }
1950                 csio = &start_ccb->csio;
1951                 scsi_read_capacity(csio,
1952                                    /*retries*/4,
1953                                    dadone,
1954                                    MSG_SIMPLE_Q_TAG,
1955                                    rcap,
1956                                    SSD_FULL_SIZE,
1957                                    /*timeout*/5000);
1958                 start_ccb->ccb_h.ccb_bp = NULL;
1959                 start_ccb->ccb_h.ccb_state = DA_CCB_PROBE;
1960                 xpt_action(start_ccb);
1961                 break;
1962         }
1963         case DA_STATE_PROBE2:
1964         {
1965                 struct ccb_scsiio *csio;
1966                 struct scsi_read_capacity_data_long *rcaplong;
1967
1968                 rcaplong = (struct scsi_read_capacity_data_long *)
1969                         malloc(sizeof(*rcaplong), M_SCSIDA, M_NOWAIT|M_ZERO);
1970                 if (rcaplong == NULL) {
1971                         printf("dastart: Couldn't malloc read_capacity data\n");
1972                         /* da_free_periph??? */
1973                         break;
1974                 }
1975                 csio = &start_ccb->csio;
1976                 scsi_read_capacity_16(csio,
1977                                       /*retries*/ 4,
1978                                       /*cbfcnp*/ dadone,
1979                                       /*tag_action*/ MSG_SIMPLE_Q_TAG,
1980                                       /*lba*/ 0,
1981                                       /*reladr*/ 0,
1982                                       /*pmi*/ 0,
1983                                       rcaplong,
1984                                       /*sense_len*/ SSD_FULL_SIZE,
1985                                       /*timeout*/ 60000);
1986                 start_ccb->ccb_h.ccb_bp = NULL;
1987                 start_ccb->ccb_h.ccb_state = DA_CCB_PROBE2;
1988                 xpt_action(start_ccb);  
1989                 break;
1990         }
1991         }
1992 }
1993
1994 static int
1995 cmd6workaround(union ccb *ccb)
1996 {
1997         struct scsi_rw_6 cmd6;
1998         struct scsi_rw_10 *cmd10;
1999         struct da_softc *softc;
2000         u_int8_t *cdb;
2001         struct bio *bp;
2002         int frozen;
2003
2004         cdb = ccb->csio.cdb_io.cdb_bytes;
2005         softc = (struct da_softc *)xpt_path_periph(ccb->ccb_h.path)->softc;
2006
2007         if (ccb->ccb_h.ccb_state == DA_CCB_DELETE) {
2008                 if (softc->delete_method == DA_DELETE_UNMAP) {
2009                         xpt_print(ccb->ccb_h.path, "UNMAP is not supported, "
2010                             "switching to WRITE SAME(16) with UNMAP.\n");
2011                         softc->delete_method = DA_DELETE_WS16;
2012                 } else if (softc->delete_method == DA_DELETE_WS16) {
2013                         xpt_print(ccb->ccb_h.path,
2014                             "WRITE SAME(16) with UNMAP is not supported, "
2015                             "disabling BIO_DELETE.\n");
2016                         softc->delete_method = DA_DELETE_DISABLE;
2017                 } else if (softc->delete_method == DA_DELETE_WS10) {
2018                         xpt_print(ccb->ccb_h.path,
2019                             "WRITE SAME(10) with UNMAP is not supported, "
2020                             "disabling BIO_DELETE.\n");
2021                         softc->delete_method = DA_DELETE_DISABLE;
2022                 } else if (softc->delete_method == DA_DELETE_ZERO) {
2023                         xpt_print(ccb->ccb_h.path,
2024                             "WRITE SAME(10) is not supported, "
2025                             "disabling BIO_DELETE.\n");
2026                         softc->delete_method = DA_DELETE_DISABLE;
2027                 } else
2028                         softc->delete_method = DA_DELETE_DISABLE;
2029                 while ((bp = bioq_takefirst(&softc->delete_run_queue))
2030                     != NULL)
2031                         bioq_disksort(&softc->delete_queue, bp);
2032                 bioq_insert_tail(&softc->delete_queue,
2033                     (struct bio *)ccb->ccb_h.ccb_bp);
2034                 ccb->ccb_h.ccb_bp = NULL;
2035                 return (0);
2036         }
2037
2038         /* Translation only possible if CDB is an array and cmd is R/W6 */
2039         if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0 ||
2040             (*cdb != READ_6 && *cdb != WRITE_6))
2041                 return 0;
2042
2043         xpt_print(ccb->ccb_h.path, "READ(6)/WRITE(6) not supported, "
2044             "increasing minimum_cmd_size to 10.\n");
2045         softc->minimum_cmd_size = 10;
2046
2047         bcopy(cdb, &cmd6, sizeof(struct scsi_rw_6));
2048         cmd10 = (struct scsi_rw_10 *)cdb;
2049         cmd10->opcode = (cmd6.opcode == READ_6) ? READ_10 : WRITE_10;
2050         cmd10->byte2 = 0;
2051         scsi_ulto4b(scsi_3btoul(cmd6.addr), cmd10->addr);
2052         cmd10->reserved = 0;
2053         scsi_ulto2b(cmd6.length, cmd10->length);
2054         cmd10->control = cmd6.control;
2055         ccb->csio.cdb_len = sizeof(*cmd10);
2056
2057         /* Requeue request, unfreezing queue if necessary */
2058         frozen = (ccb->ccb_h.status & CAM_DEV_QFRZN) != 0;
2059         ccb->ccb_h.status = CAM_REQUEUE_REQ;
2060         xpt_action(ccb);
2061         if (frozen) {
2062                 cam_release_devq(ccb->ccb_h.path,
2063                                  /*relsim_flags*/0,
2064                                  /*reduction*/0,
2065                                  /*timeout*/0,
2066                                  /*getcount_only*/0);
2067         }
2068         return (ERESTART);
2069 }
2070
2071 static void
2072 dadone(struct cam_periph *periph, union ccb *done_ccb)
2073 {
2074         struct da_softc *softc;
2075         struct ccb_scsiio *csio;
2076         u_int32_t  priority;
2077
2078         softc = (struct da_softc *)periph->softc;
2079         priority = done_ccb->ccb_h.pinfo.priority;
2080
2081         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("dadone\n"));
2082
2083         csio = &done_ccb->csio;
2084         switch (csio->ccb_h.ccb_state & DA_CCB_TYPE_MASK) {
2085         case DA_CCB_BUFFER_IO:
2086         case DA_CCB_DELETE:
2087         {
2088                 struct bio *bp, *bp1;
2089
2090                 bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
2091                 if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2092                         int error;
2093                         int sf;
2094
2095                         if ((csio->ccb_h.ccb_state & DA_CCB_RETRY_UA) != 0)
2096                                 sf = SF_RETRY_UA;
2097                         else
2098                                 sf = 0;
2099
2100                         error = daerror(done_ccb, CAM_RETRY_SELTO, sf);
2101                         if (error == ERESTART) {
2102                                 /*
2103                                  * A retry was scheuled, so
2104                                  * just return.
2105                                  */
2106                                 return;
2107                         }
2108                         bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
2109                         if (error != 0) {
2110                                 int queued_error;
2111
2112                                 /*
2113                                  * return all queued I/O with EIO, so that
2114                                  * the client can retry these I/Os in the
2115                                  * proper order should it attempt to recover.
2116                                  */
2117                                 queued_error = EIO;
2118
2119                                 if (error == ENXIO
2120                                  && (softc->flags & DA_FLAG_PACK_INVALID)== 0) {
2121                                         /*
2122                                          * Catastrophic error.  Mark our pack as
2123                                          * invalid.
2124                                          */
2125                                         /*
2126                                          * XXX See if this is really a media
2127                                          * XXX change first?
2128                                          */
2129                                         xpt_print(periph->path,
2130                                             "Invalidating pack\n");
2131                                         softc->flags |= DA_FLAG_PACK_INVALID;
2132                                         queued_error = ENXIO;
2133                                 }
2134                                 bioq_flush(&softc->bio_queue, NULL,
2135                                            queued_error);
2136                                 if (bp != NULL) {
2137                                         bp->bio_error = error;
2138                                         bp->bio_resid = bp->bio_bcount;
2139                                         bp->bio_flags |= BIO_ERROR;
2140                                 }
2141                         } else if (bp != NULL) {
2142                                 bp->bio_resid = csio->resid;
2143                                 bp->bio_error = 0;
2144                                 if (bp->bio_resid != 0)
2145                                         bp->bio_flags |= BIO_ERROR;
2146                         }
2147                         if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
2148                                 cam_release_devq(done_ccb->ccb_h.path,
2149                                                  /*relsim_flags*/0,
2150                                                  /*reduction*/0,
2151                                                  /*timeout*/0,
2152                                                  /*getcount_only*/0);
2153                 } else if (bp != NULL) {
2154                         if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
2155                                 panic("REQ_CMP with QFRZN");
2156                         bp->bio_resid = csio->resid;
2157                         if (csio->resid > 0)
2158                                 bp->bio_flags |= BIO_ERROR;
2159                         if (softc->error_inject != 0) {
2160                                 bp->bio_error = softc->error_inject;
2161                                 bp->bio_resid = bp->bio_bcount;
2162                                 bp->bio_flags |= BIO_ERROR;
2163                                 softc->error_inject = 0;
2164                         }
2165
2166                 }
2167
2168                 /*
2169                  * Block out any asyncronous callbacks
2170                  * while we touch the pending ccb list.
2171                  */
2172                 LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
2173                 softc->outstanding_cmds--;
2174                 if (softc->outstanding_cmds == 0)
2175                         softc->flags |= DA_FLAG_WENT_IDLE;
2176
2177                 if ((softc->flags & DA_FLAG_PACK_INVALID) != 0) {
2178                         xpt_print(periph->path, "oustanding %d\n",
2179                                   softc->outstanding_cmds);
2180                 }
2181
2182                 if ((csio->ccb_h.ccb_state & DA_CCB_TYPE_MASK) ==
2183                     DA_CCB_DELETE) {
2184                         while ((bp1 = bioq_takefirst(&softc->delete_run_queue))
2185                             != NULL) {
2186                                 bp1->bio_resid = bp->bio_resid;
2187                                 bp1->bio_error = bp->bio_error;
2188                                 if (bp->bio_flags & BIO_ERROR)
2189                                         bp1->bio_flags |= BIO_ERROR;
2190                                 biodone(bp1);
2191                         }
2192                         softc->delete_running = 0;
2193                         if (bp != NULL)
2194                                 biodone(bp);
2195                         daschedule(periph);
2196                 } else if (bp != NULL)
2197                         biodone(bp);
2198                 break;
2199         }
2200         case DA_CCB_PROBE:
2201         case DA_CCB_PROBE2:
2202         {
2203                 struct     scsi_read_capacity_data *rdcap;
2204                 struct     scsi_read_capacity_data_long *rcaplong;
2205                 char       announce_buf[80];
2206
2207                 rdcap = NULL;
2208                 rcaplong = NULL;
2209                 if (softc->state == DA_STATE_PROBE)
2210                         rdcap =(struct scsi_read_capacity_data *)csio->data_ptr;
2211                 else
2212                         rcaplong = (struct scsi_read_capacity_data_long *)
2213                                 csio->data_ptr;
2214
2215                 if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
2216                         struct disk_params *dp;
2217                         uint32_t block_size;
2218                         uint64_t maxsector;
2219                         u_int lbppbe;   /* LB per physical block exponent. */
2220                         u_int lalba;    /* Lowest aligned LBA. */
2221
2222                         if (softc->state == DA_STATE_PROBE) {
2223                                 block_size = scsi_4btoul(rdcap->length);
2224                                 maxsector = scsi_4btoul(rdcap->addr);
2225                                 lbppbe = 0;
2226                                 lalba = 0;
2227
2228                                 /*
2229                                  * According to SBC-2, if the standard 10
2230                                  * byte READ CAPACITY command returns 2^32,
2231                                  * we should issue the 16 byte version of
2232                                  * the command, since the device in question
2233                                  * has more sectors than can be represented
2234                                  * with the short version of the command.
2235                                  */
2236                                 if (maxsector == 0xffffffff) {
2237                                         softc->state = DA_STATE_PROBE2;
2238                                         free(rdcap, M_SCSIDA);
2239                                         xpt_release_ccb(done_ccb);
2240                                         xpt_schedule(periph, priority);
2241                                         return;
2242                                 }
2243                         } else {
2244                                 block_size = scsi_4btoul(rcaplong->length);
2245                                 maxsector = scsi_8btou64(rcaplong->addr);
2246                                 lbppbe = rcaplong->prot_lbppbe & SRC16_LBPPBE;
2247                                 lalba = scsi_2btoul(rcaplong->lalba_lbp);
2248                         }
2249
2250                         /*
2251                          * Because GEOM code just will panic us if we
2252                          * give them an 'illegal' value we'll avoid that
2253                          * here.
2254                          */
2255                         if (block_size == 0 && maxsector == 0) {
2256                                 snprintf(announce_buf, sizeof(announce_buf),
2257                                         "0MB (no media?)");
2258                         } else if (block_size >= MAXPHYS || block_size == 0) {
2259                                 xpt_print(periph->path,
2260                                     "unsupportable block size %ju\n",
2261                                     (uintmax_t) block_size);
2262                                 announce_buf[0] = '\0';
2263                                 cam_periph_invalidate(periph);
2264                         } else {
2265                                 dasetgeom(periph, block_size, maxsector,
2266                                     lbppbe, lalba & SRC16_LALBA);
2267                                 if ((lalba & SRC16_LBPME) &&
2268                                     softc->delete_method == DA_DELETE_NONE)
2269                                         softc->delete_method = DA_DELETE_UNMAP;
2270                                 dp = &softc->params;
2271                                 snprintf(announce_buf, sizeof(announce_buf),
2272                                         "%juMB (%ju %u byte sectors: %dH %dS/T "
2273                                         "%dC)", (uintmax_t)
2274                                         (((uintmax_t)dp->secsize *
2275                                         dp->sectors) / (1024*1024)),
2276                                         (uintmax_t)dp->sectors,
2277                                         dp->secsize, dp->heads,
2278                                         dp->secs_per_track, dp->cylinders);
2279                         }
2280                 } else {
2281                         int     error;
2282
2283                         announce_buf[0] = '\0';
2284
2285                         /*
2286                          * Retry any UNIT ATTENTION type errors.  They
2287                          * are expected at boot.
2288                          */
2289                         error = daerror(done_ccb, CAM_RETRY_SELTO,
2290                                         SF_RETRY_UA|SF_NO_PRINT);
2291                         if (error == ERESTART) {
2292                                 /*
2293                                  * A retry was scheuled, so
2294                                  * just return.
2295                                  */
2296                                 return;
2297                         } else if (error != 0) {
2298                                 struct scsi_sense_data *sense;
2299                                 int asc, ascq;
2300                                 int sense_key, error_code;
2301                                 int have_sense;
2302                                 cam_status status;
2303                                 struct ccb_getdev cgd;
2304
2305                                 /* Don't wedge this device's queue */
2306                                 status = done_ccb->ccb_h.status;
2307                                 if ((status & CAM_DEV_QFRZN) != 0)
2308                                         cam_release_devq(done_ccb->ccb_h.path,
2309                                                          /*relsim_flags*/0,
2310                                                          /*reduction*/0,
2311                                                          /*timeout*/0,
2312                                                          /*getcount_only*/0);
2313
2314
2315                                 xpt_setup_ccb(&cgd.ccb_h, 
2316                                               done_ccb->ccb_h.path,
2317                                               CAM_PRIORITY_NORMAL);
2318                                 cgd.ccb_h.func_code = XPT_GDEV_TYPE;
2319                                 xpt_action((union ccb *)&cgd);
2320
2321                                 if (((csio->ccb_h.flags & CAM_SENSE_PHYS) != 0)
2322                                  || ((csio->ccb_h.flags & CAM_SENSE_PTR) != 0)
2323                                  || ((status & CAM_AUTOSNS_VALID) == 0))
2324                                         have_sense = FALSE;
2325                                 else
2326                                         have_sense = TRUE;
2327
2328                                 if (have_sense) {
2329                                         sense = &csio->sense_data;
2330                                         scsi_extract_sense_len(sense,
2331                                             csio->sense_len - csio->sense_resid,
2332                                             &error_code, &sense_key, &asc,
2333                                             &ascq, /*show_errors*/ 1);
2334                                 }
2335                                 /*
2336                                  * If we tried READ CAPACITY(16) and failed,
2337                                  * fallback to READ CAPACITY(10).
2338                                  */
2339                                 if ((softc->state == DA_STATE_PROBE2) &&
2340                                     (softc->flags & DA_FLAG_CAN_RC16) &&
2341                                     (((csio->ccb_h.status & CAM_STATUS_MASK) ==
2342                                         CAM_REQ_INVALID) ||
2343                                      ((have_sense) &&
2344                                       (error_code == SSD_CURRENT_ERROR) &&
2345                                       (sense_key == SSD_KEY_ILLEGAL_REQUEST)))) {
2346                                         softc->flags &= ~DA_FLAG_CAN_RC16;
2347                                         softc->state = DA_STATE_PROBE;
2348                                         free(rdcap, M_SCSIDA);
2349                                         xpt_release_ccb(done_ccb);
2350                                         xpt_schedule(periph, priority);
2351                                         return;
2352                                 } else
2353                                 /*
2354                                  * Attach to anything that claims to be a
2355                                  * direct access or optical disk device,
2356                                  * as long as it doesn't return a "Logical
2357                                  * unit not supported" (0x25) error.
2358                                  */
2359                                 if ((have_sense) && (asc != 0x25)
2360                                  && (error_code == SSD_CURRENT_ERROR)) {
2361                                         const char *sense_key_desc;
2362                                         const char *asc_desc;
2363
2364                                         scsi_sense_desc(sense_key, asc, ascq,
2365                                                         &cgd.inq_data,
2366                                                         &sense_key_desc,
2367                                                         &asc_desc);
2368                                         snprintf(announce_buf,
2369                                             sizeof(announce_buf),
2370                                                 "Attempt to query device "
2371                                                 "size failed: %s, %s",
2372                                                 sense_key_desc,
2373                                                 asc_desc);
2374                                 } else { 
2375                                         if (have_sense)
2376                                                 scsi_sense_print(
2377                                                         &done_ccb->csio);
2378                                         else {
2379                                                 xpt_print(periph->path,
2380                                                     "got CAM status %#x\n",
2381                                                     done_ccb->ccb_h.status);
2382                                         }
2383
2384                                         xpt_print(periph->path, "fatal error, "
2385                                             "failed to attach to device\n");
2386
2387                                         /*
2388                                          * Free up resources.
2389                                          */
2390                                         cam_periph_invalidate(periph);
2391                                 } 
2392                         }
2393                 }
2394                 free(csio->data_ptr, M_SCSIDA);
2395                 if (announce_buf[0] != '\0') {
2396                         /*
2397                          * Create our sysctl variables, now that we know
2398                          * we have successfully attached.
2399                          */
2400                         /* increase the refcount */
2401                         if (cam_periph_acquire(periph) == CAM_REQ_CMP) {
2402                                 taskqueue_enqueue(taskqueue_thread,
2403                                                   &softc->sysctl_task);
2404                                 xpt_announce_periph(periph, announce_buf);
2405                         } else {
2406                                 xpt_print(periph->path, "fatal error, "
2407                                     "could not acquire reference count\n");
2408                         }
2409                                 
2410                 }
2411                 softc->state = DA_STATE_NORMAL; 
2412                 /*
2413                  * Since our peripheral may be invalidated by an error
2414                  * above or an external event, we must release our CCB
2415                  * before releasing the probe lock on the peripheral.
2416                  * The peripheral will only go away once the last lock
2417                  * is removed, and we need it around for the CCB release
2418                  * operation.
2419                  */
2420                 xpt_release_ccb(done_ccb);
2421                 cam_periph_unhold(periph);
2422                 return;
2423         }
2424         case DA_CCB_WAITING:
2425         {
2426                 /* Caller will release the CCB */
2427                 wakeup(&done_ccb->ccb_h.cbfcnp);
2428                 return;
2429         }
2430         case DA_CCB_DUMP:
2431                 /* No-op.  We're polling */
2432                 return;
2433         default:
2434                 break;
2435         }
2436         xpt_release_ccb(done_ccb);
2437 }
2438
2439 static int
2440 daerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
2441 {
2442         struct da_softc   *softc;
2443         struct cam_periph *periph;
2444         int error;
2445
2446         periph = xpt_path_periph(ccb->ccb_h.path);
2447         softc = (struct da_softc *)periph->softc;
2448
2449         /*
2450          * Automatically detect devices that do not support
2451          * READ(6)/WRITE(6) and upgrade to using 10 byte cdbs.
2452          */
2453         error = 0;
2454         if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INVALID) {
2455                 error = cmd6workaround(ccb);
2456         } else if (((ccb->ccb_h.status & CAM_STATUS_MASK) ==
2457                    CAM_SCSI_STATUS_ERROR)
2458          && (ccb->ccb_h.status & CAM_AUTOSNS_VALID)
2459          && (ccb->csio.scsi_status == SCSI_STATUS_CHECK_COND)
2460          && ((ccb->ccb_h.flags & CAM_SENSE_PHYS) == 0)
2461          && ((ccb->ccb_h.flags & CAM_SENSE_PTR) == 0)) {
2462                 int sense_key, error_code, asc, ascq;
2463
2464                 scsi_extract_sense(&ccb->csio.sense_data,
2465                                    &error_code, &sense_key, &asc, &ascq);
2466                 if (sense_key == SSD_KEY_ILLEGAL_REQUEST)
2467                         error = cmd6workaround(ccb);
2468         }
2469         if (error == ERESTART)
2470                 return (ERESTART);
2471
2472         /*
2473          * XXX
2474          * Until we have a better way of doing pack validation,
2475          * don't treat UAs as errors.
2476          */
2477         sense_flags |= SF_RETRY_UA;
2478         return(cam_periph_error(ccb, cam_flags, sense_flags,
2479                                 &softc->saved_ccb));
2480 }
2481
2482 static void
2483 daprevent(struct cam_periph *periph, int action)
2484 {
2485         struct  da_softc *softc;
2486         union   ccb *ccb;               
2487         int     error;
2488                 
2489         softc = (struct da_softc *)periph->softc;
2490
2491         if (((action == PR_ALLOW)
2492           && (softc->flags & DA_FLAG_PACK_LOCKED) == 0)
2493          || ((action == PR_PREVENT)
2494           && (softc->flags & DA_FLAG_PACK_LOCKED) != 0)) {
2495                 return;
2496         }
2497
2498         ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
2499
2500         scsi_prevent(&ccb->csio,
2501                      /*retries*/1,
2502                      /*cbcfp*/dadone,
2503                      MSG_SIMPLE_Q_TAG,
2504                      action,
2505                      SSD_FULL_SIZE,
2506                      5000);
2507
2508         error = cam_periph_runccb(ccb, daerror, CAM_RETRY_SELTO,
2509             SF_RETRY_UA | SF_QUIET_IR, softc->disk->d_devstat);
2510
2511         if (error == 0) {
2512                 if (action == PR_ALLOW)
2513                         softc->flags &= ~DA_FLAG_PACK_LOCKED;
2514                 else
2515                         softc->flags |= DA_FLAG_PACK_LOCKED;
2516         }
2517
2518         xpt_release_ccb(ccb);
2519 }
2520
2521 static int
2522 dagetcapacity(struct cam_periph *periph)
2523 {
2524         struct da_softc *softc;
2525         union ccb *ccb;
2526         struct scsi_read_capacity_data *rcap;
2527         struct scsi_read_capacity_data_long *rcaplong;
2528         uint32_t block_len;
2529         uint64_t maxsector;
2530         int error, rc16failed;
2531         u_int32_t sense_flags;
2532         u_int lbppbe;   /* Logical blocks per physical block exponent. */
2533         u_int lalba;    /* Lowest aligned LBA. */
2534
2535         softc = (struct da_softc *)periph->softc;
2536         block_len = 0;
2537         maxsector = 0;
2538         lbppbe = 0;
2539         lalba = 0;
2540         error = 0;
2541         rc16failed = 0;
2542         sense_flags = SF_RETRY_UA;
2543         if (softc->flags & DA_FLAG_PACK_REMOVABLE)
2544                 sense_flags |= SF_NO_PRINT;
2545
2546         /* Do a read capacity */
2547         rcap = (struct scsi_read_capacity_data *)malloc(sizeof(*rcaplong),
2548                                                         M_SCSIDA,
2549                                                         M_NOWAIT | M_ZERO);
2550         if (rcap == NULL)
2551                 return (ENOMEM);
2552         rcaplong = (struct scsi_read_capacity_data_long *)rcap;
2553
2554         ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
2555
2556         /* Try READ CAPACITY(16) first if we think it should work. */
2557         if (softc->flags & DA_FLAG_CAN_RC16) {
2558                 scsi_read_capacity_16(&ccb->csio,
2559                               /*retries*/ 4,
2560                               /*cbfcnp*/ dadone,
2561                               /*tag_action*/ MSG_SIMPLE_Q_TAG,
2562                               /*lba*/ 0,
2563                               /*reladr*/ 0,
2564                               /*pmi*/ 0,
2565                               rcaplong,
2566                               /*sense_len*/ SSD_FULL_SIZE,
2567                               /*timeout*/ 60000);
2568                 ccb->ccb_h.ccb_bp = NULL;
2569
2570                 error = cam_periph_runccb(ccb, daerror,
2571                                   /*cam_flags*/CAM_RETRY_SELTO,
2572                                   sense_flags,
2573                                   softc->disk->d_devstat);
2574                 if (error == 0)
2575                         goto rc16ok;
2576
2577                 /* If we got ILLEGAL REQUEST, do not prefer RC16 any more. */
2578                 if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
2579                      CAM_REQ_INVALID) {
2580                         softc->flags &= ~DA_FLAG_CAN_RC16;
2581                 } else if (((ccb->ccb_h.status & CAM_STATUS_MASK) ==
2582                      CAM_SCSI_STATUS_ERROR) &&
2583                     (ccb->csio.scsi_status == SCSI_STATUS_CHECK_COND) &&
2584                     (ccb->ccb_h.status & CAM_AUTOSNS_VALID) &&
2585                     ((ccb->ccb_h.flags & CAM_SENSE_PHYS) == 0) &&
2586                     ((ccb->ccb_h.flags & CAM_SENSE_PTR) == 0)) {
2587                         int sense_key, error_code, asc, ascq;
2588
2589                         scsi_extract_sense(&ccb->csio.sense_data,
2590                                    &error_code, &sense_key, &asc, &ascq);
2591                         if (sense_key == SSD_KEY_ILLEGAL_REQUEST)
2592                                 softc->flags &= ~DA_FLAG_CAN_RC16;
2593                 }
2594                 rc16failed = 1;
2595         }
2596
2597         /* Do READ CAPACITY(10). */
2598         scsi_read_capacity(&ccb->csio,
2599                            /*retries*/4,
2600                            /*cbfncp*/dadone,
2601                            MSG_SIMPLE_Q_TAG,
2602                            rcap,
2603                            SSD_FULL_SIZE,
2604                            /*timeout*/60000);
2605         ccb->ccb_h.ccb_bp = NULL;
2606
2607         error = cam_periph_runccb(ccb, daerror,
2608                                   /*cam_flags*/CAM_RETRY_SELTO,
2609                                   sense_flags,
2610                                   softc->disk->d_devstat);
2611         if (error == 0) {
2612                 block_len = scsi_4btoul(rcap->length);
2613                 maxsector = scsi_4btoul(rcap->addr);
2614
2615                 if (maxsector != 0xffffffff || rc16failed)
2616                         goto done;
2617         } else
2618                 goto done;
2619
2620         /* If READ CAPACITY(10) returned overflow, use READ CAPACITY(16) */
2621         scsi_read_capacity_16(&ccb->csio,
2622                               /*retries*/ 4,
2623                               /*cbfcnp*/ dadone,
2624                               /*tag_action*/ MSG_SIMPLE_Q_TAG,
2625                               /*lba*/ 0,
2626                               /*reladr*/ 0,
2627                               /*pmi*/ 0,
2628                               rcaplong,
2629                               /*sense_len*/ SSD_FULL_SIZE,
2630                               /*timeout*/ 60000);
2631         ccb->ccb_h.ccb_bp = NULL;
2632
2633         error = cam_periph_runccb(ccb, daerror,
2634                                   /*cam_flags*/CAM_RETRY_SELTO,
2635                                   sense_flags,
2636                                   softc->disk->d_devstat);
2637         if (error == 0) {
2638 rc16ok:
2639                 block_len = scsi_4btoul(rcaplong->length);
2640                 maxsector = scsi_8btou64(rcaplong->addr);
2641                 lbppbe = rcaplong->prot_lbppbe & SRC16_LBPPBE;
2642                 lalba = scsi_2btoul(rcaplong->lalba_lbp);
2643         }
2644
2645 done:
2646
2647         if (error == 0) {
2648                 if (block_len >= MAXPHYS || block_len == 0) {
2649                         xpt_print(periph->path,
2650                             "unsupportable block size %ju\n",
2651                             (uintmax_t) block_len);
2652                         error = EINVAL;
2653                 } else {
2654                         dasetgeom(periph, block_len, maxsector,
2655                             lbppbe, lalba & SRC16_LALBA);
2656                         if ((lalba & SRC16_LBPME) &&
2657                             softc->delete_method == DA_DELETE_NONE)
2658                                 softc->delete_method = DA_DELETE_UNMAP;
2659                 }
2660         }
2661
2662         xpt_release_ccb(ccb);
2663
2664         free(rcap, M_SCSIDA);
2665
2666         return (error);
2667 }
2668
2669 static void
2670 dasetgeom(struct cam_periph *periph, uint32_t block_len, uint64_t maxsector,
2671     u_int lbppbe, u_int lalba)
2672 {
2673         struct ccb_calc_geometry ccg;
2674         struct da_softc *softc;
2675         struct disk_params *dp;
2676
2677         softc = (struct da_softc *)periph->softc;
2678
2679         dp = &softc->params;
2680         dp->secsize = block_len;
2681         dp->sectors = maxsector + 1;
2682         if (lbppbe > 0) {
2683                 dp->stripesize = block_len << lbppbe;
2684                 dp->stripeoffset = (dp->stripesize - block_len * lalba) %
2685                     dp->stripesize;
2686         } else if (softc->quirks & DA_Q_4K) {
2687                 dp->stripesize = 4096;
2688                 dp->stripeoffset = 0;
2689         } else {
2690                 dp->stripesize = 0;
2691                 dp->stripeoffset = 0;
2692         }
2693         /*
2694          * Have the controller provide us with a geometry
2695          * for this disk.  The only time the geometry
2696          * matters is when we boot and the controller
2697          * is the only one knowledgeable enough to come
2698          * up with something that will make this a bootable
2699          * device.
2700          */
2701         xpt_setup_ccb(&ccg.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
2702         ccg.ccb_h.func_code = XPT_CALC_GEOMETRY;
2703         ccg.block_size = dp->secsize;
2704         ccg.volume_size = dp->sectors;
2705         ccg.heads = 0;
2706         ccg.secs_per_track = 0;
2707         ccg.cylinders = 0;
2708         xpt_action((union ccb*)&ccg);
2709         if ((ccg.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2710                 /*
2711                  * We don't know what went wrong here- but just pick
2712                  * a geometry so we don't have nasty things like divide
2713                  * by zero.
2714                  */
2715                 dp->heads = 255;
2716                 dp->secs_per_track = 255;
2717                 dp->cylinders = dp->sectors / (255 * 255);
2718                 if (dp->cylinders == 0) {
2719                         dp->cylinders = 1;
2720                 }
2721         } else {
2722                 dp->heads = ccg.heads;
2723                 dp->secs_per_track = ccg.secs_per_track;
2724                 dp->cylinders = ccg.cylinders;
2725         }
2726 }
2727
2728 static void
2729 dasendorderedtag(void *arg)
2730 {
2731         struct da_softc *softc = arg;
2732
2733         if (da_send_ordered) {
2734                 if ((softc->ordered_tag_count == 0) 
2735                  && ((softc->flags & DA_FLAG_WENT_IDLE) == 0)) {
2736                         softc->flags |= DA_FLAG_NEED_OTAG;
2737                 }
2738                 if (softc->outstanding_cmds > 0)
2739                         softc->flags &= ~DA_FLAG_WENT_IDLE;
2740
2741                 softc->ordered_tag_count = 0;
2742         }
2743         /* Queue us up again */
2744         callout_reset(&softc->sendordered_c,
2745             (da_default_timeout * hz) / DA_ORDEREDTAG_INTERVAL,
2746             dasendorderedtag, softc);
2747 }
2748
2749 /*
2750  * Step through all DA peripheral drivers, and if the device is still open,
2751  * sync the disk cache to physical media.
2752  */
2753 static void
2754 dashutdown(void * arg, int howto)
2755 {
2756         struct cam_periph *periph;
2757         struct da_softc *softc;
2758         int error;
2759
2760         TAILQ_FOREACH(periph, &dadriver.units, unit_links) {
2761                 union ccb ccb;
2762
2763                 cam_periph_lock(periph);
2764                 softc = (struct da_softc *)periph->softc;
2765
2766                 /*
2767                  * We only sync the cache if the drive is still open, and
2768                  * if the drive is capable of it..
2769                  */
2770                 if (((softc->flags & DA_FLAG_OPEN) == 0)
2771                  || (softc->quirks & DA_Q_NO_SYNC_CACHE)) {
2772                         cam_periph_unlock(periph);
2773                         continue;
2774                 }
2775
2776                 xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
2777
2778                 ccb.ccb_h.ccb_state = DA_CCB_DUMP;
2779                 scsi_synchronize_cache(&ccb.csio,
2780                                        /*retries*/0,
2781                                        /*cbfcnp*/dadone,
2782                                        MSG_SIMPLE_Q_TAG,
2783                                        /*begin_lba*/0, /* whole disk */
2784                                        /*lb_count*/0,
2785                                        SSD_FULL_SIZE,
2786                                        60 * 60 * 1000);
2787
2788                 xpt_polled_action(&ccb);
2789
2790                 error = cam_periph_error(&ccb,
2791                     0, SF_NO_RECOVERY | SF_NO_RETRY | SF_QUIET_IR, NULL);
2792                 if ((ccb.ccb_h.status & CAM_DEV_QFRZN) != 0)
2793                         cam_release_devq(ccb.ccb_h.path, /*relsim_flags*/0,
2794                             /*reduction*/0, /*timeout*/0, /*getcount_only*/0);
2795                 if (error != 0)
2796                         xpt_print(periph->path, "Synchronize cache failed\n");
2797                 cam_periph_unlock(periph);
2798         }
2799 }
2800
2801 #else /* !_KERNEL */
2802
2803 /*
2804  * XXX This is only left out of the kernel build to silence warnings.  If,
2805  * for some reason this function is used in the kernel, the ifdefs should
2806  * be moved so it is included both in the kernel and userland.
2807  */
2808 void
2809 scsi_format_unit(struct ccb_scsiio *csio, u_int32_t retries,
2810                  void (*cbfcnp)(struct cam_periph *, union ccb *),
2811                  u_int8_t tag_action, u_int8_t byte2, u_int16_t ileave,
2812                  u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
2813                  u_int32_t timeout)
2814 {
2815         struct scsi_format_unit *scsi_cmd;
2816
2817         scsi_cmd = (struct scsi_format_unit *)&csio->cdb_io.cdb_bytes;
2818         scsi_cmd->opcode = FORMAT_UNIT;
2819         scsi_cmd->byte2 = byte2;
2820         scsi_ulto2b(ileave, scsi_cmd->interleave);
2821
2822         cam_fill_csio(csio,
2823                       retries,
2824                       cbfcnp,
2825                       /*flags*/ (dxfer_len > 0) ? CAM_DIR_OUT : CAM_DIR_NONE,
2826                       tag_action,
2827                       data_ptr,
2828                       dxfer_len,
2829                       sense_len,
2830                       sizeof(*scsi_cmd),
2831                       timeout);
2832 }
2833
2834 #endif /* _KERNEL */