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