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