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