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