xref: /freebsd/sys/dev/mps/mps_user.c (revision 50757b1452ca4c8df14ee66227cd417c15089d73)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2008 Yahoo!, Inc.
5  * All rights reserved.
6  * Written by: John Baldwin <jhb@FreeBSD.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the author nor the names of any co-contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * Avago Technologies (LSI) MPT-Fusion Host Adapter FreeBSD userland interface
33  */
34 /*-
35  * Copyright (c) 2011-2015 LSI Corp.
36  * Copyright (c) 2013-2015 Avago Technologies
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  * Avago Technologies (LSI) MPT-Fusion Host Adapter FreeBSD
61  *
62  * $FreeBSD$
63  */
64 
65 #include <sys/cdefs.h>
66 __FBSDID("$FreeBSD$");
67 
68 /* TODO Move headers to mpsvar */
69 #include <sys/types.h>
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/kernel.h>
73 #include <sys/selinfo.h>
74 #include <sys/module.h>
75 #include <sys/bus.h>
76 #include <sys/conf.h>
77 #include <sys/bio.h>
78 #include <sys/malloc.h>
79 #include <sys/uio.h>
80 #include <sys/sysctl.h>
81 #include <sys/ioccom.h>
82 #include <sys/endian.h>
83 #include <sys/queue.h>
84 #include <sys/kthread.h>
85 #include <sys/taskqueue.h>
86 #include <sys/proc.h>
87 #include <sys/sysent.h>
88 
89 #include <machine/bus.h>
90 #include <machine/resource.h>
91 #include <sys/rman.h>
92 
93 #include <cam/cam.h>
94 #include <cam/cam_ccb.h>
95 #include <cam/scsi/scsi_all.h>
96 
97 #include <dev/mps/mpi/mpi2_type.h>
98 #include <dev/mps/mpi/mpi2.h>
99 #include <dev/mps/mpi/mpi2_ioc.h>
100 #include <dev/mps/mpi/mpi2_cnfg.h>
101 #include <dev/mps/mpi/mpi2_init.h>
102 #include <dev/mps/mpi/mpi2_tool.h>
103 #include <dev/mps/mps_ioctl.h>
104 #include <dev/mps/mpsvar.h>
105 #include <dev/mps/mps_table.h>
106 #include <dev/mps/mps_sas.h>
107 #include <dev/pci/pcivar.h>
108 #include <dev/pci/pcireg.h>
109 
110 static d_open_t		mps_open;
111 static d_close_t	mps_close;
112 static d_ioctl_t	mps_ioctl_devsw;
113 
114 static struct cdevsw mps_cdevsw = {
115 	.d_version =	D_VERSION,
116 	.d_flags =	0,
117 	.d_open =	mps_open,
118 	.d_close =	mps_close,
119 	.d_ioctl =	mps_ioctl_devsw,
120 	.d_name =	"mps",
121 };
122 
123 typedef int (mps_user_f)(struct mps_command *, struct mps_usr_command *);
124 static mps_user_f	mpi_pre_ioc_facts;
125 static mps_user_f	mpi_pre_port_facts;
126 static mps_user_f	mpi_pre_fw_download;
127 static mps_user_f	mpi_pre_fw_upload;
128 static mps_user_f	mpi_pre_sata_passthrough;
129 static mps_user_f	mpi_pre_smp_passthrough;
130 static mps_user_f	mpi_pre_config;
131 static mps_user_f	mpi_pre_sas_io_unit_control;
132 
133 static int mps_user_read_cfg_header(struct mps_softc *,
134 				    struct mps_cfg_page_req *);
135 static int mps_user_read_cfg_page(struct mps_softc *,
136 				  struct mps_cfg_page_req *, void *);
137 static int mps_user_read_extcfg_header(struct mps_softc *,
138 				     struct mps_ext_cfg_page_req *);
139 static int mps_user_read_extcfg_page(struct mps_softc *,
140 				     struct mps_ext_cfg_page_req *, void *);
141 static int mps_user_write_cfg_page(struct mps_softc *,
142 				   struct mps_cfg_page_req *, void *);
143 static int mps_user_setup_request(struct mps_command *,
144 				  struct mps_usr_command *);
145 static int mps_user_command(struct mps_softc *, struct mps_usr_command *);
146 
147 static int mps_user_pass_thru(struct mps_softc *sc, mps_pass_thru_t *data);
148 static void mps_user_get_adapter_data(struct mps_softc *sc,
149     mps_adapter_data_t *data);
150 static void mps_user_read_pci_info(struct mps_softc *sc,
151     mps_pci_info_t *data);
152 static uint8_t mps_get_fw_diag_buffer_number(struct mps_softc *sc,
153     uint32_t unique_id);
154 static int mps_post_fw_diag_buffer(struct mps_softc *sc,
155     mps_fw_diagnostic_buffer_t *pBuffer, uint32_t *return_code);
156 static int mps_release_fw_diag_buffer(struct mps_softc *sc,
157     mps_fw_diagnostic_buffer_t *pBuffer, uint32_t *return_code,
158     uint32_t diag_type);
159 static int mps_diag_register(struct mps_softc *sc,
160     mps_fw_diag_register_t *diag_register, uint32_t *return_code);
161 static int mps_diag_unregister(struct mps_softc *sc,
162     mps_fw_diag_unregister_t *diag_unregister, uint32_t *return_code);
163 static int mps_diag_query(struct mps_softc *sc, mps_fw_diag_query_t *diag_query,
164     uint32_t *return_code);
165 static int mps_diag_read_buffer(struct mps_softc *sc,
166     mps_diag_read_buffer_t *diag_read_buffer, uint8_t *ioctl_buf,
167     uint32_t *return_code);
168 static int mps_diag_release(struct mps_softc *sc,
169     mps_fw_diag_release_t *diag_release, uint32_t *return_code);
170 static int mps_do_diag_action(struct mps_softc *sc, uint32_t action,
171     uint8_t *diag_action, uint32_t length, uint32_t *return_code);
172 static int mps_user_diag_action(struct mps_softc *sc, mps_diag_action_t *data);
173 static void mps_user_event_query(struct mps_softc *sc, mps_event_query_t *data);
174 static void mps_user_event_enable(struct mps_softc *sc,
175     mps_event_enable_t *data);
176 static int mps_user_event_report(struct mps_softc *sc,
177     mps_event_report_t *data);
178 static int mps_user_reg_access(struct mps_softc *sc, mps_reg_access_t *data);
179 static int mps_user_btdh(struct mps_softc *sc, mps_btdh_mapping_t *data);
180 
181 MALLOC_DEFINE(M_MPSUSER, "mps_user", "Buffers for mps(4) ioctls");
182 
183 /* Macros from compat/freebsd32/freebsd32.h */
184 #define	PTRIN(v)	(void *)(uintptr_t)(v)
185 #define	PTROUT(v)	(uint32_t)(uintptr_t)(v)
186 
187 #define	CP(src,dst,fld) do { (dst).fld = (src).fld; } while (0)
188 #define	PTRIN_CP(src,dst,fld)				\
189 	do { (dst).fld = PTRIN((src).fld); } while (0)
190 #define	PTROUT_CP(src,dst,fld) \
191 	do { (dst).fld = PTROUT((src).fld); } while (0)
192 
193 int
194 mps_attach_user(struct mps_softc *sc)
195 {
196 	int unit;
197 
198 	unit = device_get_unit(sc->mps_dev);
199 	sc->mps_cdev = make_dev(&mps_cdevsw, unit, UID_ROOT, GID_OPERATOR, 0640,
200 	    "mps%d", unit);
201 	if (sc->mps_cdev == NULL) {
202 		return (ENOMEM);
203 	}
204 	sc->mps_cdev->si_drv1 = sc;
205 	return (0);
206 }
207 
208 void
209 mps_detach_user(struct mps_softc *sc)
210 {
211 
212 	/* XXX: do a purge of pending requests? */
213 	if (sc->mps_cdev != NULL)
214 		destroy_dev(sc->mps_cdev);
215 }
216 
217 static int
218 mps_open(struct cdev *dev, int flags, int fmt, struct thread *td)
219 {
220 
221 	return (0);
222 }
223 
224 static int
225 mps_close(struct cdev *dev, int flags, int fmt, struct thread *td)
226 {
227 
228 	return (0);
229 }
230 
231 static int
232 mps_user_read_cfg_header(struct mps_softc *sc,
233     struct mps_cfg_page_req *page_req)
234 {
235 	MPI2_CONFIG_PAGE_HEADER *hdr;
236 	struct mps_config_params params;
237 	int	    error;
238 
239 	hdr = &params.hdr.Struct;
240 	params.action = MPI2_CONFIG_ACTION_PAGE_HEADER;
241 	params.page_address = le32toh(page_req->page_address);
242 	hdr->PageVersion = 0;
243 	hdr->PageLength = 0;
244 	hdr->PageNumber = page_req->header.PageNumber;
245 	hdr->PageType = page_req->header.PageType;
246 	params.buffer = NULL;
247 	params.length = 0;
248 	params.callback = NULL;
249 
250 	if ((error = mps_read_config_page(sc, &params)) != 0) {
251 		/*
252 		 * Leave the request. Without resetting the chip, it's
253 		 * still owned by it and we'll just get into trouble
254 		 * freeing it now. Mark it as abandoned so that if it
255 		 * shows up later it can be freed.
256 		 */
257 		mps_printf(sc, "read_cfg_header timed out\n");
258 		return (ETIMEDOUT);
259 	}
260 
261 	page_req->ioc_status = htole16(params.status);
262 	if ((page_req->ioc_status & MPI2_IOCSTATUS_MASK) ==
263 	    MPI2_IOCSTATUS_SUCCESS) {
264 		bcopy(hdr, &page_req->header, sizeof(page_req->header));
265 	}
266 
267 	return (0);
268 }
269 
270 static int
271 mps_user_read_cfg_page(struct mps_softc *sc, struct mps_cfg_page_req *page_req,
272     void *buf)
273 {
274 	MPI2_CONFIG_PAGE_HEADER *reqhdr, *hdr;
275 	struct mps_config_params params;
276 	int	      error;
277 
278 	reqhdr = buf;
279 	hdr = &params.hdr.Struct;
280 	hdr->PageVersion = reqhdr->PageVersion;
281 	hdr->PageLength = reqhdr->PageLength;
282 	hdr->PageNumber = reqhdr->PageNumber;
283 	hdr->PageType = reqhdr->PageType & MPI2_CONFIG_PAGETYPE_MASK;
284 	params.action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT;
285 	params.page_address = le32toh(page_req->page_address);
286 	params.buffer = buf;
287 	params.length = le32toh(page_req->len);
288 	params.callback = NULL;
289 
290 	if ((error = mps_read_config_page(sc, &params)) != 0) {
291 		mps_printf(sc, "mps_user_read_cfg_page timed out\n");
292 		return (ETIMEDOUT);
293 	}
294 
295 	page_req->ioc_status = htole16(params.status);
296 	return (0);
297 }
298 
299 static int
300 mps_user_read_extcfg_header(struct mps_softc *sc,
301     struct mps_ext_cfg_page_req *ext_page_req)
302 {
303 	MPI2_CONFIG_EXTENDED_PAGE_HEADER *hdr;
304 	struct mps_config_params params;
305 	int	    error;
306 
307 	hdr = &params.hdr.Ext;
308 	params.action = MPI2_CONFIG_ACTION_PAGE_HEADER;
309 	hdr->PageVersion = ext_page_req->header.PageVersion;
310 	hdr->PageType = MPI2_CONFIG_PAGETYPE_EXTENDED;
311 	hdr->ExtPageLength = 0;
312 	hdr->PageNumber = ext_page_req->header.PageNumber;
313 	hdr->ExtPageType = ext_page_req->header.ExtPageType;
314 	params.page_address = le32toh(ext_page_req->page_address);
315 	params.buffer = NULL;
316 	params.length = 0;
317 	params.callback = NULL;
318 
319 	if ((error = mps_read_config_page(sc, &params)) != 0) {
320 		/*
321 		 * Leave the request. Without resetting the chip, it's
322 		 * still owned by it and we'll just get into trouble
323 		 * freeing it now. Mark it as abandoned so that if it
324 		 * shows up later it can be freed.
325 		 */
326 		mps_printf(sc, "mps_user_read_extcfg_header timed out\n");
327 		return (ETIMEDOUT);
328 	}
329 
330 	ext_page_req->ioc_status = htole16(params.status);
331 	if ((ext_page_req->ioc_status & MPI2_IOCSTATUS_MASK) ==
332 	    MPI2_IOCSTATUS_SUCCESS) {
333 		ext_page_req->header.PageVersion = hdr->PageVersion;
334 		ext_page_req->header.PageNumber = hdr->PageNumber;
335 		ext_page_req->header.PageType = hdr->PageType;
336 		ext_page_req->header.ExtPageLength = hdr->ExtPageLength;
337 		ext_page_req->header.ExtPageType = hdr->ExtPageType;
338 	}
339 
340 	return (0);
341 }
342 
343 static int
344 mps_user_read_extcfg_page(struct mps_softc *sc,
345     struct mps_ext_cfg_page_req *ext_page_req, void *buf)
346 {
347 	MPI2_CONFIG_EXTENDED_PAGE_HEADER *reqhdr, *hdr;
348 	struct mps_config_params params;
349 	int error;
350 
351 	reqhdr = buf;
352 	hdr = &params.hdr.Ext;
353 	params.action = MPI2_CONFIG_ACTION_PAGE_READ_CURRENT;
354 	params.page_address = le32toh(ext_page_req->page_address);
355 	hdr->PageVersion = reqhdr->PageVersion;
356 	hdr->PageType = MPI2_CONFIG_PAGETYPE_EXTENDED;
357 	hdr->PageNumber = reqhdr->PageNumber;
358 	hdr->ExtPageType = reqhdr->ExtPageType;
359 	hdr->ExtPageLength = reqhdr->ExtPageLength;
360 	params.buffer = buf;
361 	params.length = le32toh(ext_page_req->len);
362 	params.callback = NULL;
363 
364 	if ((error = mps_read_config_page(sc, &params)) != 0) {
365 		mps_printf(sc, "mps_user_read_extcfg_page timed out\n");
366 		return (ETIMEDOUT);
367 	}
368 
369 	ext_page_req->ioc_status = htole16(params.status);
370 	return (0);
371 }
372 
373 static int
374 mps_user_write_cfg_page(struct mps_softc *sc,
375     struct mps_cfg_page_req *page_req, void *buf)
376 {
377 	MPI2_CONFIG_PAGE_HEADER *reqhdr, *hdr;
378 	struct mps_config_params params;
379 	u_int	      hdr_attr;
380 	int	      error;
381 
382 	reqhdr = buf;
383 	hdr = &params.hdr.Struct;
384 	hdr_attr = reqhdr->PageType & MPI2_CONFIG_PAGEATTR_MASK;
385 	if (hdr_attr != MPI2_CONFIG_PAGEATTR_CHANGEABLE &&
386 	    hdr_attr != MPI2_CONFIG_PAGEATTR_PERSISTENT) {
387 		mps_printf(sc, "page type 0x%x not changeable\n",
388 			reqhdr->PageType & MPI2_CONFIG_PAGETYPE_MASK);
389 		return (EINVAL);
390 	}
391 
392 	/*
393 	 * There isn't any point in restoring stripped out attributes
394 	 * if you then mask them going down to issue the request.
395 	 */
396 
397 	hdr->PageVersion = reqhdr->PageVersion;
398 	hdr->PageLength = reqhdr->PageLength;
399 	hdr->PageNumber = reqhdr->PageNumber;
400 	hdr->PageType = reqhdr->PageType;
401 	params.action = MPI2_CONFIG_ACTION_PAGE_WRITE_CURRENT;
402 	params.page_address = le32toh(page_req->page_address);
403 	params.buffer = buf;
404 	params.length = le32toh(page_req->len);
405 	params.callback = NULL;
406 
407 	if ((error = mps_write_config_page(sc, &params)) != 0) {
408 		mps_printf(sc, "mps_write_cfg_page timed out\n");
409 		return (ETIMEDOUT);
410 	}
411 
412 	page_req->ioc_status = htole16(params.status);
413 	return (0);
414 }
415 
416 void
417 mpi_init_sge(struct mps_command *cm, void *req, void *sge)
418 {
419 	int off, space;
420 
421 	space = (int)cm->cm_sc->reqframesz;
422 	off = (uintptr_t)sge - (uintptr_t)req;
423 
424 	KASSERT(off < space, ("bad pointers %p %p, off %d, space %d",
425             req, sge, off, space));
426 
427 	cm->cm_sge = sge;
428 	cm->cm_sglsize = space - off;
429 }
430 
431 /*
432  * Prepare the mps_command for an IOC_FACTS request.
433  */
434 static int
435 mpi_pre_ioc_facts(struct mps_command *cm, struct mps_usr_command *cmd)
436 {
437 	MPI2_IOC_FACTS_REQUEST *req = (void *)cm->cm_req;
438 	MPI2_IOC_FACTS_REPLY *rpl;
439 
440 	if (cmd->req_len != sizeof *req)
441 		return (EINVAL);
442 	if (cmd->rpl_len != sizeof *rpl)
443 		return (EINVAL);
444 
445 	cm->cm_sge = NULL;
446 	cm->cm_sglsize = 0;
447 	return (0);
448 }
449 
450 /*
451  * Prepare the mps_command for a PORT_FACTS request.
452  */
453 static int
454 mpi_pre_port_facts(struct mps_command *cm, struct mps_usr_command *cmd)
455 {
456 	MPI2_PORT_FACTS_REQUEST *req = (void *)cm->cm_req;
457 	MPI2_PORT_FACTS_REPLY *rpl;
458 
459 	if (cmd->req_len != sizeof *req)
460 		return (EINVAL);
461 	if (cmd->rpl_len != sizeof *rpl)
462 		return (EINVAL);
463 
464 	cm->cm_sge = NULL;
465 	cm->cm_sglsize = 0;
466 	return (0);
467 }
468 
469 /*
470  * Prepare the mps_command for a FW_DOWNLOAD request.
471  */
472 static int
473 mpi_pre_fw_download(struct mps_command *cm, struct mps_usr_command *cmd)
474 {
475 	MPI2_FW_DOWNLOAD_REQUEST *req = (void *)cm->cm_req;
476 	MPI2_FW_DOWNLOAD_REPLY *rpl;
477 	MPI2_FW_DOWNLOAD_TCSGE tc;
478 	int error;
479 
480 	/*
481 	 * This code assumes there is room in the request's SGL for
482 	 * the TransactionContext plus at least a SGL chain element.
483 	 */
484 	CTASSERT(sizeof req->SGL >= sizeof tc + MPS_SGC_SIZE);
485 
486 	if (cmd->req_len != sizeof *req)
487 		return (EINVAL);
488 	if (cmd->rpl_len != sizeof *rpl)
489 		return (EINVAL);
490 
491 	if (cmd->len == 0)
492 		return (EINVAL);
493 
494 	error = copyin(cmd->buf, cm->cm_data, cmd->len);
495 	if (error != 0)
496 		return (error);
497 
498 	mpi_init_sge(cm, req, &req->SGL);
499 	bzero(&tc, sizeof tc);
500 
501 	/*
502 	 * For now, the F/W image must be provided in a single request.
503 	 */
504 	if ((req->MsgFlags & MPI2_FW_DOWNLOAD_MSGFLGS_LAST_SEGMENT) == 0)
505 		return (EINVAL);
506 	if (req->TotalImageSize != cmd->len)
507 		return (EINVAL);
508 
509 	/*
510 	 * The value of the first two elements is specified in the
511 	 * Fusion-MPT Message Passing Interface document.
512 	 */
513 	tc.ContextSize = 0;
514 	tc.DetailsLength = 12;
515 	tc.ImageOffset = 0;
516 	tc.ImageSize = cmd->len;
517 
518 	cm->cm_flags |= MPS_CM_FLAGS_DATAOUT;
519 
520 	return (mps_push_sge(cm, &tc, sizeof tc, 0));
521 }
522 
523 /*
524  * Prepare the mps_command for a FW_UPLOAD request.
525  */
526 static int
527 mpi_pre_fw_upload(struct mps_command *cm, struct mps_usr_command *cmd)
528 {
529 	MPI2_FW_UPLOAD_REQUEST *req = (void *)cm->cm_req;
530 	MPI2_FW_UPLOAD_REPLY *rpl;
531 	MPI2_FW_UPLOAD_TCSGE tc;
532 
533 	/*
534 	 * This code assumes there is room in the request's SGL for
535 	 * the TransactionContext plus at least a SGL chain element.
536 	 */
537 	CTASSERT(sizeof req->SGL >= sizeof tc + MPS_SGC_SIZE);
538 
539 	if (cmd->req_len != sizeof *req)
540 		return (EINVAL);
541 	if (cmd->rpl_len != sizeof *rpl)
542 		return (EINVAL);
543 
544 	mpi_init_sge(cm, req, &req->SGL);
545 	bzero(&tc, sizeof tc);
546 
547 	/*
548 	 * The value of the first two elements is specified in the
549 	 * Fusion-MPT Message Passing Interface document.
550 	 */
551 	tc.ContextSize = 0;
552 	tc.DetailsLength = 12;
553 	/*
554 	 * XXX Is there any reason to fetch a partial image?  I.e. to
555 	 * set ImageOffset to something other than 0?
556 	 */
557 	tc.ImageOffset = 0;
558 	tc.ImageSize = cmd->len;
559 
560 	cm->cm_flags |= MPS_CM_FLAGS_DATAIN;
561 
562 	return (mps_push_sge(cm, &tc, sizeof tc, 0));
563 }
564 
565 /*
566  * Prepare the mps_command for a SATA_PASSTHROUGH request.
567  */
568 static int
569 mpi_pre_sata_passthrough(struct mps_command *cm, struct mps_usr_command *cmd)
570 {
571 	MPI2_SATA_PASSTHROUGH_REQUEST *req = (void *)cm->cm_req;
572 	MPI2_SATA_PASSTHROUGH_REPLY *rpl;
573 
574 	if (cmd->req_len != sizeof *req)
575 		return (EINVAL);
576 	if (cmd->rpl_len != sizeof *rpl)
577 		return (EINVAL);
578 
579 	mpi_init_sge(cm, req, &req->SGL);
580 	return (0);
581 }
582 
583 /*
584  * Prepare the mps_command for a SMP_PASSTHROUGH request.
585  */
586 static int
587 mpi_pre_smp_passthrough(struct mps_command *cm, struct mps_usr_command *cmd)
588 {
589 	MPI2_SMP_PASSTHROUGH_REQUEST *req = (void *)cm->cm_req;
590 	MPI2_SMP_PASSTHROUGH_REPLY *rpl;
591 
592 	if (cmd->req_len != sizeof *req)
593 		return (EINVAL);
594 	if (cmd->rpl_len != sizeof *rpl)
595 		return (EINVAL);
596 
597 	mpi_init_sge(cm, req, &req->SGL);
598 	return (0);
599 }
600 
601 /*
602  * Prepare the mps_command for a CONFIG request.
603  */
604 static int
605 mpi_pre_config(struct mps_command *cm, struct mps_usr_command *cmd)
606 {
607 	MPI2_CONFIG_REQUEST *req = (void *)cm->cm_req;
608 	MPI2_CONFIG_REPLY *rpl;
609 
610 	if (cmd->req_len != sizeof *req)
611 		return (EINVAL);
612 	if (cmd->rpl_len != sizeof *rpl)
613 		return (EINVAL);
614 
615 	mpi_init_sge(cm, req, &req->PageBufferSGE);
616 	return (0);
617 }
618 
619 /*
620  * Prepare the mps_command for a SAS_IO_UNIT_CONTROL request.
621  */
622 static int
623 mpi_pre_sas_io_unit_control(struct mps_command *cm,
624 			     struct mps_usr_command *cmd)
625 {
626 
627 	cm->cm_sge = NULL;
628 	cm->cm_sglsize = 0;
629 	return (0);
630 }
631 
632 /*
633  * A set of functions to prepare an mps_command for the various
634  * supported requests.
635  */
636 struct mps_user_func {
637 	U8		Function;
638 	mps_user_f	*f_pre;
639 } mps_user_func_list[] = {
640 	{ MPI2_FUNCTION_IOC_FACTS,		mpi_pre_ioc_facts },
641 	{ MPI2_FUNCTION_PORT_FACTS,		mpi_pre_port_facts },
642 	{ MPI2_FUNCTION_FW_DOWNLOAD, 		mpi_pre_fw_download },
643 	{ MPI2_FUNCTION_FW_UPLOAD,		mpi_pre_fw_upload },
644 	{ MPI2_FUNCTION_SATA_PASSTHROUGH,	mpi_pre_sata_passthrough },
645 	{ MPI2_FUNCTION_SMP_PASSTHROUGH,	mpi_pre_smp_passthrough},
646 	{ MPI2_FUNCTION_CONFIG,			mpi_pre_config},
647 	{ MPI2_FUNCTION_SAS_IO_UNIT_CONTROL,	mpi_pre_sas_io_unit_control },
648 	{ 0xFF,					NULL } /* list end */
649 };
650 
651 static int
652 mps_user_setup_request(struct mps_command *cm, struct mps_usr_command *cmd)
653 {
654 	MPI2_REQUEST_HEADER *hdr = (MPI2_REQUEST_HEADER *)cm->cm_req;
655 	struct mps_user_func *f;
656 
657 	for (f = mps_user_func_list; f->f_pre != NULL; f++) {
658 		if (hdr->Function == f->Function)
659 			return (f->f_pre(cm, cmd));
660 	}
661 	return (EINVAL);
662 }
663 
664 static int
665 mps_user_command(struct mps_softc *sc, struct mps_usr_command *cmd)
666 {
667 	MPI2_REQUEST_HEADER *hdr;
668 	MPI2_DEFAULT_REPLY *rpl;
669 	void *buf = NULL;
670 	struct mps_command *cm = NULL;
671 	int err = 0;
672 	int sz;
673 
674 	mps_lock(sc);
675 	cm = mps_alloc_command(sc);
676 
677 	if (cm == NULL) {
678 		mps_printf(sc, "%s: no mps requests\n", __func__);
679 		err = ENOMEM;
680 		goto RetFree;
681 	}
682 	mps_unlock(sc);
683 
684 	hdr = (MPI2_REQUEST_HEADER *)cm->cm_req;
685 
686 	mps_dprint(sc, MPS_USER, "%s: req %p %d  rpl %p %d\n", __func__,
687 	    cmd->req, cmd->req_len, cmd->rpl, cmd->rpl_len);
688 
689 	if (cmd->req_len > (int)sc->reqframesz) {
690 		err = EINVAL;
691 		goto RetFreeUnlocked;
692 	}
693 	err = copyin(cmd->req, hdr, cmd->req_len);
694 	if (err != 0)
695 		goto RetFreeUnlocked;
696 
697 	mps_dprint(sc, MPS_USER, "%s: Function %02X MsgFlags %02X\n", __func__,
698 	    hdr->Function, hdr->MsgFlags);
699 
700 	if (cmd->len > 0) {
701 		buf = malloc(cmd->len, M_MPSUSER, M_WAITOK|M_ZERO);
702 		cm->cm_data = buf;
703 		cm->cm_length = cmd->len;
704 	} else {
705 		cm->cm_data = NULL;
706 		cm->cm_length = 0;
707 	}
708 
709 	cm->cm_flags = MPS_CM_FLAGS_SGE_SIMPLE;
710 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
711 
712 	err = mps_user_setup_request(cm, cmd);
713 	if (err == EINVAL) {
714 		mps_printf(sc, "%s: unsupported parameter or unsupported "
715 		    "function in request (function = 0x%X)\n", __func__,
716 		    hdr->Function);
717 	}
718 	if (err != 0)
719 		goto RetFreeUnlocked;
720 
721 	mps_lock(sc);
722 	err = mps_wait_command(sc, &cm, 60, CAN_SLEEP);
723 
724 	if (err || (cm == NULL)) {
725 		mps_printf(sc, "%s: invalid request: error %d\n",
726 		    __func__, err);
727 		goto RetFree;
728 	}
729 
730 	rpl = (MPI2_DEFAULT_REPLY *)cm->cm_reply;
731 	if (rpl != NULL)
732 		sz = rpl->MsgLength * 4;
733 	else
734 		sz = 0;
735 
736 	if (sz > cmd->rpl_len) {
737 		mps_printf(sc, "%s: user reply buffer (%d) smaller than "
738 		    "returned buffer (%d)\n", __func__, cmd->rpl_len, sz);
739 		sz = cmd->rpl_len;
740 	}
741 
742 	mps_unlock(sc);
743 	copyout(rpl, cmd->rpl, sz);
744 	if (buf != NULL)
745 		copyout(buf, cmd->buf, cmd->len);
746 	mps_dprint(sc, MPS_USER, "%s: reply size %d\n", __func__, sz);
747 
748 RetFreeUnlocked:
749 	mps_lock(sc);
750 RetFree:
751 	if (cm != NULL)
752 		mps_free_command(sc, cm);
753 	mps_unlock(sc);
754 	if (buf != NULL)
755 		free(buf, M_MPSUSER);
756 	return (err);
757 }
758 
759 static int
760 mps_user_pass_thru(struct mps_softc *sc, mps_pass_thru_t *data)
761 {
762 	MPI2_REQUEST_HEADER	*hdr, tmphdr;
763 	MPI2_DEFAULT_REPLY	*rpl = NULL;
764 	struct mps_command	*cm = NULL;
765 	int			err = 0, dir = 0, sz;
766 	uint8_t			function = 0;
767 	u_int			sense_len;
768 	struct mpssas_target	*targ = NULL;
769 
770 	/*
771 	 * Only allow one passthru command at a time.  Use the MPS_FLAGS_BUSY
772 	 * bit to denote that a passthru is being processed.
773 	 */
774 	mps_lock(sc);
775 	if (sc->mps_flags & MPS_FLAGS_BUSY) {
776 		mps_dprint(sc, MPS_USER, "%s: Only one passthru command "
777 		    "allowed at a single time.", __func__);
778 		mps_unlock(sc);
779 		return (EBUSY);
780 	}
781 	sc->mps_flags |= MPS_FLAGS_BUSY;
782 	mps_unlock(sc);
783 
784 	/*
785 	 * Do some validation on data direction.  Valid cases are:
786 	 *    1) DataSize is 0 and direction is NONE
787 	 *    2) DataSize is non-zero and one of:
788 	 *        a) direction is READ or
789 	 *        b) direction is WRITE or
790 	 *        c) direction is BOTH and DataOutSize is non-zero
791 	 * If valid and the direction is BOTH, change the direction to READ.
792 	 * if valid and the direction is not BOTH, make sure DataOutSize is 0.
793 	 */
794 	if (((data->DataSize == 0) &&
795 	    (data->DataDirection == MPS_PASS_THRU_DIRECTION_NONE)) ||
796 	    ((data->DataSize != 0) &&
797 	    ((data->DataDirection == MPS_PASS_THRU_DIRECTION_READ) ||
798 	    (data->DataDirection == MPS_PASS_THRU_DIRECTION_WRITE) ||
799 	    ((data->DataDirection == MPS_PASS_THRU_DIRECTION_BOTH) &&
800 	    (data->DataOutSize != 0))))) {
801 		if (data->DataDirection == MPS_PASS_THRU_DIRECTION_BOTH)
802 			data->DataDirection = MPS_PASS_THRU_DIRECTION_READ;
803 		else
804 			data->DataOutSize = 0;
805 	} else
806 		return (EINVAL);
807 
808 	mps_dprint(sc, MPS_USER, "%s: req 0x%jx %d  rpl 0x%jx %d "
809 	    "data in 0x%jx %d data out 0x%jx %d data dir %d\n", __func__,
810 	    data->PtrRequest, data->RequestSize, data->PtrReply,
811 	    data->ReplySize, data->PtrData, data->DataSize,
812 	    data->PtrDataOut, data->DataOutSize, data->DataDirection);
813 
814 	/*
815 	 * copy in the header so we know what we're dealing with before we
816 	 * commit to allocating a command for it.
817 	 */
818 	err = copyin(PTRIN(data->PtrRequest), &tmphdr, data->RequestSize);
819 	if (err != 0)
820 		goto RetFreeUnlocked;
821 
822 	if (data->RequestSize > (int)sc->reqframesz) {
823 		err = EINVAL;
824 		goto RetFreeUnlocked;
825 	}
826 
827 	function = tmphdr.Function;
828 	mps_dprint(sc, MPS_USER, "%s: Function %02X MsgFlags %02X\n", __func__,
829 	    function, tmphdr.MsgFlags);
830 
831 	/*
832 	 * Handle a passthru TM request.
833 	 */
834 	if (function == MPI2_FUNCTION_SCSI_TASK_MGMT) {
835 		MPI2_SCSI_TASK_MANAGE_REQUEST	*task;
836 
837 		mps_lock(sc);
838 		cm = mpssas_alloc_tm(sc);
839 		if (cm == NULL) {
840 			err = EINVAL;
841 			goto Ret;
842 		}
843 
844 		/* Copy the header in.  Only a small fixup is needed. */
845 		task = (MPI2_SCSI_TASK_MANAGE_REQUEST *)cm->cm_req;
846 		bcopy(&tmphdr, task, data->RequestSize);
847 		task->TaskMID = cm->cm_desc.Default.SMID;
848 
849 		cm->cm_data = NULL;
850 		cm->cm_complete = NULL;
851 		cm->cm_complete_data = NULL;
852 
853 		targ = mpssas_find_target_by_handle(sc->sassc, 0,
854 		    task->DevHandle);
855 		if (targ == NULL) {
856 			mps_dprint(sc, MPS_INFO,
857 			   "%s %d : invalid handle for requested TM 0x%x \n",
858 			   __func__, __LINE__, task->DevHandle);
859 			err = 1;
860 		} else {
861 			mpssas_prepare_for_tm(sc, cm, targ, CAM_LUN_WILDCARD);
862 			err = mps_wait_command(sc, &cm, 30, CAN_SLEEP);
863 		}
864 
865 		if (err != 0) {
866 			err = EIO;
867 			mps_dprint(sc, MPS_FAULT, "%s: task management failed",
868 			    __func__);
869 		}
870 		/*
871 		 * Copy the reply data and sense data to user space.
872 		 */
873 		if ((cm != NULL) && (cm->cm_reply != NULL)) {
874 			rpl = (MPI2_DEFAULT_REPLY *)cm->cm_reply;
875 			sz = rpl->MsgLength * 4;
876 
877 			if (sz > data->ReplySize) {
878 				mps_printf(sc, "%s: user reply buffer (%d) "
879 				    "smaller than returned buffer (%d)\n",
880 				    __func__, data->ReplySize, sz);
881 			}
882 			mps_unlock(sc);
883 			copyout(cm->cm_reply, PTRIN(data->PtrReply),
884 			    data->ReplySize);
885 			mps_lock(sc);
886 		}
887 		mpssas_free_tm(sc, cm);
888 		goto Ret;
889 	}
890 
891 	mps_lock(sc);
892 	cm = mps_alloc_command(sc);
893 
894 	if (cm == NULL) {
895 		mps_printf(sc, "%s: no mps requests\n", __func__);
896 		err = ENOMEM;
897 		goto Ret;
898 	}
899 	mps_unlock(sc);
900 
901 	hdr = (MPI2_REQUEST_HEADER *)cm->cm_req;
902 	bcopy(&tmphdr, hdr, data->RequestSize);
903 
904 	/*
905 	 * Do some checking to make sure the IOCTL request contains a valid
906 	 * request.  Then set the SGL info.
907 	 */
908 	mpi_init_sge(cm, hdr, (void *)((uint8_t *)hdr + data->RequestSize));
909 
910 	/*
911 	 * Set up for read, write or both.  From check above, DataOutSize will
912 	 * be 0 if direction is READ or WRITE, but it will have some non-zero
913 	 * value if the direction is BOTH.  So, just use the biggest size to get
914 	 * the cm_data buffer size.  If direction is BOTH, 2 SGLs need to be set
915 	 * up; the first is for the request and the second will contain the
916 	 * response data. cm_out_len needs to be set here and this will be used
917 	 * when the SGLs are set up.
918 	 */
919 	cm->cm_data = NULL;
920 	cm->cm_length = MAX(data->DataSize, data->DataOutSize);
921 	cm->cm_out_len = data->DataOutSize;
922 	cm->cm_flags = 0;
923 	if (cm->cm_length != 0) {
924 		cm->cm_data = malloc(cm->cm_length, M_MPSUSER, M_WAITOK |
925 		    M_ZERO);
926 		cm->cm_flags = MPS_CM_FLAGS_DATAIN;
927 		if (data->DataOutSize) {
928 			cm->cm_flags |= MPS_CM_FLAGS_DATAOUT;
929 			err = copyin(PTRIN(data->PtrDataOut),
930 			    cm->cm_data, data->DataOutSize);
931 		} else if (data->DataDirection ==
932 		    MPS_PASS_THRU_DIRECTION_WRITE) {
933 			cm->cm_flags = MPS_CM_FLAGS_DATAOUT;
934 			err = copyin(PTRIN(data->PtrData),
935 			    cm->cm_data, data->DataSize);
936 		}
937 		if (err != 0)
938 			mps_dprint(sc, MPS_FAULT, "%s: failed to copy "
939 			    "IOCTL data from user space\n", __func__);
940 	}
941 	cm->cm_flags |= MPS_CM_FLAGS_SGE_SIMPLE;
942 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
943 
944 	/*
945 	 * Set up Sense buffer and SGL offset for IO passthru.  SCSI IO request
946 	 * uses SCSI IO descriptor.
947 	 */
948 	if ((function == MPI2_FUNCTION_SCSI_IO_REQUEST) ||
949 	    (function == MPI2_FUNCTION_RAID_SCSI_IO_PASSTHROUGH)) {
950 		MPI2_SCSI_IO_REQUEST	*scsi_io_req;
951 
952 		scsi_io_req = (MPI2_SCSI_IO_REQUEST *)hdr;
953 		/*
954 		 * Put SGE for data and data_out buffer at the end of
955 		 * scsi_io_request message header (64 bytes in total).
956 		 * Following above SGEs, the residual space will be used by
957 		 * sense data.
958 		 */
959 		scsi_io_req->SenseBufferLength = (uint8_t)(data->RequestSize -
960 		    64);
961 		scsi_io_req->SenseBufferLowAddress = htole32(cm->cm_sense_busaddr);
962 
963 		/*
964 		 * Set SGLOffset0 value.  This is the number of dwords that SGL
965 		 * is offset from the beginning of MPI2_SCSI_IO_REQUEST struct.
966 		 */
967 		scsi_io_req->SGLOffset0 = 24;
968 
969 		/*
970 		 * Setup descriptor info.  RAID passthrough must use the
971 		 * default request descriptor which is already set, so if this
972 		 * is a SCSI IO request, change the descriptor to SCSI IO.
973 		 * Also, if this is a SCSI IO request, handle the reply in the
974 		 * mpssas_scsio_complete function.
975 		 */
976 		if (function == MPI2_FUNCTION_SCSI_IO_REQUEST) {
977 			cm->cm_desc.SCSIIO.RequestFlags =
978 			    MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO;
979 			cm->cm_desc.SCSIIO.DevHandle = scsi_io_req->DevHandle;
980 
981 			/*
982 			 * Make sure the DevHandle is not 0 because this is a
983 			 * likely error.
984 			 */
985 			if (scsi_io_req->DevHandle == 0) {
986 				err = EINVAL;
987 				goto RetFreeUnlocked;
988 			}
989 		}
990 	}
991 
992 	mps_lock(sc);
993 
994 	err = mps_wait_command(sc, &cm, 30, CAN_SLEEP);
995 
996 	if (err || (cm == NULL)) {
997 		mps_printf(sc, "%s: invalid request: error %d\n", __func__,
998 		    err);
999 		mps_unlock(sc);
1000 		goto RetFreeUnlocked;
1001 	}
1002 
1003 	/*
1004 	 * Sync the DMA data, if any.  Then copy the data to user space.
1005 	 */
1006 	if (cm->cm_data != NULL) {
1007 		if (cm->cm_flags & MPS_CM_FLAGS_DATAIN)
1008 			dir = BUS_DMASYNC_POSTREAD;
1009 		else if (cm->cm_flags & MPS_CM_FLAGS_DATAOUT)
1010 			dir = BUS_DMASYNC_POSTWRITE;
1011 		bus_dmamap_sync(sc->buffer_dmat, cm->cm_dmamap, dir);
1012 		bus_dmamap_unload(sc->buffer_dmat, cm->cm_dmamap);
1013 
1014 		if (cm->cm_flags & MPS_CM_FLAGS_DATAIN) {
1015 			mps_unlock(sc);
1016 			err = copyout(cm->cm_data,
1017 			    PTRIN(data->PtrData), data->DataSize);
1018 			mps_lock(sc);
1019 			if (err != 0)
1020 				mps_dprint(sc, MPS_FAULT, "%s: failed to copy "
1021 				    "IOCTL data to user space\n", __func__);
1022 		}
1023 	}
1024 
1025 	/*
1026 	 * Copy the reply data and sense data to user space.
1027 	 */
1028 	if (cm->cm_reply != NULL) {
1029 		rpl = (MPI2_DEFAULT_REPLY *)cm->cm_reply;
1030 		sz = rpl->MsgLength * 4;
1031 
1032 		if (sz > data->ReplySize) {
1033 			mps_printf(sc, "%s: user reply buffer (%d) smaller "
1034 			    "than returned buffer (%d)\n", __func__,
1035 			    data->ReplySize, sz);
1036 		}
1037 		mps_unlock(sc);
1038 		copyout(cm->cm_reply, PTRIN(data->PtrReply), data->ReplySize);
1039 		mps_lock(sc);
1040 
1041 		if ((function == MPI2_FUNCTION_SCSI_IO_REQUEST) ||
1042 		    (function == MPI2_FUNCTION_RAID_SCSI_IO_PASSTHROUGH)) {
1043 			if (((MPI2_SCSI_IO_REPLY *)rpl)->SCSIState &
1044 			    MPI2_SCSI_STATE_AUTOSENSE_VALID) {
1045 				sense_len =
1046 				    MIN((le32toh(((MPI2_SCSI_IO_REPLY *)rpl)->SenseCount)),
1047 				    sizeof(struct scsi_sense_data));
1048 				mps_unlock(sc);
1049 				copyout(cm->cm_sense, cm->cm_req + 64, sense_len);
1050 				mps_lock(sc);
1051 			}
1052 		}
1053 	}
1054 	mps_unlock(sc);
1055 
1056 RetFreeUnlocked:
1057 	mps_lock(sc);
1058 
1059 	if (cm != NULL) {
1060 		if (cm->cm_data)
1061 			free(cm->cm_data, M_MPSUSER);
1062 		mps_free_command(sc, cm);
1063 	}
1064 Ret:
1065 	sc->mps_flags &= ~MPS_FLAGS_BUSY;
1066 	mps_unlock(sc);
1067 
1068 	return (err);
1069 }
1070 
1071 static void
1072 mps_user_get_adapter_data(struct mps_softc *sc, mps_adapter_data_t *data)
1073 {
1074 	Mpi2ConfigReply_t	mpi_reply;
1075 	Mpi2BiosPage3_t		config_page;
1076 
1077 	/*
1078 	 * Use the PCI interface functions to get the Bus, Device, and Function
1079 	 * information.
1080 	 */
1081 	data->PciInformation.u.bits.BusNumber = pci_get_bus(sc->mps_dev);
1082 	data->PciInformation.u.bits.DeviceNumber = pci_get_slot(sc->mps_dev);
1083 	data->PciInformation.u.bits.FunctionNumber =
1084 	    pci_get_function(sc->mps_dev);
1085 
1086 	/*
1087 	 * Get the FW version that should already be saved in IOC Facts.
1088 	 */
1089 	data->MpiFirmwareVersion = sc->facts->FWVersion.Word;
1090 
1091 	/*
1092 	 * General device info.
1093 	 */
1094 	data->AdapterType = MPSIOCTL_ADAPTER_TYPE_SAS2;
1095 	if (sc->mps_flags & MPS_FLAGS_WD_AVAILABLE)
1096 		data->AdapterType = MPSIOCTL_ADAPTER_TYPE_SAS2_SSS6200;
1097 	data->PCIDeviceHwId = pci_get_device(sc->mps_dev);
1098 	data->PCIDeviceHwRev = pci_read_config(sc->mps_dev, PCIR_REVID, 1);
1099 	data->SubSystemId = pci_get_subdevice(sc->mps_dev);
1100 	data->SubsystemVendorId = pci_get_subvendor(sc->mps_dev);
1101 
1102 	/*
1103 	 * Get the driver version.
1104 	 */
1105 	strcpy((char *)&data->DriverVersion[0], MPS_DRIVER_VERSION);
1106 
1107 	/*
1108 	 * Need to get BIOS Config Page 3 for the BIOS Version.
1109 	 */
1110 	data->BiosVersion = 0;
1111 	mps_lock(sc);
1112 	if (mps_config_get_bios_pg3(sc, &mpi_reply, &config_page))
1113 		printf("%s: Error while retrieving BIOS Version\n", __func__);
1114 	else
1115 		data->BiosVersion = config_page.BiosVersion;
1116 	mps_unlock(sc);
1117 }
1118 
1119 static void
1120 mps_user_read_pci_info(struct mps_softc *sc, mps_pci_info_t *data)
1121 {
1122 	int	i;
1123 
1124 	/*
1125 	 * Use the PCI interface functions to get the Bus, Device, and Function
1126 	 * information.
1127 	 */
1128 	data->BusNumber = pci_get_bus(sc->mps_dev);
1129 	data->DeviceNumber = pci_get_slot(sc->mps_dev);
1130 	data->FunctionNumber = pci_get_function(sc->mps_dev);
1131 
1132 	/*
1133 	 * Now get the interrupt vector and the pci header.  The vector can
1134 	 * only be 0 right now.  The header is the first 256 bytes of config
1135 	 * space.
1136 	 */
1137 	data->InterruptVector = 0;
1138 	for (i = 0; i < sizeof (data->PciHeader); i++) {
1139 		data->PciHeader[i] = pci_read_config(sc->mps_dev, i, 1);
1140 	}
1141 }
1142 
1143 static uint8_t
1144 mps_get_fw_diag_buffer_number(struct mps_softc *sc, uint32_t unique_id)
1145 {
1146 	uint8_t	index;
1147 
1148 	for (index = 0; index < MPI2_DIAG_BUF_TYPE_COUNT; index++) {
1149 		if (sc->fw_diag_buffer_list[index].unique_id == unique_id) {
1150 			return (index);
1151 		}
1152 	}
1153 
1154 	return (MPS_FW_DIAGNOSTIC_UID_NOT_FOUND);
1155 }
1156 
1157 static int
1158 mps_post_fw_diag_buffer(struct mps_softc *sc,
1159     mps_fw_diagnostic_buffer_t *pBuffer, uint32_t *return_code)
1160 {
1161 	MPI2_DIAG_BUFFER_POST_REQUEST	*req;
1162 	MPI2_DIAG_BUFFER_POST_REPLY	*reply = NULL;
1163 	struct mps_command		*cm = NULL;
1164 	int				i, status;
1165 
1166 	/*
1167 	 * If buffer is not enabled, just leave.
1168 	 */
1169 	*return_code = MPS_FW_DIAG_ERROR_POST_FAILED;
1170 	if (!pBuffer->enabled) {
1171 		return (MPS_DIAG_FAILURE);
1172 	}
1173 
1174 	/*
1175 	 * Clear some flags initially.
1176 	 */
1177 	pBuffer->force_release = FALSE;
1178 	pBuffer->valid_data = FALSE;
1179 	pBuffer->owned_by_firmware = FALSE;
1180 
1181 	/*
1182 	 * Get a command.
1183 	 */
1184 	cm = mps_alloc_command(sc);
1185 	if (cm == NULL) {
1186 		mps_printf(sc, "%s: no mps requests\n", __func__);
1187 		return (MPS_DIAG_FAILURE);
1188 	}
1189 
1190 	/*
1191 	 * Build the request for releasing the FW Diag Buffer and send it.
1192 	 */
1193 	req = (MPI2_DIAG_BUFFER_POST_REQUEST *)cm->cm_req;
1194 	req->Function = MPI2_FUNCTION_DIAG_BUFFER_POST;
1195 	req->BufferType = pBuffer->buffer_type;
1196 	req->ExtendedType = pBuffer->extended_type;
1197 	req->BufferLength = pBuffer->size;
1198 	for (i = 0; i < (sizeof(req->ProductSpecific) / 4); i++)
1199 		req->ProductSpecific[i] = pBuffer->product_specific[i];
1200 	mps_from_u64(sc->fw_diag_busaddr, &req->BufferAddress);
1201 	cm->cm_data = NULL;
1202 	cm->cm_length = 0;
1203 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
1204 	cm->cm_complete_data = NULL;
1205 
1206 	/*
1207 	 * Send command synchronously.
1208 	 */
1209 	status = mps_wait_command(sc, &cm, 30, CAN_SLEEP);
1210 	if (status || (cm == NULL)) {
1211 		mps_printf(sc, "%s: invalid request: error %d\n", __func__,
1212 		    status);
1213 		status = MPS_DIAG_FAILURE;
1214 		goto done;
1215 	}
1216 
1217 	/*
1218 	 * Process POST reply.
1219 	 */
1220 	reply = (MPI2_DIAG_BUFFER_POST_REPLY *)cm->cm_reply;
1221 	if (reply == NULL) {
1222 		mps_printf(sc, "%s: reply is NULL, probably due to "
1223 		    "reinitialization\n", __func__);
1224 		status = MPS_DIAG_FAILURE;
1225 		goto done;
1226 	}
1227 	if ((le16toh(reply->IOCStatus) & MPI2_IOCSTATUS_MASK) !=
1228 	    MPI2_IOCSTATUS_SUCCESS) {
1229 		status = MPS_DIAG_FAILURE;
1230 		mps_dprint(sc, MPS_FAULT, "%s: post of FW  Diag Buffer failed "
1231 		    "with IOCStatus = 0x%x, IOCLogInfo = 0x%x and "
1232 		    "TransferLength = 0x%x\n", __func__,
1233 		    le16toh(reply->IOCStatus), le32toh(reply->IOCLogInfo),
1234 		    le32toh(reply->TransferLength));
1235 		goto done;
1236 	}
1237 
1238 	/*
1239 	 * Post was successful.
1240 	 */
1241 	pBuffer->valid_data = TRUE;
1242 	pBuffer->owned_by_firmware = TRUE;
1243 	*return_code = MPS_FW_DIAG_ERROR_SUCCESS;
1244 	status = MPS_DIAG_SUCCESS;
1245 
1246 done:
1247 	if (cm != NULL)
1248 		mps_free_command(sc, cm);
1249 	return (status);
1250 }
1251 
1252 static int
1253 mps_release_fw_diag_buffer(struct mps_softc *sc,
1254     mps_fw_diagnostic_buffer_t *pBuffer, uint32_t *return_code,
1255     uint32_t diag_type)
1256 {
1257 	MPI2_DIAG_RELEASE_REQUEST	*req;
1258 	MPI2_DIAG_RELEASE_REPLY		*reply = NULL;
1259 	struct mps_command		*cm = NULL;
1260 	int				status;
1261 
1262 	/*
1263 	 * If buffer is not enabled, just leave.
1264 	 */
1265 	*return_code = MPS_FW_DIAG_ERROR_RELEASE_FAILED;
1266 	if (!pBuffer->enabled) {
1267 		mps_dprint(sc, MPS_USER, "%s: This buffer type is not "
1268 		    "supported by the IOC", __func__);
1269 		return (MPS_DIAG_FAILURE);
1270 	}
1271 
1272 	/*
1273 	 * Clear some flags initially.
1274 	 */
1275 	pBuffer->force_release = FALSE;
1276 	pBuffer->valid_data = FALSE;
1277 	pBuffer->owned_by_firmware = FALSE;
1278 
1279 	/*
1280 	 * Get a command.
1281 	 */
1282 	cm = mps_alloc_command(sc);
1283 	if (cm == NULL) {
1284 		mps_printf(sc, "%s: no mps requests\n", __func__);
1285 		return (MPS_DIAG_FAILURE);
1286 	}
1287 
1288 	/*
1289 	 * Build the request for releasing the FW Diag Buffer and send it.
1290 	 */
1291 	req = (MPI2_DIAG_RELEASE_REQUEST *)cm->cm_req;
1292 	req->Function = MPI2_FUNCTION_DIAG_RELEASE;
1293 	req->BufferType = pBuffer->buffer_type;
1294 	cm->cm_data = NULL;
1295 	cm->cm_length = 0;
1296 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
1297 	cm->cm_complete_data = NULL;
1298 
1299 	/*
1300 	 * Send command synchronously.
1301 	 */
1302 	status = mps_wait_command(sc, &cm, 30, CAN_SLEEP);
1303 	if (status || (cm == NULL)) {
1304 		mps_printf(sc, "%s: invalid request: error %d\n", __func__,
1305 		    status);
1306 		status = MPS_DIAG_FAILURE;
1307 		goto done;
1308 	}
1309 
1310 	/*
1311 	 * Process RELEASE reply.
1312 	 */
1313 	reply = (MPI2_DIAG_RELEASE_REPLY *)cm->cm_reply;
1314 	if (reply == NULL) {
1315 		mps_printf(sc, "%s: reply is NULL, probably due to "
1316 		    "reinitialization\n", __func__);
1317 		status = MPS_DIAG_FAILURE;
1318 		goto done;
1319 	}
1320 	if (((le16toh(reply->IOCStatus) & MPI2_IOCSTATUS_MASK) !=
1321 	    MPI2_IOCSTATUS_SUCCESS) || pBuffer->owned_by_firmware) {
1322 		status = MPS_DIAG_FAILURE;
1323 		mps_dprint(sc, MPS_FAULT, "%s: release of FW Diag Buffer "
1324 		    "failed with IOCStatus = 0x%x and IOCLogInfo = 0x%x\n",
1325 		    __func__, le16toh(reply->IOCStatus),
1326 		    le32toh(reply->IOCLogInfo));
1327 		goto done;
1328 	}
1329 
1330 	/*
1331 	 * Release was successful.
1332 	 */
1333 	*return_code = MPS_FW_DIAG_ERROR_SUCCESS;
1334 	status = MPS_DIAG_SUCCESS;
1335 
1336 	/*
1337 	 * If this was for an UNREGISTER diag type command, clear the unique ID.
1338 	 */
1339 	if (diag_type == MPS_FW_DIAG_TYPE_UNREGISTER) {
1340 		pBuffer->unique_id = MPS_FW_DIAG_INVALID_UID;
1341 	}
1342 
1343 done:
1344 	if (cm != NULL)
1345 		mps_free_command(sc, cm);
1346 
1347 	return (status);
1348 }
1349 
1350 static int
1351 mps_diag_register(struct mps_softc *sc, mps_fw_diag_register_t *diag_register,
1352     uint32_t *return_code)
1353 {
1354 	mps_fw_diagnostic_buffer_t	*pBuffer;
1355 	struct mps_busdma_context	*ctx;
1356 	uint8_t				extended_type, buffer_type, i;
1357 	uint32_t			buffer_size;
1358 	uint32_t			unique_id;
1359 	int				status;
1360 	int				error;
1361 
1362 	extended_type = diag_register->ExtendedType;
1363 	buffer_type = diag_register->BufferType;
1364 	buffer_size = diag_register->RequestedBufferSize;
1365 	unique_id = diag_register->UniqueId;
1366 	ctx = NULL;
1367 	error = 0;
1368 
1369 	/*
1370 	 * Check for valid buffer type
1371 	 */
1372 	if (buffer_type >= MPI2_DIAG_BUF_TYPE_COUNT) {
1373 		*return_code = MPS_FW_DIAG_ERROR_INVALID_PARAMETER;
1374 		return (MPS_DIAG_FAILURE);
1375 	}
1376 
1377 	/*
1378 	 * Get the current buffer and look up the unique ID.  The unique ID
1379 	 * should not be found.  If it is, the ID is already in use.
1380 	 */
1381 	i = mps_get_fw_diag_buffer_number(sc, unique_id);
1382 	pBuffer = &sc->fw_diag_buffer_list[buffer_type];
1383 	if (i != MPS_FW_DIAGNOSTIC_UID_NOT_FOUND) {
1384 		*return_code = MPS_FW_DIAG_ERROR_INVALID_UID;
1385 		return (MPS_DIAG_FAILURE);
1386 	}
1387 
1388 	/*
1389 	 * The buffer's unique ID should not be registered yet, and the given
1390 	 * unique ID cannot be 0.
1391 	 */
1392 	if ((pBuffer->unique_id != MPS_FW_DIAG_INVALID_UID) ||
1393 	    (unique_id == MPS_FW_DIAG_INVALID_UID)) {
1394 		*return_code = MPS_FW_DIAG_ERROR_INVALID_UID;
1395 		return (MPS_DIAG_FAILURE);
1396 	}
1397 
1398 	/*
1399 	 * If this buffer is already posted as immediate, just change owner.
1400 	 */
1401 	if (pBuffer->immediate && pBuffer->owned_by_firmware &&
1402 	    (pBuffer->unique_id == MPS_FW_DIAG_INVALID_UID)) {
1403 		pBuffer->immediate = FALSE;
1404 		pBuffer->unique_id = unique_id;
1405 		return (MPS_DIAG_SUCCESS);
1406 	}
1407 
1408 	/*
1409 	 * Post a new buffer after checking if it's enabled.  The DMA buffer
1410 	 * that is allocated will be contiguous (nsegments = 1).
1411 	 */
1412 	if (!pBuffer->enabled) {
1413 		*return_code = MPS_FW_DIAG_ERROR_NO_BUFFER;
1414 		return (MPS_DIAG_FAILURE);
1415 	}
1416 	if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
1417 				1, 0,			/* algnmnt, boundary */
1418 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1419 				BUS_SPACE_MAXADDR,	/* highaddr */
1420 				NULL, NULL,		/* filter, filterarg */
1421                                 buffer_size,		/* maxsize */
1422                                 1,			/* nsegments */
1423                                 buffer_size,		/* maxsegsize */
1424                                 0,			/* flags */
1425                                 NULL, NULL,		/* lockfunc, lockarg */
1426                                 &sc->fw_diag_dmat)) {
1427 		mps_dprint(sc, MPS_ERROR,
1428 		    "Cannot allocate FW diag buffer DMA tag\n");
1429 		*return_code = MPS_FW_DIAG_ERROR_NO_BUFFER;
1430 		status = MPS_DIAG_FAILURE;
1431 		goto bailout;
1432 	}
1433 	if (bus_dmamem_alloc(sc->fw_diag_dmat, (void **)&sc->fw_diag_buffer,
1434 	    BUS_DMA_NOWAIT, &sc->fw_diag_map)) {
1435 		mps_dprint(sc, MPS_ERROR,
1436 		    "Cannot allocate FW diag buffer memory\n");
1437 		*return_code = MPS_FW_DIAG_ERROR_NO_BUFFER;
1438 		status = MPS_DIAG_FAILURE;
1439 		goto bailout;
1440         }
1441         bzero(sc->fw_diag_buffer, buffer_size);
1442 
1443 	ctx = malloc(sizeof(*ctx), M_MPSUSER, M_WAITOK | M_ZERO);
1444 	if (ctx == NULL) {
1445 		device_printf(sc->mps_dev, "%s: context malloc failed\n",
1446 		    __func__);
1447 		*return_code = MPS_FW_DIAG_ERROR_NO_BUFFER;
1448 		status = MPS_DIAG_FAILURE;
1449 		goto bailout;
1450 	}
1451 	ctx->addr = &sc->fw_diag_busaddr;
1452 	ctx->buffer_dmat = sc->fw_diag_dmat;
1453 	ctx->buffer_dmamap = sc->fw_diag_map;
1454 	ctx->softc = sc;
1455         error = bus_dmamap_load(sc->fw_diag_dmat, sc->fw_diag_map,
1456 	    sc->fw_diag_buffer, buffer_size, mps_memaddr_wait_cb,
1457 	    ctx, 0);
1458 
1459 	if (error == EINPROGRESS) {
1460 
1461 		/* XXX KDM */
1462 		device_printf(sc->mps_dev, "%s: Deferred bus_dmamap_load\n",
1463 		    __func__);
1464 		/*
1465 		 * Wait for the load to complete.  If we're interrupted,
1466 		 * bail out.
1467 		 */
1468 		mps_lock(sc);
1469 		if (ctx->completed == 0) {
1470 			error = msleep(ctx, &sc->mps_mtx, PCATCH, "mpswait", 0);
1471 			if (error != 0) {
1472 				/*
1473 				 * We got an error from msleep(9).  This is
1474 				 * most likely due to a signal.  Tell
1475 				 * mpr_memaddr_wait_cb() that we've abandoned
1476 				 * the context, so it needs to clean up when
1477 				 * it is called.
1478 				 */
1479 				ctx->abandoned = 1;
1480 
1481 				/* The callback will free this memory */
1482 				ctx = NULL;
1483 				mps_unlock(sc);
1484 
1485 				device_printf(sc->mps_dev, "Cannot "
1486 				    "bus_dmamap_load FW diag buffer, error = "
1487 				    "%d returned from msleep\n", error);
1488 				*return_code = MPS_FW_DIAG_ERROR_NO_BUFFER;
1489 				status = MPS_DIAG_FAILURE;
1490 				goto bailout;
1491 			}
1492 		}
1493 		mps_unlock(sc);
1494 	}
1495 
1496 	if ((error != 0) || (ctx->error != 0)) {
1497 		device_printf(sc->mps_dev, "Cannot bus_dmamap_load FW diag "
1498 		    "buffer, %serror = %d\n", error ? "" : "callback ",
1499 		    error ? error : ctx->error);
1500 		*return_code = MPS_FW_DIAG_ERROR_NO_BUFFER;
1501 		status = MPS_DIAG_FAILURE;
1502 		goto bailout;
1503 	}
1504 
1505 	bus_dmamap_sync(sc->fw_diag_dmat, sc->fw_diag_map, BUS_DMASYNC_PREREAD);
1506 
1507 	pBuffer->size = buffer_size;
1508 
1509 	/*
1510 	 * Copy the given info to the diag buffer and post the buffer.
1511 	 */
1512 	pBuffer->buffer_type = buffer_type;
1513 	pBuffer->immediate = FALSE;
1514 	if (buffer_type == MPI2_DIAG_BUF_TYPE_TRACE) {
1515 		for (i = 0; i < (sizeof (pBuffer->product_specific) / 4);
1516 		    i++) {
1517 			pBuffer->product_specific[i] =
1518 			    diag_register->ProductSpecific[i];
1519 		}
1520 	}
1521 	pBuffer->extended_type = extended_type;
1522 	pBuffer->unique_id = unique_id;
1523 	status = mps_post_fw_diag_buffer(sc, pBuffer, return_code);
1524 
1525 bailout:
1526 	/*
1527 	 * In case there was a failure, free the DMA buffer.
1528 	 */
1529 	if (status == MPS_DIAG_FAILURE) {
1530 		if (sc->fw_diag_busaddr != 0) {
1531 			bus_dmamap_unload(sc->fw_diag_dmat, sc->fw_diag_map);
1532 			sc->fw_diag_busaddr = 0;
1533 		}
1534 		if (sc->fw_diag_buffer != NULL) {
1535 			bus_dmamem_free(sc->fw_diag_dmat, sc->fw_diag_buffer,
1536 			    sc->fw_diag_map);
1537 			sc->fw_diag_buffer = NULL;
1538 		}
1539 		if (sc->fw_diag_dmat != NULL) {
1540 			bus_dma_tag_destroy(sc->fw_diag_dmat);
1541 			sc->fw_diag_dmat = NULL;
1542 		}
1543 	}
1544 
1545 	if (ctx != NULL)
1546 		free(ctx, M_MPSUSER);
1547 
1548 	return (status);
1549 }
1550 
1551 static int
1552 mps_diag_unregister(struct mps_softc *sc,
1553     mps_fw_diag_unregister_t *diag_unregister, uint32_t *return_code)
1554 {
1555 	mps_fw_diagnostic_buffer_t	*pBuffer;
1556 	uint8_t				i;
1557 	uint32_t			unique_id;
1558 	int				status;
1559 
1560 	unique_id = diag_unregister->UniqueId;
1561 
1562 	/*
1563 	 * Get the current buffer and look up the unique ID.  The unique ID
1564 	 * should be there.
1565 	 */
1566 	i = mps_get_fw_diag_buffer_number(sc, unique_id);
1567 	if (i == MPS_FW_DIAGNOSTIC_UID_NOT_FOUND) {
1568 		*return_code = MPS_FW_DIAG_ERROR_INVALID_UID;
1569 		return (MPS_DIAG_FAILURE);
1570 	}
1571 
1572 	pBuffer = &sc->fw_diag_buffer_list[i];
1573 
1574 	/*
1575 	 * Try to release the buffer from FW before freeing it.  If release
1576 	 * fails, don't free the DMA buffer in case FW tries to access it
1577 	 * later.  If buffer is not owned by firmware, can't release it.
1578 	 */
1579 	if (!pBuffer->owned_by_firmware) {
1580 		status = MPS_DIAG_SUCCESS;
1581 	} else {
1582 		status = mps_release_fw_diag_buffer(sc, pBuffer, return_code,
1583 		    MPS_FW_DIAG_TYPE_UNREGISTER);
1584 	}
1585 
1586 	/*
1587 	 * At this point, return the current status no matter what happens with
1588 	 * the DMA buffer.
1589 	 */
1590 	pBuffer->unique_id = MPS_FW_DIAG_INVALID_UID;
1591 	if (status == MPS_DIAG_SUCCESS) {
1592 		if (sc->fw_diag_busaddr != 0) {
1593 			bus_dmamap_unload(sc->fw_diag_dmat, sc->fw_diag_map);
1594 			sc->fw_diag_busaddr = 0;
1595 		}
1596 		if (sc->fw_diag_buffer != NULL) {
1597 			bus_dmamem_free(sc->fw_diag_dmat, sc->fw_diag_buffer,
1598 			    sc->fw_diag_map);
1599 			sc->fw_diag_buffer = NULL;
1600 		}
1601 		if (sc->fw_diag_dmat != NULL) {
1602 			bus_dma_tag_destroy(sc->fw_diag_dmat);
1603 			sc->fw_diag_dmat = NULL;
1604 		}
1605 	}
1606 
1607 	return (status);
1608 }
1609 
1610 static int
1611 mps_diag_query(struct mps_softc *sc, mps_fw_diag_query_t *diag_query,
1612     uint32_t *return_code)
1613 {
1614 	mps_fw_diagnostic_buffer_t	*pBuffer;
1615 	uint8_t				i;
1616 	uint32_t			unique_id;
1617 
1618 	unique_id = diag_query->UniqueId;
1619 
1620 	/*
1621 	 * If ID is valid, query on ID.
1622 	 * If ID is invalid, query on buffer type.
1623 	 */
1624 	if (unique_id == MPS_FW_DIAG_INVALID_UID) {
1625 		i = diag_query->BufferType;
1626 		if (i >= MPI2_DIAG_BUF_TYPE_COUNT) {
1627 			*return_code = MPS_FW_DIAG_ERROR_INVALID_UID;
1628 			return (MPS_DIAG_FAILURE);
1629 		}
1630 	} else {
1631 		i = mps_get_fw_diag_buffer_number(sc, unique_id);
1632 		if (i == MPS_FW_DIAGNOSTIC_UID_NOT_FOUND) {
1633 			*return_code = MPS_FW_DIAG_ERROR_INVALID_UID;
1634 			return (MPS_DIAG_FAILURE);
1635 		}
1636 	}
1637 
1638 	/*
1639 	 * Fill query structure with the diag buffer info.
1640 	 */
1641 	pBuffer = &sc->fw_diag_buffer_list[i];
1642 	diag_query->BufferType = pBuffer->buffer_type;
1643 	diag_query->ExtendedType = pBuffer->extended_type;
1644 	if (diag_query->BufferType == MPI2_DIAG_BUF_TYPE_TRACE) {
1645 		for (i = 0; i < (sizeof(diag_query->ProductSpecific) / 4);
1646 		    i++) {
1647 			diag_query->ProductSpecific[i] =
1648 			    pBuffer->product_specific[i];
1649 		}
1650 	}
1651 	diag_query->TotalBufferSize = pBuffer->size;
1652 	diag_query->DriverAddedBufferSize = 0;
1653 	diag_query->UniqueId = pBuffer->unique_id;
1654 	diag_query->ApplicationFlags = 0;
1655 	diag_query->DiagnosticFlags = 0;
1656 
1657 	/*
1658 	 * Set/Clear application flags
1659 	 */
1660 	if (pBuffer->immediate) {
1661 		diag_query->ApplicationFlags &= ~MPS_FW_DIAG_FLAG_APP_OWNED;
1662 	} else {
1663 		diag_query->ApplicationFlags |= MPS_FW_DIAG_FLAG_APP_OWNED;
1664 	}
1665 	if (pBuffer->valid_data || pBuffer->owned_by_firmware) {
1666 		diag_query->ApplicationFlags |= MPS_FW_DIAG_FLAG_BUFFER_VALID;
1667 	} else {
1668 		diag_query->ApplicationFlags &= ~MPS_FW_DIAG_FLAG_BUFFER_VALID;
1669 	}
1670 	if (pBuffer->owned_by_firmware) {
1671 		diag_query->ApplicationFlags |=
1672 		    MPS_FW_DIAG_FLAG_FW_BUFFER_ACCESS;
1673 	} else {
1674 		diag_query->ApplicationFlags &=
1675 		    ~MPS_FW_DIAG_FLAG_FW_BUFFER_ACCESS;
1676 	}
1677 
1678 	return (MPS_DIAG_SUCCESS);
1679 }
1680 
1681 static int
1682 mps_diag_read_buffer(struct mps_softc *sc,
1683     mps_diag_read_buffer_t *diag_read_buffer, uint8_t *ioctl_buf,
1684     uint32_t *return_code)
1685 {
1686 	mps_fw_diagnostic_buffer_t	*pBuffer;
1687 	uint8_t				i, *pData;
1688 	uint32_t			unique_id;
1689 	int				status;
1690 
1691 	unique_id = diag_read_buffer->UniqueId;
1692 
1693 	/*
1694 	 * Get the current buffer and look up the unique ID.  The unique ID
1695 	 * should be there.
1696 	 */
1697 	i = mps_get_fw_diag_buffer_number(sc, unique_id);
1698 	if (i == MPS_FW_DIAGNOSTIC_UID_NOT_FOUND) {
1699 		*return_code = MPS_FW_DIAG_ERROR_INVALID_UID;
1700 		return (MPS_DIAG_FAILURE);
1701 	}
1702 
1703 	pBuffer = &sc->fw_diag_buffer_list[i];
1704 
1705 	/*
1706 	 * Make sure requested read is within limits
1707 	 */
1708 	if (diag_read_buffer->StartingOffset + diag_read_buffer->BytesToRead >
1709 	    pBuffer->size) {
1710 		*return_code = MPS_FW_DIAG_ERROR_INVALID_PARAMETER;
1711 		return (MPS_DIAG_FAILURE);
1712 	}
1713 
1714 	/* Sync the DMA map before we copy to userland. */
1715 	bus_dmamap_sync(sc->fw_diag_dmat, sc->fw_diag_map,
1716 	    BUS_DMASYNC_POSTREAD);
1717 
1718 	/*
1719 	 * Copy the requested data from DMA to the diag_read_buffer.  The DMA
1720 	 * buffer that was allocated is one contiguous buffer.
1721 	 */
1722 	pData = (uint8_t *)(sc->fw_diag_buffer +
1723 	    diag_read_buffer->StartingOffset);
1724 	if (copyout(pData, ioctl_buf, diag_read_buffer->BytesToRead) != 0)
1725 		return (MPS_DIAG_FAILURE);
1726 	diag_read_buffer->Status = 0;
1727 
1728 	/*
1729 	 * Set or clear the Force Release flag.
1730 	 */
1731 	if (pBuffer->force_release) {
1732 		diag_read_buffer->Flags |= MPS_FW_DIAG_FLAG_FORCE_RELEASE;
1733 	} else {
1734 		diag_read_buffer->Flags &= ~MPS_FW_DIAG_FLAG_FORCE_RELEASE;
1735 	}
1736 
1737 	/*
1738 	 * If buffer is to be reregistered, make sure it's not already owned by
1739 	 * firmware first.
1740 	 */
1741 	status = MPS_DIAG_SUCCESS;
1742 	if (!pBuffer->owned_by_firmware) {
1743 		if (diag_read_buffer->Flags & MPS_FW_DIAG_FLAG_REREGISTER) {
1744 			status = mps_post_fw_diag_buffer(sc, pBuffer,
1745 			    return_code);
1746 		}
1747 	}
1748 
1749 	return (status);
1750 }
1751 
1752 static int
1753 mps_diag_release(struct mps_softc *sc, mps_fw_diag_release_t *diag_release,
1754     uint32_t *return_code)
1755 {
1756 	mps_fw_diagnostic_buffer_t	*pBuffer;
1757 	uint8_t				i;
1758 	uint32_t			unique_id;
1759 	int				status;
1760 
1761 	unique_id = diag_release->UniqueId;
1762 
1763 	/*
1764 	 * Get the current buffer and look up the unique ID.  The unique ID
1765 	 * should be there.
1766 	 */
1767 	i = mps_get_fw_diag_buffer_number(sc, unique_id);
1768 	if (i == MPS_FW_DIAGNOSTIC_UID_NOT_FOUND) {
1769 		*return_code = MPS_FW_DIAG_ERROR_INVALID_UID;
1770 		return (MPS_DIAG_FAILURE);
1771 	}
1772 
1773 	pBuffer = &sc->fw_diag_buffer_list[i];
1774 
1775 	/*
1776 	 * If buffer is not owned by firmware, it's already been released.
1777 	 */
1778 	if (!pBuffer->owned_by_firmware) {
1779 		*return_code = MPS_FW_DIAG_ERROR_ALREADY_RELEASED;
1780 		return (MPS_DIAG_FAILURE);
1781 	}
1782 
1783 	/*
1784 	 * Release the buffer.
1785 	 */
1786 	status = mps_release_fw_diag_buffer(sc, pBuffer, return_code,
1787 	    MPS_FW_DIAG_TYPE_RELEASE);
1788 	return (status);
1789 }
1790 
1791 static int
1792 mps_do_diag_action(struct mps_softc *sc, uint32_t action, uint8_t *diag_action,
1793     uint32_t length, uint32_t *return_code)
1794 {
1795 	mps_fw_diag_register_t		diag_register;
1796 	mps_fw_diag_unregister_t	diag_unregister;
1797 	mps_fw_diag_query_t		diag_query;
1798 	mps_diag_read_buffer_t		diag_read_buffer;
1799 	mps_fw_diag_release_t		diag_release;
1800 	int				status = MPS_DIAG_SUCCESS;
1801 	uint32_t			original_return_code;
1802 
1803 	original_return_code = *return_code;
1804 	*return_code = MPS_FW_DIAG_ERROR_SUCCESS;
1805 
1806 	switch (action) {
1807 		case MPS_FW_DIAG_TYPE_REGISTER:
1808 			if (!length) {
1809 				*return_code =
1810 				    MPS_FW_DIAG_ERROR_INVALID_PARAMETER;
1811 				status = MPS_DIAG_FAILURE;
1812 				break;
1813 			}
1814 			if (copyin(diag_action, &diag_register,
1815 			    sizeof(diag_register)) != 0)
1816 				return (MPS_DIAG_FAILURE);
1817 			status = mps_diag_register(sc, &diag_register,
1818 			    return_code);
1819 			break;
1820 
1821 		case MPS_FW_DIAG_TYPE_UNREGISTER:
1822 			if (length < sizeof(diag_unregister)) {
1823 				*return_code =
1824 				    MPS_FW_DIAG_ERROR_INVALID_PARAMETER;
1825 				status = MPS_DIAG_FAILURE;
1826 				break;
1827 			}
1828 			if (copyin(diag_action, &diag_unregister,
1829 			    sizeof(diag_unregister)) != 0)
1830 				return (MPS_DIAG_FAILURE);
1831 			status = mps_diag_unregister(sc, &diag_unregister,
1832 			    return_code);
1833 			break;
1834 
1835 		case MPS_FW_DIAG_TYPE_QUERY:
1836 			if (length < sizeof (diag_query)) {
1837 				*return_code =
1838 				    MPS_FW_DIAG_ERROR_INVALID_PARAMETER;
1839 				status = MPS_DIAG_FAILURE;
1840 				break;
1841 			}
1842 			if (copyin(diag_action, &diag_query, sizeof(diag_query))
1843 			    != 0)
1844 				return (MPS_DIAG_FAILURE);
1845 			status = mps_diag_query(sc, &diag_query, return_code);
1846 			if (status == MPS_DIAG_SUCCESS)
1847 				if (copyout(&diag_query, diag_action,
1848 				    sizeof (diag_query)) != 0)
1849 					return (MPS_DIAG_FAILURE);
1850 			break;
1851 
1852 		case MPS_FW_DIAG_TYPE_READ_BUFFER:
1853 			if (copyin(diag_action, &diag_read_buffer,
1854 			    sizeof(diag_read_buffer)) != 0)
1855 				return (MPS_DIAG_FAILURE);
1856 			if (length < diag_read_buffer.BytesToRead) {
1857 				*return_code =
1858 				    MPS_FW_DIAG_ERROR_INVALID_PARAMETER;
1859 				status = MPS_DIAG_FAILURE;
1860 				break;
1861 			}
1862 			status = mps_diag_read_buffer(sc, &diag_read_buffer,
1863 			    PTRIN(diag_read_buffer.PtrDataBuffer),
1864 			    return_code);
1865 			if (status == MPS_DIAG_SUCCESS) {
1866 				if (copyout(&diag_read_buffer, diag_action,
1867 				    sizeof(diag_read_buffer) -
1868 				    sizeof(diag_read_buffer.PtrDataBuffer)) !=
1869 				    0)
1870 					return (MPS_DIAG_FAILURE);
1871 			}
1872 			break;
1873 
1874 		case MPS_FW_DIAG_TYPE_RELEASE:
1875 			if (length < sizeof(diag_release)) {
1876 				*return_code =
1877 				    MPS_FW_DIAG_ERROR_INVALID_PARAMETER;
1878 				status = MPS_DIAG_FAILURE;
1879 				break;
1880 			}
1881 			if (copyin(diag_action, &diag_release,
1882 			    sizeof(diag_release)) != 0)
1883 				return (MPS_DIAG_FAILURE);
1884 			status = mps_diag_release(sc, &diag_release,
1885 			    return_code);
1886 			break;
1887 
1888 		default:
1889 			*return_code = MPS_FW_DIAG_ERROR_INVALID_PARAMETER;
1890 			status = MPS_DIAG_FAILURE;
1891 			break;
1892 	}
1893 
1894 	if ((status == MPS_DIAG_FAILURE) &&
1895 	    (original_return_code == MPS_FW_DIAG_NEW) &&
1896 	    (*return_code != MPS_FW_DIAG_ERROR_SUCCESS))
1897 		status = MPS_DIAG_SUCCESS;
1898 
1899 	return (status);
1900 }
1901 
1902 static int
1903 mps_user_diag_action(struct mps_softc *sc, mps_diag_action_t *data)
1904 {
1905 	int			status;
1906 
1907 	/*
1908 	 * Only allow one diag action at one time.
1909 	 */
1910 	if (sc->mps_flags & MPS_FLAGS_BUSY) {
1911 		mps_dprint(sc, MPS_USER, "%s: Only one FW diag command "
1912 		    "allowed at a single time.", __func__);
1913 		return (EBUSY);
1914 	}
1915 	sc->mps_flags |= MPS_FLAGS_BUSY;
1916 
1917 	/*
1918 	 * Send diag action request
1919 	 */
1920 	if (data->Action == MPS_FW_DIAG_TYPE_REGISTER ||
1921 	    data->Action == MPS_FW_DIAG_TYPE_UNREGISTER ||
1922 	    data->Action == MPS_FW_DIAG_TYPE_QUERY ||
1923 	    data->Action == MPS_FW_DIAG_TYPE_READ_BUFFER ||
1924 	    data->Action == MPS_FW_DIAG_TYPE_RELEASE) {
1925 		status = mps_do_diag_action(sc, data->Action,
1926 		    PTRIN(data->PtrDiagAction), data->Length,
1927 		    &data->ReturnCode);
1928 	} else
1929 		status = EINVAL;
1930 
1931 	sc->mps_flags &= ~MPS_FLAGS_BUSY;
1932 	return (status);
1933 }
1934 
1935 /*
1936  * Copy the event recording mask and the event queue size out.  For
1937  * clarification, the event recording mask (events_to_record) is not the same
1938  * thing as the event mask (event_mask).  events_to_record has a bit set for
1939  * every event type that is to be recorded by the driver, and event_mask has a
1940  * bit cleared for every event that is allowed into the driver from the IOC.
1941  * They really have nothing to do with each other.
1942  */
1943 static void
1944 mps_user_event_query(struct mps_softc *sc, mps_event_query_t *data)
1945 {
1946 	uint8_t	i;
1947 
1948 	mps_lock(sc);
1949 	data->Entries = MPS_EVENT_QUEUE_SIZE;
1950 
1951 	for (i = 0; i < 4; i++) {
1952 		data->Types[i] = sc->events_to_record[i];
1953 	}
1954 	mps_unlock(sc);
1955 }
1956 
1957 /*
1958  * Set the driver's event mask according to what's been given.  See
1959  * mps_user_event_query for explanation of the event recording mask and the IOC
1960  * event mask.  It's the app's responsibility to enable event logging by setting
1961  * the bits in events_to_record.  Initially, no events will be logged.
1962  */
1963 static void
1964 mps_user_event_enable(struct mps_softc *sc, mps_event_enable_t *data)
1965 {
1966 	uint8_t	i;
1967 
1968 	mps_lock(sc);
1969 	for (i = 0; i < 4; i++) {
1970 		sc->events_to_record[i] = data->Types[i];
1971 	}
1972 	mps_unlock(sc);
1973 }
1974 
1975 /*
1976  * Copy out the events that have been recorded, up to the max events allowed.
1977  */
1978 static int
1979 mps_user_event_report(struct mps_softc *sc, mps_event_report_t *data)
1980 {
1981 	int		status = 0;
1982 	uint32_t	size;
1983 
1984 	mps_lock(sc);
1985 	size = data->Size;
1986 	if ((size >= sizeof(sc->recorded_events)) && (status == 0)) {
1987 		mps_unlock(sc);
1988 		if (copyout((void *)sc->recorded_events,
1989 		    PTRIN(data->PtrEvents), size) != 0)
1990 			status = EFAULT;
1991 		mps_lock(sc);
1992 	} else {
1993 		/*
1994 		 * data->Size value is not large enough to copy event data.
1995 		 */
1996 		status = EFAULT;
1997 	}
1998 
1999 	/*
2000 	 * Change size value to match the number of bytes that were copied.
2001 	 */
2002 	if (status == 0)
2003 		data->Size = sizeof(sc->recorded_events);
2004 	mps_unlock(sc);
2005 
2006 	return (status);
2007 }
2008 
2009 /*
2010  * Record events into the driver from the IOC if they are not masked.
2011  */
2012 void
2013 mpssas_record_event(struct mps_softc *sc,
2014     MPI2_EVENT_NOTIFICATION_REPLY *event_reply)
2015 {
2016 	uint32_t	event;
2017 	int		i, j;
2018 	uint16_t	event_data_len;
2019 	boolean_t	sendAEN = FALSE;
2020 
2021 	event = event_reply->Event;
2022 
2023 	/*
2024 	 * Generate a system event to let anyone who cares know that a
2025 	 * LOG_ENTRY_ADDED event has occurred.  This is sent no matter what the
2026 	 * event mask is set to.
2027 	 */
2028 	if (event == MPI2_EVENT_LOG_ENTRY_ADDED) {
2029 		sendAEN = TRUE;
2030 	}
2031 
2032 	/*
2033 	 * Record the event only if its corresponding bit is set in
2034 	 * events_to_record.  event_index is the index into recorded_events and
2035 	 * event_number is the overall number of an event being recorded since
2036 	 * start-of-day.  event_index will roll over; event_number will never
2037 	 * roll over.
2038 	 */
2039 	i = (uint8_t)(event / 32);
2040 	j = (uint8_t)(event % 32);
2041 	if ((i < 4) && ((1 << j) & sc->events_to_record[i])) {
2042 		i = sc->event_index;
2043 		sc->recorded_events[i].Type = event;
2044 		sc->recorded_events[i].Number = ++sc->event_number;
2045 		bzero(sc->recorded_events[i].Data, MPS_MAX_EVENT_DATA_LENGTH *
2046 		    4);
2047 		event_data_len = event_reply->EventDataLength;
2048 
2049 		if (event_data_len > 0) {
2050 			/*
2051 			 * Limit data to size in m_event entry
2052 			 */
2053 			if (event_data_len > MPS_MAX_EVENT_DATA_LENGTH) {
2054 				event_data_len = MPS_MAX_EVENT_DATA_LENGTH;
2055 			}
2056 			for (j = 0; j < event_data_len; j++) {
2057 				sc->recorded_events[i].Data[j] =
2058 				    event_reply->EventData[j];
2059 			}
2060 
2061 			/*
2062 			 * check for index wrap-around
2063 			 */
2064 			if (++i == MPS_EVENT_QUEUE_SIZE) {
2065 				i = 0;
2066 			}
2067 			sc->event_index = (uint8_t)i;
2068 
2069 			/*
2070 			 * Set flag to send the event.
2071 			 */
2072 			sendAEN = TRUE;
2073 		}
2074 	}
2075 
2076 	/*
2077 	 * Generate a system event if flag is set to let anyone who cares know
2078 	 * that an event has occurred.
2079 	 */
2080 	if (sendAEN) {
2081 //SLM-how to send a system event (see kqueue, kevent)
2082 //		(void) ddi_log_sysevent(mpt->m_dip, DDI_VENDOR_LSI, "MPT_SAS",
2083 //		    "SAS", NULL, NULL, DDI_NOSLEEP);
2084 	}
2085 }
2086 
2087 static int
2088 mps_user_reg_access(struct mps_softc *sc, mps_reg_access_t *data)
2089 {
2090 	int	status = 0;
2091 
2092 	switch (data->Command) {
2093 		/*
2094 		 * IO access is not supported.
2095 		 */
2096 		case REG_IO_READ:
2097 		case REG_IO_WRITE:
2098 			mps_dprint(sc, MPS_USER, "IO access is not supported. "
2099 			    "Use memory access.");
2100 			status = EINVAL;
2101 			break;
2102 
2103 		case REG_MEM_READ:
2104 			data->RegData = mps_regread(sc, data->RegOffset);
2105 			break;
2106 
2107 		case REG_MEM_WRITE:
2108 			mps_regwrite(sc, data->RegOffset, data->RegData);
2109 			break;
2110 
2111 		default:
2112 			status = EINVAL;
2113 			break;
2114 	}
2115 
2116 	return (status);
2117 }
2118 
2119 static int
2120 mps_user_btdh(struct mps_softc *sc, mps_btdh_mapping_t *data)
2121 {
2122 	uint8_t		bt2dh = FALSE;
2123 	uint8_t		dh2bt = FALSE;
2124 	uint16_t	dev_handle, bus, target;
2125 
2126 	bus = data->Bus;
2127 	target = data->TargetID;
2128 	dev_handle = data->DevHandle;
2129 
2130 	/*
2131 	 * When DevHandle is 0xFFFF and Bus/Target are not 0xFFFF, use Bus/
2132 	 * Target to get DevHandle.  When Bus/Target are 0xFFFF and DevHandle is
2133 	 * not 0xFFFF, use DevHandle to get Bus/Target.  Anything else is
2134 	 * invalid.
2135 	 */
2136 	if ((bus == 0xFFFF) && (target == 0xFFFF) && (dev_handle != 0xFFFF))
2137 		dh2bt = TRUE;
2138 	if ((dev_handle == 0xFFFF) && (bus != 0xFFFF) && (target != 0xFFFF))
2139 		bt2dh = TRUE;
2140 	if (!dh2bt && !bt2dh)
2141 		return (EINVAL);
2142 
2143 	/*
2144 	 * Only handle bus of 0.  Make sure target is within range.
2145 	 */
2146 	if (bt2dh) {
2147 		if (bus != 0)
2148 			return (EINVAL);
2149 
2150 		if (target > sc->max_devices) {
2151 			mps_dprint(sc, MPS_FAULT, "Target ID is out of range "
2152 			   "for Bus/Target to DevHandle mapping.");
2153 			return (EINVAL);
2154 		}
2155 		dev_handle = sc->mapping_table[target].dev_handle;
2156 		if (dev_handle)
2157 			data->DevHandle = dev_handle;
2158 	} else {
2159 		bus = 0;
2160 		target = mps_mapping_get_tid_from_handle(sc, dev_handle);
2161 		data->Bus = bus;
2162 		data->TargetID = target;
2163 	}
2164 
2165 	return (0);
2166 }
2167 
2168 static int
2169 mps_ioctl(struct cdev *dev, u_long cmd, void *arg, int flag,
2170     struct thread *td)
2171 {
2172 	struct mps_softc *sc;
2173 	struct mps_cfg_page_req *page_req;
2174 	struct mps_ext_cfg_page_req *ext_page_req;
2175 	void *mps_page;
2176 	int error, msleep_ret;
2177 
2178 	mps_page = NULL;
2179 	sc = dev->si_drv1;
2180 	page_req = (void *)arg;
2181 	ext_page_req = (void *)arg;
2182 
2183 	switch (cmd) {
2184 	case MPSIO_READ_CFG_HEADER:
2185 		mps_lock(sc);
2186 		error = mps_user_read_cfg_header(sc, page_req);
2187 		mps_unlock(sc);
2188 		break;
2189 	case MPSIO_READ_CFG_PAGE:
2190 		mps_page = malloc(page_req->len, M_MPSUSER, M_WAITOK | M_ZERO);
2191 		error = copyin(page_req->buf, mps_page,
2192 		    sizeof(MPI2_CONFIG_PAGE_HEADER));
2193 		if (error)
2194 			break;
2195 		mps_lock(sc);
2196 		error = mps_user_read_cfg_page(sc, page_req, mps_page);
2197 		mps_unlock(sc);
2198 		if (error)
2199 			break;
2200 		error = copyout(mps_page, page_req->buf, page_req->len);
2201 		break;
2202 	case MPSIO_READ_EXT_CFG_HEADER:
2203 		mps_lock(sc);
2204 		error = mps_user_read_extcfg_header(sc, ext_page_req);
2205 		mps_unlock(sc);
2206 		break;
2207 	case MPSIO_READ_EXT_CFG_PAGE:
2208 		mps_page = malloc(ext_page_req->len, M_MPSUSER, M_WAITOK|M_ZERO);
2209 		error = copyin(ext_page_req->buf, mps_page,
2210 		    sizeof(MPI2_CONFIG_EXTENDED_PAGE_HEADER));
2211 		if (error)
2212 			break;
2213 		mps_lock(sc);
2214 		error = mps_user_read_extcfg_page(sc, ext_page_req, mps_page);
2215 		mps_unlock(sc);
2216 		if (error)
2217 			break;
2218 		error = copyout(mps_page, ext_page_req->buf, ext_page_req->len);
2219 		break;
2220 	case MPSIO_WRITE_CFG_PAGE:
2221 		mps_page = malloc(page_req->len, M_MPSUSER, M_WAITOK|M_ZERO);
2222 		error = copyin(page_req->buf, mps_page, page_req->len);
2223 		if (error)
2224 			break;
2225 		mps_lock(sc);
2226 		error = mps_user_write_cfg_page(sc, page_req, mps_page);
2227 		mps_unlock(sc);
2228 		break;
2229 	case MPSIO_MPS_COMMAND:
2230 		error = mps_user_command(sc, (struct mps_usr_command *)arg);
2231 		break;
2232 	case MPTIOCTL_PASS_THRU:
2233 		/*
2234 		 * The user has requested to pass through a command to be
2235 		 * executed by the MPT firmware.  Call our routine which does
2236 		 * this.  Only allow one passthru IOCTL at one time.
2237 		 */
2238 		error = mps_user_pass_thru(sc, (mps_pass_thru_t *)arg);
2239 		break;
2240 	case MPTIOCTL_GET_ADAPTER_DATA:
2241 		/*
2242 		 * The user has requested to read adapter data.  Call our
2243 		 * routine which does this.
2244 		 */
2245 		error = 0;
2246 		mps_user_get_adapter_data(sc, (mps_adapter_data_t *)arg);
2247 		break;
2248 	case MPTIOCTL_GET_PCI_INFO:
2249 		/*
2250 		 * The user has requested to read pci info.  Call
2251 		 * our routine which does this.
2252 		 */
2253 		mps_lock(sc);
2254 		error = 0;
2255 		mps_user_read_pci_info(sc, (mps_pci_info_t *)arg);
2256 		mps_unlock(sc);
2257 		break;
2258 	case MPTIOCTL_RESET_ADAPTER:
2259 		mps_lock(sc);
2260 		sc->port_enable_complete = 0;
2261 		uint32_t reinit_start = time_uptime;
2262 		error = mps_reinit(sc);
2263 		/* Sleep for 300 second. */
2264 		msleep_ret = msleep(&sc->port_enable_complete, &sc->mps_mtx, PRIBIO,
2265 		       "mps_porten", 300 * hz);
2266 		mps_unlock(sc);
2267 		if (msleep_ret)
2268 			printf("Port Enable did not complete after Diag "
2269 			    "Reset msleep error %d.\n", msleep_ret);
2270 		else
2271 			mps_dprint(sc, MPS_USER,
2272 				"Hard Reset with Port Enable completed in %d seconds.\n",
2273 				 (uint32_t) (time_uptime - reinit_start));
2274 		break;
2275 	case MPTIOCTL_DIAG_ACTION:
2276 		/*
2277 		 * The user has done a diag buffer action.  Call our routine
2278 		 * which does this.  Only allow one diag action at one time.
2279 		 */
2280 		mps_lock(sc);
2281 		error = mps_user_diag_action(sc, (mps_diag_action_t *)arg);
2282 		mps_unlock(sc);
2283 		break;
2284 	case MPTIOCTL_EVENT_QUERY:
2285 		/*
2286 		 * The user has done an event query. Call our routine which does
2287 		 * this.
2288 		 */
2289 		error = 0;
2290 		mps_user_event_query(sc, (mps_event_query_t *)arg);
2291 		break;
2292 	case MPTIOCTL_EVENT_ENABLE:
2293 		/*
2294 		 * The user has done an event enable. Call our routine which
2295 		 * does this.
2296 		 */
2297 		error = 0;
2298 		mps_user_event_enable(sc, (mps_event_enable_t *)arg);
2299 		break;
2300 	case MPTIOCTL_EVENT_REPORT:
2301 		/*
2302 		 * The user has done an event report. Call our routine which
2303 		 * does this.
2304 		 */
2305 		error = mps_user_event_report(sc, (mps_event_report_t *)arg);
2306 		break;
2307 	case MPTIOCTL_REG_ACCESS:
2308 		/*
2309 		 * The user has requested register access.  Call our routine
2310 		 * which does this.
2311 		 */
2312 		mps_lock(sc);
2313 		error = mps_user_reg_access(sc, (mps_reg_access_t *)arg);
2314 		mps_unlock(sc);
2315 		break;
2316 	case MPTIOCTL_BTDH_MAPPING:
2317 		/*
2318 		 * The user has requested to translate a bus/target to a
2319 		 * DevHandle or a DevHandle to a bus/target.  Call our routine
2320 		 * which does this.
2321 		 */
2322 		error = mps_user_btdh(sc, (mps_btdh_mapping_t *)arg);
2323 		break;
2324 	default:
2325 		error = ENOIOCTL;
2326 		break;
2327 	}
2328 
2329 	if (mps_page != NULL)
2330 		free(mps_page, M_MPSUSER);
2331 
2332 	return (error);
2333 }
2334 
2335 #ifdef COMPAT_FREEBSD32
2336 
2337 struct mps_cfg_page_req32 {
2338 	MPI2_CONFIG_PAGE_HEADER header;
2339 	uint32_t page_address;
2340 	uint32_t buf;
2341 	int	len;
2342 	uint16_t ioc_status;
2343 };
2344 
2345 struct mps_ext_cfg_page_req32 {
2346 	MPI2_CONFIG_EXTENDED_PAGE_HEADER header;
2347 	uint32_t page_address;
2348 	uint32_t buf;
2349 	int	len;
2350 	uint16_t ioc_status;
2351 };
2352 
2353 struct mps_raid_action32 {
2354 	uint8_t action;
2355 	uint8_t volume_bus;
2356 	uint8_t volume_id;
2357 	uint8_t phys_disk_num;
2358 	uint32_t action_data_word;
2359 	uint32_t buf;
2360 	int len;
2361 	uint32_t volume_status;
2362 	uint32_t action_data[4];
2363 	uint16_t action_status;
2364 	uint16_t ioc_status;
2365 	uint8_t write;
2366 };
2367 
2368 struct mps_usr_command32 {
2369 	uint32_t req;
2370 	uint32_t req_len;
2371 	uint32_t rpl;
2372 	uint32_t rpl_len;
2373 	uint32_t buf;
2374 	int len;
2375 	uint32_t flags;
2376 };
2377 
2378 #define	MPSIO_READ_CFG_HEADER32	_IOWR('M', 200, struct mps_cfg_page_req32)
2379 #define	MPSIO_READ_CFG_PAGE32	_IOWR('M', 201, struct mps_cfg_page_req32)
2380 #define	MPSIO_READ_EXT_CFG_HEADER32 _IOWR('M', 202, struct mps_ext_cfg_page_req32)
2381 #define	MPSIO_READ_EXT_CFG_PAGE32 _IOWR('M', 203, struct mps_ext_cfg_page_req32)
2382 #define	MPSIO_WRITE_CFG_PAGE32	_IOWR('M', 204, struct mps_cfg_page_req32)
2383 #define	MPSIO_RAID_ACTION32	_IOWR('M', 205, struct mps_raid_action32)
2384 #define	MPSIO_MPS_COMMAND32	_IOWR('M', 210, struct mps_usr_command32)
2385 
2386 static int
2387 mps_ioctl32(struct cdev *dev, u_long cmd32, void *_arg, int flag,
2388     struct thread *td)
2389 {
2390 	struct mps_cfg_page_req32 *page32 = _arg;
2391 	struct mps_ext_cfg_page_req32 *ext32 = _arg;
2392 	struct mps_raid_action32 *raid32 = _arg;
2393 	struct mps_usr_command32 *user32 = _arg;
2394 	union {
2395 		struct mps_cfg_page_req page;
2396 		struct mps_ext_cfg_page_req ext;
2397 		struct mps_raid_action raid;
2398 		struct mps_usr_command user;
2399 	} arg;
2400 	u_long cmd;
2401 	int error;
2402 
2403 	switch (cmd32) {
2404 	case MPSIO_READ_CFG_HEADER32:
2405 	case MPSIO_READ_CFG_PAGE32:
2406 	case MPSIO_WRITE_CFG_PAGE32:
2407 		if (cmd32 == MPSIO_READ_CFG_HEADER32)
2408 			cmd = MPSIO_READ_CFG_HEADER;
2409 		else if (cmd32 == MPSIO_READ_CFG_PAGE32)
2410 			cmd = MPSIO_READ_CFG_PAGE;
2411 		else
2412 			cmd = MPSIO_WRITE_CFG_PAGE;
2413 		CP(*page32, arg.page, header);
2414 		CP(*page32, arg.page, page_address);
2415 		PTRIN_CP(*page32, arg.page, buf);
2416 		CP(*page32, arg.page, len);
2417 		CP(*page32, arg.page, ioc_status);
2418 		break;
2419 
2420 	case MPSIO_READ_EXT_CFG_HEADER32:
2421 	case MPSIO_READ_EXT_CFG_PAGE32:
2422 		if (cmd32 == MPSIO_READ_EXT_CFG_HEADER32)
2423 			cmd = MPSIO_READ_EXT_CFG_HEADER;
2424 		else
2425 			cmd = MPSIO_READ_EXT_CFG_PAGE;
2426 		CP(*ext32, arg.ext, header);
2427 		CP(*ext32, arg.ext, page_address);
2428 		PTRIN_CP(*ext32, arg.ext, buf);
2429 		CP(*ext32, arg.ext, len);
2430 		CP(*ext32, arg.ext, ioc_status);
2431 		break;
2432 
2433 	case MPSIO_RAID_ACTION32:
2434 		cmd = MPSIO_RAID_ACTION;
2435 		CP(*raid32, arg.raid, action);
2436 		CP(*raid32, arg.raid, volume_bus);
2437 		CP(*raid32, arg.raid, volume_id);
2438 		CP(*raid32, arg.raid, phys_disk_num);
2439 		CP(*raid32, arg.raid, action_data_word);
2440 		PTRIN_CP(*raid32, arg.raid, buf);
2441 		CP(*raid32, arg.raid, len);
2442 		CP(*raid32, arg.raid, volume_status);
2443 		bcopy(raid32->action_data, arg.raid.action_data,
2444 		    sizeof arg.raid.action_data);
2445 		CP(*raid32, arg.raid, ioc_status);
2446 		CP(*raid32, arg.raid, write);
2447 		break;
2448 
2449 	case MPSIO_MPS_COMMAND32:
2450 		cmd = MPSIO_MPS_COMMAND;
2451 		PTRIN_CP(*user32, arg.user, req);
2452 		CP(*user32, arg.user, req_len);
2453 		PTRIN_CP(*user32, arg.user, rpl);
2454 		CP(*user32, arg.user, rpl_len);
2455 		PTRIN_CP(*user32, arg.user, buf);
2456 		CP(*user32, arg.user, len);
2457 		CP(*user32, arg.user, flags);
2458 		break;
2459 	default:
2460 		return (ENOIOCTL);
2461 	}
2462 
2463 	error = mps_ioctl(dev, cmd, &arg, flag, td);
2464 	if (error == 0 && (cmd32 & IOC_OUT) != 0) {
2465 		switch (cmd32) {
2466 		case MPSIO_READ_CFG_HEADER32:
2467 		case MPSIO_READ_CFG_PAGE32:
2468 		case MPSIO_WRITE_CFG_PAGE32:
2469 			CP(arg.page, *page32, header);
2470 			CP(arg.page, *page32, page_address);
2471 			PTROUT_CP(arg.page, *page32, buf);
2472 			CP(arg.page, *page32, len);
2473 			CP(arg.page, *page32, ioc_status);
2474 			break;
2475 
2476 		case MPSIO_READ_EXT_CFG_HEADER32:
2477 		case MPSIO_READ_EXT_CFG_PAGE32:
2478 			CP(arg.ext, *ext32, header);
2479 			CP(arg.ext, *ext32, page_address);
2480 			PTROUT_CP(arg.ext, *ext32, buf);
2481 			CP(arg.ext, *ext32, len);
2482 			CP(arg.ext, *ext32, ioc_status);
2483 			break;
2484 
2485 		case MPSIO_RAID_ACTION32:
2486 			CP(arg.raid, *raid32, action);
2487 			CP(arg.raid, *raid32, volume_bus);
2488 			CP(arg.raid, *raid32, volume_id);
2489 			CP(arg.raid, *raid32, phys_disk_num);
2490 			CP(arg.raid, *raid32, action_data_word);
2491 			PTROUT_CP(arg.raid, *raid32, buf);
2492 			CP(arg.raid, *raid32, len);
2493 			CP(arg.raid, *raid32, volume_status);
2494 			bcopy(arg.raid.action_data, raid32->action_data,
2495 			    sizeof arg.raid.action_data);
2496 			CP(arg.raid, *raid32, ioc_status);
2497 			CP(arg.raid, *raid32, write);
2498 			break;
2499 
2500 		case MPSIO_MPS_COMMAND32:
2501 			PTROUT_CP(arg.user, *user32, req);
2502 			CP(arg.user, *user32, req_len);
2503 			PTROUT_CP(arg.user, *user32, rpl);
2504 			CP(arg.user, *user32, rpl_len);
2505 			PTROUT_CP(arg.user, *user32, buf);
2506 			CP(arg.user, *user32, len);
2507 			CP(arg.user, *user32, flags);
2508 			break;
2509 		}
2510 	}
2511 
2512 	return (error);
2513 }
2514 #endif /* COMPAT_FREEBSD32 */
2515 
2516 static int
2517 mps_ioctl_devsw(struct cdev *dev, u_long com, caddr_t arg, int flag,
2518     struct thread *td)
2519 {
2520 #ifdef COMPAT_FREEBSD32
2521 	if (SV_CURPROC_FLAG(SV_ILP32))
2522 		return (mps_ioctl32(dev, com, arg, flag, td));
2523 #endif
2524 	return (mps_ioctl(dev, com, arg, flag, td));
2525 }
2526