xref: /dragonfly/sys/dev/disk/mpt/mpt.h (revision fcf53d9b)
1 /* $FreeBSD: src/sys/dev/mpt/mpt.h,v 1.48 2009/07/10 08:18:08 scottl Exp $ */
2 /*-
3  * Generic defines for LSI '909 FC  adapters.
4  * FreeBSD Version.
5  *
6  * Copyright (c)  2000, 2001 by Greg Ansley
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice immediately at the beginning of the file, without modification,
13  *    this list of conditions, and the following disclaimer.
14  * 2. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
21  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 /*-
30  * Copyright (c) 2002, 2006 by Matthew Jacob
31  * All rights reserved.
32  *
33  * Redistribution and use in source and binary forms, with or without
34  * modification, are permitted provided that the following conditions are
35  * met:
36  * 1. Redistributions of source code must retain the above copyright
37  *    notice, this list of conditions and the following disclaimer.
38  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
39  *    substantially similar to the "NO WARRANTY" disclaimer below
40  *    ("Disclaimer") and any redistribution must be conditioned upon including
41  *    a substantially similar Disclaimer requirement for further binary
42  *    redistribution.
43  * 3. Neither the names of the above listed copyright holders nor the names
44  *    of any contributors may be used to endorse or promote products derived
45  *    from this software without specific prior written permission.
46  *
47  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
48  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
49  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
50  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
51  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
52  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
53  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
54  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
55  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
56  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF THE COPYRIGHT
57  * OWNER OR CONTRIBUTOR IS ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
58  *
59  * Support from Chris Ellsworth in order to make SAS adapters work
60  * is gratefully acknowledged.
61  *
62  *
63  * Support from LSI-Logic has also gone a great deal toward making this a
64  * workable subsystem and is gratefully acknowledged.
65  */
66 /*
67  * Copyright (c) 2004, Avid Technology, Inc. and its contributors.
68  * Copyright (c) 2004, 2005 Justin T. Gibbs
69  * Copyright (c) 2005, WHEEL Sp. z o.o.
70  * All rights reserved.
71  *
72  * Redistribution and use in source and binary forms, with or without
73  * modification, are permitted provided that the following conditions are
74  * met:
75  * 1. Redistributions of source code must retain the above copyright
76  *    notice, this list of conditions and the following disclaimer.
77  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
78  *    substantially similar to the "NO WARRANTY" disclaimer below
79  *    ("Disclaimer") and any redistribution must be conditioned upon including
80  *    a substantially similar Disclaimer requirement for further binary
81  *    redistribution.
82  * 3. Neither the names of the above listed copyright holders nor the names
83  *    of any contributors may be used to endorse or promote products derived
84  *    from this software without specific prior written permission.
85  *
86  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
87  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
88  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
89  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
90  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
91  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
92  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
93  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
94  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
95  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF THE COPYRIGHT
96  * OWNER OR CONTRIBUTOR IS ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
97  */
98 
99 #ifndef _MPT_H_
100 #define _MPT_H_
101 
102 /********************************* OS Includes ********************************/
103 #include <sys/types.h>
104 #include <sys/param.h>
105 #include <sys/systm.h>
106 #include <sys/endian.h>
107 #include <sys/eventhandler.h>
108 
109 #include <sys/kernel.h>
110 #include <sys/queue.h>
111 #include <sys/malloc.h>
112 #include <sys/devicestat.h>
113 
114 #include <sys/proc.h>
115 #include <sys/bus.h>
116 #include <sys/module.h>
117 
118 #include <sys/thread2.h>
119 #include <sys/mplock2.h>
120 
121 #include <sys/rman.h>
122 
123 #if __FreeBSD_version < 500000
124 #include <bus/pci/pcireg.h>
125 #include <bus/pci/pcivar.h>
126 #else
127 #include <dev/pci/pcireg.h>
128 #include <dev/pci/pcivar.h>
129 #endif
130 
131 #include "opt_ddb.h"
132 
133 /**************************** Register Definitions ****************************/
134 #include <dev/disk/mpt/mpt_reg.h>
135 
136 /******************************* MPI Definitions ******************************/
137 #include <dev/disk/mpt/mpilib/mpi_type.h>
138 #include <dev/disk/mpt/mpilib/mpi.h>
139 #include <dev/disk/mpt/mpilib/mpi_cnfg.h>
140 #include <dev/disk/mpt/mpilib/mpi_ioc.h>
141 #include <dev/disk/mpt/mpilib/mpi_raid.h>
142 
143 /* XXX For mpt_debug.c */
144 #include <dev/disk/mpt/mpilib/mpi_init.h>
145 
146 #define	MPT_S64_2_SCALAR(y)	((((int64_t)y.High) << 32) | (y.Low))
147 #define	MPT_U64_2_SCALAR(y)	((((uint64_t)y.High) << 32) | (y.Low))
148 
149 /****************************** Misc Definitions ******************************/
150 /* #define MPT_TEST_MULTIPATH	1 */
151 #define MPT_OK (0)
152 #define MPT_FAIL (0x10000)
153 
154 #define NUM_ELEMENTS(array) (sizeof(array) / sizeof(*array))
155 
156 #define	MPT_ROLE_NONE		0
157 #define	MPT_ROLE_INITIATOR	1
158 #define	MPT_ROLE_TARGET		2
159 #define	MPT_ROLE_BOTH		3
160 #define	MPT_ROLE_DEFAULT	MPT_ROLE_INITIATOR
161 
162 /**************************** Forward Declarations ****************************/
163 struct mpt_softc;
164 struct mpt_personality;
165 typedef struct req_entry request_t;
166 
167 /************************* Personality Module Support *************************/
168 typedef int mpt_load_handler_t(struct mpt_personality *);
169 typedef int mpt_probe_handler_t(struct mpt_softc *);
170 typedef int mpt_attach_handler_t(struct mpt_softc *);
171 typedef int mpt_enable_handler_t(struct mpt_softc *);
172 typedef void mpt_ready_handler_t(struct mpt_softc *);
173 typedef int mpt_event_handler_t(struct mpt_softc *, request_t *,
174 				MSG_EVENT_NOTIFY_REPLY *);
175 typedef void mpt_reset_handler_t(struct mpt_softc *, int /*type*/);
176 /* XXX Add return value and use for veto? */
177 typedef void mpt_shutdown_handler_t(struct mpt_softc *);
178 typedef void mpt_detach_handler_t(struct mpt_softc *);
179 typedef int mpt_unload_handler_t(struct mpt_personality *);
180 
181 struct mpt_personality
182 {
183 	const char		*name;
184 	uint32_t		 id;		/* Assigned identifier. */
185 	u_int			 use_count;	/* Instances using personality*/
186 	mpt_load_handler_t	*load;		/* configure personailty */
187 #define MPT_PERS_FIRST_HANDLER(pers) (&(pers)->load)
188 	mpt_probe_handler_t	*probe;		/* configure personailty */
189 	mpt_attach_handler_t	*attach;	/* initialize device instance */
190 	mpt_enable_handler_t	*enable;	/* enable device */
191 	mpt_ready_handler_t	*ready;		/* final open for business */
192 	mpt_event_handler_t	*event;		/* Handle MPI event. */
193 	mpt_reset_handler_t	*reset;		/* Re-init after reset. */
194 	mpt_shutdown_handler_t	*shutdown;	/* Shutdown instance. */
195 	mpt_detach_handler_t	*detach;	/* release device instance */
196 	mpt_unload_handler_t	*unload;	/* Shutdown personality */
197 #define MPT_PERS_LAST_HANDLER(pers) (&(pers)->unload)
198 };
199 
200 int mpt_modevent(module_t, int, void *);
201 
202 /* Maximum supported number of personalities. */
203 #define MPT_MAX_PERSONALITIES	(15)
204 
205 #define MPT_PERSONALITY_DEPEND(name, dep, vmin, vpref, vmax) \
206 	MODULE_DEPEND(name, dep, vmin, vpref, vmax)
207 
208 #define DECLARE_MPT_PERSONALITY(name, order)				  \
209 	static moduledata_t name##_mod = {				  \
210 		#name, mpt_modevent, &name##_personality		  \
211 	};								  \
212 	DECLARE_MODULE(name, name##_mod, SI_SUB_DRIVERS, order);	  \
213 	MODULE_VERSION(name, 1);					  \
214 	MPT_PERSONALITY_DEPEND(name, mpt_core, 1, 1, 1)
215 
216 /******************************* Bus DMA Support ******************************/
217 /* XXX Need to update bus_dmamap_sync to take a range argument. */
218 #define bus_dmamap_sync_range(dma_tag, dmamap, offset, len, op)	\
219 	bus_dmamap_sync(dma_tag, dmamap, op)
220 
221 #if __FreeBSD_version < 600000
222 #define	bus_get_dma_tag(x)	NULL
223 #endif
224 #if __FreeBSD_version >= 501102
225 #define mpt_dma_tag_create(mpt, parent_tag, alignment, boundary,	\
226 			   lowaddr, highaddr, filter, filterarg,	\
227 			   maxsize, nsegments, maxsegsz, flags,		\
228 			   dma_tagp)					\
229 	bus_dma_tag_create(parent_tag, alignment, boundary,		\
230 			   lowaddr, highaddr, filter, filterarg,	\
231 			   maxsize, nsegments, maxsegsz, flags,		\
232 			   busdma_lock_mutex, &(mpt)->mpt_lock,		\
233 			   dma_tagp)
234 #else
235 #define mpt_dma_tag_create(mpt, parent_tag, alignment, boundary,	\
236 			   lowaddr, highaddr, filter, filterarg,	\
237 			   maxsize, nsegments, maxsegsz, flags,		\
238 			   dma_tagp)					\
239 	bus_dma_tag_create(parent_tag, alignment, boundary,		\
240 			   lowaddr, highaddr, filter, filterarg,	\
241 			   maxsize, nsegments, maxsegsz, flags,		\
242 			   dma_tagp)
243 #endif
244 
245 struct mpt_map_info {
246 	struct mpt_softc *mpt;
247 	int		  error;
248 	uint32_t	  phys;
249 };
250 
251 void mpt_map_rquest(void *, bus_dma_segment_t *, int, int);
252 /* **************************** NewBUS interrupt Crock ************************/
253 #ifdef __DragonFly__
254 #define	mpt_setup_intr(d, i, f, U, if, ifa, hp) \
255 	bus_setup_intr(d, i, f, if, ifa, hp, NULL)
256 #else
257 #if __FreeBSD_version < 700031
258 #define	mpt_setup_intr(d, i, f, U, if, ifa, hp)	\
259 	bus_setup_intr(d, i, f, if, ifa, hp)
260 #else
261 #define	mpt_setup_intr	bus_setup_intr
262 #endif
263 #endif
264 
265 /* **************************** NewBUS CAM Support ****************************/
266 #if __FreeBSD_version < 700049
267 #define mpt_xpt_bus_register(sim, parent, bus)	\
268 	xpt_bus_register(sim, bus)
269 #else
270 #define mpt_xpt_bus_register	xpt_bus_register
271 #endif
272 
273 /**************************** Kernel Thread Support ***************************/
274 #if __FreeBSD_version > 800001
275 #define mpt_kthread_create(func, farg, proc_ptr, flags, stackpgs, fmtstr, arg) \
276 	kproc_create(func, farg, proc_ptr, flags, stackpgs, fmtstr, arg)
277 #define	mpt_kthread_exit(status)	\
278 	kproc_exit(status)
279 #elif __FreeBSD_version > 500005
280 #define mpt_kthread_create(func, farg, proc_ptr, flags, stackpgs, fmtstr, arg) \
281 	kthread_create(func, farg, proc_ptr, flags, stackpgs, fmtstr, arg)
282 #define	mpt_kthread_exit(status)	\
283 	kthread_exit(status)
284 #else
285 #define mpt_kthread_create(func, farg, proc_ptr, flags, stackpgs, fmtstr, arg) \
286 	kthread_create(func, farg, proc_ptr, fmtstr, arg)
287 #define	mpt_kthread_exit(status)	\
288 	kthread_exit()
289 #endif
290 
291 /****************************** Timer Facilities ******************************/
292 #if __FreeBSD_version > 500000
293 #define mpt_callout_init(c)	callout_init(c, /*mpsafe*/1);
294 #else
295 #define mpt_callout_init(c)	callout_init(c);
296 #endif
297 
298 /********************************** Endianess *********************************/
299 #define	MPT_2_HOST64(ptr, tag)	ptr->tag = le64toh(ptr->tag)
300 #define	MPT_2_HOST32(ptr, tag)	ptr->tag = le32toh(ptr->tag)
301 #define	MPT_2_HOST16(ptr, tag)	ptr->tag = le16toh(ptr->tag)
302 
303 #define	HOST_2_MPT64(ptr, tag)	ptr->tag = htole64(ptr->tag)
304 #define	HOST_2_MPT32(ptr, tag)	ptr->tag = htole32(ptr->tag)
305 #define	HOST_2_MPT16(ptr, tag)	ptr->tag = htole16(ptr->tag)
306 
307 #if	_BYTE_ORDER == _BIG_ENDIAN
308 void mpt2host_sge_simple_union(SGE_SIMPLE_UNION *);
309 void mpt2host_iocfacts_reply(MSG_IOC_FACTS_REPLY *);
310 void mpt2host_portfacts_reply(MSG_PORT_FACTS_REPLY *);
311 void mpt2host_config_page_ioc2(CONFIG_PAGE_IOC_2 *);
312 void mpt2host_config_page_ioc3(CONFIG_PAGE_IOC_3 *);
313 void mpt2host_config_page_scsi_port_0(CONFIG_PAGE_SCSI_PORT_0 *);
314 void mpt2host_config_page_scsi_port_1(CONFIG_PAGE_SCSI_PORT_1 *);
315 void host2mpt_config_page_scsi_port_1(CONFIG_PAGE_SCSI_PORT_1 *);
316 void mpt2host_config_page_scsi_port_2(CONFIG_PAGE_SCSI_PORT_2 *);
317 void mpt2host_config_page_scsi_device_0(CONFIG_PAGE_SCSI_DEVICE_0 *);
318 void mpt2host_config_page_scsi_device_1(CONFIG_PAGE_SCSI_DEVICE_1 *);
319 void host2mpt_config_page_scsi_device_1(CONFIG_PAGE_SCSI_DEVICE_1 *);
320 void mpt2host_config_page_fc_port_0(CONFIG_PAGE_FC_PORT_0 *);
321 void mpt2host_config_page_fc_port_1(CONFIG_PAGE_FC_PORT_1 *);
322 void host2mpt_config_page_fc_port_1(CONFIG_PAGE_FC_PORT_1 *);
323 void mpt2host_config_page_raid_vol_0(CONFIG_PAGE_RAID_VOL_0 *);
324 void mpt2host_config_page_raid_phys_disk_0(CONFIG_PAGE_RAID_PHYS_DISK_0 *);
325 void mpt2host_mpi_raid_vol_indicator(MPI_RAID_VOL_INDICATOR *);
326 #else
327 #define	mpt2host_sge_simple_union(x)		do { ; } while (0)
328 #define	mpt2host_iocfacts_reply(x)		do { ; } while (0)
329 #define	mpt2host_portfacts_reply(x)		do { ; } while (0)
330 #define	mpt2host_config_page_ioc2(x)		do { ; } while (0)
331 #define	mpt2host_config_page_ioc3(x)		do { ; } while (0)
332 #define	mpt2host_config_page_scsi_port_0(x)	do { ; } while (0)
333 #define	mpt2host_config_page_scsi_port_1(x)	do { ; } while (0)
334 #define	host2mpt_config_page_scsi_port_1(x)	do { ; } while (0)
335 #define	mpt2host_config_page_scsi_port_2(x)	do { ; } while (0)
336 #define	mpt2host_config_page_scsi_device_0(x)	do { ; } while (0)
337 #define	mpt2host_config_page_scsi_device_1(x)	do { ; } while (0)
338 #define	host2mpt_config_page_scsi_device_1(x)	do { ; } while (0)
339 #define	mpt2host_config_page_fc_port_0(x)	do { ; } while (0)
340 #define	mpt2host_config_page_fc_port_1(x)	do { ; } while (0)
341 #define	host2mpt_config_page_fc_port_1(x)	do { ; } while (0)
342 #define	mpt2host_config_page_raid_vol_0(x)	do { ; } while (0)
343 #define	mpt2host_config_page_raid_phys_disk_0(x)			\
344 	do { ; } while (0)
345 #define	mpt2host_mpi_raid_vol_indicator(x)	do { ; } while (0)
346 #endif
347 
348 /**************************** MPI Transaction State ***************************/
349 typedef enum {
350 	REQ_STATE_NIL		= 0x00,
351 	REQ_STATE_FREE		= 0x01,
352 	REQ_STATE_ALLOCATED	= 0x02,
353 	REQ_STATE_QUEUED	= 0x04,
354 	REQ_STATE_DONE		= 0x08,
355 	REQ_STATE_TIMEDOUT	= 0x10,
356 	REQ_STATE_NEED_WAKEUP	= 0x20,
357 	REQ_STATE_LOCKED	= 0x80,	/* can't be freed */
358 	REQ_STATE_MASK		= 0xFF
359 } mpt_req_state_t;
360 
361 struct req_entry {
362 	TAILQ_ENTRY(req_entry) links;	/* Pointer to next in list */
363 	mpt_req_state_t	state;		/* Request State Information */
364 	uint16_t	index;		/* Index of this entry */
365 	uint16_t	IOCStatus;	/* Completion status */
366 	uint16_t	ResponseCode;	/* TMF Reponse Code */
367 	uint16_t	serno;		/* serial number */
368 	union ccb      *ccb;		/* CAM request */
369 	void	       *req_vbuf;	/* Virtual Address of Entry */
370 	void	       *sense_vbuf;	/* Virtual Address of sense data */
371 	bus_addr_t	req_pbuf;	/* Physical Address of Entry */
372 	bus_addr_t	sense_pbuf;	/* Physical Address of sense data */
373 	bus_dmamap_t	dmap;		/* DMA map for data buffers */
374 	struct req_entry *chain;	/* for SGE overallocations */
375 	struct callout  callout;	/* Timeout for the request */
376 };
377 
378 typedef struct mpt_config_params {
379 	u_int		Action;
380 	u_int		PageVersion;
381 	u_int		PageLength;
382 	u_int		PageNumber;
383 	u_int		PageType;
384 	u_int		PageAddress;
385 	u_int		ExtPageLength;
386 	u_int		ExtPageType;
387 } cfgparms_t;
388 
389 /**************************** MPI Target State Info ***************************/
390 
391 typedef struct {
392 	uint32_t reply_desc;	/* current reply descriptor */
393 	uint32_t resid;		/* current data residual */
394 	uint32_t bytes_xfered;	/* current relative offset */
395 	union ccb *ccb;		/* pointer to currently active ccb */
396 	request_t *req;		/* pointer to currently active assist request */
397 	uint32_t
398 		is_local : 1,
399 		nxfers	 : 31;
400 	uint32_t tag_id;
401 	enum {
402 		TGT_STATE_NIL,
403 		TGT_STATE_LOADING,
404 		TGT_STATE_LOADED,
405 		TGT_STATE_IN_CAM,
406                 TGT_STATE_SETTING_UP_FOR_DATA,
407                 TGT_STATE_MOVING_DATA,
408                 TGT_STATE_MOVING_DATA_AND_STATUS,
409                 TGT_STATE_SENDING_STATUS
410 	} state;
411 } mpt_tgt_state_t;
412 
413 /*
414  * When we get an incoming command it has its own tag which is called the
415  * IoIndex. This is the value we gave that particular command buffer when
416  * we originally assigned it. It's just a number, really. The FC card uses
417  * it as an RX_ID. We can use it to index into mpt->tgt_cmd_ptrs, which
418  * contains pointers the request_t structures related to that IoIndex.
419  *
420  * What *we* do is construct a tag out of the index for the target command
421  * which owns the incoming ATIO plus a rolling sequence number.
422  */
423 #define	MPT_MAKE_TAGID(mpt, req, ioindex)	\
424  ((ioindex << 18) | (((mpt->sequence++) & 0x3f) << 12) | (req->index & 0xfff))
425 
426 #ifdef	INVARIANTS
427 #define	MPT_TAG_2_REQ(a, b)		mpt_tag_2_req(a, (uint32_t) b)
428 #else
429 #define	MPT_TAG_2_REQ(mpt, tag)		mpt->tgt_cmd_ptrs[tag >> 18]
430 #endif
431 
432 #define	MPT_TGT_STATE(mpt, req) ((mpt_tgt_state_t *) \
433     (&((uint8_t *)req->req_vbuf)[MPT_RQSL(mpt) - sizeof (mpt_tgt_state_t)]))
434 
435 STAILQ_HEAD(mpt_hdr_stailq, ccb_hdr);
436 #define	MPT_MAX_LUNS	256
437 typedef struct {
438 	struct mpt_hdr_stailq	atios;
439 	struct mpt_hdr_stailq	inots;
440 	int enabled;
441 } tgt_resource_t;
442 #define	MPT_MAX_ELS	64
443 
444 /**************************** Handler Registration ****************************/
445 /*
446  * Global table of registered reply handlers.  The
447  * handler is indicated by byte 3 of the request
448  * index submitted to the IOC.  This allows the
449  * driver core to perform generic processing without
450  * any knowledge of per-personality behavior.
451  *
452  * MPT_NUM_REPLY_HANDLERS must be a power of 2
453  * to allow the easy generation of a mask.
454  *
455  * The handler offsets used by the core are hard coded
456  * allowing faster code generation when assigning a handler
457  * to a request.  All "personalities" must use the
458  * the handler registration mechanism.
459  *
460  * The IOC handlers that are rarely executed are placed
461  * at the tail of the table to make it more likely that
462  * all commonly executed handlers fit in a single cache
463  * line.
464  */
465 #define MPT_NUM_REPLY_HANDLERS		(32)
466 #define MPT_REPLY_HANDLER_EVENTS	MPT_CBI_TO_HID(0)
467 #define MPT_REPLY_HANDLER_CONFIG	MPT_CBI_TO_HID(MPT_NUM_REPLY_HANDLERS-1)
468 #define MPT_REPLY_HANDLER_HANDSHAKE	MPT_CBI_TO_HID(MPT_NUM_REPLY_HANDLERS-2)
469 typedef int mpt_reply_handler_t(struct mpt_softc *mpt, request_t *request,
470     uint32_t reply_desc, MSG_DEFAULT_REPLY *reply_frame);
471 typedef union {
472 	mpt_reply_handler_t	*reply_handler;
473 } mpt_handler_t;
474 
475 typedef enum {
476 	MPT_HANDLER_REPLY,
477 	MPT_HANDLER_EVENT,
478 	MPT_HANDLER_RESET,
479 	MPT_HANDLER_SHUTDOWN
480 } mpt_handler_type;
481 
482 struct mpt_handler_record
483 {
484 	LIST_ENTRY(mpt_handler_record)	links;
485 	mpt_handler_t			handler;
486 };
487 
488 LIST_HEAD(mpt_handler_list, mpt_handler_record);
489 
490 /*
491  * The handler_id is currently unused but would contain the
492  * handler ID used in the MsgContext field to allow direction
493  * of replies to the handler.  Registrations that don't require
494  * a handler id can pass in NULL for the handler_id.
495  *
496  * Deregistrations for handlers without a handler id should
497  * pass in MPT_HANDLER_ID_NONE.
498  */
499 #define MPT_HANDLER_ID_NONE		(0xFFFFFFFF)
500 int mpt_register_handler(struct mpt_softc *, mpt_handler_type,
501 			 mpt_handler_t, uint32_t *);
502 int mpt_deregister_handler(struct mpt_softc *, mpt_handler_type,
503 			   mpt_handler_t, uint32_t);
504 
505 /******************* Per-Controller Instance Data Structures ******************/
506 TAILQ_HEAD(req_queue, req_entry);
507 
508 /* Structure for saving proper values for modifyable PCI config registers */
509 struct mpt_pci_cfg {
510 	uint16_t Command;
511 	uint16_t LatencyTimer_LineSize;
512 	uint32_t IO_BAR;
513 	uint32_t Mem0_BAR[2];
514 	uint32_t Mem1_BAR[2];
515 	uint32_t ROM_BAR;
516 	uint8_t  IntLine;
517 	uint32_t PMCSR;
518 };
519 
520 typedef enum {
521 	MPT_RVF_NONE		= 0x0,
522 	MPT_RVF_ACTIVE		= 0x1,
523 	MPT_RVF_ANNOUNCED	= 0x2,
524 	MPT_RVF_UP2DATE		= 0x4,
525 	MPT_RVF_REFERENCED	= 0x8,
526 	MPT_RVF_WCE_CHANGED	= 0x10
527 } mpt_raid_volume_flags;
528 
529 struct mpt_raid_volume {
530 	CONFIG_PAGE_RAID_VOL_0	       *config_page;
531 	MPI_RAID_VOL_INDICATOR		sync_progress;
532 	mpt_raid_volume_flags		flags;
533 	u_int				quiesced_disks;
534 };
535 
536 typedef enum {
537 	MPT_RDF_NONE		= 0x00,
538 	MPT_RDF_ACTIVE		= 0x01,
539 	MPT_RDF_ANNOUNCED	= 0x02,
540 	MPT_RDF_UP2DATE		= 0x04,
541 	MPT_RDF_REFERENCED	= 0x08,
542 	MPT_RDF_QUIESCING	= 0x10,
543 	MPT_RDF_QUIESCED	= 0x20
544 } mpt_raid_disk_flags;
545 
546 struct mpt_raid_disk {
547 	CONFIG_PAGE_RAID_PHYS_DISK_0	config_page;
548 	struct mpt_raid_volume	       *volume;
549 	u_int				member_number;
550 	u_int				pass_thru_active;
551 	mpt_raid_disk_flags		flags;
552 };
553 
554 struct mpt_evtf_record {
555 	MSG_EVENT_NOTIFY_REPLY		reply;
556 	uint32_t			context;
557 	LIST_ENTRY(mpt_evtf_record)	links;
558 };
559 
560 LIST_HEAD(mpt_evtf_list, mpt_evtf_record);
561 
562 struct mptsas_devinfo {
563 	uint16_t	dev_handle;
564 	uint16_t	parent_dev_handle;
565 	uint16_t	enclosure_handle;
566 	uint16_t	slot;
567 	uint8_t		phy_num;
568 	uint8_t		physical_port;
569 	uint8_t		target_id;
570 	uint8_t		bus;
571 	uint64_t	sas_address;
572 	uint32_t	device_info;
573 };
574 
575 struct mptsas_phyinfo {
576 	uint16_t	handle;
577 	uint8_t		phy_num;
578 	uint8_t		port_id;
579 	uint8_t		negotiated_link_rate;
580 	uint8_t		hw_link_rate;
581 	uint8_t		programmed_link_rate;
582 	uint8_t		sas_port_add_phy;
583 	struct mptsas_devinfo identify;
584 	struct mptsas_devinfo attached;
585 };
586 
587 struct mptsas_portinfo {
588 	uint16_t			num_phys;
589 	struct mptsas_phyinfo		*phy_info;
590 };
591 
592 struct mpt_softc {
593 	device_t		dev;
594 #if __FreeBSD_version < 500000
595 	uint32_t		mpt_islocked;
596 	int			mpt_splsaved;
597 #else
598 	struct mtx		mpt_lock;
599 	int			mpt_locksetup;
600 #endif
601 	uint32_t		mpt_pers_mask;
602 	uint32_t
603 				: 8,
604 		unit		: 8,
605 		ready		: 1,
606 		fw_uploaded	: 1,
607 		msi_enable	: 1,
608 		twildcard	: 1,
609 		tenabled	: 1,
610 		do_cfg_role	: 1,
611 		raid_enabled	: 1,
612 		raid_mwce_set	: 1,
613 		getreqwaiter	: 1,
614 		shutdwn_raid    : 1,
615 		shutdwn_recovery: 1,
616 		outofbeer	: 1,
617 		disabled	: 1,
618 		is_spi		: 1,
619 		is_sas		: 1,
620 		is_fc		: 1;
621 
622 	u_int			cfg_role;
623 	u_int			role;	/* role: none, ini, target, both */
624 
625 	u_int			verbose;
626 #ifdef	MPT_TEST_MULTIPATH
627 	int			failure_id;
628 #endif
629 
630 	/*
631 	 * IOC Facts
632 	 */
633 	MSG_IOC_FACTS_REPLY	ioc_facts;
634 
635 	/*
636 	 * Port Facts
637 	 */
638 	MSG_PORT_FACTS_REPLY *	port_facts;
639 #define	mpt_ini_id	port_facts[0].PortSCSIID
640 #define	mpt_max_tgtcmds	port_facts[0].MaxPostedCmdBuffers
641 
642 	/*
643 	 * Device Configuration Information
644 	 */
645 	union {
646 		struct mpt_spi_cfg {
647 			CONFIG_PAGE_SCSI_PORT_0		_port_page0;
648 			CONFIG_PAGE_SCSI_PORT_1		_port_page1;
649 			CONFIG_PAGE_SCSI_PORT_2		_port_page2;
650 			CONFIG_PAGE_SCSI_DEVICE_0	_dev_page0[16];
651 			CONFIG_PAGE_SCSI_DEVICE_1	_dev_page1[16];
652 			uint16_t			_tag_enable;
653 			uint16_t			_disc_enable;
654 		} spi;
655 #define	mpt_port_page0		cfg.spi._port_page0
656 #define	mpt_port_page1		cfg.spi._port_page1
657 #define	mpt_port_page2		cfg.spi._port_page2
658 #define	mpt_dev_page0		cfg.spi._dev_page0
659 #define	mpt_dev_page1		cfg.spi._dev_page1
660 #define	mpt_tag_enable		cfg.spi._tag_enable
661 #define	mpt_disc_enable		cfg.spi._disc_enable
662 		struct mpi_fc_cfg {
663 			CONFIG_PAGE_FC_PORT_0 _port_page0;
664 			uint32_t _port_speed;
665 #define	mpt_fcport_page0	cfg.fc._port_page0
666 #define	mpt_fcport_speed	cfg.fc._port_speed
667 		} fc;
668 	} cfg;
669 #if __FreeBSD_version >= 500000
670 	/*
671 	 * Device config information stored up for sysctl to access
672 	 */
673 	union {
674 		struct {
675 			unsigned int initiator_id;
676 		} spi;
677 		struct {
678 			char wwnn[19];
679 			char wwpn[19];
680 		} fc;
681 	} scinfo;
682 #endif
683 
684 	/* Controller Info for RAID information */
685 	CONFIG_PAGE_IOC_2 *	ioc_page2;
686 	CONFIG_PAGE_IOC_3 *	ioc_page3;
687 
688 	/* Raid Data */
689 	struct mpt_raid_volume* raid_volumes;
690 	struct mpt_raid_disk*	raid_disks;
691 	u_int			raid_max_volumes;
692 	u_int			raid_max_disks;
693 	u_int			raid_page0_len;
694 	u_int			raid_wakeup;
695 	u_int			raid_rescan;
696 	u_int			raid_resync_rate;
697 	u_int			raid_mwce_setting;
698 	u_int			raid_queue_depth;
699 	u_int			raid_nonopt_volumes;
700 	thread_t 	        raid_thread;
701 	struct callout		raid_timer;
702 
703 	/*
704 	 * PCI Hardware info
705 	 */
706 	int			pci_msi_count;
707 	struct resource *	pci_irq;	/* Interrupt map for chip */
708 	void *			ih;		/* Interupt handle */
709 	struct mpt_pci_cfg	pci_cfg;	/* saved PCI conf registers */
710 
711 	/*
712 	 * DMA Mapping Stuff
713 	 */
714 	struct resource *	pci_reg;	/* Register map for chip */
715 	int			pci_mem_rid;	/* Resource ID */
716 	bus_space_tag_t		pci_st;		/* Bus tag for registers */
717 	bus_space_handle_t	pci_sh;		/* Bus handle for registers */
718 	/* PIO versions of above. */
719 	int			pci_pio_rid;
720 	struct resource *	pci_pio_reg;
721 	bus_space_tag_t		pci_pio_st;
722 	bus_space_handle_t	pci_pio_sh;
723 
724 	bus_dma_tag_t		parent_dmat;	/* DMA tag for parent PCI bus */
725 	bus_dma_tag_t		reply_dmat;	/* DMA tag for reply memory */
726 	bus_dmamap_t		reply_dmap;	/* DMA map for reply memory */
727 	uint8_t		       *reply;		/* KVA of reply memory */
728 	bus_addr_t		reply_phys;	/* BusAddr of reply memory */
729 
730 	bus_dma_tag_t		buffer_dmat;	/* DMA tag for buffers */
731 	bus_dma_tag_t		request_dmat;	/* DMA tag for request memroy */
732 	bus_dmamap_t		request_dmap;	/* DMA map for request memroy */
733 	uint8_t		       *request;	/* KVA of Request memory */
734 	bus_addr_t		request_phys;	/* BusAddr of request memory */
735 
736 	uint32_t		max_seg_cnt;	/* calculated after IOC facts */
737 
738 	/*
739 	 * Hardware management
740 	 */
741 	u_int			reset_cnt;
742 
743 	/*
744 	 * CAM && Software Management
745 	 */
746 	request_t	       *request_pool;
747 	struct req_queue	request_free_list;
748 	struct req_queue	request_pending_list;
749 	struct req_queue	request_timeout_list;
750 
751 
752 	struct cam_sim	       *sim;
753 	struct cam_path	       *path;
754 
755 	struct cam_sim	       *phydisk_sim;
756 	struct cam_path	       *phydisk_path;
757 
758 	thread_t	       recovery_thread;
759 	request_t	       *tmf_req;
760 
761 	/*
762 	 * Deferred frame acks due to resource shortage.
763 	 */
764 	struct mpt_evtf_list	ack_frames;
765 
766 	/*
767 	 * Target Mode Support
768 	 */
769 	uint32_t		scsi_tgt_handler_id;
770 	request_t **		tgt_cmd_ptrs;
771 	request_t **		els_cmd_ptrs;	/* FC only */
772 
773 	/*
774 	 * *snork*- this is chosen to be here *just in case* somebody
775 	 * forgets to point to it exactly and we index off of trt with
776 	 * CAM_LUN_WILDCARD.
777 	 */
778 	tgt_resource_t		trt_wildcard;		/* wildcard luns */
779 	tgt_resource_t		trt[MPT_MAX_LUNS];
780 	uint16_t		tgt_cmds_allocated;
781 	uint16_t		els_cmds_allocated;	/* FC only */
782 
783 	uint16_t		timeouts;	/* timeout count */
784 	uint16_t		success;	/* successes afer timeout */
785 	uint16_t		sequence;	/* Sequence Number */
786 	uint16_t		pad3;
787 
788 
789 	/* Paired port in some dual adapters configurations */
790 	struct mpt_softc *	mpt2;
791 
792 	/* FW Image management */
793 	uint32_t		fw_image_size;
794 	uint8_t		       *fw_image;
795 	bus_dma_tag_t		fw_dmat;	/* DMA tag for firmware image */
796 	bus_dmamap_t		fw_dmap;	/* DMA map for firmware image */
797 	bus_addr_t		fw_phys;	/* BusAddr of firmware image */
798 
799 	/* SAS Topology */
800 	struct mptsas_portinfo	*sas_portinfo;
801 
802 	/* Shutdown Event Handler. */
803 	eventhandler_tag         eh;
804 
805 	/* Userland management interface. */
806 	struct cdev		*cdev;
807 
808 	TAILQ_ENTRY(mpt_softc)	links;
809 };
810 
811 static __inline void mpt_assign_serno(struct mpt_softc *, request_t *);
812 
813 static __inline void
814 mpt_assign_serno(struct mpt_softc *mpt, request_t *req)
815 {
816 	if ((req->serno = mpt->sequence++) == 0) {
817 		req->serno = mpt->sequence++;
818 	}
819 }
820 
821 /***************************** Locking Primitives *****************************/
822 #ifdef __DragonFly__
823 #define PUSER 0
824 #define MPT_IFLAGS              0
825 #define MPT_LOCK(mpt)           crit_enter()
826 #define MPT_UNLOCK(mpt)         crit_exit()
827 #define MPT_LOCK_SETUP(mpt)	do { } while(0)
828 #define MPT_LOCK_DESTROY(mpt)	do { } while(0)
829 #define MPT_LOCK_ASSERT(mpt)	do { } while(0)
830 #define	MPTLOCK_2_CAMLOCK	MPT_UNLOCK
831 #define	CAMLOCK_2_MPTLOCK	MPT_LOCK
832 #define splx(s)
833 #define splsoftvm() 0
834 static __inline int
835 mpt_sleep(struct mpt_softc *mpt, void *ident, int priority,
836 	   const char *wmesg, int timo) {
837 	int error;
838 	error = tsleep(ident, 0, wmesg, timo);
839 	return(error);
840 }
841 #endif
842 #define mpt_req_timeout(req, ticks, func, arg) \
843 	callout_reset(&(req)->callout, (ticks), (func), (arg));
844 #define mpt_req_untimeout(req, func, arg) \
845 	callout_stop(&(req)->callout)
846 #if 0
847 #if __FreeBSD_version < 500000
848 #define	MPT_IFLAGS		INTR_TYPE_CAM
849 #define	MPT_LOCK(mpt)		mpt_lockspl(mpt)
850 #define	MPT_UNLOCK(mpt)		mpt_unlockspl(mpt)
851 #define	MPT_OWNED(mpt)		mpt->mpt_islocked
852 #define	MPT_LOCK_ASSERT(mpt)
853 #define	MPTLOCK_2_CAMLOCK	MPT_UNLOCK
854 #define	CAMLOCK_2_MPTLOCK	MPT_LOCK
855 #define	MPT_LOCK_SETUP(mpt)
856 #define	MPT_LOCK_DESTROY(mpt)
857 
858 static __inline void mpt_lockspl(struct mpt_softc *mpt);
859 static __inline void mpt_unlockspl(struct mpt_softc *mpt);
860 
861 static __inline void
862 mpt_lockspl(struct mpt_softc *mpt)
863 {
864        int s;
865 
866        s = splcam();
867        if (mpt->mpt_islocked++ == 0) {
868                mpt->mpt_splsaved = s;
869        } else {
870                splx(s);
871 	       panic("Recursed lock with mask: 0x%x\n", s);
872        }
873 }
874 
875 static __inline void
876 mpt_unlockspl(struct mpt_softc *mpt)
877 {
878        if (mpt->mpt_islocked) {
879                if (--mpt->mpt_islocked == 0) {
880                        splx(mpt->mpt_splsaved);
881                }
882        } else
883 	       panic("Negative lock count\n");
884 }
885 
886 static __inline int
887 mpt_sleep(struct mpt_softc *mpt, void *ident, int priority,
888 	   const char *wmesg, int timo)
889 {
890 	int saved_cnt;
891 	int saved_spl;
892 	int error;
893 
894 	KASSERT(mpt->mpt_islocked <= 1, ("Invalid lock count on tsleep"));
895 	saved_cnt = mpt->mpt_islocked;
896 	saved_spl = mpt->mpt_splsaved;
897 	mpt->mpt_islocked = 0;
898 	error = tsleep(ident, priority, wmesg, timo);
899 	KASSERT(mpt->mpt_islocked == 0, ("Invalid lock count on wakeup"));
900 	mpt->mpt_islocked = saved_cnt;
901 	mpt->mpt_splsaved = saved_spl;
902 	return (error);
903 }
904 
905 #define mpt_req_timeout(req, ticks, func, arg) \
906 	callout_reset(&(req)->callout, (ticks), (func), (arg));
907 #define mpt_req_untimeout(req, func, arg) \
908 	callout_stop(&(req)->callout)
909 #else
910 #if 1
911 #define	MPT_IFLAGS		INTR_TYPE_CAM | INTR_ENTROPY | INTR_MPSAFE
912 #define	MPT_LOCK_SETUP(mpt)						\
913 		mtx_init(&mpt->mpt_lock, "mpt", NULL, MTX_DEF);		\
914 		mpt->mpt_locksetup = 1
915 #define	MPT_LOCK_DESTROY(mpt)						\
916 	if (mpt->mpt_locksetup) {					\
917 		mtx_destroy(&mpt->mpt_lock);				\
918 		mpt->mpt_locksetup = 0;					\
919 	}
920 
921 #define	MPT_LOCK(mpt)		mtx_lock(&(mpt)->mpt_lock)
922 #define	MPT_UNLOCK(mpt)		mtx_unlock(&(mpt)->mpt_lock)
923 #define	MPT_OWNED(mpt)		mtx_owned(&(mpt)->mpt_lock)
924 #define	MPT_LOCK_ASSERT(mpt)	mtx_assert(&(mpt)->mpt_lock, MA_OWNED)
925 #define	MPTLOCK_2_CAMLOCK(mpt)
926 #define	CAMLOCK_2_MPTLOCK(mpt)
927 #define mpt_sleep(mpt, ident, priority, wmesg, timo) \
928 	msleep(ident, &(mpt)->mpt_lock, priority, wmesg, timo)
929 #define mpt_req_timeout(req, ticks, func, arg) \
930 	callout_reset(&(req)->callout, (ticks), (func), (arg));
931 #define mpt_req_untimeout(req, func, arg) \
932 	callout_stop(&(req)->callout)
933 #else
934 
935 #define	MPT_IFLAGS		INTR_TYPE_CAM | INTR_ENTROPY
936 #define	MPT_LOCK_SETUP(mpt)	do { } while (0)
937 #define	MPT_LOCK_DESTROY(mpt)	do { } while (0)
938 #define	MPT_LOCK_ASSERT(mpt)	mtx_assert(&Giant, MA_OWNED)
939 #define	MPT_LOCK(mpt)		mtx_lock(&Giant)
940 #define	MPT_UNLOCK(mpt)		mtx_unlock(&Giant)
941 #define	MPTLOCK_2_CAMLOCK(mpt)
942 #define	CAMLOCK_2_MPTLOCK(mpt)
943 
944 static __inline int
945 mpt_sleep(struct mpt_softc *, void *, int, const char *, int);
946 
947 #define mpt_ccb_timeout(ccb, ticks, func, arg) \
948 	do {	\
949 		(ccb)->ccb_h.timeout_ch = timeout((func), (arg), (ticks)); \
950 	} while (0)
951 #define mpt_ccb_untimeout(ccb, func, arg) \
952 	untimeout((func), (arg), (ccb)->ccb_h.timeout_ch)
953 #define mpt_ccb_timeout_init(ccb) \
954 	callout_handle_init(&(ccb)->ccb_h.timeout_ch)
955 
956 static __inline int
957 mpt_sleep(struct mpt_softc *mpt, void *i, int p, const char *w, int t)
958 {
959 	int r;
960 	r = tsleep(i, p, w, t);
961 	return (r);
962 }
963 #endif
964 #endif
965 #endif
966 
967 /******************************* Register Access ******************************/
968 static __inline void mpt_write(struct mpt_softc *, size_t, uint32_t);
969 static __inline uint32_t mpt_read(struct mpt_softc *, int);
970 static __inline void mpt_pio_write(struct mpt_softc *, size_t, uint32_t);
971 static __inline uint32_t mpt_pio_read(struct mpt_softc *, int);
972 
973 static __inline void
974 mpt_write(struct mpt_softc *mpt, size_t offset, uint32_t val)
975 {
976 	bus_space_write_4(mpt->pci_st, mpt->pci_sh, offset, val);
977 }
978 
979 static __inline uint32_t
980 mpt_read(struct mpt_softc *mpt, int offset)
981 {
982 	return (bus_space_read_4(mpt->pci_st, mpt->pci_sh, offset));
983 }
984 
985 /*
986  * Some operations (e.g. diagnostic register writes while the ARM proccessor
987  * is disabled), must be performed using "PCI pio" operations.  On non-PCI
988  * busses, these operations likely map to normal register accesses.
989  */
990 static __inline void
991 mpt_pio_write(struct mpt_softc *mpt, size_t offset, uint32_t val)
992 {
993 	bus_space_write_4(mpt->pci_pio_st, mpt->pci_pio_sh, offset, val);
994 }
995 
996 static __inline uint32_t
997 mpt_pio_read(struct mpt_softc *mpt, int offset)
998 {
999 	return (bus_space_read_4(mpt->pci_pio_st, mpt->pci_pio_sh, offset));
1000 }
1001 /*********************** Reply Frame/Request Management ***********************/
1002 /* Max MPT Reply we are willing to accept (must be power of 2) */
1003 #define MPT_REPLY_SIZE   	256
1004 
1005 /* Max i/o size, based on legacy MAXPHYS.  Can be increased. */
1006 #define MPT_MAXPHYS		(128 * 1024)
1007 
1008 /*
1009  * Must be less than 16384 in order for target mode to work
1010  */
1011 #define MPT_MAX_REQUESTS(mpt)	512
1012 #define MPT_REQUEST_AREA	512
1013 #define MPT_SENSE_SIZE		32	/* included in MPT_REQUEST_AREA */
1014 #define MPT_REQ_MEM_SIZE(mpt)	(MPT_MAX_REQUESTS(mpt) * MPT_REQUEST_AREA)
1015 
1016 #define MPT_CONTEXT_CB_SHIFT	(16)
1017 #define MPT_CBI(handle)		(handle >> MPT_CONTEXT_CB_SHIFT)
1018 #define MPT_CBI_TO_HID(cbi)	((cbi) << MPT_CONTEXT_CB_SHIFT)
1019 #define MPT_CONTEXT_TO_CBI(x)	\
1020     (((x) >> MPT_CONTEXT_CB_SHIFT) & (MPT_NUM_REPLY_HANDLERS - 1))
1021 #define MPT_CONTEXT_REQI_MASK	0xFFFF
1022 #define MPT_CONTEXT_TO_REQI(x)	((x) & MPT_CONTEXT_REQI_MASK)
1023 
1024 /*
1025  * Convert a 32bit physical address returned from IOC to an
1026  * offset into our reply frame memory or the kvm address needed
1027  * to access the data.  The returned address is only the low
1028  * 32 bits, so mask our base physical address accordingly.
1029  */
1030 #define MPT_REPLY_BADDR(x)		\
1031 	(x << 1)
1032 #define MPT_REPLY_OTOV(m, i) 		\
1033 	((void *)(&m->reply[i]))
1034 
1035 #define	MPT_DUMP_REPLY_FRAME(mpt, reply_frame)		\
1036 do {							\
1037 	if (mpt->verbose > MPT_PRT_DEBUG)		\
1038 		mpt_dump_reply_frame(mpt, reply_frame);	\
1039 } while(0)
1040 
1041 static __inline uint32_t mpt_pop_reply_queue(struct mpt_softc *mpt);
1042 static __inline void mpt_free_reply(struct mpt_softc *mpt, uint32_t ptr);
1043 
1044 /*
1045  * Give the reply buffer back to the IOC after we have
1046  * finished processing it.
1047  */
1048 static __inline void
1049 mpt_free_reply(struct mpt_softc *mpt, uint32_t ptr)
1050 {
1051      mpt_write(mpt, MPT_OFFSET_REPLY_Q, ptr);
1052 }
1053 
1054 /* Get a reply from the IOC */
1055 static __inline uint32_t
1056 mpt_pop_reply_queue(struct mpt_softc *mpt)
1057 {
1058      return mpt_read(mpt, MPT_OFFSET_REPLY_Q);
1059 }
1060 
1061 void
1062 mpt_complete_request_chain(struct mpt_softc *, struct req_queue *, u_int);
1063 
1064 /************************** Scatter Gather Managment **************************/
1065 /* MPT_RQSL- size of request frame, in bytes */
1066 #define	MPT_RQSL(mpt)		(mpt->ioc_facts.RequestFrameSize << 2)
1067 
1068 /* MPT_NSGL- how many SG entries can fit in a request frame size */
1069 #define	MPT_NSGL(mpt)		(MPT_RQSL(mpt) / sizeof (SGE_IO_UNION))
1070 
1071 /* MPT_NRFM- how many request frames can fit in each request alloc we make */
1072 #define	MPT_NRFM(mpt)		(MPT_REQUEST_AREA / MPT_RQSL(mpt))
1073 
1074 /*
1075  * MPT_NSGL_FIRST- # of SG elements that can fit after
1076  * an I/O request but still within the request frame.
1077  * Do this safely based upon SGE_IO_UNION.
1078  *
1079  * Note that the first element is *within* the SCSI request.
1080  */
1081 #define	MPT_NSGL_FIRST(mpt)	\
1082     ((MPT_RQSL(mpt) - sizeof (MSG_SCSI_IO_REQUEST) + sizeof (SGE_IO_UNION)) / \
1083     sizeof (SGE_IO_UNION))
1084 
1085 /***************************** IOC Initialization *****************************/
1086 int mpt_reset(struct mpt_softc *, int /*reinit*/);
1087 
1088 /****************************** Debugging ************************************/
1089 typedef struct mpt_decode_entry {
1090 	char    *name;
1091 	u_int	 value;
1092 	u_int	 mask;
1093 } mpt_decode_entry_t;
1094 
1095 int mpt_decode_value(mpt_decode_entry_t *table, u_int num_entries,
1096 		     const char *name, u_int value, u_int *cur_column,
1097 		     u_int wrap_point);
1098 
1099 void mpt_dump_data(struct mpt_softc *, const char *, void *, int);
1100 void mpt_dump_request(struct mpt_softc *, request_t *);
1101 
1102 enum {
1103 	MPT_PRT_ALWAYS,
1104 	MPT_PRT_FATAL,
1105 	MPT_PRT_ERROR,
1106 	MPT_PRT_WARN,
1107 	MPT_PRT_INFO,
1108 	MPT_PRT_NEGOTIATION,
1109 	MPT_PRT_DEBUG,
1110 	MPT_PRT_DEBUG1,
1111 	MPT_PRT_DEBUG2,
1112 	MPT_PRT_DEBUG3,
1113 	MPT_PRT_TRACE,
1114 	MPT_PRT_NONE=100
1115 };
1116 
1117 #if __FreeBSD_version > 500000
1118 #define mpt_lprt(mpt, level, ...)		\
1119 do {						\
1120 	if (level <= (mpt)->verbose)		\
1121 		mpt_prt(mpt, __VA_ARGS__);	\
1122 } while (0)
1123 
1124 #define mpt_lprtc(mpt, level, ...)		 \
1125 do {						 \
1126 	if (level <= (mpt)->debug_level)	 \
1127 		mpt_prtc(mpt, __VA_ARGS__);	 \
1128 } while (0)
1129 #else
1130 void mpt_lprt(struct mpt_softc *, int, const char *, ...)
1131 	__printflike(3, 4);
1132 void mpt_lprtc(struct mpt_softc *, int, const char *, ...)
1133 	__printflike(3, 4);
1134 #endif
1135 void mpt_prt(struct mpt_softc *, const char *, ...)
1136 	__printflike(2, 3);
1137 void mpt_prtc(struct mpt_softc *, const char *, ...)
1138 	__printflike(2, 3);
1139 
1140 /**************************** Target Mode Related ***************************/
1141 static __inline int mpt_cdblen(uint8_t, int);
1142 static __inline int
1143 mpt_cdblen(uint8_t cdb0, int maxlen)
1144 {
1145 	int group = cdb0 >> 5;
1146 	switch (group) {
1147 	case 0:
1148 		return (6);
1149 	case 1:
1150 		return (10);
1151 	case 4:
1152 	case 5:
1153 		return (12);
1154 	default:
1155 		return (16);
1156 	}
1157 }
1158 #ifdef	INVARIANTS
1159 static __inline request_t * mpt_tag_2_req(struct mpt_softc *, uint32_t);
1160 static __inline request_t *
1161 mpt_tag_2_req(struct mpt_softc *mpt, uint32_t tag)
1162 {
1163 	uint16_t rtg = (tag >> 18);
1164 	KASSERT(rtg < mpt->tgt_cmds_allocated, ("bad tag %d\n", tag));
1165 	KASSERT(mpt->tgt_cmd_ptrs, ("no cmd backpointer array"));
1166 	KASSERT(mpt->tgt_cmd_ptrs[rtg], ("no cmd backpointer"));
1167 	return (mpt->tgt_cmd_ptrs[rtg]);
1168 }
1169 
1170 
1171 static __inline int
1172 mpt_req_on_free_list(struct mpt_softc *, request_t *);
1173 static __inline int
1174 mpt_req_on_pending_list(struct mpt_softc *, request_t *);
1175 
1176 static __inline void
1177 mpt_req_spcl(struct mpt_softc *, request_t *, const char *, int);
1178 static __inline void
1179 mpt_req_not_spcl(struct mpt_softc *, request_t *, const char *, int);
1180 
1181 
1182 /*
1183  * Is request on freelist?
1184  */
1185 static __inline int
1186 mpt_req_on_free_list(struct mpt_softc *mpt, request_t *req)
1187 {
1188 	request_t *lrq;
1189 
1190 	TAILQ_FOREACH(lrq, &mpt->request_free_list, links) {
1191 		if (lrq == req) {
1192 			return (1);
1193 		}
1194 	}
1195 	return (0);
1196 }
1197 
1198 /*
1199  * Is request on pending list?
1200  */
1201 static __inline int
1202 mpt_req_on_pending_list(struct mpt_softc *mpt, request_t *req)
1203 {
1204 	request_t *lrq;
1205 
1206 	TAILQ_FOREACH(lrq, &mpt->request_pending_list, links) {
1207 		if (lrq == req) {
1208 			return (1);
1209 		}
1210 	}
1211 	return (0);
1212 }
1213 
1214 /*
1215  * Make sure that req *is* part of one of the special lists
1216  */
1217 static __inline void
1218 mpt_req_spcl(struct mpt_softc *mpt, request_t *req, const char *s, int line)
1219 {
1220 	int i;
1221 	for (i = 0; i < mpt->els_cmds_allocated; i++) {
1222 		if (req == mpt->els_cmd_ptrs[i]) {
1223 			return;
1224 		}
1225 	}
1226 	for (i = 0; i < mpt->tgt_cmds_allocated; i++) {
1227 		if (req == mpt->tgt_cmd_ptrs[i]) {
1228 			return;
1229 		}
1230 	}
1231 	panic("%s(%d): req %p:%u function %x not in els or tgt ptrs\n",
1232 	    s, line, req, req->serno,
1233 	    ((PTR_MSG_REQUEST_HEADER)req->req_vbuf)->Function);
1234 }
1235 
1236 /*
1237  * Make sure that req is *not* part of one of the special lists.
1238  */
1239 static __inline void
1240 mpt_req_not_spcl(struct mpt_softc *mpt, request_t *req, const char *s, int line)
1241 {
1242 	int i;
1243 	for (i = 0; i < mpt->els_cmds_allocated; i++) {
1244 		KASSERT(req != mpt->els_cmd_ptrs[i],
1245 		    ("%s(%d): req %p:%u func %x in els ptrs at ioindex %d\n",
1246 		    s, line, req, req->serno,
1247 		    ((PTR_MSG_REQUEST_HEADER)req->req_vbuf)->Function, i));
1248 	}
1249 	for (i = 0; i < mpt->tgt_cmds_allocated; i++) {
1250 		KASSERT(req != mpt->tgt_cmd_ptrs[i],
1251 		    ("%s(%d): req %p:%u func %x in tgt ptrs at ioindex %d\n",
1252 		    s, line, req, req->serno,
1253 		    ((PTR_MSG_REQUEST_HEADER)req->req_vbuf)->Function, i));
1254 	}
1255 }
1256 #endif
1257 
1258 /*
1259  * Task Management Types, purely for internal consumption
1260  */
1261 typedef enum {
1262 	MPT_ABORT_TASK_SET=1234,
1263 	MPT_CLEAR_TASK_SET,
1264 	MPT_TARGET_RESET,
1265 	MPT_CLEAR_ACA,
1266 	MPT_TERMINATE_TASK,
1267 	MPT_NIL_TMT_VALUE=5678
1268 } mpt_task_mgmt_t;
1269 
1270 /**************************** Unclassified Routines ***************************/
1271 void		mpt_send_cmd(struct mpt_softc *mpt, request_t *req);
1272 int		mpt_recv_handshake_reply(struct mpt_softc *mpt,
1273 					 size_t reply_len, void *reply);
1274 int		mpt_wait_req(struct mpt_softc *mpt, request_t *req,
1275 			     mpt_req_state_t state, mpt_req_state_t mask,
1276 			     int sleep_ok, int time_ms);
1277 void		mpt_enable_ints(struct mpt_softc *mpt);
1278 void		mpt_disable_ints(struct mpt_softc *mpt);
1279 int		mpt_attach(struct mpt_softc *mpt);
1280 int		mpt_shutdown(struct mpt_softc *mpt);
1281 int		mpt_detach(struct mpt_softc *mpt);
1282 int		mpt_send_handshake_cmd(struct mpt_softc *mpt,
1283 				       size_t len, void *cmd);
1284 request_t *	mpt_get_request(struct mpt_softc *mpt, int sleep_ok);
1285 void		mpt_free_request(struct mpt_softc *mpt, request_t *req);
1286 void		mpt_intr(void *arg);
1287 void		mpt_check_doorbell(struct mpt_softc *mpt);
1288 void		mpt_dump_reply_frame(struct mpt_softc *mpt,
1289 				     MSG_DEFAULT_REPLY *reply_frame);
1290 
1291 void		mpt_set_config_regs(struct mpt_softc *);
1292 int		mpt_issue_cfg_req(struct mpt_softc */*mpt*/, request_t */*req*/,
1293 				  cfgparms_t *params,
1294 				  bus_addr_t /*addr*/, bus_size_t/*len*/,
1295 				  int /*sleep_ok*/, int /*timeout_ms*/);
1296 int		mpt_read_extcfg_header(struct mpt_softc *mpt, int PageVersion,
1297 				       int PageNumber, uint32_t PageAddress,
1298 				       int ExtPageType,
1299 				       CONFIG_EXTENDED_PAGE_HEADER *rslt,
1300 				       int sleep_ok, int timeout_ms);
1301 int		mpt_read_extcfg_page(struct mpt_softc *mpt, int Action,
1302 				     uint32_t PageAddress,
1303 				     CONFIG_EXTENDED_PAGE_HEADER *hdr,
1304 				     void *buf, size_t len, int sleep_ok,
1305 				     int timeout_ms);
1306 int		mpt_read_cfg_header(struct mpt_softc *, int /*PageType*/,
1307 				    int /*PageNumber*/,
1308 				    uint32_t /*PageAddress*/,
1309 				    CONFIG_PAGE_HEADER *,
1310 				    int /*sleep_ok*/, int /*timeout_ms*/);
1311 int		mpt_read_cfg_page(struct mpt_softc *t, int /*Action*/,
1312 				  uint32_t /*PageAddress*/,
1313 				  CONFIG_PAGE_HEADER *, size_t /*len*/,
1314 				  int /*sleep_ok*/, int /*timeout_ms*/);
1315 int		mpt_write_cfg_page(struct mpt_softc *, int /*Action*/,
1316 				   uint32_t /*PageAddress*/,
1317 				   CONFIG_PAGE_HEADER *, size_t /*len*/,
1318 				   int /*sleep_ok*/, int /*timeout_ms*/);
1319 static __inline int
1320 mpt_read_cur_cfg_page(struct mpt_softc *mpt, uint32_t PageAddress,
1321 		      CONFIG_PAGE_HEADER *hdr, size_t len,
1322 		      int sleep_ok, int timeout_ms)
1323 {
1324 	return (mpt_read_cfg_page(mpt, MPI_CONFIG_ACTION_PAGE_READ_CURRENT,
1325 				  PageAddress, hdr, len, sleep_ok, timeout_ms));
1326 }
1327 
1328 static __inline int
1329 mpt_write_cur_cfg_page(struct mpt_softc *mpt, uint32_t PageAddress,
1330 		       CONFIG_PAGE_HEADER *hdr, size_t len, int sleep_ok,
1331 		       int timeout_ms)
1332 {
1333 	return (mpt_write_cfg_page(mpt, MPI_CONFIG_ACTION_PAGE_WRITE_CURRENT,
1334 				   PageAddress, hdr, len, sleep_ok,
1335 				   timeout_ms));
1336 }
1337 /* mpt_debug.c functions */
1338 void mpt_print_reply(void *vmsg);
1339 void mpt_print_db(uint32_t mb);
1340 void mpt_print_config_reply(void *vmsg);
1341 char *mpt_ioc_diag(uint32_t diag);
1342 void mpt_req_state(mpt_req_state_t state);
1343 void mpt_print_config_request(void *vmsg);
1344 void mpt_print_request(void *vmsg);
1345 void mpt_print_scsi_io_request(MSG_SCSI_IO_REQUEST *msg);
1346 void mpt_dump_sgl(SGE_IO_UNION *se, int offset);
1347 #endif /* _MPT_H_ */
1348