1 /*-
2  * Copyright (c) 2009 Yahoo! Inc.
3  * Copyright (c) 2011-2015 LSI Corp.
4  * Copyright (c) 2013-2016 Avago Technologies
5  * Copyright 2000-2020 Broadcom Inc.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * Broadcom Inc. (LSI) MPT-Fusion Host Adapter FreeBSD
30  *
31  */
32 
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD: stable/12/sys/dev/mpr/mpr.c 373239 2023-10-05 20:37:12Z asomers $");
35 
36 /* Communications core for Avago Technologies (LSI) MPT3 */
37 
38 /* TODO Move headers to mprvar */
39 #include <sys/types.h>
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
43 #include <sys/selinfo.h>
44 #include <sys/lock.h>
45 #include <sys/mutex.h>
46 #include <sys/module.h>
47 #include <sys/bus.h>
48 #include <sys/conf.h>
49 #include <sys/bio.h>
50 #include <sys/malloc.h>
51 #include <sys/uio.h>
52 #include <sys/sysctl.h>
53 #include <sys/smp.h>
54 #include <sys/queue.h>
55 #include <sys/kthread.h>
56 #include <sys/taskqueue.h>
57 #include <sys/endian.h>
58 #include <sys/eventhandler.h>
59 #include <sys/sbuf.h>
60 #include <sys/priv.h>
61 
62 #include <machine/bus.h>
63 #include <machine/resource.h>
64 #include <sys/rman.h>
65 #include <sys/proc.h>
66 
67 #include <dev/pci/pcivar.h>
68 
69 #include <cam/cam.h>
70 #include <cam/cam_ccb.h>
71 #include <cam/scsi/scsi_all.h>
72 
73 #include <dev/mpr/mpi/mpi2_type.h>
74 #include <dev/mpr/mpi/mpi2.h>
75 #include <dev/mpr/mpi/mpi2_ioc.h>
76 #include <dev/mpr/mpi/mpi2_sas.h>
77 #include <dev/mpr/mpi/mpi2_pci.h>
78 #include <dev/mpr/mpi/mpi2_cnfg.h>
79 #include <dev/mpr/mpi/mpi2_init.h>
80 #include <dev/mpr/mpi/mpi2_tool.h>
81 #include <dev/mpr/mpr_ioctl.h>
82 #include <dev/mpr/mprvar.h>
83 #include <dev/mpr/mpr_table.h>
84 #include <dev/mpr/mpr_sas.h>
85 
86 static int mpr_diag_reset(struct mpr_softc *sc, int sleep_flag);
87 static int mpr_init_queues(struct mpr_softc *sc);
88 static void mpr_resize_queues(struct mpr_softc *sc);
89 static int mpr_message_unit_reset(struct mpr_softc *sc, int sleep_flag);
90 static int mpr_transition_operational(struct mpr_softc *sc);
91 static int mpr_iocfacts_allocate(struct mpr_softc *sc, uint8_t attaching);
92 static void mpr_iocfacts_free(struct mpr_softc *sc);
93 static void mpr_startup(void *arg);
94 static int mpr_send_iocinit(struct mpr_softc *sc);
95 static int mpr_alloc_queues(struct mpr_softc *sc);
96 static int mpr_alloc_hw_queues(struct mpr_softc *sc);
97 static int mpr_alloc_replies(struct mpr_softc *sc);
98 static int mpr_alloc_requests(struct mpr_softc *sc);
99 static int mpr_alloc_nvme_prp_pages(struct mpr_softc *sc);
100 static int mpr_attach_log(struct mpr_softc *sc);
101 static __inline void mpr_complete_command(struct mpr_softc *sc,
102     struct mpr_command *cm);
103 static void mpr_dispatch_event(struct mpr_softc *sc, uintptr_t data,
104     MPI2_EVENT_NOTIFICATION_REPLY *reply);
105 static void mpr_config_complete(struct mpr_softc *sc, struct mpr_command *cm);
106 static void mpr_periodic(void *);
107 static int mpr_reregister_events(struct mpr_softc *sc);
108 static void mpr_enqueue_request(struct mpr_softc *sc, struct mpr_command *cm);
109 static int mpr_get_iocfacts(struct mpr_softc *sc, MPI2_IOC_FACTS_REPLY *facts);
110 static int mpr_wait_db_ack(struct mpr_softc *sc, int timeout, int sleep_flag);
111 static int mpr_debug_sysctl(SYSCTL_HANDLER_ARGS);
112 static int mpr_dump_reqs(SYSCTL_HANDLER_ARGS);
113 static void mpr_parse_debug(struct mpr_softc *sc, char *list);
114 static void adjust_iocfacts_endianness(MPI2_IOC_FACTS_REPLY *facts);
115 
116 SYSCTL_NODE(_hw, OID_AUTO, mpr, CTLFLAG_RD, 0, "MPR Driver Parameters");
117 
118 MALLOC_DEFINE(M_MPR, "mpr", "mpr driver memory");
119 
120 /*
121  * Do a "Diagnostic Reset" aka a hard reset.  This should get the chip out of
122  * any state and back to its initialization state machine.
123  */
124 static char mpt2_reset_magic[] = { 0x00, 0x0f, 0x04, 0x0b, 0x02, 0x07, 0x0d };
125 
126 /*
127  * Added this union to smoothly convert le64toh cm->cm_desc.Words.
128  * Compiler only supports uint64_t to be passed as an argument.
129  * Otherwise it will throw this error:
130  * "aggregate value used where an integer was expected"
131  */
132 typedef union _reply_descriptor {
133         u64 word;
134         struct {
135                 u32 low;
136                 u32 high;
137         } u;
138 } reply_descriptor, request_descriptor;
139 
140 /* Rate limit chain-fail messages to 1 per minute */
141 static struct timeval mpr_chainfail_interval = { 60, 0 };
142 
143 /*
144  * sleep_flag can be either CAN_SLEEP or NO_SLEEP.
145  * If this function is called from process context, it can sleep
146  * and there is no harm to sleep, in case if this fuction is called
147  * from Interrupt handler, we can not sleep and need NO_SLEEP flag set.
148  * based on sleep flags driver will call either msleep, pause or DELAY.
149  * msleep and pause are of same variant, but pause is used when mpr_mtx
150  * is not hold by driver.
151  */
152 static int
mpr_diag_reset(struct mpr_softc * sc,int sleep_flag)153 mpr_diag_reset(struct mpr_softc *sc,int sleep_flag)
154 {
155 	uint32_t reg;
156 	int i, error, tries = 0;
157 	uint8_t first_wait_done = FALSE;
158 
159 	mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
160 
161 	/* Clear any pending interrupts */
162 	mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
163 
164 	/*
165 	 * Force NO_SLEEP for threads prohibited to sleep
166  	 * e.a Thread from interrupt handler are prohibited to sleep.
167  	 */
168 #if __FreeBSD_version >= 1000029
169 	if (curthread->td_no_sleeping)
170 #else //__FreeBSD_version < 1000029
171 	if (curthread->td_pflags & TDP_NOSLEEPING)
172 #endif //__FreeBSD_version >= 1000029
173 		sleep_flag = NO_SLEEP;
174 
175 	mpr_dprint(sc, MPR_INIT, "sequence start, sleep_flag=%d\n", sleep_flag);
176 	/* Push the magic sequence */
177 	error = ETIMEDOUT;
178 	while (tries++ < 20) {
179 		for (i = 0; i < sizeof(mpt2_reset_magic); i++)
180 			mpr_regwrite(sc, MPI2_WRITE_SEQUENCE_OFFSET,
181 			    mpt2_reset_magic[i]);
182 
183 		/* wait 100 msec */
184 		if (mtx_owned(&sc->mpr_mtx) && sleep_flag == CAN_SLEEP)
185 			msleep(&sc->msleep_fake_chan, &sc->mpr_mtx, 0,
186 			    "mprdiag", hz/10);
187 		else if (sleep_flag == CAN_SLEEP)
188 			pause("mprdiag", hz/10);
189 		else
190 			DELAY(100 * 1000);
191 
192 		reg = mpr_regread(sc, MPI2_HOST_DIAGNOSTIC_OFFSET);
193 		if (reg & MPI2_DIAG_DIAG_WRITE_ENABLE) {
194 			error = 0;
195 			break;
196 		}
197 	}
198 	if (error) {
199 		mpr_dprint(sc, MPR_INIT, "sequence failed, error=%d, exit\n",
200 		    error);
201 		return (error);
202 	}
203 
204 	/* Send the actual reset.  XXX need to refresh the reg? */
205 	reg |= MPI2_DIAG_RESET_ADAPTER;
206 	mpr_dprint(sc, MPR_INIT, "sequence success, sending reset, reg= 0x%x\n",
207 	    reg);
208 	mpr_regwrite(sc, MPI2_HOST_DIAGNOSTIC_OFFSET, reg);
209 
210 	/* Wait up to 300 seconds in 50ms intervals */
211 	error = ETIMEDOUT;
212 	for (i = 0; i < 6000; i++) {
213 		/*
214 		 * Wait 50 msec. If this is the first time through, wait 256
215 		 * msec to satisfy Diag Reset timing requirements.
216 		 */
217 		if (first_wait_done) {
218 			if (mtx_owned(&sc->mpr_mtx) && sleep_flag == CAN_SLEEP)
219 				msleep(&sc->msleep_fake_chan, &sc->mpr_mtx, 0,
220 				    "mprdiag", hz/20);
221 			else if (sleep_flag == CAN_SLEEP)
222 				pause("mprdiag", hz/20);
223 			else
224 				DELAY(50 * 1000);
225 		} else {
226 			DELAY(256 * 1000);
227 			first_wait_done = TRUE;
228 		}
229 		/*
230 		 * Check for the RESET_ADAPTER bit to be cleared first, then
231 		 * wait for the RESET state to be cleared, which takes a little
232 		 * longer.
233 		 */
234 		reg = mpr_regread(sc, MPI2_HOST_DIAGNOSTIC_OFFSET);
235 		if (reg & MPI2_DIAG_RESET_ADAPTER) {
236 			continue;
237 		}
238 		reg = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
239 		if ((reg & MPI2_IOC_STATE_MASK) != MPI2_IOC_STATE_RESET) {
240 			error = 0;
241 			break;
242 		}
243 	}
244 	if (error) {
245 		mpr_dprint(sc, MPR_INIT, "reset failed, error= %d, exit\n",
246 		    error);
247 		return (error);
248 	}
249 
250 	mpr_regwrite(sc, MPI2_WRITE_SEQUENCE_OFFSET, 0x0);
251 	mpr_dprint(sc, MPR_INIT, "diag reset success, exit\n");
252 
253 	return (0);
254 }
255 
256 static int
mpr_message_unit_reset(struct mpr_softc * sc,int sleep_flag)257 mpr_message_unit_reset(struct mpr_softc *sc, int sleep_flag)
258 {
259 	int error;
260 
261 	MPR_FUNCTRACE(sc);
262 
263 	mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
264 
265 	error = 0;
266 	mpr_regwrite(sc, MPI2_DOORBELL_OFFSET,
267 	    MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET <<
268 	    MPI2_DOORBELL_FUNCTION_SHIFT);
269 
270 	if (mpr_wait_db_ack(sc, 5, sleep_flag) != 0) {
271 		mpr_dprint(sc, MPR_INIT|MPR_FAULT,
272 		    "Doorbell handshake failed\n");
273 		error = ETIMEDOUT;
274 	}
275 
276 	mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
277 	return (error);
278 }
279 
280 static int
mpr_transition_ready(struct mpr_softc * sc)281 mpr_transition_ready(struct mpr_softc *sc)
282 {
283 	uint32_t reg, state;
284 	int error, tries = 0;
285 	int sleep_flags;
286 
287 	MPR_FUNCTRACE(sc);
288 	/* If we are in attach call, do not sleep */
289 	sleep_flags = (sc->mpr_flags & MPR_FLAGS_ATTACH_DONE)
290 	    ? CAN_SLEEP : NO_SLEEP;
291 
292 	error = 0;
293 
294 	mpr_dprint(sc, MPR_INIT, "%s entered, sleep_flags= %d\n",
295 	    __func__, sleep_flags);
296 
297 	while (tries++ < 1200) {
298 		reg = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
299 		mpr_dprint(sc, MPR_INIT, "  Doorbell= 0x%x\n", reg);
300 
301 		/*
302 		 * Ensure the IOC is ready to talk.  If it's not, try
303 		 * resetting it.
304 		 */
305 		if (reg & MPI2_DOORBELL_USED) {
306 			mpr_dprint(sc, MPR_INIT, "  Not ready, sending diag "
307 			    "reset\n");
308 			mpr_diag_reset(sc, sleep_flags);
309 			DELAY(50000);
310 			continue;
311 		}
312 
313 		/* Is the adapter owned by another peer? */
314 		if ((reg & MPI2_DOORBELL_WHO_INIT_MASK) ==
315 		    (MPI2_WHOINIT_PCI_PEER << MPI2_DOORBELL_WHO_INIT_SHIFT)) {
316 			mpr_dprint(sc, MPR_INIT|MPR_FAULT, "IOC is under the "
317 			    "control of another peer host, aborting "
318 			    "initialization.\n");
319 			error = ENXIO;
320 			break;
321 		}
322 
323 		state = reg & MPI2_IOC_STATE_MASK;
324 		if (state == MPI2_IOC_STATE_READY) {
325 			/* Ready to go! */
326 			error = 0;
327 			break;
328 		} else if (state == MPI2_IOC_STATE_FAULT) {
329 			mpr_dprint(sc, MPR_INIT|MPR_FAULT, "IOC in fault "
330 			    "state 0x%x, resetting\n",
331 			    state & MPI2_DOORBELL_FAULT_CODE_MASK);
332 			mpr_diag_reset(sc, sleep_flags);
333 		} else if (state == MPI2_IOC_STATE_OPERATIONAL) {
334 			/* Need to take ownership */
335 			mpr_message_unit_reset(sc, sleep_flags);
336 		} else if (state == MPI2_IOC_STATE_RESET) {
337 			/* Wait a bit, IOC might be in transition */
338 			mpr_dprint(sc, MPR_INIT|MPR_FAULT,
339 			    "IOC in unexpected reset state\n");
340 		} else {
341 			mpr_dprint(sc, MPR_INIT|MPR_FAULT,
342 			    "IOC in unknown state 0x%x\n", state);
343 			error = EINVAL;
344 			break;
345 		}
346 
347 		/* Wait 50ms for things to settle down. */
348 		DELAY(50000);
349 	}
350 
351 	if (error)
352 		mpr_dprint(sc, MPR_INIT|MPR_FAULT,
353 		    "Cannot transition IOC to ready\n");
354 	mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
355 	return (error);
356 }
357 
358 static int
mpr_transition_operational(struct mpr_softc * sc)359 mpr_transition_operational(struct mpr_softc *sc)
360 {
361 	uint32_t reg, state;
362 	int error;
363 
364 	MPR_FUNCTRACE(sc);
365 
366 	error = 0;
367 	reg = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
368 	mpr_dprint(sc, MPR_INIT, "%s entered, Doorbell= 0x%x\n", __func__, reg);
369 
370 	state = reg & MPI2_IOC_STATE_MASK;
371 	if (state != MPI2_IOC_STATE_READY) {
372 		mpr_dprint(sc, MPR_INIT, "IOC not ready\n");
373 		if ((error = mpr_transition_ready(sc)) != 0) {
374 			mpr_dprint(sc, MPR_INIT|MPR_FAULT,
375 			    "failed to transition ready, exit\n");
376 			return (error);
377 		}
378 	}
379 
380 	error = mpr_send_iocinit(sc);
381 	mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
382 
383 	return (error);
384 }
385 
386 static void
mpr_resize_queues(struct mpr_softc * sc)387 mpr_resize_queues(struct mpr_softc *sc)
388 {
389 	u_int reqcr, prireqcr, maxio, sges_per_frame, chain_seg_size;
390 
391 	/*
392 	 * Size the queues. Since the reply queues always need one free
393 	 * entry, we'll deduct one reply message here.  The LSI documents
394 	 * suggest instead to add a count to the request queue, but I think
395 	 * that it's better to deduct from reply queue.
396 	 */
397 	prireqcr = MAX(1, sc->max_prireqframes);
398 	prireqcr = MIN(prireqcr, sc->facts->HighPriorityCredit);
399 
400 	reqcr = MAX(2, sc->max_reqframes);
401 	reqcr = MIN(reqcr, sc->facts->RequestCredit);
402 
403 	sc->num_reqs = prireqcr + reqcr;
404 	sc->num_prireqs = prireqcr;
405 	sc->num_replies = MIN(sc->max_replyframes + sc->max_evtframes,
406 	    sc->facts->MaxReplyDescriptorPostQueueDepth) - 1;
407 
408 	/* Store the request frame size in bytes rather than as 32bit words */
409 	sc->reqframesz = sc->facts->IOCRequestFrameSize * 4;
410 
411 	/*
412 	 * Gen3 and beyond uses the IOCMaxChainSegmentSize from IOC Facts to
413 	 * get the size of a Chain Frame.  Previous versions use the size as a
414 	 * Request Frame for the Chain Frame size.  If IOCMaxChainSegmentSize
415 	 * is 0, use the default value.  The IOCMaxChainSegmentSize is the
416 	 * number of 16-byte elelements that can fit in a Chain Frame, which is
417 	 * the size of an IEEE Simple SGE.
418 	 */
419 	if (sc->facts->MsgVersion >= MPI2_VERSION_02_05) {
420 		chain_seg_size = sc->facts->IOCMaxChainSegmentSize;
421 		if (chain_seg_size == 0)
422 			chain_seg_size = MPR_DEFAULT_CHAIN_SEG_SIZE;
423 		sc->chain_frame_size = chain_seg_size *
424 		    MPR_MAX_CHAIN_ELEMENT_SIZE;
425 	} else {
426 		sc->chain_frame_size = sc->reqframesz;
427 	}
428 
429 	/*
430 	 * Max IO Size is Page Size * the following:
431 	 * ((SGEs per frame - 1 for chain element) * Max Chain Depth)
432 	 * + 1 for no chain needed in last frame
433 	 *
434 	 * If user suggests a Max IO size to use, use the smaller of the
435 	 * user's value and the calculated value as long as the user's
436 	 * value is larger than 0. The user's value is in pages.
437 	 */
438 	sges_per_frame = sc->chain_frame_size/sizeof(MPI2_IEEE_SGE_SIMPLE64)-1;
439 	maxio = (sges_per_frame * sc->facts->MaxChainDepth + 1) * PAGE_SIZE;
440 
441 	/*
442 	 * If I/O size limitation requested then use it and pass up to CAM.
443 	 * If not, use MAXPHYS as an optimization hint, but report HW limit.
444 	 */
445 	if (sc->max_io_pages > 0) {
446 		maxio = min(maxio, sc->max_io_pages * PAGE_SIZE);
447 		sc->maxio = maxio;
448 	} else {
449 		sc->maxio = maxio;
450 		maxio = min(maxio, MAXPHYS);
451 	}
452 
453 	sc->num_chains = (maxio / PAGE_SIZE + sges_per_frame - 2) /
454 	    sges_per_frame * reqcr;
455 	if (sc->max_chains > 0 && sc->max_chains < sc->num_chains)
456 		sc->num_chains = sc->max_chains;
457 
458 	/*
459 	 * Figure out the number of MSIx-based queues.  If the firmware or
460 	 * user has done something crazy and not allowed enough credit for
461 	 * the queues to be useful then don't enable multi-queue.
462 	 */
463 	if (sc->facts->MaxMSIxVectors < 2)
464 		sc->msi_msgs = 1;
465 
466 	if (sc->msi_msgs > 1) {
467 		sc->msi_msgs = MIN(sc->msi_msgs, mp_ncpus);
468 		sc->msi_msgs = MIN(sc->msi_msgs, sc->facts->MaxMSIxVectors);
469 		if (sc->num_reqs / sc->msi_msgs < 2)
470 			sc->msi_msgs = 1;
471 	}
472 
473 	mpr_dprint(sc, MPR_INIT, "Sized queues to q=%d reqs=%d replies=%d\n",
474 	    sc->msi_msgs, sc->num_reqs, sc->num_replies);
475 }
476 
477 /*
478  * This is called during attach and when re-initializing due to a Diag Reset.
479  * IOC Facts is used to allocate many of the structures needed by the driver.
480  * If called from attach, de-allocation is not required because the driver has
481  * not allocated any structures yet, but if called from a Diag Reset, previously
482  * allocated structures based on IOC Facts will need to be freed and re-
483  * allocated bases on the latest IOC Facts.
484  */
485 static int
mpr_iocfacts_allocate(struct mpr_softc * sc,uint8_t attaching)486 mpr_iocfacts_allocate(struct mpr_softc *sc, uint8_t attaching)
487 {
488 	int error;
489 	Mpi2IOCFactsReply_t saved_facts;
490 	uint8_t saved_mode, reallocating;
491 
492 	mpr_dprint(sc, MPR_INIT|MPR_TRACE, "%s entered\n", __func__);
493 
494 	/* Save old IOC Facts and then only reallocate if Facts have changed */
495 	if (!attaching) {
496 		bcopy(sc->facts, &saved_facts, sizeof(MPI2_IOC_FACTS_REPLY));
497 	}
498 
499 	/*
500 	 * Get IOC Facts.  In all cases throughout this function, panic if doing
501 	 * a re-initialization and only return the error if attaching so the OS
502 	 * can handle it.
503 	 */
504 	if ((error = mpr_get_iocfacts(sc, sc->facts)) != 0) {
505 		if (attaching) {
506 			mpr_dprint(sc, MPR_INIT|MPR_FAULT, "Failed to get "
507 			    "IOC Facts with error %d, exit\n", error);
508 			return (error);
509 		} else {
510 			panic("%s failed to get IOC Facts with error %d\n",
511 			    __func__, error);
512 		}
513 	}
514 
515 	MPR_DPRINT_PAGE(sc, MPR_XINFO, iocfacts, sc->facts);
516 
517 	snprintf(sc->fw_version, sizeof(sc->fw_version),
518 	    "%02d.%02d.%02d.%02d",
519 	    sc->facts->FWVersion.Struct.Major,
520 	    sc->facts->FWVersion.Struct.Minor,
521 	    sc->facts->FWVersion.Struct.Unit,
522 	    sc->facts->FWVersion.Struct.Dev);
523 
524 	snprintf(sc->msg_version, sizeof(sc->msg_version), "%d.%d",
525 	    (sc->facts->MsgVersion & MPI2_IOCFACTS_MSGVERSION_MAJOR_MASK) >>
526 	    MPI2_IOCFACTS_MSGVERSION_MAJOR_SHIFT,
527 	    (sc->facts->MsgVersion & MPI2_IOCFACTS_MSGVERSION_MINOR_MASK) >>
528 	    MPI2_IOCFACTS_MSGVERSION_MINOR_SHIFT);
529 
530 	mpr_dprint(sc, MPR_INFO, "Firmware: %s, Driver: %s\n", sc->fw_version,
531 	    MPR_DRIVER_VERSION);
532 	mpr_dprint(sc, MPR_INFO,
533 	    "IOCCapabilities: %b\n", sc->facts->IOCCapabilities,
534 	    "\20" "\3ScsiTaskFull" "\4DiagTrace" "\5SnapBuf" "\6ExtBuf"
535 	    "\7EEDP" "\10BiDirTarg" "\11Multicast" "\14TransRetry" "\15IR"
536 	    "\16EventReplay" "\17RaidAccel" "\20MSIXIndex" "\21HostDisc"
537 	    "\22FastPath" "\23RDPQArray" "\24AtomicReqDesc" "\25PCIeSRIOV");
538 
539 	/*
540 	 * If the chip doesn't support event replay then a hard reset will be
541 	 * required to trigger a full discovery.  Do the reset here then
542 	 * retransition to Ready.  A hard reset might have already been done,
543 	 * but it doesn't hurt to do it again.  Only do this if attaching, not
544 	 * for a Diag Reset.
545 	 */
546 	if (attaching && ((sc->facts->IOCCapabilities &
547 	    MPI2_IOCFACTS_CAPABILITY_EVENT_REPLAY) == 0)) {
548 		mpr_dprint(sc, MPR_INIT, "No event replay, resetting\n");
549 		mpr_diag_reset(sc, NO_SLEEP);
550 		if ((error = mpr_transition_ready(sc)) != 0) {
551 			mpr_dprint(sc, MPR_INIT|MPR_FAULT, "Failed to "
552 			    "transition to ready with error %d, exit\n",
553 			    error);
554 			return (error);
555 		}
556 	}
557 
558 	/*
559 	 * Set flag if IR Firmware is loaded.  If the RAID Capability has
560 	 * changed from the previous IOC Facts, log a warning, but only if
561 	 * checking this after a Diag Reset and not during attach.
562 	 */
563 	saved_mode = sc->ir_firmware;
564 	if (sc->facts->IOCCapabilities &
565 	    MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID)
566 		sc->ir_firmware = 1;
567 	if (!attaching) {
568 		if (sc->ir_firmware != saved_mode) {
569 			mpr_dprint(sc, MPR_INIT|MPR_FAULT, "new IR/IT mode "
570 			    "in IOC Facts does not match previous mode\n");
571 		}
572 	}
573 
574 	/* Only deallocate and reallocate if relevant IOC Facts have changed */
575 	reallocating = FALSE;
576 	sc->mpr_flags &= ~MPR_FLAGS_REALLOCATED;
577 
578 	if ((!attaching) &&
579 	    ((saved_facts.MsgVersion != sc->facts->MsgVersion) ||
580 	    (saved_facts.HeaderVersion != sc->facts->HeaderVersion) ||
581 	    (saved_facts.MaxChainDepth != sc->facts->MaxChainDepth) ||
582 	    (saved_facts.RequestCredit != sc->facts->RequestCredit) ||
583 	    (saved_facts.ProductID != sc->facts->ProductID) ||
584 	    (saved_facts.IOCCapabilities != sc->facts->IOCCapabilities) ||
585 	    (saved_facts.IOCRequestFrameSize !=
586 	    sc->facts->IOCRequestFrameSize) ||
587 	    (saved_facts.IOCMaxChainSegmentSize !=
588 	    sc->facts->IOCMaxChainSegmentSize) ||
589 	    (saved_facts.MaxTargets != sc->facts->MaxTargets) ||
590 	    (saved_facts.MaxSasExpanders != sc->facts->MaxSasExpanders) ||
591 	    (saved_facts.MaxEnclosures != sc->facts->MaxEnclosures) ||
592 	    (saved_facts.HighPriorityCredit != sc->facts->HighPriorityCredit) ||
593 	    (saved_facts.MaxReplyDescriptorPostQueueDepth !=
594 	    sc->facts->MaxReplyDescriptorPostQueueDepth) ||
595 	    (saved_facts.ReplyFrameSize != sc->facts->ReplyFrameSize) ||
596 	    (saved_facts.MaxVolumes != sc->facts->MaxVolumes) ||
597 	    (saved_facts.MaxPersistentEntries !=
598 	    sc->facts->MaxPersistentEntries))) {
599 		reallocating = TRUE;
600 
601 		/* Record that we reallocated everything */
602 		sc->mpr_flags |= MPR_FLAGS_REALLOCATED;
603 	}
604 
605 	/*
606 	 * Some things should be done if attaching or re-allocating after a Diag
607 	 * Reset, but are not needed after a Diag Reset if the FW has not
608 	 * changed.
609 	 */
610 	if (attaching || reallocating) {
611 		/*
612 		 * Check if controller supports FW diag buffers and set flag to
613 		 * enable each type.
614 		 */
615 		if (sc->facts->IOCCapabilities &
616 		    MPI2_IOCFACTS_CAPABILITY_DIAG_TRACE_BUFFER)
617 			sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_TRACE].
618 			    enabled = TRUE;
619 		if (sc->facts->IOCCapabilities &
620 		    MPI2_IOCFACTS_CAPABILITY_SNAPSHOT_BUFFER)
621 			sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_SNAPSHOT].
622 			    enabled = TRUE;
623 		if (sc->facts->IOCCapabilities &
624 		    MPI2_IOCFACTS_CAPABILITY_EXTENDED_BUFFER)
625 			sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_EXTENDED].
626 			    enabled = TRUE;
627 
628 		/*
629 		 * Set flags for some supported items.
630 		 */
631 		if (sc->facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_EEDP)
632 			sc->eedp_enabled = TRUE;
633 		if (sc->facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_TLR)
634 			sc->control_TLR = TRUE;
635 		if ((sc->facts->IOCCapabilities &
636 		    MPI26_IOCFACTS_CAPABILITY_ATOMIC_REQ) &&
637 		    (sc->mpr_flags & MPR_FLAGS_SEA_IOC))
638 			sc->atomic_desc_capable = TRUE;
639 
640 		mpr_resize_queues(sc);
641 
642 		/*
643 		 * Initialize all Tail Queues
644 		 */
645 		TAILQ_INIT(&sc->req_list);
646 		TAILQ_INIT(&sc->high_priority_req_list);
647 		TAILQ_INIT(&sc->chain_list);
648 		TAILQ_INIT(&sc->prp_page_list);
649 		TAILQ_INIT(&sc->tm_list);
650 	}
651 
652 	/*
653 	 * If doing a Diag Reset and the FW is significantly different
654 	 * (reallocating will be set above in IOC Facts comparison), then all
655 	 * buffers based on the IOC Facts will need to be freed before they are
656 	 * reallocated.
657 	 */
658 	if (reallocating) {
659 		mpr_iocfacts_free(sc);
660 		mprsas_realloc_targets(sc, saved_facts.MaxTargets +
661 		    saved_facts.MaxVolumes);
662 	}
663 
664 	/*
665 	 * Any deallocation has been completed.  Now start reallocating
666 	 * if needed.  Will only need to reallocate if attaching or if the new
667 	 * IOC Facts are different from the previous IOC Facts after a Diag
668 	 * Reset. Targets have already been allocated above if needed.
669 	 */
670 	error = 0;
671 	while (attaching || reallocating) {
672 		if ((error = mpr_alloc_hw_queues(sc)) != 0)
673 			break;
674 		if ((error = mpr_alloc_replies(sc)) != 0)
675 			break;
676 		if ((error = mpr_alloc_requests(sc)) != 0)
677 			break;
678 		if ((error = mpr_alloc_queues(sc)) != 0)
679 			break;
680 		break;
681 	}
682 	if (error) {
683 		mpr_dprint(sc, MPR_INIT|MPR_ERROR,
684 		    "Failed to alloc queues with error %d\n", error);
685 		mpr_free(sc);
686 		return (error);
687 	}
688 
689 	/* Always initialize the queues */
690 	bzero(sc->free_queue, sc->fqdepth * 4);
691 	mpr_init_queues(sc);
692 
693 	/*
694 	 * Always get the chip out of the reset state, but only panic if not
695 	 * attaching.  If attaching and there is an error, that is handled by
696 	 * the OS.
697 	 */
698 	error = mpr_transition_operational(sc);
699 	if (error != 0) {
700 		mpr_dprint(sc, MPR_INIT|MPR_FAULT, "Failed to "
701 		    "transition to operational with error %d\n", error);
702 		mpr_free(sc);
703 		return (error);
704 	}
705 
706 	/*
707 	 * Finish the queue initialization.
708 	 * These are set here instead of in mpr_init_queues() because the
709 	 * IOC resets these values during the state transition in
710 	 * mpr_transition_operational().  The free index is set to 1
711 	 * because the corresponding index in the IOC is set to 0, and the
712 	 * IOC treats the queues as full if both are set to the same value.
713 	 * Hence the reason that the queue can't hold all of the possible
714 	 * replies.
715 	 */
716 	sc->replypostindex = 0;
717 	mpr_regwrite(sc, MPI2_REPLY_FREE_HOST_INDEX_OFFSET, sc->replyfreeindex);
718 	mpr_regwrite(sc, MPI2_REPLY_POST_HOST_INDEX_OFFSET, 0);
719 
720 	/*
721 	 * Attach the subsystems so they can prepare their event masks.
722 	 * XXX Should be dynamic so that IM/IR and user modules can attach
723 	 */
724 	error = 0;
725 	while (attaching) {
726 		mpr_dprint(sc, MPR_INIT, "Attaching subsystems\n");
727 		if ((error = mpr_attach_log(sc)) != 0)
728 			break;
729 		if ((error = mpr_attach_sas(sc)) != 0)
730 			break;
731 		if ((error = mpr_attach_user(sc)) != 0)
732 			break;
733 		break;
734 	}
735 	if (error) {
736 		mpr_dprint(sc, MPR_INIT|MPR_ERROR,
737 		    "Failed to attach all subsystems: error %d\n", error);
738 		mpr_free(sc);
739 		return (error);
740 	}
741 
742 	/*
743 	 * XXX If the number of MSI-X vectors changes during re-init, this
744 	 * won't see it and adjust.
745 	 */
746 	if ((attaching || reallocating) && (error = mpr_pci_setup_interrupts(sc)) != 0) {
747 		mpr_dprint(sc, MPR_INIT|MPR_ERROR,
748 		    "Failed to setup interrupts\n");
749 		mpr_free(sc);
750 		return (error);
751 	}
752 
753 	return (error);
754 }
755 
756 /*
757  * This is called if memory is being free (during detach for example) and when
758  * buffers need to be reallocated due to a Diag Reset.
759  */
760 static void
mpr_iocfacts_free(struct mpr_softc * sc)761 mpr_iocfacts_free(struct mpr_softc *sc)
762 {
763 	struct mpr_command *cm;
764 	int i;
765 
766 	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
767 
768 	if (sc->free_busaddr != 0)
769 		bus_dmamap_unload(sc->queues_dmat, sc->queues_map);
770 	if (sc->free_queue != NULL)
771 		bus_dmamem_free(sc->queues_dmat, sc->free_queue,
772 		    sc->queues_map);
773 	if (sc->queues_dmat != NULL)
774 		bus_dma_tag_destroy(sc->queues_dmat);
775 
776 	if (sc->chain_frames != NULL) {
777 		bus_dmamap_unload(sc->chain_dmat, sc->chain_map);
778 		bus_dmamem_free(sc->chain_dmat, sc->chain_frames,
779 		    sc->chain_map);
780 	}
781 	if (sc->chain_dmat != NULL)
782 		bus_dma_tag_destroy(sc->chain_dmat);
783 
784 	if (sc->sense_busaddr != 0)
785 		bus_dmamap_unload(sc->sense_dmat, sc->sense_map);
786 	if (sc->sense_frames != NULL)
787 		bus_dmamem_free(sc->sense_dmat, sc->sense_frames,
788 		    sc->sense_map);
789 	if (sc->sense_dmat != NULL)
790 		bus_dma_tag_destroy(sc->sense_dmat);
791 
792 	if (sc->prp_page_busaddr != 0)
793 		bus_dmamap_unload(sc->prp_page_dmat, sc->prp_page_map);
794 	if (sc->prp_pages != NULL)
795 		bus_dmamem_free(sc->prp_page_dmat, sc->prp_pages,
796 		    sc->prp_page_map);
797 	if (sc->prp_page_dmat != NULL)
798 		bus_dma_tag_destroy(sc->prp_page_dmat);
799 
800 	if (sc->reply_busaddr != 0)
801 		bus_dmamap_unload(sc->reply_dmat, sc->reply_map);
802 	if (sc->reply_frames != NULL)
803 		bus_dmamem_free(sc->reply_dmat, sc->reply_frames,
804 		    sc->reply_map);
805 	if (sc->reply_dmat != NULL)
806 		bus_dma_tag_destroy(sc->reply_dmat);
807 
808 	if (sc->req_busaddr != 0)
809 		bus_dmamap_unload(sc->req_dmat, sc->req_map);
810 	if (sc->req_frames != NULL)
811 		bus_dmamem_free(sc->req_dmat, sc->req_frames, sc->req_map);
812 	if (sc->req_dmat != NULL)
813 		bus_dma_tag_destroy(sc->req_dmat);
814 
815 	if (sc->chains != NULL)
816 		free(sc->chains, M_MPR);
817 	if (sc->prps != NULL)
818 		free(sc->prps, M_MPR);
819 	if (sc->commands != NULL) {
820 		for (i = 1; i < sc->num_reqs; i++) {
821 			cm = &sc->commands[i];
822 			bus_dmamap_destroy(sc->buffer_dmat, cm->cm_dmamap);
823 		}
824 		free(sc->commands, M_MPR);
825 	}
826 	if (sc->buffer_dmat != NULL)
827 		bus_dma_tag_destroy(sc->buffer_dmat);
828 
829 	mpr_pci_free_interrupts(sc);
830 	free(sc->queues, M_MPR);
831 	sc->queues = NULL;
832 }
833 
834 /*
835  * The terms diag reset and hard reset are used interchangeably in the MPI
836  * docs to mean resetting the controller chip.  In this code diag reset
837  * cleans everything up, and the hard reset function just sends the reset
838  * sequence to the chip.  This should probably be refactored so that every
839  * subsystem gets a reset notification of some sort, and can clean up
840  * appropriately.
841  */
842 int
mpr_reinit(struct mpr_softc * sc)843 mpr_reinit(struct mpr_softc *sc)
844 {
845 	int error;
846 	struct mprsas_softc *sassc;
847 
848 	sassc = sc->sassc;
849 
850 	MPR_FUNCTRACE(sc);
851 
852 	mtx_assert(&sc->mpr_mtx, MA_OWNED);
853 
854 	mpr_dprint(sc, MPR_INIT|MPR_INFO, "Reinitializing controller\n");
855 	if (sc->mpr_flags & MPR_FLAGS_DIAGRESET) {
856 		mpr_dprint(sc, MPR_INIT, "Reset already in progress\n");
857 		return 0;
858 	}
859 
860 	/*
861 	 * Make sure the completion callbacks can recognize they're getting
862 	 * a NULL cm_reply due to a reset.
863 	 */
864 	sc->mpr_flags |= MPR_FLAGS_DIAGRESET;
865 
866 	/*
867 	 * Mask interrupts here.
868 	 */
869 	mpr_dprint(sc, MPR_INIT, "Masking interrupts and resetting\n");
870 	mpr_mask_intr(sc);
871 
872 	error = mpr_diag_reset(sc, CAN_SLEEP);
873 	if (error != 0) {
874 		panic("%s hard reset failed with error %d\n", __func__, error);
875 	}
876 
877 	/* Restore the PCI state, including the MSI-X registers */
878 	mpr_pci_restore(sc);
879 
880 	/* Give the I/O subsystem special priority to get itself prepared */
881 	mprsas_handle_reinit(sc);
882 
883 	/*
884 	 * Get IOC Facts and allocate all structures based on this information.
885 	 * The attach function will also call mpr_iocfacts_allocate at startup.
886 	 * If relevant values have changed in IOC Facts, this function will free
887 	 * all of the memory based on IOC Facts and reallocate that memory.
888 	 */
889 	if ((error = mpr_iocfacts_allocate(sc, FALSE)) != 0) {
890 		panic("%s IOC Facts based allocation failed with error %d\n",
891 		    __func__, error);
892 	}
893 
894 	/*
895 	 * Mapping structures will be re-allocated after getting IOC Page8, so
896 	 * free these structures here.
897 	 */
898 	mpr_mapping_exit(sc);
899 
900 	/*
901 	 * The static page function currently read is IOC Page8.  Others can be
902 	 * added in future.  It's possible that the values in IOC Page8 have
903 	 * changed after a Diag Reset due to user modification, so always read
904 	 * these.  Interrupts are masked, so unmask them before getting config
905 	 * pages.
906 	 */
907 	mpr_unmask_intr(sc);
908 	sc->mpr_flags &= ~MPR_FLAGS_DIAGRESET;
909 	mpr_base_static_config_pages(sc);
910 
911 	/*
912 	 * Some mapping info is based in IOC Page8 data, so re-initialize the
913 	 * mapping tables.
914 	 */
915 	mpr_mapping_initialize(sc);
916 
917 	/*
918 	 * Restart will reload the event masks clobbered by the reset, and
919 	 * then enable the port.
920 	 */
921 	mpr_reregister_events(sc);
922 
923 	/* the end of discovery will release the simq, so we're done. */
924 	mpr_dprint(sc, MPR_INIT|MPR_XINFO, "Finished sc %p post %u free %u\n",
925 	    sc, sc->replypostindex, sc->replyfreeindex);
926 	mprsas_release_simq_reinit(sassc);
927 	mpr_dprint(sc, MPR_INIT, "%s exit error= %d\n", __func__, error);
928 
929 	return 0;
930 }
931 
932 /* Wait for the chip to ACK a word that we've put into its FIFO
933  * Wait for <timeout> seconds. In single loop wait for busy loop
934  * for 500 microseconds.
935  * Total is [ 0.5 * (2000 * <timeout>) ] in miliseconds.
936  * */
937 static int
mpr_wait_db_ack(struct mpr_softc * sc,int timeout,int sleep_flag)938 mpr_wait_db_ack(struct mpr_softc *sc, int timeout, int sleep_flag)
939 {
940 	u32 cntdn, count;
941 	u32 int_status;
942 	u32 doorbell;
943 
944 	count = 0;
945 	cntdn = (sleep_flag == CAN_SLEEP) ? 1000*timeout : 2000*timeout;
946 	do {
947 		int_status = mpr_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET);
948 		if (!(int_status & MPI2_HIS_SYS2IOC_DB_STATUS)) {
949 			mpr_dprint(sc, MPR_TRACE, "%s: successful count(%d), "
950 			    "timeout(%d)\n", __func__, count, timeout);
951 			return 0;
952 		} else if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
953 			doorbell = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
954 			if ((doorbell & MPI2_IOC_STATE_MASK) ==
955 			    MPI2_IOC_STATE_FAULT) {
956 				mpr_dprint(sc, MPR_FAULT,
957 				    "fault_state(0x%04x)!\n", doorbell);
958 				return (EFAULT);
959 			}
960 		} else if (int_status == 0xFFFFFFFF)
961 			goto out;
962 
963 		/*
964 		 * If it can sleep, sleep for 1 milisecond, else busy loop for
965  		 * 0.5 milisecond
966 		 */
967 		if (mtx_owned(&sc->mpr_mtx) && sleep_flag == CAN_SLEEP)
968 			msleep(&sc->msleep_fake_chan, &sc->mpr_mtx, 0, "mprdba",
969 			    hz/1000);
970 		else if (sleep_flag == CAN_SLEEP)
971 			pause("mprdba", hz/1000);
972 		else
973 			DELAY(500);
974 		count++;
975 	} while (--cntdn);
976 
977 out:
978 	mpr_dprint(sc, MPR_FAULT, "%s: failed due to timeout count(%d), "
979 		"int_status(%x)!\n", __func__, count, int_status);
980 	return (ETIMEDOUT);
981 }
982 
983 /* Wait for the chip to signal that the next word in its FIFO can be fetched */
984 static int
mpr_wait_db_int(struct mpr_softc * sc)985 mpr_wait_db_int(struct mpr_softc *sc)
986 {
987 	int retry;
988 
989 	for (retry = 0; retry < MPR_DB_MAX_WAIT; retry++) {
990 		if ((mpr_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET) &
991 		    MPI2_HIS_IOC2SYS_DB_STATUS) != 0)
992 			return (0);
993 		DELAY(2000);
994 	}
995 	return (ETIMEDOUT);
996 }
997 
998 /* Step through the synchronous command state machine, i.e. "Doorbell mode" */
999 static int
mpr_request_sync(struct mpr_softc * sc,void * req,MPI2_DEFAULT_REPLY * reply,int req_sz,int reply_sz,int timeout)1000 mpr_request_sync(struct mpr_softc *sc, void *req, MPI2_DEFAULT_REPLY *reply,
1001     int req_sz, int reply_sz, int timeout)
1002 {
1003 	uint32_t *data32;
1004 	uint16_t *data16;
1005 	int i, count, ioc_sz, residual;
1006 	int sleep_flags = CAN_SLEEP;
1007 
1008 #if __FreeBSD_version >= 1000029
1009 	if (curthread->td_no_sleeping)
1010 #else //__FreeBSD_version < 1000029
1011 	if (curthread->td_pflags & TDP_NOSLEEPING)
1012 #endif //__FreeBSD_version >= 1000029
1013 		sleep_flags = NO_SLEEP;
1014 
1015 	/* Step 1 */
1016 	mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1017 
1018 	/* Step 2 */
1019 	if (mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED)
1020 		return (EBUSY);
1021 
1022 	/* Step 3
1023 	 * Announce that a message is coming through the doorbell.  Messages
1024 	 * are pushed at 32bit words, so round up if needed.
1025 	 */
1026 	count = (req_sz + 3) / 4;
1027 	mpr_regwrite(sc, MPI2_DOORBELL_OFFSET,
1028 	    (MPI2_FUNCTION_HANDSHAKE << MPI2_DOORBELL_FUNCTION_SHIFT) |
1029 	    (count << MPI2_DOORBELL_ADD_DWORDS_SHIFT));
1030 
1031 	/* Step 4 */
1032 	if (mpr_wait_db_int(sc) ||
1033 	    (mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED) == 0) {
1034 		mpr_dprint(sc, MPR_FAULT, "Doorbell failed to activate\n");
1035 		return (ENXIO);
1036 	}
1037 	mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1038 	if (mpr_wait_db_ack(sc, 5, sleep_flags) != 0) {
1039 		mpr_dprint(sc, MPR_FAULT, "Doorbell handshake failed\n");
1040 		return (ENXIO);
1041 	}
1042 
1043 	/* Step 5 */
1044 	/* Clock out the message data synchronously in 32-bit dwords*/
1045 	data32 = (uint32_t *)req;
1046 	for (i = 0; i < count; i++) {
1047 		mpr_regwrite(sc, MPI2_DOORBELL_OFFSET, htole32(data32[i]));
1048 		if (mpr_wait_db_ack(sc, 5, sleep_flags) != 0) {
1049 			mpr_dprint(sc, MPR_FAULT,
1050 			    "Timeout while writing doorbell\n");
1051 			return (ENXIO);
1052 		}
1053 	}
1054 
1055 	/* Step 6 */
1056 	/* Clock in the reply in 16-bit words.  The total length of the
1057 	 * message is always in the 4th byte, so clock out the first 2 words
1058 	 * manually, then loop the rest.
1059 	 */
1060 	data16 = (uint16_t *)reply;
1061 	if (mpr_wait_db_int(sc) != 0) {
1062 		mpr_dprint(sc, MPR_FAULT, "Timeout reading doorbell 0\n");
1063 		return (ENXIO);
1064 	}
1065 
1066 	/*
1067 	 * If in a BE platform, swap bytes using le16toh to not
1068 	 * disturb 8 bit field neighbors in destination structure
1069 	 * pointed by data16.
1070 	 */
1071 	data16[0] =
1072 	    le16toh(mpr_regread(sc, MPI2_DOORBELL_OFFSET)) & MPI2_DOORBELL_DATA_MASK;
1073 	mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1074 	if (mpr_wait_db_int(sc) != 0) {
1075 		mpr_dprint(sc, MPR_FAULT, "Timeout reading doorbell 1\n");
1076 		return (ENXIO);
1077 	}
1078 	data16[1] =
1079 	    le16toh(mpr_regread(sc, MPI2_DOORBELL_OFFSET)) & MPI2_DOORBELL_DATA_MASK;
1080 	mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1081 
1082 	/* Number of 32bit words in the message */
1083 	ioc_sz = reply->MsgLength;
1084 
1085 	/*
1086 	 * Figure out how many 16bit words to clock in without overrunning.
1087 	 * The precision loss with dividing reply_sz can safely be
1088 	 * ignored because the messages can only be multiples of 32bits.
1089 	 */
1090 	residual = 0;
1091 	count = MIN((reply_sz / 4), ioc_sz) * 2;
1092 	if (count < ioc_sz * 2) {
1093 		residual = ioc_sz * 2 - count;
1094 		mpr_dprint(sc, MPR_ERROR, "Driver error, throwing away %d "
1095 		    "residual message words\n", residual);
1096 	}
1097 
1098 	for (i = 2; i < count; i++) {
1099 		if (mpr_wait_db_int(sc) != 0) {
1100 			mpr_dprint(sc, MPR_FAULT,
1101 			    "Timeout reading doorbell %d\n", i);
1102 			return (ENXIO);
1103 		}
1104 		data16[i] = le16toh(mpr_regread(sc, MPI2_DOORBELL_OFFSET)) &
1105 		    MPI2_DOORBELL_DATA_MASK;
1106 		mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1107 	}
1108 
1109 	/*
1110 	 * Pull out residual words that won't fit into the provided buffer.
1111 	 * This keeps the chip from hanging due to a driver programming
1112 	 * error.
1113 	 */
1114 	while (residual--) {
1115 		if (mpr_wait_db_int(sc) != 0) {
1116 			mpr_dprint(sc, MPR_FAULT, "Timeout reading doorbell\n");
1117 			return (ENXIO);
1118 		}
1119 		(void)mpr_regread(sc, MPI2_DOORBELL_OFFSET);
1120 		mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1121 	}
1122 
1123 	/* Step 7 */
1124 	if (mpr_wait_db_int(sc) != 0) {
1125 		mpr_dprint(sc, MPR_FAULT, "Timeout waiting to exit doorbell\n");
1126 		return (ENXIO);
1127 	}
1128 	if (mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED)
1129 		mpr_dprint(sc, MPR_FAULT, "Warning, doorbell still active\n");
1130 	mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1131 
1132 	return (0);
1133 }
1134 
1135 static void
mpr_enqueue_request(struct mpr_softc * sc,struct mpr_command * cm)1136 mpr_enqueue_request(struct mpr_softc *sc, struct mpr_command *cm)
1137 {
1138 	request_descriptor rd;
1139 
1140 	MPR_FUNCTRACE(sc);
1141 	mpr_dprint(sc, MPR_TRACE, "SMID %u cm %p ccb %p\n",
1142 	    cm->cm_desc.Default.SMID, cm, cm->cm_ccb);
1143 
1144 	if (sc->mpr_flags & MPR_FLAGS_ATTACH_DONE && !(sc->mpr_flags &
1145 	    MPR_FLAGS_SHUTDOWN))
1146 		mtx_assert(&sc->mpr_mtx, MA_OWNED);
1147 
1148 	if (++sc->io_cmds_active > sc->io_cmds_highwater)
1149 		sc->io_cmds_highwater++;
1150 
1151 	KASSERT(cm->cm_state == MPR_CM_STATE_BUSY, ("command not busy\n"));
1152 	cm->cm_state = MPR_CM_STATE_INQUEUE;
1153 
1154 	if (sc->atomic_desc_capable) {
1155 		rd.u.low = cm->cm_desc.Words.Low;
1156 		mpr_regwrite(sc, MPI26_ATOMIC_REQUEST_DESCRIPTOR_POST_OFFSET,
1157 		    rd.u.low);
1158 	} else {
1159 		rd.u.low = htole32(cm->cm_desc.Words.Low);
1160 		rd.u.high = htole32(cm->cm_desc.Words.High);
1161 		mpr_regwrite(sc, MPI2_REQUEST_DESCRIPTOR_POST_LOW_OFFSET,
1162 		    rd.u.low);
1163 		mpr_regwrite(sc, MPI2_REQUEST_DESCRIPTOR_POST_HIGH_OFFSET,
1164 		    rd.u.high);
1165 	}
1166 }
1167 
1168 /*
1169  * Ioc facts are read in 16 bit words and and stored with le16toh,
1170  * this takes care of proper U8 fields endianness in
1171  * MPI2_IOC_FACTS_REPLY, but we still need to swap back U16 fields.
1172  */
1173 static void
adjust_iocfacts_endianness(MPI2_IOC_FACTS_REPLY * facts)1174 adjust_iocfacts_endianness(MPI2_IOC_FACTS_REPLY *facts)
1175 {
1176 	facts->HeaderVersion = le16toh(facts->HeaderVersion);
1177 	facts->Reserved1 = le16toh(facts->Reserved1);
1178 	facts->IOCExceptions = le16toh(facts->IOCExceptions);
1179 	facts->IOCStatus = le16toh(facts->IOCStatus);
1180 	facts->IOCLogInfo = le32toh(facts->IOCLogInfo);
1181 	facts->RequestCredit = le16toh(facts->RequestCredit);
1182 	facts->ProductID = le16toh(facts->ProductID);
1183 	facts->IOCCapabilities = le32toh(facts->IOCCapabilities);
1184 	facts->IOCRequestFrameSize = le16toh(facts->IOCRequestFrameSize);
1185 	facts->IOCMaxChainSegmentSize = le16toh(facts->IOCMaxChainSegmentSize);
1186 	facts->MaxInitiators = le16toh(facts->MaxInitiators);
1187 	facts->MaxTargets = le16toh(facts->MaxTargets);
1188 	facts->MaxSasExpanders = le16toh(facts->MaxSasExpanders);
1189 	facts->MaxEnclosures = le16toh(facts->MaxEnclosures);
1190 	facts->ProtocolFlags = le16toh(facts->ProtocolFlags);
1191 	facts->HighPriorityCredit = le16toh(facts->HighPriorityCredit);
1192 	facts->MaxReplyDescriptorPostQueueDepth = le16toh(facts->MaxReplyDescriptorPostQueueDepth);
1193 	facts->MaxDevHandle = le16toh(facts->MaxDevHandle);
1194 	facts->MaxPersistentEntries = le16toh(facts->MaxPersistentEntries);
1195 	facts->MinDevHandle = le16toh(facts->MinDevHandle);
1196 }
1197 
1198 /*
1199  * Just the FACTS, ma'am.
1200  */
1201 static int
mpr_get_iocfacts(struct mpr_softc * sc,MPI2_IOC_FACTS_REPLY * facts)1202 mpr_get_iocfacts(struct mpr_softc *sc, MPI2_IOC_FACTS_REPLY *facts)
1203 {
1204 	MPI2_DEFAULT_REPLY *reply;
1205 	MPI2_IOC_FACTS_REQUEST request;
1206 	int error, req_sz, reply_sz;
1207 
1208 	MPR_FUNCTRACE(sc);
1209 	mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
1210 
1211 	req_sz = sizeof(MPI2_IOC_FACTS_REQUEST);
1212 	reply_sz = sizeof(MPI2_IOC_FACTS_REPLY);
1213 	reply = (MPI2_DEFAULT_REPLY *)facts;
1214 
1215 	bzero(&request, req_sz);
1216 	request.Function = MPI2_FUNCTION_IOC_FACTS;
1217 	error = mpr_request_sync(sc, &request, reply, req_sz, reply_sz, 5);
1218 
1219 	adjust_iocfacts_endianness(facts);
1220 	mpr_dprint(sc, MPR_TRACE, "facts->IOCCapabilities 0x%x\n", facts->IOCCapabilities);
1221 
1222 	mpr_dprint(sc, MPR_INIT, "%s exit, error= %d\n", __func__, error);
1223 	return (error);
1224 }
1225 
1226 static int
mpr_send_iocinit(struct mpr_softc * sc)1227 mpr_send_iocinit(struct mpr_softc *sc)
1228 {
1229 	MPI2_IOC_INIT_REQUEST	init;
1230 	MPI2_DEFAULT_REPLY	reply;
1231 	int req_sz, reply_sz, error;
1232 	struct timeval now;
1233 	uint64_t time_in_msec;
1234 
1235 	MPR_FUNCTRACE(sc);
1236 	mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
1237 
1238 	/* Do a quick sanity check on proper initialization */
1239 	if ((sc->pqdepth == 0) || (sc->fqdepth == 0) || (sc->reqframesz == 0)
1240 	    || (sc->replyframesz == 0)) {
1241 		mpr_dprint(sc, MPR_INIT|MPR_ERROR,
1242 		    "Driver not fully initialized for IOCInit\n");
1243 		return (EINVAL);
1244 	}
1245 
1246 	req_sz = sizeof(MPI2_IOC_INIT_REQUEST);
1247 	reply_sz = sizeof(MPI2_IOC_INIT_REPLY);
1248 	bzero(&init, req_sz);
1249 	bzero(&reply, reply_sz);
1250 
1251 	/*
1252 	 * Fill in the init block.  Note that most addresses are
1253 	 * deliberately in the lower 32bits of memory.  This is a micro-
1254 	 * optimzation for PCI/PCIX, though it's not clear if it helps PCIe.
1255 	 */
1256 	init.Function = MPI2_FUNCTION_IOC_INIT;
1257 	init.WhoInit = MPI2_WHOINIT_HOST_DRIVER;
1258 	init.MsgVersion = htole16(MPI2_VERSION);
1259 	init.HeaderVersion = htole16(MPI2_HEADER_VERSION);
1260 	init.SystemRequestFrameSize = htole16((uint16_t)(sc->reqframesz / 4));
1261 	init.ReplyDescriptorPostQueueDepth = htole16(sc->pqdepth);
1262 	init.ReplyFreeQueueDepth = htole16(sc->fqdepth);
1263 	init.SenseBufferAddressHigh = 0;
1264 	init.SystemReplyAddressHigh = 0;
1265 	init.SystemRequestFrameBaseAddress.High = 0;
1266 	init.SystemRequestFrameBaseAddress.Low =
1267 	    htole32((uint32_t)sc->req_busaddr);
1268 	init.ReplyDescriptorPostQueueAddress.High = 0;
1269 	init.ReplyDescriptorPostQueueAddress.Low =
1270 	    htole32((uint32_t)sc->post_busaddr);
1271 	init.ReplyFreeQueueAddress.High = 0;
1272 	init.ReplyFreeQueueAddress.Low = htole32((uint32_t)sc->free_busaddr);
1273 	getmicrotime(&now);
1274 	time_in_msec = (now.tv_sec * 1000 + now.tv_usec/1000);
1275 	init.TimeStamp.High = htole32((time_in_msec >> 32) & 0xFFFFFFFF);
1276 	init.TimeStamp.Low = htole32(time_in_msec & 0xFFFFFFFF);
1277 	init.HostPageSize = HOST_PAGE_SIZE_4K;
1278 
1279 	error = mpr_request_sync(sc, &init, &reply, req_sz, reply_sz, 5);
1280 	if ((le16toh(reply.IOCStatus) & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS)
1281 		error = ENXIO;
1282 
1283 	mpr_dprint(sc, MPR_INIT, "IOCInit status= 0x%x\n", le16toh(reply.IOCStatus));
1284 	mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
1285 	return (error);
1286 }
1287 
1288 void
mpr_memaddr_cb(void * arg,bus_dma_segment_t * segs,int nsegs,int error)1289 mpr_memaddr_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1290 {
1291 	bus_addr_t *addr;
1292 
1293 	addr = arg;
1294 	*addr = segs[0].ds_addr;
1295 }
1296 
1297 void
mpr_memaddr_wait_cb(void * arg,bus_dma_segment_t * segs,int nsegs,int error)1298 mpr_memaddr_wait_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1299 {
1300 	struct mpr_busdma_context *ctx;
1301 	int need_unload, need_free;
1302 
1303 	ctx = (struct mpr_busdma_context *)arg;
1304 	need_unload = 0;
1305 	need_free = 0;
1306 
1307 	mpr_lock(ctx->softc);
1308 	ctx->error = error;
1309 	ctx->completed = 1;
1310 	if ((error == 0) && (ctx->abandoned == 0)) {
1311 		*ctx->addr = segs[0].ds_addr;
1312 	} else {
1313 		if (nsegs != 0)
1314 			need_unload = 1;
1315 		if (ctx->abandoned != 0)
1316 			need_free = 1;
1317 	}
1318 	if (need_free == 0)
1319 		wakeup(ctx);
1320 
1321 	mpr_unlock(ctx->softc);
1322 
1323 	if (need_unload != 0) {
1324 		bus_dmamap_unload(ctx->buffer_dmat,
1325 				  ctx->buffer_dmamap);
1326 		*ctx->addr = 0;
1327 	}
1328 
1329 	if (need_free != 0)
1330 		free(ctx, M_MPR);
1331 }
1332 
1333 static int
mpr_alloc_queues(struct mpr_softc * sc)1334 mpr_alloc_queues(struct mpr_softc *sc)
1335 {
1336 	struct mpr_queue *q;
1337 	int nq, i;
1338 
1339 	nq = sc->msi_msgs;
1340 	mpr_dprint(sc, MPR_INIT|MPR_XINFO, "Allocating %d I/O queues\n", nq);
1341 
1342 	sc->queues = malloc(sizeof(struct mpr_queue) * nq, M_MPR,
1343 	     M_NOWAIT|M_ZERO);
1344 	if (sc->queues == NULL)
1345 		return (ENOMEM);
1346 
1347 	for (i = 0; i < nq; i++) {
1348 		q = &sc->queues[i];
1349 		mpr_dprint(sc, MPR_INIT, "Configuring queue %d %p\n", i, q);
1350 		q->sc = sc;
1351 		q->qnum = i;
1352 	}
1353 	return (0);
1354 }
1355 
1356 static int
mpr_alloc_hw_queues(struct mpr_softc * sc)1357 mpr_alloc_hw_queues(struct mpr_softc *sc)
1358 {
1359 	bus_addr_t queues_busaddr;
1360 	uint8_t *queues;
1361 	int qsize, fqsize, pqsize;
1362 
1363 	/*
1364 	 * The reply free queue contains 4 byte entries in multiples of 16 and
1365 	 * aligned on a 16 byte boundary. There must always be an unused entry.
1366 	 * This queue supplies fresh reply frames for the firmware to use.
1367 	 *
1368 	 * The reply descriptor post queue contains 8 byte entries in
1369 	 * multiples of 16 and aligned on a 16 byte boundary.  This queue
1370 	 * contains filled-in reply frames sent from the firmware to the host.
1371 	 *
1372 	 * These two queues are allocated together for simplicity.
1373 	 */
1374 	sc->fqdepth = roundup2(sc->num_replies + 1, 16);
1375 	sc->pqdepth = roundup2(sc->num_replies + 1, 16);
1376 	fqsize= sc->fqdepth * 4;
1377 	pqsize = sc->pqdepth * 8;
1378 	qsize = fqsize + pqsize;
1379 
1380         if (bus_dma_tag_create( sc->mpr_parent_dmat,    /* parent */
1381 				16, 0,			/* algnmnt, boundary */
1382 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1383 				BUS_SPACE_MAXADDR,	/* highaddr */
1384 				NULL, NULL,		/* filter, filterarg */
1385                                 qsize,			/* maxsize */
1386                                 1,			/* nsegments */
1387                                 qsize,			/* maxsegsize */
1388                                 0,			/* flags */
1389                                 NULL, NULL,		/* lockfunc, lockarg */
1390                                 &sc->queues_dmat)) {
1391 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate queues DMA tag\n");
1392 		return (ENOMEM);
1393         }
1394         if (bus_dmamem_alloc(sc->queues_dmat, (void **)&queues, BUS_DMA_NOWAIT,
1395 	    &sc->queues_map)) {
1396 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate queues memory\n");
1397 		return (ENOMEM);
1398         }
1399         bzero(queues, qsize);
1400         bus_dmamap_load(sc->queues_dmat, sc->queues_map, queues, qsize,
1401 	    mpr_memaddr_cb, &queues_busaddr, 0);
1402 
1403 	sc->free_queue = (uint32_t *)queues;
1404 	sc->free_busaddr = queues_busaddr;
1405 	sc->post_queue = (MPI2_REPLY_DESCRIPTORS_UNION *)(queues + fqsize);
1406 	sc->post_busaddr = queues_busaddr + fqsize;
1407 	mpr_dprint(sc, MPR_INIT, "free queue busaddr= %#016jx size= %d\n",
1408 	    (uintmax_t)sc->free_busaddr, fqsize);
1409 	mpr_dprint(sc, MPR_INIT, "reply queue busaddr= %#016jx size= %d\n",
1410 	    (uintmax_t)sc->post_busaddr, pqsize);
1411 
1412 	return (0);
1413 }
1414 
1415 static int
mpr_alloc_replies(struct mpr_softc * sc)1416 mpr_alloc_replies(struct mpr_softc *sc)
1417 {
1418 	int rsize, num_replies;
1419 
1420 	/* Store the reply frame size in bytes rather than as 32bit words */
1421 	sc->replyframesz = sc->facts->ReplyFrameSize * 4;
1422 
1423 	/*
1424 	 * sc->num_replies should be one less than sc->fqdepth.  We need to
1425 	 * allocate space for sc->fqdepth replies, but only sc->num_replies
1426 	 * replies can be used at once.
1427 	 */
1428 	num_replies = max(sc->fqdepth, sc->num_replies);
1429 
1430 	rsize = sc->replyframesz * num_replies;
1431         if (bus_dma_tag_create( sc->mpr_parent_dmat,    /* parent */
1432 				4, 0,			/* algnmnt, boundary */
1433 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1434 				BUS_SPACE_MAXADDR,	/* highaddr */
1435 				NULL, NULL,		/* filter, filterarg */
1436                                 rsize,			/* maxsize */
1437                                 1,			/* nsegments */
1438                                 rsize,			/* maxsegsize */
1439                                 0,			/* flags */
1440                                 NULL, NULL,		/* lockfunc, lockarg */
1441                                 &sc->reply_dmat)) {
1442 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate replies DMA tag\n");
1443 		return (ENOMEM);
1444         }
1445         if (bus_dmamem_alloc(sc->reply_dmat, (void **)&sc->reply_frames,
1446 	    BUS_DMA_NOWAIT, &sc->reply_map)) {
1447 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate replies memory\n");
1448 		return (ENOMEM);
1449         }
1450         bzero(sc->reply_frames, rsize);
1451         bus_dmamap_load(sc->reply_dmat, sc->reply_map, sc->reply_frames, rsize,
1452 	    mpr_memaddr_cb, &sc->reply_busaddr, 0);
1453 	mpr_dprint(sc, MPR_INIT, "reply frames busaddr= %#016jx size= %d\n",
1454 	    (uintmax_t)sc->reply_busaddr, rsize);
1455 
1456 	return (0);
1457 }
1458 
1459 static void
mpr_load_chains_cb(void * arg,bus_dma_segment_t * segs,int nsegs,int error)1460 mpr_load_chains_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1461 {
1462 	struct mpr_softc *sc = arg;
1463 	struct mpr_chain *chain;
1464 	bus_size_t bo;
1465 	int i, o, s;
1466 
1467 	if (error != 0)
1468 		return;
1469 
1470 	for (i = 0, o = 0, s = 0; s < nsegs; s++) {
1471 		for (bo = 0; bo + sc->chain_frame_size <= segs[s].ds_len;
1472 		    bo += sc->chain_frame_size) {
1473 			chain = &sc->chains[i++];
1474 			chain->chain =(MPI2_SGE_IO_UNION *)(sc->chain_frames+o);
1475 			chain->chain_busaddr = segs[s].ds_addr + bo;
1476 			o += sc->chain_frame_size;
1477 			mpr_free_chain(sc, chain);
1478 		}
1479 		if (bo != segs[s].ds_len)
1480 			o += segs[s].ds_len - bo;
1481 	}
1482 	sc->chain_free_lowwater = i;
1483 }
1484 
1485 static int
mpr_alloc_requests(struct mpr_softc * sc)1486 mpr_alloc_requests(struct mpr_softc *sc)
1487 {
1488 	struct mpr_command *cm;
1489 	int i, rsize, nsegs;
1490 
1491 	rsize = sc->reqframesz * sc->num_reqs;
1492         if (bus_dma_tag_create( sc->mpr_parent_dmat,    /* parent */
1493 				16, 0,			/* algnmnt, boundary */
1494 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1495 				BUS_SPACE_MAXADDR,	/* highaddr */
1496 				NULL, NULL,		/* filter, filterarg */
1497                                 rsize,			/* maxsize */
1498                                 1,			/* nsegments */
1499                                 rsize,			/* maxsegsize */
1500                                 0,			/* flags */
1501                                 NULL, NULL,		/* lockfunc, lockarg */
1502                                 &sc->req_dmat)) {
1503 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate request DMA tag\n");
1504 		return (ENOMEM);
1505         }
1506         if (bus_dmamem_alloc(sc->req_dmat, (void **)&sc->req_frames,
1507 	    BUS_DMA_NOWAIT, &sc->req_map)) {
1508 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate request memory\n");
1509 		return (ENOMEM);
1510         }
1511         bzero(sc->req_frames, rsize);
1512         bus_dmamap_load(sc->req_dmat, sc->req_map, sc->req_frames, rsize,
1513 	    mpr_memaddr_cb, &sc->req_busaddr, 0);
1514 	mpr_dprint(sc, MPR_INIT, "request frames busaddr= %#016jx size= %d\n",
1515 	    (uintmax_t)sc->req_busaddr, rsize);
1516 
1517 	sc->chains = malloc(sizeof(struct mpr_chain) * sc->num_chains, M_MPR,
1518 	    M_NOWAIT | M_ZERO);
1519 	if (!sc->chains) {
1520 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate chain memory\n");
1521 		return (ENOMEM);
1522 	}
1523 	rsize = sc->chain_frame_size * sc->num_chains;
1524 	if (bus_dma_tag_create( sc->mpr_parent_dmat,	/* parent */
1525 				16, 0,			/* algnmnt, boundary */
1526 				BUS_SPACE_MAXADDR,	/* lowaddr */
1527 				BUS_SPACE_MAXADDR,	/* highaddr */
1528 				NULL, NULL,		/* filter, filterarg */
1529 				rsize,			/* maxsize */
1530 				howmany(rsize, PAGE_SIZE), /* nsegments */
1531 				rsize,			/* maxsegsize */
1532 				0,			/* flags */
1533 				NULL, NULL,		/* lockfunc, lockarg */
1534 				&sc->chain_dmat)) {
1535 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate chain DMA tag\n");
1536 		return (ENOMEM);
1537 	}
1538 	if (bus_dmamem_alloc(sc->chain_dmat, (void **)&sc->chain_frames,
1539 	    BUS_DMA_NOWAIT | BUS_DMA_ZERO, &sc->chain_map)) {
1540 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate chain memory\n");
1541 		return (ENOMEM);
1542 	}
1543 	if (bus_dmamap_load(sc->chain_dmat, sc->chain_map, sc->chain_frames,
1544 	    rsize, mpr_load_chains_cb, sc, BUS_DMA_NOWAIT)) {
1545 		mpr_dprint(sc, MPR_ERROR, "Cannot load chain memory\n");
1546 		bus_dmamem_free(sc->chain_dmat, sc->chain_frames,
1547 		    sc->chain_map);
1548 		return (ENOMEM);
1549 	}
1550 
1551 	rsize = MPR_SENSE_LEN * sc->num_reqs;
1552 	if (bus_dma_tag_create( sc->mpr_parent_dmat,    /* parent */
1553 				1, 0,			/* algnmnt, boundary */
1554 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1555 				BUS_SPACE_MAXADDR,	/* highaddr */
1556 				NULL, NULL,		/* filter, filterarg */
1557                                 rsize,			/* maxsize */
1558                                 1,			/* nsegments */
1559                                 rsize,			/* maxsegsize */
1560                                 0,			/* flags */
1561                                 NULL, NULL,		/* lockfunc, lockarg */
1562                                 &sc->sense_dmat)) {
1563 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate sense DMA tag\n");
1564 		return (ENOMEM);
1565         }
1566         if (bus_dmamem_alloc(sc->sense_dmat, (void **)&sc->sense_frames,
1567 	    BUS_DMA_NOWAIT, &sc->sense_map)) {
1568 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate sense memory\n");
1569 		return (ENOMEM);
1570         }
1571         bzero(sc->sense_frames, rsize);
1572         bus_dmamap_load(sc->sense_dmat, sc->sense_map, sc->sense_frames, rsize,
1573 	    mpr_memaddr_cb, &sc->sense_busaddr, 0);
1574 	mpr_dprint(sc, MPR_INIT, "sense frames busaddr= %#016jx size= %d\n",
1575 	    (uintmax_t)sc->sense_busaddr, rsize);
1576 
1577 	/*
1578 	 * Allocate NVMe PRP Pages for NVMe SGL support only if the FW supports
1579 	 * these devices.
1580 	 */
1581 	if ((sc->facts->MsgVersion >= MPI2_VERSION_02_06) &&
1582 	    (sc->facts->ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_NVME_DEVICES)) {
1583 		if (mpr_alloc_nvme_prp_pages(sc) == ENOMEM)
1584 			return (ENOMEM);
1585 	}
1586 
1587 	nsegs = (sc->maxio / PAGE_SIZE) + 1;
1588         if (bus_dma_tag_create( sc->mpr_parent_dmat,    /* parent */
1589 				1, 0,			/* algnmnt, boundary */
1590 				BUS_SPACE_MAXADDR,	/* lowaddr */
1591 				BUS_SPACE_MAXADDR,	/* highaddr */
1592 				NULL, NULL,		/* filter, filterarg */
1593                                 BUS_SPACE_MAXSIZE_32BIT,/* maxsize */
1594                                 nsegs,			/* nsegments */
1595                                 BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
1596                                 BUS_DMA_ALLOCNOW,	/* flags */
1597                                 busdma_lock_mutex,	/* lockfunc */
1598 				&sc->mpr_mtx,		/* lockarg */
1599                                 &sc->buffer_dmat)) {
1600 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate buffer DMA tag\n");
1601 		return (ENOMEM);
1602         }
1603 
1604 	/*
1605 	 * SMID 0 cannot be used as a free command per the firmware spec.
1606 	 * Just drop that command instead of risking accounting bugs.
1607 	 */
1608 	sc->commands = malloc(sizeof(struct mpr_command) * sc->num_reqs,
1609 	    M_MPR, M_WAITOK | M_ZERO);
1610 	for (i = 1; i < sc->num_reqs; i++) {
1611 		cm = &sc->commands[i];
1612 		cm->cm_req = sc->req_frames + i * sc->reqframesz;
1613 		cm->cm_req_busaddr = sc->req_busaddr + i * sc->reqframesz;
1614 		cm->cm_sense = &sc->sense_frames[i];
1615 		cm->cm_sense_busaddr = sc->sense_busaddr + i * MPR_SENSE_LEN;
1616 		cm->cm_desc.Default.SMID = htole16(i);
1617 		cm->cm_sc = sc;
1618 		cm->cm_state = MPR_CM_STATE_BUSY;
1619 		TAILQ_INIT(&cm->cm_chain_list);
1620 		TAILQ_INIT(&cm->cm_prp_page_list);
1621 		callout_init_mtx(&cm->cm_callout, &sc->mpr_mtx, 0);
1622 
1623 		/* XXX Is a failure here a critical problem? */
1624 		if (bus_dmamap_create(sc->buffer_dmat, 0, &cm->cm_dmamap)
1625 		    == 0) {
1626 			if (i <= sc->num_prireqs)
1627 				mpr_free_high_priority_command(sc, cm);
1628 			else
1629 				mpr_free_command(sc, cm);
1630 		} else {
1631 			panic("failed to allocate command %d\n", i);
1632 			sc->num_reqs = i;
1633 			break;
1634 		}
1635 	}
1636 
1637 	return (0);
1638 }
1639 
1640 /*
1641  * Allocate contiguous buffers for PCIe NVMe devices for building native PRPs,
1642  * which are scatter/gather lists for NVMe devices.
1643  *
1644  * This buffer must be contiguous due to the nature of how NVMe PRPs are built
1645  * and translated by FW.
1646  *
1647  * returns ENOMEM if memory could not be allocated, otherwise returns 0.
1648  */
1649 static int
mpr_alloc_nvme_prp_pages(struct mpr_softc * sc)1650 mpr_alloc_nvme_prp_pages(struct mpr_softc *sc)
1651 {
1652 	int PRPs_per_page, PRPs_required, pages_required;
1653 	int rsize, i;
1654 	struct mpr_prp_page *prp_page;
1655 
1656 	/*
1657 	 * Assuming a MAX_IO_SIZE of 1MB and a PAGE_SIZE of 4k, the max number
1658 	 * of PRPs (NVMe's Scatter/Gather Element) needed per I/O is:
1659 	 * MAX_IO_SIZE / PAGE_SIZE = 256
1660 	 *
1661 	 * 1 PRP entry in main frame for PRP list pointer still leaves 255 PRPs
1662 	 * required for the remainder of the 1MB I/O. 512 PRPs can fit into one
1663 	 * page (4096 / 8 = 512), so only one page is required for each I/O.
1664 	 *
1665 	 * Each of these buffers will need to be contiguous. For simplicity,
1666 	 * only one buffer is allocated here, which has all of the space
1667 	 * required for the NVMe Queue Depth. If there are problems allocating
1668 	 * this one buffer, this function will need to change to allocate
1669 	 * individual, contiguous NVME_QDEPTH buffers.
1670 	 *
1671 	 * The real calculation will use the real max io size. Above is just an
1672 	 * example.
1673 	 *
1674 	 */
1675 	PRPs_required = sc->maxio / PAGE_SIZE;
1676 	PRPs_per_page = (PAGE_SIZE / PRP_ENTRY_SIZE) - 1;
1677 	pages_required = (PRPs_required / PRPs_per_page) + 1;
1678 
1679 	sc->prp_buffer_size = PAGE_SIZE * pages_required;
1680 	rsize = sc->prp_buffer_size * NVME_QDEPTH;
1681 	if (bus_dma_tag_create( sc->mpr_parent_dmat,	/* parent */
1682 				4, 0,			/* algnmnt, boundary */
1683 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1684 				BUS_SPACE_MAXADDR,	/* highaddr */
1685 				NULL, NULL,		/* filter, filterarg */
1686 				rsize,			/* maxsize */
1687 				1,			/* nsegments */
1688 				rsize,			/* maxsegsize */
1689 				0,			/* flags */
1690 				NULL, NULL,		/* lockfunc, lockarg */
1691 				&sc->prp_page_dmat)) {
1692 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate NVMe PRP DMA "
1693 		    "tag\n");
1694 		return (ENOMEM);
1695 	}
1696 	if (bus_dmamem_alloc(sc->prp_page_dmat, (void **)&sc->prp_pages,
1697 	    BUS_DMA_NOWAIT, &sc->prp_page_map)) {
1698 		mpr_dprint(sc, MPR_ERROR, "Cannot allocate NVMe PRP memory\n");
1699 		return (ENOMEM);
1700 	}
1701 	bzero(sc->prp_pages, rsize);
1702 	bus_dmamap_load(sc->prp_page_dmat, sc->prp_page_map, sc->prp_pages,
1703 	    rsize, mpr_memaddr_cb, &sc->prp_page_busaddr, 0);
1704 
1705 	sc->prps = malloc(sizeof(struct mpr_prp_page) * NVME_QDEPTH, M_MPR,
1706 	    M_WAITOK | M_ZERO);
1707 	for (i = 0; i < NVME_QDEPTH; i++) {
1708 		prp_page = &sc->prps[i];
1709 		prp_page->prp_page = (uint64_t *)(sc->prp_pages +
1710 		    i * sc->prp_buffer_size);
1711 		prp_page->prp_page_busaddr = (uint64_t)(sc->prp_page_busaddr +
1712 		    i * sc->prp_buffer_size);
1713 		mpr_free_prp_page(sc, prp_page);
1714 		sc->prp_pages_free_lowwater++;
1715 	}
1716 
1717 	return (0);
1718 }
1719 
1720 static int
mpr_init_queues(struct mpr_softc * sc)1721 mpr_init_queues(struct mpr_softc *sc)
1722 {
1723 	int i;
1724 
1725 	memset((uint8_t *)sc->post_queue, 0xff, sc->pqdepth * 8);
1726 
1727 	/*
1728 	 * According to the spec, we need to use one less reply than we
1729 	 * have space for on the queue.  So sc->num_replies (the number we
1730 	 * use) should be less than sc->fqdepth (allocated size).
1731 	 */
1732 	if (sc->num_replies >= sc->fqdepth)
1733 		return (EINVAL);
1734 
1735 	/*
1736 	 * Initialize all of the free queue entries.
1737 	 */
1738 	for (i = 0; i < sc->fqdepth; i++) {
1739 		sc->free_queue[i] = htole32(sc->reply_busaddr + (i * sc->replyframesz));
1740 	}
1741 	sc->replyfreeindex = sc->num_replies;
1742 
1743 	return (0);
1744 }
1745 
1746 /* Get the driver parameter tunables.  Lowest priority are the driver defaults.
1747  * Next are the global settings, if they exist.  Highest are the per-unit
1748  * settings, if they exist.
1749  */
1750 void
mpr_get_tunables(struct mpr_softc * sc)1751 mpr_get_tunables(struct mpr_softc *sc)
1752 {
1753 	char tmpstr[80], mpr_debug[80];
1754 
1755 	/* XXX default to some debugging for now */
1756 	sc->mpr_debug = MPR_INFO | MPR_FAULT;
1757 	sc->disable_msix = 0;
1758 	sc->disable_msi = 0;
1759 	sc->max_msix = MPR_MSIX_MAX;
1760 	sc->max_chains = MPR_CHAIN_FRAMES;
1761 	sc->max_io_pages = MPR_MAXIO_PAGES;
1762 	sc->enable_ssu = MPR_SSU_ENABLE_SSD_DISABLE_HDD;
1763 	sc->spinup_wait_time = DEFAULT_SPINUP_WAIT;
1764 	sc->use_phynum = 1;
1765 	sc->max_reqframes = MPR_REQ_FRAMES;
1766 	sc->max_prireqframes = MPR_PRI_REQ_FRAMES;
1767 	sc->max_replyframes = MPR_REPLY_FRAMES;
1768 	sc->max_evtframes = MPR_EVT_REPLY_FRAMES;
1769 
1770 	/*
1771 	 * Grab the global variables.
1772 	 */
1773 	bzero(mpr_debug, 80);
1774 	if (TUNABLE_STR_FETCH("hw.mpr.debug_level", mpr_debug, 80) != 0)
1775 		mpr_parse_debug(sc, mpr_debug);
1776 	TUNABLE_INT_FETCH("hw.mpr.disable_msix", &sc->disable_msix);
1777 	TUNABLE_INT_FETCH("hw.mpr.disable_msi", &sc->disable_msi);
1778 	TUNABLE_INT_FETCH("hw.mpr.max_msix", &sc->max_msix);
1779 	TUNABLE_INT_FETCH("hw.mpr.max_chains", &sc->max_chains);
1780 	TUNABLE_INT_FETCH("hw.mpr.max_io_pages", &sc->max_io_pages);
1781 	TUNABLE_INT_FETCH("hw.mpr.enable_ssu", &sc->enable_ssu);
1782 	TUNABLE_INT_FETCH("hw.mpr.spinup_wait_time", &sc->spinup_wait_time);
1783 	TUNABLE_INT_FETCH("hw.mpr.use_phy_num", &sc->use_phynum);
1784 	TUNABLE_INT_FETCH("hw.mpr.max_reqframes", &sc->max_reqframes);
1785 	TUNABLE_INT_FETCH("hw.mpr.max_prireqframes", &sc->max_prireqframes);
1786 	TUNABLE_INT_FETCH("hw.mpr.max_replyframes", &sc->max_replyframes);
1787 	TUNABLE_INT_FETCH("hw.mpr.max_evtframes", &sc->max_evtframes);
1788 
1789 	/* Grab the unit-instance variables */
1790 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.debug_level",
1791 	    device_get_unit(sc->mpr_dev));
1792 	bzero(mpr_debug, 80);
1793 	if (TUNABLE_STR_FETCH(tmpstr, mpr_debug, 80) != 0)
1794 		mpr_parse_debug(sc, mpr_debug);
1795 
1796 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.disable_msix",
1797 	    device_get_unit(sc->mpr_dev));
1798 	TUNABLE_INT_FETCH(tmpstr, &sc->disable_msix);
1799 
1800 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.disable_msi",
1801 	    device_get_unit(sc->mpr_dev));
1802 	TUNABLE_INT_FETCH(tmpstr, &sc->disable_msi);
1803 
1804 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_msix",
1805 	    device_get_unit(sc->mpr_dev));
1806 	TUNABLE_INT_FETCH(tmpstr, &sc->max_msix);
1807 
1808 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_chains",
1809 	    device_get_unit(sc->mpr_dev));
1810 	TUNABLE_INT_FETCH(tmpstr, &sc->max_chains);
1811 
1812 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_io_pages",
1813 	    device_get_unit(sc->mpr_dev));
1814 	TUNABLE_INT_FETCH(tmpstr, &sc->max_io_pages);
1815 
1816 	bzero(sc->exclude_ids, sizeof(sc->exclude_ids));
1817 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.exclude_ids",
1818 	    device_get_unit(sc->mpr_dev));
1819 	TUNABLE_STR_FETCH(tmpstr, sc->exclude_ids, sizeof(sc->exclude_ids));
1820 
1821 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.enable_ssu",
1822 	    device_get_unit(sc->mpr_dev));
1823 	TUNABLE_INT_FETCH(tmpstr, &sc->enable_ssu);
1824 
1825 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.spinup_wait_time",
1826 	    device_get_unit(sc->mpr_dev));
1827 	TUNABLE_INT_FETCH(tmpstr, &sc->spinup_wait_time);
1828 
1829 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.use_phy_num",
1830 	    device_get_unit(sc->mpr_dev));
1831 	TUNABLE_INT_FETCH(tmpstr, &sc->use_phynum);
1832 
1833 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_reqframes",
1834 	    device_get_unit(sc->mpr_dev));
1835 	TUNABLE_INT_FETCH(tmpstr, &sc->max_reqframes);
1836 
1837 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_prireqframes",
1838 	    device_get_unit(sc->mpr_dev));
1839 	TUNABLE_INT_FETCH(tmpstr, &sc->max_prireqframes);
1840 
1841 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_replyframes",
1842 	    device_get_unit(sc->mpr_dev));
1843 	TUNABLE_INT_FETCH(tmpstr, &sc->max_replyframes);
1844 
1845 	snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_evtframes",
1846 	    device_get_unit(sc->mpr_dev));
1847 	TUNABLE_INT_FETCH(tmpstr, &sc->max_evtframes);
1848 }
1849 
1850 static void
mpr_setup_sysctl(struct mpr_softc * sc)1851 mpr_setup_sysctl(struct mpr_softc *sc)
1852 {
1853 	struct sysctl_ctx_list	*sysctl_ctx = NULL;
1854 	struct sysctl_oid	*sysctl_tree = NULL;
1855 	char tmpstr[80], tmpstr2[80];
1856 
1857 	/*
1858 	 * Setup the sysctl variable so the user can change the debug level
1859 	 * on the fly.
1860 	 */
1861 	snprintf(tmpstr, sizeof(tmpstr), "MPR controller %d",
1862 	    device_get_unit(sc->mpr_dev));
1863 	snprintf(tmpstr2, sizeof(tmpstr2), "%d", device_get_unit(sc->mpr_dev));
1864 
1865 	sysctl_ctx = device_get_sysctl_ctx(sc->mpr_dev);
1866 	if (sysctl_ctx != NULL)
1867 		sysctl_tree = device_get_sysctl_tree(sc->mpr_dev);
1868 
1869 	if (sysctl_tree == NULL) {
1870 		sysctl_ctx_init(&sc->sysctl_ctx);
1871 		sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
1872 		    SYSCTL_STATIC_CHILDREN(_hw_mpr), OID_AUTO, tmpstr2,
1873 		    CTLFLAG_RD, 0, tmpstr);
1874 		if (sc->sysctl_tree == NULL)
1875 			return;
1876 		sysctl_ctx = &sc->sysctl_ctx;
1877 		sysctl_tree = sc->sysctl_tree;
1878 	}
1879 
1880 	SYSCTL_ADD_PROC(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1881 	    OID_AUTO, "debug_level", CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
1882 	    sc, 0, mpr_debug_sysctl, "A", "mpr debug level");
1883 
1884 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1885 	    OID_AUTO, "disable_msix", CTLFLAG_RD, &sc->disable_msix, 0,
1886 	    "Disable the use of MSI-X interrupts");
1887 
1888 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1889 	    OID_AUTO, "max_msix", CTLFLAG_RD, &sc->max_msix, 0,
1890 	    "User-defined maximum number of MSIX queues");
1891 
1892 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1893 	    OID_AUTO, "msix_msgs", CTLFLAG_RD, &sc->msi_msgs, 0,
1894 	    "Negotiated number of MSIX queues");
1895 
1896 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1897 	    OID_AUTO, "max_reqframes", CTLFLAG_RD, &sc->max_reqframes, 0,
1898 	    "Total number of allocated request frames");
1899 
1900 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1901 	    OID_AUTO, "max_prireqframes", CTLFLAG_RD, &sc->max_prireqframes, 0,
1902 	    "Total number of allocated high priority request frames");
1903 
1904 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1905 	    OID_AUTO, "max_replyframes", CTLFLAG_RD, &sc->max_replyframes, 0,
1906 	    "Total number of allocated reply frames");
1907 
1908 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1909 	    OID_AUTO, "max_evtframes", CTLFLAG_RD, &sc->max_evtframes, 0,
1910 	    "Total number of event frames allocated");
1911 
1912 	SYSCTL_ADD_STRING(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1913 	    OID_AUTO, "firmware_version", CTLFLAG_RD, sc->fw_version,
1914 	    strlen(sc->fw_version), "firmware version");
1915 
1916 	SYSCTL_ADD_STRING(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1917 	    OID_AUTO, "driver_version", CTLFLAG_RD, MPR_DRIVER_VERSION,
1918 	    strlen(MPR_DRIVER_VERSION), "driver version");
1919 
1920 	SYSCTL_ADD_STRING(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1921 	    OID_AUTO, "msg_version", CTLFLAG_RD, sc->msg_version,
1922 	    strlen(sc->msg_version), "message interface version (deprecated)");
1923 
1924 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1925 	    OID_AUTO, "io_cmds_active", CTLFLAG_RD,
1926 	    &sc->io_cmds_active, 0, "number of currently active commands");
1927 
1928 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1929 	    OID_AUTO, "io_cmds_highwater", CTLFLAG_RD,
1930 	    &sc->io_cmds_highwater, 0, "maximum active commands seen");
1931 
1932 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1933 	    OID_AUTO, "chain_free", CTLFLAG_RD,
1934 	    &sc->chain_free, 0, "number of free chain elements");
1935 
1936 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1937 	    OID_AUTO, "chain_free_lowwater", CTLFLAG_RD,
1938 	    &sc->chain_free_lowwater, 0,"lowest number of free chain elements");
1939 
1940 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1941 	    OID_AUTO, "max_chains", CTLFLAG_RD,
1942 	    &sc->max_chains, 0,"maximum chain frames that will be allocated");
1943 
1944 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1945 	    OID_AUTO, "max_io_pages", CTLFLAG_RD,
1946 	    &sc->max_io_pages, 0,"maximum pages to allow per I/O (if <1 use "
1947 	    "IOCFacts)");
1948 
1949 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1950 	    OID_AUTO, "enable_ssu", CTLFLAG_RW, &sc->enable_ssu, 0,
1951 	    "enable SSU to SATA SSD/HDD at shutdown");
1952 
1953 	SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1954 	    OID_AUTO, "chain_alloc_fail", CTLFLAG_RD,
1955 	    &sc->chain_alloc_fail, "chain allocation failures");
1956 
1957 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1958 	    OID_AUTO, "spinup_wait_time", CTLFLAG_RD,
1959 	    &sc->spinup_wait_time, DEFAULT_SPINUP_WAIT, "seconds to wait for "
1960 	    "spinup after SATA ID error");
1961 
1962 	SYSCTL_ADD_PROC(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1963 	    OID_AUTO, "dump_reqs", CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_SKIP, sc, 0,
1964 	    mpr_dump_reqs, "I", "Dump Active Requests");
1965 
1966 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1967 	    OID_AUTO, "use_phy_num", CTLFLAG_RD, &sc->use_phynum, 0,
1968 	    "Use the phy number for enumeration");
1969 
1970 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1971 	    OID_AUTO, "prp_pages_free", CTLFLAG_RD,
1972 	    &sc->prp_pages_free, 0, "number of free PRP pages");
1973 
1974 	SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1975 	    OID_AUTO, "prp_pages_free_lowwater", CTLFLAG_RD,
1976 	    &sc->prp_pages_free_lowwater, 0,"lowest number of free PRP pages");
1977 
1978 	SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1979 	    OID_AUTO, "prp_page_alloc_fail", CTLFLAG_RD,
1980 	    &sc->prp_page_alloc_fail, "PRP page allocation failures");
1981 }
1982 
1983 static struct mpr_debug_string {
1984 	char *name;
1985 	int flag;
1986 } mpr_debug_strings[] = {
1987 	{"info", MPR_INFO},
1988 	{"fault", MPR_FAULT},
1989 	{"event", MPR_EVENT},
1990 	{"log", MPR_LOG},
1991 	{"recovery", MPR_RECOVERY},
1992 	{"error", MPR_ERROR},
1993 	{"init", MPR_INIT},
1994 	{"xinfo", MPR_XINFO},
1995 	{"user", MPR_USER},
1996 	{"mapping", MPR_MAPPING},
1997 	{"trace", MPR_TRACE}
1998 };
1999 
2000 enum mpr_debug_level_combiner {
2001 	COMB_NONE,
2002 	COMB_ADD,
2003 	COMB_SUB
2004 };
2005 
2006 static int
mpr_debug_sysctl(SYSCTL_HANDLER_ARGS)2007 mpr_debug_sysctl(SYSCTL_HANDLER_ARGS)
2008 {
2009 	struct mpr_softc *sc;
2010 	struct mpr_debug_string *string;
2011 	struct sbuf *sbuf;
2012 	char *buffer;
2013 	size_t sz;
2014 	int i, len, debug, error;
2015 
2016 	sc = (struct mpr_softc *)arg1;
2017 
2018 	error = sysctl_wire_old_buffer(req, 0);
2019 	if (error != 0)
2020 		return (error);
2021 
2022 	sbuf = sbuf_new_for_sysctl(NULL, NULL, 128, req);
2023 	debug = sc->mpr_debug;
2024 
2025 	sbuf_printf(sbuf, "%#x", debug);
2026 
2027 	sz = sizeof(mpr_debug_strings) / sizeof(mpr_debug_strings[0]);
2028 	for (i = 0; i < sz; i++) {
2029 		string = &mpr_debug_strings[i];
2030 		if (debug & string->flag)
2031 			sbuf_printf(sbuf, ",%s", string->name);
2032 	}
2033 
2034 	error = sbuf_finish(sbuf);
2035 	sbuf_delete(sbuf);
2036 
2037 	if (error || req->newptr == NULL)
2038 		return (error);
2039 
2040 	len = req->newlen - req->newidx;
2041 	if (len == 0)
2042 		return (0);
2043 
2044 	buffer = malloc(len, M_MPR, M_ZERO|M_WAITOK);
2045 	error = SYSCTL_IN(req, buffer, len);
2046 
2047 	mpr_parse_debug(sc, buffer);
2048 
2049 	free(buffer, M_MPR);
2050 	return (error);
2051 }
2052 
2053 static void
mpr_parse_debug(struct mpr_softc * sc,char * list)2054 mpr_parse_debug(struct mpr_softc *sc, char *list)
2055 {
2056 	struct mpr_debug_string *string;
2057 	enum mpr_debug_level_combiner op;
2058 	char *token, *endtoken;
2059 	size_t sz;
2060 	int flags, i;
2061 
2062 	if (list == NULL || *list == '\0')
2063 		return;
2064 
2065 	if (*list == '+') {
2066 		op = COMB_ADD;
2067 		list++;
2068 	} else if (*list == '-') {
2069 		op = COMB_SUB;
2070 		list++;
2071 	} else
2072 		op = COMB_NONE;
2073 	if (*list == '\0')
2074 		return;
2075 
2076 	flags = 0;
2077 	sz = sizeof(mpr_debug_strings) / sizeof(mpr_debug_strings[0]);
2078 	while ((token = strsep(&list, ":,")) != NULL) {
2079 
2080 		/* Handle integer flags */
2081 		flags |= strtol(token, &endtoken, 0);
2082 		if (token != endtoken)
2083 			continue;
2084 
2085 		/* Handle text flags */
2086 		for (i = 0; i < sz; i++) {
2087 			string = &mpr_debug_strings[i];
2088 			if (strcasecmp(token, string->name) == 0) {
2089 				flags |= string->flag;
2090 				break;
2091 			}
2092 		}
2093 	}
2094 
2095 	switch (op) {
2096 	case COMB_NONE:
2097 		sc->mpr_debug = flags;
2098 		break;
2099 	case COMB_ADD:
2100 		sc->mpr_debug |= flags;
2101 		break;
2102 	case COMB_SUB:
2103 		sc->mpr_debug &= (~flags);
2104 		break;
2105 	}
2106 	return;
2107 }
2108 
2109 struct mpr_dumpreq_hdr {
2110 	uint32_t	smid;
2111 	uint32_t	state;
2112 	uint32_t	numframes;
2113 	uint32_t	deschi;
2114 	uint32_t	desclo;
2115 };
2116 
2117 static int
mpr_dump_reqs(SYSCTL_HANDLER_ARGS)2118 mpr_dump_reqs(SYSCTL_HANDLER_ARGS)
2119 {
2120 	struct mpr_softc *sc;
2121 	struct mpr_chain *chain, *chain1;
2122 	struct mpr_command *cm;
2123 	struct mpr_dumpreq_hdr hdr;
2124 	struct sbuf *sb;
2125 	uint32_t smid, state;
2126 	int i, numreqs, error = 0;
2127 
2128 	sc = (struct mpr_softc *)arg1;
2129 
2130 	if ((error = priv_check(curthread, PRIV_DRIVER)) != 0) {
2131 		printf("priv check error %d\n", error);
2132 		return (error);
2133 	}
2134 
2135 	state = MPR_CM_STATE_INQUEUE;
2136 	smid = 1;
2137 	numreqs = sc->num_reqs;
2138 
2139 	if (req->newptr != NULL)
2140 		return (EINVAL);
2141 
2142 	if (smid == 0 || smid > sc->num_reqs)
2143 		return (EINVAL);
2144 	if (numreqs <= 0 || (numreqs + smid > sc->num_reqs))
2145 		numreqs = sc->num_reqs;
2146 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
2147 
2148 	/* Best effort, no locking */
2149 	for (i = smid; i < numreqs; i++) {
2150 		cm = &sc->commands[i];
2151 		if (cm->cm_state != state)
2152 			continue;
2153 		hdr.smid = i;
2154 		hdr.state = cm->cm_state;
2155 		hdr.numframes = 1;
2156 		hdr.deschi = cm->cm_desc.Words.High;
2157 		hdr.desclo = cm->cm_desc.Words.Low;
2158 		TAILQ_FOREACH_SAFE(chain, &cm->cm_chain_list, chain_link,
2159 		   chain1)
2160 			hdr.numframes++;
2161 		sbuf_bcat(sb, &hdr, sizeof(hdr));
2162 		sbuf_bcat(sb, cm->cm_req, 128);
2163 		TAILQ_FOREACH_SAFE(chain, &cm->cm_chain_list, chain_link,
2164 		    chain1)
2165 			sbuf_bcat(sb, chain->chain, 128);
2166 	}
2167 
2168 	error = sbuf_finish(sb);
2169 	sbuf_delete(sb);
2170 	return (error);
2171 }
2172 
2173 int
mpr_attach(struct mpr_softc * sc)2174 mpr_attach(struct mpr_softc *sc)
2175 {
2176 	int error;
2177 
2178 	MPR_FUNCTRACE(sc);
2179 	mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
2180 
2181 	mtx_init(&sc->mpr_mtx, "MPR lock", NULL, MTX_DEF);
2182 	callout_init_mtx(&sc->periodic, &sc->mpr_mtx, 0);
2183 	callout_init_mtx(&sc->device_check_callout, &sc->mpr_mtx, 0);
2184 	TAILQ_INIT(&sc->event_list);
2185 	timevalclear(&sc->lastfail);
2186 
2187 	if ((error = mpr_transition_ready(sc)) != 0) {
2188 		mpr_dprint(sc, MPR_INIT|MPR_FAULT,
2189 		    "Failed to transition ready\n");
2190 		return (error);
2191 	}
2192 
2193 	sc->facts = malloc(sizeof(MPI2_IOC_FACTS_REPLY), M_MPR,
2194 	    M_ZERO|M_NOWAIT);
2195 	if (!sc->facts) {
2196 		mpr_dprint(sc, MPR_INIT|MPR_FAULT,
2197 		    "Cannot allocate memory, exit\n");
2198 		return (ENOMEM);
2199 	}
2200 
2201 	/*
2202 	 * Get IOC Facts and allocate all structures based on this information.
2203 	 * A Diag Reset will also call mpr_iocfacts_allocate and re-read the IOC
2204 	 * Facts. If relevant values have changed in IOC Facts, this function
2205 	 * will free all of the memory based on IOC Facts and reallocate that
2206 	 * memory.  If this fails, any allocated memory should already be freed.
2207 	 */
2208 	if ((error = mpr_iocfacts_allocate(sc, TRUE)) != 0) {
2209 		mpr_dprint(sc, MPR_INIT|MPR_FAULT, "IOC Facts allocation "
2210 		    "failed with error %d\n", error);
2211 		return (error);
2212 	}
2213 
2214 	/* Start the periodic watchdog check on the IOC Doorbell */
2215 	mpr_periodic(sc);
2216 
2217 	/*
2218 	 * The portenable will kick off discovery events that will drive the
2219 	 * rest of the initialization process.  The CAM/SAS module will
2220 	 * hold up the boot sequence until discovery is complete.
2221 	 */
2222 	sc->mpr_ich.ich_func = mpr_startup;
2223 	sc->mpr_ich.ich_arg = sc;
2224 	if (config_intrhook_establish(&sc->mpr_ich) != 0) {
2225 		mpr_dprint(sc, MPR_INIT|MPR_ERROR,
2226 		    "Cannot establish MPR config hook\n");
2227 		error = EINVAL;
2228 	}
2229 
2230 	/*
2231 	 * Allow IR to shutdown gracefully when shutdown occurs.
2232 	 */
2233 	sc->shutdown_eh = EVENTHANDLER_REGISTER(shutdown_final,
2234 	    mprsas_ir_shutdown, sc, SHUTDOWN_PRI_DEFAULT);
2235 
2236 	if (sc->shutdown_eh == NULL)
2237 		mpr_dprint(sc, MPR_INIT|MPR_ERROR,
2238 		    "shutdown event registration failed\n");
2239 
2240 	mpr_setup_sysctl(sc);
2241 
2242 	sc->mpr_flags |= MPR_FLAGS_ATTACH_DONE;
2243 	mpr_dprint(sc, MPR_INIT, "%s exit error= %d\n", __func__, error);
2244 
2245 	return (error);
2246 }
2247 
2248 /* Run through any late-start handlers. */
2249 static void
mpr_startup(void * arg)2250 mpr_startup(void *arg)
2251 {
2252 	struct mpr_softc *sc;
2253 
2254 	sc = (struct mpr_softc *)arg;
2255 	mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
2256 
2257 	mpr_lock(sc);
2258 	mpr_unmask_intr(sc);
2259 
2260 	/* initialize device mapping tables */
2261 	mpr_base_static_config_pages(sc);
2262 	mpr_mapping_initialize(sc);
2263 	mprsas_startup(sc);
2264 	mpr_unlock(sc);
2265 
2266 	mpr_dprint(sc, MPR_INIT, "disestablish config intrhook\n");
2267 	config_intrhook_disestablish(&sc->mpr_ich);
2268 	sc->mpr_ich.ich_arg = NULL;
2269 
2270 	mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
2271 }
2272 
2273 /* Periodic watchdog.  Is called with the driver lock already held. */
2274 static void
mpr_periodic(void * arg)2275 mpr_periodic(void *arg)
2276 {
2277 	struct mpr_softc *sc;
2278 	uint32_t db;
2279 
2280 	sc = (struct mpr_softc *)arg;
2281 	if (sc->mpr_flags & MPR_FLAGS_SHUTDOWN)
2282 		return;
2283 
2284 	db = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
2285 	if ((db & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
2286 		if ((db & MPI2_DOORBELL_FAULT_CODE_MASK) ==
2287 		    IFAULT_IOP_OVER_TEMP_THRESHOLD_EXCEEDED) {
2288 			panic("TEMPERATURE FAULT: STOPPING.");
2289 		}
2290 		mpr_dprint(sc, MPR_FAULT, "IOC Fault 0x%08x, Resetting\n", db);
2291 		mpr_reinit(sc);
2292 	}
2293 
2294 	callout_reset(&sc->periodic, MPR_PERIODIC_DELAY * hz, mpr_periodic, sc);
2295 }
2296 
2297 static void
mpr_log_evt_handler(struct mpr_softc * sc,uintptr_t data,MPI2_EVENT_NOTIFICATION_REPLY * event)2298 mpr_log_evt_handler(struct mpr_softc *sc, uintptr_t data,
2299     MPI2_EVENT_NOTIFICATION_REPLY *event)
2300 {
2301 	MPI2_EVENT_DATA_LOG_ENTRY_ADDED *entry;
2302 
2303 	MPR_DPRINT_EVENT(sc, generic, event);
2304 
2305 	switch (event->Event) {
2306 	case MPI2_EVENT_LOG_DATA:
2307 		mpr_dprint(sc, MPR_EVENT, "MPI2_EVENT_LOG_DATA:\n");
2308 		if (sc->mpr_debug & MPR_EVENT)
2309 			hexdump(event->EventData, event->EventDataLength, NULL,
2310 			    0);
2311 		break;
2312 	case MPI2_EVENT_LOG_ENTRY_ADDED:
2313 		entry = (MPI2_EVENT_DATA_LOG_ENTRY_ADDED *)event->EventData;
2314 		mpr_dprint(sc, MPR_EVENT, "MPI2_EVENT_LOG_ENTRY_ADDED event "
2315 		    "0x%x Sequence %d:\n", entry->LogEntryQualifier,
2316 		     entry->LogSequence);
2317 		break;
2318 	default:
2319 		break;
2320 	}
2321 	return;
2322 }
2323 
2324 static int
mpr_attach_log(struct mpr_softc * sc)2325 mpr_attach_log(struct mpr_softc *sc)
2326 {
2327 	uint8_t events[16];
2328 
2329 	bzero(events, 16);
2330 	setbit(events, MPI2_EVENT_LOG_DATA);
2331 	setbit(events, MPI2_EVENT_LOG_ENTRY_ADDED);
2332 
2333 	mpr_register_events(sc, events, mpr_log_evt_handler, NULL,
2334 	    &sc->mpr_log_eh);
2335 
2336 	return (0);
2337 }
2338 
2339 static int
mpr_detach_log(struct mpr_softc * sc)2340 mpr_detach_log(struct mpr_softc *sc)
2341 {
2342 
2343 	if (sc->mpr_log_eh != NULL)
2344 		mpr_deregister_events(sc, sc->mpr_log_eh);
2345 	return (0);
2346 }
2347 
2348 /*
2349  * Free all of the driver resources and detach submodules.  Should be called
2350  * without the lock held.
2351  */
2352 int
mpr_free(struct mpr_softc * sc)2353 mpr_free(struct mpr_softc *sc)
2354 {
2355 	int error;
2356 
2357 	mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
2358 	/* Turn off the watchdog */
2359 	mpr_lock(sc);
2360 	sc->mpr_flags |= MPR_FLAGS_SHUTDOWN;
2361 	mpr_unlock(sc);
2362 	/* Lock must not be held for this */
2363 	callout_drain(&sc->periodic);
2364 	callout_drain(&sc->device_check_callout);
2365 
2366 	if (((error = mpr_detach_log(sc)) != 0) ||
2367 	    ((error = mpr_detach_sas(sc)) != 0)) {
2368 		mpr_dprint(sc, MPR_INIT|MPR_FAULT, "failed to detach "
2369 		    "subsystems, error= %d, exit\n", error);
2370 		return (error);
2371 	}
2372 
2373 	mpr_detach_user(sc);
2374 
2375 	/* Put the IOC back in the READY state. */
2376 	mpr_lock(sc);
2377 	if ((error = mpr_transition_ready(sc)) != 0) {
2378 		mpr_unlock(sc);
2379 		return (error);
2380 	}
2381 	mpr_unlock(sc);
2382 
2383 	if (sc->facts != NULL)
2384 		free(sc->facts, M_MPR);
2385 
2386 	/*
2387 	 * Free all buffers that are based on IOC Facts.  A Diag Reset may need
2388 	 * to free these buffers too.
2389 	 */
2390 	mpr_iocfacts_free(sc);
2391 
2392 	if (sc->sysctl_tree != NULL)
2393 		sysctl_ctx_free(&sc->sysctl_ctx);
2394 
2395 	/* Deregister the shutdown function */
2396 	if (sc->shutdown_eh != NULL)
2397 		EVENTHANDLER_DEREGISTER(shutdown_final, sc->shutdown_eh);
2398 
2399 	mtx_destroy(&sc->mpr_mtx);
2400 	mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
2401 
2402 	return (0);
2403 }
2404 
2405 static __inline void
mpr_complete_command(struct mpr_softc * sc,struct mpr_command * cm)2406 mpr_complete_command(struct mpr_softc *sc, struct mpr_command *cm)
2407 {
2408 	MPR_FUNCTRACE(sc);
2409 
2410 	if (cm == NULL) {
2411 		mpr_dprint(sc, MPR_ERROR, "Completing NULL command\n");
2412 		return;
2413 	}
2414 
2415 	cm->cm_state = MPR_CM_STATE_BUSY;
2416 	if (cm->cm_flags & MPR_CM_FLAGS_POLLED)
2417 		cm->cm_flags |= MPR_CM_FLAGS_COMPLETE;
2418 
2419 	if (cm->cm_complete != NULL) {
2420 		mpr_dprint(sc, MPR_TRACE,
2421 		    "%s cm %p calling cm_complete %p data %p reply %p\n",
2422 		    __func__, cm, cm->cm_complete, cm->cm_complete_data,
2423 		    cm->cm_reply);
2424 		cm->cm_complete(sc, cm);
2425 	}
2426 
2427 	if (cm->cm_flags & MPR_CM_FLAGS_WAKEUP) {
2428 		mpr_dprint(sc, MPR_TRACE, "waking up %p\n", cm);
2429 		wakeup(cm);
2430 	}
2431 
2432 	if (sc->io_cmds_active != 0) {
2433 		sc->io_cmds_active--;
2434 	} else {
2435 		mpr_dprint(sc, MPR_ERROR, "Warning: io_cmds_active is "
2436 		    "out of sync - resynching to 0\n");
2437 	}
2438 }
2439 
2440 static void
mpr_sas_log_info(struct mpr_softc * sc,u32 log_info)2441 mpr_sas_log_info(struct mpr_softc *sc , u32 log_info)
2442 {
2443 	union loginfo_type {
2444 		u32	loginfo;
2445 		struct {
2446 			u32	subcode:16;
2447 			u32	code:8;
2448 			u32	originator:4;
2449 			u32	bus_type:4;
2450 		} dw;
2451 	};
2452 	union loginfo_type sas_loginfo;
2453 	char *originator_str = NULL;
2454 
2455 	sas_loginfo.loginfo = log_info;
2456 	if (sas_loginfo.dw.bus_type != 3 /*SAS*/)
2457 		return;
2458 
2459 	/* each nexus loss loginfo */
2460 	if (log_info == 0x31170000)
2461 		return;
2462 
2463 	/* eat the loginfos associated with task aborts */
2464 	if ((log_info == 30050000) || (log_info == 0x31140000) ||
2465 	    (log_info == 0x31130000))
2466 		return;
2467 
2468 	switch (sas_loginfo.dw.originator) {
2469 	case 0:
2470 		originator_str = "IOP";
2471 		break;
2472 	case 1:
2473 		originator_str = "PL";
2474 		break;
2475 	case 2:
2476 		originator_str = "IR";
2477 		break;
2478 	}
2479 
2480 	mpr_dprint(sc, MPR_LOG, "log_info(0x%08x): originator(%s), "
2481 	    "code(0x%02x), sub_code(0x%04x)\n", log_info, originator_str,
2482 	    sas_loginfo.dw.code, sas_loginfo.dw.subcode);
2483 }
2484 
2485 static void
mpr_display_reply_info(struct mpr_softc * sc,uint8_t * reply)2486 mpr_display_reply_info(struct mpr_softc *sc, uint8_t *reply)
2487 {
2488 	MPI2DefaultReply_t *mpi_reply;
2489 	u16 sc_status;
2490 
2491 	mpi_reply = (MPI2DefaultReply_t*)reply;
2492 	sc_status = le16toh(mpi_reply->IOCStatus);
2493 	if (sc_status & MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE)
2494 		mpr_sas_log_info(sc, le32toh(mpi_reply->IOCLogInfo));
2495 }
2496 
2497 void
mpr_intr(void * data)2498 mpr_intr(void *data)
2499 {
2500 	struct mpr_softc *sc;
2501 	uint32_t status;
2502 
2503 	sc = (struct mpr_softc *)data;
2504 	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2505 
2506 	/*
2507 	 * Check interrupt status register to flush the bus.  This is
2508 	 * needed for both INTx interrupts and driver-driven polling
2509 	 */
2510 	status = mpr_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET);
2511 	if ((status & MPI2_HIS_REPLY_DESCRIPTOR_INTERRUPT) == 0)
2512 		return;
2513 
2514 	mpr_lock(sc);
2515 	mpr_intr_locked(data);
2516 	mpr_unlock(sc);
2517 	return;
2518 }
2519 
2520 /*
2521  * In theory, MSI/MSIX interrupts shouldn't need to read any registers on the
2522  * chip.  Hopefully this theory is correct.
2523  */
2524 void
mpr_intr_msi(void * data)2525 mpr_intr_msi(void *data)
2526 {
2527 	struct mpr_softc *sc;
2528 
2529 	sc = (struct mpr_softc *)data;
2530 	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2531 	mpr_lock(sc);
2532 	mpr_intr_locked(data);
2533 	mpr_unlock(sc);
2534 	return;
2535 }
2536 
2537 /*
2538  * The locking is overly broad and simplistic, but easy to deal with for now.
2539  */
2540 void
mpr_intr_locked(void * data)2541 mpr_intr_locked(void *data)
2542 {
2543 	MPI2_REPLY_DESCRIPTORS_UNION *desc;
2544 	MPI2_DIAG_RELEASE_REPLY *rel_rep;
2545 	mpr_fw_diagnostic_buffer_t *pBuffer;
2546 	struct mpr_softc *sc;
2547 	uint64_t tdesc;
2548 	struct mpr_command *cm = NULL;
2549 	uint8_t flags;
2550 	u_int pq;
2551 
2552 	sc = (struct mpr_softc *)data;
2553 
2554 	pq = sc->replypostindex;
2555 	mpr_dprint(sc, MPR_TRACE,
2556 	    "%s sc %p starting with replypostindex %u\n",
2557 	    __func__, sc, sc->replypostindex);
2558 
2559 	for ( ;; ) {
2560 		cm = NULL;
2561 		desc = &sc->post_queue[sc->replypostindex];
2562 
2563 		/*
2564 		 * Copy and clear out the descriptor so that any reentry will
2565 		 * immediately know that this descriptor has already been
2566 		 * looked at.  There is unfortunate casting magic because the
2567 		 * MPI API doesn't have a cardinal 64bit type.
2568 		 */
2569 		tdesc = 0xffffffffffffffff;
2570 		tdesc = atomic_swap_64((uint64_t *)desc, tdesc);
2571 		desc = (MPI2_REPLY_DESCRIPTORS_UNION *)&tdesc;
2572 
2573 		flags = desc->Default.ReplyFlags &
2574 		    MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
2575 		if ((flags == MPI2_RPY_DESCRIPT_FLAGS_UNUSED) ||
2576 		    (le32toh(desc->Words.High) == 0xffffffff))
2577 			break;
2578 
2579 		/* increment the replypostindex now, so that event handlers
2580 		 * and cm completion handlers which decide to do a diag
2581 		 * reset can zero it without it getting incremented again
2582 		 * afterwards, and we break out of this loop on the next
2583 		 * iteration since the reply post queue has been cleared to
2584 		 * 0xFF and all descriptors look unused (which they are).
2585 		 */
2586 		if (++sc->replypostindex >= sc->pqdepth)
2587 			sc->replypostindex = 0;
2588 
2589 		switch (flags) {
2590 		case MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS:
2591 		case MPI25_RPY_DESCRIPT_FLAGS_FAST_PATH_SCSI_IO_SUCCESS:
2592 		case MPI26_RPY_DESCRIPT_FLAGS_PCIE_ENCAPSULATED_SUCCESS:
2593 			cm = &sc->commands[le16toh(desc->SCSIIOSuccess.SMID)];
2594 			KASSERT(cm->cm_state == MPR_CM_STATE_INQUEUE,
2595 			    ("command not inqueue\n"));
2596 			cm->cm_state = MPR_CM_STATE_BUSY;
2597 			cm->cm_reply = NULL;
2598 			break;
2599 		case MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY:
2600 		{
2601 			uint32_t baddr;
2602 			uint8_t *reply;
2603 
2604 			/*
2605 			 * Re-compose the reply address from the address
2606 			 * sent back from the chip.  The ReplyFrameAddress
2607 			 * is the lower 32 bits of the physical address of
2608 			 * particular reply frame.  Convert that address to
2609 			 * host format, and then use that to provide the
2610 			 * offset against the virtual address base
2611 			 * (sc->reply_frames).
2612 			 */
2613 			baddr = le32toh(desc->AddressReply.ReplyFrameAddress);
2614 			reply = sc->reply_frames +
2615 				(baddr - ((uint32_t)sc->reply_busaddr));
2616 			/*
2617 			 * Make sure the reply we got back is in a valid
2618 			 * range.  If not, go ahead and panic here, since
2619 			 * we'll probably panic as soon as we deference the
2620 			 * reply pointer anyway.
2621 			 */
2622 			if ((reply < sc->reply_frames)
2623 			 || (reply > (sc->reply_frames +
2624 			     (sc->fqdepth * sc->replyframesz)))) {
2625 				printf("%s: WARNING: reply %p out of range!\n",
2626 				       __func__, reply);
2627 				printf("%s: reply_frames %p, fqdepth %d, "
2628 				       "frame size %d\n", __func__,
2629 				       sc->reply_frames, sc->fqdepth,
2630 				       sc->replyframesz);
2631 				printf("%s: baddr %#x,\n", __func__, baddr);
2632 				/* LSI-TODO. See Linux Code for Graceful exit */
2633 				panic("Reply address out of range");
2634 			}
2635 			if (le16toh(desc->AddressReply.SMID) == 0) {
2636 				if (((MPI2_DEFAULT_REPLY *)reply)->Function ==
2637 				    MPI2_FUNCTION_DIAG_BUFFER_POST) {
2638 					/*
2639 					 * If SMID is 0 for Diag Buffer Post,
2640 					 * this implies that the reply is due to
2641 					 * a release function with a status that
2642 					 * the buffer has been released.  Set
2643 					 * the buffer flags accordingly.
2644 					 */
2645 					rel_rep =
2646 					    (MPI2_DIAG_RELEASE_REPLY *)reply;
2647 					if ((le16toh(rel_rep->IOCStatus) &
2648 					    MPI2_IOCSTATUS_MASK) ==
2649 					    MPI2_IOCSTATUS_DIAGNOSTIC_RELEASED)
2650 					{
2651 						pBuffer =
2652 						    &sc->fw_diag_buffer_list[
2653 						    rel_rep->BufferType];
2654 						pBuffer->valid_data = TRUE;
2655 						pBuffer->owned_by_firmware =
2656 						    FALSE;
2657 						pBuffer->immediate = FALSE;
2658 					}
2659 				} else
2660 					mpr_dispatch_event(sc, baddr,
2661 					    (MPI2_EVENT_NOTIFICATION_REPLY *)
2662 					    reply);
2663 			} else {
2664 				cm = &sc->commands[
2665 				    le16toh(desc->AddressReply.SMID)];
2666 				if (cm->cm_state == MPR_CM_STATE_INQUEUE) {
2667 					cm->cm_reply = reply;
2668 					cm->cm_reply_data =
2669 					    le32toh(desc->AddressReply.
2670 						ReplyFrameAddress);
2671 				} else {
2672 					mpr_dprint(sc, MPR_RECOVERY,
2673 					    "Bad state for ADDRESS_REPLY status,"
2674 					    " ignoring state %d cm %p\n",
2675 					    cm->cm_state, cm);
2676 				}
2677 			}
2678 			break;
2679 		}
2680 		case MPI2_RPY_DESCRIPT_FLAGS_TARGETASSIST_SUCCESS:
2681 		case MPI2_RPY_DESCRIPT_FLAGS_TARGET_COMMAND_BUFFER:
2682 		case MPI2_RPY_DESCRIPT_FLAGS_RAID_ACCELERATOR_SUCCESS:
2683 		default:
2684 			/* Unhandled */
2685 			mpr_dprint(sc, MPR_ERROR, "Unhandled reply 0x%x\n",
2686 			    desc->Default.ReplyFlags);
2687 			cm = NULL;
2688 			break;
2689 		}
2690 
2691 		if (cm != NULL) {
2692 			// Print Error reply frame
2693 			if (cm->cm_reply)
2694 				mpr_display_reply_info(sc,cm->cm_reply);
2695 			mpr_complete_command(sc, cm);
2696 		}
2697 	}
2698 
2699 	if (pq != sc->replypostindex) {
2700 		mpr_dprint(sc, MPR_TRACE, "%s sc %p writing postindex %d\n",
2701 		    __func__, sc, sc->replypostindex);
2702 		mpr_regwrite(sc, MPI2_REPLY_POST_HOST_INDEX_OFFSET,
2703 		    sc->replypostindex);
2704 	}
2705 
2706 	return;
2707 }
2708 
2709 static void
mpr_dispatch_event(struct mpr_softc * sc,uintptr_t data,MPI2_EVENT_NOTIFICATION_REPLY * reply)2710 mpr_dispatch_event(struct mpr_softc *sc, uintptr_t data,
2711     MPI2_EVENT_NOTIFICATION_REPLY *reply)
2712 {
2713 	struct mpr_event_handle *eh;
2714 	int event, handled = 0;
2715 
2716 	event = le16toh(reply->Event);
2717 	TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
2718 		if (isset(eh->mask, event)) {
2719 			eh->callback(sc, data, reply);
2720 			handled++;
2721 		}
2722 	}
2723 
2724 	if (handled == 0)
2725 		mpr_dprint(sc, MPR_EVENT, "Unhandled event 0x%x\n",
2726 		    le16toh(event));
2727 
2728 	/*
2729 	 * This is the only place that the event/reply should be freed.
2730 	 * Anything wanting to hold onto the event data should have
2731 	 * already copied it into their own storage.
2732 	 */
2733 	mpr_free_reply(sc, data);
2734 }
2735 
2736 static void
mpr_reregister_events_complete(struct mpr_softc * sc,struct mpr_command * cm)2737 mpr_reregister_events_complete(struct mpr_softc *sc, struct mpr_command *cm)
2738 {
2739 	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2740 
2741 	if (cm->cm_reply)
2742 		MPR_DPRINT_EVENT(sc, generic,
2743 			(MPI2_EVENT_NOTIFICATION_REPLY *)cm->cm_reply);
2744 
2745 	mpr_free_command(sc, cm);
2746 
2747 	/* next, send a port enable */
2748 	mprsas_startup(sc);
2749 }
2750 
2751 /*
2752  * For both register_events and update_events, the caller supplies a bitmap
2753  * of events that it _wants_.  These functions then turn that into a bitmask
2754  * suitable for the controller.
2755  */
2756 int
mpr_register_events(struct mpr_softc * sc,uint8_t * mask,mpr_evt_callback_t * cb,void * data,struct mpr_event_handle ** handle)2757 mpr_register_events(struct mpr_softc *sc, uint8_t *mask,
2758     mpr_evt_callback_t *cb, void *data, struct mpr_event_handle **handle)
2759 {
2760 	struct mpr_event_handle *eh;
2761 	int error = 0;
2762 
2763 	eh = malloc(sizeof(struct mpr_event_handle), M_MPR, M_WAITOK|M_ZERO);
2764 	eh->callback = cb;
2765 	eh->data = data;
2766 	TAILQ_INSERT_TAIL(&sc->event_list, eh, eh_list);
2767 	if (mask != NULL)
2768 		error = mpr_update_events(sc, eh, mask);
2769 	*handle = eh;
2770 
2771 	return (error);
2772 }
2773 
2774 int
mpr_update_events(struct mpr_softc * sc,struct mpr_event_handle * handle,uint8_t * mask)2775 mpr_update_events(struct mpr_softc *sc, struct mpr_event_handle *handle,
2776     uint8_t *mask)
2777 {
2778 	MPI2_EVENT_NOTIFICATION_REQUEST *evtreq;
2779 	MPI2_EVENT_NOTIFICATION_REPLY *reply = NULL;
2780 	struct mpr_command *cm = NULL;
2781 	struct mpr_event_handle *eh;
2782 	int error, i;
2783 
2784 	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2785 
2786 	if ((mask != NULL) && (handle != NULL))
2787 		bcopy(mask, &handle->mask[0], 16);
2788 	memset(sc->event_mask, 0xff, 16);
2789 
2790 	TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
2791 		for (i = 0; i < 16; i++)
2792 			sc->event_mask[i] &= ~eh->mask[i];
2793 	}
2794 
2795 	if ((cm = mpr_alloc_command(sc)) == NULL)
2796 		return (EBUSY);
2797 	evtreq = (MPI2_EVENT_NOTIFICATION_REQUEST *)cm->cm_req;
2798 	evtreq->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
2799 	evtreq->MsgFlags = 0;
2800 	evtreq->SASBroadcastPrimitiveMasks = 0;
2801 #ifdef MPR_DEBUG_ALL_EVENTS
2802 	{
2803 		u_char fullmask[sizeof(evtreq->EventMasks)];
2804 		memset(fullmask, 0x00, sizeof(fullmask));
2805 		bcopy(fullmask, (uint8_t *)&evtreq->EventMasks, sizeof(fullmask));
2806 	}
2807 #else
2808 	bcopy(sc->event_mask, (uint8_t *)&evtreq->EventMasks, sizeof(sc->event_mask));
2809 	for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
2810 		evtreq->EventMasks[i] = htole32(evtreq->EventMasks[i]);
2811 #endif
2812 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
2813 	cm->cm_data = NULL;
2814 
2815 	error = mpr_request_polled(sc, &cm);
2816 	if (cm != NULL)
2817 		reply = (MPI2_EVENT_NOTIFICATION_REPLY *)cm->cm_reply;
2818 	if ((reply == NULL) ||
2819 	    (reply->IOCStatus & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS)
2820 		error = ENXIO;
2821 
2822 	if (reply)
2823 		MPR_DPRINT_EVENT(sc, generic, reply);
2824 
2825 	mpr_dprint(sc, MPR_TRACE, "%s finished error %d\n", __func__, error);
2826 
2827 	if (cm != NULL)
2828 		mpr_free_command(sc, cm);
2829 	return (error);
2830 }
2831 
2832 static int
mpr_reregister_events(struct mpr_softc * sc)2833 mpr_reregister_events(struct mpr_softc *sc)
2834 {
2835 	MPI2_EVENT_NOTIFICATION_REQUEST *evtreq;
2836 	struct mpr_command *cm;
2837 	struct mpr_event_handle *eh;
2838 	int error, i;
2839 
2840 	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2841 
2842 	/* first, reregister events */
2843 
2844 	memset(sc->event_mask, 0xff, 16);
2845 
2846 	TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
2847 		for (i = 0; i < 16; i++)
2848 			sc->event_mask[i] &= ~eh->mask[i];
2849 	}
2850 
2851 	if ((cm = mpr_alloc_command(sc)) == NULL)
2852 		return (EBUSY);
2853 	evtreq = (MPI2_EVENT_NOTIFICATION_REQUEST *)cm->cm_req;
2854 	evtreq->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
2855 	evtreq->MsgFlags = 0;
2856 	evtreq->SASBroadcastPrimitiveMasks = 0;
2857 #ifdef MPR_DEBUG_ALL_EVENTS
2858 	{
2859 		u_char fullmask[sizeof(evtreq->EventMasks)];
2860 		memset(fullmask, 0x00, sizeof(fullmask));
2861 		bcopy(fullmask, (uint8_t *)&evtreq->EventMasks, sizeof(fullmask));
2862 	}
2863 #else
2864 	bcopy(sc->event_mask, (uint8_t *)&evtreq->EventMasks, sizeof(sc->event_mask));
2865 	for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
2866 		evtreq->EventMasks[i] = htole32(evtreq->EventMasks[i]);
2867 #endif
2868 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
2869 	cm->cm_data = NULL;
2870 	cm->cm_complete = mpr_reregister_events_complete;
2871 
2872 	error = mpr_map_command(sc, cm);
2873 
2874 	mpr_dprint(sc, MPR_TRACE, "%s finished with error %d\n", __func__,
2875 	    error);
2876 	return (error);
2877 }
2878 
2879 int
mpr_deregister_events(struct mpr_softc * sc,struct mpr_event_handle * handle)2880 mpr_deregister_events(struct mpr_softc *sc, struct mpr_event_handle *handle)
2881 {
2882 
2883 	TAILQ_REMOVE(&sc->event_list, handle, eh_list);
2884 	free(handle, M_MPR);
2885 	return (mpr_update_events(sc, NULL, NULL));
2886 }
2887 
2888 /**
2889 * mpr_build_nvme_prp - This function is called for NVMe end devices to build a
2890 * native SGL (NVMe PRP). The native SGL is built starting in the first PRP entry
2891 * of the NVMe message (PRP1). If the data buffer is small enough to be described
2892 * entirely using PRP1, then PRP2 is not used. If needed, PRP2 is used to
2893 * describe a larger data buffer. If the data buffer is too large to describe
2894 * using the two PRP entriess inside the NVMe message, then PRP1 describes the
2895 * first data memory segment, and PRP2 contains a pointer to a PRP list located
2896 * elsewhere in memory to describe the remaining data memory segments. The PRP
2897 * list will be contiguous.
2898 
2899 * The native SGL for NVMe devices is a Physical Region Page (PRP). A PRP
2900 * consists of a list of PRP entries to describe a number of noncontigous
2901 * physical memory segments as a single memory buffer, just as a SGL does. Note
2902 * however, that this function is only used by the IOCTL call, so the memory
2903 * given will be guaranteed to be contiguous. There is no need to translate
2904 * non-contiguous SGL into a PRP in this case. All PRPs will describe contiguous
2905 * space that is one page size each.
2906 *
2907 * Each NVMe message contains two PRP entries. The first (PRP1) either contains
2908 * a PRP list pointer or a PRP element, depending upon the command. PRP2 contains
2909 * the second PRP element if the memory being described fits within 2 PRP
2910 * entries, or a PRP list pointer if the PRP spans more than two entries.
2911 *
2912 * A PRP list pointer contains the address of a PRP list, structured as a linear
2913 * array of PRP entries. Each PRP entry in this list describes a segment of
2914 * physical memory.
2915 *
2916 * Each 64-bit PRP entry comprises an address and an offset field. The address
2917 * always points to the beginning of a PAGE_SIZE physical memory page, and the
2918 * offset describes where within that page the memory segment begins. Only the
2919 * first element in a PRP list may contain a non-zero offest, implying that all
2920 * memory segments following the first begin at the start of a PAGE_SIZE page.
2921 *
2922 * Each PRP element normally describes a chunck of PAGE_SIZE physical memory,
2923 * with exceptions for the first and last elements in the list. If the memory
2924 * being described by the list begins at a non-zero offset within the first page,
2925 * then the first PRP element will contain a non-zero offset indicating where the
2926 * region begins within the page. The last memory segment may end before the end
2927 * of the PAGE_SIZE segment, depending upon the overall size of the memory being
2928 * described by the PRP list.
2929 *
2930 * Since PRP entries lack any indication of size, the overall data buffer length
2931 * is used to determine where the end of the data memory buffer is located, and
2932 * how many PRP entries are required to describe it.
2933 *
2934 * Returns nothing.
2935 */
2936 void
mpr_build_nvme_prp(struct mpr_softc * sc,struct mpr_command * cm,Mpi26NVMeEncapsulatedRequest_t * nvme_encap_request,void * data,uint32_t data_in_sz,uint32_t data_out_sz)2937 mpr_build_nvme_prp(struct mpr_softc *sc, struct mpr_command *cm,
2938     Mpi26NVMeEncapsulatedRequest_t *nvme_encap_request, void *data,
2939     uint32_t data_in_sz, uint32_t data_out_sz)
2940 {
2941 	int			prp_size = PRP_ENTRY_SIZE;
2942 	uint64_t		*prp_entry, *prp1_entry, *prp2_entry;
2943 	uint64_t		*prp_entry_phys, *prp_page, *prp_page_phys;
2944 	uint32_t		offset, entry_len, page_mask_result, page_mask;
2945 	bus_addr_t		paddr;
2946 	size_t			length;
2947 	struct mpr_prp_page	*prp_page_info = NULL;
2948 
2949 	/*
2950 	 * Not all commands require a data transfer. If no data, just return
2951 	 * without constructing any PRP.
2952 	 */
2953 	if (!data_in_sz && !data_out_sz)
2954 		return;
2955 
2956 	/*
2957 	 * Set pointers to PRP1 and PRP2, which are in the NVMe command. PRP1 is
2958 	 * located at a 24 byte offset from the start of the NVMe command. Then
2959 	 * set the current PRP entry pointer to PRP1.
2960 	 */
2961 	prp1_entry = (uint64_t *)(nvme_encap_request->NVMe_Command +
2962 	    NVME_CMD_PRP1_OFFSET);
2963 	prp2_entry = (uint64_t *)(nvme_encap_request->NVMe_Command +
2964 	    NVME_CMD_PRP2_OFFSET);
2965 	prp_entry = prp1_entry;
2966 
2967 	/*
2968 	 * For the PRP entries, use the specially allocated buffer of
2969 	 * contiguous memory. PRP Page allocation failures should not happen
2970 	 * because there should be enough PRP page buffers to account for the
2971 	 * possible NVMe QDepth.
2972 	 */
2973 	prp_page_info = mpr_alloc_prp_page(sc);
2974 	KASSERT(prp_page_info != NULL, ("%s: There are no PRP Pages left to be "
2975 	    "used for building a native NVMe SGL.\n", __func__));
2976 	prp_page = (uint64_t *)prp_page_info->prp_page;
2977 	prp_page_phys = (uint64_t *)(uintptr_t)prp_page_info->prp_page_busaddr;
2978 
2979 	/*
2980 	 * Insert the allocated PRP page into the command's PRP page list. This
2981 	 * will be freed when the command is freed.
2982 	 */
2983 	TAILQ_INSERT_TAIL(&cm->cm_prp_page_list, prp_page_info, prp_page_link);
2984 
2985 	/*
2986 	 * Check if we are within 1 entry of a page boundary we don't want our
2987 	 * first entry to be a PRP List entry.
2988 	 */
2989 	page_mask = PAGE_SIZE - 1;
2990 	page_mask_result = (uintptr_t)((uint8_t *)prp_page + prp_size) &
2991 	    page_mask;
2992 	if (!page_mask_result)
2993 	{
2994 		/* Bump up to next page boundary. */
2995 		prp_page = (uint64_t *)((uint8_t *)prp_page + prp_size);
2996 		prp_page_phys = (uint64_t *)((uint8_t *)prp_page_phys +
2997 		    prp_size);
2998 	}
2999 
3000 	/*
3001 	 * Set PRP physical pointer, which initially points to the current PRP
3002 	 * DMA memory page.
3003 	 */
3004 	prp_entry_phys = prp_page_phys;
3005 
3006 	/* Get physical address and length of the data buffer. */
3007 	paddr = (bus_addr_t)(uintptr_t)data;
3008 	if (data_in_sz)
3009 		length = data_in_sz;
3010 	else
3011 		length = data_out_sz;
3012 
3013 	/* Loop while the length is not zero. */
3014 	while (length)
3015 	{
3016 		/*
3017 		 * Check if we need to put a list pointer here if we are at page
3018 		 * boundary - prp_size (8 bytes).
3019 		 */
3020 		page_mask_result = (uintptr_t)((uint8_t *)prp_entry_phys +
3021 		    prp_size) & page_mask;
3022 		if (!page_mask_result)
3023 		{
3024 			/*
3025 			 * This is the last entry in a PRP List, so we need to
3026 			 * put a PRP list pointer here. What this does is:
3027 			 *   - bump the current memory pointer to the next
3028 			 *     address, which will be the next full page.
3029 			 *   - set the PRP Entry to point to that page. This is
3030 			 *     now the PRP List pointer.
3031 			 *   - bump the PRP Entry pointer the start of the next
3032 			 *     page. Since all of this PRP memory is contiguous,
3033 			 *     no need to get a new page - it's just the next
3034 			 *     address.
3035 			 */
3036 			prp_entry_phys++;
3037 			*prp_entry =
3038 			    htole64((uint64_t)(uintptr_t)prp_entry_phys);
3039 			prp_entry++;
3040 		}
3041 
3042 		/* Need to handle if entry will be part of a page. */
3043 		offset = (uint32_t)paddr & page_mask;
3044 		entry_len = PAGE_SIZE - offset;
3045 
3046 		if (prp_entry == prp1_entry)
3047 		{
3048 			/*
3049 			 * Must fill in the first PRP pointer (PRP1) before
3050 			 * moving on.
3051 			 */
3052 			*prp1_entry = htole64((uint64_t)paddr);
3053 
3054 			/*
3055 			 * Now point to the second PRP entry within the
3056 			 * command (PRP2).
3057 			 */
3058 			prp_entry = prp2_entry;
3059 		}
3060 		else if (prp_entry == prp2_entry)
3061 		{
3062 			/*
3063 			 * Should the PRP2 entry be a PRP List pointer or just a
3064 			 * regular PRP pointer? If there is more than one more
3065 			 * page of data, must use a PRP List pointer.
3066 			 */
3067 			if (length > PAGE_SIZE)
3068 			{
3069 				/*
3070 				 * PRP2 will contain a PRP List pointer because
3071 				 * more PRP's are needed with this command. The
3072 				 * list will start at the beginning of the
3073 				 * contiguous buffer.
3074 				 */
3075 				*prp2_entry =
3076 				    htole64(
3077 				    (uint64_t)(uintptr_t)prp_entry_phys);
3078 
3079 				/*
3080 				 * The next PRP Entry will be the start of the
3081 				 * first PRP List.
3082 				 */
3083 				prp_entry = prp_page;
3084 			}
3085 			else
3086 			{
3087 				/*
3088 				 * After this, the PRP Entries are complete.
3089 				 * This command uses 2 PRP's and no PRP list.
3090 				 */
3091 				*prp2_entry = htole64((uint64_t)paddr);
3092 			}
3093 		}
3094 		else
3095 		{
3096 			/*
3097 			 * Put entry in list and bump the addresses.
3098 			 *
3099 			 * After PRP1 and PRP2 are filled in, this will fill in
3100 			 * all remaining PRP entries in a PRP List, one per each
3101 			 * time through the loop.
3102 			 */
3103 			*prp_entry = htole64((uint64_t)paddr);
3104 			prp_entry++;
3105 			prp_entry_phys++;
3106 		}
3107 
3108 		/*
3109 		 * Bump the phys address of the command's data buffer by the
3110 		 * entry_len.
3111 		 */
3112 		paddr += entry_len;
3113 
3114 		/* Decrement length accounting for last partial page. */
3115 		if (entry_len > length)
3116 			length = 0;
3117 		else
3118 			length -= entry_len;
3119 	}
3120 }
3121 
3122 /*
3123  * mpr_check_pcie_native_sgl - This function is called for PCIe end devices to
3124  * determine if the driver needs to build a native SGL. If so, that native SGL
3125  * is built in the contiguous buffers allocated especially for PCIe SGL
3126  * creation. If the driver will not build a native SGL, return TRUE and a
3127  * normal IEEE SGL will be built. Currently this routine supports NVMe devices
3128  * only.
3129  *
3130  * Returns FALSE (0) if native SGL was built, TRUE (1) if no SGL was built.
3131  */
3132 static int
mpr_check_pcie_native_sgl(struct mpr_softc * sc,struct mpr_command * cm,bus_dma_segment_t * segs,int segs_left)3133 mpr_check_pcie_native_sgl(struct mpr_softc *sc, struct mpr_command *cm,
3134     bus_dma_segment_t *segs, int segs_left)
3135 {
3136 	uint32_t		i, sge_dwords, length, offset, entry_len;
3137 	uint32_t		num_entries, buff_len = 0, sges_in_segment;
3138 	uint32_t		page_mask, page_mask_result, *curr_buff;
3139 	uint32_t		*ptr_sgl, *ptr_first_sgl, first_page_offset;
3140 	uint32_t		first_page_data_size, end_residual;
3141 	uint64_t		*msg_phys;
3142 	bus_addr_t		paddr;
3143 	int			build_native_sgl = 0, first_prp_entry;
3144 	int			prp_size = PRP_ENTRY_SIZE;
3145 	Mpi25IeeeSgeChain64_t	*main_chain_element = NULL;
3146 	struct mpr_prp_page	*prp_page_info = NULL;
3147 
3148 	mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
3149 
3150 	/*
3151 	 * Add up the sizes of each segment length to get the total transfer
3152 	 * size, which will be checked against the Maximum Data Transfer Size.
3153 	 * If the data transfer length exceeds the MDTS for this device, just
3154 	 * return 1 so a normal IEEE SGL will be built. F/W will break the I/O
3155 	 * up into multiple I/O's. [nvme_mdts = 0 means unlimited]
3156 	 */
3157 	for (i = 0; i < segs_left; i++)
3158 		buff_len += htole32(segs[i].ds_len);
3159 	if ((cm->cm_targ->MDTS > 0) && (buff_len > cm->cm_targ->MDTS))
3160 		return 1;
3161 
3162 	/* Create page_mask (to get offset within page) */
3163 	page_mask = PAGE_SIZE - 1;
3164 
3165 	/*
3166 	 * Check if the number of elements exceeds the max number that can be
3167 	 * put in the main message frame (H/W can only translate an SGL that
3168 	 * is contained entirely in the main message frame).
3169 	 */
3170 	sges_in_segment = (sc->reqframesz -
3171 	    offsetof(Mpi25SCSIIORequest_t, SGL)) / sizeof(MPI25_SGE_IO_UNION);
3172 	if (segs_left > sges_in_segment)
3173 		build_native_sgl = 1;
3174 	else
3175 	{
3176 		/*
3177 		 * NVMe uses one PRP for each physical page (or part of physical
3178 		 * page).
3179 		 *    if 4 pages or less then IEEE is OK
3180 		 *    if > 5 pages then we need to build a native SGL
3181 		 *    if > 4 and <= 5 pages, then check the physical address of
3182 		 *      the first SG entry, then if this first size in the page
3183 		 *      is >= the residual beyond 4 pages then use IEEE,
3184 		 *      otherwise use native SGL
3185 		 */
3186 		if (buff_len > (PAGE_SIZE * 5))
3187 			build_native_sgl = 1;
3188 		else if ((buff_len > (PAGE_SIZE * 4)) &&
3189 		    (buff_len <= (PAGE_SIZE * 5)) )
3190 		{
3191 			msg_phys = (uint64_t *)(uintptr_t)segs[0].ds_addr;
3192 			first_page_offset =
3193 			    ((uint32_t)(uint64_t)(uintptr_t)msg_phys &
3194 			    page_mask);
3195 			first_page_data_size = PAGE_SIZE - first_page_offset;
3196 			end_residual = buff_len % PAGE_SIZE;
3197 
3198 			/*
3199 			 * If offset into first page pushes the end of the data
3200 			 * beyond end of the 5th page, we need the extra PRP
3201 			 * list.
3202 			 */
3203 			if (first_page_data_size < end_residual)
3204 				build_native_sgl = 1;
3205 
3206 			/*
3207 			 * Check if first SG entry size is < residual beyond 4
3208 			 * pages.
3209 			 */
3210 			if (htole32(segs[0].ds_len) <
3211 			    (buff_len - (PAGE_SIZE * 4)))
3212 				build_native_sgl = 1;
3213 		}
3214 	}
3215 
3216 	/* check if native SGL is needed */
3217 	if (!build_native_sgl)
3218 		return 1;
3219 
3220 	/*
3221 	 * Native SGL is needed.
3222 	 * Put a chain element in main message frame that points to the first
3223 	 * chain buffer.
3224 	 *
3225 	 * NOTE:  The ChainOffset field must be 0 when using a chain pointer to
3226 	 *        a native SGL.
3227 	 */
3228 
3229 	/* Set main message chain element pointer */
3230 	main_chain_element = (pMpi25IeeeSgeChain64_t)cm->cm_sge;
3231 
3232 	/*
3233 	 * For NVMe the chain element needs to be the 2nd SGL entry in the main
3234 	 * message.
3235 	 */
3236 	main_chain_element = (Mpi25IeeeSgeChain64_t *)
3237 	    ((uint8_t *)main_chain_element + sizeof(MPI25_IEEE_SGE_CHAIN64));
3238 
3239 	/*
3240 	 * For the PRP entries, use the specially allocated buffer of
3241 	 * contiguous memory. PRP Page allocation failures should not happen
3242 	 * because there should be enough PRP page buffers to account for the
3243 	 * possible NVMe QDepth.
3244 	 */
3245 	prp_page_info = mpr_alloc_prp_page(sc);
3246 	KASSERT(prp_page_info != NULL, ("%s: There are no PRP Pages left to be "
3247 	    "used for building a native NVMe SGL.\n", __func__));
3248 	curr_buff = (uint32_t *)prp_page_info->prp_page;
3249 	msg_phys = (uint64_t *)(uintptr_t)prp_page_info->prp_page_busaddr;
3250 
3251 	/*
3252 	 * Insert the allocated PRP page into the command's PRP page list. This
3253 	 * will be freed when the command is freed.
3254 	 */
3255 	TAILQ_INSERT_TAIL(&cm->cm_prp_page_list, prp_page_info, prp_page_link);
3256 
3257 	/*
3258 	 * Check if we are within 1 entry of a page boundary we don't want our
3259 	 * first entry to be a PRP List entry.
3260 	 */
3261 	page_mask_result = (uintptr_t)((uint8_t *)curr_buff + prp_size) &
3262 	    page_mask;
3263 	if (!page_mask_result) {
3264 		/* Bump up to next page boundary. */
3265 		curr_buff = (uint32_t *)((uint8_t *)curr_buff + prp_size);
3266 		msg_phys = (uint64_t *)((uint8_t *)msg_phys + prp_size);
3267 	}
3268 
3269 	/* Fill in the chain element and make it an NVMe segment type. */
3270 	main_chain_element->Address.High =
3271 	    htole32((uint32_t)((uint64_t)(uintptr_t)msg_phys >> 32));
3272 	main_chain_element->Address.Low =
3273 	    htole32((uint32_t)(uintptr_t)msg_phys);
3274 	main_chain_element->NextChainOffset = 0;
3275 	main_chain_element->Flags = MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT |
3276 	    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR |
3277 	    MPI26_IEEE_SGE_FLAGS_NSF_NVME_PRP;
3278 
3279 	/* Set SGL pointer to start of contiguous PCIe buffer. */
3280 	ptr_sgl = curr_buff;
3281 	sge_dwords = 2;
3282 	num_entries = 0;
3283 
3284 	/*
3285 	 * NVMe has a very convoluted PRP format. One PRP is required for each
3286 	 * page or partial page. We need to split up OS SG entries if they are
3287 	 * longer than one page or cross a page boundary. We also have to insert
3288 	 * a PRP list pointer entry as the last entry in each physical page of
3289 	 * the PRP list.
3290 	 *
3291 	 * NOTE: The first PRP "entry" is actually placed in the first SGL entry
3292 	 * in the main message in IEEE 64 format. The 2nd entry in the main
3293 	 * message is the chain element, and the rest of the PRP entries are
3294 	 * built in the contiguous PCIe buffer.
3295 	 */
3296 	first_prp_entry = 1;
3297 	ptr_first_sgl = (uint32_t *)cm->cm_sge;
3298 
3299 	for (i = 0; i < segs_left; i++) {
3300 		/* Get physical address and length of this SG entry. */
3301 		paddr = segs[i].ds_addr;
3302 		length = segs[i].ds_len;
3303 
3304 		/*
3305 		 * Check whether a given SGE buffer lies on a non-PAGED
3306 		 * boundary if this is not the first page. If so, this is not
3307 		 * expected so have FW build the SGL.
3308 		 */
3309 		if ((i != 0) && (((uint32_t)paddr & page_mask) != 0)) {
3310 			mpr_dprint(sc, MPR_ERROR, "Unaligned SGE while "
3311 			    "building NVMe PRPs, low address is 0x%x\n",
3312 			    (uint32_t)paddr);
3313 			return 1;
3314 		}
3315 
3316 		/* Apart from last SGE, if any other SGE boundary is not page
3317 		 * aligned then it means that hole exists. Existence of hole
3318 		 * leads to data corruption. So fallback to IEEE SGEs.
3319 		 */
3320 		if (i != (segs_left - 1)) {
3321 			if (((uint32_t)paddr + length) & page_mask) {
3322 				mpr_dprint(sc, MPR_ERROR, "Unaligned SGE "
3323 				    "boundary while building NVMe PRPs, low "
3324 				    "address: 0x%x and length: %u\n",
3325 				    (uint32_t)paddr, length);
3326 				return 1;
3327 			}
3328 		}
3329 
3330 		/* Loop while the length is not zero. */
3331 		while (length) {
3332 			/*
3333 			 * Check if we need to put a list pointer here if we are
3334 			 * at page boundary - prp_size.
3335 			 */
3336 			page_mask_result = (uintptr_t)((uint8_t *)ptr_sgl +
3337 			    prp_size) & page_mask;
3338 			if (!page_mask_result) {
3339 				/*
3340 				 * Need to put a PRP list pointer here.
3341 				 */
3342 				msg_phys = (uint64_t *)((uint8_t *)msg_phys +
3343 				    prp_size);
3344 				*ptr_sgl = htole32((uintptr_t)msg_phys);
3345 				*(ptr_sgl+1) = htole32((uint64_t)(uintptr_t)
3346 				    msg_phys >> 32);
3347 				ptr_sgl += sge_dwords;
3348 				num_entries++;
3349 			}
3350 
3351 			/* Need to handle if entry will be part of a page. */
3352 			offset = (uint32_t)paddr & page_mask;
3353 			entry_len = PAGE_SIZE - offset;
3354 			if (first_prp_entry) {
3355 				/*
3356 				 * Put IEEE entry in first SGE in main message.
3357 				 * (Simple element, System addr, not end of
3358 				 * list.)
3359 				 */
3360 				*ptr_first_sgl = htole32((uint32_t)paddr);
3361 				*(ptr_first_sgl + 1) =
3362 				    htole32((uint32_t)((uint64_t)paddr >> 32));
3363 				*(ptr_first_sgl + 2) = htole32(entry_len);
3364 				*(ptr_first_sgl + 3) = 0;
3365 
3366 				/* No longer the first PRP entry. */
3367 				first_prp_entry = 0;
3368 			} else {
3369 				/* Put entry in list. */
3370 				*ptr_sgl = htole32((uint32_t)paddr);
3371 				*(ptr_sgl + 1) =
3372 				    htole32((uint32_t)((uint64_t)paddr >> 32));
3373 
3374 				/* Bump ptr_sgl, msg_phys, and num_entries. */
3375 				ptr_sgl += sge_dwords;
3376 				msg_phys = (uint64_t *)((uint8_t *)msg_phys +
3377 				    prp_size);
3378 				num_entries++;
3379 			}
3380 
3381 			/* Bump the phys address by the entry_len. */
3382 			paddr += entry_len;
3383 
3384 			/* Decrement length accounting for last partial page. */
3385 			if (entry_len > length)
3386 				length = 0;
3387 			else
3388 				length -= entry_len;
3389 		}
3390 	}
3391 
3392 	/* Set chain element Length. */
3393 	main_chain_element->Length = htole32(num_entries * prp_size);
3394 
3395 	/* Return 0, indicating we built a native SGL. */
3396 	return 0;
3397 }
3398 
3399 /*
3400  * Add a chain element as the next SGE for the specified command.
3401  * Reset cm_sge and cm_sgesize to indicate all the available space. Chains are
3402  * only required for IEEE commands.  Therefore there is no code for commands
3403  * that have the MPR_CM_FLAGS_SGE_SIMPLE flag set (and those commands
3404  * shouldn't be requesting chains).
3405  */
3406 static int
mpr_add_chain(struct mpr_command * cm,int segsleft)3407 mpr_add_chain(struct mpr_command *cm, int segsleft)
3408 {
3409 	struct mpr_softc *sc = cm->cm_sc;
3410 	MPI2_REQUEST_HEADER *req;
3411 	MPI25_IEEE_SGE_CHAIN64 *ieee_sgc;
3412 	struct mpr_chain *chain;
3413 	int sgc_size, current_segs, rem_segs, segs_per_frame;
3414 	uint8_t next_chain_offset = 0;
3415 
3416 	/*
3417 	 * Fail if a command is requesting a chain for SIMPLE SGE's.  For SAS3
3418 	 * only IEEE commands should be requesting chains.  Return some error
3419 	 * code other than 0.
3420 	 */
3421 	if (cm->cm_flags & MPR_CM_FLAGS_SGE_SIMPLE) {
3422 		mpr_dprint(sc, MPR_ERROR, "A chain element cannot be added to "
3423 		    "an MPI SGL.\n");
3424 		return(ENOBUFS);
3425 	}
3426 
3427 	sgc_size = sizeof(MPI25_IEEE_SGE_CHAIN64);
3428 	if (cm->cm_sglsize < sgc_size)
3429 		panic("MPR: Need SGE Error Code\n");
3430 
3431 	chain = mpr_alloc_chain(cm->cm_sc);
3432 	if (chain == NULL)
3433 		return (ENOBUFS);
3434 
3435 	/*
3436 	 * Note: a double-linked list is used to make it easier to walk for
3437 	 * debugging.
3438 	 */
3439 	TAILQ_INSERT_TAIL(&cm->cm_chain_list, chain, chain_link);
3440 
3441 	/*
3442 	 * Need to know if the number of frames left is more than 1 or not.  If
3443 	 * more than 1 frame is required, NextChainOffset will need to be set,
3444 	 * which will just be the last segment of the frame.
3445 	 */
3446 	rem_segs = 0;
3447 	if (cm->cm_sglsize < (sgc_size * segsleft)) {
3448 		/*
3449 		 * rem_segs is the number of segment remaining after the
3450 		 * segments that will go into the current frame.  Since it is
3451 		 * known that at least one more frame is required, account for
3452 		 * the chain element.  To know if more than one more frame is
3453 		 * required, just check if there will be a remainder after using
3454 		 * the current frame (with this chain) and the next frame.  If
3455 		 * so the NextChainOffset must be the last element of the next
3456 		 * frame.
3457 		 */
3458 		current_segs = (cm->cm_sglsize / sgc_size) - 1;
3459 		rem_segs = segsleft - current_segs;
3460 		segs_per_frame = sc->chain_frame_size / sgc_size;
3461 		if (rem_segs > segs_per_frame) {
3462 			next_chain_offset = segs_per_frame - 1;
3463 		}
3464 	}
3465 	ieee_sgc = &((MPI25_SGE_IO_UNION *)cm->cm_sge)->IeeeChain;
3466 	ieee_sgc->Length = next_chain_offset ?
3467 	    htole32((uint32_t)sc->chain_frame_size) :
3468 	    htole32((uint32_t)rem_segs * (uint32_t)sgc_size);
3469 	ieee_sgc->NextChainOffset = next_chain_offset;
3470 	ieee_sgc->Flags = (MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT |
3471 	    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR);
3472 	ieee_sgc->Address.Low = htole32(chain->chain_busaddr);
3473 	ieee_sgc->Address.High = htole32(chain->chain_busaddr >> 32);
3474 	cm->cm_sge = &((MPI25_SGE_IO_UNION *)chain->chain)->IeeeSimple;
3475 	req = (MPI2_REQUEST_HEADER *)cm->cm_req;
3476 	req->ChainOffset = (sc->chain_frame_size - sgc_size) >> 4;
3477 
3478 	cm->cm_sglsize = sc->chain_frame_size;
3479 	return (0);
3480 }
3481 
3482 /*
3483  * Add one scatter-gather element to the scatter-gather list for a command.
3484  * Maintain cm_sglsize and cm_sge as the remaining size and pointer to the
3485  * next SGE to fill in, respectively.  In Gen3, the MPI SGL does not have a
3486  * chain, so don't consider any chain additions.
3487  */
3488 int
mpr_push_sge(struct mpr_command * cm,MPI2_SGE_SIMPLE64 * sge,size_t len,int segsleft)3489 mpr_push_sge(struct mpr_command *cm, MPI2_SGE_SIMPLE64 *sge, size_t len,
3490     int segsleft)
3491 {
3492 	uint32_t saved_buf_len, saved_address_low, saved_address_high;
3493 	u32 sge_flags;
3494 
3495 	/*
3496 	 * case 1: >=1 more segment, no room for anything (error)
3497 	 * case 2: 1 more segment and enough room for it
3498          */
3499 
3500 	if (cm->cm_sglsize < (segsleft * sizeof(MPI2_SGE_SIMPLE64))) {
3501 		mpr_dprint(cm->cm_sc, MPR_ERROR,
3502 		    "%s: warning: Not enough room for MPI SGL in frame.\n",
3503 		    __func__);
3504 		return(ENOBUFS);
3505 	}
3506 
3507 	KASSERT(segsleft == 1,
3508 	    ("segsleft cannot be more than 1 for an MPI SGL; segsleft = %d\n",
3509 	    segsleft));
3510 
3511 	/*
3512 	 * There is one more segment left to add for the MPI SGL and there is
3513 	 * enough room in the frame to add it.  This is the normal case because
3514 	 * MPI SGL's don't have chains, otherwise something is wrong.
3515 	 *
3516 	 * If this is a bi-directional request, need to account for that
3517 	 * here.  Save the pre-filled sge values.  These will be used
3518 	 * either for the 2nd SGL or for a single direction SGL.  If
3519 	 * cm_out_len is non-zero, this is a bi-directional request, so
3520 	 * fill in the OUT SGL first, then the IN SGL, otherwise just
3521 	 * fill in the IN SGL.  Note that at this time, when filling in
3522 	 * 2 SGL's for a bi-directional request, they both use the same
3523 	 * DMA buffer (same cm command).
3524 	 */
3525 	saved_buf_len = sge->FlagsLength & 0x00FFFFFF;
3526 	saved_address_low = sge->Address.Low;
3527 	saved_address_high = sge->Address.High;
3528 	if (cm->cm_out_len) {
3529 		sge->FlagsLength = cm->cm_out_len |
3530 		    ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
3531 		    MPI2_SGE_FLAGS_END_OF_BUFFER |
3532 		    MPI2_SGE_FLAGS_HOST_TO_IOC |
3533 		    MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
3534 		    MPI2_SGE_FLAGS_SHIFT);
3535 		cm->cm_sglsize -= len;
3536 		/* Endian Safe code */
3537 		sge_flags = sge->FlagsLength;
3538 		sge->FlagsLength = htole32(sge_flags);
3539 		bcopy(sge, cm->cm_sge, len);
3540 		cm->cm_sge = (MPI2_SGE_IO_UNION *)((uintptr_t)cm->cm_sge + len);
3541 	}
3542 	sge->FlagsLength = saved_buf_len |
3543 	    ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
3544 	    MPI2_SGE_FLAGS_END_OF_BUFFER |
3545 	    MPI2_SGE_FLAGS_LAST_ELEMENT |
3546 	    MPI2_SGE_FLAGS_END_OF_LIST |
3547 	    MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
3548 	    MPI2_SGE_FLAGS_SHIFT);
3549 	if (cm->cm_flags & MPR_CM_FLAGS_DATAIN) {
3550 		sge->FlagsLength |=
3551 		    ((uint32_t)(MPI2_SGE_FLAGS_IOC_TO_HOST) <<
3552 		    MPI2_SGE_FLAGS_SHIFT);
3553 	} else {
3554 		sge->FlagsLength |=
3555 		    ((uint32_t)(MPI2_SGE_FLAGS_HOST_TO_IOC) <<
3556 		    MPI2_SGE_FLAGS_SHIFT);
3557 	}
3558 	sge->Address.Low = saved_address_low;
3559 	sge->Address.High = saved_address_high;
3560 
3561 	cm->cm_sglsize -= len;
3562 	/* Endian Safe code */
3563 	sge_flags = sge->FlagsLength;
3564 	sge->FlagsLength = htole32(sge_flags);
3565 	bcopy(sge, cm->cm_sge, len);
3566 	cm->cm_sge = (MPI2_SGE_IO_UNION *)((uintptr_t)cm->cm_sge + len);
3567 	return (0);
3568 }
3569 
3570 /*
3571  * Add one IEEE scatter-gather element (chain or simple) to the IEEE scatter-
3572  * gather list for a command.  Maintain cm_sglsize and cm_sge as the
3573  * remaining size and pointer to the next SGE to fill in, respectively.
3574  */
3575 int
mpr_push_ieee_sge(struct mpr_command * cm,void * sgep,int segsleft)3576 mpr_push_ieee_sge(struct mpr_command *cm, void *sgep, int segsleft)
3577 {
3578 	MPI2_IEEE_SGE_SIMPLE64 *sge = sgep;
3579 	int error, ieee_sge_size = sizeof(MPI25_SGE_IO_UNION);
3580 	uint32_t saved_buf_len, saved_address_low, saved_address_high;
3581 	uint32_t sge_length;
3582 
3583 	/*
3584 	 * case 1: No room for chain or segment (error).
3585 	 * case 2: Two or more segments left but only room for chain.
3586 	 * case 3: Last segment and room for it, so set flags.
3587 	 */
3588 
3589 	/*
3590 	 * There should be room for at least one element, or there is a big
3591 	 * problem.
3592 	 */
3593 	if (cm->cm_sglsize < ieee_sge_size)
3594 		panic("MPR: Need SGE Error Code\n");
3595 
3596 	if ((segsleft >= 2) && (cm->cm_sglsize < (ieee_sge_size * 2))) {
3597 		if ((error = mpr_add_chain(cm, segsleft)) != 0)
3598 			return (error);
3599 	}
3600 
3601 	if (segsleft == 1) {
3602 		/*
3603 		 * If this is a bi-directional request, need to account for that
3604 		 * here.  Save the pre-filled sge values.  These will be used
3605 		 * either for the 2nd SGL or for a single direction SGL.  If
3606 		 * cm_out_len is non-zero, this is a bi-directional request, so
3607 		 * fill in the OUT SGL first, then the IN SGL, otherwise just
3608 		 * fill in the IN SGL.  Note that at this time, when filling in
3609 		 * 2 SGL's for a bi-directional request, they both use the same
3610 		 * DMA buffer (same cm command).
3611 		 */
3612 		saved_buf_len = sge->Length;
3613 		saved_address_low = sge->Address.Low;
3614 		saved_address_high = sge->Address.High;
3615 		if (cm->cm_out_len) {
3616 			sge->Length = cm->cm_out_len;
3617 			sge->Flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
3618 			    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR);
3619 			cm->cm_sglsize -= ieee_sge_size;
3620 			/* Endian Safe code */
3621 			sge_length = sge->Length;
3622 			sge->Length = htole32(sge_length);
3623 			bcopy(sgep, cm->cm_sge, ieee_sge_size);
3624 			cm->cm_sge =
3625 			    (MPI25_SGE_IO_UNION *)((uintptr_t)cm->cm_sge +
3626 			    ieee_sge_size);
3627 		}
3628 		sge->Length = saved_buf_len;
3629 		sge->Flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
3630 		    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR |
3631 		    MPI25_IEEE_SGE_FLAGS_END_OF_LIST);
3632 		sge->Address.Low = saved_address_low;
3633 		sge->Address.High = saved_address_high;
3634 	}
3635 
3636 	cm->cm_sglsize -= ieee_sge_size;
3637 	/* Endian Safe code */
3638 	sge_length = sge->Length;
3639 	sge->Length = htole32(sge_length);
3640 	bcopy(sgep, cm->cm_sge, ieee_sge_size);
3641 	cm->cm_sge = (MPI25_SGE_IO_UNION *)((uintptr_t)cm->cm_sge +
3642 	    ieee_sge_size);
3643 	return (0);
3644 }
3645 
3646 /*
3647  * Add one dma segment to the scatter-gather list for a command.
3648  */
3649 int
mpr_add_dmaseg(struct mpr_command * cm,vm_paddr_t pa,size_t len,u_int flags,int segsleft)3650 mpr_add_dmaseg(struct mpr_command *cm, vm_paddr_t pa, size_t len, u_int flags,
3651     int segsleft)
3652 {
3653 	MPI2_SGE_SIMPLE64 sge;
3654 	MPI2_IEEE_SGE_SIMPLE64 ieee_sge;
3655 
3656 	if (!(cm->cm_flags & MPR_CM_FLAGS_SGE_SIMPLE)) {
3657 		ieee_sge.Flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
3658 		    MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR);
3659 		ieee_sge.Length = len;
3660 		mpr_from_u64(pa, &ieee_sge.Address);
3661 
3662 		return (mpr_push_ieee_sge(cm, &ieee_sge, segsleft));
3663 	} else {
3664 		/*
3665 		 * This driver always uses 64-bit address elements for
3666 		 * simplicity.
3667 		 */
3668 		flags |= MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
3669 		    MPI2_SGE_FLAGS_64_BIT_ADDRESSING;
3670 		/* Set Endian safe macro in mpr_push_sge */
3671 		sge.FlagsLength = len | (flags << MPI2_SGE_FLAGS_SHIFT);
3672 		mpr_from_u64(pa, &sge.Address);
3673 
3674 		return (mpr_push_sge(cm, &sge, sizeof sge, segsleft));
3675 	}
3676 }
3677 
3678 static void
mpr_data_cb(void * arg,bus_dma_segment_t * segs,int nsegs,int error)3679 mpr_data_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
3680 {
3681 	struct mpr_softc *sc;
3682 	struct mpr_command *cm;
3683 	u_int i, dir, sflags;
3684 
3685 	cm = (struct mpr_command *)arg;
3686 	sc = cm->cm_sc;
3687 
3688 	/*
3689 	 * In this case, just print out a warning and let the chip tell the
3690 	 * user they did the wrong thing.
3691 	 */
3692 	if ((cm->cm_max_segs != 0) && (nsegs > cm->cm_max_segs)) {
3693 		mpr_dprint(sc, MPR_ERROR, "%s: warning: busdma returned %d "
3694 		    "segments, more than the %d allowed\n", __func__, nsegs,
3695 		    cm->cm_max_segs);
3696 	}
3697 
3698 	/*
3699 	 * Set up DMA direction flags.  Bi-directional requests are also handled
3700 	 * here.  In that case, both direction flags will be set.
3701 	 */
3702 	sflags = 0;
3703 	if (cm->cm_flags & MPR_CM_FLAGS_SMP_PASS) {
3704 		/*
3705 		 * We have to add a special case for SMP passthrough, there
3706 		 * is no easy way to generically handle it.  The first
3707 		 * S/G element is used for the command (therefore the
3708 		 * direction bit needs to be set).  The second one is used
3709 		 * for the reply.  We'll leave it to the caller to make
3710 		 * sure we only have two buffers.
3711 		 */
3712 		/*
3713 		 * Even though the busdma man page says it doesn't make
3714 		 * sense to have both direction flags, it does in this case.
3715 		 * We have one s/g element being accessed in each direction.
3716 		 */
3717 		dir = BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD;
3718 
3719 		/*
3720 		 * Set the direction flag on the first buffer in the SMP
3721 		 * passthrough request.  We'll clear it for the second one.
3722 		 */
3723 		sflags |= MPI2_SGE_FLAGS_DIRECTION |
3724 			  MPI2_SGE_FLAGS_END_OF_BUFFER;
3725 	} else if (cm->cm_flags & MPR_CM_FLAGS_DATAOUT) {
3726 		sflags |= MPI2_SGE_FLAGS_HOST_TO_IOC;
3727 		dir = BUS_DMASYNC_PREWRITE;
3728 	} else
3729 		dir = BUS_DMASYNC_PREREAD;
3730 
3731 	/* Check if a native SG list is needed for an NVMe PCIe device. */
3732 	if (cm->cm_targ && cm->cm_targ->is_nvme &&
3733 	    mpr_check_pcie_native_sgl(sc, cm, segs, nsegs) == 0) {
3734 		/* A native SG list was built, skip to end. */
3735 		goto out;
3736 	}
3737 
3738 	for (i = 0; i < nsegs; i++) {
3739 		if ((cm->cm_flags & MPR_CM_FLAGS_SMP_PASS) && (i != 0)) {
3740 			sflags &= ~MPI2_SGE_FLAGS_DIRECTION;
3741 		}
3742 		error = mpr_add_dmaseg(cm, segs[i].ds_addr, segs[i].ds_len,
3743 		    sflags, nsegs - i);
3744 		if (error != 0) {
3745 			/* Resource shortage, roll back! */
3746 			if (ratecheck(&sc->lastfail, &mpr_chainfail_interval))
3747 				mpr_dprint(sc, MPR_INFO, "Out of chain frames, "
3748 				    "consider increasing hw.mpr.max_chains.\n");
3749 			cm->cm_flags |= MPR_CM_FLAGS_CHAIN_FAILED;
3750 			mpr_complete_command(sc, cm);
3751 			return;
3752 		}
3753 	}
3754 
3755 out:
3756 	bus_dmamap_sync(sc->buffer_dmat, cm->cm_dmamap, dir);
3757 	mpr_enqueue_request(sc, cm);
3758 
3759 	return;
3760 }
3761 
3762 static void
mpr_data_cb2(void * arg,bus_dma_segment_t * segs,int nsegs,bus_size_t mapsize,int error)3763 mpr_data_cb2(void *arg, bus_dma_segment_t *segs, int nsegs, bus_size_t mapsize,
3764 	     int error)
3765 {
3766 	mpr_data_cb(arg, segs, nsegs, error);
3767 }
3768 
3769 /*
3770  * This is the routine to enqueue commands ansynchronously.
3771  * Note that the only error path here is from bus_dmamap_load(), which can
3772  * return EINPROGRESS if it is waiting for resources.  Other than this, it's
3773  * assumed that if you have a command in-hand, then you have enough credits
3774  * to use it.
3775  */
3776 int
mpr_map_command(struct mpr_softc * sc,struct mpr_command * cm)3777 mpr_map_command(struct mpr_softc *sc, struct mpr_command *cm)
3778 {
3779 	int error = 0;
3780 
3781 	if (cm->cm_flags & MPR_CM_FLAGS_USE_UIO) {
3782 		error = bus_dmamap_load_uio(sc->buffer_dmat, cm->cm_dmamap,
3783 		    &cm->cm_uio, mpr_data_cb2, cm, 0);
3784 	} else if (cm->cm_flags & MPR_CM_FLAGS_USE_CCB) {
3785 		error = bus_dmamap_load_ccb(sc->buffer_dmat, cm->cm_dmamap,
3786 		    cm->cm_data, mpr_data_cb, cm, 0);
3787 	} else if ((cm->cm_data != NULL) && (cm->cm_length != 0)) {
3788 		error = bus_dmamap_load(sc->buffer_dmat, cm->cm_dmamap,
3789 		    cm->cm_data, cm->cm_length, mpr_data_cb, cm, 0);
3790 	} else {
3791 		/* Add a zero-length element as needed */
3792 		if (cm->cm_sge != NULL)
3793 			mpr_add_dmaseg(cm, 0, 0, 0, 1);
3794 		mpr_enqueue_request(sc, cm);
3795 	}
3796 
3797 	return (error);
3798 }
3799 
3800 /*
3801  * This is the routine to enqueue commands synchronously.  An error of
3802  * EINPROGRESS from mpr_map_command() is ignored since the command will
3803  * be executed and enqueued automatically.  Other errors come from msleep().
3804  */
3805 int
mpr_wait_command(struct mpr_softc * sc,struct mpr_command ** cmp,int timeout,int sleep_flag)3806 mpr_wait_command(struct mpr_softc *sc, struct mpr_command **cmp, int timeout,
3807     int sleep_flag)
3808 {
3809 	int error, rc;
3810 	struct timeval cur_time, start_time;
3811 	struct mpr_command *cm = *cmp;
3812 
3813 	if (sc->mpr_flags & MPR_FLAGS_DIAGRESET)
3814 		return  EBUSY;
3815 
3816 	cm->cm_complete = NULL;
3817 	cm->cm_flags |= (MPR_CM_FLAGS_WAKEUP + MPR_CM_FLAGS_POLLED);
3818 	error = mpr_map_command(sc, cm);
3819 	if ((error != 0) && (error != EINPROGRESS))
3820 		return (error);
3821 
3822 	// Check for context and wait for 50 mSec at a time until time has
3823 	// expired or the command has finished.  If msleep can't be used, need
3824 	// to poll.
3825 #if __FreeBSD_version >= 1000029
3826 	if (curthread->td_no_sleeping)
3827 #else //__FreeBSD_version < 1000029
3828 	if (curthread->td_pflags & TDP_NOSLEEPING)
3829 #endif //__FreeBSD_version >= 1000029
3830 		sleep_flag = NO_SLEEP;
3831 	getmicrouptime(&start_time);
3832 	if (mtx_owned(&sc->mpr_mtx) && sleep_flag == CAN_SLEEP) {
3833 		error = msleep(cm, &sc->mpr_mtx, 0, "mprwait", timeout*hz);
3834 		if (error == EWOULDBLOCK) {
3835 			/*
3836 			 * Record the actual elapsed time in the case of a
3837 			 * timeout for the message below.
3838 			 */
3839 			getmicrouptime(&cur_time);
3840 			timevalsub(&cur_time, &start_time);
3841 		}
3842 	} else {
3843 		while ((cm->cm_flags & MPR_CM_FLAGS_COMPLETE) == 0) {
3844 			mpr_intr_locked(sc);
3845 			if (sleep_flag == CAN_SLEEP)
3846 				pause("mprwait", hz/20);
3847 			else
3848 				DELAY(50000);
3849 
3850 			getmicrouptime(&cur_time);
3851 			timevalsub(&cur_time, &start_time);
3852 			if (cur_time.tv_sec > timeout) {
3853 				error = EWOULDBLOCK;
3854 				break;
3855 			}
3856 		}
3857 	}
3858 
3859 	if (error == EWOULDBLOCK) {
3860 		if (cm->cm_timeout_handler == NULL) {
3861 			mpr_dprint(sc, MPR_FAULT, "Calling Reinit from %s, timeout=%d,"
3862 			    " elapsed=%jd\n", __func__, timeout,
3863 			    (intmax_t)cur_time.tv_sec);
3864 			rc = mpr_reinit(sc);
3865 			mpr_dprint(sc, MPR_FAULT, "Reinit %s\n", (rc == 0) ? "success" :
3866 			    "failed");
3867 		} else
3868 			cm->cm_timeout_handler(sc, cm);
3869 		if (sc->mpr_flags & MPR_FLAGS_REALLOCATED) {
3870 			/*
3871 			 * Tell the caller that we freed the command in a
3872 			 * reinit.
3873 			 */
3874 			*cmp = NULL;
3875 		}
3876 		error = ETIMEDOUT;
3877 	}
3878 	return (error);
3879 }
3880 
3881 /*
3882  * This is the routine to enqueue a command synchonously and poll for
3883  * completion.  Its use should be rare.
3884  */
3885 int
mpr_request_polled(struct mpr_softc * sc,struct mpr_command ** cmp)3886 mpr_request_polled(struct mpr_softc *sc, struct mpr_command **cmp)
3887 {
3888 	int error, rc;
3889 	struct timeval cur_time, start_time;
3890 	struct mpr_command *cm = *cmp;
3891 
3892 	error = 0;
3893 
3894 	cm->cm_flags |= MPR_CM_FLAGS_POLLED;
3895 	cm->cm_complete = NULL;
3896 	mpr_map_command(sc, cm);
3897 
3898 	getmicrouptime(&start_time);
3899 	while ((cm->cm_flags & MPR_CM_FLAGS_COMPLETE) == 0) {
3900 		mpr_intr_locked(sc);
3901 
3902 		if (mtx_owned(&sc->mpr_mtx))
3903 			msleep(&sc->msleep_fake_chan, &sc->mpr_mtx, 0,
3904 			    "mprpoll", hz/20);
3905 		else
3906 			pause("mprpoll", hz/20);
3907 
3908 		/*
3909 		 * Check for real-time timeout and fail if more than 60 seconds.
3910 		 */
3911 		getmicrouptime(&cur_time);
3912 		timevalsub(&cur_time, &start_time);
3913 		if (cur_time.tv_sec > 60) {
3914 			mpr_dprint(sc, MPR_FAULT, "polling failed\n");
3915 			error = ETIMEDOUT;
3916 			break;
3917 		}
3918 	}
3919 	cm->cm_state = MPR_CM_STATE_BUSY;
3920 	if (error) {
3921 		mpr_dprint(sc, MPR_FAULT, "Calling Reinit from %s\n", __func__);
3922 		rc = mpr_reinit(sc);
3923 		mpr_dprint(sc, MPR_FAULT, "Reinit %s\n", (rc == 0) ? "success" :
3924 		    "failed");
3925 
3926 		if (sc->mpr_flags & MPR_FLAGS_REALLOCATED) {
3927 			/*
3928 			 * Tell the caller that we freed the command in a
3929 			 * reinit.
3930 			 */
3931 			*cmp = NULL;
3932 		}
3933 	}
3934 	return (error);
3935 }
3936 
3937 /*
3938  * The MPT driver had a verbose interface for config pages.  In this driver,
3939  * reduce it to much simpler terms, similar to the Linux driver.
3940  */
3941 int
mpr_read_config_page(struct mpr_softc * sc,struct mpr_config_params * params)3942 mpr_read_config_page(struct mpr_softc *sc, struct mpr_config_params *params)
3943 {
3944 	MPI2_CONFIG_REQUEST *req;
3945 	struct mpr_command *cm;
3946 	int error;
3947 
3948 	if (sc->mpr_flags & MPR_FLAGS_BUSY) {
3949 		return (EBUSY);
3950 	}
3951 
3952 	cm = mpr_alloc_command(sc);
3953 	if (cm == NULL) {
3954 		return (EBUSY);
3955 	}
3956 
3957 	req = (MPI2_CONFIG_REQUEST *)cm->cm_req;
3958 	req->Function = MPI2_FUNCTION_CONFIG;
3959 	req->Action = params->action;
3960 	req->SGLFlags = 0;
3961 	req->ChainOffset = 0;
3962 	req->PageAddress = params->page_address;
3963 	if (params->hdr.Struct.PageType == MPI2_CONFIG_PAGETYPE_EXTENDED) {
3964 		MPI2_CONFIG_EXTENDED_PAGE_HEADER *hdr;
3965 
3966 		hdr = &params->hdr.Ext;
3967 		req->ExtPageType = hdr->ExtPageType;
3968 		req->ExtPageLength = hdr->ExtPageLength;
3969 		req->Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED;
3970 		req->Header.PageLength = 0; /* Must be set to zero */
3971 		req->Header.PageNumber = hdr->PageNumber;
3972 		req->Header.PageVersion = hdr->PageVersion;
3973 	} else {
3974 		MPI2_CONFIG_PAGE_HEADER *hdr;
3975 
3976 		hdr = &params->hdr.Struct;
3977 		req->Header.PageType = hdr->PageType;
3978 		req->Header.PageNumber = hdr->PageNumber;
3979 		req->Header.PageLength = hdr->PageLength;
3980 		req->Header.PageVersion = hdr->PageVersion;
3981 	}
3982 
3983 	cm->cm_data = params->buffer;
3984 	cm->cm_length = params->length;
3985 	if (cm->cm_data != NULL) {
3986 		cm->cm_sge = &req->PageBufferSGE;
3987 		cm->cm_sglsize = sizeof(MPI2_SGE_IO_UNION);
3988 		cm->cm_flags = MPR_CM_FLAGS_SGE_SIMPLE | MPR_CM_FLAGS_DATAIN;
3989 	} else
3990 		cm->cm_sge = NULL;
3991 	cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
3992 
3993 	cm->cm_complete_data = params;
3994 	if (params->callback != NULL) {
3995 		cm->cm_complete = mpr_config_complete;
3996 		return (mpr_map_command(sc, cm));
3997 	} else {
3998 		error = mpr_wait_command(sc, &cm, 0, CAN_SLEEP);
3999 		if (error) {
4000 			mpr_dprint(sc, MPR_FAULT,
4001 			    "Error %d reading config page\n", error);
4002 			if (cm != NULL)
4003 				mpr_free_command(sc, cm);
4004 			return (error);
4005 		}
4006 		mpr_config_complete(sc, cm);
4007 	}
4008 
4009 	return (0);
4010 }
4011 
4012 int
mpr_write_config_page(struct mpr_softc * sc,struct mpr_config_params * params)4013 mpr_write_config_page(struct mpr_softc *sc, struct mpr_config_params *params)
4014 {
4015 	return (EINVAL);
4016 }
4017 
4018 static void
mpr_config_complete(struct mpr_softc * sc,struct mpr_command * cm)4019 mpr_config_complete(struct mpr_softc *sc, struct mpr_command *cm)
4020 {
4021 	MPI2_CONFIG_REPLY *reply;
4022 	struct mpr_config_params *params;
4023 
4024 	MPR_FUNCTRACE(sc);
4025 	params = cm->cm_complete_data;
4026 
4027 	if (cm->cm_data != NULL) {
4028 		bus_dmamap_sync(sc->buffer_dmat, cm->cm_dmamap,
4029 		    BUS_DMASYNC_POSTREAD);
4030 		bus_dmamap_unload(sc->buffer_dmat, cm->cm_dmamap);
4031 	}
4032 
4033 	/*
4034 	 * XXX KDM need to do more error recovery?  This results in the
4035 	 * device in question not getting probed.
4036 	 */
4037 	if ((cm->cm_flags & MPR_CM_FLAGS_ERROR_MASK) != 0) {
4038 		params->status = MPI2_IOCSTATUS_BUSY;
4039 		goto done;
4040 	}
4041 
4042 	reply = (MPI2_CONFIG_REPLY *)cm->cm_reply;
4043 	if (reply == NULL) {
4044 		params->status = MPI2_IOCSTATUS_BUSY;
4045 		goto done;
4046 	}
4047 	params->status = reply->IOCStatus;
4048 	if (params->hdr.Struct.PageType == MPI2_CONFIG_PAGETYPE_EXTENDED) {
4049 		params->hdr.Ext.ExtPageType = reply->ExtPageType;
4050 		params->hdr.Ext.ExtPageLength = reply->ExtPageLength;
4051 		params->hdr.Ext.PageType = reply->Header.PageType;
4052 		params->hdr.Ext.PageNumber = reply->Header.PageNumber;
4053 		params->hdr.Ext.PageVersion = reply->Header.PageVersion;
4054 	} else {
4055 		params->hdr.Struct.PageType = reply->Header.PageType;
4056 		params->hdr.Struct.PageNumber = reply->Header.PageNumber;
4057 		params->hdr.Struct.PageLength = reply->Header.PageLength;
4058 		params->hdr.Struct.PageVersion = reply->Header.PageVersion;
4059 	}
4060 
4061 done:
4062 	mpr_free_command(sc, cm);
4063 	if (params->callback != NULL)
4064 		params->callback(sc, params);
4065 
4066 	return;
4067 }
4068