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