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