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