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