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