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