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