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