1/*	$NetBSD: twa.c,v 1.40 2012/01/30 19:41:23 drochner Exp $ */
2/*	$wasabi: twa.c,v 1.27 2006/07/28 18:17:21 wrstuden Exp $	*/
3
4/*-
5 * Copyright (c) 2004 The NetBSD Foundation, Inc.
6 * All rights reserved.
7 *
8 * This code is derived from software contributed to The NetBSD Foundation
9 * by Jordan Rhody of Wasabi Systems, Inc.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 *    notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 *    notice, this list of conditions and the following disclaimer in the
18 *    documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33/*-
34 * Copyright (c) 2003-04 3ware, Inc.
35 * Copyright (c) 2000 Michael Smith
36 * Copyright (c) 2000 BSDi
37 * All rights reserved.
38 *
39 * Redistribution and use in source and binary forms, with or without
40 * modification, are permitted provided that the following conditions
41 * are met:
42 * 1. Redistributions of source code must retain the above copyright
43 *    notice, this list of conditions and the following disclaimer.
44 * 2. Redistributions in binary form must reproduce the above copyright
45 *    notice, this list of conditions and the following disclaimer in the
46 *    documentation and/or other materials provided with the distribution.
47 *
48 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
49 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
52 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58 * SUCH DAMAGE.
59 *
60 *	$FreeBSD: src/sys/dev/twa/twa.c,v 1.2 2004/04/02 15:09:57 des Exp $
61 */
62
63/*
64 * 3ware driver for 9000 series storage controllers.
65 *
66 * Author: Vinod Kashyap
67 */
68
69#include <sys/cdefs.h>
70__KERNEL_RCSID(0, "$NetBSD: twa.c,v 1.40 2012/01/30 19:41:23 drochner Exp $");
71
72#include <sys/param.h>
73#include <sys/systm.h>
74#include <sys/kernel.h>
75#include <sys/device.h>
76#include <sys/queue.h>
77#include <sys/proc.h>
78#include <sys/bswap.h>
79#include <sys/buf.h>
80#include <sys/bufq.h>
81#include <sys/endian.h>
82#include <sys/malloc.h>
83#include <sys/conf.h>
84#include <sys/disk.h>
85#include <sys/sysctl.h>
86#include <sys/syslog.h>
87
88#include <sys/bus.h>
89
90#include <dev/pci/pcireg.h>
91#include <dev/pci/pcivar.h>
92#include <dev/pci/pcidevs.h>
93#include <dev/pci/twareg.h>
94#include <dev/pci/twavar.h>
95#include <dev/pci/twaio.h>
96
97#include <dev/scsipi/scsipi_all.h>
98#include <dev/scsipi/scsipi_disk.h>
99#include <dev/scsipi/scsipiconf.h>
100#include <dev/scsipi/scsi_spc.h>
101
102#include <dev/ldvar.h>
103
104#include "locators.h"
105
106#define	PCI_CBIO	0x10
107
108static int	twa_fetch_aen(struct twa_softc *);
109static void	twa_aen_callback(struct twa_request *);
110static int	twa_find_aen(struct twa_softc *sc, uint16_t);
111static uint16_t	twa_enqueue_aen(struct twa_softc *sc,
112			struct twa_command_header *);
113
114static void	twa_attach(device_t, device_t, void *);
115static void	twa_shutdown(void *);
116static int	twa_init_connection(struct twa_softc *, uint16_t, uint32_t,
117				    uint16_t, uint16_t, uint16_t, uint16_t, uint16_t *,
118					uint16_t *, uint16_t *, uint16_t *, uint32_t *);
119static int	twa_intr(void *);
120static int 	twa_match(device_t, cfdata_t, void *);
121static int	twa_reset(struct twa_softc *);
122
123static int	twa_print(void *, const char *);
124static int	twa_soft_reset(struct twa_softc *);
125
126static int	twa_check_ctlr_state(struct twa_softc *, uint32_t);
127static int	twa_get_param(struct twa_softc *, int, int, size_t,
128				void (* callback)(struct twa_request *),
129				struct twa_param_9k **);
130static int 	twa_set_param(struct twa_softc *, int, int, int, void *,
131				void (* callback)(struct twa_request *));
132static void	twa_describe_controller(struct twa_softc *);
133static int	twa_wait_status(struct twa_softc *, uint32_t, uint32_t);
134static int	twa_done(struct twa_softc *);
135
136extern struct	cfdriver twa_cd;
137extern uint32_t twa_fw_img_size;
138extern uint8_t	twa_fw_img[];
139
140CFATTACH_DECL(twa, sizeof(struct twa_softc),
141    twa_match, twa_attach, NULL, NULL);
142
143/* FreeBSD driver revision for sysctl expected by the 3ware cli */
144const char twaver[] = "1.50.01.002";
145
146/* AEN messages. */
147static const struct twa_message	twa_aen_table[] = {
148	{0x0000, "AEN queue empty"},
149	{0x0001, "Controller reset occurred"},
150	{0x0002, "Degraded unit detected"},
151	{0x0003, "Controller error occured"},
152	{0x0004, "Background rebuild failed"},
153	{0x0005, "Background rebuild done"},
154	{0x0006, "Incomplete unit detected"},
155	{0x0007, "Background initialize done"},
156	{0x0008, "Unclean shutdown detected"},
157	{0x0009, "Drive timeout detected"},
158	{0x000A, "Drive error detected"},
159	{0x000B, "Rebuild started"},
160	{0x000C, "Background initialize started"},
161	{0x000D, "Entire logical unit was deleted"},
162	{0x000E, "Background initialize failed"},
163	{0x000F, "SMART attribute exceeded threshold"},
164	{0x0010, "Power supply reported AC under range"},
165	{0x0011, "Power supply reported DC out of range"},
166	{0x0012, "Power supply reported a malfunction"},
167	{0x0013, "Power supply predicted malfunction"},
168	{0x0014, "Battery charge is below threshold"},
169	{0x0015, "Fan speed is below threshold"},
170	{0x0016, "Temperature sensor is above threshold"},
171	{0x0017, "Power supply was removed"},
172	{0x0018, "Power supply was inserted"},
173	{0x0019, "Drive was removed from a bay"},
174	{0x001A, "Drive was inserted into a bay"},
175	{0x001B, "Drive bay cover door was opened"},
176	{0x001C, "Drive bay cover door was closed"},
177	{0x001D, "Product case was opened"},
178	{0x0020, "Prepare for shutdown (power-off)"},
179	{0x0021, "Downgrade UDMA mode to lower speed"},
180	{0x0022, "Upgrade UDMA mode to higher speed"},
181	{0x0023, "Sector repair completed"},
182	{0x0024, "Sbuf memory test failed"},
183	{0x0025, "Error flushing cached write data to disk"},
184	{0x0026, "Drive reported data ECC error"},
185	{0x0027, "DCB has checksum error"},
186	{0x0028, "DCB version is unsupported"},
187	{0x0029, "Background verify started"},
188	{0x002A, "Background verify failed"},
189	{0x002B, "Background verify done"},
190	{0x002C, "Bad sector overwritten during rebuild"},
191	{0x002D, "Source drive error occurred"},
192	{0x002E, "Replace failed because replacement drive too small"},
193	{0x002F, "Verify failed because array was never initialized"},
194	{0x0030, "Unsupported ATA drive"},
195	{0x0031, "Synchronize host/controller time"},
196	{0x0032, "Spare capacity is inadequate for some units"},
197	{0x0033, "Background migration started"},
198	{0x0034, "Background migration failed"},
199	{0x0035, "Background migration done"},
200	{0x0036, "Verify detected and fixed data/parity mismatch"},
201	{0x0037, "SO-DIMM incompatible"},
202	{0x0038, "SO-DIMM not detected"},
203	{0x0039, "Corrected Sbuf ECC error"},
204	{0x003A, "Drive power on reset detected"},
205	{0x003B, "Background rebuild paused"},
206	{0x003C, "Background initialize paused"},
207	{0x003D, "Background verify paused"},
208	{0x003E, "Background migration paused"},
209	{0x003F, "Corrupt flash file system detected"},
210	{0x0040, "Flash file system repaired"},
211	{0x0041, "Unit number assignments were lost"},
212	{0x0042, "Error during read of primary DCB"},
213	{0x0043, "Latent error found in backup DCB"},
214	{0x0044, "Battery voltage is normal"},
215	{0x0045, "Battery voltage is low"},
216	{0x0046, "Battery voltage is high"},
217	{0x0047, "Battery voltage is too low"},
218	{0x0048, "Battery voltage is too high"},
219	{0x0049, "Battery temperature is normal"},
220	{0x004A, "Battery temperature is low"},
221	{0x004B, "Battery temperature is high"},
222	{0x004C, "Battery temperature is too low"},
223	{0x004D, "Battery temperature is too high"},
224	{0x004E, "Battery capacity test started"},
225	{0x004F, "Cache synchronization skipped"},
226	{0x0050, "Battery capacity test completed"},
227	{0x0051, "Battery health check started"},
228	{0x0052, "Battery health check completed"},
229	{0x0053, "Battery capacity test needed"},
230	{0x0054, "Battery charge termination voltage is at high level"},
231	{0x0055, "Battery charging started"},
232	{0x0056, "Battery charging completed"},
233	{0x0057, "Battery charging fault"},
234	{0x0058, "Battery capacity is below warning level"},
235	{0x0059, "Battery capacity is below error level"},
236	{0x005A, "Battery is present"},
237	{0x005B, "Battery is not present"},
238	{0x005C, "Battery is weak"},
239	{0x005D, "Battery health check failed"},
240	{0x005E, "Cache synchronized after power fail"},
241	{0x005F, "Cache synchronization failed; some data lost"},
242	{0x0060, "Bad cache meta data checksum"},
243	{0x0061, "Bad cache meta data signature"},
244	{0x0062, "Cache meta data restore failed"},
245	{0x0063, "BBU not found after power fail"},
246	{0x00FC, "Recovered/finished array membership update"},
247	{0x00FD, "Handler lockup"},
248	{0x00FE, "Retrying PCI transfer"},
249	{0x00FF, "AEN queue is full"},
250	{0xFFFFFFFF, NULL}
251};
252
253/* AEN severity table. */
254static const char	*twa_aen_severity_table[] = {
255	"None",
256	"ERROR",
257	"WARNING",
258	"INFO",
259	"DEBUG",
260	NULL
261};
262
263/* Error messages. */
264static const struct twa_message	twa_error_table[] = {
265	{0x0100, "SGL entry contains zero data"},
266	{0x0101, "Invalid command opcode"},
267	{0x0102, "SGL entry has unaligned address"},
268	{0x0103, "SGL size does not match command"},
269	{0x0104, "SGL entry has illegal length"},
270	{0x0105, "Command packet is not aligned"},
271	{0x0106, "Invalid request ID"},
272	{0x0107, "Duplicate request ID"},
273	{0x0108, "ID not locked"},
274	{0x0109, "LBA out of range"},
275	{0x010A, "Logical unit not supported"},
276	{0x010B, "Parameter table does not exist"},
277	{0x010C, "Parameter index does not exist"},
278	{0x010D, "Invalid field in CDB"},
279	{0x010E, "Specified port has invalid drive"},
280	{0x010F, "Parameter item size mismatch"},
281	{0x0110, "Failed memory allocation"},
282	{0x0111, "Memory request too large"},
283	{0x0112, "Out of memory segments"},
284	{0x0113, "Invalid address to deallocate"},
285	{0x0114, "Out of memory"},
286	{0x0115, "Out of heap"},
287	{0x0120, "Double degrade"},
288	{0x0121, "Drive not degraded"},
289	{0x0122, "Reconstruct error"},
290	{0x0123, "Replace not accepted"},
291	{0x0124, "Replace drive capacity too small"},
292	{0x0125, "Sector count not allowed"},
293	{0x0126, "No spares left"},
294	{0x0127, "Reconstruct error"},
295	{0x0128, "Unit is offline"},
296	{0x0129, "Cannot update status to DCB"},
297	{0x0130, "Invalid stripe handle"},
298	{0x0131, "Handle that was not locked"},
299	{0x0132, "Handle that was not empy"},
300	{0x0133, "Handle has different owner"},
301	{0x0140, "IPR has parent"},
302	{0x0150, "Illegal Pbuf address alignment"},
303	{0x0151, "Illegal Pbuf transfer length"},
304	{0x0152, "Illegal Sbuf address alignment"},
305	{0x0153, "Illegal Sbuf transfer length"},
306	{0x0160, "Command packet too large"},
307	{0x0161, "SGL exceeds maximum length"},
308	{0x0162, "SGL has too many entries"},
309	{0x0170, "Insufficient resources for rebuilder"},
310	{0x0171, "Verify error (data != parity)"},
311	{0x0180, "Requested segment not in directory of this DCB"},
312	{0x0181, "DCB segment has unsupported version"},
313	{0x0182, "DCB segment has checksum error"},
314	{0x0183, "DCB support (settings) segment invalid"},
315	{0x0184, "DCB UDB (unit descriptor block) segment invalid"},
316	{0x0185, "DCB GUID (globally unique identifier) segment invalid"},
317	{0x01A0, "Could not clear Sbuf"},
318	{0x01C0, "Flash identify failed"},
319	{0x01C1, "Flash out of bounds"},
320	{0x01C2, "Flash verify error"},
321	{0x01C3, "Flash file object not found"},
322	{0x01C4, "Flash file already present"},
323	{0x01C5, "Flash file system full"},
324	{0x01C6, "Flash file not present"},
325	{0x01C7, "Flash file size error"},
326	{0x01C8, "Bad flash file checksum"},
327	{0x01CA, "Corrupt flash file system detected"},
328	{0x01D0, "Invalid field in parameter list"},
329	{0x01D1, "Parameter list length error"},
330	{0x01D2, "Parameter item is not changeable"},
331	{0x01D3, "Parameter item is not saveable"},
332	{0x0200, "UDMA CRC error"},
333	{0x0201, "Internal CRC error"},
334	{0x0202, "Data ECC error"},
335	{0x0203, "ADP level 1 error"},
336	{0x0204, "Port timeout"},
337	{0x0205, "Drive power on reset"},
338	{0x0206, "ADP level 2 error"},
339	{0x0207, "Soft reset failed"},
340	{0x0208, "Drive not ready"},
341	{0x0209, "Unclassified port error"},
342	{0x020A, "Drive aborted command"},
343	{0x0210, "Internal CRC error"},
344	{0x0211, "Host PCI bus abort"},
345	{0x0212, "Host PCI parity error"},
346	{0x0213, "Port handler error"},
347	{0x0214, "Token interrupt count error"},
348	{0x0215, "Timeout waiting for PCI transfer"},
349	{0x0216, "Corrected buffer ECC"},
350	{0x0217, "Uncorrected buffer ECC"},
351	{0x0230, "Unsupported command during flash recovery"},
352	{0x0231, "Next image buffer expected"},
353	{0x0232, "Binary image architecture incompatible"},
354	{0x0233, "Binary image has no signature"},
355	{0x0234, "Binary image has bad checksum"},
356	{0x0235, "Image downloaded overflowed buffer"},
357	{0x0240, "I2C device not found"},
358	{0x0241, "I2C transaction aborted"},
359	{0x0242, "SO-DIMM parameter(s) incompatible using defaults"},
360	{0x0243, "SO-DIMM unsupported"},
361	{0x0248, "SPI transfer status error"},
362	{0x0249, "SPI transfer timeout error"},
363	{0x0250, "Invalid unit descriptor size in CreateUnit"},
364	{0x0251, "Unit descriptor size exceeds data buffer in CreateUnit"},
365	{0x0252, "Invalid value in CreateUnit descriptor"},
366	{0x0253, "Inadequate disk space to support descriptor in CreateUnit"},
367	{0x0254, "Unable to create data channel for this unit descriptor"},
368	{0x0255, "CreateUnit descriptor specifies a drive already in use"},
369       {0x0256, "Unable to write configuration to all disks during CreateUnit"},
370	{0x0257, "CreateUnit does not support this descriptor version"},
371	{0x0258, "Invalid subunit for RAID 0 or 5 in CreateUnit"},
372	{0x0259, "Too many descriptors in CreateUnit"},
373	{0x025A, "Invalid configuration specified in CreateUnit descriptor"},
374	{0x025B, "Invalid LBA offset specified in CreateUnit descriptor"},
375	{0x025C, "Invalid stripelet size specified in CreateUnit descriptor"},
376	{0x0260, "SMART attribute exceeded threshold"},
377	{0xFFFFFFFF, NULL}
378};
379
380struct twa_pci_identity {
381	uint32_t	vendor_id;
382	uint32_t	product_id;
383	const char	*name;
384};
385
386static const struct twa_pci_identity twa_pci_products[] = {
387	{ PCI_VENDOR_3WARE,
388	  PCI_PRODUCT_3WARE_9000,
389	  "3ware 9000 series",
390	},
391	{ PCI_VENDOR_3WARE,
392	  PCI_PRODUCT_3WARE_9550,
393	  "3ware 9550SX series",
394	},
395	{ PCI_VENDOR_3WARE,
396	  PCI_PRODUCT_3WARE_9650,
397	  "3ware 9650SE series",
398	},
399	{ PCI_VENDOR_3WARE,
400	  PCI_PRODUCT_3WARE_9690,
401	  "3ware 9690 series",
402	},
403	{ 0,
404	  0,
405	  NULL,
406	},
407};
408
409
410static inline void
411twa_outl(struct twa_softc *sc, int off, uint32_t val)
412{
413
414	bus_space_write_4(sc->twa_bus_iot, sc->twa_bus_ioh, off, val);
415	bus_space_barrier(sc->twa_bus_iot, sc->twa_bus_ioh, off, 4,
416	    BUS_SPACE_BARRIER_WRITE);
417}
418
419static inline uint32_t	twa_inl(struct twa_softc *sc, int off)
420{
421
422	bus_space_barrier(sc->twa_bus_iot, sc->twa_bus_ioh, off, 4,
423	    BUS_SPACE_BARRIER_WRITE | BUS_SPACE_BARRIER_READ);
424	return (bus_space_read_4(sc->twa_bus_iot, sc->twa_bus_ioh, off));
425}
426
427void
428twa_request_wait_handler(struct twa_request *tr)
429{
430
431	wakeup(tr);
432}
433
434static const struct twa_pci_identity *
435twa_lookup(pcireg_t id)
436{
437	const struct twa_pci_identity *entry;
438	int i;
439
440	for (i = 0; i < __arraycount(twa_pci_products); i++) {
441		entry = &twa_pci_products[i];
442		if (entry->vendor_id == PCI_VENDOR(id) &&
443		    entry->product_id == PCI_PRODUCT(id)) {
444			return entry;
445		}
446	}
447	return NULL;
448}
449
450static int
451twa_match(device_t parent, cfdata_t cfdata, void *aux)
452{
453	struct pci_attach_args *pa = aux;
454	const struct twa_pci_identity *entry;
455
456	entry = twa_lookup(pa->pa_id);
457	if (entry != NULL) {
458		return 1;
459	}
460	return (0);
461}
462
463static const char *
464twa_find_msg_string(const struct twa_message *table, uint16_t code)
465{
466	int	i;
467
468	for (i = 0; table[i].message != NULL; i++)
469		if (table[i].code == code)
470			return(table[i].message);
471
472	return(table[i].message);
473}
474
475void
476twa_release_request(struct twa_request *tr)
477{
478	int s;
479	struct twa_softc *sc;
480
481	sc = tr->tr_sc;
482
483	if ((tr->tr_flags & TWA_CMD_AEN) == 0) {
484		s = splbio();
485		TAILQ_INSERT_TAIL(&tr->tr_sc->twa_free, tr, tr_link);
486		splx(s);
487		if (__predict_false((tr->tr_sc->twa_sc_flags &
488		    TWA_STATE_REQUEST_WAIT) != 0)) {
489			tr->tr_sc->twa_sc_flags &= ~TWA_STATE_REQUEST_WAIT;
490			wakeup(&sc->twa_free);
491		}
492	} else
493		tr->tr_flags &= ~TWA_CMD_AEN_BUSY;
494}
495
496static void
497twa_unmap_request(struct twa_request *tr)
498{
499	struct twa_softc	*sc = tr->tr_sc;
500	uint8_t			cmd_status;
501	int s;
502
503	/* If the command involved data, unmap that too. */
504	if (tr->tr_data != NULL) {
505		if (tr->tr_cmd_pkt_type & TWA_CMD_PKT_TYPE_9K)
506			cmd_status = tr->tr_command->command.cmd_pkt_9k.status;
507		else
508			cmd_status =
509			      tr->tr_command->command.cmd_pkt_7k.generic.status;
510
511		if (tr->tr_flags & TWA_CMD_DATA_OUT) {
512			bus_dmamap_sync(tr->tr_sc->twa_dma_tag, tr->tr_dma_map,
513				0, tr->tr_length, BUS_DMASYNC_POSTREAD);
514			/*
515			 * If we are using a bounce buffer, and we are reading
516			 * data, copy the real data in.
517			 */
518			if (tr->tr_flags & TWA_CMD_DATA_COPY_NEEDED)
519				if (cmd_status == 0)
520					memcpy(tr->tr_real_data, tr->tr_data,
521						tr->tr_real_length);
522		}
523		if (tr->tr_flags & TWA_CMD_DATA_IN)
524			bus_dmamap_sync(tr->tr_sc->twa_dma_tag, tr->tr_dma_map,
525				0, tr->tr_length, BUS_DMASYNC_POSTWRITE);
526
527		bus_dmamap_unload(sc->twa_dma_tag, tr->tr_dma_map);
528	}
529
530	/* Free alignment buffer if it was used. */
531	if (tr->tr_flags & TWA_CMD_DATA_COPY_NEEDED) {
532		s = splvm();
533		uvm_km_kmem_free(kmem_va_arena, (vaddr_t)tr->tr_data,
534		    tr->tr_length);
535		splx(s);
536		tr->tr_data = tr->tr_real_data;
537		tr->tr_length = tr->tr_real_length;
538	}
539}
540
541/*
542 * Function name:	twa_wait_request
543 * Description:		Sends down a firmware cmd, and waits for the completion,
544 *			but NOT in a tight loop.
545 *
546 * Input:		tr	-- ptr to request pkt
547 *			timeout -- max # of seconds to wait before giving up
548 * Output:		None
549 * Return value:	0	-- success
550 *			non-zero-- failure
551 */
552static int
553twa_wait_request(struct twa_request *tr, uint32_t timeout)
554{
555	time_t	end_time;
556	struct timeval	t1;
557	int	s, rv;
558
559	tr->tr_flags |= TWA_CMD_SLEEP_ON_REQUEST;
560	tr->tr_callback = twa_request_wait_handler;
561	tr->tr_status = TWA_CMD_BUSY;
562
563	rv = twa_map_request(tr);
564
565	if (rv != 0)
566		return (rv);
567
568	microtime(&t1);
569	end_time = t1.tv_usec +
570		(timeout * 1000 * 100);
571
572	while (tr->tr_status != TWA_CMD_COMPLETE) {
573		rv = tr->tr_error;
574		if (rv != 0)
575			return(rv);
576		if ((rv = tsleep(tr, PRIBIO, "twawait", timeout * hz)) == 0)
577			break;
578
579		if (rv == EWOULDBLOCK) {
580			/*
581			 * We will reset the controller only if the request has
582			 * already been submitted, so as to not lose the
583			 * request packet.  If a busy request timed out, the
584			 * reset will take care of freeing resources.  If a
585			 * pending request timed out, we will free resources
586			 * for that request, right here.  So, the caller is
587			 * expected to NOT cleanup when ETIMEDOUT is returned.
588			 */
589			if (tr->tr_status == TWA_CMD_BUSY)
590				twa_reset(tr->tr_sc);
591			else {
592				/* Request was never submitted.  Clean up. */
593				s = splbio();
594				TAILQ_REMOVE(&tr->tr_sc->twa_pending, tr,
595				    tr_link);
596				splx(s);
597
598				twa_unmap_request(tr);
599				if (tr->tr_data)
600					free(tr->tr_data, M_DEVBUF);
601
602				twa_release_request(tr);
603			}
604			return(ETIMEDOUT);
605		}
606		/*
607		 * Either the request got completed, or we were woken up by a
608		 * signal. Calculate the new timeout, in case it was the
609		 * latter.
610		 */
611		microtime(&t1);
612
613		timeout = (end_time - t1.tv_usec) / (1000 * 100);
614	}
615	return(rv);
616}
617
618/*
619 * Function name:	twa_immediate_request
620 * Description:		Sends down a firmware cmd, and waits for the completion
621 *			in a tight loop.
622 *
623 * Input:		tr	-- ptr to request pkt
624 *			timeout -- max # of seconds to wait before giving up
625 * Output:		None
626 * Return value:	0	-- success
627 *			non-zero-- failure
628 */
629static int
630twa_immediate_request(struct twa_request *tr, uint32_t timeout)
631{
632	struct timeval t1;
633	int	s = 0, rv = 0;
634
635	rv = twa_map_request(tr);
636
637	if (rv != 0)
638		return(rv);
639
640	timeout = (timeout * 10000 * 10);
641
642	microtime(&t1);
643
644	timeout += t1.tv_usec;
645
646	do {
647		rv = tr->tr_error;
648		if (rv != 0)
649			return(rv);
650		s = splbio();
651		twa_done(tr->tr_sc);
652		splx(s);
653		if (tr->tr_status == TWA_CMD_COMPLETE)
654			return(rv);
655		microtime(&t1);
656	} while (t1.tv_usec <= timeout);
657
658	/*
659	 * We will reset the controller only if the request has
660	 * already been submitted, so as to not lose the
661	 * request packet.  If a busy request timed out, the
662	 * reset will take care of freeing resources.  If a
663	 * pending request timed out, we will free resources
664	 * for that request, right here.  So, the caller is
665	 * expected to NOT cleanup when ETIMEDOUT is returned.
666	 */
667	rv = ETIMEDOUT;
668
669	if (tr->tr_status == TWA_CMD_BUSY)
670		twa_reset(tr->tr_sc);
671	else {
672		/* Request was never submitted.  Clean up. */
673		s = splbio();
674		TAILQ_REMOVE(&tr->tr_sc->twa_pending, tr, tr_link);
675		splx(s);
676		twa_unmap_request(tr);
677		if (tr->tr_data)
678			free(tr->tr_data, M_DEVBUF);
679
680		twa_release_request(tr);
681	}
682	return (rv);
683}
684
685static int
686twa_inquiry(struct twa_request *tr, int lunid)
687{
688	int error;
689	struct twa_command_9k *tr_9k_cmd;
690
691	if (tr->tr_data == NULL)
692		return (ENOMEM);
693
694	memset(tr->tr_data, 0, TWA_SECTOR_SIZE);
695
696	tr->tr_length = TWA_SECTOR_SIZE;
697	tr->tr_cmd_pkt_type = TWA_CMD_PKT_TYPE_9K;
698	tr->tr_flags |= TWA_CMD_DATA_IN | TWA_CMD_DATA_OUT;
699
700	tr_9k_cmd = &tr->tr_command->command.cmd_pkt_9k;
701
702	tr_9k_cmd->command.opcode = TWA_OP_EXECUTE_SCSI_COMMAND;
703	tr_9k_cmd->unit = lunid;
704	tr_9k_cmd->request_id = tr->tr_request_id;
705	tr_9k_cmd->status = 0;
706	tr_9k_cmd->sgl_offset = 16;
707	tr_9k_cmd->sgl_entries = 1;
708	/* create the CDB here */
709	tr_9k_cmd->cdb[0] = INQUIRY;
710	tr_9k_cmd->cdb[1] = ((lunid << 5) & 0x0e);
711	tr_9k_cmd->cdb[4] = 255;
712
713	/* XXXX setup page data no lun device
714	 * it seems 9000 series does not indicate
715	 * NOTPRESENT - need more investigation
716	 */
717	((struct scsipi_inquiry_data *)tr->tr_data)->device =
718		SID_QUAL_LU_NOTPRESENT;
719
720	error = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
721	if (error != 0)
722		return (error);
723
724	if (((struct scsipi_inquiry_data *)tr->tr_data)->device ==
725		SID_QUAL_LU_NOTPRESENT)
726		error = 1;
727
728	return (error);
729}
730
731static int
732twa_print_inquiry_data(struct twa_softc *sc, struct scsipi_inquiry_data *scsipi)
733{
734
735    printf("%s: %s\n", device_xname(&sc->twa_dv), scsipi->vendor);
736
737    return (1);
738}
739
740
741static uint64_t
742twa_read_capacity(struct twa_request *tr, int lunid)
743{
744	int error;
745	struct twa_command_9k *tr_9k_cmd;
746	uint64_t array_size = 0LL;
747
748	if (tr->tr_data == NULL)
749		return (ENOMEM);
750
751	memset(tr->tr_data, 0, TWA_SECTOR_SIZE);
752
753	tr->tr_length = TWA_SECTOR_SIZE;
754	tr->tr_cmd_pkt_type = TWA_CMD_PKT_TYPE_9K;
755	tr->tr_flags |= TWA_CMD_DATA_OUT;
756
757	tr_9k_cmd = &tr->tr_command->command.cmd_pkt_9k;
758
759	tr_9k_cmd->command.opcode = TWA_OP_EXECUTE_SCSI_COMMAND;
760	tr_9k_cmd->unit = lunid;
761	tr_9k_cmd->request_id = tr->tr_request_id;
762	tr_9k_cmd->status = 0;
763	tr_9k_cmd->sgl_offset = 16;
764	tr_9k_cmd->sgl_entries = 1;
765	/* create the CDB here */
766	tr_9k_cmd->cdb[0] = READ_CAPACITY_16;
767	tr_9k_cmd->cdb[1] = ((lunid << 5) & 0x0e) | SRC16_SERVICE_ACTION;
768
769	error = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
770
771	if (error == 0) {
772#if BYTE_ORDER == BIG_ENDIAN
773		array_size = bswap64(_8btol(
774		    ((struct scsipi_read_capacity_16_data *)tr->tr_data->addr) + 1);
775#else
776		array_size = _8btol(((struct scsipi_read_capacity_16_data *)
777				tr->tr_data)->addr) + 1;
778#endif
779	}
780	return (array_size);
781}
782
783static int
784twa_request_sense(struct twa_request *tr, int lunid)
785{
786	int error = 1;
787	struct twa_command_9k *tr_9k_cmd;
788
789	if (tr->tr_data == NULL)
790		return (error);
791
792	memset(tr->tr_data, 0, TWA_SECTOR_SIZE);
793
794	tr->tr_length = TWA_SECTOR_SIZE;
795	tr->tr_cmd_pkt_type = TWA_CMD_PKT_TYPE_9K;
796	tr->tr_flags |= TWA_CMD_DATA_OUT;
797
798	tr_9k_cmd = &tr->tr_command->command.cmd_pkt_9k;
799
800	tr_9k_cmd->command.opcode = TWA_OP_EXECUTE_SCSI_COMMAND;
801	tr_9k_cmd->unit = lunid;
802	tr_9k_cmd->request_id = tr->tr_request_id;
803	tr_9k_cmd->status = 0;
804	tr_9k_cmd->sgl_offset = 16;
805	tr_9k_cmd->sgl_entries = 1;
806	/* create the CDB here */
807	tr_9k_cmd->cdb[0] = SCSI_REQUEST_SENSE;
808	tr_9k_cmd->cdb[1] = ((lunid << 5) & 0x0e);
809	tr_9k_cmd->cdb[4] = 255;
810
811	/*XXX AEN notification called in interrupt context
812	 * so just queue the request. Return as quickly
813	 * as possible from interrupt
814	 */
815	if ((tr->tr_flags & TWA_CMD_AEN) != 0)
816		error = twa_map_request(tr);
817 	else
818		error = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
819
820	return (error);
821}
822
823static int
824twa_alloc_req_pkts(struct twa_softc *sc, int num_reqs)
825{
826	struct twa_request	*tr;
827	struct twa_command_packet *tc;
828	bus_dma_segment_t	seg;
829	size_t max_segs, max_xfer;
830	int	i, rv, rseg, size;
831
832	if ((sc->sc_units = malloc(sc->sc_nunits *
833	    sizeof(struct twa_drive), M_DEVBUF, M_NOWAIT|M_ZERO)) == NULL)
834		return(ENOMEM);
835
836	if ((sc->twa_req_buf = malloc(num_reqs * sizeof(struct twa_request),
837					M_DEVBUF, M_NOWAIT)) == NULL)
838		return(ENOMEM);
839
840	size = num_reqs * sizeof(struct twa_command_packet);
841
842	/* Allocate memory for cmd pkts. */
843	if ((rv = bus_dmamem_alloc(sc->twa_dma_tag,
844		size, PAGE_SIZE, 0, &seg,
845		1, &rseg, BUS_DMA_NOWAIT)) != 0){
846			aprint_error_dev(&sc->twa_dv, "unable to allocate "
847				"command packets, rv = %d\n", rv);
848			return (ENOMEM);
849	}
850
851	if ((rv = bus_dmamem_map(sc->twa_dma_tag,
852		&seg, rseg, size, (void **)&sc->twa_cmds,
853		BUS_DMA_NOWAIT | BUS_DMA_COHERENT)) != 0) {
854			aprint_error_dev(&sc->twa_dv, "unable to map commands, rv = %d\n", rv);
855			return (1);
856	}
857
858	if ((rv = bus_dmamap_create(sc->twa_dma_tag,
859		size, num_reqs, size,
860		0, BUS_DMA_NOWAIT, &sc->twa_cmd_map)) != 0) {
861			aprint_error_dev(&sc->twa_dv, "unable to create command DMA map, "
862				"rv = %d\n", rv);
863			return (ENOMEM);
864	}
865
866	if ((rv = bus_dmamap_load(sc->twa_dma_tag, sc->twa_cmd_map,
867		sc->twa_cmds, size, NULL,
868		BUS_DMA_NOWAIT)) != 0) {
869			aprint_error_dev(&sc->twa_dv, "unable to load command DMA map, "
870				"rv = %d\n", rv);
871			return (1);
872	}
873
874	if ((uintptr_t)sc->twa_cmds % TWA_ALIGNMENT) {
875		aprint_error_dev(&sc->twa_dv, "DMA map memory not aligned on %d boundary\n", TWA_ALIGNMENT);
876
877		return (1);
878	}
879	tc = sc->twa_cmd_pkt_buf = (struct twa_command_packet *)sc->twa_cmds;
880	sc->twa_cmd_pkt_phys = sc->twa_cmd_map->dm_segs[0].ds_addr;
881
882	memset(sc->twa_req_buf, 0, num_reqs * sizeof(struct twa_request));
883	memset(sc->twa_cmd_pkt_buf, 0,
884		num_reqs * sizeof(struct twa_command_packet));
885
886	sc->sc_twa_request = sc->twa_req_buf;
887	max_segs = twa_get_maxsegs();
888	max_xfer = twa_get_maxxfer(max_segs);
889
890	for (i = 0; i < num_reqs; i++, tc++) {
891		tr = &(sc->twa_req_buf[i]);
892		tr->tr_command = tc;
893		tr->tr_cmd_phys = sc->twa_cmd_pkt_phys +
894				(i * sizeof(struct twa_command_packet));
895		tr->tr_request_id = i;
896		tr->tr_sc = sc;
897
898		/*
899		 * Create a map for data buffers.  maxsize (256 * 1024) used in
900		 * bus_dma_tag_create above should suffice the bounce page needs
901		 * for data buffers, since the max I/O size we support is 128KB.
902		 * If we supported I/O's bigger than 256KB, we would have to
903		 * create a second dma_tag, with the appropriate maxsize.
904		 */
905		if ((rv = bus_dmamap_create(sc->twa_dma_tag,
906			max_xfer, max_segs, 1, 0, BUS_DMA_NOWAIT,
907			&tr->tr_dma_map)) != 0) {
908				aprint_error_dev(&sc->twa_dv, "unable to create command "
909					"DMA map, rv = %d\n", rv);
910				return (ENOMEM);
911		}
912		/* Insert request into the free queue. */
913		if (i != 0) {
914			sc->twa_lookup[i] = tr;
915			twa_release_request(tr);
916		} else
917			tr->tr_flags |= TWA_CMD_AEN;
918	}
919	return(0);
920}
921
922static void
923twa_recompute_openings(struct twa_softc *sc)
924{
925	struct twa_drive *td;
926	int unit;
927	int openings;
928	uint64_t total_size;
929
930	total_size = 0;
931	for (unit = 0; unit < sc->sc_nunits; unit++) {
932		td = &sc->sc_units[unit];
933		total_size += td->td_size;
934	}
935
936	for (unit = 0; unit < sc->sc_nunits; unit++) {
937		td = &sc->sc_units[unit];
938		/*
939		 * In theory, TWA_Q_LENGTH - 1 should be usable, but
940		 * keep one additional ccb for internal commands.
941		 * This makes the controller more reliable under load.
942		 */
943		if (total_size > 0) {
944			openings = (TWA_Q_LENGTH - 2) * td->td_size / total_size;
945		} else
946			openings = 0;
947
948		if (openings == td->td_openings)
949			continue;
950		td->td_openings = openings;
951
952#ifdef TWA_DEBUG
953		printf("%s: unit %d openings %d\n",
954				device_xname(&sc->twa_dv), unit, openings);
955#endif
956		if (td->td_dev != NULL)
957			(*td->td_callbacks->tcb_openings)(td->td_dev, td->td_openings);
958	}
959}
960
961static int
962twa_request_bus_scan(struct twa_softc *sc)
963{
964	struct twa_drive *td;
965	struct twa_request *tr;
966	struct twa_attach_args twaa;
967	int locs[TWACF_NLOCS];
968	int s, unit;
969
970	s = splbio();
971	for (unit = 0; unit < sc->sc_nunits; unit++) {
972
973		if ((tr = twa_get_request(sc, 0)) == NULL) {
974			splx(s);
975			return (EIO);
976		}
977
978		tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
979
980		tr->tr_data = malloc(TWA_SECTOR_SIZE, M_DEVBUF, M_NOWAIT);
981
982		if (tr->tr_data == NULL) {
983			twa_release_request(tr);
984			splx(s);
985			return (ENOMEM);
986		}
987		td = &sc->sc_units[unit];
988
989		if (twa_inquiry(tr, unit) == 0) {
990			if (td->td_dev == NULL) {
991	    			twa_print_inquiry_data(sc,
992				   ((struct scsipi_inquiry_data *)tr->tr_data));
993
994				sc->sc_units[unit].td_size =
995					twa_read_capacity(tr, unit);
996
997				twaa.twaa_unit = unit;
998
999				twa_recompute_openings(sc);
1000
1001				locs[TWACF_UNIT] = unit;
1002
1003				sc->sc_units[unit].td_dev =
1004				    config_found_sm_loc(&sc->twa_dv, "twa",
1005				    locs, &twaa, twa_print, config_stdsubmatch);
1006			}
1007		} else {
1008			if (td->td_dev != NULL) {
1009				(void) config_detach(td->td_dev, DETACH_FORCE);
1010				td->td_dev = NULL;
1011				td->td_size = 0;
1012
1013				twa_recompute_openings(sc);
1014			}
1015		}
1016		free(tr->tr_data, M_DEVBUF);
1017
1018		twa_release_request(tr);
1019	}
1020	splx(s);
1021
1022	return (0);
1023}
1024
1025
1026#ifdef	DIAGNOSTIC
1027static inline void
1028twa_check_busy_q(struct twa_request *tr)
1029{
1030	struct twa_request *rq;
1031	struct twa_softc *sc = tr->tr_sc;
1032
1033	TAILQ_FOREACH(rq, &sc->twa_busy, tr_link) {
1034		if (tr->tr_request_id == rq->tr_request_id) {
1035			panic("cannot submit same request more than once");
1036		} else if (tr->bp == rq->bp && tr->bp != 0) {
1037			/* XXX A check for 0 for the buf ptr is needed to
1038			 * guard against ioctl requests with a buf ptr of
1039			 * 0 and also aen notifications. Looking for
1040			 * external cmds only.
1041			 */
1042			panic("cannot submit same buf more than once");
1043		} else {
1044			/* Empty else statement */
1045		}
1046	}
1047}
1048#endif
1049
1050static int
1051twa_start(struct twa_request *tr)
1052{
1053	struct twa_softc	*sc = tr->tr_sc;
1054	uint32_t		status_reg;
1055	int			s;
1056	int			error;
1057
1058	s = splbio();
1059
1060	/*
1061	 * The 9650 and 9690 have a bug in the detection of the full queue
1062	 * condition.
1063	 *
1064	 * If a write operation has filled the queue and is directly followed
1065	 * by a status read, it sometimes doesn't return the correct result.
1066	 * To work around this, the upper 32bit are written first.
1067	 * This effectively serialises the hardware, but does not change
1068	 * the state of the queue.
1069	 */
1070	if (sc->sc_quirks & TWA_QUIRK_QUEUEFULL_BUG) {
1071		/* Write lower 32 bits of address */
1072		TWA_WRITE_COMMAND_QUEUE_LOW(sc, tr->tr_cmd_phys +
1073			sizeof(struct twa_command_header));
1074	}
1075
1076	/* Check to see if we can post a command. */
1077	status_reg = twa_inl(sc, TWA_STATUS_REGISTER_OFFSET);
1078	if ((error = twa_check_ctlr_state(sc, status_reg)))
1079		goto out;
1080
1081	if (status_reg & TWA_STATUS_COMMAND_QUEUE_FULL) {
1082			if (tr->tr_status != TWA_CMD_PENDING) {
1083				tr->tr_status = TWA_CMD_PENDING;
1084				TAILQ_INSERT_TAIL(&tr->tr_sc->twa_pending,
1085					tr, tr_link);
1086			}
1087			twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
1088					TWA_CONTROL_UNMASK_COMMAND_INTERRUPT);
1089			error = EBUSY;
1090	} else {
1091	   	bus_dmamap_sync(sc->twa_dma_tag, sc->twa_cmd_map,
1092			(char *)tr->tr_command - (char *)sc->twa_cmds,
1093			sizeof(struct twa_command_packet),
1094			BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
1095
1096		if (sc->sc_quirks & TWA_QUIRK_QUEUEFULL_BUG) {
1097			/*
1098			 * Cmd queue is not full.  Post the command
1099			 * by writing upper 32 bits of address.
1100			 */
1101			TWA_WRITE_COMMAND_QUEUE_HIGH(sc, tr->tr_cmd_phys +
1102				sizeof(struct twa_command_header));
1103		} else {
1104			/* Cmd queue is not full.  Post the command. */
1105			TWA_WRITE_COMMAND_QUEUE(sc, tr->tr_cmd_phys +
1106				sizeof(struct twa_command_header));
1107		}
1108
1109		/* Mark the request as currently being processed. */
1110		tr->tr_status = TWA_CMD_BUSY;
1111
1112#ifdef	DIAGNOSTIC
1113		twa_check_busy_q(tr);
1114#endif
1115
1116		/* Move the request into the busy queue. */
1117		TAILQ_INSERT_TAIL(&tr->tr_sc->twa_busy, tr, tr_link);
1118	}
1119out:
1120	splx(s);
1121	return(error);
1122}
1123
1124static int
1125twa_drain_response_queue(struct twa_softc *sc)
1126{
1127	union twa_response_queue	rq;
1128	uint32_t			status_reg;
1129
1130	for (;;) {
1131		status_reg = twa_inl(sc, TWA_STATUS_REGISTER_OFFSET);
1132		if (twa_check_ctlr_state(sc, status_reg))
1133			return(1);
1134		if (status_reg & TWA_STATUS_RESPONSE_QUEUE_EMPTY)
1135			return(0); /* no more response queue entries */
1136		rq.value = twa_inl(sc, TWA_RESPONSE_QUEUE_OFFSET);
1137	}
1138}
1139
1140/*
1141 * twa_drain_response_queue_large:
1142 *
1143 * specific to the 9550 and 9650 controller to remove requests.
1144 *
1145 * Removes all requests from "large" response queue on the 9550 controller.
1146 * This procedure is called as part of the 9550 controller reset sequence.
1147 */
1148static int
1149twa_drain_response_queue_large(struct twa_softc *sc, uint32_t timeout)
1150{
1151	uint32_t	start_time = 0, end_time;
1152	uint32_t	response = 0;
1153
1154	if (sc->sc_product_id == PCI_PRODUCT_3WARE_9550 ||
1155	    sc->sc_product_id == PCI_PRODUCT_3WARE_9650 ) {
1156	       start_time = 0;
1157	       end_time = (timeout * TWA_MICROSECOND);
1158
1159	       while ((response &
1160		   TWA_9550SX_DRAIN_COMPLETE) != TWA_9550SX_DRAIN_COMPLETE) {
1161			response = twa_inl(sc, TWA_RESPONSE_QUEUE_LARGE_OFFSET);
1162			if (start_time >= end_time)
1163			       return (1);
1164			DELAY(1);
1165			start_time++;
1166	       }
1167	       /* P-chip delay */
1168	       DELAY(500000);
1169       }
1170       return (0);
1171}
1172
1173static void
1174twa_drain_busy_queue(struct twa_softc *sc)
1175{
1176	struct twa_request	*tr;
1177
1178	/* Walk the busy queue. */
1179
1180	while ((tr = TAILQ_FIRST(&sc->twa_busy)) != NULL) {
1181		TAILQ_REMOVE(&sc->twa_busy, tr, tr_link);
1182
1183		twa_unmap_request(tr);
1184		if ((tr->tr_cmd_pkt_type & TWA_CMD_PKT_TYPE_INTERNAL) ||
1185			(tr->tr_cmd_pkt_type & TWA_CMD_PKT_TYPE_IOCTL)) {
1186			/* It's an internal/ioctl request.  Simply free it. */
1187			if (tr->tr_data)
1188				free(tr->tr_data, M_DEVBUF);
1189			twa_release_request(tr);
1190		} else {
1191			/* It's a SCSI request.  Complete it. */
1192			tr->tr_command->command.cmd_pkt_9k.status = EIO;
1193			if (tr->tr_callback)
1194				tr->tr_callback(tr);
1195		}
1196	}
1197}
1198
1199static int
1200twa_drain_pending_queue(struct twa_softc *sc)
1201{
1202	struct twa_request	*tr;
1203	int			s, error = 0;
1204
1205	/*
1206	 * Pull requests off the pending queue, and submit them.
1207	 */
1208	s = splbio();
1209	while ((tr = TAILQ_FIRST(&sc->twa_pending)) != NULL) {
1210		TAILQ_REMOVE(&sc->twa_pending, tr, tr_link);
1211
1212		if ((error = twa_start(tr))) {
1213			if (error == EBUSY) {
1214				tr->tr_status = TWA_CMD_PENDING;
1215
1216				/* queue at the head */
1217				TAILQ_INSERT_HEAD(&tr->tr_sc->twa_pending,
1218					tr, tr_link);
1219				error = 0;
1220				break;
1221			} else {
1222				if (tr->tr_flags & TWA_CMD_SLEEP_ON_REQUEST) {
1223					tr->tr_error = error;
1224					tr->tr_callback(tr);
1225					error = EIO;
1226				}
1227			}
1228		}
1229	}
1230	splx(s);
1231
1232	return(error);
1233}
1234
1235static int
1236twa_drain_aen_queue(struct twa_softc *sc)
1237{
1238	int				s, error = 0;
1239	struct twa_request		*tr;
1240	struct twa_command_header	*cmd_hdr;
1241	struct timeval	t1;
1242	uint32_t		timeout;
1243
1244	for (;;) {
1245		if ((tr = twa_get_request(sc, 0)) == NULL) {
1246			error = EIO;
1247			break;
1248		}
1249		tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
1250		tr->tr_callback = NULL;
1251
1252		tr->tr_data = malloc(TWA_SECTOR_SIZE, M_DEVBUF, M_NOWAIT);
1253
1254		if (tr->tr_data == NULL) {
1255			error = 1;
1256			goto out;
1257		}
1258
1259		if (twa_request_sense(tr, 0) != 0) {
1260			error = 1;
1261			break;
1262		}
1263
1264		timeout = (1000/*ms*/ * 100/*us*/ * TWA_REQUEST_TIMEOUT_PERIOD);
1265
1266		microtime(&t1);
1267
1268		timeout += t1.tv_usec;
1269
1270		do {
1271			s = splbio();
1272			twa_done(tr->tr_sc);
1273			splx(s);
1274			if (tr->tr_status != TWA_CMD_BUSY)
1275				break;
1276			microtime(&t1);
1277		} while (t1.tv_usec <= timeout);
1278
1279		if (tr->tr_status != TWA_CMD_COMPLETE) {
1280			error = ETIMEDOUT;
1281			break;
1282		}
1283
1284		if ((error = tr->tr_command->command.cmd_pkt_9k.status))
1285			break;
1286
1287		cmd_hdr = (struct twa_command_header *)(tr->tr_data);
1288		if ((cmd_hdr->status_block.error) /* aen_code */
1289				== TWA_AEN_QUEUE_EMPTY)
1290			break;
1291		(void)twa_enqueue_aen(sc, cmd_hdr);
1292
1293		free(tr->tr_data, M_DEVBUF);
1294		twa_release_request(tr);
1295	}
1296out:
1297	if (tr) {
1298		if (tr->tr_data)
1299			free(tr->tr_data, M_DEVBUF);
1300
1301		twa_release_request(tr);
1302	}
1303	return(error);
1304}
1305
1306
1307#if 0
1308static void
1309twa_check_response_q(struct twa_request *tr, int clear)
1310{
1311	int j;
1312	static int i = 0;
1313	static struct twa_request	*req = 0;
1314	static struct buf		*hist[255];
1315
1316
1317	if (clear) {
1318		i = 0;
1319		for (j = 0; j < 255; j++)
1320			hist[j] = 0;
1321		return;
1322	}
1323
1324	if (req == 0)
1325		req = tr;
1326
1327	if ((tr->tr_cmd_pkt_type & TWA_CMD_PKT_TYPE_EXTERNAL) != 0) {
1328		/* XXX this is bogus ! req can't be anything else but tr ! */
1329		if (req->tr_request_id == tr->tr_request_id)
1330			panic("req id: %d on controller queue twice",
1331		    	    tr->tr_request_id);
1332
1333		for (j = 0; j < i; j++)
1334			if (tr->bp == hist[j])
1335				panic("req id: %d buf found twice",
1336		    	    	    tr->tr_request_id);
1337		}
1338	req = tr;
1339
1340	hist[i++] = req->bp;
1341}
1342#endif
1343
1344static int
1345twa_done(struct twa_softc *sc)
1346{
1347	union twa_response_queue	rq;
1348	struct twa_request		*tr;
1349	int				rv = 0;
1350	uint32_t			status_reg;
1351
1352	for (;;) {
1353		status_reg = twa_inl(sc, TWA_STATUS_REGISTER_OFFSET);
1354		if ((rv = twa_check_ctlr_state(sc, status_reg)))
1355			break;
1356		if (status_reg & TWA_STATUS_RESPONSE_QUEUE_EMPTY)
1357			break;
1358		/* Response queue is not empty. */
1359		rq.value = twa_inl(sc, TWA_RESPONSE_QUEUE_OFFSET);
1360		tr = sc->sc_twa_request + rq.u.response_id;
1361#if 0
1362		twa_check_response_q(tr, 0);
1363#endif
1364		/* Unmap the command packet, and any associated data buffer. */
1365		twa_unmap_request(tr);
1366
1367		tr->tr_status = TWA_CMD_COMPLETE;
1368		TAILQ_REMOVE(&tr->tr_sc->twa_busy, tr, tr_link);
1369
1370		if (tr->tr_callback)
1371			tr->tr_callback(tr);
1372	}
1373	(void)twa_drain_pending_queue(sc);
1374
1375#if 0
1376	twa_check_response_q(NULL, 1);
1377#endif
1378	return(rv);
1379}
1380
1381/*
1382 * Function name:	twa_init_ctlr
1383 * Description:		Establishes a logical connection with the controller.
1384 *			If bundled with firmware, determines whether or not
1385 *			the driver is compatible with the firmware on the
1386 *			controller, before proceeding to work with it.
1387 *
1388 * Input:		sc	-- ptr to per ctlr structure
1389 * Output:		None
1390 * Return value:	0	-- success
1391 *			non-zero-- failure
1392 */
1393static int
1394twa_init_ctlr(struct twa_softc *sc)
1395{
1396	uint16_t	fw_on_ctlr_srl = 0;
1397	uint16_t	fw_on_ctlr_arch_id = 0;
1398	uint16_t	fw_on_ctlr_branch = 0;
1399	uint16_t	fw_on_ctlr_build = 0;
1400	uint32_t	init_connect_result = 0;
1401	int		error = 0;
1402
1403	/* Wait for the controller to become ready. */
1404	if (twa_wait_status(sc, TWA_STATUS_MICROCONTROLLER_READY,
1405					TWA_REQUEST_TIMEOUT_PERIOD)) {
1406		return(ENXIO);
1407	}
1408	/* Drain the response queue. */
1409	if (twa_drain_response_queue(sc))
1410		return(1);
1411
1412	/* Establish a logical connection with the controller. */
1413	if ((error = twa_init_connection(sc, TWA_INIT_MESSAGE_CREDITS,
1414			TWA_EXTENDED_INIT_CONNECT, TWA_CURRENT_FW_SRL,
1415			TWA_9000_ARCH_ID, TWA_CURRENT_FW_BRANCH,
1416			TWA_CURRENT_FW_BUILD, &fw_on_ctlr_srl,
1417			&fw_on_ctlr_arch_id, &fw_on_ctlr_branch,
1418			&fw_on_ctlr_build, &init_connect_result))) {
1419		return(error);
1420	}
1421	twa_drain_aen_queue(sc);
1422
1423	/* Set controller state to initialized. */
1424	sc->twa_state &= ~TWA_STATE_SHUTDOWN;
1425	return(0);
1426}
1427
1428static int
1429twa_setup(struct twa_softc *sc)
1430{
1431	struct tw_cl_event_packet *aen_queue;
1432	uint32_t		i = 0;
1433	int			error = 0;
1434
1435	/* Initialize request queues. */
1436	TAILQ_INIT(&sc->twa_free);
1437	TAILQ_INIT(&sc->twa_busy);
1438	TAILQ_INIT(&sc->twa_pending);
1439
1440	sc->twa_sc_flags = 0;
1441
1442	if (twa_alloc_req_pkts(sc, TWA_Q_LENGTH)) {
1443
1444		return(ENOMEM);
1445	}
1446
1447	/* Allocate memory for the AEN queue. */
1448	if ((aen_queue = malloc(sizeof(struct tw_cl_event_packet) *
1449	    TWA_Q_LENGTH, M_DEVBUF, M_WAITOK)) == NULL) {
1450		/*
1451		 * This should not cause us to return error.  We will only be
1452		 * unable to support AEN's.  But then, we will have to check
1453		 * time and again to see if we can support AEN's, if we
1454		 * continue.  So, we will just return error.
1455		 */
1456		return (ENOMEM);
1457	}
1458	/* Initialize the aen queue. */
1459	memset(aen_queue, 0, sizeof(struct tw_cl_event_packet) * TWA_Q_LENGTH);
1460
1461	for (i = 0; i < TWA_Q_LENGTH; i++)
1462		sc->twa_aen_queue[i] = &(aen_queue[i]);
1463
1464	twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
1465		TWA_CONTROL_DISABLE_INTERRUPTS);
1466
1467	/* Initialize the controller. */
1468	if ((error = twa_init_ctlr(sc))) {
1469		/* Soft reset the controller, and try one more time. */
1470
1471		printf("%s: controller initialization failed. "
1472		    "Retrying initialization\n", device_xname(&sc->twa_dv));
1473
1474		if ((error = twa_soft_reset(sc)) == 0)
1475			error = twa_init_ctlr(sc);
1476	}
1477
1478	twa_describe_controller(sc);
1479
1480	error = twa_request_bus_scan(sc);
1481
1482	twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
1483		TWA_CONTROL_CLEAR_ATTENTION_INTERRUPT |
1484		TWA_CONTROL_UNMASK_RESPONSE_INTERRUPT |
1485		TWA_CONTROL_ENABLE_INTERRUPTS);
1486
1487	return (error);
1488}
1489
1490void *twa_sdh;
1491
1492static void
1493twa_attach(device_t parent, device_t self, void *aux)
1494{
1495	struct pci_attach_args *pa;
1496	struct twa_softc *sc;
1497	pci_chipset_tag_t pc;
1498	pcireg_t csr;
1499	pci_intr_handle_t ih;
1500	const char *intrstr;
1501	const struct sysctlnode *node;
1502	const struct twa_pci_identity *entry;
1503	int i;
1504	bool use_64bit;
1505
1506	sc = device_private(self);
1507
1508	pa = aux;
1509	pc = pa->pa_pc;
1510	sc->pc = pa->pa_pc;
1511	sc->tag = pa->pa_tag;
1512
1513	entry = twa_lookup(pa->pa_id);
1514	pci_aprint_devinfo_fancy(pa, "RAID controller", entry->name, 1);
1515
1516	sc->sc_quirks = 0;
1517
1518	if (PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_3WARE_9000) {
1519		sc->sc_nunits = TWA_MAX_UNITS;
1520		use_64bit = false;
1521		if (pci_mapreg_map(pa, PCI_MAPREG_START, PCI_MAPREG_TYPE_IO, 0,
1522	    	    &sc->twa_bus_iot, &sc->twa_bus_ioh, NULL, NULL)) {
1523			aprint_error_dev(&sc->twa_dv, "can't map i/o space\n");
1524			return;
1525		}
1526	} else if (PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_3WARE_9550) {
1527		sc->sc_nunits = TWA_MAX_UNITS;
1528		use_64bit = true;
1529		if (pci_mapreg_map(pa, PCI_MAPREG_START + 0x08,
1530	    	    PCI_MAPREG_MEM_TYPE_64BIT, 0, &sc->twa_bus_iot,
1531		    &sc->twa_bus_ioh, NULL, NULL)) {
1532			aprint_error_dev(&sc->twa_dv, "can't map mem space\n");
1533			return;
1534		}
1535	} else if (PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_3WARE_9650) {
1536		sc->sc_nunits = TWA_9650_MAX_UNITS;
1537		use_64bit = true;
1538		if (pci_mapreg_map(pa, PCI_MAPREG_START + 0x08,
1539	    	    PCI_MAPREG_MEM_TYPE_64BIT, 0, &sc->twa_bus_iot,
1540		    &sc->twa_bus_ioh, NULL, NULL)) {
1541			aprint_error_dev(&sc->twa_dv, "can't map mem space\n");
1542			return;
1543		}
1544		sc->sc_quirks |= TWA_QUIRK_QUEUEFULL_BUG;
1545	} else if (PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_3WARE_9690) {
1546		sc->sc_nunits = TWA_9690_MAX_UNITS;
1547		use_64bit = true;
1548		if (pci_mapreg_map(pa, PCI_MAPREG_START + 0x08,
1549	    	    PCI_MAPREG_MEM_TYPE_64BIT, 0, &sc->twa_bus_iot,
1550		    &sc->twa_bus_ioh, NULL, NULL)) {
1551			aprint_error_dev(&sc->twa_dv, "can't map mem space\n");
1552			return;
1553		}
1554		sc->sc_quirks |= TWA_QUIRK_QUEUEFULL_BUG;
1555	} else {
1556		sc->sc_nunits = 0;
1557		use_64bit = false;
1558		aprint_error_dev(&sc->twa_dv, "product id 0x%02x not recognized\n",
1559		    PCI_PRODUCT(pa->pa_id));
1560		return;
1561	}
1562
1563	if (pci_dma64_available(pa) && use_64bit) {
1564		aprint_verbose_dev(self, "64bit DMA addressing active");
1565		sc->twa_dma_tag = pa->pa_dmat64;
1566	} else {
1567		sc->twa_dma_tag = pa->pa_dmat;
1568	}
1569
1570 	sc->sc_product_id = PCI_PRODUCT(pa->pa_id);
1571	/* Enable the device. */
1572	csr = pci_conf_read(pa->pa_pc, pa->pa_tag, PCI_COMMAND_STATUS_REG);
1573
1574	pci_conf_write(pa->pa_pc, pa->pa_tag, PCI_COMMAND_STATUS_REG,
1575	    csr | PCI_COMMAND_MASTER_ENABLE);
1576
1577	/* Map and establish the interrupt. */
1578	if (pci_intr_map(pa, &ih)) {
1579		aprint_error_dev(&sc->twa_dv, "can't map interrupt\n");
1580		return;
1581	}
1582	intrstr = pci_intr_string(pc, ih);
1583
1584	sc->twa_ih = pci_intr_establish(pc, ih, IPL_BIO, twa_intr, sc);
1585	if (sc->twa_ih == NULL) {
1586		aprint_error_dev(&sc->twa_dv, "can't establish interrupt%s%s\n",
1587			(intrstr) ? " at " : "",
1588			(intrstr) ? intrstr : "");
1589		return;
1590	}
1591
1592	if (intrstr != NULL)
1593		aprint_normal_dev(&sc->twa_dv, "interrupting at %s\n",
1594			intrstr);
1595
1596	twa_setup(sc);
1597
1598	if (twa_sdh == NULL)
1599		twa_sdh = shutdownhook_establish(twa_shutdown, NULL);
1600
1601	/* sysctl set-up for 3ware cli */
1602	if (sysctl_createv(NULL, 0, NULL, NULL,
1603				CTLFLAG_PERMANENT, CTLTYPE_NODE, "hw",
1604				NULL, NULL, 0, NULL, 0,
1605				CTL_HW, CTL_EOL) != 0) {
1606		aprint_error_dev(&sc->twa_dv, "could not create %s sysctl node\n",
1607			"hw");
1608		return;
1609	}
1610	if (sysctl_createv(NULL, 0, NULL, &node,
1611				0, CTLTYPE_NODE, device_xname(&sc->twa_dv),
1612				SYSCTL_DESCR("twa driver information"),
1613				NULL, 0, NULL, 0,
1614				CTL_HW, CTL_CREATE, CTL_EOL) != 0) {
1615		aprint_error_dev(&sc->twa_dv, "could not create %s.%s sysctl node\n",
1616			"hw",
1617			device_xname(&sc->twa_dv));
1618		return;
1619	}
1620	if ((i = sysctl_createv(NULL, 0, NULL, NULL,
1621				0, CTLTYPE_STRING, "driver_version",
1622				SYSCTL_DESCR("twa driver version"),
1623				NULL, 0, __UNCONST(&twaver), 0,
1624				CTL_HW, node->sysctl_num, CTL_CREATE, CTL_EOL))
1625				!= 0) {
1626		aprint_error_dev(&sc->twa_dv, "could not create %s.%s.driver_version sysctl\n",
1627			"hw",
1628			device_xname(&sc->twa_dv));
1629		return;
1630	}
1631
1632	return;
1633}
1634
1635static void
1636twa_shutdown(void *arg)
1637{
1638	extern struct cfdriver twa_cd;
1639	struct twa_softc *sc;
1640	int i, rv, unit;
1641
1642	for (i = 0; i < twa_cd.cd_ndevs; i++) {
1643		if ((sc = device_lookup_private(&twa_cd, i)) == NULL)
1644			continue;
1645
1646		for (unit = 0; unit < sc->sc_nunits; unit++)
1647			if (sc->sc_units[unit].td_dev != NULL)
1648				(void) config_detach(sc->sc_units[unit].td_dev,
1649					DETACH_FORCE | DETACH_QUIET);
1650
1651		twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
1652			TWA_CONTROL_DISABLE_INTERRUPTS);
1653
1654		/* Let the controller know that we are going down. */
1655		rv = twa_init_connection(sc, TWA_SHUTDOWN_MESSAGE_CREDITS,
1656				0, 0, 0, 0, 0,
1657				NULL, NULL, NULL, NULL, NULL);
1658	}
1659}
1660
1661void
1662twa_register_callbacks(struct twa_softc *sc, int unit,
1663    const struct twa_callbacks *tcb)
1664{
1665
1666	sc->sc_units[unit].td_callbacks = tcb;
1667}
1668
1669/*
1670 * Print autoconfiguration message for a sub-device
1671 */
1672static int
1673twa_print(void *aux, const char *pnp)
1674{
1675	struct twa_attach_args *twaa;
1676
1677	twaa = aux;
1678
1679	if (pnp !=NULL)
1680		aprint_normal("block device at %s\n", pnp);
1681	aprint_normal(" unit %d\n", twaa->twaa_unit);
1682	return (UNCONF);
1683}
1684
1685static void
1686twa_fillin_sgl(struct twa_sg *sgl, bus_dma_segment_t *segs, int nsegments)
1687{
1688	int	i;
1689	for (i = 0; i < nsegments; i++) {
1690		sgl[i].address = segs[i].ds_addr;
1691		sgl[i].length = (uint32_t)(segs[i].ds_len);
1692	}
1693}
1694
1695static int
1696twa_submit_io(struct twa_request *tr)
1697{
1698	int	error;
1699
1700	if ((error = twa_start(tr))) {
1701		if (error == EBUSY)
1702			error = 0; /* request is in the pending queue */
1703		else {
1704			tr->tr_error = error;
1705		}
1706	}
1707	return(error);
1708}
1709
1710/*
1711 * Function name:	twa_setup_data_dmamap
1712 * Description:		Callback of bus_dmamap_load for the buffer associated
1713 *			with data.  Updates the cmd pkt (size/sgl_entries
1714 *			fields, as applicable) to reflect the number of sg
1715 *			elements.
1716 *
1717 * Input:		arg	-- ptr to request pkt
1718 *			segs	-- ptr to a list of segment descriptors
1719 *			nsegments--# of segments
1720 *			error	-- 0 if no errors encountered before callback,
1721 *				   non-zero if errors were encountered
1722 * Output:		None
1723 * Return value:	None
1724 */
1725static int
1726twa_setup_data_dmamap(void *arg, bus_dma_segment_t *segs, int nsegments)
1727{
1728	struct twa_request		*tr = (struct twa_request *)arg;
1729	struct twa_command_packet	*cmdpkt = tr->tr_command;
1730	struct twa_command_9k		*cmd9k;
1731	union twa_command_7k		*cmd7k;
1732	uint8_t				sgl_offset;
1733	int				error;
1734
1735	if (tr->tr_cmd_pkt_type & TWA_CMD_PKT_TYPE_9K) {
1736		cmd9k = &(cmdpkt->command.cmd_pkt_9k);
1737		twa_fillin_sgl(&(cmd9k->sg_list[0]), segs, nsegments);
1738		cmd9k->sgl_entries += nsegments - 1;
1739	} else {
1740		/* It's a 7000 command packet. */
1741		cmd7k = &(cmdpkt->command.cmd_pkt_7k);
1742		if ((sgl_offset = cmdpkt->command.cmd_pkt_7k.generic.sgl_offset))
1743			twa_fillin_sgl((struct twa_sg *)
1744					(((uint32_t *)cmd7k) + sgl_offset),
1745					segs, nsegments);
1746		/* Modify the size field, based on sg address size. */
1747		cmd7k->generic.size +=
1748			((TWA_64BIT_ADDRESSES ? 3 : 2) * nsegments);
1749	}
1750	if (tr->tr_flags & TWA_CMD_DATA_IN)
1751		bus_dmamap_sync(tr->tr_sc->twa_dma_tag, tr->tr_dma_map, 0,
1752			tr->tr_length, BUS_DMASYNC_PREWRITE);
1753	if (tr->tr_flags & TWA_CMD_DATA_OUT) {
1754		/*
1755		 * If we're using an alignment buffer, and we're
1756		 * writing data, copy the real data out.
1757		 */
1758		if (tr->tr_flags & TWA_CMD_DATA_COPY_NEEDED)
1759			memcpy(tr->tr_data, tr->tr_real_data,
1760				tr->tr_real_length);
1761		bus_dmamap_sync(tr->tr_sc->twa_dma_tag, tr->tr_dma_map, 0,
1762			tr->tr_length, BUS_DMASYNC_PREREAD);
1763	}
1764	error = twa_submit_io(tr);
1765
1766	if (error) {
1767		twa_unmap_request(tr);
1768		/*
1769		 * If the caller had been returned EINPROGRESS, and he has
1770		 * registered a callback for handling completion, the callback
1771		 * will never get called because we were unable to submit the
1772		 * request.  So, free up the request right here.
1773		 */
1774		if (tr->tr_callback)
1775			twa_release_request(tr);
1776	}
1777	return (error);
1778}
1779
1780/*
1781 * Function name:	twa_map_request
1782 * Description:		Maps a cmd pkt and data associated with it, into
1783 *			DMA'able memory.
1784 *
1785 * Input:		tr	-- ptr to request pkt
1786 * Output:		None
1787 * Return value:	0	-- success
1788 *			non-zero-- failure
1789 */
1790int
1791twa_map_request(struct twa_request *tr)
1792{
1793	struct twa_softc	*sc = tr->tr_sc;
1794	int			 s, rv, rc;
1795
1796	/* If the command involves data, map that too. */
1797	if (tr->tr_data != NULL) {
1798
1799		if (((u_long)tr->tr_data & (511)) != 0) {
1800			tr->tr_flags |= TWA_CMD_DATA_COPY_NEEDED;
1801			tr->tr_real_data = tr->tr_data;
1802			tr->tr_real_length = tr->tr_length;
1803			s = splvm();
1804			rc = uvm_km_kmem_alloc(kmem_va_arena,
1805			    tr->tr_length, (VM_NOSLEEP | VM_INSTANTFIT),
1806			    (vmem_addr_t *)&tr->tr_data);
1807			splx(s);
1808
1809			if (rc != 0) {
1810				tr->tr_data = tr->tr_real_data;
1811				tr->tr_length = tr->tr_real_length;
1812				return(ENOMEM);
1813			}
1814			if ((tr->tr_flags & TWA_CMD_DATA_IN) != 0)
1815				memcpy(tr->tr_data, tr->tr_real_data,
1816					tr->tr_length);
1817		}
1818
1819		/*
1820		 * Map the data buffer into bus space and build the S/G list.
1821		 */
1822		rv = bus_dmamap_load(sc->twa_dma_tag, tr->tr_dma_map,
1823			tr->tr_data, tr->tr_length, NULL,
1824			BUS_DMA_NOWAIT | BUS_DMA_STREAMING);
1825
1826		if (rv != 0) {
1827			if ((tr->tr_flags & TWA_CMD_DATA_COPY_NEEDED) != 0) {
1828				s = splvm();
1829				uvm_km_kmem_free(kmem_va_arena,
1830				    (vaddr_t)tr->tr_data,
1831				    tr->tr_length);
1832				splx(s);
1833			}
1834			return (rv);
1835		}
1836
1837		if ((rv = twa_setup_data_dmamap(tr,
1838				tr->tr_dma_map->dm_segs,
1839				tr->tr_dma_map->dm_nsegs))) {
1840
1841			if (tr->tr_flags & TWA_CMD_DATA_COPY_NEEDED) {
1842				s = splvm();
1843				uvm_km_kmem_free(kmem_va_arena, (vaddr_t)tr->tr_data,
1844				    tr->tr_length);
1845				splx(s);
1846				tr->tr_data = tr->tr_real_data;
1847				tr->tr_length = tr->tr_real_length;
1848			}
1849		}
1850
1851	} else
1852		if ((rv = twa_submit_io(tr)))
1853			twa_unmap_request(tr);
1854
1855	return (rv);
1856}
1857
1858/*
1859 * Function name:	twa_intr
1860 * Description:		Interrupt handler.  Determines the kind of interrupt,
1861 *			and calls the appropriate handler.
1862 *
1863 * Input:		sc	-- ptr to per ctlr structure
1864 * Output:		None
1865 * Return value:	None
1866 */
1867
1868static int
1869twa_intr(void *arg)
1870{
1871	int	caught, s, rv;
1872	struct twa_softc *sc;
1873	uint32_t	status_reg;
1874	sc = (struct twa_softc *)arg;
1875
1876	caught = 0;
1877	/* Collect current interrupt status. */
1878	status_reg = twa_inl(sc, TWA_STATUS_REGISTER_OFFSET);
1879	if (twa_check_ctlr_state(sc, status_reg)) {
1880		caught = 1;
1881		goto bail;
1882	}
1883	/* Dispatch based on the kind of interrupt. */
1884	if (status_reg & TWA_STATUS_HOST_INTERRUPT) {
1885		twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
1886			TWA_CONTROL_CLEAR_HOST_INTERRUPT);
1887		caught = 1;
1888	}
1889	if ((status_reg & TWA_STATUS_ATTENTION_INTERRUPT) != 0) {
1890		twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
1891			TWA_CONTROL_CLEAR_ATTENTION_INTERRUPT);
1892		rv = twa_fetch_aen(sc);
1893#ifdef DIAGNOSTIC
1894		if (rv != 0)
1895			printf("%s: unable to retrieve AEN (%d)\n",
1896				device_xname(&sc->twa_dv), rv);
1897#endif
1898		caught = 1;
1899	}
1900	if (status_reg & TWA_STATUS_COMMAND_INTERRUPT) {
1901		/* Start any requests that might be in the pending queue. */
1902		twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
1903			TWA_CONTROL_MASK_COMMAND_INTERRUPT);
1904		(void)twa_drain_pending_queue(sc);
1905		caught = 1;
1906	}
1907	if (status_reg & TWA_STATUS_RESPONSE_INTERRUPT) {
1908		s = splbio();
1909		twa_done(sc);
1910		splx(s);
1911		caught = 1;
1912	}
1913bail:
1914	return (caught);
1915}
1916
1917/*
1918 * Accept an open operation on the control device.
1919 */
1920static int
1921twaopen(dev_t dev, int flag, int mode, struct lwp *l)
1922{
1923	struct twa_softc *twa;
1924
1925	if ((twa = device_lookup_private(&twa_cd, minor(dev))) == NULL)
1926		return (ENXIO);
1927	if ((twa->twa_sc_flags & TWA_STATE_OPEN) != 0)
1928		return (EBUSY);
1929
1930	twa->twa_sc_flags |= TWA_STATE_OPEN;
1931
1932	return (0);
1933}
1934
1935/*
1936 * Accept the last close on the control device.
1937 */
1938static int
1939twaclose(dev_t dev, int flag, int mode,
1940    struct lwp *l)
1941{
1942	struct twa_softc *twa;
1943
1944	twa = device_lookup_private(&twa_cd, minor(dev));
1945	twa->twa_sc_flags &= ~TWA_STATE_OPEN;
1946	return (0);
1947}
1948
1949/*
1950 * Function name:	twaioctl
1951 * Description:		ioctl handler.
1952 *
1953 * Input:		sc	-- ptr to per ctlr structure
1954 *			cmd	-- ioctl cmd
1955 *			buf	-- ptr to buffer in kernel memory, which is
1956 *				   a copy of the input buffer in user-space
1957 * Output:		buf	-- ptr to buffer in kernel memory, which will
1958 *				   be copied of the output buffer in user-space
1959 * Return value:	0	-- success
1960 *			non-zero-- failure
1961 */
1962static int
1963twaioctl(dev_t dev, u_long cmd, void *data, int flag,
1964    struct lwp *l)
1965{
1966	struct twa_softc *sc;
1967	struct twa_ioctl_9k	*user_buf = (struct twa_ioctl_9k *)data;
1968	struct tw_cl_event_packet event_buf;
1969	struct twa_request 	*tr = 0;
1970	int32_t			event_index = 0;
1971	int32_t			start_index;
1972	int			s, error = 0;
1973
1974	sc = device_lookup_private(&twa_cd, minor(dev));
1975
1976	switch (cmd) {
1977	case TW_OSL_IOCTL_FIRMWARE_PASS_THROUGH:
1978	{
1979		struct twa_command_packet	*cmdpkt;
1980		uint32_t			data_buf_size_adjusted;
1981
1982		/* Get a request packet */
1983		tr = twa_get_request_wait(sc, 0);
1984		KASSERT(tr != NULL);
1985		/*
1986		 * Make sure that the data buffer sent to firmware is a
1987		 * 512 byte multiple in size.
1988		 */
1989		data_buf_size_adjusted =
1990			(user_buf->twa_drvr_pkt.buffer_length + 511) & ~511;
1991
1992		if ((tr->tr_length = data_buf_size_adjusted)) {
1993			if ((tr->tr_data = malloc(data_buf_size_adjusted,
1994			    M_DEVBUF, M_WAITOK)) == NULL) {
1995				error = ENOMEM;
1996				goto fw_passthru_done;
1997			}
1998			/* Copy the payload. */
1999			if ((error = copyin((void *) (user_buf->pdata),
2000				(void *) (tr->tr_data),
2001				user_buf->twa_drvr_pkt.buffer_length)) != 0) {
2002					goto fw_passthru_done;
2003			}
2004			tr->tr_flags |= TWA_CMD_DATA_IN | TWA_CMD_DATA_OUT;
2005		}
2006		tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_IOCTL;
2007		cmdpkt = tr->tr_command;
2008
2009		/* Copy the command packet. */
2010		memcpy(cmdpkt, &(user_buf->twa_cmd_pkt),
2011			sizeof(struct twa_command_packet));
2012		cmdpkt->command.cmd_pkt_7k.generic.request_id =
2013			tr->tr_request_id;
2014
2015		/* Send down the request, and wait for it to complete. */
2016		if ((error = twa_wait_request(tr, TWA_REQUEST_TIMEOUT_PERIOD))) 		{
2017			if (error == ETIMEDOUT)
2018				break; /* clean-up done by twa_wait_request */
2019			goto fw_passthru_done;
2020		}
2021
2022		/* Copy the command packet back into user space. */
2023		memcpy(&user_buf->twa_cmd_pkt, cmdpkt,
2024			sizeof(struct twa_command_packet));
2025
2026		/* If there was a payload, copy it back too. */
2027		if (tr->tr_length)
2028			error = copyout(tr->tr_data, user_buf->pdata,
2029					user_buf->twa_drvr_pkt.buffer_length);
2030fw_passthru_done:
2031		/* Free resources. */
2032		if (tr->tr_data)
2033			free(tr->tr_data, M_DEVBUF);
2034
2035		if (tr)
2036			twa_release_request(tr);
2037		break;
2038	}
2039
2040	case TW_OSL_IOCTL_SCAN_BUS:
2041		twa_request_bus_scan(sc);
2042		break;
2043
2044	case TW_CL_IOCTL_GET_FIRST_EVENT:
2045		if (sc->twa_aen_queue_wrapped) {
2046			if (sc->twa_aen_queue_overflow) {
2047				/*
2048				 * The aen queue has wrapped, even before some
2049				 * events have been retrieved.  Let the caller
2050				 * know that he missed out on some AEN's.
2051				 */
2052				user_buf->twa_drvr_pkt.status =
2053					TWA_ERROR_AEN_OVERFLOW;
2054				sc->twa_aen_queue_overflow = FALSE;
2055			} else
2056				user_buf->twa_drvr_pkt.status = 0;
2057			event_index = sc->twa_aen_head;
2058		} else {
2059			if (sc->twa_aen_head == sc->twa_aen_tail) {
2060				user_buf->twa_drvr_pkt.status =
2061					TWA_ERROR_AEN_NO_EVENTS;
2062				break;
2063			}
2064			user_buf->twa_drvr_pkt.status = 0;
2065			event_index = sc->twa_aen_tail;	/* = 0 */
2066		}
2067		if ((error = copyout(sc->twa_aen_queue[event_index],
2068		    user_buf->pdata, sizeof(struct tw_cl_event_packet))) != 0)
2069			(sc->twa_aen_queue[event_index])->retrieved =
2070			    TWA_AEN_RETRIEVED;
2071		break;
2072
2073	case TW_CL_IOCTL_GET_LAST_EVENT:
2074		if (sc->twa_aen_queue_wrapped) {
2075			if (sc->twa_aen_queue_overflow) {
2076				/*
2077				 * The aen queue has wrapped, even before some
2078				 * events have been retrieved.  Let the caller
2079				 * know that he missed out on some AEN's.
2080				 */
2081				user_buf->twa_drvr_pkt.status =
2082					TWA_ERROR_AEN_OVERFLOW;
2083				sc->twa_aen_queue_overflow = FALSE;
2084			} else
2085				user_buf->twa_drvr_pkt.status = 0;
2086		} else {
2087			if (sc->twa_aen_head == sc->twa_aen_tail) {
2088				user_buf->twa_drvr_pkt.status =
2089					TWA_ERROR_AEN_NO_EVENTS;
2090				break;
2091			}
2092			user_buf->twa_drvr_pkt.status = 0;
2093		}
2094		event_index =
2095		    (sc->twa_aen_head - 1 + TWA_Q_LENGTH) % TWA_Q_LENGTH;
2096		if ((error = copyout(sc->twa_aen_queue[event_index],
2097		    user_buf->pdata, sizeof(struct tw_cl_event_packet))) != 0)
2098			(sc->twa_aen_queue[event_index])->retrieved =
2099			    TWA_AEN_RETRIEVED;
2100		break;
2101
2102	case TW_CL_IOCTL_GET_NEXT_EVENT:
2103		user_buf->twa_drvr_pkt.status = 0;
2104		if (sc->twa_aen_queue_wrapped) {
2105
2106			if (sc->twa_aen_queue_overflow) {
2107				/*
2108				 * The aen queue has wrapped, even before some
2109				 * events have been retrieved.  Let the caller
2110				 * know that he missed out on some AEN's.
2111				 */
2112				user_buf->twa_drvr_pkt.status =
2113					TWA_ERROR_AEN_OVERFLOW;
2114				sc->twa_aen_queue_overflow = FALSE;
2115			}
2116			start_index = sc->twa_aen_head;
2117		} else {
2118			if (sc->twa_aen_head == sc->twa_aen_tail) {
2119				user_buf->twa_drvr_pkt.status =
2120					TWA_ERROR_AEN_NO_EVENTS;
2121				break;
2122			}
2123			start_index = sc->twa_aen_tail;	/* = 0 */
2124		}
2125		error = copyin(user_buf->pdata, &event_buf,
2126				sizeof(struct tw_cl_event_packet));
2127
2128		event_index = (start_index + event_buf.sequence_id -
2129		    (sc->twa_aen_queue[start_index])->sequence_id + 1)
2130		    % TWA_Q_LENGTH;
2131
2132		if (!((sc->twa_aen_queue[event_index])->sequence_id >
2133		    event_buf.sequence_id)) {
2134			if (user_buf->twa_drvr_pkt.status ==
2135			    TWA_ERROR_AEN_OVERFLOW)
2136				/* so we report the overflow next time */
2137				sc->twa_aen_queue_overflow = TRUE;
2138			user_buf->twa_drvr_pkt.status = TWA_ERROR_AEN_NO_EVENTS;
2139			break;
2140		}
2141		if ((error = copyout(sc->twa_aen_queue[event_index],
2142		    user_buf->pdata, sizeof(struct tw_cl_event_packet))) != 0)
2143			(sc->twa_aen_queue[event_index])->retrieved =
2144			    TWA_AEN_RETRIEVED;
2145		break;
2146
2147	case TW_CL_IOCTL_GET_PREVIOUS_EVENT:
2148		user_buf->twa_drvr_pkt.status = 0;
2149		if (sc->twa_aen_queue_wrapped) {
2150			if (sc->twa_aen_queue_overflow) {
2151				/*
2152				 * The aen queue has wrapped, even before some
2153				 * events have been retrieved.  Let the caller
2154				 * know that he missed out on some AEN's.
2155				 */
2156				user_buf->twa_drvr_pkt.status =
2157					TWA_ERROR_AEN_OVERFLOW;
2158				sc->twa_aen_queue_overflow = FALSE;
2159			}
2160			start_index = sc->twa_aen_head;
2161		} else {
2162			if (sc->twa_aen_head == sc->twa_aen_tail) {
2163				user_buf->twa_drvr_pkt.status =
2164					TWA_ERROR_AEN_NO_EVENTS;
2165				break;
2166			}
2167			start_index = sc->twa_aen_tail;	/* = 0 */
2168		}
2169		if ((error = copyin(user_buf->pdata, &event_buf,
2170				sizeof(struct tw_cl_event_packet))) != 0)
2171
2172		event_index = (start_index + event_buf.sequence_id -
2173		    (sc->twa_aen_queue[start_index])->sequence_id - 1)
2174		    % TWA_Q_LENGTH;
2175		if (!((sc->twa_aen_queue[event_index])->sequence_id <
2176		    event_buf.sequence_id)) {
2177			if (user_buf->twa_drvr_pkt.status ==
2178			    TWA_ERROR_AEN_OVERFLOW)
2179				/* so we report the overflow next time */
2180				sc->twa_aen_queue_overflow = TRUE;
2181			user_buf->twa_drvr_pkt.status =
2182				TWA_ERROR_AEN_NO_EVENTS;
2183			break;
2184		}
2185		if ((error = copyout(sc->twa_aen_queue [event_index],
2186		    user_buf->pdata, sizeof(struct tw_cl_event_packet))) != 0)
2187			aprint_error_dev(&sc->twa_dv, "get_previous: Could not copyout to "
2188			    "event_buf. error = %x\n",
2189			    error);
2190		(sc->twa_aen_queue[event_index])->retrieved = TWA_AEN_RETRIEVED;
2191		break;
2192
2193	case TW_CL_IOCTL_GET_LOCK:
2194	{
2195		struct tw_cl_lock_packet	twa_lock;
2196
2197		copyin(user_buf->pdata, &twa_lock,
2198				sizeof(struct tw_cl_lock_packet));
2199		s = splbio();
2200		if ((sc->twa_ioctl_lock.lock == TWA_LOCK_FREE) ||
2201			(twa_lock.force_flag) ||
2202			(time_second >= sc->twa_ioctl_lock.timeout)) {
2203
2204			sc->twa_ioctl_lock.lock = TWA_LOCK_HELD;
2205			sc->twa_ioctl_lock.timeout = time_second +
2206				(twa_lock.timeout_msec / 1000);
2207			twa_lock.time_remaining_msec = twa_lock.timeout_msec;
2208			user_buf->twa_drvr_pkt.status = 0;
2209		} else {
2210			twa_lock.time_remaining_msec =
2211				(sc->twa_ioctl_lock.timeout - time_second) *
2212				1000;
2213			user_buf->twa_drvr_pkt.status =
2214					TWA_ERROR_IOCTL_LOCK_ALREADY_HELD;
2215		}
2216		splx(s);
2217		copyout(&twa_lock, user_buf->pdata,
2218				sizeof(struct tw_cl_lock_packet));
2219		break;
2220	}
2221
2222	case TW_CL_IOCTL_RELEASE_LOCK:
2223		s = splbio();
2224		if (sc->twa_ioctl_lock.lock == TWA_LOCK_FREE) {
2225			user_buf->twa_drvr_pkt.status =
2226				TWA_ERROR_IOCTL_LOCK_NOT_HELD;
2227		} else {
2228			sc->twa_ioctl_lock.lock = TWA_LOCK_FREE;
2229			user_buf->twa_drvr_pkt.status = 0;
2230		}
2231		splx(s);
2232		break;
2233
2234	case TW_CL_IOCTL_GET_COMPATIBILITY_INFO:
2235	{
2236		struct tw_cl_compatibility_packet	comp_pkt;
2237
2238		memcpy(comp_pkt.driver_version, TWA_DRIVER_VERSION_STRING,
2239					sizeof(TWA_DRIVER_VERSION_STRING));
2240		comp_pkt.working_srl = sc->working_srl;
2241		comp_pkt.working_branch = sc->working_branch;
2242		comp_pkt.working_build = sc->working_build;
2243		user_buf->twa_drvr_pkt.status = 0;
2244
2245		/* Copy compatibility information to user space. */
2246		copyout(&comp_pkt, user_buf->pdata,
2247				min(sizeof(struct tw_cl_compatibility_packet),
2248					user_buf->twa_drvr_pkt.buffer_length));
2249		break;
2250	}
2251
2252	case TWA_IOCTL_GET_UNITNAME:	/* WASABI EXTENSION */
2253	{
2254		struct twa_unitname	*tn;
2255		struct twa_drive	*tdr;
2256
2257		tn = (struct twa_unitname *)data;
2258			/* XXX mutex */
2259		if (tn->tn_unit < 0 || tn->tn_unit >= sc->sc_nunits)
2260			return (EINVAL);
2261		tdr = &sc->sc_units[tn->tn_unit];
2262		if (tdr->td_dev == NULL)
2263			tn->tn_name[0] = '\0';
2264		else
2265			strlcpy(tn->tn_name, device_xname(tdr->td_dev),
2266			    sizeof(tn->tn_name));
2267		return (0);
2268	}
2269
2270	default:
2271		/* Unknown opcode. */
2272		error = ENOTTY;
2273	}
2274
2275	return(error);
2276}
2277
2278const struct cdevsw twa_cdevsw = {
2279	twaopen, twaclose, noread, nowrite, twaioctl,
2280	nostop, notty, nopoll, nommap, nokqfilter, D_OTHER,
2281};
2282
2283/*
2284 * Function name:	twa_get_param
2285 * Description:		Get a firmware parameter.
2286 *
2287 * Input:		sc		-- ptr to per ctlr structure
2288 *			table_id	-- parameter table #
2289 *			param_id	-- index of the parameter in the table
2290 *			param_size	-- size of the parameter in bytes
2291 *			callback	-- ptr to function, if any, to be called
2292 *					back on completion; NULL if no callback.
2293 * Output:		None
2294 * Return value:	ptr to param structure	-- success
2295 *			NULL			-- failure
2296 */
2297static int
2298twa_get_param(struct twa_softc *sc, int table_id, int param_id,
2299    size_t param_size, void (* callback)(struct twa_request *tr),
2300    struct twa_param_9k **param)
2301{
2302	int			rv = 0;
2303	struct twa_request	*tr;
2304	union twa_command_7k	*cmd;
2305
2306	/* Get a request packet. */
2307	if ((tr = twa_get_request(sc, 0)) == NULL) {
2308		rv = EAGAIN;
2309		goto out;
2310	}
2311
2312	tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
2313
2314	/* Allocate memory to read data into. */
2315	if ((*param = (struct twa_param_9k *)
2316		malloc(TWA_SECTOR_SIZE, M_DEVBUF, M_NOWAIT)) == NULL) {
2317		rv = ENOMEM;
2318		goto out;
2319	}
2320
2321	memset(*param, 0, sizeof(struct twa_param_9k) - 1 + param_size);
2322	tr->tr_data = *param;
2323	tr->tr_length = TWA_SECTOR_SIZE;
2324	tr->tr_flags = TWA_CMD_DATA_IN | TWA_CMD_DATA_OUT;
2325
2326	/* Build the cmd pkt. */
2327	cmd = &(tr->tr_command->command.cmd_pkt_7k);
2328
2329	tr->tr_command->cmd_hdr.header_desc.size_header = 128;
2330
2331	cmd->param.opcode = TWA_OP_GET_PARAM;
2332	cmd->param.sgl_offset = 2;
2333	cmd->param.size = 2;
2334	cmd->param.request_id = tr->tr_request_id;
2335	cmd->param.unit = 0;
2336	cmd->param.param_count = 1;
2337
2338	/* Specify which parameter we need. */
2339	(*param)->table_id = table_id | TWA_9K_PARAM_DESCRIPTOR;
2340	(*param)->parameter_id = param_id;
2341	(*param)->parameter_size_bytes = param_size;
2342
2343	/* Submit the command. */
2344	if (callback == NULL) {
2345		/* There's no call back; wait till the command completes. */
2346		rv = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
2347
2348		if (rv != 0)
2349			goto out;
2350
2351		if ((rv = cmd->param.status) != 0) {
2352		     /* twa_drain_complete_queue will have done the unmapping */
2353		     goto out;
2354		}
2355		twa_release_request(tr);
2356		return (rv);
2357	} else {
2358		/* There's a call back.  Simply submit the command. */
2359		tr->tr_callback = callback;
2360		rv = twa_map_request(tr);
2361		return (rv);
2362	}
2363out:
2364	if (tr)
2365		twa_release_request(tr);
2366	return(rv);
2367}
2368
2369/*
2370 * Function name:	twa_set_param
2371 * Description:		Set a firmware parameter.
2372 *
2373 * Input:		sc		-- ptr to per ctlr structure
2374 *			table_id	-- parameter table #
2375 *			param_id	-- index of the parameter in the table
2376 *			param_size	-- size of the parameter in bytes
2377 *			callback	-- ptr to function, if any, to be called
2378 *					back on completion; NULL if no callback.
2379 * Output:		None
2380 * Return value:	0	-- success
2381 *			non-zero-- failure
2382 */
2383static int
2384twa_set_param(struct twa_softc *sc, int table_id, int param_id, int param_size,
2385    void *data, void (* callback)(struct twa_request *tr))
2386{
2387	struct twa_request	*tr;
2388	union twa_command_7k	*cmd;
2389	struct twa_param_9k	*param = NULL;
2390	int			error = ENOMEM;
2391
2392	tr = twa_get_request(sc, 0);
2393	if (tr == NULL)
2394		return (EAGAIN);
2395
2396	tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
2397
2398	/* Allocate memory to send data using. */
2399	if ((param = (struct twa_param_9k *)
2400			malloc(TWA_SECTOR_SIZE, M_DEVBUF, M_NOWAIT)) == NULL)
2401		goto out;
2402	memset(param, 0, sizeof(struct twa_param_9k) - 1 + param_size);
2403	tr->tr_data = param;
2404	tr->tr_length = TWA_SECTOR_SIZE;
2405	tr->tr_flags = TWA_CMD_DATA_IN | TWA_CMD_DATA_OUT;
2406
2407	/* Build the cmd pkt. */
2408	cmd = &(tr->tr_command->command.cmd_pkt_7k);
2409
2410	tr->tr_command->cmd_hdr.header_desc.size_header = 128;
2411
2412	cmd->param.opcode = TWA_OP_SET_PARAM;
2413	cmd->param.sgl_offset = 2;
2414	cmd->param.size = 2;
2415	cmd->param.request_id = tr->tr_request_id;
2416	cmd->param.unit = 0;
2417	cmd->param.param_count = 1;
2418
2419	/* Specify which parameter we want to set. */
2420	param->table_id = table_id | TWA_9K_PARAM_DESCRIPTOR;
2421	param->parameter_id = param_id;
2422	param->parameter_size_bytes = param_size;
2423	memcpy(param->data, data, param_size);
2424
2425	/* Submit the command. */
2426	if (callback == NULL) {
2427		/* There's no call back;  wait till the command completes. */
2428		error = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
2429		if (error == ETIMEDOUT)
2430			/* clean-up done by twa_immediate_request */
2431			return(error);
2432		if (error)
2433			goto out;
2434		if ((error = cmd->param.status)) {
2435			/*
2436			 * twa_drain_complete_queue will have done the
2437			 * unmapping.
2438			 */
2439			goto out;
2440		}
2441		free(param, M_DEVBUF);
2442		twa_release_request(tr);
2443		return(error);
2444	} else {
2445		/* There's a call back.  Simply submit the command. */
2446		tr->tr_callback = callback;
2447		if ((error = twa_map_request(tr)))
2448			goto out;
2449
2450		return (0);
2451	}
2452out:
2453	if (param)
2454		free(param, M_DEVBUF);
2455	if (tr)
2456		twa_release_request(tr);
2457	return(error);
2458}
2459
2460/*
2461 * Function name:	twa_init_connection
2462 * Description:		Send init_connection cmd to firmware
2463 *
2464 * Input:		sc		-- ptr to per ctlr structure
2465 *			message_credits	-- max # of requests that we might send
2466 *					 down simultaneously.  This will be
2467 *					 typically set to 256 at init-time or
2468 *					after a reset, and to 1 at shutdown-time
2469 *			set_features	-- indicates if we intend to use 64-bit
2470 *					sg, also indicates if we want to do a
2471 *					basic or an extended init_connection;
2472 *
2473 * Note: The following input/output parameters are valid, only in case of an
2474 *		extended init_connection:
2475 *
2476 *			current_fw_srl		-- srl of fw we are bundled
2477 *						with, if any; 0 otherwise
2478 *			current_fw_arch_id	-- arch_id of fw we are bundled
2479 *						with, if any; 0 otherwise
2480 *			current_fw_branch	-- branch # of fw we are bundled
2481 *						with, if any; 0 otherwise
2482 *			current_fw_build	-- build # of fw we are bundled
2483 *						with, if any; 0 otherwise
2484 * Output:		fw_on_ctlr_srl		-- srl of fw on ctlr
2485 *			fw_on_ctlr_arch_id	-- arch_id of fw on ctlr
2486 *			fw_on_ctlr_branch	-- branch # of fw on ctlr
2487 *			fw_on_ctlr_build	-- build # of fw on ctlr
2488 *			init_connect_result	-- result bitmap of fw response
2489 * Return value:	0	-- success
2490 *			non-zero-- failure
2491 */
2492static int
2493twa_init_connection(struct twa_softc *sc, uint16_t message_credits,
2494    uint32_t set_features, uint16_t current_fw_srl,
2495    uint16_t current_fw_arch_id, uint16_t current_fw_branch,
2496    uint16_t current_fw_build, uint16_t *fw_on_ctlr_srl,
2497    uint16_t *fw_on_ctlr_arch_id, uint16_t *fw_on_ctlr_branch,
2498    uint16_t *fw_on_ctlr_build, uint32_t *init_connect_result)
2499{
2500	struct twa_request		*tr;
2501	struct twa_command_init_connect	*init_connect;
2502	int				error = 1;
2503
2504	/* Get a request packet. */
2505	if ((tr = twa_get_request(sc, 0)) == NULL)
2506		goto out;
2507	tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
2508	/* Build the cmd pkt. */
2509	init_connect = &(tr->tr_command->command.cmd_pkt_7k.init_connect);
2510
2511	tr->tr_command->cmd_hdr.header_desc.size_header = 128;
2512
2513	init_connect->opcode = TWA_OP_INIT_CONNECTION;
2514   	init_connect->request_id = tr->tr_request_id;
2515	init_connect->message_credits = message_credits;
2516	init_connect->features = set_features;
2517	if (TWA_64BIT_ADDRESSES)
2518		init_connect->features |= TWA_64BIT_SG_ADDRESSES;
2519	if (set_features & TWA_EXTENDED_INIT_CONNECT) {
2520		/*
2521		 * Fill in the extra fields needed for
2522		 * an extended init_connect.
2523		 */
2524		init_connect->size = 6;
2525		init_connect->fw_srl = current_fw_srl;
2526		init_connect->fw_arch_id = current_fw_arch_id;
2527		init_connect->fw_branch = current_fw_branch;
2528	} else
2529		init_connect->size = 3;
2530
2531	/* Submit the command, and wait for it to complete. */
2532	error = twa_immediate_request(tr, TWA_REQUEST_TIMEOUT_PERIOD);
2533	if (error == ETIMEDOUT)
2534		return(error); /* clean-up done by twa_immediate_request */
2535	if (error)
2536		goto out;
2537	if ((error = init_connect->status)) {
2538		/* twa_drain_complete_queue will have done the unmapping */
2539		goto out;
2540	}
2541	if (set_features & TWA_EXTENDED_INIT_CONNECT) {
2542		*fw_on_ctlr_srl = init_connect->fw_srl;
2543		*fw_on_ctlr_arch_id = init_connect->fw_arch_id;
2544		*fw_on_ctlr_branch = init_connect->fw_branch;
2545		*fw_on_ctlr_build = init_connect->fw_build;
2546		*init_connect_result = init_connect->result;
2547	}
2548	twa_release_request(tr);
2549	return(error);
2550
2551out:
2552	if (tr)
2553		twa_release_request(tr);
2554	return(error);
2555}
2556
2557static int
2558twa_reset(struct twa_softc *sc)
2559{
2560	int	s;
2561	int	error = 0;
2562
2563	/* Set the 'in reset' flag. */
2564	sc->twa_sc_flags |= TWA_STATE_IN_RESET;
2565
2566	/*
2567	 * Disable interrupts from the controller, and mask any
2568	 * accidental entry into our interrupt handler.
2569	 */
2570	twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
2571		TWA_CONTROL_DISABLE_INTERRUPTS);
2572
2573	s = splbio();
2574
2575	/* Soft reset the controller. */
2576	if ((error = twa_soft_reset(sc)))
2577		goto out;
2578
2579	/* Re-establish logical connection with the controller. */
2580	if ((error = twa_init_connection(sc, TWA_INIT_MESSAGE_CREDITS,
2581					0, 0, 0, 0, 0,
2582					NULL, NULL, NULL, NULL, NULL))) {
2583		goto out;
2584	}
2585	/*
2586	 * Complete all requests in the complete queue; error back all requests
2587	 * in the busy queue.  Any internal requests will be simply freed.
2588	 * Re-submit any requests in the pending queue.
2589	 */
2590	twa_drain_busy_queue(sc);
2591
2592out:
2593	splx(s);
2594	/*
2595	 * Enable interrupts, and also clear attention and response interrupts.
2596	 */
2597	twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
2598		TWA_CONTROL_CLEAR_ATTENTION_INTERRUPT |
2599		TWA_CONTROL_UNMASK_RESPONSE_INTERRUPT |
2600		TWA_CONTROL_ENABLE_INTERRUPTS);
2601
2602	/* Clear the 'in reset' flag. */
2603	sc->twa_sc_flags &= ~TWA_STATE_IN_RESET;
2604
2605	return(error);
2606}
2607
2608static int
2609twa_soft_reset(struct twa_softc *sc)
2610{
2611	uint32_t	status_reg;
2612
2613	twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
2614			TWA_CONTROL_ISSUE_SOFT_RESET |
2615			TWA_CONTROL_CLEAR_HOST_INTERRUPT |
2616			TWA_CONTROL_CLEAR_ATTENTION_INTERRUPT |
2617			TWA_CONTROL_MASK_COMMAND_INTERRUPT |
2618			TWA_CONTROL_MASK_RESPONSE_INTERRUPT |
2619			TWA_CONTROL_DISABLE_INTERRUPTS);
2620
2621	if (twa_drain_response_queue_large(sc, 30) != 0) {
2622		aprint_error_dev(&sc->twa_dv,
2623		    "response queue not empty after reset.\n");
2624		return(1);
2625	}
2626	if (twa_wait_status(sc, TWA_STATUS_MICROCONTROLLER_READY |
2627				TWA_STATUS_ATTENTION_INTERRUPT, 30)) {
2628		aprint_error_dev(&sc->twa_dv, "no attention interrupt after reset.\n");
2629		return(1);
2630	}
2631	twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
2632		TWA_CONTROL_CLEAR_ATTENTION_INTERRUPT);
2633
2634	if (twa_drain_response_queue(sc)) {
2635		aprint_error_dev(&sc->twa_dv, "cannot drain response queue.\n");
2636		return(1);
2637	}
2638	if (twa_drain_aen_queue(sc)) {
2639		aprint_error_dev(&sc->twa_dv, "cannot drain AEN queue.\n");
2640		return(1);
2641	}
2642	if (twa_find_aen(sc, TWA_AEN_SOFT_RESET)) {
2643		aprint_error_dev(&sc->twa_dv, "reset not reported by controller.\n");
2644		return(1);
2645	}
2646	status_reg = twa_inl(sc, TWA_STATUS_REGISTER_OFFSET);
2647	if (TWA_STATUS_ERRORS(status_reg) ||
2648	    twa_check_ctlr_state(sc, status_reg)) {
2649		aprint_error_dev(&sc->twa_dv, "controller errors detected.\n");
2650		return(1);
2651	}
2652	return(0);
2653}
2654
2655static int
2656twa_wait_status(struct twa_softc *sc, uint32_t status, uint32_t timeout)
2657{
2658	struct timeval		t1;
2659	time_t		end_time;
2660	uint32_t	status_reg;
2661
2662	timeout = (timeout * 1000 * 100);
2663
2664	microtime(&t1);
2665
2666	end_time = t1.tv_usec + timeout;
2667
2668	do {
2669		status_reg = twa_inl(sc, TWA_STATUS_REGISTER_OFFSET);
2670		/* got the required bit(s)? */
2671		if ((status_reg & status) == status)
2672			return(0);
2673		DELAY(100000);
2674		microtime(&t1);
2675	} while (t1.tv_usec <= end_time);
2676
2677	return(1);
2678}
2679
2680static int
2681twa_fetch_aen(struct twa_softc *sc)
2682{
2683	struct twa_request	*tr;
2684	int			s, error = 0;
2685
2686	s = splbio();
2687
2688	if ((tr = twa_get_request(sc, TWA_CMD_AEN)) == NULL) {
2689		splx(s);
2690		return(EIO);
2691	}
2692	tr->tr_cmd_pkt_type |= TWA_CMD_PKT_TYPE_INTERNAL;
2693	tr->tr_callback = twa_aen_callback;
2694	tr->tr_data = malloc(TWA_SECTOR_SIZE, M_DEVBUF, M_NOWAIT);
2695	if (twa_request_sense(tr, 0) != 0) {
2696		if (tr->tr_data)
2697			free(tr->tr_data, M_DEVBUF);
2698		twa_release_request(tr);
2699		error = 1;
2700	}
2701	splx(s);
2702
2703	return(error);
2704}
2705
2706/*
2707 * Function name:	twa_aen_callback
2708 * Description:		Callback for requests to fetch AEN's.
2709 *
2710 * Input:		tr	-- ptr to completed request pkt
2711 * Output:		None
2712 * Return value:	None
2713 */
2714static void
2715twa_aen_callback(struct twa_request *tr)
2716{
2717	int i;
2718	int fetch_more_aens = 0;
2719	struct twa_softc		*sc = tr->tr_sc;
2720	struct twa_command_header	*cmd_hdr =
2721		(struct twa_command_header *)(tr->tr_data);
2722	struct twa_command_9k		*cmd =
2723		&(tr->tr_command->command.cmd_pkt_9k);
2724
2725	if (! cmd->status) {
2726		if ((tr->tr_cmd_pkt_type & TWA_CMD_PKT_TYPE_9K) &&
2727			(cmd->cdb[0] == 0x3 /* REQUEST_SENSE */))
2728			if (twa_enqueue_aen(sc, cmd_hdr)
2729				!= TWA_AEN_QUEUE_EMPTY)
2730				fetch_more_aens = 1;
2731	} else {
2732		cmd_hdr->err_specific_desc[sizeof(cmd_hdr->err_specific_desc) - 1] = '\0';
2733		for (i = 0; i < 18; i++)
2734			printf("%x\t", tr->tr_command->cmd_hdr.sense_data[i]);
2735
2736		printf(""); /* print new line */
2737
2738		for (i = 0; i < 128; i++)
2739			printf("%x\t", ((int8_t *)(tr->tr_data))[i]);
2740	}
2741	if (tr->tr_data)
2742		free(tr->tr_data, M_DEVBUF);
2743	twa_release_request(tr);
2744
2745	if (fetch_more_aens)
2746		twa_fetch_aen(sc);
2747}
2748
2749/*
2750 * Function name:	twa_enqueue_aen
2751 * Description:		Queues AEN's to be supplied to user-space tools on request.
2752 *
2753 * Input:		sc	-- ptr to per ctlr structure
2754 *			cmd_hdr	-- ptr to hdr of fw cmd pkt, from where the AEN
2755 *				   details can be retrieved.
2756 * Output:		None
2757 * Return value:	None
2758 */
2759static uint16_t
2760twa_enqueue_aen(struct twa_softc *sc, struct twa_command_header *cmd_hdr)
2761{
2762	int			rv, s;
2763	struct tw_cl_event_packet *event;
2764	uint16_t		aen_code;
2765	unsigned long		sync_time;
2766
2767	s = splbio();
2768	aen_code = cmd_hdr->status_block.error;
2769
2770	switch (aen_code) {
2771	case TWA_AEN_SYNC_TIME_WITH_HOST:
2772
2773		sync_time = (time_second - (3 * 86400)) % 604800;
2774		rv = twa_set_param(sc, TWA_PARAM_TIME_TABLE,
2775				TWA_PARAM_TIME_SchedulerTime, 4,
2776				&sync_time, twa_aen_callback);
2777#ifdef DIAGNOSTIC
2778		if (rv != 0)
2779			aprint_error_dev(&sc->twa_dv, "unable to sync time with ctlr\n");
2780#endif
2781		break;
2782
2783	case TWA_AEN_QUEUE_EMPTY:
2784		break;
2785
2786	default:
2787		/* Queue the event. */
2788		event = sc->twa_aen_queue[sc->twa_aen_head];
2789		if (event->retrieved == TWA_AEN_NOT_RETRIEVED)
2790			sc->twa_aen_queue_overflow = TRUE;
2791		event->severity =
2792			cmd_hdr->status_block.substatus_block.severity;
2793		event->time_stamp_sec = time_second;
2794		event->aen_code = aen_code;
2795		event->retrieved = TWA_AEN_NOT_RETRIEVED;
2796		event->sequence_id = ++(sc->twa_current_sequence_id);
2797		cmd_hdr->err_specific_desc[sizeof(cmd_hdr->err_specific_desc) - 1] = '\0';
2798		event->parameter_len = strlen(cmd_hdr->err_specific_desc);
2799		memcpy(event->parameter_data, cmd_hdr->err_specific_desc,
2800			event->parameter_len);
2801
2802		if (event->severity < TWA_AEN_SEVERITY_DEBUG) {
2803			printf("%s: AEN 0x%04X: %s: %s: %s\n",
2804				device_xname(&sc->twa_dv),
2805				aen_code,
2806				twa_aen_severity_table[event->severity],
2807				twa_find_msg_string(twa_aen_table, aen_code),
2808				event->parameter_data);
2809		}
2810
2811		if ((sc->twa_aen_head + 1) == TWA_Q_LENGTH)
2812			sc->twa_aen_queue_wrapped = TRUE;
2813		sc->twa_aen_head = (sc->twa_aen_head + 1) % TWA_Q_LENGTH;
2814		break;
2815	} /* switch */
2816	splx(s);
2817
2818	return (aen_code);
2819}
2820
2821/*
2822 * Function name:	twa_find_aen
2823 * Description:		Reports whether a given AEN ever occurred.
2824 *
2825 * Input:		sc	-- ptr to per ctlr structure
2826 *			aen_code-- AEN to look for
2827 * Output:		None
2828 * Return value:	0	-- success
2829 *			non-zero-- failure
2830 */
2831static int
2832twa_find_aen(struct twa_softc *sc, uint16_t aen_code)
2833{
2834	uint32_t	last_index;
2835	int		s;
2836	int		i;
2837
2838	s = splbio();
2839
2840	if (sc->twa_aen_queue_wrapped)
2841		last_index = sc->twa_aen_head;
2842	else
2843		last_index = 0;
2844
2845	i = sc->twa_aen_head;
2846	do {
2847		i = (i + TWA_Q_LENGTH - 1) % TWA_Q_LENGTH;
2848		if ((sc->twa_aen_queue[i])->aen_code == aen_code) {
2849			splx(s);
2850			return(0);
2851		}
2852	} while (i != last_index);
2853
2854	splx(s);
2855	return(1);
2856}
2857
2858static inline void
2859twa_request_init(struct twa_request *tr, int flags)
2860{
2861	tr->tr_data = NULL;
2862	tr->tr_real_data = NULL;
2863	tr->tr_length = 0;
2864	tr->tr_real_length = 0;
2865	tr->tr_status = TWA_CMD_SETUP;/* command is in setup phase */
2866	tr->tr_flags = flags;
2867	tr->tr_error = 0;
2868	tr->tr_callback = NULL;
2869	tr->tr_cmd_pkt_type = 0;
2870	tr->bp = 0;
2871
2872	/*
2873	 * Look at the status field in the command packet to see how
2874	 * it completed the last time it was used, and zero out only
2875	 * the portions that might have changed.  Note that we don't
2876	 * care to zero out the sglist.
2877	 */
2878	if (tr->tr_command->command.cmd_pkt_9k.status)
2879		memset(tr->tr_command, 0,
2880			sizeof(struct twa_command_header) + 28);
2881	else
2882		memset(&(tr->tr_command->command), 0, 28);
2883}
2884
2885struct twa_request *
2886twa_get_request_wait(struct twa_softc *sc, int flags)
2887{
2888	struct twa_request *tr;
2889	int s;
2890
2891	KASSERT((flags & TWA_CMD_AEN) == 0);
2892
2893	s = splbio();
2894	while ((tr = TAILQ_FIRST(&sc->twa_free)) == NULL) {
2895		sc->twa_sc_flags |= TWA_STATE_REQUEST_WAIT;
2896		(void) tsleep(&sc->twa_free, PRIBIO, "twaccb", hz);
2897	}
2898	TAILQ_REMOVE(&sc->twa_free, tr, tr_link);
2899
2900	splx(s);
2901
2902	twa_request_init(tr, flags);
2903
2904	return(tr);
2905}
2906
2907struct twa_request *
2908twa_get_request(struct twa_softc *sc, int flags)
2909{
2910	int s;
2911	struct twa_request *tr;
2912
2913	/* Get a free request packet. */
2914	s = splbio();
2915	if (__predict_false((flags & TWA_CMD_AEN) != 0)) {
2916
2917		if ((sc->sc_twa_request->tr_flags & TWA_CMD_AEN_BUSY) == 0) {
2918			tr = sc->sc_twa_request;
2919			flags |= TWA_CMD_AEN_BUSY;
2920		} else {
2921			splx(s);
2922			return (NULL);
2923		}
2924	} else {
2925		if (__predict_false((tr =
2926				TAILQ_FIRST(&sc->twa_free)) == NULL)) {
2927			splx(s);
2928			return (NULL);
2929		}
2930		TAILQ_REMOVE(&sc->twa_free, tr, tr_link);
2931	}
2932	splx(s);
2933
2934	twa_request_init(tr, flags);
2935
2936	return(tr);
2937}
2938
2939/*
2940 * Print some information about the controller
2941 */
2942static void
2943twa_describe_controller(struct twa_softc *sc)
2944{
2945	struct twa_param_9k	*p[10];
2946	int			i, rv = 0;
2947	uint32_t		dsize;
2948	uint8_t			ports;
2949
2950	memset(p, sizeof(struct twa_param_9k *), 10);
2951
2952	/* Get the port count. */
2953	rv |= twa_get_param(sc, TWA_PARAM_CONTROLLER,
2954		TWA_PARAM_CONTROLLER_PortCount, 1, NULL, &p[0]);
2955
2956	/* get version strings */
2957	rv |= twa_get_param(sc, TWA_PARAM_VERSION, TWA_PARAM_VERSION_FW,
2958		16, NULL, &p[1]);
2959	rv |= twa_get_param(sc, TWA_PARAM_VERSION, TWA_PARAM_VERSION_BIOS,
2960		16, NULL, &p[2]);
2961	rv |= twa_get_param(sc, TWA_PARAM_VERSION, TWA_PARAM_VERSION_Mon,
2962		16, NULL, &p[3]);
2963	rv |= twa_get_param(sc, TWA_PARAM_VERSION, TWA_PARAM_VERSION_PCBA,
2964		8, NULL, &p[4]);
2965	rv |= twa_get_param(sc, TWA_PARAM_VERSION, TWA_PARAM_VERSION_ATA,
2966		8, NULL, &p[5]);
2967	rv |= twa_get_param(sc, TWA_PARAM_VERSION, TWA_PARAM_VERSION_PCI,
2968		8, NULL, &p[6]);
2969	rv |= twa_get_param(sc, TWA_PARAM_DRIVESUMMARY, TWA_PARAM_DRIVESTATUS,
2970		16, NULL, &p[7]);
2971
2972	if (rv) {
2973		/* some error occurred */
2974		aprint_error_dev(&sc->twa_dv, "failed to fetch version information\n");
2975		goto bail;
2976	}
2977
2978	ports = *(uint8_t *)(p[0]->data);
2979
2980	aprint_normal_dev(&sc->twa_dv, "%d ports, Firmware %.16s, BIOS %.16s\n",
2981		ports, p[1]->data, p[2]->data);
2982
2983	aprint_verbose_dev(&sc->twa_dv, "Monitor %.16s, PCB %.8s, Achip %.8s, Pchip %.8s\n",
2984		p[3]->data, p[4]->data,
2985		p[5]->data, p[6]->data);
2986
2987	for (i = 0; i < ports; i++) {
2988
2989		if ((*((char *)(p[7]->data + i)) & TWA_DRIVE_DETECTED) == 0)
2990			continue;
2991
2992		rv = twa_get_param(sc, TWA_PARAM_DRIVE_TABLE + i,
2993			TWA_PARAM_DRIVEMODELINDEX,
2994			TWA_PARAM_DRIVEMODEL_LENGTH, NULL, &p[8]);
2995
2996		if (rv != 0) {
2997			aprint_error_dev(&sc->twa_dv, "unable to get drive model for port"
2998				" %d\n", i);
2999			continue;
3000		}
3001
3002		rv = twa_get_param(sc, TWA_PARAM_DRIVE_TABLE + i,
3003			TWA_PARAM_DRIVESIZEINDEX,
3004			TWA_PARAM_DRIVESIZE_LENGTH, NULL, &p[9]);
3005
3006		if (rv != 0) {
3007			aprint_error_dev(&sc->twa_dv, "unable to get drive size"
3008				" for port %d\n", i);
3009			free(p[8], M_DEVBUF);
3010			continue;
3011		}
3012
3013		dsize = *(uint32_t *)(p[9]->data);
3014
3015		aprint_verbose_dev(&sc->twa_dv, "port %d: %.40s %d MB\n",
3016		    i, p[8]->data, dsize / 2048);
3017
3018		if (p[8])
3019			free(p[8], M_DEVBUF);
3020		if (p[9])
3021			free(p[9], M_DEVBUF);
3022	}
3023bail:
3024	if (p[0])
3025		free(p[0], M_DEVBUF);
3026	if (p[1])
3027		free(p[1], M_DEVBUF);
3028	if (p[2])
3029		free(p[2], M_DEVBUF);
3030	if (p[3])
3031		free(p[3], M_DEVBUF);
3032	if (p[4])
3033		free(p[4], M_DEVBUF);
3034	if (p[5])
3035		free(p[5], M_DEVBUF);
3036	if (p[6])
3037		free(p[6], M_DEVBUF);
3038}
3039
3040/*
3041 * Function name:	twa_check_ctlr_state
3042 * Description:		Makes sure that the fw status register reports a
3043 *			proper status.
3044 *
3045 * Input:		sc		-- ptr to per ctlr structure
3046 *			status_reg	-- value in the status register
3047 * Output:		None
3048 * Return value:	0	-- no errors
3049 *			non-zero-- errors
3050 */
3051static int
3052twa_check_ctlr_state(struct twa_softc *sc, uint32_t status_reg)
3053{
3054	int		result = 0;
3055	struct timeval	t1;
3056	static time_t	last_warning[2] = {0, 0};
3057
3058	/* Check if the 'micro-controller ready' bit is not set. */
3059	if ((status_reg & TWA_STATUS_EXPECTED_BITS) !=
3060				TWA_STATUS_EXPECTED_BITS) {
3061
3062		microtime(&t1);
3063
3064		last_warning[0] += (5 * 1000 * 100);
3065
3066		if (t1.tv_usec > last_warning[0]) {
3067			microtime(&t1);
3068			last_warning[0] = t1.tv_usec;
3069		}
3070		result = 1;
3071	}
3072
3073	/* Check if any error bits are set. */
3074	if ((status_reg & TWA_STATUS_UNEXPECTED_BITS) != 0) {
3075
3076		microtime(&t1);
3077		last_warning[1] += (5 * 1000 * 100);
3078		if (t1.tv_usec > last_warning[1]) {
3079		     	microtime(&t1);
3080			last_warning[1] = t1.tv_usec;
3081		}
3082		if (status_reg & TWA_STATUS_PCI_PARITY_ERROR_INTERRUPT) {
3083			aprint_error_dev(&sc->twa_dv, "clearing PCI parity error "
3084				"re-seat/move/replace card.\n");
3085			twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
3086				TWA_CONTROL_CLEAR_PARITY_ERROR);
3087			pci_conf_write(sc->pc, sc->tag,
3088				PCI_COMMAND_STATUS_REG,
3089				TWA_PCI_CONFIG_CLEAR_PARITY_ERROR);
3090		}
3091		if (status_reg & TWA_STATUS_PCI_ABORT_INTERRUPT) {
3092			aprint_error_dev(&sc->twa_dv, "clearing PCI abort\n");
3093			twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
3094				TWA_CONTROL_CLEAR_PCI_ABORT);
3095			pci_conf_write(sc->pc, sc->tag,
3096				PCI_COMMAND_STATUS_REG,
3097				TWA_PCI_CONFIG_CLEAR_PCI_ABORT);
3098		}
3099		if (status_reg & TWA_STATUS_QUEUE_ERROR_INTERRUPT) {
3100 			/*
3101			 * As documented by 3ware, the 9650 erroneously
3102			 * flags queue errors during resets.
3103			 * Just ignore them during the reset instead of
3104			 * bothering the console.
3105 			 */
3106 			if ((sc->sc_product_id != PCI_PRODUCT_3WARE_9650) ||
3107 			    ((sc->twa_sc_flags & TWA_STATE_IN_RESET) == 0)) {
3108 				aprint_error_dev(&sc->twa_dv,
3109 				    "clearing controller queue error\n");
3110 			}
3111
3112  			twa_outl(sc, TWA_CONTROL_REGISTER_OFFSET,
3113 				TWA_CONTROL_CLEAR_QUEUE_ERROR);
3114		}
3115		if (status_reg & TWA_STATUS_MICROCONTROLLER_ERROR) {
3116			aprint_error_dev(&sc->twa_dv, "micro-controller error\n");
3117			result = 1;
3118		}
3119	}
3120	return(result);
3121}
3122