twa(4): Add MSI support.
[dragonfly.git] / sys / dev / raid / twa / tw_osl_freebsd.c
1 /*
2  * Copyright (c) 2004-07 Applied Micro Circuits Corporation.
3  * Copyright (c) 2004-05 Vinod Kashyap.
4  * Copyright (c) 2000 Michael Smith
5  * Copyright (c) 2000 BSDi
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
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
21  * FOR 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  *      $FreeBSD: src/sys/dev/twa/tw_osl_freebsd.c,v 1.19 2011/11/07 06:44:47 ed Exp $
30  */
31
32 /*
33  * AMCC'S 3ware driver for 9000 series storage controllers.
34  *
35  * Author: Vinod Kashyap
36  * Modifications by: Adam Radford
37  * Modifications by: Manjunath Ranganathaiah
38  */
39
40
41 /*
42  * FreeBSD specific functions not related to CAM, and other
43  * miscellaneous functions.
44  */
45
46
47 #include <dev/raid/twa/tw_osl_includes.h>
48 #include <dev/raid/twa/tw_cl_fwif.h>
49 #include <dev/raid/twa/tw_cl_ioctl.h>
50 #include <dev/raid/twa/tw_osl_ioctl.h>
51
52 #ifdef TW_OSL_DEBUG
53 TW_INT32        TW_DEBUG_LEVEL_FOR_OSL = TW_OSL_DEBUG;
54 TW_INT32        TW_OSL_DEBUG_LEVEL_FOR_CL = TW_OSL_DEBUG;
55 #endif /* TW_OSL_DEBUG */
56
57 static MALLOC_DEFINE(TW_OSLI_MALLOC_CLASS, "twa_commands", "twa commands");
58
59
60 static  d_open_t                twa_open;
61 static  d_close_t               twa_close;
62 static  d_ioctl_t               twa_ioctl;
63
64 static struct dev_ops twa_ops = {
65         { "twa", 0, 0 },
66         .d_open =       twa_open,
67         .d_close =      twa_close,
68         .d_ioctl =      twa_ioctl,
69 };
70
71 static devclass_t       twa_devclass;
72
73 static int              twa_msi_enable = 0;
74 TUNABLE_INT("hw.twa.msi.enable", &twa_msi_enable);
75
76
77 /*
78  * Function name:       twa_open
79  * Description:         Called when the controller is opened.
80  *                      Simply marks the controller as open.
81  *
82  * Input:               dev     -- control device corresponding to the ctlr
83  *                      flags   -- mode of open
84  *                      fmt     -- device type (character/block etc.)
85  *                      proc    -- current process
86  * Output:              None
87  * Return value:        0       -- success
88  *                      non-zero-- failure
89  */
90 static TW_INT32
91 twa_open(struct dev_open_args *ap)
92 {
93         cdev_t                  dev = ap->a_head.a_dev;
94         struct twa_softc        *sc = (struct twa_softc *)(dev->si_drv1);
95
96         tw_osli_dbg_dprintf(5, sc, "entered");
97         sc->open = TW_CL_TRUE;
98         return(0);
99 }
100
101
102
103 /*
104  * Function name:       twa_close
105  * Description:         Called when the controller is closed.
106  *                      Simply marks the controller as not open.
107  *
108  * Input:               dev     -- control device corresponding to the ctlr
109  *                      flags   -- mode of corresponding open
110  *                      fmt     -- device type (character/block etc.)
111  *                      proc    -- current process
112  * Output:              None
113  * Return value:        0       -- success
114  *                      non-zero-- failure
115  */
116 static TW_INT32
117 twa_close(struct dev_close_args *ap)
118 {
119         cdev_t                  dev = ap->a_head.a_dev;
120         struct twa_softc        *sc = (struct twa_softc *)(dev->si_drv1);
121
122         tw_osli_dbg_dprintf(5, sc, "entered");
123         sc->open = TW_CL_FALSE;
124         return(0);
125 }
126
127
128
129 /*
130  * Function name:       twa_ioctl
131  * Description:         Called when an ioctl is posted to the controller.
132  *                      Handles any OS Layer specific cmds, passes the rest
133  *                      on to the Common Layer.
134  *
135  * Input:               dev     -- control device corresponding to the ctlr
136  *                      cmd     -- ioctl cmd
137  *                      buf     -- ptr to buffer in kernel memory, which is
138  *                                 a copy of the input buffer in user-space
139  *                      flags   -- mode of corresponding open
140  *                      proc    -- current process
141  * Output:              buf     -- ptr to buffer in kernel memory, which will
142  *                                 be copied to the output buffer in user-space
143  * Return value:        0       -- success
144  *                      non-zero-- failure
145  */
146 static TW_INT32
147 twa_ioctl(struct dev_ioctl_args *ap)
148 {
149         cdev_t                  dev = ap->a_head.a_dev;
150         u_long                  cmd = ap->a_cmd;
151         caddr_t                 buf = ap->a_data;
152         struct twa_softc        *sc = (struct twa_softc *)(dev->si_drv1);
153         TW_INT32                error;
154
155         tw_osli_dbg_dprintf(5, sc, "entered");
156
157         switch (cmd) {
158         case TW_OSL_IOCTL_FIRMWARE_PASS_THROUGH:
159                 tw_osli_dbg_dprintf(6, sc, "ioctl: fw_passthru");
160                 error = tw_osli_fw_passthru(sc, (TW_INT8 *)buf);
161                 break;
162
163         case TW_OSL_IOCTL_SCAN_BUS:
164                 /* Request CAM for a bus scan. */
165                 tw_osli_dbg_dprintf(6, sc, "ioctl: scan bus");
166                 error = tw_osli_request_bus_scan(sc);
167                 break;
168
169         default:
170                 tw_osli_dbg_dprintf(6, sc, "ioctl: 0x%lx", cmd);
171                 error = tw_cl_ioctl(&sc->ctlr_handle, cmd, buf);
172                 break;
173         }
174         return(error);
175 }
176
177
178
179 static TW_INT32 twa_probe(device_t dev);
180 static TW_INT32 twa_attach(device_t dev);
181 static TW_INT32 twa_detach(device_t dev);
182 static TW_INT32 twa_shutdown(device_t dev);
183 #if 0 /* XXX swildner */
184 static TW_VOID  twa_busdma_lock(TW_VOID *lock_arg, bus_dma_lock_op_t op);
185 #endif
186 static TW_VOID  twa_pci_intr(TW_VOID *arg);
187 static TW_VOID  twa_watchdog(TW_VOID *arg);
188 int twa_setup_intr(struct twa_softc *sc);
189 int twa_teardown_intr(struct twa_softc *sc);
190
191 static TW_INT32 tw_osli_alloc_mem(struct twa_softc *sc);
192 static TW_VOID  tw_osli_free_resources(struct twa_softc *sc);
193
194 static TW_VOID  twa_map_load_data_callback(TW_VOID *arg,
195         bus_dma_segment_t *segs, TW_INT32 nsegments, TW_INT32 error);
196 static TW_VOID  twa_map_load_callback(TW_VOID *arg,
197         bus_dma_segment_t *segs, TW_INT32 nsegments, TW_INT32 error);
198
199
200 static device_method_t  twa_methods[] = {
201         /* Device interface */
202         DEVMETHOD(device_probe,         twa_probe),
203         DEVMETHOD(device_attach,        twa_attach),
204         DEVMETHOD(device_detach,        twa_detach),
205         DEVMETHOD(device_shutdown,      twa_shutdown),
206
207         DEVMETHOD(bus_print_child,      bus_generic_print_child),
208         DEVMETHOD(bus_driver_added,     bus_generic_driver_added),
209         {0, 0}
210 };
211
212 static driver_t twa_pci_driver = {
213         "twa",
214         twa_methods,
215         sizeof(struct twa_softc)
216 };
217
218 DRIVER_MODULE(twa, pci, twa_pci_driver, twa_devclass, NULL, NULL);
219 MODULE_DEPEND(twa, cam, 1, 1, 1);
220 MODULE_DEPEND(twa, pci, 1, 1, 1);
221 MODULE_VERSION(twa, 1);
222
223
224 /*
225  * Function name:       twa_probe
226  * Description:         Called at driver load time.  Claims 9000 ctlrs.
227  *
228  * Input:               dev     -- bus device corresponding to the ctlr
229  * Output:              None
230  * Return value:        <= 0    -- success
231  *                      > 0     -- failure
232  */
233 static TW_INT32
234 twa_probe(device_t dev)
235 {
236         static TW_UINT8 first_ctlr = 1;
237
238         tw_osli_dbg_printf(3, "entered");
239
240         if (tw_cl_ctlr_supported(pci_get_vendor(dev), pci_get_device(dev))) {
241                 device_set_desc(dev, TW_OSLI_DEVICE_NAME);
242                 /* Print the driver version only once. */
243                 if (first_ctlr) {
244                         kprintf("3ware device driver for 9000 series storage "
245                                 "controllers, version: %s\n",
246                                 TW_OSL_DRIVER_VERSION_STRING);
247                         first_ctlr = 0;
248                 }
249                 return(0);
250         }
251         return(ENXIO);
252 }
253
254 int twa_setup_intr(struct twa_softc *sc)
255 {
256         int error = 0;
257
258         if (!(sc->intr_handle) && (sc->irq_res)) {
259                 error = bus_setup_intr(sc->bus_dev, sc->irq_res,
260                                         INTR_MPSAFE,
261                                         twa_pci_intr,
262                                         sc, &sc->intr_handle, NULL);
263         }
264         return( error );
265 }
266
267
268 int twa_teardown_intr(struct twa_softc *sc)
269 {
270         int error = 0;
271
272         if ((sc->intr_handle) && (sc->irq_res)) {
273                 error = bus_teardown_intr(sc->bus_dev,
274                                                 sc->irq_res, sc->intr_handle);
275                 sc->intr_handle = NULL;
276         }
277         return( error );
278 }
279
280
281
282 /*
283  * Function name:       twa_attach
284  * Description:         Allocates pci resources; updates sc; adds a node to the
285  *                      sysctl tree to expose the driver version; makes calls
286  *                      (to the Common Layer) to initialize ctlr, and to
287  *                      attach to CAM.
288  *
289  * Input:               dev     -- bus device corresponding to the ctlr
290  * Output:              None
291  * Return value:        0       -- success
292  *                      non-zero-- failure
293  */
294 static TW_INT32
295 twa_attach(device_t dev)
296 {
297         struct twa_softc        *sc = device_get_softc(dev);
298         TW_UINT32               command;
299         TW_INT32                bar_num;
300         TW_INT32                bar0_offset;
301         TW_INT32                bar_size;
302         TW_INT32                irq_flags;
303         TW_INT32                error;
304
305         tw_osli_dbg_dprintf(3, sc, "entered");
306
307         sc->ctlr_handle.osl_ctlr_ctxt = sc;
308
309         /* Initialize the softc structure. */
310         sc->bus_dev = dev;
311         sc->device_id = pci_get_device(dev);
312
313         /* Initialize the mutexes right here. */
314         sc->io_lock = &(sc->io_lock_handle);
315         spin_init(sc->io_lock);
316         sc->q_lock = &(sc->q_lock_handle);
317         spin_init(sc->q_lock);
318         sc->sim_lock = &(sc->sim_lock_handle);
319         lockinit(sc->sim_lock, "tw_osl_sim_lock", 0, LK_CANRECURSE);
320
321         sysctl_ctx_init(&sc->sysctl_ctxt);
322         sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctxt,
323                 SYSCTL_STATIC_CHILDREN(_hw), OID_AUTO,
324                 device_get_nameunit(dev), CTLFLAG_RD, 0, "");
325         if (sc->sysctl_tree == NULL) {
326                 tw_osli_printf(sc, "error = %d",
327                         TW_CL_SEVERITY_ERROR_STRING,
328                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
329                         0x2000,
330                         "Cannot add sysctl tree node",
331                         ENXIO);
332                 return(ENXIO);
333         }
334         SYSCTL_ADD_STRING(&sc->sysctl_ctxt, SYSCTL_CHILDREN(sc->sysctl_tree),
335                 OID_AUTO, "driver_version", CTLFLAG_RD,
336                 TW_OSL_DRIVER_VERSION_STRING, 0, "TWA driver version");
337
338         /* Make sure we are going to be able to talk to this board. */
339         command = pci_read_config(dev, PCIR_COMMAND, 2);
340         if ((command & PCIM_CMD_PORTEN) == 0) {
341                 tw_osli_printf(sc, "error = %d",
342                         TW_CL_SEVERITY_ERROR_STRING,
343                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
344                         0x2001,
345                         "Register window not available",
346                         ENXIO);
347                 tw_osli_free_resources(sc);
348                 return(ENXIO);
349         }
350
351         /* Force the busmaster enable bit on, in case the BIOS forgot. */
352         command |= PCIM_CMD_BUSMASTEREN;
353         pci_write_config(dev, PCIR_COMMAND, command, 2);
354
355         /* Allocate the PCI register window. */
356         if ((error = tw_cl_get_pci_bar_info(sc->device_id, TW_CL_BAR_TYPE_MEM,
357                 &bar_num, &bar0_offset, &bar_size))) {
358                 tw_osli_printf(sc, "error = %d",
359                         TW_CL_SEVERITY_ERROR_STRING,
360                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
361                         0x201F,
362                         "Can't get PCI BAR info",
363                         error);
364                 tw_osli_free_resources(sc);
365                 return(error);
366         }
367         sc->reg_res_id = PCIR_BARS + bar0_offset;
368         if ((sc->reg_res = bus_alloc_resource(dev, SYS_RES_MEMORY,
369                                 &(sc->reg_res_id), 0, ~0, 1, RF_ACTIVE))
370                                 == NULL) {
371                 tw_osli_printf(sc, "error = %d",
372                         TW_CL_SEVERITY_ERROR_STRING,
373                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
374                         0x2002,
375                         "Can't allocate register window",
376                         ENXIO);
377                 tw_osli_free_resources(sc);
378                 return(ENXIO);
379         }
380         sc->bus_tag = rman_get_bustag(sc->reg_res);
381         sc->bus_handle = rman_get_bushandle(sc->reg_res);
382
383         /* Allocate and register our interrupt. */
384         sc->irq_res_id = 0;
385         sc->irq_type = pci_alloc_1intr(sc->bus_dev, twa_msi_enable,
386             &sc->irq_res_id, &irq_flags);
387         if ((sc->irq_res = bus_alloc_resource(sc->bus_dev, SYS_RES_IRQ,
388                                 &(sc->irq_res_id), 0, ~0, 1,
389                                 irq_flags)) == NULL) {
390                 tw_osli_printf(sc, "error = %d",
391                         TW_CL_SEVERITY_ERROR_STRING,
392                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
393                         0x2003,
394                         "Can't allocate interrupt",
395                         ENXIO);
396                 tw_osli_free_resources(sc);
397                 return(ENXIO);
398         }
399         if ((error = twa_setup_intr(sc))) {
400                 tw_osli_printf(sc, "error = %d",
401                         TW_CL_SEVERITY_ERROR_STRING,
402                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
403                         0x2004,
404                         "Can't set up interrupt",
405                         error);
406                 tw_osli_free_resources(sc);
407                 return(error);
408         }
409
410         if ((error = tw_osli_alloc_mem(sc))) {
411                 tw_osli_printf(sc, "error = %d",
412                         TW_CL_SEVERITY_ERROR_STRING,
413                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
414                         0x2005,
415                         "Memory allocation failure",
416                         error);
417                 tw_osli_free_resources(sc);
418                 return(error);
419         }
420
421         /* Initialize the Common Layer for this controller. */
422         if ((error = tw_cl_init_ctlr(&sc->ctlr_handle, sc->flags, sc->device_id,
423                         TW_OSLI_MAX_NUM_REQUESTS, TW_OSLI_MAX_NUM_AENS,
424                         sc->non_dma_mem, sc->dma_mem,
425                         sc->dma_mem_phys
426                         ))) {
427                 tw_osli_printf(sc, "error = %d",
428                         TW_CL_SEVERITY_ERROR_STRING,
429                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
430                         0x2006,
431                         "Failed to initialize Common Layer/controller",
432                         error);
433                 tw_osli_free_resources(sc);
434                 return(error);
435         }
436
437         /* Create the control device. */
438         sc->ctrl_dev = make_dev(&twa_ops, device_get_unit(sc->bus_dev),
439                         UID_ROOT, GID_OPERATOR, S_IRUSR | S_IWUSR,
440                         "twa%d", device_get_unit(sc->bus_dev));
441         sc->ctrl_dev->si_drv1 = sc;
442
443         if ((error = tw_osli_cam_attach(sc))) {
444                 tw_osli_free_resources(sc);
445                 tw_osli_printf(sc, "error = %d",
446                         TW_CL_SEVERITY_ERROR_STRING,
447                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
448                         0x2007,
449                         "Failed to initialize CAM",
450                         error);
451                 return(error);
452         }
453
454         sc->watchdog_index = 0;
455         callout_init(&(sc->watchdog_callout[0]));
456         callout_init(&(sc->watchdog_callout[1]));
457         callout_reset(&(sc->watchdog_callout[0]), 5*hz, twa_watchdog, &sc->ctlr_handle);
458
459         return(0);
460 }
461
462
463 static TW_VOID
464 twa_watchdog(TW_VOID *arg)
465 {
466         struct tw_cl_ctlr_handle *ctlr_handle =
467                 (struct tw_cl_ctlr_handle *)arg;
468         struct twa_softc                *sc = ctlr_handle->osl_ctlr_ctxt;
469         int                             i;
470         int                             i_need_a_reset = 0;
471         int                             driver_is_active = 0;
472         TW_UINT64                       current_time;
473         struct tw_osli_req_context      *my_req;
474
475
476 //==============================================================================
477         current_time = (TW_UINT64) (tw_osl_get_local_time());
478
479         for (i = 0; i < TW_OSLI_MAX_NUM_REQUESTS; i++) {
480                 my_req = &(sc->req_ctx_buf[i]);
481
482                 if ((my_req->state == TW_OSLI_REQ_STATE_BUSY) &&
483                         (my_req->deadline) &&
484                         (my_req->deadline < current_time)) {
485                         tw_cl_set_reset_needed(ctlr_handle);
486 #ifdef    TW_OSL_DEBUG
487                         device_printf((sc)->bus_dev, "Request %d timed out! d = %llu, c = %llu\n", i, my_req->deadline, current_time);
488 #else  /* TW_OSL_DEBUG */
489                         device_printf((sc)->bus_dev, "Request %d timed out!\n", i);
490 #endif /* TW_OSL_DEBUG */
491                         break;
492                 }
493         }
494 //==============================================================================
495
496         i_need_a_reset = tw_cl_is_reset_needed(ctlr_handle);
497
498         i = (int) ((sc->watchdog_index++) & 1);
499
500         driver_is_active = tw_cl_is_active(ctlr_handle);
501
502         if (i_need_a_reset) {
503 #ifdef    TW_OSL_DEBUG
504                 device_printf((sc)->bus_dev, "Watchdog rescheduled in 70 seconds\n");
505 #endif /* TW_OSL_DEBUG */
506                 callout_reset(&(sc->watchdog_callout[i]), 70*hz, twa_watchdog, &sc->ctlr_handle);
507                 tw_cl_reset_ctlr(ctlr_handle);
508 #ifdef    TW_OSL_DEBUG
509                 device_printf((sc)->bus_dev, "Watchdog reset completed!\n");
510 #endif /* TW_OSL_DEBUG */
511         } else if (driver_is_active) {
512                 callout_reset(&(sc->watchdog_callout[i]),  5*hz, twa_watchdog, &sc->ctlr_handle);
513         }
514 #ifdef    TW_OSL_DEBUG
515         if (i_need_a_reset)
516                 device_printf((sc)->bus_dev, "i_need_a_reset = %d, "
517                 "driver_is_active = %d\n",
518                 i_need_a_reset, driver_is_active);
519 #endif /* TW_OSL_DEBUG */
520 }
521
522
523 /*
524  * Function name:       tw_osli_alloc_mem
525  * Description:         Allocates memory needed both by CL and OSL.
526  *
527  * Input:               sc      -- OSL internal controller context
528  * Output:              None
529  * Return value:        0       -- success
530  *                      non-zero-- failure
531  */
532 static TW_INT32
533 tw_osli_alloc_mem(struct twa_softc *sc)
534 {
535         struct tw_osli_req_context      *req;
536         TW_UINT32                       max_sg_elements;
537         TW_UINT32                       non_dma_mem_size;
538         TW_UINT32                       dma_mem_size;
539         TW_INT32                        error;
540         TW_INT32                        i;
541
542         tw_osli_dbg_dprintf(3, sc, "entered");
543
544         sc->flags |= (sizeof(bus_addr_t) == 8) ? TW_CL_64BIT_ADDRESSES : 0;
545         sc->flags |= (sizeof(bus_size_t) == 8) ? TW_CL_64BIT_SG_LENGTH : 0;
546
547         max_sg_elements = (sizeof(bus_addr_t) == 8) ?
548                 TW_CL_MAX_64BIT_SG_ELEMENTS : TW_CL_MAX_32BIT_SG_ELEMENTS;
549
550         if ((error = tw_cl_get_mem_requirements(&sc->ctlr_handle, sc->flags,
551                         sc->device_id, TW_OSLI_MAX_NUM_REQUESTS,  TW_OSLI_MAX_NUM_AENS,
552                         &(sc->alignment), &(sc->sg_size_factor),
553                         &non_dma_mem_size, &dma_mem_size
554                         ))) {
555                 tw_osli_printf(sc, "error = %d",
556                         TW_CL_SEVERITY_ERROR_STRING,
557                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
558                         0x2008,
559                         "Can't get Common Layer's memory requirements",
560                         error);
561                 return(error);
562         }
563
564         sc->non_dma_mem = kmalloc(non_dma_mem_size, TW_OSLI_MALLOC_CLASS,
565             M_WAITOK);
566
567         /* Create the parent dma tag. */
568         if (bus_dma_tag_create(NULL,                    /* parent */
569                                 sc->alignment,          /* alignment */
570                                 TW_OSLI_DMA_BOUNDARY,   /* boundary */
571                                 BUS_SPACE_MAXADDR,      /* lowaddr */
572                                 BUS_SPACE_MAXADDR,      /* highaddr */
573                                 NULL, NULL,             /* filter, filterarg */
574                                 TW_CL_MAX_IO_SIZE,      /* maxsize */
575                                 max_sg_elements,        /* nsegments */
576                                 TW_CL_MAX_IO_SIZE,      /* maxsegsize */
577                                 0,                      /* flags */
578                                 &sc->parent_tag         /* tag */)) {
579                 tw_osli_printf(sc, "error = %d",
580                         TW_CL_SEVERITY_ERROR_STRING,
581                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
582                         0x200A,
583                         "Can't allocate parent DMA tag",
584                         ENOMEM);
585                 return(ENOMEM);
586         }
587
588         /* Create a dma tag for Common Layer's DMA'able memory (dma_mem). */
589         if (bus_dma_tag_create(sc->parent_tag,          /* parent */
590                                 sc->alignment,          /* alignment */
591                                 0,                      /* boundary */
592                                 BUS_SPACE_MAXADDR,      /* lowaddr */
593                                 BUS_SPACE_MAXADDR,      /* highaddr */
594                                 NULL, NULL,             /* filter, filterarg */
595                                 dma_mem_size,           /* maxsize */
596                                 1,                      /* nsegments */
597                                 BUS_SPACE_MAXSIZE,      /* maxsegsize */
598                                 0,                      /* flags */
599                                 &sc->cmd_tag            /* tag */)) {
600                 tw_osli_printf(sc, "error = %d",
601                         TW_CL_SEVERITY_ERROR_STRING,
602                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
603                         0x200B,
604                         "Can't allocate DMA tag for Common Layer's "
605                         "DMA'able memory",
606                         ENOMEM);
607                 return(ENOMEM);
608         }
609
610         if (bus_dmamem_alloc(sc->cmd_tag, &sc->dma_mem,
611                 BUS_DMA_NOWAIT, &sc->cmd_map)) {
612                 /* Try a second time. */
613                 if (bus_dmamem_alloc(sc->cmd_tag, &sc->dma_mem,
614                         BUS_DMA_NOWAIT, &sc->cmd_map)) {
615                         tw_osli_printf(sc, "error = %d",
616                                 TW_CL_SEVERITY_ERROR_STRING,
617                                 TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
618                                 0x200C,
619                                 "Can't allocate DMA'able memory for the"
620                                 "Common Layer",
621                                 ENOMEM);
622                         return(ENOMEM);
623                 }
624         }
625
626         bus_dmamap_load(sc->cmd_tag, sc->cmd_map, sc->dma_mem,
627                 dma_mem_size, twa_map_load_callback,
628                 &sc->dma_mem_phys, 0);
629
630         /*
631          * Create a dma tag for data buffers; size will be the maximum
632          * possible I/O size (128kB).
633          */
634         if (bus_dma_tag_create(sc->parent_tag,          /* parent */
635                                 sc->alignment,          /* alignment */
636                                 0,                      /* boundary */
637                                 BUS_SPACE_MAXADDR,      /* lowaddr */
638                                 BUS_SPACE_MAXADDR,      /* highaddr */
639                                 NULL, NULL,             /* filter, filterarg */
640                                 TW_CL_MAX_IO_SIZE,      /* maxsize */
641                                 max_sg_elements,        /* nsegments */
642                                 TW_CL_MAX_IO_SIZE,      /* maxsegsize */
643                                 BUS_DMA_ALLOCNOW,       /* flags */
644 #if 0 /* XXX swildner */
645                                 twa_busdma_lock,        /* lockfunc */
646                                 sc->io_lock,            /* lockfuncarg */
647 #endif
648                                 &sc->dma_tag            /* tag */)) {
649                 tw_osli_printf(sc, "error = %d",
650                         TW_CL_SEVERITY_ERROR_STRING,
651                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
652                         0x200F,
653                         "Can't allocate DMA tag for data buffers",
654                         ENOMEM);
655                 return(ENOMEM);
656         }
657
658         /*
659          * Create a dma tag for ioctl data buffers; size will be the maximum
660          * possible I/O size (128kB).
661          */
662         if (bus_dma_tag_create(sc->parent_tag,          /* parent */
663                                 sc->alignment,          /* alignment */
664                                 0,                      /* boundary */
665                                 BUS_SPACE_MAXADDR,      /* lowaddr */
666                                 BUS_SPACE_MAXADDR,      /* highaddr */
667                                 NULL, NULL,             /* filter, filterarg */
668                                 TW_CL_MAX_IO_SIZE,      /* maxsize */
669                                 max_sg_elements,        /* nsegments */
670                                 TW_CL_MAX_IO_SIZE,      /* maxsegsize */
671                                 BUS_DMA_ALLOCNOW,       /* flags */
672 #if 0 /* XXX swildner */
673                                 twa_busdma_lock,        /* lockfunc */
674                                 sc->io_lock,            /* lockfuncarg */
675 #endif
676                                 &sc->ioctl_tag          /* tag */)) {
677                 tw_osli_printf(sc, "error = %d",
678                         TW_CL_SEVERITY_ERROR_STRING,
679                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
680                         0x2010,
681                         "Can't allocate DMA tag for ioctl data buffers",
682                         ENOMEM);
683                 return(ENOMEM);
684         }
685
686         /* Create just one map for all ioctl request data buffers. */
687         if (bus_dmamap_create(sc->ioctl_tag, 0, &sc->ioctl_map)) {
688                 tw_osli_printf(sc, "error = %d",
689                         TW_CL_SEVERITY_ERROR_STRING,
690                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
691                         0x2011,
692                         "Can't create ioctl map",
693                         ENOMEM);
694                 return(ENOMEM);
695         }
696
697
698         /* Initialize request queues. */
699         tw_osli_req_q_init(sc, TW_OSLI_FREE_Q);
700         tw_osli_req_q_init(sc, TW_OSLI_BUSY_Q);
701
702         sc->req_ctx_buf = kmalloc((sizeof(struct tw_osli_req_context) *
703             TW_OSLI_MAX_NUM_REQUESTS), TW_OSLI_MALLOC_CLASS,
704             M_WAITOK | M_ZERO);
705         for (i = 0; i < TW_OSLI_MAX_NUM_REQUESTS; i++) {
706                 req = &(sc->req_ctx_buf[i]);
707                 req->ctlr = sc;
708                 if (bus_dmamap_create(sc->dma_tag, 0, &req->dma_map)) {
709                         tw_osli_printf(sc, "request # = %d, error = %d",
710                                 TW_CL_SEVERITY_ERROR_STRING,
711                                 TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
712                                 0x2013,
713                                 "Can't create dma map",
714                                 i, ENOMEM);
715                         return(ENOMEM);
716                 }
717
718                 /* Initialize the ioctl wakeup/ timeout mutex */
719                 req->ioctl_wake_timeout_lock = &(req->ioctl_wake_timeout_lock_handle);
720                 lockinit(req->ioctl_wake_timeout_lock, "tw_ioctl_wake_timeout_lock", 0, 0);
721
722                 /* Insert request into the free queue. */
723                 tw_osli_req_q_insert_tail(req, TW_OSLI_FREE_Q);
724         }
725
726         return(0);
727 }
728
729
730
731 /*
732  * Function name:       tw_osli_free_resources
733  * Description:         Performs clean-up at the time of going down.
734  *
735  * Input:               sc      -- ptr to OSL internal ctlr context
736  * Output:              None
737  * Return value:        None
738  */
739 static TW_VOID
740 tw_osli_free_resources(struct twa_softc *sc)
741 {
742         struct tw_osli_req_context      *req;
743         TW_INT32                        error = 0;
744
745         tw_osli_dbg_dprintf(3, sc, "entered");
746
747         /* Detach from CAM */
748         tw_osli_cam_detach(sc);
749
750         if (sc->req_ctx_buf)
751                 while ((req = tw_osli_req_q_remove_head(sc, TW_OSLI_FREE_Q)) !=
752                         NULL) {
753                         lockuninit(req->ioctl_wake_timeout_lock);
754
755                         if ((error = bus_dmamap_destroy(sc->dma_tag,
756                                         req->dma_map)))
757                                 tw_osli_dbg_dprintf(1, sc,
758                                         "dmamap_destroy(dma) returned %d",
759                                         error);
760                 }
761
762         if ((sc->ioctl_tag) && (sc->ioctl_map))
763                 if ((error = bus_dmamap_destroy(sc->ioctl_tag, sc->ioctl_map)))
764                         tw_osli_dbg_dprintf(1, sc,
765                                 "dmamap_destroy(ioctl) returned %d", error);
766
767         /* Free all memory allocated so far. */
768         if (sc->req_ctx_buf)
769                 kfree(sc->req_ctx_buf, TW_OSLI_MALLOC_CLASS);
770
771         if (sc->non_dma_mem)
772                 kfree(sc->non_dma_mem, TW_OSLI_MALLOC_CLASS);
773
774         if (sc->dma_mem) {
775                 bus_dmamap_unload(sc->cmd_tag, sc->cmd_map);
776                 bus_dmamem_free(sc->cmd_tag, sc->dma_mem,
777                         sc->cmd_map);
778         }
779         if (sc->cmd_tag)
780                 if ((error = bus_dma_tag_destroy(sc->cmd_tag)))
781                         tw_osli_dbg_dprintf(1, sc,
782                                 "dma_tag_destroy(cmd) returned %d", error);
783
784         if (sc->dma_tag)
785                 if ((error = bus_dma_tag_destroy(sc->dma_tag)))
786                         tw_osli_dbg_dprintf(1, sc,
787                                 "dma_tag_destroy(dma) returned %d", error);
788
789         if (sc->ioctl_tag)
790                 if ((error = bus_dma_tag_destroy(sc->ioctl_tag)))
791                         tw_osli_dbg_dprintf(1, sc,
792                                 "dma_tag_destroy(ioctl) returned %d", error);
793
794         if (sc->parent_tag)
795                 if ((error = bus_dma_tag_destroy(sc->parent_tag)))
796                         tw_osli_dbg_dprintf(1, sc,
797                                 "dma_tag_destroy(parent) returned %d", error);
798
799
800         /* Disconnect the interrupt handler. */
801         if ((error = twa_teardown_intr(sc)))
802                         tw_osli_dbg_dprintf(1, sc,
803                                 "teardown_intr returned %d", error);
804
805         if (sc->irq_res != NULL)
806                 if ((error = bus_release_resource(sc->bus_dev,
807                                 SYS_RES_IRQ, sc->irq_res_id, sc->irq_res)))
808                         tw_osli_dbg_dprintf(1, sc,
809                                 "release_resource(irq) returned %d", error);
810
811         if (sc->irq_type == PCI_INTR_TYPE_MSI)
812                 pci_release_msi(sc->bus_dev);
813
814         /* Release the register window mapping. */
815         if (sc->reg_res != NULL)
816                 if ((error = bus_release_resource(sc->bus_dev,
817                                 SYS_RES_MEMORY, sc->reg_res_id, sc->reg_res)))
818                         tw_osli_dbg_dprintf(1, sc,
819                                 "release_resource(io) returned %d", error);
820
821         dev_ops_remove_minor(&twa_ops, device_get_unit(sc->bus_dev));
822
823         /* Destroy the control device. */
824         if (sc->ctrl_dev != NULL)
825                 destroy_dev(sc->ctrl_dev);
826
827         if ((error = sysctl_ctx_free(&sc->sysctl_ctxt)))
828                 tw_osli_dbg_dprintf(1, sc,
829                         "sysctl_ctx_free returned %d", error);
830
831 }
832
833
834
835 /*
836  * Function name:       twa_detach
837  * Description:         Called when the controller is being detached from
838  *                      the pci bus.
839  *
840  * Input:               dev     -- bus device corresponding to the ctlr
841  * Output:              None
842  * Return value:        0       -- success
843  *                      non-zero-- failure
844  */
845 static TW_INT32
846 twa_detach(device_t dev)
847 {
848         struct twa_softc        *sc = device_get_softc(dev);
849         TW_INT32                error;
850
851         tw_osli_dbg_dprintf(3, sc, "entered");
852
853         error = EBUSY;
854         if (sc->open) {
855                 tw_osli_printf(sc, "error = %d",
856                         TW_CL_SEVERITY_ERROR_STRING,
857                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
858                         0x2014,
859                         "Device open",
860                         error);
861                 goto out;
862         }
863
864         /* Shut the controller down. */
865         if ((error = twa_shutdown(dev)))
866                 goto out;
867
868         /* Free all resources associated with this controller. */
869         tw_osli_free_resources(sc);
870         error = 0;
871
872 out:
873         return(error);
874 }
875
876
877
878 /*
879  * Function name:       twa_shutdown
880  * Description:         Called at unload/shutdown time.  Lets the controller
881  *                      know that we are going down.
882  *
883  * Input:               dev     -- bus device corresponding to the ctlr
884  * Output:              None
885  * Return value:        0       -- success
886  *                      non-zero-- failure
887  */
888 static TW_INT32
889 twa_shutdown(device_t dev)
890 {
891         struct twa_softc        *sc = device_get_softc(dev);
892         TW_INT32                error = 0;
893
894         tw_osli_dbg_dprintf(3, sc, "entered");
895
896         /* Disconnect interrupts. */
897         error = twa_teardown_intr(sc);
898
899 #if 0 /* XXX swildner */
900         /* Stop watchdog task. */
901         callout_drain(&(sc->watchdog_callout[0]));
902         callout_drain(&(sc->watchdog_callout[1]));
903 #endif
904
905         /* Disconnect from the controller. */
906         if ((error = tw_cl_shutdown_ctlr(&(sc->ctlr_handle), 0))) {
907                 tw_osli_printf(sc, "error = %d",
908                         TW_CL_SEVERITY_ERROR_STRING,
909                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
910                         0x2015,
911                         "Failed to shutdown Common Layer/controller",
912                         error);
913         }
914         return(error);
915 }
916
917
918
919 #if 0 /* XXX swildner */
920 /*
921  * Function name:       twa_busdma_lock
922  * Description:         Function to provide synchronization during busdma_swi.
923  *
924  * Input:               lock_arg -- lock mutex sent as argument
925  *                      op -- operation (lock/unlock) expected of the function
926  * Output:              None
927  * Return value:        None
928  */
929 TW_VOID
930 twa_busdma_lock(TW_VOID *lock_arg, bus_dma_lock_op_t op)
931 {
932         struct spinlock *lock;
933
934         lock = (struct spinlock *)lock_arg;
935         switch (op) {
936         case BUS_DMA_LOCK:
937                 spin_lock(lock);
938                 break;
939
940         case BUS_DMA_UNLOCK:
941                 spin_unlock(lock);
942                 break;
943
944         default:
945                 panic("Unknown operation 0x%x for twa_busdma_lock!", op);
946         }
947 }
948 #endif
949
950
951 /*
952  * Function name:       twa_pci_intr
953  * Description:         Interrupt handler.  Wrapper for twa_interrupt.
954  *
955  * Input:               arg     -- ptr to OSL internal ctlr context
956  * Output:              None
957  * Return value:        None
958  */
959 static TW_VOID
960 twa_pci_intr(TW_VOID *arg)
961 {
962         struct twa_softc        *sc = (struct twa_softc *)arg;
963
964         tw_osli_dbg_dprintf(10, sc, "entered");
965         tw_cl_interrupt(&(sc->ctlr_handle));
966 }
967
968
969 /*
970  * Function name:       tw_osli_fw_passthru
971  * Description:         Builds a fw passthru cmd pkt, and submits it to CL.
972  *
973  * Input:               sc      -- ptr to OSL internal ctlr context
974  *                      buf     -- ptr to ioctl pkt understood by CL
975  * Output:              None
976  * Return value:        0       -- success
977  *                      non-zero-- failure
978  */
979 TW_INT32
980 tw_osli_fw_passthru(struct twa_softc *sc, TW_INT8 *buf)
981 {
982         struct tw_osli_req_context              *req;
983         struct tw_osli_ioctl_no_data_buf        *user_buf =
984                 (struct tw_osli_ioctl_no_data_buf *)buf;
985         TW_TIME                                 end_time;
986         TW_UINT32                               timeout = 60;
987         TW_UINT32                               data_buf_size_adjusted;
988         struct tw_cl_req_packet                 *req_pkt;
989         struct tw_cl_passthru_req_packet        *pt_req;
990         TW_INT32                                error;
991
992         tw_osli_dbg_dprintf(5, sc, "ioctl: passthru");
993
994         if ((req = tw_osli_get_request(sc)) == NULL)
995                 return(EBUSY);
996
997         req->req_handle.osl_req_ctxt = req;
998         req->orig_req = buf;
999         req->flags |= TW_OSLI_REQ_FLAGS_PASSTHRU;
1000
1001         req_pkt = &(req->req_pkt);
1002         req_pkt->status = 0;
1003         req_pkt->tw_osl_callback = tw_osl_complete_passthru;
1004         /* Let the Common Layer retry the request on cmd queue full. */
1005         req_pkt->flags |= TW_CL_REQ_RETRY_ON_BUSY;
1006
1007         pt_req = &(req_pkt->gen_req_pkt.pt_req);
1008         /*
1009          * Make sure that the data buffer sent to firmware is a
1010          * 512 byte multiple in size.
1011          */
1012         data_buf_size_adjusted =
1013                 (user_buf->driver_pkt.buffer_length +
1014                 (sc->sg_size_factor - 1)) & ~(sc->sg_size_factor - 1);
1015         if ((req->length = data_buf_size_adjusted)) {
1016                 req->data = kmalloc(data_buf_size_adjusted,
1017                     TW_OSLI_MALLOC_CLASS, M_WAITOK);
1018                 /* Copy the payload. */
1019                 if ((error = copyin((TW_VOID *)(user_buf->pdata),
1020                         req->data,
1021                         user_buf->driver_pkt.buffer_length)) != 0) {
1022                         tw_osli_printf(sc, "error = %d",
1023                                 TW_CL_SEVERITY_ERROR_STRING,
1024                                 TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
1025                                 0x2017,
1026                                 "Could not copyin fw_passthru data_buf",
1027                                 error);
1028                         goto fw_passthru_err;
1029                 }
1030                 pt_req->sgl_entries = 1; /* will be updated during mapping */
1031                 req->flags |= (TW_OSLI_REQ_FLAGS_DATA_IN |
1032                         TW_OSLI_REQ_FLAGS_DATA_OUT);
1033         } else
1034                 pt_req->sgl_entries = 0; /* no payload */
1035
1036         pt_req->cmd_pkt = (TW_VOID *)(&(user_buf->cmd_pkt));
1037         pt_req->cmd_pkt_length = sizeof(struct tw_cl_command_packet);
1038
1039         if ((error = tw_osli_map_request(req)))
1040                 goto fw_passthru_err;
1041
1042         end_time = tw_osl_get_local_time() + timeout;
1043         while (req->state != TW_OSLI_REQ_STATE_COMPLETE) {
1044                 lockmgr(req->ioctl_wake_timeout_lock, LK_EXCLUSIVE);
1045                 req->flags |= TW_OSLI_REQ_FLAGS_SLEEPING;
1046
1047                 error = lksleep(req, req->ioctl_wake_timeout_lock, 0,
1048                             "twa_passthru", timeout*hz);
1049                 lockmgr(req->ioctl_wake_timeout_lock, LK_RELEASE);
1050
1051                 if (!(req->flags & TW_OSLI_REQ_FLAGS_SLEEPING))
1052                         error = 0;
1053                 req->flags &= ~TW_OSLI_REQ_FLAGS_SLEEPING;
1054
1055                 if (! error) {
1056                         if (((error = req->error_code)) ||
1057                                 ((error = (req->state !=
1058                                 TW_OSLI_REQ_STATE_COMPLETE))) ||
1059                                 ((error = req_pkt->status)))
1060                                 goto fw_passthru_err;
1061                         break;
1062                 }
1063
1064                 if (req_pkt->status) {
1065                         error = req_pkt->status;
1066                         goto fw_passthru_err;
1067                 }
1068
1069                 if (error == EWOULDBLOCK) {
1070                         /* Time out! */
1071                         if ((!(req->error_code))                       &&
1072                             (req->state == TW_OSLI_REQ_STATE_COMPLETE) &&
1073                             (!(req_pkt->status))                          ) {
1074 #ifdef    TW_OSL_DEBUG
1075                                 tw_osli_printf(sc, "request = %p",
1076                                         TW_CL_SEVERITY_ERROR_STRING,
1077                                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
1078                                         0x7777,
1079                                         "FALSE Passthru timeout!",
1080                                         req);
1081 #endif /* TW_OSL_DEBUG */
1082                                 error = 0; /* False error */
1083                                 break;
1084                         }
1085                         if (!(tw_cl_is_reset_needed(&(req->ctlr->ctlr_handle)))) {
1086 #ifdef    TW_OSL_DEBUG
1087                                 tw_osli_printf(sc, "request = %p",
1088                                         TW_CL_SEVERITY_ERROR_STRING,
1089                                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
1090                                         0x2018,
1091                                         "Passthru request timed out!",
1092                                         req);
1093 #else  /* TW_OSL_DEBUG */
1094                         device_printf((sc)->bus_dev, "Passthru request timed out!\n");
1095 #endif /* TW_OSL_DEBUG */
1096                                 tw_cl_reset_ctlr(&(req->ctlr->ctlr_handle));
1097                         }
1098
1099                         error = 0;
1100                         end_time = tw_osl_get_local_time() + timeout;
1101                         continue;
1102                         /*
1103                          * Don't touch req after a reset.  It (and any
1104                          * associated data) will be
1105                          * unmapped by the callback.
1106                          */
1107                 }
1108                 /*
1109                  * Either the request got completed, or we were woken up by a
1110                  * signal.  Calculate the new timeout, in case it was the latter.
1111                  */
1112                 timeout = (end_time - tw_osl_get_local_time());
1113         } /* End of while loop */
1114
1115         /* If there was a payload, copy it back. */
1116         if ((!error) && (req->length))
1117                 if ((error = copyout(req->data, user_buf->pdata,
1118                         user_buf->driver_pkt.buffer_length)))
1119                         tw_osli_printf(sc, "error = %d",
1120                                 TW_CL_SEVERITY_ERROR_STRING,
1121                                 TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
1122                                 0x2019,
1123                                 "Could not copyout fw_passthru data_buf",
1124                                 error);
1125
1126 fw_passthru_err:
1127
1128         if (req_pkt->status == TW_CL_ERR_REQ_BUS_RESET)
1129                 error = EBUSY;
1130
1131         user_buf->driver_pkt.os_status = error;
1132         /* Free resources. */
1133         if (req->data)
1134                 kfree(req->data, TW_OSLI_MALLOC_CLASS);
1135         tw_osli_req_q_insert_tail(req, TW_OSLI_FREE_Q);
1136         return(error);
1137 }
1138
1139
1140
1141 /*
1142  * Function name:       tw_osl_complete_passthru
1143  * Description:         Called to complete passthru requests.
1144  *
1145  * Input:               req_handle      -- ptr to request handle
1146  * Output:              None
1147  * Return value:        None
1148  */
1149 TW_VOID
1150 tw_osl_complete_passthru(struct tw_cl_req_handle *req_handle)
1151 {
1152         struct tw_osli_req_context      *req = req_handle->osl_req_ctxt;
1153         struct tw_cl_req_packet         *req_pkt =
1154                 (struct tw_cl_req_packet *)(&req->req_pkt);
1155         struct twa_softc                *sc = req->ctlr;
1156
1157         tw_osli_dbg_dprintf(5, sc, "entered");
1158
1159         if (req->state != TW_OSLI_REQ_STATE_BUSY) {
1160                 tw_osli_printf(sc, "request = %p, status = %d",
1161                         TW_CL_SEVERITY_ERROR_STRING,
1162                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
1163                         0x201B,
1164                         "Unposted command completed!!",
1165                         req, req->state);
1166         }
1167
1168         /*
1169          * Remove request from the busy queue.  Just mark it complete.
1170          * There's no need to move it into the complete queue as we are
1171          * going to be done with it right now.
1172          */
1173         req->state = TW_OSLI_REQ_STATE_COMPLETE;
1174         tw_osli_req_q_remove_item(req, TW_OSLI_BUSY_Q);
1175
1176         tw_osli_unmap_request(req);
1177
1178         /*
1179          * Don't do a wake up if there was an error even before the request
1180          * was sent down to the Common Layer, and we hadn't gotten an
1181          * EINPROGRESS.  The request originator will then be returned an
1182          * error, and he can do the clean-up.
1183          */
1184         if ((req->error_code) && (!(req->flags & TW_OSLI_REQ_FLAGS_IN_PROGRESS)))
1185                 return;
1186
1187         if (req->flags & TW_OSLI_REQ_FLAGS_PASSTHRU) {
1188                 if (req->flags & TW_OSLI_REQ_FLAGS_SLEEPING) {
1189                         /* Wake up the sleeping command originator. */
1190                         tw_osli_dbg_dprintf(5, sc,
1191                                 "Waking up originator of request %p", req);
1192                         req->flags &= ~TW_OSLI_REQ_FLAGS_SLEEPING;
1193                         wakeup_one(req);
1194                 } else {
1195                         /*
1196                          * If the request completed even before mtx_sleep
1197                          * was called, simply return.
1198                          */
1199                         if (req->flags & TW_OSLI_REQ_FLAGS_MAPPED)
1200                                 return;
1201
1202                         if (req_pkt->status == TW_CL_ERR_REQ_BUS_RESET)
1203                                 return;
1204
1205                         tw_osli_printf(sc, "request = %p",
1206                                 TW_CL_SEVERITY_ERROR_STRING,
1207                                 TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
1208                                 0x201C,
1209                                 "Passthru callback called, "
1210                                 "and caller not sleeping",
1211                                 req);
1212                 }
1213         } else {
1214                 tw_osli_printf(sc, "request = %p",
1215                         TW_CL_SEVERITY_ERROR_STRING,
1216                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
1217                         0x201D,
1218                         "Passthru callback called for non-passthru request",
1219                         req);
1220         }
1221 }
1222
1223
1224
1225 /*
1226  * Function name:       tw_osli_get_request
1227  * Description:         Gets a request pkt from the free queue.
1228  *
1229  * Input:               sc      -- ptr to OSL internal ctlr context
1230  * Output:              None
1231  * Return value:        ptr to request pkt      -- success
1232  *                      NULL                    -- failure
1233  */
1234 struct tw_osli_req_context *
1235 tw_osli_get_request(struct twa_softc *sc)
1236 {
1237         struct tw_osli_req_context      *req;
1238
1239         tw_osli_dbg_dprintf(4, sc, "entered");
1240
1241         /* Get a free request packet. */
1242         req = tw_osli_req_q_remove_head(sc, TW_OSLI_FREE_Q);
1243
1244         /* Initialize some fields to their defaults. */
1245         if (req) {
1246                 req->req_handle.osl_req_ctxt = NULL;
1247                 req->req_handle.cl_req_ctxt = NULL;
1248                 req->req_handle.is_io = 0;
1249                 req->data = NULL;
1250                 req->length = 0;
1251                 req->deadline = 0;
1252                 req->real_data = NULL;
1253                 req->real_length = 0;
1254                 req->state = TW_OSLI_REQ_STATE_INIT;/* req being initialized */
1255                 req->flags = 0;
1256                 req->error_code = 0;
1257                 req->orig_req = NULL;
1258
1259                 bzero(&(req->req_pkt), sizeof(struct tw_cl_req_packet));
1260
1261         }
1262         return(req);
1263 }
1264
1265
1266
1267 /*
1268  * Function name:       twa_map_load_data_callback
1269  * Description:         Callback of bus_dmamap_load for the buffer associated
1270  *                      with data.  Updates the cmd pkt (size/sgl_entries
1271  *                      fields, as applicable) to reflect the number of sg
1272  *                      elements.
1273  *
1274  * Input:               arg     -- ptr to OSL internal request context
1275  *                      segs    -- ptr to a list of segment descriptors
1276  *                      nsegments--# of segments
1277  *                      error   -- 0 if no errors encountered before callback,
1278  *                                 non-zero if errors were encountered
1279  * Output:              None
1280  * Return value:        None
1281  */
1282 static TW_VOID
1283 twa_map_load_data_callback(TW_VOID *arg, bus_dma_segment_t *segs,
1284         TW_INT32 nsegments, TW_INT32 error)
1285 {
1286         struct tw_osli_req_context      *req =
1287                 (struct tw_osli_req_context *)arg;
1288         struct twa_softc                *sc = req->ctlr;
1289         struct tw_cl_req_packet         *req_pkt = &(req->req_pkt);
1290
1291         tw_osli_dbg_dprintf(10, sc, "entered");
1292
1293         if (error == EINVAL) {
1294                 req->error_code = error;
1295                 return;
1296         }
1297
1298         /* Mark the request as currently being processed. */
1299         req->state = TW_OSLI_REQ_STATE_BUSY;
1300         /* Move the request into the busy queue. */
1301         tw_osli_req_q_insert_tail(req, TW_OSLI_BUSY_Q);
1302
1303         req->flags |= TW_OSLI_REQ_FLAGS_MAPPED;
1304
1305         if (error == EFBIG) {
1306                 req->error_code = error;
1307                 goto out;
1308         }
1309
1310         if (req->flags & TW_OSLI_REQ_FLAGS_PASSTHRU) {
1311                 struct tw_cl_passthru_req_packet        *pt_req;
1312
1313                 if (req->flags & TW_OSLI_REQ_FLAGS_DATA_IN)
1314                         bus_dmamap_sync(sc->ioctl_tag, sc->ioctl_map,
1315                                 BUS_DMASYNC_PREREAD);
1316
1317                 if (req->flags & TW_OSLI_REQ_FLAGS_DATA_OUT) {
1318                         /*
1319                          * If we're using an alignment buffer, and we're
1320                          * writing data, copy the real data out.
1321                          */
1322                         if (req->flags & TW_OSLI_REQ_FLAGS_DATA_COPY_NEEDED)
1323                                 bcopy(req->real_data, req->data, req->real_length);
1324                         bus_dmamap_sync(sc->ioctl_tag, sc->ioctl_map,
1325                                 BUS_DMASYNC_PREWRITE);
1326                 }
1327
1328                 pt_req = &(req_pkt->gen_req_pkt.pt_req);
1329                 pt_req->sg_list = (TW_UINT8 *)segs;
1330                 pt_req->sgl_entries += (nsegments - 1);
1331                 error = tw_cl_fw_passthru(&(sc->ctlr_handle), req_pkt,
1332                         &(req->req_handle));
1333         } else {
1334                 struct tw_cl_scsi_req_packet    *scsi_req;
1335
1336                 if (req->flags & TW_OSLI_REQ_FLAGS_DATA_IN)
1337                         bus_dmamap_sync(sc->dma_tag, req->dma_map,
1338                                 BUS_DMASYNC_PREREAD);
1339
1340                 if (req->flags & TW_OSLI_REQ_FLAGS_DATA_OUT) {
1341                         /*
1342                          * If we're using an alignment buffer, and we're
1343                          * writing data, copy the real data out.
1344                          */
1345                         if (req->flags & TW_OSLI_REQ_FLAGS_DATA_COPY_NEEDED)
1346                                 bcopy(req->real_data, req->data, req->real_length);
1347                         bus_dmamap_sync(sc->dma_tag, req->dma_map,
1348                                 BUS_DMASYNC_PREWRITE);
1349                 }
1350
1351                 scsi_req = &(req_pkt->gen_req_pkt.scsi_req);
1352                 scsi_req->sg_list = (TW_UINT8 *)segs;
1353                 scsi_req->sgl_entries += (nsegments - 1);
1354                 error = tw_cl_start_io(&(sc->ctlr_handle), req_pkt,
1355                         &(req->req_handle));
1356         }
1357
1358 out:
1359         if (error) {
1360                 req->error_code = error;
1361                 req_pkt->tw_osl_callback(&(req->req_handle));
1362                 /*
1363                  * If the caller had been returned EINPROGRESS, and he has
1364                  * registered a callback for handling completion, the callback
1365                  * will never get called because we were unable to submit the
1366                  * request.  So, free up the request right here.
1367                  */
1368                 if (req->flags & TW_OSLI_REQ_FLAGS_IN_PROGRESS)
1369                         tw_osli_req_q_insert_tail(req, TW_OSLI_FREE_Q);
1370         }
1371 }
1372
1373
1374
1375 /*
1376  * Function name:       twa_map_load_callback
1377  * Description:         Callback of bus_dmamap_load for the buffer associated
1378  *                      with a cmd pkt.
1379  *
1380  * Input:               arg     -- ptr to variable to hold phys addr
1381  *                      segs    -- ptr to a list of segment descriptors
1382  *                      nsegments--# of segments
1383  *                      error   -- 0 if no errors encountered before callback,
1384  *                                 non-zero if errors were encountered
1385  * Output:              None
1386  * Return value:        None
1387  */
1388 static TW_VOID
1389 twa_map_load_callback(TW_VOID *arg, bus_dma_segment_t *segs,
1390         TW_INT32 nsegments, TW_INT32 error)
1391 {
1392         *((bus_addr_t *)arg) = segs[0].ds_addr;
1393 }
1394
1395
1396
1397 /*
1398  * Function name:       tw_osli_map_request
1399  * Description:         Maps a cmd pkt and data associated with it, into
1400  *                      DMA'able memory.
1401  *
1402  * Input:               req     -- ptr to request pkt
1403  * Output:              None
1404  * Return value:        0       -- success
1405  *                      non-zero-- failure
1406  */
1407 TW_INT32
1408 tw_osli_map_request(struct tw_osli_req_context *req)
1409 {
1410         struct twa_softc        *sc = req->ctlr;
1411         TW_INT32                error = 0;
1412
1413         tw_osli_dbg_dprintf(10, sc, "entered");
1414
1415         /* If the command involves data, map that too. */
1416         if (req->data != NULL) {
1417                 /*
1418                  * It's sufficient for the data pointer to be 4-byte aligned
1419                  * to work with 9000.  However, if 4-byte aligned addresses
1420                  * are passed to bus_dmamap_load, we can get back sg elements
1421                  * that are not 512-byte multiples in size.  So, we will let
1422                  * only those buffers that are 512-byte aligned to pass
1423                  * through, and bounce the rest, so as to make sure that we
1424                  * always get back sg elements that are 512-byte multiples
1425                  * in size.
1426                  */
1427                 if (((vm_offset_t)req->data % sc->sg_size_factor) ||
1428                         (req->length % sc->sg_size_factor)) {
1429                         req->flags |= TW_OSLI_REQ_FLAGS_DATA_COPY_NEEDED;
1430                         /* Save original data pointer and length. */
1431                         req->real_data = req->data;
1432                         req->real_length = req->length;
1433                         req->length = (req->length +
1434                                 (sc->sg_size_factor - 1)) &
1435                                 ~(sc->sg_size_factor - 1);
1436                         req->data = kmalloc(req->length, TW_OSLI_MALLOC_CLASS,
1437                                         M_NOWAIT);
1438                         if (req->data == NULL) {
1439                                 tw_osli_printf(sc, "error = %d",
1440                                         TW_CL_SEVERITY_ERROR_STRING,
1441                                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
1442                                         0x201E,
1443                                         "Failed to allocate memory "
1444                                         "for bounce buffer",
1445                                         ENOMEM);
1446                                 /* Restore original data pointer and length. */
1447                                 req->data = req->real_data;
1448                                 req->length = req->real_length;
1449                                 return(ENOMEM);
1450                         }
1451                 }
1452
1453                 /*
1454                  * Map the data buffer into bus space and build the SG list.
1455                  */
1456                 if (req->flags & TW_OSLI_REQ_FLAGS_PASSTHRU) {
1457                         /* Lock against multiple simultaneous ioctl calls. */
1458                         spin_lock(sc->io_lock);
1459                         error = bus_dmamap_load(sc->ioctl_tag, sc->ioctl_map,
1460                                 req->data, req->length,
1461                                 twa_map_load_data_callback, req,
1462                                 BUS_DMA_WAITOK);
1463                         spin_unlock(sc->io_lock);
1464                 } else {
1465                         /*
1466                          * There's only one CAM I/O thread running at a time.
1467                          * So, there's no need to hold the io_lock.
1468                          */
1469                         error = bus_dmamap_load(sc->dma_tag, req->dma_map,
1470                                 req->data, req->length,
1471                                 twa_map_load_data_callback, req,
1472                                 BUS_DMA_WAITOK);
1473                 }
1474
1475                 if (!error)
1476                         error = req->error_code;
1477                 else {
1478                         if (error == EINPROGRESS) {
1479                                 /*
1480                                  * Specifying sc->io_lock as the lockfuncarg
1481                                  * in ...tag_create should protect the access
1482                                  * of ...FLAGS_MAPPED from the callback.
1483                                  */
1484                                 spin_lock(sc->io_lock);
1485                                 if (!(req->flags & TW_OSLI_REQ_FLAGS_MAPPED))
1486                                         req->flags |= TW_OSLI_REQ_FLAGS_IN_PROGRESS;
1487                                 tw_osli_disallow_new_requests(sc, &(req->req_handle));
1488                                 spin_unlock(sc->io_lock);
1489                                 error = 0;
1490                         } else {
1491                                 tw_osli_printf(sc, "error = %d",
1492                                         TW_CL_SEVERITY_ERROR_STRING,
1493                                         TW_CL_MESSAGE_SOURCE_FREEBSD_DRIVER,
1494                                         0x9999,
1495                                         "Failed to map DMA memory "
1496                                         "for I/O request",
1497                                         error);
1498                                 req->flags |= TW_OSLI_REQ_FLAGS_FAILED;
1499                                 /* Free alignment buffer if it was used. */
1500                                 if (req->flags &
1501                                         TW_OSLI_REQ_FLAGS_DATA_COPY_NEEDED) {
1502                                         kfree(req->data, TW_OSLI_MALLOC_CLASS);
1503                                         /*
1504                                          * Restore original data pointer
1505                                          * and length.
1506                                          */
1507                                         req->data = req->real_data;
1508                                         req->length = req->real_length;
1509                                 }
1510                         }
1511                 }
1512
1513         } else {
1514                 /* Mark the request as currently being processed. */
1515                 req->state = TW_OSLI_REQ_STATE_BUSY;
1516                 /* Move the request into the busy queue. */
1517                 tw_osli_req_q_insert_tail(req, TW_OSLI_BUSY_Q);
1518                 if (req->flags & TW_OSLI_REQ_FLAGS_PASSTHRU)
1519                         error = tw_cl_fw_passthru(&sc->ctlr_handle,
1520                                         &(req->req_pkt), &(req->req_handle));
1521                 else
1522                         error = tw_cl_start_io(&sc->ctlr_handle,
1523                                         &(req->req_pkt), &(req->req_handle));
1524                 if (error) {
1525                         req->error_code = error;
1526                         req->req_pkt.tw_osl_callback(&(req->req_handle));
1527                 }
1528         }
1529         return(error);
1530 }
1531
1532
1533
1534 /*
1535  * Function name:       tw_osli_unmap_request
1536  * Description:         Undoes the mapping done by tw_osli_map_request.
1537  *
1538  * Input:               req     -- ptr to request pkt
1539  * Output:              None
1540  * Return value:        None
1541  */
1542 TW_VOID
1543 tw_osli_unmap_request(struct tw_osli_req_context *req)
1544 {
1545         struct twa_softc        *sc = req->ctlr;
1546
1547         tw_osli_dbg_dprintf(10, sc, "entered");
1548
1549         /* If the command involved data, unmap that too. */
1550         if (req->data != NULL) {
1551                 if (req->flags & TW_OSLI_REQ_FLAGS_PASSTHRU) {
1552                         /* Lock against multiple simultaneous ioctl calls. */
1553                         spin_lock(sc->io_lock);
1554
1555                         if (req->flags & TW_OSLI_REQ_FLAGS_DATA_IN) {
1556                                 bus_dmamap_sync(sc->ioctl_tag,
1557                                         sc->ioctl_map, BUS_DMASYNC_POSTREAD);
1558
1559                                 /*
1560                                  * If we are using a bounce buffer, and we are
1561                                  * reading data, copy the real data in.
1562                                  */
1563                                 if (req->flags & TW_OSLI_REQ_FLAGS_DATA_COPY_NEEDED)
1564                                         bcopy(req->data, req->real_data,
1565                                                 req->real_length);
1566                         }
1567
1568                         if (req->flags & TW_OSLI_REQ_FLAGS_DATA_OUT)
1569                                 bus_dmamap_sync(sc->ioctl_tag, sc->ioctl_map,
1570                                         BUS_DMASYNC_POSTWRITE);
1571
1572                         bus_dmamap_unload(sc->ioctl_tag, sc->ioctl_map);
1573
1574                         spin_unlock(sc->io_lock);
1575                 } else {
1576                         if (req->flags & TW_OSLI_REQ_FLAGS_DATA_IN) {
1577                                 bus_dmamap_sync(sc->dma_tag,
1578                                         req->dma_map, BUS_DMASYNC_POSTREAD);
1579
1580                                 /*
1581                                  * If we are using a bounce buffer, and we are
1582                                  * reading data, copy the real data in.
1583                                  */
1584                                 if (req->flags & TW_OSLI_REQ_FLAGS_DATA_COPY_NEEDED)
1585                                         bcopy(req->data, req->real_data,
1586                                                 req->real_length);
1587                         }
1588                         if (req->flags & TW_OSLI_REQ_FLAGS_DATA_OUT)
1589                                 bus_dmamap_sync(sc->dma_tag, req->dma_map,
1590                                         BUS_DMASYNC_POSTWRITE);
1591
1592                         bus_dmamap_unload(sc->dma_tag, req->dma_map);
1593                 }
1594         }
1595
1596         /* Free alignment buffer if it was used. */
1597         if (req->flags & TW_OSLI_REQ_FLAGS_DATA_COPY_NEEDED) {
1598                 kfree(req->data, TW_OSLI_MALLOC_CLASS);
1599                 /* Restore original data pointer and length. */
1600                 req->data = req->real_data;
1601                 req->length = req->real_length;
1602         }
1603 }
1604
1605
1606
1607 #ifdef TW_OSL_DEBUG
1608
1609 TW_VOID twa_report_stats(TW_VOID);
1610 TW_VOID twa_reset_stats(TW_VOID);
1611 TW_VOID tw_osli_print_ctlr_stats(struct twa_softc *sc);
1612 TW_VOID twa_print_req_info(struct tw_osli_req_context *req);
1613
1614
1615 /*
1616  * Function name:       twa_report_stats
1617  * Description:         For being called from ddb.  Calls functions that print
1618  *                      OSL and CL internal stats for the controller.
1619  *
1620  * Input:               None
1621  * Output:              None
1622  * Return value:        None
1623  */
1624 TW_VOID
1625 twa_report_stats(TW_VOID)
1626 {
1627         struct twa_softc        *sc;
1628         TW_INT32                i;
1629
1630         for (i = 0; (sc = devclass_get_softc(twa_devclass, i)) != NULL; i++) {
1631                 tw_osli_print_ctlr_stats(sc);
1632                 tw_cl_print_ctlr_stats(&sc->ctlr_handle);
1633         }
1634 }
1635
1636
1637
1638 /*
1639  * Function name:       tw_osli_print_ctlr_stats
1640  * Description:         For being called from ddb.  Prints OSL controller stats
1641  *
1642  * Input:               sc      -- ptr to OSL internal controller context
1643  * Output:              None
1644  * Return value:        None
1645  */
1646 TW_VOID
1647 tw_osli_print_ctlr_stats(struct twa_softc *sc)
1648 {
1649         twa_printf(sc, "osl_ctlr_ctxt = %p\n", sc);
1650         twa_printf(sc, "OSLq type  current  max\n");
1651         twa_printf(sc, "free      %04d     %04d\n",
1652                 sc->q_stats[TW_OSLI_FREE_Q].cur_len,
1653                 sc->q_stats[TW_OSLI_FREE_Q].max_len);
1654         twa_printf(sc, "busy      %04d     %04d\n",
1655                 sc->q_stats[TW_OSLI_BUSY_Q].cur_len,
1656                 sc->q_stats[TW_OSLI_BUSY_Q].max_len);
1657 }
1658
1659
1660
1661 /*
1662  * Function name:       twa_print_req_info
1663  * Description:         For being called from ddb.  Calls functions that print
1664  *                      OSL and CL internal details for the request.
1665  *
1666  * Input:               req     -- ptr to OSL internal request context
1667  * Output:              None
1668  * Return value:        None
1669  */
1670 TW_VOID
1671 twa_print_req_info(struct tw_osli_req_context *req)
1672 {
1673         struct twa_softc        *sc = req->ctlr;
1674
1675         twa_printf(sc, "OSL details for request:\n");
1676         twa_printf(sc, "osl_req_ctxt = %p, cl_req_ctxt = %p\n"
1677                 "data = %p, length = 0x%x, real_data = %p, real_length = 0x%x\n"
1678                 "state = 0x%x, flags = 0x%x, error = 0x%x, orig_req = %p\n"
1679                 "next_req = %p, prev_req = %p, dma_map = %p\n",
1680                 req->req_handle.osl_req_ctxt, req->req_handle.cl_req_ctxt,
1681                 req->data, req->length, req->real_data, req->real_length,
1682                 req->state, req->flags, req->error_code, req->orig_req,
1683                 req->link.next, req->link.prev, req->dma_map);
1684         tw_cl_print_req_info(&(req->req_handle));
1685 }
1686
1687
1688
1689 /*
1690  * Function name:       twa_reset_stats
1691  * Description:         For being called from ddb.
1692  *                      Resets some OSL controller stats.
1693  *
1694  * Input:               None
1695  * Output:              None
1696  * Return value:        None
1697  */
1698 TW_VOID
1699 twa_reset_stats(TW_VOID)
1700 {
1701         struct twa_softc        *sc;
1702         TW_INT32                i;
1703
1704         for (i = 0; (sc = devclass_get_softc(twa_devclass, i)) != NULL; i++) {
1705                 sc->q_stats[TW_OSLI_FREE_Q].max_len = 0;
1706                 sc->q_stats[TW_OSLI_BUSY_Q].max_len = 0;
1707                 tw_cl_reset_stats(&sc->ctlr_handle);
1708         }
1709 }
1710
1711 #endif /* TW_OSL_DEBUG */