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