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