Initial import from FreeBSD RELENG_4:
[dragonfly.git] / sys / dev / raid / dpt / dpt_scsi.c
1 /*
2  *       Copyright (c) 1997 by Simon Shapiro
3  *       All Rights Reserved
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions, and the following disclaimer,
10  *    without modification, immediately at the beginning of the file.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
21  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 /*
31  * dpt_scsi.c: SCSI dependant code for the DPT driver
32  *
33  * credits:     Assisted by Mike Neuffer in the early low level DPT code
34  *              Thanx to Mark Salyzyn of DPT for his assistance.
35  *              Special thanx to Justin Gibbs for invaluable help in
36  *              making this driver look and work like a FreeBSD component.
37  *              Last but not least, many thanx to UCB and the FreeBSD
38  *              team for creating and maintaining such a wonderful O/S.
39  *
40  * TODO:     * Add ISA probe code.
41  *           * Add driver-level RAID-0. This will allow interoperability with
42  *             NiceTry, M$-Doze, Win-Dog, Slowlaris, etc., in recognizing RAID
43  *             arrays that span controllers (Wow!).
44  */
45
46 #ident "$FreeBSD: src/sys/dev/dpt/dpt_scsi.c,v 1.28.2.3 2003/01/31 02:47:10 grog Exp $"
47
48 #define _DPT_C_
49
50 #include "opt_dpt.h"
51 #include <sys/param.h>
52 #include <sys/systm.h>
53 #include <sys/eventhandler.h>
54 #include <sys/malloc.h>
55 #include <sys/kernel.h>
56
57 #include <sys/bus.h>
58
59 #include <machine/bus_memio.h>
60 #include <machine/bus_pio.h>
61 #include <machine/bus.h>
62
63 #include <machine/clock.h>
64
65 #include <cam/cam.h>
66 #include <cam/cam_ccb.h>
67 #include <cam/cam_sim.h>
68 #include <cam/cam_xpt_sim.h>
69 #include <cam/cam_debug.h>
70 #include <cam/scsi/scsi_all.h>
71 #include <cam/scsi/scsi_message.h>
72
73 #include <vm/vm.h>
74 #include <vm/pmap.h>
75
76 #include <dev/dpt/dpt.h>
77
78 /* dpt_isa.c, dpt_eisa.c, and dpt_pci.c need this in a central place */
79 int dpt_controllers_present;
80
81 u_long  dpt_unit;       /* Next unit number to use */
82
83 /* The linked list of softc structures */
84 struct dpt_softc_list dpt_softcs = TAILQ_HEAD_INITIALIZER(dpt_softcs);
85
86 #define microtime_now dpt_time_now()
87
88 #define dpt_inl(dpt, port)                              \
89         bus_space_read_4((dpt)->tag, (dpt)->bsh, port)
90 #define dpt_inb(dpt, port)                              \
91         bus_space_read_1((dpt)->tag, (dpt)->bsh, port)
92 #define dpt_outl(dpt, port, value)                      \
93         bus_space_write_4((dpt)->tag, (dpt)->bsh, port, value)
94 #define dpt_outb(dpt, port, value)                      \
95         bus_space_write_1((dpt)->tag, (dpt)->bsh, port, value)
96
97 /*
98  * These will have to be setup by parameters passed at boot/load time. For
99  * perfromance reasons, we make them constants for the time being.
100  */
101 #define dpt_min_segs    DPT_MAX_SEGS
102 #define dpt_max_segs    DPT_MAX_SEGS
103
104 /* Definitions for our use of the SIM private CCB area */
105 #define ccb_dccb_ptr spriv_ptr0
106 #define ccb_dpt_ptr spriv_ptr1
107
108 /* ================= Private Inline Function declarations ===================*/
109 static __inline int             dpt_just_reset(dpt_softc_t * dpt);
110 static __inline int             dpt_raid_busy(dpt_softc_t * dpt);
111 static __inline int             dpt_pio_wait (u_int32_t, u_int, u_int, u_int);
112 static __inline int             dpt_wait(dpt_softc_t *dpt, u_int bits,
113                                          u_int state);
114 static __inline struct dpt_ccb* dptgetccb(struct dpt_softc *dpt);
115 static __inline void            dptfreeccb(struct dpt_softc *dpt,
116                                            struct dpt_ccb *dccb);
117 static __inline u_int32_t       dptccbvtop(struct dpt_softc *dpt,
118                                            struct dpt_ccb *dccb);
119
120 static __inline int             dpt_send_immediate(dpt_softc_t *dpt,
121                                                    eata_ccb_t *cmd_block,
122                                                    u_int32_t cmd_busaddr,  
123                                                    u_int retries,
124                                                    u_int ifc, u_int code,
125                                                    u_int code2);
126
127 /* ==================== Private Function declarations =======================*/
128 static void             dptmapmem(void *arg, bus_dma_segment_t *segs,
129                                   int nseg, int error);
130
131 static struct sg_map_node*
132                         dptallocsgmap(struct dpt_softc *dpt);
133
134 static int              dptallocccbs(dpt_softc_t *dpt);
135
136 static int              dpt_get_conf(dpt_softc_t *dpt, dpt_ccb_t *dccb,
137                                      u_int32_t dccb_busaddr, u_int size,
138                                      u_int page, u_int target, int extent);
139 static void             dpt_detect_cache(dpt_softc_t *dpt, dpt_ccb_t *dccb,
140                                          u_int32_t dccb_busaddr,
141                                          u_int8_t *buff);
142
143 static void             dpt_poll(struct cam_sim *sim);
144
145 static void             dptexecuteccb(void *arg, bus_dma_segment_t *dm_segs,
146                                       int nseg, int error);
147
148 static void             dpt_action(struct cam_sim *sim, union ccb *ccb);
149
150 static int              dpt_send_eata_command(dpt_softc_t *dpt, eata_ccb_t *cmd,
151                                               u_int32_t cmd_busaddr,
152                                               u_int command, u_int retries,
153                                               u_int ifc, u_int code,
154                                               u_int code2);
155 static void             dptprocesserror(dpt_softc_t *dpt, dpt_ccb_t *dccb,
156                                         union ccb *ccb, u_int hba_stat,
157                                         u_int scsi_stat, u_int32_t resid);
158
159 static void             dpttimeout(void *arg);
160 static void             dptshutdown(void *arg, int howto);
161
162 /* ================= Private Inline Function definitions ====================*/
163 static __inline int
164 dpt_just_reset(dpt_softc_t * dpt)
165 {
166         if ((dpt_inb(dpt, 2) == 'D')
167          && (dpt_inb(dpt, 3) == 'P')
168          && (dpt_inb(dpt, 4) == 'T')
169          && (dpt_inb(dpt, 5) == 'H'))
170                 return (1);
171         else
172                 return (0);
173 }
174
175 static __inline int
176 dpt_raid_busy(dpt_softc_t * dpt)
177 {
178         if ((dpt_inb(dpt, 0) == 'D')
179          && (dpt_inb(dpt, 1) == 'P')
180          && (dpt_inb(dpt, 2) == 'T'))
181                 return (1);
182         else
183                 return (0);
184 }
185
186 static __inline int
187 dpt_pio_wait (u_int32_t base, u_int reg, u_int bits, u_int state)
188 {
189         int   i;
190         u_int c;
191
192         for (i = 0; i < 20000; i++) {   /* wait 20ms for not busy */
193                 c = inb(base + reg) & bits;
194                 if (!(c == state))
195                         return (0);
196                 else
197                         DELAY(50);
198         }
199         return (-1);
200 }
201
202 static __inline int
203 dpt_wait(dpt_softc_t *dpt, u_int bits, u_int state)
204 {
205         int   i;
206         u_int c;
207
208         for (i = 0; i < 20000; i++) {   /* wait 20ms for not busy */
209                 c = dpt_inb(dpt, HA_RSTATUS) & bits;
210                 if (c == state)
211                         return (0);
212                 else
213                         DELAY(50);
214         }
215         return (-1);
216 }
217
218 static __inline struct dpt_ccb*
219 dptgetccb(struct dpt_softc *dpt)
220 {
221         struct  dpt_ccb* dccb;
222         int     s;
223
224         s = splcam();
225         if ((dccb = SLIST_FIRST(&dpt->free_dccb_list)) != NULL) {
226                 SLIST_REMOVE_HEAD(&dpt->free_dccb_list, links);
227                 dpt->free_dccbs--;
228         } else if (dpt->total_dccbs < dpt->max_dccbs) {
229                 dptallocccbs(dpt);
230                 dccb = SLIST_FIRST(&dpt->free_dccb_list);
231                 if (dccb == NULL)
232                         printf("dpt%d: Can't malloc DCCB\n", dpt->unit);
233                 else {
234                         SLIST_REMOVE_HEAD(&dpt->free_dccb_list, links);
235                         dpt->free_dccbs--;
236                 }
237         }
238         splx(s);
239
240         return (dccb);
241 }
242
243 static __inline void
244 dptfreeccb(struct dpt_softc *dpt, struct dpt_ccb *dccb)
245 {
246         int s;
247
248         s = splcam();
249         if ((dccb->state & DCCB_ACTIVE) != 0)
250                 LIST_REMOVE(&dccb->ccb->ccb_h, sim_links.le);
251         if ((dccb->state & DCCB_RELEASE_SIMQ) != 0)
252                 dccb->ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
253         else if (dpt->resource_shortage != 0
254          && (dccb->ccb->ccb_h.status & CAM_RELEASE_SIMQ) == 0) {
255                 dccb->ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
256                 dpt->resource_shortage = FALSE;
257         }
258         dccb->state = DCCB_FREE;
259         SLIST_INSERT_HEAD(&dpt->free_dccb_list, dccb, links);
260         ++dpt->free_dccbs;
261         splx(s);
262 }
263
264 static __inline u_int32_t
265 dptccbvtop(struct dpt_softc *dpt, struct dpt_ccb *dccb)
266 {
267         return (dpt->dpt_ccb_busbase
268               + (u_int32_t)((caddr_t)dccb - (caddr_t)dpt->dpt_dccbs));
269 }
270
271 static __inline struct dpt_ccb *
272 dptccbptov(struct dpt_softc *dpt, u_int32_t busaddr)
273 {
274         return (dpt->dpt_dccbs
275              +  ((struct dpt_ccb *)busaddr
276                - (struct dpt_ccb *)dpt->dpt_ccb_busbase));
277 }
278
279 /*
280  * Send a command for immediate execution by the DPT
281  * See above function for IMPORTANT notes.
282  */
283 static __inline int
284 dpt_send_immediate(dpt_softc_t *dpt, eata_ccb_t *cmd_block,
285                    u_int32_t cmd_busaddr, u_int retries,
286                    u_int ifc, u_int code, u_int code2)
287 {
288         return (dpt_send_eata_command(dpt, cmd_block, cmd_busaddr,
289                                       EATA_CMD_IMMEDIATE, retries, ifc,
290                                       code, code2));
291 }
292
293
294 /* ===================== Private Function definitions =======================*/
295 static void
296 dptmapmem(void *arg, bus_dma_segment_t *segs, int nseg, int error)
297 {
298         bus_addr_t *busaddrp;
299
300         busaddrp = (bus_addr_t *)arg;
301         *busaddrp = segs->ds_addr;
302 }
303
304 static struct sg_map_node *
305 dptallocsgmap(struct dpt_softc *dpt)
306 {
307         struct sg_map_node *sg_map;
308
309         sg_map = malloc(sizeof(*sg_map), M_DEVBUF, M_NOWAIT);
310
311         if (sg_map == NULL)
312                 return (NULL);
313
314         /* Allocate S/G space for the next batch of CCBS */
315         if (bus_dmamem_alloc(dpt->sg_dmat, (void **)&sg_map->sg_vaddr,
316                              BUS_DMA_NOWAIT, &sg_map->sg_dmamap) != 0) {
317                 free(sg_map, M_DEVBUF);
318                 return (NULL);
319         }
320
321         (void)bus_dmamap_load(dpt->sg_dmat, sg_map->sg_dmamap, sg_map->sg_vaddr,
322                               PAGE_SIZE, dptmapmem, &sg_map->sg_physaddr,
323                               /*flags*/0);
324
325         SLIST_INSERT_HEAD(&dpt->sg_maps, sg_map, links);
326
327         return (sg_map);
328 }
329
330 /*
331  * Allocate another chunk of CCB's. Return count of entries added.
332  * Assumed to be called at splcam().
333  */
334 static int
335 dptallocccbs(dpt_softc_t *dpt)
336 {
337         struct dpt_ccb *next_ccb;
338         struct sg_map_node *sg_map;
339         bus_addr_t physaddr;
340         dpt_sg_t *segs;
341         int newcount;
342         int i;
343
344         next_ccb = &dpt->dpt_dccbs[dpt->total_dccbs];
345
346         if (next_ccb == dpt->dpt_dccbs) {
347                 /*
348                  * First time through.  Re-use the S/G
349                  * space we allocated for initialization
350                  * CCBS.
351                  */
352                 sg_map = SLIST_FIRST(&dpt->sg_maps);
353         } else {
354                 sg_map = dptallocsgmap(dpt);
355         }
356
357         if (sg_map == NULL)
358                 return (0);
359
360         segs = sg_map->sg_vaddr;
361         physaddr = sg_map->sg_physaddr;
362
363         newcount = (PAGE_SIZE / (dpt->sgsize * sizeof(dpt_sg_t)));
364         for (i = 0; dpt->total_dccbs < dpt->max_dccbs && i < newcount; i++) {
365                 int error;
366
367                 error = bus_dmamap_create(dpt->buffer_dmat, /*flags*/0,
368                                           &next_ccb->dmamap);
369                 if (error != 0)
370                         break;
371                 next_ccb->sg_list = segs;
372                 next_ccb->sg_busaddr = htonl(physaddr);
373                 next_ccb->eata_ccb.cp_dataDMA = htonl(physaddr);
374                 next_ccb->eata_ccb.cp_statDMA = htonl(dpt->sp_physaddr);
375                 next_ccb->eata_ccb.cp_reqDMA =
376                     htonl(dptccbvtop(dpt, next_ccb)
377                         + offsetof(struct dpt_ccb, sense_data));
378                 next_ccb->eata_ccb.cp_busaddr = dpt->dpt_ccb_busend;
379                 next_ccb->state = DCCB_FREE;
380                 next_ccb->tag = dpt->total_dccbs;
381                 SLIST_INSERT_HEAD(&dpt->free_dccb_list, next_ccb, links);
382                 segs += dpt->sgsize;
383                 physaddr += (dpt->sgsize * sizeof(dpt_sg_t));
384                 dpt->dpt_ccb_busend += sizeof(*next_ccb);
385                 next_ccb++;
386                 dpt->total_dccbs++;
387         }
388         return (i);
389 }
390
391 dpt_conf_t *
392 dpt_pio_get_conf (u_int32_t base)
393 {
394         static dpt_conf_t *     conf;
395         u_int16_t *             p;
396         int                     i;
397
398         /*
399          * Allocate a dpt_conf_t
400          */
401         if (!conf) {
402                 conf = (dpt_conf_t *)malloc(sizeof(dpt_conf_t),
403                                                  M_DEVBUF, M_NOWAIT);
404         }
405         
406         /*
407          * If we didn't get one then we probably won't ever get one.
408          */
409         if (!conf) {
410                 printf("dpt: unable to allocate dpt_conf_t\n");
411                 return (NULL);
412         }
413
414         /*
415          * If we have one, clean it up.
416          */
417         bzero(conf, sizeof(dpt_conf_t));
418
419         /*
420          * Reset the controller.
421          */
422         outb((base + HA_WCOMMAND), EATA_CMD_RESET);
423
424         /*
425          * Wait for the controller to become ready.
426          * For some reason there can be -no- delays after calling reset
427          * before we wait on ready status.
428          */
429         if (dpt_pio_wait(base, HA_RSTATUS, HA_SBUSY, 0)) {
430                 printf("dpt: timeout waiting for controller to become ready\n");
431                 return (NULL);
432         }
433
434         if (dpt_pio_wait(base, HA_RAUXSTAT, HA_ABUSY, 0)) {
435                 printf("dpt: timetout waiting for adapter ready.\n");
436                 return (NULL);
437         }
438
439         /*
440          * Send the PIO_READ_CONFIG command.
441          */
442         outb((base + HA_WCOMMAND), EATA_CMD_PIO_READ_CONFIG);
443
444         /*
445          * Read the data into the struct.
446          */
447         p = (u_int16_t *)conf;
448         for (i = 0; i < (sizeof(dpt_conf_t) / 2); i++) {
449
450                 if (dpt_pio_wait(base, HA_RSTATUS, HA_SDRQ, 0)) {
451                         printf("dpt: timeout in data read.\n");
452                         return (NULL);
453                 }
454
455                 (*p) = inw(base + HA_RDATA);
456                 p++;
457         }
458
459         if (inb(base + HA_RSTATUS) & HA_SERROR) {
460                 printf("dpt: error reading configuration data.\n");
461                 return (NULL);
462         }
463
464 #define BE_EATA_SIGNATURE       0x45415441
465 #define LE_EATA_SIGNATURE       0x41544145
466
467         /*
468          * Test to see if we have a valid card.
469          */
470         if ((conf->signature == BE_EATA_SIGNATURE) ||
471             (conf->signature == LE_EATA_SIGNATURE)) {
472
473                 while (inb(base + HA_RSTATUS) & HA_SDRQ) {
474                         inw(base + HA_RDATA);
475                 }
476
477                 return (conf);
478         }
479         return (NULL);
480 }
481
482 /*
483  * Read a configuration page into the supplied dpt_cont_t buffer.
484  */
485 static int
486 dpt_get_conf(dpt_softc_t *dpt, dpt_ccb_t *dccb, u_int32_t dccb_busaddr,
487              u_int size, u_int page, u_int target, int extent)
488 {
489         eata_ccb_t *cp;
490
491         u_int8_t   status;
492
493         int        ndx;
494         int        ospl;
495         int        result;
496
497         cp = &dccb->eata_ccb;
498         bzero((void *)(uintptr_t)(volatile void *)dpt->sp, sizeof(*dpt->sp));
499
500         cp->Interpret = 1;
501         cp->DataIn = 1;
502         cp->Auto_Req_Sen = 1;
503         cp->reqlen = sizeof(struct scsi_sense_data);
504
505         cp->cp_id = target;
506         cp->cp_LUN = 0;         /* In the EATA packet */
507         cp->cp_lun = 0;         /* In the SCSI command */
508
509         cp->cp_scsi_cmd = INQUIRY;
510         cp->cp_len = size;
511
512         cp->cp_extent = extent;
513
514         cp->cp_page = page;
515         cp->cp_channel = 0;     /* DNC, Interpret mode is set */
516         cp->cp_identify = 1;
517         cp->cp_datalen = htonl(size);
518
519         ospl = splcam();
520
521         /*
522          * This could be a simple for loop, but we suspected the compiler To
523          * have optimized it a bit too much. Wait for the controller to
524          * become ready
525          */
526         while (((status = dpt_inb(dpt, HA_RSTATUS)) != (HA_SREADY | HA_SSC)
527              && (status != (HA_SREADY | HA_SSC | HA_SERROR))
528              && (status != (HA_SDRDY | HA_SERROR | HA_SDRQ)))
529             || (dpt_wait(dpt, HA_SBUSY, 0))) {
530
531                 /*
532                  * RAID Drives still Spinning up? (This should only occur if
533                  * the DPT controller is in a NON PC (PCI?) platform).
534                  */
535                 if (dpt_raid_busy(dpt)) {
536                         printf("dpt%d WARNING: Get_conf() RSUS failed.\n",
537                                dpt->unit);
538                         splx(ospl);
539                         return (0);
540                 }
541         }
542
543         DptStat_Reset_BUSY(dpt->sp);
544
545         /*
546          * XXXX We might want to do something more clever than aborting at
547          * this point, like resetting (rebooting) the controller and trying
548          * again.
549          */
550         if ((result = dpt_send_eata_command(dpt, cp, dccb_busaddr,
551                                             EATA_CMD_DMA_SEND_CP,
552                                             10000, 0, 0, 0)) != 0) {
553                 printf("dpt%d WARNING: Get_conf() failed (%d) to send "
554                        "EATA_CMD_DMA_READ_CONFIG\n",
555                        dpt->unit, result);
556                 splx(ospl);
557                 return (0);
558         }
559         /* Wait for two seconds for a response.  This can be slow  */
560         for (ndx = 0;
561              (ndx < 20000)
562              && !((status = dpt_inb(dpt, HA_RAUXSTAT)) & HA_AIRQ);
563              ndx++) {
564                 DELAY(50);
565         }
566
567         /* Grab the status and clear interrupts */
568         status = dpt_inb(dpt, HA_RSTATUS);
569
570         splx(ospl);
571
572         /*
573          * Check the status carefully.  Return only if the
574          * command was successful.
575          */
576         if (((status & HA_SERROR) == 0)
577          && (dpt->sp->hba_stat == 0)
578          && (dpt->sp->scsi_stat == 0)
579          && (dpt->sp->residue_len == 0))
580                 return (0);
581
582         if (dpt->sp->scsi_stat == SCSI_STATUS_CHECK_COND)
583                 return (0);
584
585         return (1);
586 }
587
588 /* Detect Cache parameters and size */
589 static void
590 dpt_detect_cache(dpt_softc_t *dpt, dpt_ccb_t *dccb, u_int32_t dccb_busaddr,
591                  u_int8_t *buff)
592 {
593         eata_ccb_t *cp;
594         u_int8_t   *param;
595         int         bytes;
596         int         result;
597         int         ospl;
598         int         ndx;
599         u_int8_t    status;
600
601         /*
602          * Default setting, for best perfromance..
603          * This is what virtually all cards default to..
604          */
605         dpt->cache_type = DPT_CACHE_WRITEBACK;
606         dpt->cache_size = 0;
607
608         cp = &dccb->eata_ccb;
609         bzero((void *)(uintptr_t)(volatile void *)dpt->sp, sizeof(dpt->sp));
610         bzero(buff, 512);
611
612         /* Setup the command structure */
613         cp->Interpret = 1;
614         cp->DataIn = 1;
615         cp->Auto_Req_Sen = 1;
616         cp->reqlen = sizeof(struct scsi_sense_data);
617
618         cp->cp_id = 0;          /* who cares?  The HBA will interpret.. */
619         cp->cp_LUN = 0;         /* In the EATA packet */
620         cp->cp_lun = 0;         /* In the SCSI command */
621         cp->cp_channel = 0;
622
623         cp->cp_scsi_cmd = EATA_CMD_DMA_SEND_CP;
624         cp->cp_len = 56;
625
626         cp->cp_extent = 0;
627         cp->cp_page = 0;
628         cp->cp_identify = 1;
629         cp->cp_dispri = 1;
630
631         /*
632          * Build the EATA Command Packet structure
633          * for a Log Sense Command.
634          */
635         cp->cp_cdb[0] = 0x4d;
636         cp->cp_cdb[1] = 0x0;
637         cp->cp_cdb[2] = 0x40 | 0x33;
638         cp->cp_cdb[7] = 1;
639
640         cp->cp_datalen = htonl(512);
641
642         ospl = splcam();
643         result = dpt_send_eata_command(dpt, cp, dccb_busaddr,
644                                        EATA_CMD_DMA_SEND_CP,
645                                        10000, 0, 0, 0);
646         if (result != 0) {
647                 printf("dpt%d WARNING: detect_cache() failed (%d) to send "
648                        "EATA_CMD_DMA_SEND_CP\n", dpt->unit, result);
649                 splx(ospl);
650                 return;
651         }
652         /* Wait for two seconds for a response.  This can be slow... */
653         for (ndx = 0;
654              (ndx < 20000) &&
655              !((status = dpt_inb(dpt, HA_RAUXSTAT)) & HA_AIRQ);
656              ndx++) {
657                 DELAY(50);
658         }
659
660         /* Grab the status and clear interrupts */
661         status = dpt_inb(dpt, HA_RSTATUS);
662         splx(ospl);
663
664         /*
665          * Sanity check
666          */
667         if (buff[0] != 0x33) {
668                 return;
669         }
670         bytes = DPT_HCP_LENGTH(buff);
671         param = DPT_HCP_FIRST(buff);
672
673         if (DPT_HCP_CODE(param) != 1) {
674                 /*
675                  * DPT Log Page layout error
676                  */
677                 printf("dpt%d: NOTICE: Log Page (1) layout error\n",
678                        dpt->unit);
679                 return;
680         }
681         if (!(param[4] & 0x4)) {
682                 dpt->cache_type = DPT_NO_CACHE;
683                 return;
684         }
685         while (DPT_HCP_CODE(param) != 6) {
686                 param = DPT_HCP_NEXT(param);
687                 if ((param < buff)
688                  || (param >= &buff[bytes])) {
689                         return;
690                 }
691         }
692
693         if (param[4] & 0x2) {
694                 /*
695                  * Cache disabled
696                  */
697                 dpt->cache_type = DPT_NO_CACHE;
698                 return;
699         }
700
701         if (param[4] & 0x4) {
702                 dpt->cache_type = DPT_CACHE_WRITETHROUGH;
703         }
704
705         /* XXX This isn't correct.  This log parameter only has two bytes.... */
706 #if 0
707         dpt->cache_size = param[5]
708                         | (param[6] << 8)
709                         | (param[7] << 16)
710                         | (param[8] << 24);
711 #endif
712 }
713
714 static void
715 dpt_poll(struct cam_sim *sim)
716 {
717         dpt_intr(cam_sim_softc(sim));
718 }
719
720 static void
721 dptexecuteccb(void *arg, bus_dma_segment_t *dm_segs, int nseg, int error)
722 {
723         struct   dpt_ccb *dccb;
724         union    ccb *ccb;
725         struct   dpt_softc *dpt;
726         int      s;
727
728         dccb = (struct dpt_ccb *)arg;
729         ccb = dccb->ccb;
730         dpt = (struct dpt_softc *)ccb->ccb_h.ccb_dpt_ptr;
731
732         if (error != 0) {
733                 if (error != EFBIG)
734                         printf("dpt%d: Unexepected error 0x%x returned from "
735                                "bus_dmamap_load\n", dpt->unit, error);
736                 if (ccb->ccb_h.status == CAM_REQ_INPROG) {
737                         xpt_freeze_devq(ccb->ccb_h.path, /*count*/1);
738                         ccb->ccb_h.status = CAM_REQ_TOO_BIG|CAM_DEV_QFRZN;
739                 }
740                 dptfreeccb(dpt, dccb);
741                 xpt_done(ccb);
742                 return;
743         }
744                 
745         if (nseg != 0) {
746                 dpt_sg_t *sg;
747                 bus_dma_segment_t *end_seg;
748                 bus_dmasync_op_t op;
749
750                 end_seg = dm_segs + nseg;
751
752                 /* Copy the segments into our SG list */
753                 sg = dccb->sg_list;
754                 while (dm_segs < end_seg) {
755                         sg->seg_len = htonl(dm_segs->ds_len);
756                         sg->seg_addr = htonl(dm_segs->ds_addr);
757                         sg++;
758                         dm_segs++;
759                 }
760
761                 if (nseg > 1) {
762                         dccb->eata_ccb.scatter = 1;
763                         dccb->eata_ccb.cp_dataDMA = dccb->sg_busaddr;
764                         dccb->eata_ccb.cp_datalen =
765                             htonl(nseg * sizeof(dpt_sg_t));
766                 } else {
767                         dccb->eata_ccb.cp_dataDMA = dccb->sg_list[0].seg_addr;
768                         dccb->eata_ccb.cp_datalen = dccb->sg_list[0].seg_len;
769                 }
770
771                 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN)
772                         op = BUS_DMASYNC_PREREAD;
773                 else
774                         op = BUS_DMASYNC_PREWRITE;
775
776                 bus_dmamap_sync(dpt->buffer_dmat, dccb->dmamap, op);
777
778         } else {
779                 dccb->eata_ccb.cp_dataDMA = 0;
780                 dccb->eata_ccb.cp_datalen = 0;
781         }
782
783         s = splcam();
784
785         /*
786          * Last time we need to check if this CCB needs to
787          * be aborted.
788          */
789         if (ccb->ccb_h.status != CAM_REQ_INPROG) {
790                 if (nseg != 0)
791                         bus_dmamap_unload(dpt->buffer_dmat, dccb->dmamap);
792                 dptfreeccb(dpt, dccb);
793                 xpt_done(ccb);
794                 splx(s);
795                 return;
796         }
797                 
798         dccb->state |= DCCB_ACTIVE;
799         ccb->ccb_h.status |= CAM_SIM_QUEUED;
800         LIST_INSERT_HEAD(&dpt->pending_ccb_list, &ccb->ccb_h, sim_links.le);
801         ccb->ccb_h.timeout_ch =
802             timeout(dpttimeout, (caddr_t)dccb,
803                     (ccb->ccb_h.timeout * hz) / 1000);
804         if (dpt_send_eata_command(dpt, &dccb->eata_ccb,
805                                   dccb->eata_ccb.cp_busaddr,
806                                   EATA_CMD_DMA_SEND_CP, 0, 0, 0, 0) != 0) {
807                 ccb->ccb_h.status = CAM_NO_HBA; /* HBA dead or just busy?? */
808                 if (nseg != 0)
809                         bus_dmamap_unload(dpt->buffer_dmat, dccb->dmamap);
810                 dptfreeccb(dpt, dccb);
811                 xpt_done(ccb);
812         }
813
814         splx(s);
815 }
816
817 static void
818 dpt_action(struct cam_sim *sim, union ccb *ccb)
819 {
820         struct    dpt_softc *dpt;
821
822         CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("dpt_action\n"));
823         
824         dpt = (struct dpt_softc *)cam_sim_softc(sim);
825
826         if ((dpt->state & DPT_HA_SHUTDOWN_ACTIVE) != 0) {
827                 xpt_print_path(ccb->ccb_h.path);
828                 printf("controller is shutdown. Aborting CCB.\n");
829                 ccb->ccb_h.status = CAM_NO_HBA;
830                 xpt_done(ccb);
831                 return;
832         }
833
834         switch (ccb->ccb_h.func_code) {
835         /* Common cases first */
836         case XPT_SCSI_IO:       /* Execute the requested I/O operation */
837         {
838                 struct  ccb_scsiio *csio;
839                 struct  ccb_hdr *ccbh;
840                 struct  dpt_ccb *dccb;
841                 struct  eata_ccb *eccb;
842
843                 csio = &ccb->csio;
844                 ccbh = &ccb->ccb_h;
845                 /* Max CDB length is 12 bytes */
846                 if (csio->cdb_len > 12) { 
847                         ccb->ccb_h.status = CAM_REQ_INVALID;
848                         xpt_done(ccb);
849                         return;
850                 }
851                 if ((dccb = dptgetccb(dpt)) == NULL) {
852                         int s;
853         
854                         s = splcam();
855                         dpt->resource_shortage = 1;
856                         splx(s);
857                         xpt_freeze_simq(sim, /*count*/1);
858                         ccb->ccb_h.status = CAM_REQUEUE_REQ;
859                         xpt_done(ccb);
860                         return;
861                 }
862                 eccb = &dccb->eata_ccb;
863
864                 /* Link dccb and ccb so we can find one from the other */
865                 dccb->ccb = ccb;
866                 ccb->ccb_h.ccb_dccb_ptr = dccb;
867                 ccb->ccb_h.ccb_dpt_ptr = dpt;
868
869                 /*
870                  * Explicitly set all flags so that the compiler can
871                  * be smart about setting them.
872                  */
873                 eccb->SCSI_Reset = 0;
874                 eccb->HBA_Init = 0;
875                 eccb->Auto_Req_Sen = (ccb->ccb_h.flags & CAM_DIS_AUTOSENSE)
876                                    ? 0 : 1;
877                 eccb->scatter = 0;
878                 eccb->Quick = 0;
879                 eccb->Interpret =
880                     ccb->ccb_h.target_id == dpt->hostid[cam_sim_bus(sim)]
881                     ? 1 : 0;
882                 eccb->DataOut = (ccb->ccb_h.flags & CAM_DIR_OUT) ? 1 : 0;
883                 eccb->DataIn = (ccb->ccb_h.flags & CAM_DIR_IN) ? 1 : 0;
884                 eccb->reqlen = csio->sense_len;
885                 eccb->cp_id = ccb->ccb_h.target_id;
886                 eccb->cp_channel = cam_sim_bus(sim);
887                 eccb->cp_LUN = ccb->ccb_h.target_lun;
888                 eccb->cp_luntar = 0;
889                 eccb->cp_dispri = (ccb->ccb_h.flags & CAM_DIS_DISCONNECT)
890                                 ? 0 : 1;
891                 eccb->cp_identify = 1;
892
893                 if ((ccb->ccb_h.flags & CAM_TAG_ACTION_VALID) != 0
894                  && csio->tag_action != CAM_TAG_ACTION_NONE) {
895                         eccb->cp_msg[0] = csio->tag_action;
896                         eccb->cp_msg[1] = dccb->tag;
897                 } else {
898                         eccb->cp_msg[0] = 0;
899                         eccb->cp_msg[1] = 0;
900                 }
901                 eccb->cp_msg[2] = 0;
902
903                 if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0) {
904                         if ((ccb->ccb_h.flags & CAM_CDB_PHYS) == 0) {
905                                 bcopy(csio->cdb_io.cdb_ptr,
906                                       eccb->cp_cdb, csio->cdb_len);
907                         } else {
908                                 /* I guess I could map it in... */
909                                 ccb->ccb_h.status = CAM_REQ_INVALID;
910                                 dptfreeccb(dpt, dccb);
911                                 xpt_done(ccb);
912                                 return;
913                         }
914                 } else {
915                         bcopy(csio->cdb_io.cdb_bytes,
916                               eccb->cp_cdb, csio->cdb_len);
917                 }
918                 /*
919                  * If we have any data to send with this command,
920                  * map it into bus space.
921                  */
922                 /* Only use S/G if there is a transfer */
923                 if ((ccbh->flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
924                         if ((ccbh->flags & CAM_SCATTER_VALID) == 0) {
925                                 /*
926                                  * We've been given a pointer
927                                  * to a single buffer.
928                                  */
929                                 if ((ccbh->flags & CAM_DATA_PHYS) == 0) {
930                                         int s;
931                                         int error;
932
933                                         s = splsoftvm();
934                                         error =
935                                             bus_dmamap_load(dpt->buffer_dmat,
936                                                             dccb->dmamap,
937                                                             csio->data_ptr,
938                                                             csio->dxfer_len,
939                                                             dptexecuteccb,
940                                                             dccb, /*flags*/0);
941                                         if (error == EINPROGRESS) {
942                                                 /*
943                                                  * So as to maintain ordering,
944                                                  * freeze the controller queue
945                                                  * until our mapping is
946                                                  * returned.
947                                                  */
948                                                 xpt_freeze_simq(sim, 1);
949                                                 dccb->state |= CAM_RELEASE_SIMQ;
950                                         }
951                                         splx(s);
952                                 } else {
953                                         struct bus_dma_segment seg; 
954
955                                         /* Pointer to physical buffer */
956                                         seg.ds_addr =
957                                             (bus_addr_t)csio->data_ptr;
958                                         seg.ds_len = csio->dxfer_len;
959                                         dptexecuteccb(dccb, &seg, 1, 0);
960                                 }
961                         } else {
962                                 struct bus_dma_segment *segs;
963
964                                 if ((ccbh->flags & CAM_DATA_PHYS) != 0)
965                                         panic("dpt_action - Physical "
966                                               "segment pointers "
967                                               "unsupported");
968
969                                 if ((ccbh->flags&CAM_SG_LIST_PHYS)==0)
970                                         panic("dpt_action - Virtual "
971                                               "segment addresses "
972                                               "unsupported");
973
974                                 /* Just use the segments provided */
975                                 segs = (struct bus_dma_segment *)csio->data_ptr;
976                                 dptexecuteccb(dccb, segs, csio->sglist_cnt, 0);
977                         }
978                 } else {
979                         /*
980                          * XXX JGibbs.
981                          * Does it want them both on or both off?
982                          * CAM_DIR_NONE is both on, so this code can
983                          * be removed if this is also what the DPT
984                          * exptects.
985                          */
986                         eccb->DataOut = 0;
987                         eccb->DataIn = 0;
988                         dptexecuteccb(dccb, NULL, 0, 0);
989                 }
990                 break;
991         }
992         case XPT_RESET_DEV:     /* Bus Device Reset the specified SCSI device */
993         case XPT_ABORT:                 /* Abort the specified CCB */
994                 /* XXX Implement */
995                 ccb->ccb_h.status = CAM_REQ_INVALID;
996                 xpt_done(ccb);
997                 break;
998         case XPT_SET_TRAN_SETTINGS:
999         {
1000                 ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
1001                 xpt_done(ccb);  
1002                 break;
1003         }
1004         case XPT_GET_TRAN_SETTINGS:
1005         /* Get default/user set transfer settings for the target */
1006         {
1007                 struct  ccb_trans_settings *cts;
1008                 u_int   target_mask;
1009  
1010                 cts = &ccb->cts;
1011                 target_mask = 0x01 << ccb->ccb_h.target_id;
1012                 if ((cts->flags & CCB_TRANS_USER_SETTINGS) != 0) { 
1013                         cts->flags = CCB_TRANS_DISC_ENB|CCB_TRANS_TAG_ENB;
1014                         cts->bus_width = (dpt->max_id > 7)
1015                                        ? MSG_EXT_WDTR_BUS_8_BIT
1016                                        : MSG_EXT_WDTR_BUS_16_BIT;
1017                         cts->sync_period = 25; /* 10MHz */
1018
1019                         if (cts->sync_period != 0)
1020                                 cts->sync_offset = 15;
1021
1022                         cts->valid = CCB_TRANS_SYNC_RATE_VALID
1023                                    | CCB_TRANS_SYNC_OFFSET_VALID
1024                                    | CCB_TRANS_BUS_WIDTH_VALID
1025                                    | CCB_TRANS_DISC_VALID
1026                                    | CCB_TRANS_TQ_VALID;
1027                         ccb->ccb_h.status = CAM_REQ_CMP;
1028                 } else {
1029                         ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
1030                 }
1031                 xpt_done(ccb);
1032                 break;
1033         }
1034         case XPT_CALC_GEOMETRY:
1035         {
1036                 struct    ccb_calc_geometry *ccg;
1037                 u_int32_t size_mb;
1038                 u_int32_t secs_per_cylinder;
1039                 int       extended;
1040
1041                 /*
1042                  * XXX Use Adaptec translation until I find out how to
1043                  *     get this information from the card.
1044                  */
1045                 ccg = &ccb->ccg;
1046                 size_mb = ccg->volume_size
1047                         / ((1024L * 1024L) / ccg->block_size);
1048                 extended = 1;
1049                 
1050                 if (size_mb > 1024 && extended) {
1051                         ccg->heads = 255;
1052                         ccg->secs_per_track = 63;
1053                 } else {
1054                         ccg->heads = 64;
1055                         ccg->secs_per_track = 32;
1056                 }
1057                 secs_per_cylinder = ccg->heads * ccg->secs_per_track;
1058                 ccg->cylinders = ccg->volume_size / secs_per_cylinder;
1059                 ccb->ccb_h.status = CAM_REQ_CMP;
1060                 xpt_done(ccb);
1061                 break;
1062         }
1063         case XPT_RESET_BUS:             /* Reset the specified SCSI bus */
1064         {
1065                 /* XXX Implement */
1066                 ccb->ccb_h.status = CAM_REQ_CMP;
1067                 xpt_done(ccb);
1068                 break;
1069         }
1070         case XPT_TERM_IO:               /* Terminate the I/O process */
1071                 /* XXX Implement */
1072                 ccb->ccb_h.status = CAM_REQ_INVALID;
1073                 xpt_done(ccb);
1074                 break;
1075         case XPT_PATH_INQ:              /* Path routing inquiry */
1076         {
1077                 struct ccb_pathinq *cpi = &ccb->cpi;
1078                 
1079                 cpi->version_num = 1;
1080                 cpi->hba_inquiry = PI_SDTR_ABLE|PI_TAG_ABLE;
1081                 if (dpt->max_id > 7)
1082                         cpi->hba_inquiry |= PI_WIDE_16;
1083                 cpi->target_sprt = 0;
1084                 cpi->hba_misc = 0;
1085                 cpi->hba_eng_cnt = 0;
1086                 cpi->max_target = dpt->max_id;
1087                 cpi->max_lun = dpt->max_lun;
1088                 cpi->initiator_id = dpt->hostid[cam_sim_bus(sim)];
1089                 cpi->bus_id = cam_sim_bus(sim);
1090                 cpi->base_transfer_speed = 3300;
1091                 strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
1092                 strncpy(cpi->hba_vid, "DPT", HBA_IDLEN);
1093                 strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
1094                 cpi->unit_number = cam_sim_unit(sim);
1095                 cpi->ccb_h.status = CAM_REQ_CMP;
1096                 xpt_done(ccb);
1097                 break;
1098         }
1099         default:
1100                 ccb->ccb_h.status = CAM_REQ_INVALID;
1101                 xpt_done(ccb);
1102                 break;
1103         }
1104 }
1105
1106 /*
1107  * This routine will try to send an EATA command to the DPT HBA.
1108  * It will, by default, try 20,000 times, waiting 50us between tries.
1109  * It returns 0 on success and 1 on failure.
1110  * It is assumed to be called at splcam().
1111  */
1112 static int
1113 dpt_send_eata_command(dpt_softc_t *dpt, eata_ccb_t *cmd_block,
1114                       u_int32_t cmd_busaddr, u_int command, u_int retries,
1115                       u_int ifc, u_int code, u_int code2)
1116 {
1117         u_int   loop;
1118         
1119         if (!retries)
1120                 retries = 20000;
1121
1122         /*
1123          * I hate this polling nonsense. Wish there was a way to tell the DPT
1124          * to go get commands at its own pace,  or to interrupt when ready.
1125          * In the mean time we will measure how many itterations it really
1126          * takes.
1127          */
1128         for (loop = 0; loop < retries; loop++) {
1129                 if ((dpt_inb(dpt, HA_RAUXSTAT) & HA_ABUSY) == 0)
1130                         break;
1131                 else
1132                         DELAY(50);
1133         }
1134
1135         if (loop < retries) {
1136 #ifdef DPT_MEASURE_PERFORMANCE
1137                 if (loop > dpt->performance.max_eata_tries)
1138                         dpt->performance.max_eata_tries = loop;
1139
1140                 if (loop < dpt->performance.min_eata_tries)
1141                         dpt->performance.min_eata_tries = loop;
1142 #endif
1143         } else {
1144 #ifdef DPT_MEASURE_PERFORMANCE
1145                 ++dpt->performance.command_too_busy;
1146 #endif
1147                 return (1);
1148         }
1149
1150         /* The controller is alive, advance the wedge timer */
1151 #ifdef DPT_RESET_HBA
1152         dpt->last_contact = microtime_now;
1153 #endif
1154
1155         if (cmd_block == NULL)
1156                 cmd_busaddr = 0;
1157 #if (BYTE_ORDER == BIG_ENDIAN)
1158         else {
1159                 cmd_busaddr = ((cmd_busaddr >> 24) & 0xFF)
1160                             | ((cmd_busaddr >> 16) & 0xFF)
1161                             | ((cmd_busaddr >> 8) & 0xFF)
1162                             | (cmd_busaddr & 0xFF);
1163         }
1164 #endif
1165         /* And now the address */
1166         dpt_outl(dpt, HA_WDMAADDR, cmd_busaddr);
1167
1168         if (command == EATA_CMD_IMMEDIATE) {
1169                 if (cmd_block == NULL) {
1170                         dpt_outb(dpt, HA_WCODE2, code2);
1171                         dpt_outb(dpt, HA_WCODE, code);
1172                 }
1173                 dpt_outb(dpt, HA_WIFC, ifc);
1174         }
1175         dpt_outb(dpt, HA_WCOMMAND, command);
1176
1177         return (0);
1178 }
1179
1180
1181 /* ==================== Exported Function definitions =======================*/
1182 dpt_softc_t *
1183 dpt_alloc(device_t dev, bus_space_tag_t tag, bus_space_handle_t bsh)
1184 {
1185         dpt_softc_t     *dpt = device_get_softc(dev);
1186         int    i;
1187
1188         bzero(dpt, sizeof(dpt_softc_t));
1189         dpt->tag = tag;
1190         dpt->bsh = bsh;
1191         dpt->unit = device_get_unit(dev);
1192         SLIST_INIT(&dpt->free_dccb_list);
1193         LIST_INIT(&dpt->pending_ccb_list);
1194         TAILQ_INSERT_TAIL(&dpt_softcs, dpt, links);
1195         for (i = 0; i < MAX_CHANNELS; i++)
1196                 dpt->resetlevel[i] = DPT_HA_OK;
1197
1198 #ifdef DPT_MEASURE_PERFORMANCE
1199         dpt_reset_performance(dpt);
1200 #endif /* DPT_MEASURE_PERFORMANCE */
1201         return (dpt);
1202 }
1203
1204 void
1205 dpt_free(struct dpt_softc *dpt)
1206 {
1207         switch (dpt->init_level) {
1208         default:
1209         case 5:
1210                 bus_dmamap_unload(dpt->dccb_dmat, dpt->dccb_dmamap);
1211         case 4:
1212                 bus_dmamem_free(dpt->dccb_dmat, dpt->dpt_dccbs,
1213                                 dpt->dccb_dmamap);
1214                 bus_dmamap_destroy(dpt->dccb_dmat, dpt->dccb_dmamap);
1215         case 3:
1216                 bus_dma_tag_destroy(dpt->dccb_dmat);
1217         case 2:
1218                 bus_dma_tag_destroy(dpt->buffer_dmat);
1219         case 1:
1220         {
1221                 struct sg_map_node *sg_map;
1222
1223                 while ((sg_map = SLIST_FIRST(&dpt->sg_maps)) != NULL) {
1224                         SLIST_REMOVE_HEAD(&dpt->sg_maps, links);
1225                         bus_dmamap_unload(dpt->sg_dmat,
1226                                           sg_map->sg_dmamap);
1227                         bus_dmamem_free(dpt->sg_dmat, sg_map->sg_vaddr,
1228                                         sg_map->sg_dmamap);
1229                         free(sg_map, M_DEVBUF);
1230                 }
1231                 bus_dma_tag_destroy(dpt->sg_dmat);
1232         }
1233         case 0:
1234                 break;
1235         }
1236         TAILQ_REMOVE(&dpt_softcs, dpt, links);
1237 }
1238
1239 static u_int8_t string_sizes[] =
1240 {
1241         sizeof(((dpt_inq_t*)NULL)->vendor),
1242         sizeof(((dpt_inq_t*)NULL)->modelNum),
1243         sizeof(((dpt_inq_t*)NULL)->firmware),
1244         sizeof(((dpt_inq_t*)NULL)->protocol),
1245 };
1246
1247 int
1248 dpt_init(struct dpt_softc *dpt)
1249 {
1250         dpt_conf_t  conf;
1251         struct      sg_map_node *sg_map;
1252         dpt_ccb_t  *dccb;
1253         u_int8_t   *strp;
1254         int         index;
1255         int         i;
1256         int         retval;
1257
1258         dpt->init_level = 0;
1259         SLIST_INIT(&dpt->sg_maps);
1260
1261 #ifdef DPT_RESET_BOARD
1262         printf("dpt%d: resetting HBA\n", dpt->unit);
1263         dpt_outb(dpt, HA_WCOMMAND, EATA_CMD_RESET);
1264         DELAY(750000);
1265         /* XXX Shouldn't we poll a status register or something??? */
1266 #endif
1267         /* DMA tag for our S/G structures.  We allocate in page sized chunks */
1268         if (bus_dma_tag_create(dpt->parent_dmat, /*alignment*/1, /*boundary*/0,
1269                                /*lowaddr*/BUS_SPACE_MAXADDR,
1270                                /*highaddr*/BUS_SPACE_MAXADDR,
1271                                /*filter*/NULL, /*filterarg*/NULL,
1272                                PAGE_SIZE, /*nsegments*/1,
1273                                /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
1274                                /*flags*/0, &dpt->sg_dmat) != 0) {
1275                 goto error_exit;
1276         }
1277
1278         dpt->init_level++;
1279
1280         /*
1281          * We allocate our DPT ccbs as a contiguous array of bus dma'able
1282          * memory.  To get the allocation size, we need to know how many
1283          * ccbs the card supports.  This requires a ccb.  We solve this
1284          * chicken and egg problem by allocating some re-usable S/G space
1285          * up front, and treating it as our status packet, CCB, and target
1286          * memory space for these commands.
1287          */
1288         sg_map = dptallocsgmap(dpt);
1289         if (sg_map == NULL)
1290                 goto error_exit;
1291
1292         dpt->sp = (volatile dpt_sp_t *)sg_map->sg_vaddr;
1293         dccb = (struct dpt_ccb *)(uintptr_t)(volatile void *)&dpt->sp[1];
1294         bzero(dccb, sizeof(*dccb));
1295         dpt->sp_physaddr = sg_map->sg_physaddr;
1296         dccb->eata_ccb.cp_dataDMA =
1297             htonl(sg_map->sg_physaddr + sizeof(dpt_sp_t) + sizeof(*dccb));
1298         dccb->eata_ccb.cp_busaddr = ~0;
1299         dccb->eata_ccb.cp_statDMA = htonl(dpt->sp_physaddr);
1300         dccb->eata_ccb.cp_reqDMA = htonl(dpt->sp_physaddr + sizeof(*dccb)
1301                                        + offsetof(struct dpt_ccb, sense_data));
1302
1303         /* Okay.  Fetch our config */
1304         bzero(&dccb[1], sizeof(conf)); /* data area */
1305         retval = dpt_get_conf(dpt, dccb, sg_map->sg_physaddr + sizeof(dpt_sp_t),
1306                               sizeof(conf), 0xc1, 7, 1);
1307
1308         if (retval != 0) {
1309                 printf("dpt%d: Failed to get board configuration\n", dpt->unit);
1310                 return (retval);
1311         }
1312         bcopy(&dccb[1], &conf, sizeof(conf));
1313
1314         bzero(&dccb[1], sizeof(dpt->board_data));
1315         retval = dpt_get_conf(dpt, dccb, sg_map->sg_physaddr + sizeof(dpt_sp_t),
1316                               sizeof(dpt->board_data), 0, conf.scsi_id0, 0);
1317         if (retval != 0) {
1318                 printf("dpt%d: Failed to get inquiry information\n", dpt->unit);
1319                 return (retval);
1320         }
1321         bcopy(&dccb[1], &dpt->board_data, sizeof(dpt->board_data));
1322
1323         dpt_detect_cache(dpt, dccb, sg_map->sg_physaddr + sizeof(dpt_sp_t),
1324                          (u_int8_t *)&dccb[1]);
1325
1326         switch (ntohl(conf.splen)) {
1327         case DPT_EATA_REVA:
1328                 dpt->EATA_revision = 'a';
1329                 break;
1330         case DPT_EATA_REVB:
1331                 dpt->EATA_revision = 'b';
1332                 break;
1333         case DPT_EATA_REVC:
1334                 dpt->EATA_revision = 'c';
1335                 break;
1336         case DPT_EATA_REVZ:
1337                 dpt->EATA_revision = 'z';
1338                 break;
1339         default:
1340                 dpt->EATA_revision = '?';
1341         }
1342
1343         dpt->max_id      = conf.MAX_ID;
1344         dpt->max_lun     = conf.MAX_LUN;
1345         dpt->irq         = conf.IRQ;
1346         dpt->dma_channel = (8 - conf.DMA_channel) & 7;
1347         dpt->channels    = conf.MAX_CHAN + 1;
1348         dpt->state      |= DPT_HA_OK;
1349         if (conf.SECOND)
1350                 dpt->primary = FALSE;
1351         else
1352                 dpt->primary = TRUE;
1353
1354         dpt->more_support = conf.MORE_support;
1355
1356         if (strncmp(dpt->board_data.firmware, "07G0", 4) >= 0)
1357                 dpt->immediate_support = 1;
1358         else
1359                 dpt->immediate_support = 0;
1360
1361         dpt->broken_INQUIRY = FALSE;
1362
1363         dpt->cplen = ntohl(conf.cplen);
1364         dpt->cppadlen = ntohs(conf.cppadlen);
1365         dpt->max_dccbs = ntohs(conf.queuesiz);
1366
1367         if (dpt->max_dccbs > 256) {
1368                 printf("dpt%d: Max CCBs reduced from %d to "
1369                        "256 due to tag algorithm\n", dpt->unit, dpt->max_dccbs);
1370                 dpt->max_dccbs = 256;
1371         }
1372
1373         dpt->hostid[0] = conf.scsi_id0;
1374         dpt->hostid[1] = conf.scsi_id1;
1375         dpt->hostid[2] = conf.scsi_id2;
1376
1377         if (conf.SG_64K)
1378                 dpt->sgsize = 8192;
1379         else
1380                 dpt->sgsize = ntohs(conf.SGsiz);
1381
1382         /* We can only get 64k buffers, so don't bother to waste space. */
1383         if (dpt->sgsize < 17 || dpt->sgsize > 32)
1384                 dpt->sgsize = 32; 
1385
1386         if (dpt->sgsize > dpt_max_segs)
1387                 dpt->sgsize = dpt_max_segs;
1388         
1389         /* DMA tag for mapping buffers into device visible space. */
1390         if (bus_dma_tag_create(dpt->parent_dmat, /*alignment*/1, /*boundary*/0,
1391                                /*lowaddr*/BUS_SPACE_MAXADDR,
1392                                /*highaddr*/BUS_SPACE_MAXADDR,
1393                                /*filter*/NULL, /*filterarg*/NULL,
1394                                /*maxsize*/MAXBSIZE, /*nsegments*/dpt->sgsize,
1395                                /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
1396                                /*flags*/BUS_DMA_ALLOCNOW,
1397                                &dpt->buffer_dmat) != 0) {
1398                 printf("dpt: bus_dma_tag_create(...,dpt->buffer_dmat) failed\n");
1399                 goto error_exit;
1400         }
1401
1402         dpt->init_level++;
1403
1404         /* DMA tag for our ccb structures and interrupt status packet */
1405         if (bus_dma_tag_create(dpt->parent_dmat, /*alignment*/1, /*boundary*/0,
1406                                /*lowaddr*/BUS_SPACE_MAXADDR,
1407                                /*highaddr*/BUS_SPACE_MAXADDR,
1408                                /*filter*/NULL, /*filterarg*/NULL,
1409                                (dpt->max_dccbs * sizeof(struct dpt_ccb))
1410                                + sizeof(dpt_sp_t),
1411                                /*nsegments*/1,
1412                                /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
1413                                /*flags*/0, &dpt->dccb_dmat) != 0) {
1414                 printf("dpt: bus_dma_tag_create(...,dpt->dccb_dmat) failed\n");
1415                 goto error_exit;
1416         }
1417
1418         dpt->init_level++;
1419
1420         /* Allocation for our ccbs and interrupt status packet */
1421         if (bus_dmamem_alloc(dpt->dccb_dmat, (void **)&dpt->dpt_dccbs,
1422                              BUS_DMA_NOWAIT, &dpt->dccb_dmamap) != 0) {
1423                 printf("dpt: bus_dmamem_alloc(dpt->dccb_dmat,...) failed\n");
1424                 goto error_exit;
1425         }
1426
1427         dpt->init_level++;
1428
1429         /* And permanently map them */
1430         bus_dmamap_load(dpt->dccb_dmat, dpt->dccb_dmamap,
1431                         dpt->dpt_dccbs,
1432                         (dpt->max_dccbs * sizeof(struct dpt_ccb))
1433                         + sizeof(dpt_sp_t),
1434                         dptmapmem, &dpt->dpt_ccb_busbase, /*flags*/0);
1435
1436         /* Clear them out. */
1437         bzero(dpt->dpt_dccbs,
1438               (dpt->max_dccbs * sizeof(struct dpt_ccb)) + sizeof(dpt_sp_t));
1439
1440         dpt->dpt_ccb_busend = dpt->dpt_ccb_busbase;
1441
1442         dpt->sp = (dpt_sp_t*)&dpt->dpt_dccbs[dpt->max_dccbs];
1443         dpt->sp_physaddr = dpt->dpt_ccb_busbase
1444                          + (dpt->max_dccbs * sizeof(dpt_ccb_t));
1445         dpt->init_level++;
1446
1447         /* Allocate our first batch of ccbs */
1448         if (dptallocccbs(dpt) == 0) {
1449                 printf("dpt: dptallocccbs(dpt) == 0\n");
1450                 return (2);
1451         }
1452
1453         /* Prepare for Target Mode */
1454         dpt->target_mode_enabled = 1;
1455
1456         /* Nuke excess spaces from inquiry information */
1457         strp = dpt->board_data.vendor;
1458         for (i = 0; i < sizeof(string_sizes); i++) {
1459                 index = string_sizes[i] - 1;    
1460                 while (index && (strp[index] == ' '))
1461                         strp[index--] = '\0';
1462                 strp += string_sizes[i];
1463         }
1464
1465         printf("dpt%d: %.8s %.16s FW Rev. %.4s, ",
1466                dpt->unit, dpt->board_data.vendor,
1467                dpt->board_data.modelNum, dpt->board_data.firmware);
1468
1469         printf("%d channel%s, ", dpt->channels, dpt->channels > 1 ? "s" : "");
1470
1471         if (dpt->cache_type != DPT_NO_CACHE
1472          && dpt->cache_size != 0) {
1473                 printf("%s Cache, ",
1474                        dpt->cache_type == DPT_CACHE_WRITETHROUGH
1475                      ? "Write-Through" : "Write-Back");
1476         }
1477
1478         printf("%d CCBs\n", dpt->max_dccbs);
1479         return (0);
1480                 
1481 error_exit:
1482         return (1);
1483 }
1484
1485 int
1486 dpt_attach(dpt_softc_t *dpt)
1487 {
1488         struct cam_devq *devq;
1489         int i;
1490
1491         /*
1492          * Create the device queue for our SIM.
1493          */
1494         devq = cam_simq_alloc(dpt->max_dccbs);
1495         if (devq == NULL)
1496                 return (0);
1497
1498         for (i = 0; i < dpt->channels; i++) {
1499                 /*
1500                  * Construct our SIM entry
1501                  */
1502                 dpt->sims[i] = cam_sim_alloc(dpt_action, dpt_poll, "dpt",
1503                                              dpt, dpt->unit, /*untagged*/2,
1504                                              /*tagged*/dpt->max_dccbs, devq);
1505                 if (xpt_bus_register(dpt->sims[i], i) != CAM_SUCCESS) {
1506                         cam_sim_free(dpt->sims[i], /*free_devq*/i == 0);
1507                         break;
1508                 }
1509
1510                 if (xpt_create_path(&dpt->paths[i], /*periph*/NULL,
1511                                     cam_sim_path(dpt->sims[i]),
1512                                     CAM_TARGET_WILDCARD,
1513                                     CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1514                         xpt_bus_deregister(cam_sim_path(dpt->sims[i]));
1515                         cam_sim_free(dpt->sims[i], /*free_devq*/i == 0);
1516                         break;
1517                 }
1518
1519         }
1520         if (i > 0)
1521                 EVENTHANDLER_REGISTER(shutdown_final, dptshutdown,
1522                                       dpt, SHUTDOWN_PRI_DEFAULT);
1523         return (i);
1524 }
1525
1526
1527 /*
1528  * This is the interrupt handler for the DPT driver.
1529  */
1530 void
1531 dpt_intr(void *arg)
1532 {
1533         dpt_softc_t    *dpt;
1534         dpt_ccb_t      *dccb;
1535         union ccb      *ccb;
1536         u_int           status;
1537         u_int           aux_status;
1538         u_int           hba_stat;
1539         u_int           scsi_stat;
1540         u_int32_t       residue_len;    /* Number of bytes not transferred */
1541
1542         dpt = (dpt_softc_t *)arg;
1543
1544         /* First order of business is to check if this interrupt is for us */
1545         while (((aux_status = dpt_inb(dpt, HA_RAUXSTAT)) & HA_AIRQ) != 0) {
1546
1547                 /*
1548                  * What we want to do now, is to capture the status, all of it,
1549                  * move it where it belongs, wake up whoever sleeps waiting to
1550                  * process this result, and get out of here.
1551                  */
1552                 if (dpt->sp->ccb_busaddr < dpt->dpt_ccb_busbase
1553                  || dpt->sp->ccb_busaddr >= dpt->dpt_ccb_busend) {
1554                         printf("Encountered bogus status packet\n");
1555                         status = dpt_inb(dpt, HA_RSTATUS);
1556                         return;
1557                 }
1558
1559                 dccb = dptccbptov(dpt, dpt->sp->ccb_busaddr);
1560
1561                 dpt->sp->ccb_busaddr = ~0;
1562
1563                 /* Ignore status packets with EOC not set */
1564                 if (dpt->sp->EOC == 0) {
1565                         printf("dpt%d ERROR: Request %d received with "
1566                                "clear EOC.\n     Marking as LOST.\n",
1567                                dpt->unit, dccb->transaction_id);
1568
1569 #ifdef DPT_HANDLE_TIMEOUTS
1570                         dccb->state |= DPT_CCB_STATE_MARKED_LOST;
1571 #endif
1572                         /* This CLEARS the interrupt! */
1573                         status = dpt_inb(dpt, HA_RSTATUS);
1574                         continue;
1575                 }
1576                 dpt->sp->EOC = 0;
1577
1578                 /*
1579                  * Double buffer the status information so the hardware can
1580                  * work on updating the status packet while we decifer the
1581                  * one we were just interrupted for.
1582                  * According to Mark Salyzyn, we only need few pieces of it.
1583                  */
1584                 hba_stat = dpt->sp->hba_stat;
1585                 scsi_stat = dpt->sp->scsi_stat;
1586                 residue_len = dpt->sp->residue_len;
1587
1588                 /* Clear interrupts, check for error */
1589                 if ((status = dpt_inb(dpt, HA_RSTATUS)) & HA_SERROR) {
1590                         /*
1591                          * Error Condition. Check for magic cookie. Exit
1592                          * this test on earliest sign of non-reset condition
1593                          */
1594
1595                         /* Check that this is not a board reset interrupt */
1596                         if (dpt_just_reset(dpt)) {
1597                                 printf("dpt%d: HBA rebooted.\n"
1598                                        "      All transactions should be "
1599                                        "resubmitted\n",
1600                                        dpt->unit);
1601
1602                                 printf("dpt%d: >>---->>  This is incomplete, "
1603                                        "fix me....  <<----<<", dpt->unit);
1604                                 panic("DPT Rebooted");
1605
1606                         }
1607                 }
1608                 /* Process CCB */
1609                 ccb = dccb->ccb;
1610                 untimeout(dpttimeout, dccb, ccb->ccb_h.timeout_ch);
1611                 if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
1612                         bus_dmasync_op_t op;
1613
1614                         if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN)
1615                                 op = BUS_DMASYNC_POSTREAD;
1616                         else
1617                                 op = BUS_DMASYNC_POSTWRITE;
1618                         bus_dmamap_sync(dpt->buffer_dmat, dccb->dmamap, op);
1619                         bus_dmamap_unload(dpt->buffer_dmat, dccb->dmamap);
1620                 }
1621
1622                 /* Common Case inline... */
1623                 if (hba_stat == HA_NO_ERROR) {
1624                         ccb->csio.scsi_status = scsi_stat;
1625                         ccb->ccb_h.status = 0;
1626                         switch (scsi_stat) {
1627                         case SCSI_STATUS_OK:
1628                                 ccb->ccb_h.status |= CAM_REQ_CMP;
1629                                 break;
1630                         case SCSI_STATUS_CHECK_COND:
1631                         case SCSI_STATUS_CMD_TERMINATED:
1632                                 bcopy(&dccb->sense_data, &ccb->csio.sense_data,
1633                                       ccb->csio.sense_len);
1634                                 ccb->ccb_h.status |= CAM_AUTOSNS_VALID;
1635                                 /* FALLTHROUGH */
1636                         default:
1637                                 ccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
1638                                 /* XXX Freeze DevQ */
1639                                 break;
1640                         }
1641                         ccb->csio.resid = residue_len;
1642                         dptfreeccb(dpt, dccb);
1643                         xpt_done(ccb);
1644                 } else {
1645                         dptprocesserror(dpt, dccb, ccb, hba_stat, scsi_stat,
1646                                         residue_len);
1647                 }
1648         }
1649 }
1650
1651 static void
1652 dptprocesserror(dpt_softc_t *dpt, dpt_ccb_t *dccb, union ccb *ccb,
1653                 u_int hba_stat, u_int scsi_stat, u_int32_t resid)
1654 {
1655         ccb->csio.resid = resid;
1656         switch (hba_stat) {
1657         case HA_ERR_SEL_TO:
1658                 ccb->ccb_h.status = CAM_SEL_TIMEOUT;
1659                 break;
1660         case HA_ERR_CMD_TO:
1661                 ccb->ccb_h.status = CAM_CMD_TIMEOUT;
1662                 break;
1663         case HA_SCSIBUS_RESET:
1664         case HA_HBA_POWER_UP:   /* Similar effect to a bus reset??? */
1665                 ccb->ccb_h.status = CAM_SCSI_BUS_RESET;
1666                 break;
1667         case HA_CP_ABORTED:
1668         case HA_CP_RESET:       /* XXX ??? */
1669         case HA_CP_ABORT_NA:    /* XXX ??? */
1670         case HA_CP_RESET_NA:    /* XXX ??? */
1671                 if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INPROG)
1672                         ccb->ccb_h.status = CAM_REQ_ABORTED;
1673                 break;
1674         case HA_PCI_PARITY:
1675         case HA_PCI_MABORT:
1676         case HA_PCI_TABORT:
1677         case HA_PCI_STABORT:
1678         case HA_BUS_PARITY:
1679         case HA_PARITY_ERR:
1680         case HA_ECC_ERR:
1681                 ccb->ccb_h.status = CAM_UNCOR_PARITY;
1682                 break;
1683         case HA_UNX_MSGRJCT:
1684                 ccb->ccb_h.status = CAM_MSG_REJECT_REC;
1685                 break;
1686         case HA_UNX_BUSPHASE:
1687                 ccb->ccb_h.status = CAM_SEQUENCE_FAIL;
1688                 break;
1689         case HA_UNX_BUS_FREE:
1690                 ccb->ccb_h.status = CAM_UNEXP_BUSFREE;
1691                 break;
1692         case HA_SCSI_HUNG:
1693         case HA_RESET_STUCK:
1694                 /*
1695                  * Dead???  Can the controller get unstuck
1696                  * from these conditions
1697                  */
1698                 ccb->ccb_h.status = CAM_NO_HBA;
1699                 break;
1700         case HA_RSENSE_FAIL:
1701                 ccb->ccb_h.status = CAM_AUTOSENSE_FAIL;
1702                 break;
1703         default:
1704                 printf("dpt%d: Undocumented Error %x\n", dpt->unit, hba_stat);
1705                 printf("Please mail this message to shimon@simon-shapiro.org\n");
1706                 ccb->ccb_h.status = CAM_REQ_CMP_ERR;
1707                 break;
1708         }
1709         dptfreeccb(dpt, dccb);
1710         xpt_done(ccb);
1711 }
1712
1713 static void
1714 dpttimeout(void *arg)
1715 {
1716         struct dpt_ccb   *dccb;
1717         union  ccb       *ccb;
1718         struct dpt_softc *dpt;
1719         int               s;
1720
1721         dccb = (struct dpt_ccb *)arg;
1722         ccb = dccb->ccb;
1723         dpt = (struct dpt_softc *)ccb->ccb_h.ccb_dpt_ptr;
1724         xpt_print_path(ccb->ccb_h.path);
1725         printf("CCB %p - timed out\n", (void *)dccb);
1726
1727         s = splcam();
1728
1729         /*
1730          * Try to clear any pending jobs.  FreeBSD will loose interrupts,
1731          * leaving the controller suspended, and commands timed-out.
1732          * By calling the interrupt handler, any command thus stuck will be
1733          * completed.
1734          */
1735         dpt_intr(dpt);
1736         
1737         if ((dccb->state & DCCB_ACTIVE) == 0) {
1738                 xpt_print_path(ccb->ccb_h.path);
1739                 printf("CCB %p - timed out CCB already completed\n",
1740                        (void *)dccb);
1741                 splx(s);
1742                 return;
1743         }
1744
1745         /* Abort this particular command.  Leave all others running */
1746         dpt_send_immediate(dpt, &dccb->eata_ccb, dccb->eata_ccb.cp_busaddr,
1747                            /*retries*/20000, EATA_SPECIFIC_ABORT, 0, 0);
1748         ccb->ccb_h.status = CAM_CMD_TIMEOUT;
1749         splx(s);
1750 }
1751
1752 /*
1753  * Shutdown the controller and ensure that the cache is completely flushed.
1754  * Called from the shutdown_final event after all disk access has completed.
1755  */
1756 static void
1757 dptshutdown(void *arg, int howto)
1758 {
1759         dpt_softc_t *dpt;
1760
1761         dpt = (dpt_softc_t *)arg;
1762
1763         printf("dpt%d: Shutting down (mode %x) HBA.     Please wait...\n",
1764                dpt->unit, howto);
1765
1766         /*
1767          * What we do for a shutdown, is give the DPT early power loss warning
1768          */
1769         dpt_send_immediate(dpt, NULL, 0, EATA_POWER_OFF_WARN, 0, 0, 0);
1770         DELAY(1000 * 1000 * 5);
1771         printf("dpt%d: Controller was warned of shutdown and is now "
1772                "disabled\n", dpt->unit);
1773 }
1774
1775 /*============================================================================*/
1776
1777 #if 0
1778 #ifdef DPT_RESET_HBA
1779
1780 /*
1781 **      Function name : dpt_reset_hba
1782 **
1783 **      Description : Reset the HBA and properly discard all pending work
1784 **      Input :       Softc
1785 **      Output :      Nothing
1786 */
1787 static void
1788 dpt_reset_hba(dpt_softc_t *dpt)
1789 {
1790         eata_ccb_t       *ccb;
1791         int               ospl;
1792         dpt_ccb_t         dccb, *dccbp;
1793         int               result;
1794         struct scsi_xfer *xs;
1795     
1796         /* Prepare a control block.  The SCSI command part is immaterial */
1797         dccb.xs = NULL;
1798         dccb.flags = 0;
1799         dccb.state = DPT_CCB_STATE_NEW;
1800         dccb.std_callback = NULL;
1801         dccb.wrbuff_callback = NULL;
1802
1803         ccb = &dccb.eata_ccb;
1804         ccb->CP_OpCode = EATA_CMD_RESET;
1805         ccb->SCSI_Reset = 0;
1806         ccb->HBA_Init = 1;
1807         ccb->Auto_Req_Sen = 1;
1808         ccb->cp_id = 0; /* Should be ignored */
1809         ccb->DataIn = 1;
1810         ccb->DataOut = 0;
1811         ccb->Interpret = 1;
1812         ccb->reqlen = htonl(sizeof(struct scsi_sense_data));
1813         ccb->cp_statDMA = htonl(vtophys(&ccb->cp_statDMA));
1814         ccb->cp_reqDMA = htonl(vtophys(&ccb->cp_reqDMA));
1815         ccb->cp_viraddr = (u_int32_t) & ccb;
1816
1817         ccb->cp_msg[0] = HA_IDENTIFY_MSG | HA_DISCO_RECO;
1818         ccb->cp_scsi_cmd = 0;  /* Should be ignored */
1819
1820         /* Lock up the submitted queue.  We are very persistant here */
1821         ospl = splcam();
1822         while (dpt->queue_status & DPT_SUBMITTED_QUEUE_ACTIVE) {
1823                 DELAY(100);
1824         }
1825         
1826         dpt->queue_status |= DPT_SUBMITTED_QUEUE_ACTIVE;
1827         splx(ospl);
1828
1829         /* Send the RESET message */
1830         if ((result = dpt_send_eata_command(dpt, &dccb.eata_ccb,
1831                                             EATA_CMD_RESET, 0, 0, 0, 0)) != 0) {
1832                 printf("dpt%d: Failed to send the RESET message.\n"
1833                        "      Trying cold boot (ouch!)\n", dpt->unit);
1834         
1835         
1836                 if ((result = dpt_send_eata_command(dpt, &dccb.eata_ccb,
1837                                                     EATA_COLD_BOOT, 0, 0,
1838                                                     0, 0)) != 0) {
1839                         panic("dpt%d:  Faild to cold boot the HBA\n",
1840                               dpt->unit);
1841                 }
1842 #ifdef DPT_MEASURE_PERFORMANCE
1843                 dpt->performance.cold_boots++;
1844 #endif /* DPT_MEASURE_PERFORMANCE */
1845         }
1846         
1847 #ifdef DPT_MEASURE_PERFORMANCE
1848         dpt->performance.warm_starts++;
1849 #endif /* DPT_MEASURE_PERFORMANCE */
1850         
1851         printf("dpt%d:  Aborting pending requests.  O/S should re-submit\n",
1852                dpt->unit);
1853
1854         while ((dccbp = TAILQ_FIRST(&dpt->completed_ccbs)) != NULL) {
1855                 struct scsi_xfer *xs = dccbp->xs;
1856             
1857                 /* Not all transactions have xs structs */
1858                 if (xs != NULL) {
1859                         /* Tell the kernel proper this did not complete well */
1860                         xs->error |= XS_SELTIMEOUT;
1861                         xs->flags |= SCSI_ITSDONE;
1862                         scsi_done(xs);
1863                 }
1864             
1865                 dpt_Qremove_submitted(dpt, dccbp);
1866         
1867                 /* Remember, Callbacks are NOT in the standard queue */
1868                 if (dccbp->std_callback != NULL) {
1869                         (dccbp->std_callback)(dpt, dccbp->eata_ccb.cp_channel,
1870                                                dccbp);
1871                 } else {
1872                         ospl = splcam();
1873                         dpt_Qpush_free(dpt, dccbp);
1874                         splx(ospl);
1875                 }
1876         }
1877
1878         printf("dpt%d: reset done aborting all pending commands\n", dpt->unit);
1879         dpt->queue_status &= ~DPT_SUBMITTED_QUEUE_ACTIVE;
1880 }
1881
1882 #endif /* DPT_RESET_HBA */ 
1883
1884 /*
1885  * Build a Command Block for target mode READ/WRITE BUFFER,
1886  * with the ``sync'' bit ON.
1887  *
1888  * Although the length and offset are 24 bit fields in the command, they cannot
1889  * exceed 8192 bytes, so we take them as short integers andcheck their range.
1890  * If they are sensless, we round them to zero offset, maximum length and
1891  * complain.
1892  */
1893
1894 static void
1895 dpt_target_ccb(dpt_softc_t * dpt, int bus, u_int8_t target, u_int8_t lun,
1896                dpt_ccb_t * ccb, int mode, u_int8_t command,
1897                u_int16_t length, u_int16_t offset)
1898 {
1899         eata_ccb_t     *cp;
1900         int             ospl;
1901
1902         if ((length + offset) > DPT_MAX_TARGET_MODE_BUFFER_SIZE) {
1903                 printf("dpt%d:  Length of %d, and offset of %d are wrong\n",
1904                        dpt->unit, length, offset);
1905                 length = DPT_MAX_TARGET_MODE_BUFFER_SIZE;
1906                 offset = 0;
1907         }
1908         ccb->xs = NULL;
1909         ccb->flags = 0;
1910         ccb->state = DPT_CCB_STATE_NEW;
1911         ccb->std_callback = (ccb_callback) dpt_target_done;
1912         ccb->wrbuff_callback = NULL;
1913
1914         cp = &ccb->eata_ccb;
1915         cp->CP_OpCode = EATA_CMD_DMA_SEND_CP;
1916         cp->SCSI_Reset = 0;
1917         cp->HBA_Init = 0;
1918         cp->Auto_Req_Sen = 1;
1919         cp->cp_id = target;
1920         cp->DataIn = 1;
1921         cp->DataOut = 0;
1922         cp->Interpret = 0;
1923         cp->reqlen = htonl(sizeof(struct scsi_sense_data));
1924         cp->cp_statDMA = htonl(vtophys(&cp->cp_statDMA));
1925         cp->cp_reqDMA = htonl(vtophys(&cp->cp_reqDMA));
1926         cp->cp_viraddr = (u_int32_t) & ccb;
1927
1928         cp->cp_msg[0] = HA_IDENTIFY_MSG | HA_DISCO_RECO;
1929
1930         cp->cp_scsi_cmd = command;
1931         cp->cp_cdb[1] = (u_int8_t) (mode & SCSI_TM_MODE_MASK);
1932         cp->cp_lun = lun;       /* Order is important here! */
1933         cp->cp_cdb[2] = 0x00;   /* Buffer Id, only 1 :-( */
1934         cp->cp_cdb[3] = (length >> 16) & 0xFF;  /* Buffer offset MSB */
1935         cp->cp_cdb[4] = (length >> 8) & 0xFF;
1936         cp->cp_cdb[5] = length & 0xFF;
1937         cp->cp_cdb[6] = (length >> 16) & 0xFF;  /* Length MSB */
1938         cp->cp_cdb[7] = (length >> 8) & 0xFF;
1939         cp->cp_cdb[8] = length & 0xFF;  /* Length LSB */
1940         cp->cp_cdb[9] = 0;      /* No sync, no match bits */
1941
1942         /*
1943          * This could be optimized to live in dpt_register_buffer.
1944          * We keep it here, just in case the kernel decides to reallocate pages
1945          */
1946         if (dpt_scatter_gather(dpt, ccb, DPT_RW_BUFFER_SIZE,
1947                                dpt->rw_buffer[bus][target][lun])) {
1948                 printf("dpt%d: Failed to setup Scatter/Gather for "
1949                        "Target-Mode buffer\n", dpt->unit);
1950         }
1951 }
1952
1953 /* Setup a target mode READ command */
1954
1955 static void
1956 dpt_set_target(int redo, dpt_softc_t * dpt,
1957                u_int8_t bus, u_int8_t target, u_int8_t lun, int mode,
1958                u_int16_t length, u_int16_t offset, dpt_ccb_t * ccb)
1959 {
1960         int ospl;
1961
1962         if (dpt->target_mode_enabled) {
1963                 ospl = splcam();
1964
1965                 if (!redo)
1966                         dpt_target_ccb(dpt, bus, target, lun, ccb, mode,
1967                                        SCSI_TM_READ_BUFFER, length, offset);
1968
1969                 ccb->transaction_id = ++dpt->commands_processed;
1970
1971 #ifdef DPT_MEASURE_PERFORMANCE
1972                 dpt->performance.command_count[ccb->eata_ccb.cp_scsi_cmd]++;
1973                 ccb->command_started = microtime_now;
1974 #endif
1975                 dpt_Qadd_waiting(dpt, ccb);
1976                 dpt_sched_queue(dpt);
1977
1978                 splx(ospl);
1979         } else {
1980                 printf("dpt%d:  Target Mode Request, but Target Mode is OFF\n",
1981                        dpt->unit);
1982         }
1983 }
1984
1985 /*
1986  * Schedule a buffer to be sent to another target.
1987  * The work will be scheduled and the callback provided will be called when
1988  * the work is actually done.
1989  *
1990  * Please NOTE:  ``Anyone'' can send a buffer, but only registered clients
1991  * get notified of receipt of buffers.
1992  */
1993
1994 int
1995 dpt_send_buffer(int unit, u_int8_t channel, u_int8_t target, u_int8_t lun,
1996                 u_int8_t mode, u_int16_t length, u_int16_t offset, void *data,
1997                 buff_wr_done callback)
1998 {
1999         dpt_softc_t    *dpt;
2000         dpt_ccb_t      *ccb = NULL;
2001         int             ospl;
2002
2003         /* This is an external call.  Be a bit paranoid */
2004         for (dpt = TAILQ_FIRST(&dpt_softc_list);
2005              dpt != NULL;
2006              dpt = TAILQ_NEXT(dpt, links)) {
2007                 if (dpt->unit == unit)
2008                         goto valid_unit;
2009         }
2010
2011         return (INVALID_UNIT);
2012
2013 valid_unit:
2014
2015         if (dpt->target_mode_enabled) {
2016                 if ((channel >= dpt->channels) || (target > dpt->max_id) ||
2017                     (lun > dpt->max_lun)) {
2018                         return (INVALID_SENDER);
2019                 }
2020                 if ((dpt->rw_buffer[channel][target][lun] == NULL) ||
2021                     (dpt->buffer_receiver[channel][target][lun] == NULL))
2022                         return (NOT_REGISTERED);
2023
2024                 ospl = splsoftcam();
2025                 /* Process the free list */
2026                 if ((TAILQ_EMPTY(&dpt->free_ccbs)) && dpt_alloc_freelist(dpt)) {
2027                         printf("dpt%d ERROR: Cannot allocate any more free CCB's.\n"
2028                                "             Please try later\n",
2029                                dpt->unit);
2030                         splx(ospl);
2031                         return (NO_RESOURCES);
2032                 }
2033                 /* Now grab the newest CCB */
2034                 if ((ccb = dpt_Qpop_free(dpt)) == NULL) {
2035                         splx(ospl);
2036                         panic("dpt%d: Got a NULL CCB from pop_free()\n", dpt->unit);
2037                 }
2038                 splx(ospl);
2039
2040                 bcopy(dpt->rw_buffer[channel][target][lun] + offset, data, length);
2041                 dpt_target_ccb(dpt, channel, target, lun, ccb, mode, 
2042                                            SCSI_TM_WRITE_BUFFER,
2043                                            length, offset);
2044                 ccb->std_callback = (ccb_callback) callback; /* Potential trouble */
2045
2046                 ospl = splcam();
2047                 ccb->transaction_id = ++dpt->commands_processed;
2048
2049 #ifdef DPT_MEASURE_PERFORMANCE
2050                 dpt->performance.command_count[ccb->eata_ccb.cp_scsi_cmd]++;
2051                 ccb->command_started = microtime_now;
2052 #endif
2053                 dpt_Qadd_waiting(dpt, ccb);
2054                 dpt_sched_queue(dpt);
2055
2056                 splx(ospl);
2057                 return (0);
2058         }
2059         return (DRIVER_DOWN);
2060 }
2061
2062 static void
2063 dpt_target_done(dpt_softc_t * dpt, int bus, dpt_ccb_t * ccb)
2064 {
2065         int             ospl;
2066         eata_ccb_t     *cp;
2067
2068         cp = &ccb->eata_ccb;
2069
2070         /*
2071          * Remove the CCB from the waiting queue.
2072          *  We do NOT put it back on the free, etc., queues as it is a special
2073          * ccb, owned by the dpt_softc of this unit.
2074          */
2075         ospl = splsoftcam();
2076         dpt_Qremove_completed(dpt, ccb);
2077         splx(ospl);
2078
2079 #define br_channel           (ccb->eata_ccb.cp_channel)
2080 #define br_target            (ccb->eata_ccb.cp_id)
2081 #define br_lun               (ccb->eata_ccb.cp_LUN)
2082 #define br_index             [br_channel][br_target][br_lun]
2083 #define read_buffer_callback (dpt->buffer_receiver br_index )
2084 #define read_buffer          (dpt->rw_buffer[br_channel][br_target][br_lun])
2085 #define cb(offset)           (ccb->eata_ccb.cp_cdb[offset])
2086 #define br_offset            ((cb(3) << 16) | (cb(4) << 8) | cb(5))
2087 #define br_length            ((cb(6) << 16) | (cb(7) << 8) | cb(8))
2088
2089         /* Different reasons for being here, you know... */
2090         switch (ccb->eata_ccb.cp_scsi_cmd) {
2091         case SCSI_TM_READ_BUFFER:
2092                 if (read_buffer_callback != NULL) {
2093                         /* This is a buffer generated by a kernel process */
2094                         read_buffer_callback(dpt->unit, br_channel,
2095                                              br_target, br_lun,
2096                                              read_buffer,
2097                                              br_offset, br_length);
2098                 } else {
2099                         /*
2100                          * This is a buffer waited for by a user (sleeping)
2101                          * command
2102                          */
2103                         wakeup(ccb);
2104                 }
2105
2106                 /* We ALWAYS re-issue the same command; args are don't-care  */
2107                 dpt_set_target(1, 0, 0, 0, 0, 0, 0, 0, 0);
2108                 break;
2109
2110         case SCSI_TM_WRITE_BUFFER:
2111                 (ccb->wrbuff_callback) (dpt->unit, br_channel, br_target,
2112                                         br_offset, br_length,
2113                                         br_lun, ccb->status_packet.hba_stat);
2114                 break;
2115         default:
2116                 printf("dpt%d:  %s is an unsupported command for target mode\n",
2117                        dpt->unit, scsi_cmd_name(ccb->eata_ccb.cp_scsi_cmd));
2118         }
2119         ospl = splsoftcam();
2120         dpt->target_ccb[br_channel][br_target][br_lun] = NULL;
2121         dpt_Qpush_free(dpt, ccb);
2122         splx(ospl);
2123 }
2124
2125
2126 /*
2127  * Use this function to register a client for a buffer read target operation.
2128  * The function you register will be called every time a buffer is received
2129  * by the target mode code.
2130  */
2131 dpt_rb_t
2132 dpt_register_buffer(int unit, u_int8_t channel, u_int8_t target, u_int8_t lun,
2133                     u_int8_t mode, u_int16_t length, u_int16_t offset,
2134                     dpt_rec_buff callback, dpt_rb_op_t op)
2135 {
2136         dpt_softc_t    *dpt;
2137         dpt_ccb_t      *ccb = NULL;
2138         int             ospl;
2139
2140         for (dpt = TAILQ_FIRST(&dpt_softc_list);
2141              dpt != NULL;
2142              dpt = TAILQ_NEXT(dpt, links)) {
2143                 if (dpt->unit == unit)
2144                         goto valid_unit;
2145         }
2146
2147         return (INVALID_UNIT);
2148
2149 valid_unit:
2150
2151         if (dpt->state & DPT_HA_SHUTDOWN_ACTIVE)
2152                 return (DRIVER_DOWN);
2153
2154         if ((channel > (dpt->channels - 1)) || (target > (dpt->max_id - 1)) ||
2155             (lun > (dpt->max_lun - 1)))
2156                 return (INVALID_SENDER);
2157
2158         if (dpt->buffer_receiver[channel][target][lun] == NULL) {
2159                 if (op == REGISTER_BUFFER) {
2160                         /* Assign the requested callback */
2161                         dpt->buffer_receiver[channel][target][lun] = callback;
2162                         /* Get a CCB */
2163                         ospl = splsoftcam();
2164
2165                         /* Process the free list */
2166                         if ((TAILQ_EMPTY(&dpt->free_ccbs)) && dpt_alloc_freelist(dpt)) {
2167                                 printf("dpt%d ERROR: Cannot allocate any more free CCB's.\n"
2168                                        "             Please try later\n",
2169                                        dpt->unit);
2170                                 splx(ospl);
2171                                 return (NO_RESOURCES);
2172                         }
2173                         /* Now grab the newest CCB */
2174                         if ((ccb = dpt_Qpop_free(dpt)) == NULL) {
2175                                 splx(ospl);
2176                                 panic("dpt%d: Got a NULL CCB from pop_free()\n",
2177                                       dpt->unit);
2178                         }
2179                         splx(ospl);
2180
2181                         /* Clean up the leftover of the previous tenant */
2182                         ccb->status = DPT_CCB_STATE_NEW;
2183                         dpt->target_ccb[channel][target][lun] = ccb;
2184
2185                         dpt->rw_buffer[channel][target][lun] =
2186                                 malloc(DPT_RW_BUFFER_SIZE, M_DEVBUF, M_NOWAIT);
2187                         if (dpt->rw_buffer[channel][target][lun] == NULL) {
2188                                 printf("dpt%d: Failed to allocate "
2189                                        "Target-Mode buffer\n", dpt->unit);
2190                                 ospl = splsoftcam();
2191                                 dpt_Qpush_free(dpt, ccb);
2192                                 splx(ospl);
2193                                 return (NO_RESOURCES);
2194                         }
2195                         dpt_set_target(0, dpt, channel, target, lun, mode,
2196                                        length, offset, ccb);
2197                         return (SUCCESSFULLY_REGISTERED);
2198                 } else
2199                         return (NOT_REGISTERED);
2200         } else {
2201                 if (op == REGISTER_BUFFER) {
2202                         if (dpt->buffer_receiver[channel][target][lun] == callback)
2203                                 return (ALREADY_REGISTERED);
2204                         else
2205                                 return (REGISTERED_TO_ANOTHER);
2206                 } else {
2207                         if (dpt->buffer_receiver[channel][target][lun] == callback) {
2208                                 dpt->buffer_receiver[channel][target][lun] = NULL;
2209                                 ospl = splsoftcam();
2210                                 dpt_Qpush_free(dpt, ccb);
2211                                 splx(ospl);
2212                                 free(dpt->rw_buffer[channel][target][lun], M_DEVBUF);
2213                                 return (SUCCESSFULLY_REGISTERED);
2214                         } else
2215                                 return (INVALID_CALLBACK);
2216                 }
2217
2218         }
2219 }
2220
2221 /* Return the state of the blinking DPT LED's */
2222 u_int8_t
2223 dpt_blinking_led(dpt_softc_t * dpt)
2224 {
2225         int             ndx;
2226         int             ospl;
2227         u_int32_t       state;
2228         u_int32_t       previous;
2229         u_int8_t        result;
2230
2231         ospl = splcam();
2232
2233         result = 0;
2234
2235         for (ndx = 0, state = 0, previous = 0;
2236              (ndx < 10) && (state != previous);
2237              ndx++) {
2238                 previous = state;
2239                 state = dpt_inl(dpt, 1);
2240         }
2241
2242         if ((state == previous) && (state == DPT_BLINK_INDICATOR))
2243                 result = dpt_inb(dpt, 5);
2244
2245         splx(ospl);
2246         return (result);
2247 }
2248
2249 /*
2250  * Execute a command which did not come from the kernel's SCSI layer.
2251  * The only way to map user commands to bus and target is to comply with the
2252  * standard DPT wire-down scheme:
2253  */
2254 int
2255 dpt_user_cmd(dpt_softc_t * dpt, eata_pt_t * user_cmd,
2256              caddr_t cmdarg, int minor_no)
2257 {
2258         dpt_ccb_t *ccb;
2259         void      *data;
2260         int        channel, target, lun;
2261         int        huh;
2262         int        result;
2263         int        ospl;
2264         int        submitted;
2265
2266         data = NULL;
2267         channel = minor2hba(minor_no);
2268         target = minor2target(minor_no);
2269         lun = minor2lun(minor_no);
2270
2271         if ((channel > (dpt->channels - 1))
2272          || (target > dpt->max_id)
2273          || (lun > dpt->max_lun))
2274                 return (ENXIO);
2275
2276         if (target == dpt->sc_scsi_link[channel].adapter_targ) {
2277                 /* This one is for the controller itself */
2278                 if ((user_cmd->eataID[0] != 'E')
2279                  || (user_cmd->eataID[1] != 'A')
2280                  || (user_cmd->eataID[2] != 'T')
2281                  || (user_cmd->eataID[3] != 'A')) {
2282                         return (ENXIO);
2283                 }
2284         }
2285         /* Get a DPT CCB, so we can prepare a command */
2286         ospl = splsoftcam();
2287
2288         /* Process the free list */
2289         if ((TAILQ_EMPTY(&dpt->free_ccbs)) && dpt_alloc_freelist(dpt)) {
2290                 printf("dpt%d ERROR: Cannot allocate any more free CCB's.\n"
2291                        "             Please try later\n",
2292                        dpt->unit);
2293                 splx(ospl);
2294                 return (EFAULT);
2295         }
2296         /* Now grab the newest CCB */
2297         if ((ccb = dpt_Qpop_free(dpt)) == NULL) {
2298                 splx(ospl);
2299                 panic("dpt%d: Got a NULL CCB from pop_free()\n", dpt->unit);
2300         } else {
2301                 splx(ospl);
2302                 /* Clean up the leftover of the previous tenant */
2303                 ccb->status = DPT_CCB_STATE_NEW;
2304         }
2305
2306         bcopy((caddr_t) & user_cmd->command_packet, (caddr_t) & ccb->eata_ccb,
2307               sizeof(eata_ccb_t));
2308
2309         /* We do not want to do user specified scatter/gather.  Why?? */
2310         if (ccb->eata_ccb.scatter == 1)
2311                 return (EINVAL);
2312
2313         ccb->eata_ccb.Auto_Req_Sen = 1;
2314         ccb->eata_ccb.reqlen = htonl(sizeof(struct scsi_sense_data));
2315         ccb->eata_ccb.cp_datalen = htonl(sizeof(ccb->eata_ccb.cp_datalen));
2316         ccb->eata_ccb.cp_dataDMA = htonl(vtophys(ccb->eata_ccb.cp_dataDMA));
2317         ccb->eata_ccb.cp_statDMA = htonl(vtophys(&ccb->eata_ccb.cp_statDMA));
2318         ccb->eata_ccb.cp_reqDMA = htonl(vtophys(&ccb->eata_ccb.cp_reqDMA));
2319         ccb->eata_ccb.cp_viraddr = (u_int32_t) & ccb;
2320
2321         if (ccb->eata_ccb.DataIn || ccb->eata_ccb.DataOut) {
2322                 /* Data I/O is involved in this command.  Alocate buffer */
2323                 if (ccb->eata_ccb.cp_datalen > PAGE_SIZE) {
2324                         data = contigmalloc(ccb->eata_ccb.cp_datalen,
2325                                             M_TEMP, M_WAITOK, 0, ~0,
2326                                             ccb->eata_ccb.cp_datalen,
2327                                             0x10000);
2328                 } else {
2329                         data = malloc(ccb->eata_ccb.cp_datalen, M_TEMP,
2330                                       M_WAITOK);
2331                 }
2332
2333                 if (data == NULL) {
2334                         printf("dpt%d: Cannot allocate %d bytes "
2335                                "for EATA command\n", dpt->unit,
2336                                ccb->eata_ccb.cp_datalen);
2337                         return (EFAULT);
2338                 }
2339 #define usr_cmd_DMA (caddr_t)user_cmd->command_packet.cp_dataDMA
2340                 if (ccb->eata_ccb.DataIn == 1) {
2341                         if (copyin(usr_cmd_DMA,
2342                                    data, ccb->eata_ccb.cp_datalen) == -1)
2343                                 return (EFAULT);
2344                 }
2345         } else {
2346                 /* No data I/O involved here.  Make sure the DPT knows that */
2347                 ccb->eata_ccb.cp_datalen = 0;
2348                 data = NULL;
2349         }
2350
2351         if (ccb->eata_ccb.FWNEST == 1)
2352                 ccb->eata_ccb.FWNEST = 0;
2353
2354         if (ccb->eata_ccb.cp_datalen != 0) {
2355                 if (dpt_scatter_gather(dpt, ccb, ccb->eata_ccb.cp_datalen,
2356                                        data) != 0) {
2357                         if (data != NULL)
2358                                 free(data, M_TEMP);
2359                         return (EFAULT);
2360                 }
2361         }
2362         /**
2363          * We are required to quiet a SCSI bus.
2364          * since we do not queue comands on a bus basis,
2365          * we wait for ALL commands on a controller to complete.
2366          * In the mean time, sched_queue() will not schedule new commands.
2367          */
2368         if ((ccb->eata_ccb.cp_cdb[0] == MULTIFUNCTION_CMD)
2369             && (ccb->eata_ccb.cp_cdb[2] == BUS_QUIET)) {
2370                 /* We wait for ALL traffic for this HBa to subside */
2371                 ospl = splsoftcam();
2372                 dpt->state |= DPT_HA_QUIET;
2373                 splx(ospl);
2374
2375                 while ((submitted = dpt->submitted_ccbs_count) != 0) {
2376                         huh = tsleep((void *) dpt, PCATCH | PRIBIO, "dptqt",
2377                                      100 * hz);
2378                         switch (huh) {
2379                         case 0:
2380                                 /* Wakeup call received */
2381                                 break;
2382                         case EWOULDBLOCK:
2383                                 /* Timer Expired */
2384                                 break;
2385                         default:
2386                                 /* anything else */
2387                                 break;
2388                         }
2389                 }
2390         }
2391         /* Resume normal operation */
2392         if ((ccb->eata_ccb.cp_cdb[0] == MULTIFUNCTION_CMD)
2393             && (ccb->eata_ccb.cp_cdb[2] == BUS_UNQUIET)) {
2394                 ospl = splsoftcam();
2395                 dpt->state &= ~DPT_HA_QUIET;
2396                 splx(ospl);
2397         }
2398         /**
2399          * Schedule the command and submit it.
2400          * We bypass dpt_sched_queue, as it will block on DPT_HA_QUIET
2401          */
2402         ccb->xs = NULL;
2403         ccb->flags = 0;
2404         ccb->eata_ccb.Auto_Req_Sen = 1; /* We always want this feature */
2405
2406         ccb->transaction_id = ++dpt->commands_processed;
2407         ccb->std_callback = (ccb_callback) dpt_user_cmd_done;
2408         ccb->result = (u_int32_t) & cmdarg;
2409         ccb->data = data;
2410
2411 #ifdef DPT_MEASURE_PERFORMANCE
2412         ++dpt->performance.command_count[ccb->eata_ccb.cp_scsi_cmd];
2413         ccb->command_started = microtime_now;
2414 #endif
2415         ospl = splcam();
2416         dpt_Qadd_waiting(dpt, ccb);
2417         splx(ospl);
2418
2419         dpt_sched_queue(dpt);
2420
2421         /* Wait for the command to complete */
2422         (void) tsleep((void *) ccb, PCATCH | PRIBIO, "dptucw", 100 * hz);
2423
2424         /* Free allocated memory */
2425         if (data != NULL)
2426                 free(data, M_TEMP);
2427
2428         return (0);
2429 }
2430
2431 static void
2432 dpt_user_cmd_done(dpt_softc_t * dpt, int bus, dpt_ccb_t * ccb)
2433 {
2434         int             ospl = splsoftcam();
2435         u_int32_t       result;
2436         caddr_t         cmd_arg;
2437
2438         /**
2439          * If Auto Request Sense is on, copyout the sense struct
2440          */
2441 #define usr_pckt_DMA    (caddr_t)(intptr_t)ntohl(ccb->eata_ccb.cp_reqDMA)
2442 #define usr_pckt_len    ntohl(ccb->eata_ccb.cp_datalen)
2443         if (ccb->eata_ccb.Auto_Req_Sen == 1) {
2444                 if (copyout((caddr_t) & ccb->sense_data, usr_pckt_DMA,
2445                             sizeof(struct scsi_sense_data))) {
2446                         ccb->result = EFAULT;
2447                         dpt_Qpush_free(dpt, ccb);
2448                         splx(ospl);
2449                         wakeup(ccb);
2450                         return;
2451                 }
2452         }
2453         /* If DataIn is on, copyout the data */
2454         if ((ccb->eata_ccb.DataIn == 1)
2455             && (ccb->status_packet.hba_stat == HA_NO_ERROR)) {
2456                 if (copyout(ccb->data, usr_pckt_DMA, usr_pckt_len)) {
2457                         dpt_Qpush_free(dpt, ccb);
2458                         ccb->result = EFAULT;
2459
2460                         splx(ospl);
2461                         wakeup(ccb);
2462                         return;
2463                 }
2464         }
2465         /* Copyout the status */
2466         result = ccb->status_packet.hba_stat;
2467         cmd_arg = (caddr_t) ccb->result;
2468
2469         if (copyout((caddr_t) & result, cmd_arg, sizeof(result))) {
2470                 dpt_Qpush_free(dpt, ccb);
2471                 ccb->result = EFAULT;
2472                 splx(ospl);
2473                 wakeup(ccb);
2474                 return;
2475         }
2476         /* Put the CCB back in the freelist */
2477         ccb->state |= DPT_CCB_STATE_COMPLETED;
2478         dpt_Qpush_free(dpt, ccb);
2479
2480         /* Free allocated memory */
2481         splx(ospl);
2482         return;
2483 }
2484
2485 #ifdef DPT_HANDLE_TIMEOUTS
2486 /**
2487  * This function walks down the SUBMITTED queue.
2488  * Every request that is too old gets aborted and marked.
2489  * Since the DPT will complete (interrupt) immediately (what does that mean?),
2490  * We just walk the list, aborting old commands and marking them as such.
2491  * The dpt_complete function will get rid of the that were interrupted in the
2492  * normal manner.
2493  *
2494  * This function needs to run at splcam(), as it interacts with the submitted
2495  * queue, as well as the completed and free queues.  Just like dpt_intr() does.
2496  * To run it at any ISPL other than that of dpt_intr(), will mean that dpt_intr
2497  * willbe able to pre-empt it, grab a transaction in progress (towards
2498  * destruction) and operate on it.  The state of this transaction will be not
2499  * very clear.
2500  * The only other option, is to lock it only as long as necessary but have
2501  * dpt_intr() spin-wait on it. In a UP environment this makes no sense and in
2502  * a SMP environment, the advantage is dubvious for a function that runs once
2503  * every ten seconds for few microseconds and, on systems with healthy
2504  * hardware, does not do anything anyway.
2505  */
2506
2507 static void
2508 dpt_handle_timeouts(dpt_softc_t * dpt)
2509 {
2510         dpt_ccb_t      *ccb;
2511         int             ospl;
2512
2513         ospl = splcam();
2514
2515         if (dpt->state & DPT_HA_TIMEOUTS_ACTIVE) {
2516                 printf("dpt%d WARNING: Timeout Handling Collision\n",
2517                        dpt->unit);
2518                 splx(ospl);
2519                 return;
2520         }
2521         dpt->state |= DPT_HA_TIMEOUTS_ACTIVE;
2522
2523         /* Loop through the entire submitted queue, looking for lost souls */
2524         for (ccb = TAILQ_FIRST(&dpt->submitted_ccbs);
2525              ccb != NULL;
2526              ccb = TAILQ_NEXT(ccb, links)) {
2527                 struct scsi_xfer *xs;
2528                 u_int32_t       age, max_age;
2529
2530                 xs = ccb->xs;
2531                 age = dpt_time_delta(ccb->command_started, microtime_now);
2532
2533 #define TenSec  10000000
2534
2535                 if (xs == NULL) {       /* Local, non-kernel call */
2536                         max_age = TenSec;
2537                 } else {
2538                         max_age = (((xs->timeout * (dpt->submitted_ccbs_count
2539                                                     + DPT_TIMEOUT_FACTOR))
2540                                     > TenSec)
2541                                  ? (xs->timeout * (dpt->submitted_ccbs_count
2542                                                    + DPT_TIMEOUT_FACTOR))
2543                                    : TenSec);
2544                 }
2545
2546                 /*
2547                  * If a transaction is marked lost and is TWICE as old as we
2548                  * care, then, and only then do we destroy it!
2549                  */
2550                 if (ccb->state & DPT_CCB_STATE_MARKED_LOST) {
2551                         /* Remember who is next */
2552                         if (age > (max_age * 2)) {
2553                                 dpt_Qremove_submitted(dpt, ccb);
2554                                 ccb->state &= ~DPT_CCB_STATE_MARKED_LOST;
2555                                 ccb->state |= DPT_CCB_STATE_ABORTED;
2556 #define cmd_name scsi_cmd_name(ccb->eata_ccb.cp_scsi_cmd)
2557                                 if (ccb->retries++ > DPT_RETRIES) {
2558                                         printf("dpt%d ERROR: Destroying stale "
2559                                                "%d (%s)\n"
2560                                                "                on "
2561                                                "c%db%dt%du%d (%d/%d)\n",
2562                                              dpt->unit, ccb->transaction_id,
2563                                                cmd_name,
2564                                                dpt->unit,
2565                                                ccb->eata_ccb.cp_channel,
2566                                                ccb->eata_ccb.cp_id,
2567                                                ccb->eata_ccb.cp_LUN, age,
2568                                                ccb->retries);
2569 #define send_ccb &ccb->eata_ccb
2570 #define ESA      EATA_SPECIFIC_ABORT
2571                                         (void) dpt_send_immediate(dpt,
2572                                                                   send_ccb,
2573                                                                   ESA,
2574                                                                   0, 0);
2575                                         dpt_Qpush_free(dpt, ccb);
2576
2577                                         /* The SCSI layer should re-try */
2578                                         xs->error |= XS_TIMEOUT;
2579                                         xs->flags |= SCSI_ITSDONE;
2580                                         scsi_done(xs);
2581                                 } else {
2582                                         printf("dpt%d ERROR: Stale %d (%s) on "
2583                                                "c%db%dt%du%d (%d)\n"
2584                                              "          gets another "
2585                                                "chance(%d/%d)\n",
2586                                              dpt->unit, ccb->transaction_id,
2587                                                cmd_name,
2588                                                dpt->unit,
2589                                                ccb->eata_ccb.cp_channel,
2590                                                ccb->eata_ccb.cp_id,
2591                                                ccb->eata_ccb.cp_LUN,
2592                                             age, ccb->retries, DPT_RETRIES);
2593
2594                                         dpt_Qpush_waiting(dpt, ccb);
2595                                         dpt_sched_queue(dpt);
2596                                 }
2597                         }
2598                 } else {
2599                         /*
2600                          * This is a transaction that is not to be destroyed
2601                          * (yet) But it is too old for our liking. We wait as
2602                          * long as the upper layer thinks. Not really, we
2603                          * multiply that by the number of commands in the
2604                          * submitted queue + 1.
2605                          */
2606                         if (!(ccb->state & DPT_CCB_STATE_MARKED_LOST) &&
2607                             (age != ~0) && (age > max_age)) {
2608                                 printf("dpt%d ERROR: Marking %d (%s) on "
2609                                        "c%db%dt%du%d \n"
2610                                        "            as late after %dusec\n",
2611                                        dpt->unit, ccb->transaction_id,
2612                                        cmd_name,
2613                                        dpt->unit, ccb->eata_ccb.cp_channel,
2614                                        ccb->eata_ccb.cp_id,
2615                                        ccb->eata_ccb.cp_LUN, age);
2616                                 ccb->state |= DPT_CCB_STATE_MARKED_LOST;
2617                         }
2618                 }
2619         }
2620
2621         dpt->state &= ~DPT_HA_TIMEOUTS_ACTIVE;
2622         splx(ospl);
2623 }
2624
2625 static void
2626 dpt_timeout(void *arg)
2627 {
2628         dpt_softc_t    *dpt = (dpt_softc_t *) arg;
2629
2630         if (!(dpt->state & DPT_HA_TIMEOUTS_ACTIVE))
2631                 dpt_handle_timeouts(dpt);
2632
2633         timeout(dpt_timeout, (caddr_t) dpt, hz * 10);
2634 }
2635
2636 #endif                          /* DPT_HANDLE_TIMEOUTS */
2637
2638 #endif