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