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