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