]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cam/scsi/scsi_da.c
Last commit was broken.. It always prints '[CTRL-C to abort]'.
[FreeBSD/FreeBSD.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  * $FreeBSD$
29  */
30
31 #ifdef _KERNEL
32 #include "opt_hw_wdog.h"
33 #endif /* _KERNEL */
34
35 #include <sys/param.h>
36
37 #ifdef _KERNEL
38 #include <sys/systm.h>
39 #include <sys/kernel.h>
40 #include <sys/bio.h>
41 #endif /* _KERNEL */
42
43 #include <sys/devicestat.h>
44 #include <sys/conf.h>
45 #include <sys/disk.h>
46 #include <sys/eventhandler.h>
47 #include <sys/malloc.h>
48 #include <sys/cons.h>
49
50 #include <machine/md_var.h>
51
52 #include <vm/vm.h>
53 #include <vm/pmap.h>
54
55 #ifndef _KERNEL
56 #include <stdio.h>
57 #include <string.h>
58 #endif /* _KERNEL */
59
60 #include <cam/cam.h>
61 #include <cam/cam_ccb.h>
62 #include <cam/cam_extend.h>
63 #include <cam/cam_periph.h>
64 #include <cam/cam_xpt_periph.h>
65
66 #include <cam/scsi/scsi_message.h>
67
68 #ifndef _KERNEL 
69 #include <cam/scsi/scsi_da.h>
70 #endif /* !_KERNEL */
71
72 #ifdef _KERNEL
73 typedef enum {
74         DA_STATE_PROBE,
75         DA_STATE_NORMAL
76 } da_state;
77
78 typedef enum {
79         DA_FLAG_PACK_INVALID    = 0x001,
80         DA_FLAG_NEW_PACK        = 0x002,
81         DA_FLAG_PACK_LOCKED     = 0x004,
82         DA_FLAG_PACK_REMOVABLE  = 0x008,
83         DA_FLAG_TAGGED_QUEUING  = 0x010,
84         DA_FLAG_NEED_OTAG       = 0x020,
85         DA_FLAG_WENT_IDLE       = 0x040,
86         DA_FLAG_RETRY_UA        = 0x080,
87         DA_FLAG_OPEN            = 0x100
88 } da_flags;
89
90 typedef enum {
91         DA_Q_NONE               = 0x00,
92         DA_Q_NO_SYNC_CACHE      = 0x01,
93         DA_Q_NO_6_BYTE          = 0x02
94 } da_quirks;
95
96 typedef enum {
97         DA_CCB_PROBE            = 0x01,
98         DA_CCB_BUFFER_IO        = 0x02,
99         DA_CCB_WAITING          = 0x03,
100         DA_CCB_DUMP             = 0x04,
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_int16_t cylinders;
112         u_int8_t  secs_per_track;
113         u_int32_t secsize;      /* Number of bytes/sector */
114         u_int32_t sectors;      /* total number sectors */
115 };
116
117 struct da_softc {
118         struct   bio_queue_head bio_queue;
119         struct   devstat device_stats;
120         SLIST_ENTRY(da_softc) links;
121         LIST_HEAD(, ccb_hdr) pending_ccbs;
122         da_state state;
123         da_flags flags; 
124         da_quirks quirks;
125         int      minimum_cmd_size;
126         int      ordered_tag_count;
127         struct   disk_params params;
128         struct   disk disk;
129         union    ccb saved_ccb;
130         dev_t    dev;
131 };
132
133 struct da_quirk_entry {
134         struct scsi_inquiry_pattern inq_pat;
135         da_quirks quirks;
136 };
137
138 static const char quantum[] = "QUANTUM";
139 static const char microp[] = "MICROP";
140
141 static struct da_quirk_entry da_quirk_table[] =
142 {
143         {
144                 /*
145                  * This particular Fujitsu drive doesn't like the
146                  * synchronize cache command.
147                  * Reported by: Tom Jackson <toj@gorilla.net>
148                  */
149                 {T_DIRECT, SIP_MEDIA_FIXED, "FUJITSU", "M2954*", "*"},
150                 /*quirks*/ DA_Q_NO_SYNC_CACHE
151         
152         },
153         {
154                 /*
155                  * This drive doesn't like the synchronize cache command
156                  * either.  Reported by: Matthew Jacob <mjacob@feral.com>
157                  * in NetBSD PR kern/6027, August 24, 1998.
158                  */
159                 {T_DIRECT, SIP_MEDIA_FIXED, microp, "2217*", "*"},
160                 /*quirks*/ DA_Q_NO_SYNC_CACHE
161         },
162         {
163                 /*
164                  * This drive doesn't like the synchronize cache command
165                  * either.  Reported by: Hellmuth Michaelis (hm@kts.org)
166                  * (PR 8882).
167                  */
168                 {T_DIRECT, SIP_MEDIA_FIXED, microp, "2112*", "*"},
169                 /*quirks*/ DA_Q_NO_SYNC_CACHE
170         },
171         {
172                 /*
173                  * Doesn't like the synchronize cache command.
174                  * Reported by: Blaz Zupan <blaz@gold.amis.net>
175                  */
176                 {T_DIRECT, SIP_MEDIA_FIXED, "NEC", "D3847*", "*"},
177                 /*quirks*/ DA_Q_NO_SYNC_CACHE
178         },
179         {
180                 /*
181                  * Doesn't like the synchronize cache command.
182                  */
183                 {T_DIRECT, SIP_MEDIA_FIXED, quantum, "MAVERICK 540S", "*"},
184                 /*quirks*/ DA_Q_NO_SYNC_CACHE
185         },
186         {
187                 /*
188                  * Doesn't like the synchronize cache command.
189                  */
190                 {T_DIRECT, SIP_MEDIA_FIXED, quantum, "LPS525S", "*"},
191                 /*quirks*/ DA_Q_NO_SYNC_CACHE
192         },
193         {
194                 /*
195                  * Doesn't work correctly with 6 byte reads/writes.
196                  * Returns illegal request, and points to byte 9 of the
197                  * 6-byte CDB.
198                  * Reported by:  Adam McDougall <bsdx@spawnet.com>
199                  */
200                 {T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 4*", "*"},
201                 /*quirks*/ DA_Q_NO_6_BYTE
202         },
203         {
204                 /*
205                  * See above.
206                  */
207                 {T_DIRECT, SIP_MEDIA_FIXED, quantum, "VIKING 2*", "*"},
208                 /*quirks*/ DA_Q_NO_6_BYTE
209         },
210
211         /* Below a list of quirks for USB devices supported by umass. */
212         {
213                 /*
214                  * This USB floppy drive uses the UFI command set. This
215                  * command set is a derivative of the ATAPI command set and
216                  * does not support READ_6 commands only READ_10. It also does
217                  * not support sync cache (0x35).
218                  */
219                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Y-E DATA", "USB-FDU", "*"},
220                 /*quirks*/ DA_Q_NO_6_BYTE|DA_Q_NO_SYNC_CACHE
221         },
222         {
223                 /* Another USB floppy */
224                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "MATSHITA", "FDD CF-VFDU*","*"},
225                 /*quirks*/ DA_Q_NO_6_BYTE|DA_Q_NO_SYNC_CACHE
226         },
227         {
228                 /*
229                  * Sony Memory Stick adapter MSAC-US1,
230                  * does not support READ_6 commands only READ_10. It also does
231                  * not support sync cache (0x35).
232                  * Sony PCG-C1VJ Internal Memory Stick Slot (MSC-U01) also
233                  * has this quirk.  Make all sony MS* products use this
234                  * quirk.  Reported by: TERAMOTO Masahiro
235                  * <teramoto@comm.eng.osaka-u.ac.jp> (PR 23378).
236                  */
237                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Sony", "MS*", "*"},
238                 /*quirks*/ DA_Q_NO_6_BYTE|DA_Q_NO_SYNC_CACHE
239         },
240         {
241                 /*
242                  * Sony DSC cameras (DSC-S30, DSC-S50, DSC-S70)
243                  * do not support READ_6 commands, only READ_10. 
244                  */
245                 {T_DIRECT, SIP_MEDIA_REMOVABLE, "Sony", "Sony DSC", "*"},
246                 /*quirks*/ DA_Q_NO_6_BYTE|DA_Q_NO_SYNC_CACHE
247         },
248         {
249                 {T_OPTICAL, SIP_MEDIA_REMOVABLE, "FUJITSU", "MCF3064AP", "*"},
250                 /*quirks*/ DA_Q_NO_6_BYTE
251         }
252 };
253
254 static  d_open_t        daopen;
255 static  d_close_t       daclose;
256 static  d_strategy_t    dastrategy;
257 static  d_ioctl_t       daioctl;
258 static  d_dump_t        dadump;
259 static  periph_init_t   dainit;
260 static  void            daasync(void *callback_arg, u_int32_t code,
261                                 struct cam_path *path, void *arg);
262 static  periph_ctor_t   daregister;
263 static  periph_dtor_t   dacleanup;
264 static  periph_start_t  dastart;
265 static  periph_oninv_t  daoninvalidate;
266 static  void            dadone(struct cam_periph *periph,
267                                union ccb *done_ccb);
268 static  int             daerror(union ccb *ccb, u_int32_t cam_flags,
269                                 u_int32_t sense_flags);
270 static void             daprevent(struct cam_periph *periph, int action);
271 static void             dasetgeom(struct cam_periph *periph,
272                                   struct scsi_read_capacity_data * rdcap);
273 static timeout_t        dasendorderedtag;
274 static void             dashutdown(void *arg, int howto);
275
276 #ifndef DA_DEFAULT_TIMEOUT
277 #define DA_DEFAULT_TIMEOUT 60   /* Timeout in seconds */
278 #endif
279
280 /*
281  * DA_ORDEREDTAG_INTERVAL determines how often, relative
282  * to the default timeout, we check to see whether an ordered
283  * tagged transaction is appropriate to prevent simple tag
284  * starvation.  Since we'd like to ensure that there is at least
285  * 1/2 of the timeout length left for a starved transaction to
286  * complete after we've sent an ordered tag, we must poll at least
287  * four times in every timeout period.  This takes care of the worst
288  * case where a starved transaction starts during an interval that
289  * meets the requirement "don't send an ordered tag" test so it takes
290  * us two intervals to determine that a tag must be sent.
291  */
292 #ifndef DA_ORDEREDTAG_INTERVAL
293 #define DA_ORDEREDTAG_INTERVAL 4
294 #endif
295
296 static struct periph_driver dadriver =
297 {
298         dainit, "da",
299         TAILQ_HEAD_INITIALIZER(dadriver.units), /* generation */ 0
300 };
301
302 PERIPHDRIVER_DECLARE(da, dadriver);
303
304 #define DA_CDEV_MAJOR 13
305
306 /* For 2.2-stable support */
307 #ifndef D_DISK
308 #define D_DISK 0
309 #endif
310
311 static struct cdevsw da_cdevsw = {
312         /* open */      daopen,
313         /* close */     daclose,
314         /* read */      physread,
315         /* write */     physwrite,
316         /* ioctl */     daioctl,
317         /* poll */      nopoll,
318         /* mmap */      nommap,
319         /* strategy */  dastrategy,
320         /* name */      "da",
321         /* maj */       DA_CDEV_MAJOR,
322         /* dump */      dadump,
323         /* psize */     nopsize,
324         /* flags */     D_DISK,
325 };
326
327 static struct cdevsw dadisk_cdevsw;
328
329 static SLIST_HEAD(,da_softc) softc_list;
330 static struct extend_array *daperiphs;
331
332 static int
333 daopen(dev_t dev, int flags, int fmt, struct proc *p)
334 {
335         struct cam_periph *periph;
336         struct da_softc *softc;
337         struct disklabel *label;        
338         struct scsi_read_capacity_data *rcap;
339         union  ccb *ccb;
340         int unit;
341         int part;
342         int error;
343         int s;
344
345         unit = dkunit(dev);
346         part = dkpart(dev);
347         s = splsoftcam();
348         periph = cam_extend_get(daperiphs, unit);
349         if (periph == NULL) {
350                 splx(s);
351                 return (ENXIO); 
352         }
353
354         softc = (struct da_softc *)periph->softc;
355
356         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
357             ("daopen: dev=%s (unit %d , partition %d)\n", devtoname(dev),
358              unit, part));
359
360         if ((error = cam_periph_lock(periph, PRIBIO|PCATCH)) != 0)
361                 return (error); /* error code from tsleep */
362
363         if (cam_periph_acquire(periph) != CAM_REQ_CMP)
364                 return(ENXIO);
365         softc->flags |= DA_FLAG_OPEN;
366
367         if ((softc->flags & DA_FLAG_PACK_INVALID) != 0) {
368                 /* Invalidate our pack information. */
369                 disk_invalidate(&softc->disk);
370                 softc->flags &= ~DA_FLAG_PACK_INVALID;
371         }
372         splx(s);
373
374         /* Do a read capacity */
375         rcap = (struct scsi_read_capacity_data *)malloc(sizeof(*rcap),
376                                                         M_TEMP,
377                                                         M_WAITOK);
378                 
379         ccb = cam_periph_getccb(periph, /*priority*/1);
380         scsi_read_capacity(&ccb->csio,
381                            /*retries*/4,
382                            /*cbfncp*/dadone,
383                            MSG_SIMPLE_Q_TAG,
384                            rcap,
385                            SSD_FULL_SIZE,
386                            /*timeout*/60000);
387         ccb->ccb_h.ccb_bp = NULL;
388
389         error = cam_periph_runccb(ccb, daerror,
390                                   /*cam_flags*/CAM_RETRY_SELTO,
391                                   /*sense_flags*/SF_RETRY_UA,
392                                   &softc->device_stats);
393
394         if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
395                 cam_release_devq(ccb->ccb_h.path,
396                                  /*relsim_flags*/0,
397                                  /*reduction*/0,
398                                  /*timeout*/0,
399                                  /*getcount_only*/0);
400         xpt_release_ccb(ccb);
401
402         if (error == 0)
403                 dasetgeom(periph, rcap);
404
405         free(rcap, M_TEMP);
406
407         if (error == 0) {
408                 struct ccb_getdev cgd;
409
410                 /* Build label for whole disk. */
411                 label = &softc->disk.d_label;
412                 bzero(label, sizeof(*label));
413                 label->d_type = DTYPE_SCSI;
414
415                 /*
416                  * Grab the inquiry data to get the vendor and product names.
417                  * Put them in the typename and packname for the label.
418                  */
419                 xpt_setup_ccb(&cgd.ccb_h, periph->path, /*priority*/ 1);
420                 cgd.ccb_h.func_code = XPT_GDEV_TYPE;
421                 xpt_action((union ccb *)&cgd);
422
423                 strncpy(label->d_typename, cgd.inq_data.vendor,
424                         min(SID_VENDOR_SIZE, sizeof(label->d_typename)));
425                 strncpy(label->d_packname, cgd.inq_data.product,
426                         min(SID_PRODUCT_SIZE, sizeof(label->d_packname)));
427                 
428                 label->d_secsize = softc->params.secsize;
429                 label->d_nsectors = softc->params.secs_per_track;
430                 label->d_ntracks = softc->params.heads;
431                 label->d_ncylinders = softc->params.cylinders;
432                 label->d_secpercyl = softc->params.heads
433                                   * softc->params.secs_per_track;
434                 label->d_secperunit = softc->params.sectors;
435
436                 /*
437                  * Check to see whether or not the blocksize is set yet.
438                  * If it isn't, set it and then clear the blocksize
439                  * unavailable flag for the device statistics.
440                  */
441                 if ((softc->device_stats.flags & DEVSTAT_BS_UNAVAILABLE) != 0){
442                         softc->device_stats.block_size = softc->params.secsize;
443                         softc->device_stats.flags &= ~DEVSTAT_BS_UNAVAILABLE;
444                 }
445         }
446         
447         if (error == 0) {
448                 if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0)
449                         daprevent(periph, PR_PREVENT);
450         }
451         cam_periph_unlock(periph);
452         return (error);
453 }
454
455 static int
456 daclose(dev_t dev, int flag, int fmt, struct proc *p)
457 {
458         struct  cam_periph *periph;
459         struct  da_softc *softc;
460         int     unit;
461         int     error;
462
463         unit = dkunit(dev);
464         periph = cam_extend_get(daperiphs, unit);
465         if (periph == NULL)
466                 return (ENXIO); 
467
468         softc = (struct da_softc *)periph->softc;
469
470         if ((error = cam_periph_lock(periph, PRIBIO)) != 0) {
471                 return (error); /* error code from tsleep */
472         }
473
474         if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
475                 union   ccb *ccb;
476
477                 ccb = cam_periph_getccb(periph, /*priority*/1);
478
479                 scsi_synchronize_cache(&ccb->csio,
480                                        /*retries*/1,
481                                        /*cbfcnp*/dadone,
482                                        MSG_SIMPLE_Q_TAG,
483                                        /*begin_lba*/0,/* Cover the whole disk */
484                                        /*lb_count*/0,
485                                        SSD_FULL_SIZE,
486                                        5 * 60 * 1000);
487
488                 cam_periph_runccb(ccb, /*error_routine*/NULL, /*cam_flags*/0,
489                                   /*sense_flags*/SF_RETRY_UA,
490                                   &softc->device_stats);
491
492                 if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
493                         if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
494                              CAM_SCSI_STATUS_ERROR) {
495                                 int asc, ascq;
496                                 int sense_key, error_code;
497
498                                 scsi_extract_sense(&ccb->csio.sense_data,
499                                                    &error_code,
500                                                    &sense_key, 
501                                                    &asc, &ascq);
502                                 if (sense_key != SSD_KEY_ILLEGAL_REQUEST)
503                                         scsi_sense_print(&ccb->csio);
504                         } else {
505                                 xpt_print_path(periph->path);
506                                 printf("Synchronize cache failed, status "
507                                        "== 0x%x, scsi status == 0x%x\n",
508                                        ccb->csio.ccb_h.status,
509                                        ccb->csio.scsi_status);
510                         }
511                 }
512
513                 if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
514                         cam_release_devq(ccb->ccb_h.path,
515                                          /*relsim_flags*/0,
516                                          /*reduction*/0,
517                                          /*timeout*/0,
518                                          /*getcount_only*/0);
519
520                 xpt_release_ccb(ccb);
521
522         }
523
524         if ((softc->flags & DA_FLAG_PACK_REMOVABLE) != 0) {
525                 daprevent(periph, PR_ALLOW);
526                 /*
527                  * If we've got removeable media, mark the blocksize as
528                  * unavailable, since it could change when new media is
529                  * inserted.
530                  */
531                 softc->device_stats.flags |= DEVSTAT_BS_UNAVAILABLE;
532         }
533
534         softc->flags &= ~DA_FLAG_OPEN;
535         cam_periph_unlock(periph);
536         cam_periph_release(periph);
537         return (0);     
538 }
539
540 /*
541  * Actually translate the requested transfer into one the physical driver
542  * can understand.  The transfer is described by a buf and will include
543  * only one physical transfer.
544  */
545 static void
546 dastrategy(struct bio *bp)
547 {
548         struct cam_periph *periph;
549         struct da_softc *softc;
550         u_int  unit;
551         u_int  part;
552         int    s;
553         
554         unit = dkunit(bp->bio_dev);
555         part = dkpart(bp->bio_dev);
556         periph = cam_extend_get(daperiphs, unit);
557         if (periph == NULL) {
558                 bp->bio_error = ENXIO;
559                 goto bad;               
560         }
561         softc = (struct da_softc *)periph->softc;
562 #if 0
563         /*
564          * check it's not too big a transfer for our adapter
565          */
566         scsi_minphys(bp,&sd_switch);
567 #endif
568
569         /*
570          * Mask interrupts so that the pack cannot be invalidated until
571          * after we are in the queue.  Otherwise, we might not properly
572          * clean up one of the buffers.
573          */
574         s = splbio();
575         
576         /*
577          * If the device has been made invalid, error out
578          */
579         if ((softc->flags & DA_FLAG_PACK_INVALID)) {
580                 splx(s);
581                 bp->bio_error = ENXIO;
582                 goto bad;
583         }
584         
585         /*
586          * Place it in the queue of disk activities for this disk
587          */
588         bioqdisksort(&softc->bio_queue, bp);
589
590         splx(s);
591         
592         /*
593          * Schedule ourselves for performing the work.
594          */
595         xpt_schedule(periph, /* XXX priority */1);
596
597         return;
598 bad:
599         bp->bio_flags |= BIO_ERROR;
600
601         /*
602          * Correctly set the buf to indicate a completed xfer
603          */
604         bp->bio_resid = bp->bio_bcount;
605         biodone(bp);
606         return;
607 }
608
609 /* For 2.2-stable support */
610 #ifndef ENOIOCTL
611 #define ENOIOCTL -1
612 #endif
613
614 static int
615 daioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p)
616 {
617         struct cam_periph *periph;
618         struct da_softc *softc;
619         int unit;
620         int error;
621
622         unit = dkunit(dev);
623         periph = cam_extend_get(daperiphs, unit);
624         if (periph == NULL)
625                 return (ENXIO); 
626
627         softc = (struct da_softc *)periph->softc;
628
629         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("daioctl\n"));
630
631         if ((error = cam_periph_lock(periph, PRIBIO|PCATCH)) != 0) {
632                 return (error); /* error code from tsleep */
633         }       
634
635         error = cam_periph_ioctl(periph, cmd, addr, daerror);
636
637         cam_periph_unlock(periph);
638         
639         return (error);
640 }
641
642 static int
643 dadump(dev_t dev)
644 {
645         struct      cam_periph *periph;
646         struct      da_softc *softc;
647         u_int       unit;
648         u_int       part;
649         u_int       secsize;
650         u_int       num;        /* number of sectors to write */
651         u_int       blknum;
652         long        blkcnt;
653         vm_offset_t addr;       
654         struct      ccb_scsiio csio;
655         int         dumppages = MAXDUMPPGS;
656         int         error;
657         int         i;
658
659         /* toss any characters present prior to dump */
660         while (cncheckc() != -1)
661                 ;
662
663         unit = dkunit(dev);
664         part = dkpart(dev);
665         periph = cam_extend_get(daperiphs, unit);
666         if (periph == NULL) {
667                 return (ENXIO);
668         }
669         softc = (struct da_softc *)periph->softc;
670         
671         if ((softc->flags & DA_FLAG_PACK_INVALID) != 0)
672                 return (ENXIO);
673
674         error = disk_dumpcheck(dev, &num, &blknum, &secsize);
675         if (error)
676                 return (error);
677
678         addr = 0;       /* starting address */
679         blkcnt = howmany(PAGE_SIZE, secsize);
680
681         while (num > 0) {
682                 caddr_t va = NULL;
683
684                 if ((num / blkcnt) < dumppages)
685                         dumppages = num / blkcnt;
686
687                 for (i = 0; i < dumppages; ++i) {
688                         vm_offset_t a = addr + (i * PAGE_SIZE);
689                         if (is_physical_memory(a))
690                                 va = pmap_kenter_temporary(trunc_page(a), i);
691                         else
692                                 va = pmap_kenter_temporary(trunc_page(0), i);
693                 }
694
695                 xpt_setup_ccb(&csio.ccb_h, periph->path, /*priority*/1);
696                 csio.ccb_h.ccb_state = DA_CCB_DUMP;
697                 scsi_read_write(&csio,
698                                 /*retries*/1,
699                                 dadone,
700                                 MSG_ORDERED_Q_TAG,
701                                 /*read*/FALSE,
702                                 /*byte2*/0,
703                                 /*minimum_cmd_size*/ softc->minimum_cmd_size,
704                                 blknum,
705                                 blkcnt * dumppages,
706                                 /*data_ptr*/(u_int8_t *) va,
707                                 /*dxfer_len*/blkcnt * secsize * dumppages,
708                                 /*sense_len*/SSD_FULL_SIZE,
709                                 DA_DEFAULT_TIMEOUT * 1000);             
710                 xpt_polled_action((union ccb *)&csio);
711
712                 if ((csio.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
713                         printf("Aborting dump due to I/O error.\n");
714                         if ((csio.ccb_h.status & CAM_STATUS_MASK) ==
715                              CAM_SCSI_STATUS_ERROR)
716                                 scsi_sense_print(&csio);
717                         else
718                                 printf("status == 0x%x, scsi status == 0x%x\n",
719                                        csio.ccb_h.status, csio.scsi_status);
720                         return(EIO);
721                 }
722                 
723                 if (dumpstatus(addr, (long)(num * softc->params.secsize)) < 0)
724                         return (EINTR);
725
726                 /* update block count */
727                 num -= blkcnt * dumppages;
728                 blknum += blkcnt * dumppages;
729                 addr += PAGE_SIZE * dumppages;
730         }
731
732         /*
733          * Sync the disk cache contents to the physical media.
734          */
735         if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) {
736
737                 xpt_setup_ccb(&csio.ccb_h, periph->path, /*priority*/1);
738                 csio.ccb_h.ccb_state = DA_CCB_DUMP;
739                 scsi_synchronize_cache(&csio,
740                                        /*retries*/1,
741                                        /*cbfcnp*/dadone,
742                                        MSG_SIMPLE_Q_TAG,
743                                        /*begin_lba*/0,/* Cover the whole disk */
744                                        /*lb_count*/0,
745                                        SSD_FULL_SIZE,
746                                        5 * 60 * 1000);
747                 xpt_polled_action((union ccb *)&csio);
748
749                 if ((csio.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
750                         if ((csio.ccb_h.status & CAM_STATUS_MASK) ==
751                              CAM_SCSI_STATUS_ERROR) {
752                                 int asc, ascq;
753                                 int sense_key, error_code;
754
755                                 scsi_extract_sense(&csio.sense_data,
756                                                    &error_code,
757                                                    &sense_key, 
758                                                    &asc, &ascq);
759                                 if (sense_key != SSD_KEY_ILLEGAL_REQUEST)
760                                         scsi_sense_print(&csio);
761                         } else {
762                                 xpt_print_path(periph->path);
763                                 printf("Synchronize cache failed, status "
764                                        "== 0x%x, scsi status == 0x%x\n",
765                                        csio.ccb_h.status, csio.scsi_status);
766                         }
767                 }
768         }
769         return (0);
770 }
771
772 static void
773 dainit(void)
774 {
775         cam_status status;
776         struct cam_path *path;
777
778         /*
779          * Create our extend array for storing the devices we attach to.
780          */
781         daperiphs = cam_extend_new();
782         SLIST_INIT(&softc_list);
783         if (daperiphs == NULL) {
784                 printf("da: Failed to alloc extend array!\n");
785                 return;
786         }
787         
788         /*
789          * Install a global async callback.  This callback will
790          * receive async callbacks like "new device found".
791          */
792         status = xpt_create_path(&path, /*periph*/NULL, CAM_XPT_PATH_ID,
793                                  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
794
795         if (status == CAM_REQ_CMP) {
796                 struct ccb_setasync csa;
797
798                 xpt_setup_ccb(&csa.ccb_h, path, /*priority*/5);
799                 csa.ccb_h.func_code = XPT_SASYNC_CB;
800                 csa.event_enable = AC_FOUND_DEVICE;
801                 csa.callback = daasync;
802                 csa.callback_arg = NULL;
803                 xpt_action((union ccb *)&csa);
804                 status = csa.ccb_h.status;
805                 xpt_free_path(path);
806         }
807
808         if (status != CAM_REQ_CMP) {
809                 printf("da: Failed to attach master async callback "
810                        "due to status 0x%x!\n", status);
811         } else {
812
813                 /*
814                  * Schedule a periodic event to occasioanly send an
815                  * ordered tag to a device.
816                  */
817                 timeout(dasendorderedtag, NULL,
818                         (DA_DEFAULT_TIMEOUT * hz) / DA_ORDEREDTAG_INTERVAL);
819
820                 /* Register our shutdown event handler */
821                 if ((EVENTHANDLER_REGISTER(shutdown_post_sync, dashutdown, 
822                                            NULL, SHUTDOWN_PRI_DEFAULT)) == NULL)
823                     printf("dainit: shutdown event registration failed!\n");
824         }
825 }
826
827 static void
828 daoninvalidate(struct cam_periph *periph)
829 {
830         int s;
831         struct da_softc *softc;
832         struct bio *q_bp;
833         struct ccb_setasync csa;
834
835         softc = (struct da_softc *)periph->softc;
836
837         /*
838          * De-register any async callbacks.
839          */
840         xpt_setup_ccb(&csa.ccb_h, periph->path,
841                       /* priority */ 5);
842         csa.ccb_h.func_code = XPT_SASYNC_CB;
843         csa.event_enable = 0;
844         csa.callback = daasync;
845         csa.callback_arg = periph;
846         xpt_action((union ccb *)&csa);
847
848         softc->flags |= DA_FLAG_PACK_INVALID;
849
850         /*
851          * Although the oninvalidate() routines are always called at
852          * splsoftcam, we need to be at splbio() here to keep the buffer
853          * queue from being modified while we traverse it.
854          */
855         s = splbio();
856
857         /*
858          * Return all queued I/O with ENXIO.
859          * XXX Handle any transactions queued to the card
860          *     with XPT_ABORT_CCB.
861          */
862         while ((q_bp = bioq_first(&softc->bio_queue)) != NULL){
863                 bioq_remove(&softc->bio_queue, q_bp);
864                 q_bp->bio_resid = q_bp->bio_bcount;
865                 q_bp->bio_error = ENXIO;
866                 q_bp->bio_flags |= BIO_ERROR;
867                 biodone(q_bp);
868         }
869         splx(s);
870
871         SLIST_REMOVE(&softc_list, softc, da_softc, links);
872
873         xpt_print_path(periph->path);
874         printf("lost device\n");
875 }
876
877 static void
878 dacleanup(struct cam_periph *periph)
879 {
880         struct da_softc *softc;
881
882         softc = (struct da_softc *)periph->softc;
883
884         devstat_remove_entry(&softc->device_stats);
885         cam_extend_release(daperiphs, periph->unit_number);
886         xpt_print_path(periph->path);
887         printf("removing device entry\n");
888         if (softc->dev) {
889                 disk_destroy(softc->dev);
890         }
891         free(softc, M_DEVBUF);
892 }
893
894 static void
895 daasync(void *callback_arg, u_int32_t code,
896         struct cam_path *path, void *arg)
897 {
898         struct cam_periph *periph;
899
900         periph = (struct cam_periph *)callback_arg;
901         switch (code) {
902         case AC_FOUND_DEVICE:
903         {
904                 struct ccb_getdev *cgd;
905                 cam_status status;
906  
907                 cgd = (struct ccb_getdev *)arg;
908
909                 if (SID_TYPE(&cgd->inq_data) != T_DIRECT
910                     && SID_TYPE(&cgd->inq_data) != T_OPTICAL)
911                         break;
912
913                 /*
914                  * Allocate a peripheral instance for
915                  * this device and start the probe
916                  * process.
917                  */
918                 status = cam_periph_alloc(daregister, daoninvalidate,
919                                           dacleanup, dastart,
920                                           "da", CAM_PERIPH_BIO,
921                                           cgd->ccb_h.path, daasync,
922                                           AC_FOUND_DEVICE, cgd);
923
924                 if (status != CAM_REQ_CMP
925                  && status != CAM_REQ_INPROG)
926                         printf("daasync: Unable to attach to new device "
927                                 "due to status 0x%x\n", status);
928                 break;
929         }
930         case AC_SENT_BDR:
931         case AC_BUS_RESET:
932         {
933                 struct da_softc *softc;
934                 struct ccb_hdr *ccbh;
935                 int s;
936
937                 softc = (struct da_softc *)periph->softc;
938                 s = splsoftcam();
939                 /*
940                  * Don't fail on the expected unit attention
941                  * that will occur.
942                  */
943                 softc->flags |= DA_FLAG_RETRY_UA;
944                 LIST_FOREACH(ccbh, &softc->pending_ccbs, periph_links.le)
945                         ccbh->ccb_state |= DA_CCB_RETRY_UA;
946                 splx(s);
947                 /* FALLTHROUGH*/
948         }
949         default:
950                 cam_periph_async(periph, code, path, arg);
951                 break;
952         }
953 }
954
955 static cam_status
956 daregister(struct cam_periph *periph, void *arg)
957 {
958         int s;
959         struct da_softc *softc;
960         struct ccb_setasync csa;
961         struct ccb_getdev *cgd;
962         caddr_t match;
963
964         cgd = (struct ccb_getdev *)arg;
965         if (periph == NULL) {
966                 printf("daregister: periph was NULL!!\n");
967                 return(CAM_REQ_CMP_ERR);
968         }
969
970         if (cgd == NULL) {
971                 printf("daregister: no getdev CCB, can't register device\n");
972                 return(CAM_REQ_CMP_ERR);
973         }
974
975         softc = (struct da_softc *)malloc(sizeof(*softc),M_DEVBUF,M_NOWAIT);
976
977         if (softc == NULL) {
978                 printf("daregister: Unable to probe new device. "
979                        "Unable to allocate softc\n");                           
980                 return(CAM_REQ_CMP_ERR);
981         }
982
983         bzero(softc, sizeof(*softc));
984         LIST_INIT(&softc->pending_ccbs);
985         softc->state = DA_STATE_PROBE;
986         bioq_init(&softc->bio_queue);
987         if (SID_IS_REMOVABLE(&cgd->inq_data))
988                 softc->flags |= DA_FLAG_PACK_REMOVABLE;
989         if ((cgd->inq_data.flags & SID_CmdQue) != 0)
990                 softc->flags |= DA_FLAG_TAGGED_QUEUING;
991
992         periph->softc = softc;
993         
994         cam_extend_set(daperiphs, periph->unit_number, periph);
995
996         /*
997          * See if this device has any quirks.
998          */
999         match = cam_quirkmatch((caddr_t)&cgd->inq_data,
1000                                (caddr_t)da_quirk_table,
1001                                sizeof(da_quirk_table)/sizeof(*da_quirk_table),
1002                                sizeof(*da_quirk_table), scsi_inquiry_match);
1003
1004         if (match != NULL)
1005                 softc->quirks = ((struct da_quirk_entry *)match)->quirks;
1006         else
1007                 softc->quirks = DA_Q_NONE;
1008
1009         if (softc->quirks & DA_Q_NO_6_BYTE)
1010                 softc->minimum_cmd_size = 10;
1011         else
1012                 softc->minimum_cmd_size = 6;
1013
1014         /*
1015          * Block our timeout handler while we
1016          * add this softc to the dev list.
1017          */
1018         s = splsoftclock();
1019         SLIST_INSERT_HEAD(&softc_list, softc, links);
1020         splx(s);
1021
1022         /*
1023          * The DA driver supports a blocksize, but
1024          * we don't know the blocksize until we do 
1025          * a read capacity.  So, set a flag to
1026          * indicate that the blocksize is 
1027          * unavailable right now.  We'll clear the
1028          * flag as soon as we've done a read capacity.
1029          */
1030         devstat_add_entry(&softc->device_stats, "da", 
1031                           periph->unit_number, 0,
1032                           DEVSTAT_BS_UNAVAILABLE,
1033                           SID_TYPE(&cgd->inq_data) | DEVSTAT_TYPE_IF_SCSI,
1034                           DEVSTAT_PRIORITY_DISK);
1035
1036         /*
1037          * Register this media as a disk
1038          */
1039         softc->dev = disk_create(periph->unit_number, &softc->disk, 0, 
1040             &da_cdevsw, &dadisk_cdevsw);
1041
1042         /*
1043          * Add async callbacks for bus reset and
1044          * bus device reset calls.  I don't bother
1045          * checking if this fails as, in most cases,
1046          * the system will function just fine without
1047          * them and the only alternative would be to
1048          * not attach the device on failure.
1049          */
1050         xpt_setup_ccb(&csa.ccb_h, periph->path, /*priority*/5);
1051         csa.ccb_h.func_code = XPT_SASYNC_CB;
1052         csa.event_enable = AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE;
1053         csa.callback = daasync;
1054         csa.callback_arg = periph;
1055         xpt_action((union ccb *)&csa);
1056         /*
1057          * Lock this peripheral until we are setup.
1058          * This first call can't block
1059          */
1060         (void)cam_periph_lock(periph, PRIBIO);
1061         xpt_schedule(periph, /*priority*/5);
1062
1063         return(CAM_REQ_CMP);
1064 }
1065
1066 static void
1067 dastart(struct cam_periph *periph, union ccb *start_ccb)
1068 {
1069         struct da_softc *softc;
1070
1071         softc = (struct da_softc *)periph->softc;
1072
1073         
1074         switch (softc->state) {
1075         case DA_STATE_NORMAL:
1076         {
1077                 /* Pull a buffer from the queue and get going on it */          
1078                 struct bio *bp;
1079                 int s;
1080
1081                 /*
1082                  * See if there is a buf with work for us to do..
1083                  */
1084                 s = splbio();
1085                 bp = bioq_first(&softc->bio_queue);
1086                 if (periph->immediate_priority <= periph->pinfo.priority) {
1087                         CAM_DEBUG_PRINT(CAM_DEBUG_SUBTRACE,
1088                                         ("queuing for immediate ccb\n"));
1089                         start_ccb->ccb_h.ccb_state = DA_CCB_WAITING;
1090                         SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
1091                                           periph_links.sle);
1092                         periph->immediate_priority = CAM_PRIORITY_NONE;
1093                         splx(s);
1094                         wakeup(&periph->ccb_list);
1095                 } else if (bp == NULL) {
1096                         splx(s);
1097                         xpt_release_ccb(start_ccb);
1098                 } else {
1099                         int oldspl;
1100                         u_int8_t tag_code;
1101
1102                         bioq_remove(&softc->bio_queue, bp);
1103
1104                         devstat_start_transaction(&softc->device_stats);
1105
1106                         if ((bp->bio_flags & BIO_ORDERED) != 0
1107                          || (softc->flags & DA_FLAG_NEED_OTAG) != 0) {
1108                                 softc->flags &= ~DA_FLAG_NEED_OTAG;
1109                                 softc->ordered_tag_count++;
1110                                 tag_code = MSG_ORDERED_Q_TAG;
1111                         } else {
1112                                 tag_code = MSG_SIMPLE_Q_TAG;
1113                         }
1114                         scsi_read_write(&start_ccb->csio,
1115                                         /*retries*/4,
1116                                         dadone,
1117                                         tag_code,
1118                                         bp->bio_cmd == BIO_READ,
1119                                         /*byte2*/0,
1120                                         softc->minimum_cmd_size,
1121                                         bp->bio_pblkno,
1122                                         bp->bio_bcount / softc->params.secsize,
1123                                         bp->bio_data,
1124                                         bp->bio_bcount,
1125                                         /*sense_len*/SSD_FULL_SIZE,
1126                                         DA_DEFAULT_TIMEOUT * 1000);
1127                         start_ccb->ccb_h.ccb_state = DA_CCB_BUFFER_IO;
1128
1129                         /*
1130                          * Block out any asyncronous callbacks
1131                          * while we touch the pending ccb list.
1132                          */
1133                         oldspl = splcam();
1134                         LIST_INSERT_HEAD(&softc->pending_ccbs,
1135                                          &start_ccb->ccb_h, periph_links.le);
1136                         splx(oldspl);
1137
1138                         /* We expect a unit attention from this device */
1139                         if ((softc->flags & DA_FLAG_RETRY_UA) != 0) {
1140                                 start_ccb->ccb_h.ccb_state |= DA_CCB_RETRY_UA;
1141                                 softc->flags &= ~DA_FLAG_RETRY_UA;
1142                         }
1143
1144                         start_ccb->ccb_h.ccb_bp = bp;
1145                         bp = bioq_first(&softc->bio_queue);
1146                         splx(s);
1147
1148                         xpt_action(start_ccb);
1149                 }
1150                 
1151                 if (bp != NULL) {
1152                         /* Have more work to do, so ensure we stay scheduled */
1153                         xpt_schedule(periph, /* XXX priority */1);
1154                 }
1155                 break;
1156         }
1157         case DA_STATE_PROBE:
1158         {
1159                 struct ccb_scsiio *csio;
1160                 struct scsi_read_capacity_data *rcap;
1161
1162                 rcap = (struct scsi_read_capacity_data *)malloc(sizeof(*rcap),
1163                                                                 M_TEMP,
1164                                                                 M_NOWAIT);
1165                 if (rcap == NULL) {
1166                         printf("dastart: Couldn't malloc read_capacity data\n");
1167                         /* da_free_periph??? */
1168                         break;
1169                 }
1170                 csio = &start_ccb->csio;
1171                 scsi_read_capacity(csio,
1172                                    /*retries*/4,
1173                                    dadone,
1174                                    MSG_SIMPLE_Q_TAG,
1175                                    rcap,
1176                                    SSD_FULL_SIZE,
1177                                    /*timeout*/5000);
1178                 start_ccb->ccb_h.ccb_bp = NULL;
1179                 start_ccb->ccb_h.ccb_state = DA_CCB_PROBE;
1180                 xpt_action(start_ccb);
1181                 break;
1182         }
1183         }
1184 }
1185
1186
1187 static void
1188 dadone(struct cam_periph *periph, union ccb *done_ccb)
1189 {
1190         struct da_softc *softc;
1191         struct ccb_scsiio *csio;
1192
1193         softc = (struct da_softc *)periph->softc;
1194         csio = &done_ccb->csio;
1195         switch (csio->ccb_h.ccb_state & DA_CCB_TYPE_MASK) {
1196         case DA_CCB_BUFFER_IO:
1197         {
1198                 struct bio *bp;
1199                 int    oldspl;
1200
1201                 bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
1202                 if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1203                         int error;
1204                         int s;
1205                         int sf;
1206                         
1207                         if ((csio->ccb_h.ccb_state & DA_CCB_RETRY_UA) != 0)
1208                                 sf = SF_RETRY_UA;
1209                         else
1210                                 sf = 0;
1211
1212                         error = daerror(done_ccb, CAM_RETRY_SELTO, sf);
1213                         if (error == ERESTART) {
1214                                 /*
1215                                  * A retry was scheuled, so
1216                                  * just return.
1217                                  */
1218                                 return;
1219                         }
1220                         if (error != 0) {
1221                                 struct bio *q_bp;
1222
1223                                 s = splbio();
1224
1225                                 if (error == ENXIO) {
1226                                         /*
1227                                          * Catastrophic error.  Mark our pack as
1228                                          * invalid.
1229                                          */
1230                                         /* XXX See if this is really a media
1231                                          *     change first.
1232                                          */
1233                                         xpt_print_path(periph->path);
1234                                         printf("Invalidating pack\n");
1235                                         softc->flags |= DA_FLAG_PACK_INVALID;
1236                                 }
1237
1238                                 /*
1239                                  * return all queued I/O with EIO, so that
1240                                  * the client can retry these I/Os in the
1241                                  * proper order should it attempt to recover.
1242                                  */
1243                                 while ((q_bp = bioq_first(&softc->bio_queue))
1244                                         != NULL) {
1245                                         bioq_remove(&softc->bio_queue, q_bp);
1246                                         q_bp->bio_resid = q_bp->bio_bcount;
1247                                         q_bp->bio_error = EIO;
1248                                         q_bp->bio_flags |= BIO_ERROR;
1249                                         biodone(q_bp);
1250                                 }
1251                                 splx(s);
1252                                 bp->bio_error = error;
1253                                 bp->bio_resid = bp->bio_bcount;
1254                                 bp->bio_flags |= BIO_ERROR;
1255                         } else {
1256                                 bp->bio_resid = csio->resid;
1257                                 bp->bio_error = 0;
1258                                 if (bp->bio_resid != 0) {
1259                                         /* Short transfer ??? */
1260                                         bp->bio_flags |= BIO_ERROR;
1261                                 }
1262                         }
1263                         if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1264                                 cam_release_devq(done_ccb->ccb_h.path,
1265                                                  /*relsim_flags*/0,
1266                                                  /*reduction*/0,
1267                                                  /*timeout*/0,
1268                                                  /*getcount_only*/0);
1269                 } else {
1270                         if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1271                                 panic("REQ_CMP with QFRZN");
1272                         bp->bio_resid = csio->resid;
1273                         if (csio->resid > 0)
1274                                 bp->bio_flags |= BIO_ERROR;
1275                 }
1276
1277                 /*
1278                  * Block out any asyncronous callbacks
1279                  * while we touch the pending ccb list.
1280                  */
1281                 oldspl = splcam();
1282                 LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
1283                 splx(oldspl);
1284
1285                 if (softc->device_stats.busy_count == 0)
1286                         softc->flags |= DA_FLAG_WENT_IDLE;
1287
1288                 devstat_end_transaction_bio(&softc->device_stats, bp);
1289                 biodone(bp);
1290                 break;
1291         }
1292         case DA_CCB_PROBE:
1293         {
1294                 struct     scsi_read_capacity_data *rdcap;
1295                 char       announce_buf[80];
1296
1297                 rdcap = (struct scsi_read_capacity_data *)csio->data_ptr;
1298                 
1299                 if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1300                         struct disk_params *dp;
1301
1302                         dasetgeom(periph, rdcap);
1303                         dp = &softc->params;
1304                         snprintf(announce_buf, sizeof(announce_buf),
1305                                 "%luMB (%u %u byte sectors: %dH %dS/T %dC)",
1306                                 (unsigned long) (((u_int64_t)dp->secsize *
1307                                 dp->sectors) / (1024*1024)), dp->sectors,
1308                                 dp->secsize, dp->heads, dp->secs_per_track,
1309                                 dp->cylinders);
1310                 } else {
1311                         int     error;
1312
1313                         announce_buf[0] = '\0';
1314
1315                         /*
1316                          * Retry any UNIT ATTENTION type errors.  They
1317                          * are expected at boot.
1318                          */
1319                         error = daerror(done_ccb, CAM_RETRY_SELTO,
1320                                         SF_RETRY_UA|SF_NO_PRINT);
1321                         if (error == ERESTART) {
1322                                 /*
1323                                  * A retry was scheuled, so
1324                                  * just return.
1325                                  */
1326                                 return;
1327                         } else if (error != 0) {
1328                                 struct scsi_sense_data *sense;
1329                                 int asc, ascq;
1330                                 int sense_key, error_code;
1331                                 int have_sense;
1332                                 cam_status status;
1333                                 struct ccb_getdev cgd;
1334
1335                                 /* Don't wedge this device's queue */
1336                                 status = done_ccb->ccb_h.status;
1337                                 if ((status & CAM_DEV_QFRZN) != 0)
1338                                         cam_release_devq(done_ccb->ccb_h.path,
1339                                                          /*relsim_flags*/0,
1340                                                          /*reduction*/0,
1341                                                          /*timeout*/0,
1342                                                          /*getcount_only*/0);
1343
1344
1345                                 xpt_setup_ccb(&cgd.ccb_h, 
1346                                               done_ccb->ccb_h.path,
1347                                               /* priority */ 1);
1348                                 cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1349                                 xpt_action((union ccb *)&cgd);
1350
1351                                 if (((csio->ccb_h.flags & CAM_SENSE_PHYS) != 0)
1352                                  || ((csio->ccb_h.flags & CAM_SENSE_PTR) != 0)
1353                                  || ((status & CAM_AUTOSNS_VALID) == 0))
1354                                         have_sense = FALSE;
1355                                 else
1356                                         have_sense = TRUE;
1357
1358                                 if (have_sense) {
1359                                         sense = &csio->sense_data;
1360                                         scsi_extract_sense(sense, &error_code,
1361                                                            &sense_key, 
1362                                                            &asc, &ascq);
1363                                 }
1364                                 /*
1365                                  * Attach to anything that claims to be a
1366                                  * direct access or optical disk device,
1367                                  * as long as it doesn't return a "Logical
1368                                  * unit not supported" (0x25) error.
1369                                  */
1370                                 if ((have_sense) && (asc != 0x25)
1371                                  && (error_code == SSD_CURRENT_ERROR)) {
1372                                         const char *sense_key_desc;
1373                                         const char *asc_desc;
1374
1375                                         scsi_sense_desc(sense_key, asc, ascq,
1376                                                         &cgd.inq_data,
1377                                                         &sense_key_desc,
1378                                                         &asc_desc);
1379                                         snprintf(announce_buf,
1380                                             sizeof(announce_buf),
1381                                                 "Attempt to query device "
1382                                                 "size failed: %s, %s",
1383                                                 sense_key_desc,
1384                                                 asc_desc);
1385                                 } else { 
1386                                         if (have_sense)
1387                                                 scsi_sense_print(
1388                                                         &done_ccb->csio);
1389                                         else {
1390                                                 xpt_print_path(periph->path);
1391                                                 printf("got CAM status %#x\n",
1392                                                        done_ccb->ccb_h.status);
1393                                         }
1394
1395                                         xpt_print_path(periph->path);
1396                                         printf("fatal error, failed" 
1397                                                " to attach to device\n");
1398
1399                                         /*
1400                                          * Free up resources.
1401                                          */
1402                                         cam_periph_invalidate(periph);
1403                                 } 
1404                         }
1405                 }
1406                 free(rdcap, M_TEMP);
1407                 if (announce_buf[0] != '\0')
1408                         xpt_announce_periph(periph, announce_buf);
1409                 softc->state = DA_STATE_NORMAL; 
1410                 /*
1411                  * Since our peripheral may be invalidated by an error
1412                  * above or an external event, we must release our CCB
1413                  * before releasing the probe lock on the peripheral.
1414                  * The peripheral will only go away once the last lock
1415                  * is removed, and we need it around for the CCB release
1416                  * operation.
1417                  */
1418                 xpt_release_ccb(done_ccb);
1419                 cam_periph_unlock(periph);
1420                 return;
1421         }
1422         case DA_CCB_WAITING:
1423         {
1424                 /* Caller will release the CCB */
1425                 wakeup(&done_ccb->ccb_h.cbfcnp);
1426                 return;
1427         }
1428         case DA_CCB_DUMP:
1429                 /* No-op.  We're polling */
1430                 return;
1431         default:
1432                 break;
1433         }
1434         xpt_release_ccb(done_ccb);
1435 }
1436
1437 static int
1438 daerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
1439 {
1440         struct da_softc   *softc;
1441         struct cam_periph *periph;
1442
1443         periph = xpt_path_periph(ccb->ccb_h.path);
1444         softc = (struct da_softc *)periph->softc;
1445
1446         /*
1447          * XXX
1448          * Until we have a better way of doing pack validation,
1449          * don't treat UAs as errors.
1450          */
1451         sense_flags |= SF_RETRY_UA;
1452         return(cam_periph_error(ccb, cam_flags, sense_flags,
1453                                 &softc->saved_ccb));
1454 }
1455
1456 static void
1457 daprevent(struct cam_periph *periph, int action)
1458 {
1459         struct  da_softc *softc;
1460         union   ccb *ccb;               
1461         int     error;
1462                 
1463         softc = (struct da_softc *)periph->softc;
1464
1465         if (((action == PR_ALLOW)
1466           && (softc->flags & DA_FLAG_PACK_LOCKED) == 0)
1467          || ((action == PR_PREVENT)
1468           && (softc->flags & DA_FLAG_PACK_LOCKED) != 0)) {
1469                 return;
1470         }
1471
1472         ccb = cam_periph_getccb(periph, /*priority*/1);
1473
1474         scsi_prevent(&ccb->csio,
1475                      /*retries*/1,
1476                      /*cbcfp*/dadone,
1477                      MSG_SIMPLE_Q_TAG,
1478                      action,
1479                      SSD_FULL_SIZE,
1480                      5000);
1481
1482         error = cam_periph_runccb(ccb, /*error_routine*/NULL, /*cam_flags*/0,
1483                                   /*sense_flags*/0, &softc->device_stats);
1484
1485         if (error == 0) {
1486                 if (action == PR_ALLOW)
1487                         softc->flags &= ~DA_FLAG_PACK_LOCKED;
1488                 else
1489                         softc->flags |= DA_FLAG_PACK_LOCKED;
1490         }
1491
1492         xpt_release_ccb(ccb);
1493 }
1494
1495 static void
1496 dasetgeom(struct cam_periph *periph, struct scsi_read_capacity_data * rdcap)
1497 {
1498         struct ccb_calc_geometry ccg;
1499         struct da_softc *softc;
1500         struct disk_params *dp;
1501
1502         softc = (struct da_softc *)periph->softc;
1503
1504         dp = &softc->params;
1505         dp->secsize = scsi_4btoul(rdcap->length);
1506         dp->sectors = scsi_4btoul(rdcap->addr) + 1;
1507         /*
1508          * Have the controller provide us with a geometry
1509          * for this disk.  The only time the geometry
1510          * matters is when we boot and the controller
1511          * is the only one knowledgeable enough to come
1512          * up with something that will make this a bootable
1513          * device.
1514          */
1515         xpt_setup_ccb(&ccg.ccb_h, periph->path, /*priority*/1);
1516         ccg.ccb_h.func_code = XPT_CALC_GEOMETRY;
1517         ccg.block_size = dp->secsize;
1518         ccg.volume_size = dp->sectors;
1519         ccg.heads = 0;
1520         ccg.secs_per_track = 0;
1521         ccg.cylinders = 0;
1522         xpt_action((union ccb*)&ccg);
1523         dp->heads = ccg.heads;
1524         dp->secs_per_track = ccg.secs_per_track;
1525         dp->cylinders = ccg.cylinders;
1526 }
1527
1528 static void
1529 dasendorderedtag(void *arg)
1530 {
1531         struct da_softc *softc;
1532         int s;
1533
1534         for (softc = SLIST_FIRST(&softc_list);
1535              softc != NULL;
1536              softc = SLIST_NEXT(softc, links)) {
1537                 s = splsoftcam();
1538                 if ((softc->ordered_tag_count == 0) 
1539                  && ((softc->flags & DA_FLAG_WENT_IDLE) == 0)) {
1540                         softc->flags |= DA_FLAG_NEED_OTAG;
1541                 }
1542                 if (softc->device_stats.busy_count > 0)
1543                         softc->flags &= ~DA_FLAG_WENT_IDLE;
1544
1545                 softc->ordered_tag_count = 0;
1546                 splx(s);
1547         }
1548         /* Queue us up again */
1549         timeout(dasendorderedtag, NULL,
1550                 (DA_DEFAULT_TIMEOUT * hz) / DA_ORDEREDTAG_INTERVAL);
1551 }
1552
1553 /*
1554  * Step through all DA peripheral drivers, and if the device is still open,
1555  * sync the disk cache to physical media.
1556  */
1557 static void
1558 dashutdown(void * arg, int howto)
1559 {
1560         struct cam_periph *periph;
1561         struct da_softc *softc;
1562
1563         TAILQ_FOREACH(periph, &dadriver.units, unit_links) {
1564                 union ccb ccb;
1565                 softc = (struct da_softc *)periph->softc;
1566
1567                 /*
1568                  * We only sync the cache if the drive is still open, and
1569                  * if the drive is capable of it..
1570                  */
1571                 if (((softc->flags & DA_FLAG_OPEN) == 0)
1572                  || (softc->quirks & DA_Q_NO_SYNC_CACHE))
1573                         continue;
1574
1575                 xpt_setup_ccb(&ccb.ccb_h, periph->path, /*priority*/1);
1576
1577                 ccb.ccb_h.ccb_state = DA_CCB_DUMP;
1578                 scsi_synchronize_cache(&ccb.csio,
1579                                        /*retries*/1,
1580                                        /*cbfcnp*/dadone,
1581                                        MSG_SIMPLE_Q_TAG,
1582                                        /*begin_lba*/0, /* whole disk */
1583                                        /*lb_count*/0,
1584                                        SSD_FULL_SIZE,
1585                                        5 * 60 * 1000);
1586
1587                 xpt_polled_action(&ccb);
1588
1589                 if ((ccb.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1590                         if (((ccb.ccb_h.status & CAM_STATUS_MASK) ==
1591                              CAM_SCSI_STATUS_ERROR)
1592                          && (ccb.csio.scsi_status == SCSI_STATUS_CHECK_COND)){
1593                                 int error_code, sense_key, asc, ascq;
1594
1595                                 scsi_extract_sense(&ccb.csio.sense_data,
1596                                                    &error_code, &sense_key,
1597                                                    &asc, &ascq);
1598
1599                                 if (sense_key != SSD_KEY_ILLEGAL_REQUEST)
1600                                         scsi_sense_print(&ccb.csio);
1601                         } else {
1602                                 xpt_print_path(periph->path);
1603                                 printf("Synchronize cache failed, status "
1604                                        "== 0x%x, scsi status == 0x%x\n",
1605                                        ccb.ccb_h.status, ccb.csio.scsi_status);
1606                         }
1607                 }
1608
1609                 if ((ccb.ccb_h.status & CAM_DEV_QFRZN) != 0)
1610                         cam_release_devq(ccb.ccb_h.path,
1611                                          /*relsim_flags*/0,
1612                                          /*reduction*/0,
1613                                          /*timeout*/0,
1614                                          /*getcount_only*/0);
1615
1616         }
1617 }
1618
1619 #else /* !_KERNEL */
1620
1621 /*
1622  * XXX This is only left out of the kernel build to silence warnings.  If,
1623  * for some reason this function is used in the kernel, the ifdefs should
1624  * be moved so it is included both in the kernel and userland.
1625  */
1626 void
1627 scsi_format_unit(struct ccb_scsiio *csio, u_int32_t retries,
1628                  void (*cbfcnp)(struct cam_periph *, union ccb *),
1629                  u_int8_t tag_action, u_int8_t byte2, u_int16_t ileave,
1630                  u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
1631                  u_int32_t timeout)
1632 {
1633         struct scsi_format_unit *scsi_cmd;
1634
1635         scsi_cmd = (struct scsi_format_unit *)&csio->cdb_io.cdb_bytes;
1636         scsi_cmd->opcode = FORMAT_UNIT;
1637         scsi_cmd->byte2 = byte2;
1638         scsi_ulto2b(ileave, scsi_cmd->interleave);
1639
1640         cam_fill_csio(csio,
1641                       retries,
1642                       cbfcnp,
1643                       /*flags*/ (dxfer_len > 0) ? CAM_DIR_OUT : CAM_DIR_NONE,
1644                       tag_action,
1645                       data_ptr,
1646                       dxfer_len,
1647                       sense_len,
1648                       sizeof(*scsi_cmd),
1649                       timeout);
1650 }
1651
1652 #endif /* _KERNEL */