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