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