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