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