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