xref: /freebsd/sys/dev/ntb/ntb_transport.c (revision a2aef24aa3c8458e4036735dd6928b4ef77294e5)
1 /*-
2  * Copyright (c) 2016-2017 Alexander Motin <mav@FreeBSD.org>
3  * Copyright (C) 2013 Intel Corporation
4  * Copyright (C) 2015 EMC Corporation
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 /*
30  * The Non-Transparent Bridge (NTB) is a device that allows you to connect
31  * two or more systems using a PCI-e links, providing remote memory access.
32  *
33  * This module contains a transport for sending and receiving messages by
34  * writing to remote memory window(s) provided by underlying NTB device.
35  *
36  * NOTE: Much of the code in this module is shared with Linux. Any patches may
37  * be picked up and redistributed in Linux with a dual GPL/BSD license.
38  */
39 
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42 
43 #include <sys/param.h>
44 #include <sys/kernel.h>
45 #include <sys/systm.h>
46 #include <sys/bus.h>
47 #include <sys/ktr.h>
48 #include <sys/limits.h>
49 #include <sys/lock.h>
50 #include <sys/malloc.h>
51 #include <sys/mbuf.h>
52 #include <sys/module.h>
53 #include <sys/mutex.h>
54 #include <sys/queue.h>
55 #include <sys/sysctl.h>
56 #include <sys/taskqueue.h>
57 
58 #include <vm/vm.h>
59 #include <vm/pmap.h>
60 
61 #include <machine/bus.h>
62 
63 #include "ntb.h"
64 #include "ntb_transport.h"
65 
66 #define KTR_NTB KTR_SPARE3
67 
68 #define NTB_TRANSPORT_VERSION	4
69 
70 static SYSCTL_NODE(_hw, OID_AUTO, ntb_transport, CTLFLAG_RW, 0, "ntb_transport");
71 
72 static unsigned g_ntb_transport_debug_level;
73 SYSCTL_UINT(_hw_ntb_transport, OID_AUTO, debug_level, CTLFLAG_RWTUN,
74     &g_ntb_transport_debug_level, 0,
75     "ntb_transport log level -- higher is more verbose");
76 #define ntb_printf(lvl, ...) do {			\
77 	if ((lvl) <= g_ntb_transport_debug_level) {	\
78 		printf(__VA_ARGS__);			\
79 	}						\
80 } while (0)
81 
82 static unsigned transport_mtu = 0x10000;
83 
84 static uint64_t max_mw_size;
85 SYSCTL_UQUAD(_hw_ntb_transport, OID_AUTO, max_mw_size, CTLFLAG_RDTUN, &max_mw_size, 0,
86     "If enabled (non-zero), limit the size of large memory windows. "
87     "Both sides of the NTB MUST set the same value here.");
88 
89 static unsigned enable_xeon_watchdog;
90 SYSCTL_UINT(_hw_ntb_transport, OID_AUTO, enable_xeon_watchdog, CTLFLAG_RDTUN,
91     &enable_xeon_watchdog, 0, "If non-zero, write a register every second to "
92     "keep a watchdog from tearing down the NTB link");
93 
94 STAILQ_HEAD(ntb_queue_list, ntb_queue_entry);
95 
96 typedef uint32_t ntb_q_idx_t;
97 
98 struct ntb_queue_entry {
99 	/* ntb_queue list reference */
100 	STAILQ_ENTRY(ntb_queue_entry) entry;
101 
102 	/* info on data to be transferred */
103 	void		*cb_data;
104 	void		*buf;
105 	uint32_t	len;
106 	uint32_t	flags;
107 
108 	struct ntb_transport_qp		*qp;
109 	struct ntb_payload_header	*x_hdr;
110 	ntb_q_idx_t	index;
111 };
112 
113 struct ntb_rx_info {
114 	ntb_q_idx_t	entry;
115 };
116 
117 struct ntb_transport_qp {
118 	struct ntb_transport_ctx	*transport;
119 	device_t		 dev;
120 
121 	void			*cb_data;
122 
123 	bool			client_ready;
124 	volatile bool		link_is_up;
125 	uint8_t			qp_num;	/* Only 64 QPs are allowed.  0-63 */
126 
127 	struct ntb_rx_info	*rx_info;
128 	struct ntb_rx_info	*remote_rx_info;
129 
130 	void (*tx_handler)(struct ntb_transport_qp *qp, void *qp_data,
131 	    void *data, int len);
132 	struct ntb_queue_list	tx_free_q;
133 	struct mtx		ntb_tx_free_q_lock;
134 	caddr_t			tx_mw;
135 	bus_addr_t		tx_mw_phys;
136 	ntb_q_idx_t		tx_index;
137 	ntb_q_idx_t		tx_max_entry;
138 	uint64_t		tx_max_frame;
139 
140 	void (*rx_handler)(struct ntb_transport_qp *qp, void *qp_data,
141 	    void *data, int len);
142 	struct ntb_queue_list	rx_post_q;
143 	struct ntb_queue_list	rx_pend_q;
144 	/* ntb_rx_q_lock: synchronize access to rx_XXXX_q */
145 	struct mtx		ntb_rx_q_lock;
146 	struct task		rxc_db_work;
147 	struct taskqueue	*rxc_tq;
148 	caddr_t			rx_buff;
149 	ntb_q_idx_t		rx_index;
150 	ntb_q_idx_t		rx_max_entry;
151 	uint64_t		rx_max_frame;
152 
153 	void (*event_handler)(void *data, enum ntb_link_event status);
154 	struct callout		link_work;
155 	struct callout		rx_full;
156 
157 	uint64_t		last_rx_no_buf;
158 
159 	/* Stats */
160 	uint64_t		rx_bytes;
161 	uint64_t		rx_pkts;
162 	uint64_t		rx_ring_empty;
163 	uint64_t		rx_err_no_buf;
164 	uint64_t		rx_err_oflow;
165 	uint64_t		rx_err_ver;
166 	uint64_t		tx_bytes;
167 	uint64_t		tx_pkts;
168 	uint64_t		tx_ring_full;
169 	uint64_t		tx_err_no_buf;
170 
171 	struct mtx		tx_lock;
172 };
173 
174 struct ntb_transport_mw {
175 	vm_paddr_t	phys_addr;
176 	size_t		phys_size;
177 	size_t		xlat_align;
178 	size_t		xlat_align_size;
179 	bus_addr_t	addr_limit;
180 	/* Tx buff is off vbase / phys_addr */
181 	caddr_t		vbase;
182 	size_t		xlat_size;
183 	size_t		buff_size;
184 	/* Rx buff is off virt_addr / dma_addr */
185 	caddr_t		virt_addr;
186 	bus_addr_t	dma_addr;
187 };
188 
189 struct ntb_transport_child {
190 	device_t	dev;
191 	int		consumer;
192 	int		qpoff;
193 	int		qpcnt;
194 	struct ntb_transport_child *next;
195 };
196 
197 struct ntb_transport_ctx {
198 	device_t		 dev;
199 	struct ntb_transport_child *child;
200 	struct ntb_transport_mw	*mw_vec;
201 	struct ntb_transport_qp	*qp_vec;
202 	unsigned		mw_count;
203 	unsigned		qp_count;
204 	uint64_t		qp_bitmap;
205 	volatile bool		link_is_up;
206 	enum ntb_speed		link_speed;
207 	enum ntb_width		link_width;
208 	struct callout		link_work;
209 	struct callout		link_watchdog;
210 	struct task		link_cleanup;
211 };
212 
213 enum {
214 	NTBT_DESC_DONE_FLAG = 1 << 0,
215 	NTBT_LINK_DOWN_FLAG = 1 << 1,
216 };
217 
218 struct ntb_payload_header {
219 	ntb_q_idx_t ver;
220 	uint32_t len;
221 	uint32_t flags;
222 };
223 
224 enum {
225 	/*
226 	 * The order of this enum is part of the remote protocol.  Do not
227 	 * reorder without bumping protocol version (and it's probably best
228 	 * to keep the protocol in lock-step with the Linux NTB driver.
229 	 */
230 	NTBT_VERSION = 0,
231 	NTBT_QP_LINKS,
232 	NTBT_NUM_QPS,
233 	NTBT_NUM_MWS,
234 	/*
235 	 * N.B.: transport_link_work assumes MW1 enums = MW0 + 2.
236 	 */
237 	NTBT_MW0_SZ_HIGH,
238 	NTBT_MW0_SZ_LOW,
239 	NTBT_MW1_SZ_HIGH,
240 	NTBT_MW1_SZ_LOW,
241 
242 	/*
243 	 * Some NTB-using hardware have a watchdog to work around NTB hangs; if
244 	 * a register or doorbell isn't written every few seconds, the link is
245 	 * torn down.  Write an otherwise unused register every few seconds to
246 	 * work around this watchdog.
247 	 */
248 	NTBT_WATCHDOG_SPAD = 15
249 };
250 
251 #define QP_TO_MW(nt, qp)	((qp) % nt->mw_count)
252 #define NTB_QP_DEF_NUM_ENTRIES	100
253 #define NTB_LINK_DOWN_TIMEOUT	100
254 
255 static int ntb_transport_probe(device_t dev);
256 static int ntb_transport_attach(device_t dev);
257 static int ntb_transport_detach(device_t dev);
258 static void ntb_transport_init_queue(struct ntb_transport_ctx *nt,
259     unsigned int qp_num);
260 static int ntb_process_tx(struct ntb_transport_qp *qp,
261     struct ntb_queue_entry *entry);
262 static void ntb_transport_rxc_db(void *arg, int pending);
263 static int ntb_process_rxc(struct ntb_transport_qp *qp);
264 static void ntb_memcpy_rx(struct ntb_transport_qp *qp,
265     struct ntb_queue_entry *entry, void *offset);
266 static inline void ntb_rx_copy_callback(struct ntb_transport_qp *qp,
267     void *data);
268 static void ntb_complete_rxc(struct ntb_transport_qp *qp);
269 static void ntb_transport_doorbell_callback(void *data, uint32_t vector);
270 static void ntb_transport_event_callback(void *data);
271 static void ntb_transport_link_work(void *arg);
272 static int ntb_set_mw(struct ntb_transport_ctx *, int num_mw, size_t size);
273 static void ntb_free_mw(struct ntb_transport_ctx *nt, int num_mw);
274 static int ntb_transport_setup_qp_mw(struct ntb_transport_ctx *nt,
275     unsigned int qp_num);
276 static void ntb_qp_link_work(void *arg);
277 static void ntb_transport_link_cleanup(struct ntb_transport_ctx *nt);
278 static void ntb_transport_link_cleanup_work(void *, int);
279 static void ntb_qp_link_down(struct ntb_transport_qp *qp);
280 static void ntb_qp_link_down_reset(struct ntb_transport_qp *qp);
281 static void ntb_qp_link_cleanup(struct ntb_transport_qp *qp);
282 static void ntb_send_link_down(struct ntb_transport_qp *qp);
283 static void ntb_list_add(struct mtx *lock, struct ntb_queue_entry *entry,
284     struct ntb_queue_list *list);
285 static struct ntb_queue_entry *ntb_list_rm(struct mtx *lock,
286     struct ntb_queue_list *list);
287 static struct ntb_queue_entry *ntb_list_mv(struct mtx *lock,
288     struct ntb_queue_list *from, struct ntb_queue_list *to);
289 static void xeon_link_watchdog_hb(void *);
290 
291 static const struct ntb_ctx_ops ntb_transport_ops = {
292 	.link_event = ntb_transport_event_callback,
293 	.db_event = ntb_transport_doorbell_callback,
294 };
295 
296 MALLOC_DEFINE(M_NTB_T, "ntb_transport", "ntb transport driver");
297 
298 static inline void
299 iowrite32(uint32_t val, void *addr)
300 {
301 
302 	bus_space_write_4(X86_BUS_SPACE_MEM, 0/* HACK */, (uintptr_t)addr,
303 	    val);
304 }
305 
306 /* Transport Init and teardown */
307 
308 static void
309 xeon_link_watchdog_hb(void *arg)
310 {
311 	struct ntb_transport_ctx *nt;
312 
313 	nt = arg;
314 	ntb_spad_write(nt->dev, NTBT_WATCHDOG_SPAD, 0);
315 	callout_reset(&nt->link_watchdog, 1 * hz, xeon_link_watchdog_hb, nt);
316 }
317 
318 static int
319 ntb_transport_probe(device_t dev)
320 {
321 
322 	device_set_desc(dev, "NTB Transport");
323 	return (0);
324 }
325 
326 static int
327 ntb_transport_attach(device_t dev)
328 {
329 	struct ntb_transport_ctx *nt = device_get_softc(dev);
330 	struct ntb_transport_child **cpp = &nt->child;
331 	struct ntb_transport_child *nc;
332 	struct ntb_transport_mw *mw;
333 	uint64_t db_bitmap;
334 	int rc, i, db_count, spad_count, qp, qpu, qpo, qpt;
335 	char cfg[128] = "";
336 	char buf[32];
337 	char *n, *np, *c, *name;
338 
339 	nt->dev = dev;
340 	nt->mw_count = ntb_mw_count(dev);
341 	spad_count = ntb_spad_count(dev);
342 	db_bitmap = ntb_db_valid_mask(dev);
343 	db_count = flsll(db_bitmap);
344 	KASSERT(db_bitmap == (1 << db_count) - 1,
345 	    ("Doorbells are not sequential (%jx).\n", db_bitmap));
346 
347 	if (nt->mw_count == 0) {
348 		device_printf(dev, "At least 1 memory window required.\n");
349 		return (ENXIO);
350 	}
351 	if (spad_count < 6) {
352 		device_printf(dev, "At least 6 scratchpads required.\n");
353 		return (ENXIO);
354 	}
355 	if (spad_count < 4 + 2 * nt->mw_count) {
356 		nt->mw_count = (spad_count - 4) / 2;
357 		device_printf(dev, "Scratchpads enough only for %d "
358 		    "memory windows.\n", nt->mw_count);
359 	}
360 	if (db_bitmap == 0) {
361 		device_printf(dev, "At least one doorbell required.\n");
362 		return (ENXIO);
363 	}
364 
365 	nt->mw_vec = malloc(nt->mw_count * sizeof(*nt->mw_vec), M_NTB_T,
366 	    M_WAITOK | M_ZERO);
367 	for (i = 0; i < nt->mw_count; i++) {
368 		mw = &nt->mw_vec[i];
369 
370 		rc = ntb_mw_get_range(dev, i, &mw->phys_addr, &mw->vbase,
371 		    &mw->phys_size, &mw->xlat_align, &mw->xlat_align_size,
372 		    &mw->addr_limit);
373 		if (rc != 0)
374 			goto err;
375 
376 		mw->buff_size = 0;
377 		mw->xlat_size = 0;
378 		mw->virt_addr = NULL;
379 		mw->dma_addr = 0;
380 
381 		rc = ntb_mw_set_wc(dev, i, VM_MEMATTR_WRITE_COMBINING);
382 		if (rc)
383 			ntb_printf(0, "Unable to set mw%d caching\n", i);
384 	}
385 
386 	qpu = 0;
387 	qpo = imin(db_count, nt->mw_count);
388 	qpt = db_count;
389 
390 	snprintf(buf, sizeof(buf), "hint.%s.%d.config", device_get_name(dev),
391 	    device_get_unit(dev));
392 	TUNABLE_STR_FETCH(buf, cfg, sizeof(cfg));
393 	n = cfg;
394 	i = 0;
395 	while ((c = strsep(&n, ",")) != NULL) {
396 		np = c;
397 		name = strsep(&np, ":");
398 		if (name != NULL && name[0] == 0)
399 			name = NULL;
400 		qp = (np && np[0] != 0) ? strtol(np, NULL, 10) : qpo - qpu;
401 		if (qp <= 0)
402 			qp = 1;
403 
404 		if (qp > qpt - qpu) {
405 			device_printf(dev, "Not enough resources for config\n");
406 			break;
407 		}
408 
409 		nc = malloc(sizeof(*nc), M_DEVBUF, M_WAITOK | M_ZERO);
410 		nc->consumer = i;
411 		nc->qpoff = qpu;
412 		nc->qpcnt = qp;
413 		nc->dev = device_add_child(dev, name, -1);
414 		if (nc->dev == NULL) {
415 			device_printf(dev, "Can not add child.\n");
416 			break;
417 		}
418 		device_set_ivars(nc->dev, nc);
419 		*cpp = nc;
420 		cpp = &nc->next;
421 
422 		if (bootverbose) {
423 			device_printf(dev, "%d \"%s\": queues %d",
424 			    i, name, qpu);
425 			if (qp > 1)
426 				printf("-%d", qpu + qp - 1);
427 			printf("\n");
428 		}
429 
430 		qpu += qp;
431 		i++;
432 	}
433 	nt->qp_count = qpu;
434 
435 	nt->qp_vec = malloc(nt->qp_count * sizeof(*nt->qp_vec), M_NTB_T,
436 	    M_WAITOK | M_ZERO);
437 
438 	for (i = 0; i < nt->qp_count; i++)
439 		ntb_transport_init_queue(nt, i);
440 
441 	callout_init(&nt->link_work, 0);
442 	callout_init(&nt->link_watchdog, 0);
443 	TASK_INIT(&nt->link_cleanup, 0, ntb_transport_link_cleanup_work, nt);
444 	nt->link_is_up = false;
445 
446 	rc = ntb_set_ctx(dev, nt, &ntb_transport_ops);
447 	if (rc != 0)
448 		goto err;
449 
450 	ntb_link_enable(dev, NTB_SPEED_AUTO, NTB_WIDTH_AUTO);
451 
452 	if (enable_xeon_watchdog != 0)
453 		callout_reset(&nt->link_watchdog, 0, xeon_link_watchdog_hb, nt);
454 
455 	bus_generic_attach(dev);
456 	return (0);
457 
458 err:
459 	free(nt->qp_vec, M_NTB_T);
460 	free(nt->mw_vec, M_NTB_T);
461 	return (rc);
462 }
463 
464 static int
465 ntb_transport_detach(device_t dev)
466 {
467 	struct ntb_transport_ctx *nt = device_get_softc(dev);
468 	struct ntb_transport_child **cpp = &nt->child;
469 	struct ntb_transport_child *nc;
470 	int error = 0, i;
471 
472 	while ((nc = *cpp) != NULL) {
473 		*cpp = (*cpp)->next;
474 		error = device_delete_child(dev, nc->dev);
475 		if (error)
476 			break;
477 		free(nc, M_DEVBUF);
478 	}
479 	KASSERT(nt->qp_bitmap == 0,
480 	    ("Some queues not freed on detach (%jx)", nt->qp_bitmap));
481 
482 	ntb_transport_link_cleanup(nt);
483 	taskqueue_drain(taskqueue_swi, &nt->link_cleanup);
484 	callout_drain(&nt->link_work);
485 	callout_drain(&nt->link_watchdog);
486 
487 	ntb_link_disable(dev);
488 	ntb_clear_ctx(dev);
489 
490 	for (i = 0; i < nt->mw_count; i++)
491 		ntb_free_mw(nt, i);
492 
493 	free(nt->qp_vec, M_NTB_T);
494 	free(nt->mw_vec, M_NTB_T);
495 	return (0);
496 }
497 
498 static int
499 ntb_transport_print_child(device_t dev, device_t child)
500 {
501 	struct ntb_transport_child *nc = device_get_ivars(child);
502 	int retval;
503 
504 	retval = bus_print_child_header(dev, child);
505 	if (nc->qpcnt > 0) {
506 		printf(" queue %d", nc->qpoff);
507 		if (nc->qpcnt > 1)
508 			printf("-%d", nc->qpoff + nc->qpcnt - 1);
509 	}
510 	retval += printf(" at consumer %d", nc->consumer);
511 	retval += bus_print_child_domain(dev, child);
512 	retval += bus_print_child_footer(dev, child);
513 
514 	return (retval);
515 }
516 
517 static int
518 ntb_transport_child_location_str(device_t dev, device_t child, char *buf,
519     size_t buflen)
520 {
521 	struct ntb_transport_child *nc = device_get_ivars(child);
522 
523 	snprintf(buf, buflen, "consumer=%d", nc->consumer);
524 	return (0);
525 }
526 
527 int
528 ntb_transport_queue_count(device_t dev)
529 {
530 	struct ntb_transport_child *nc = device_get_ivars(dev);
531 
532 	return (nc->qpcnt);
533 }
534 
535 static void
536 ntb_transport_init_queue(struct ntb_transport_ctx *nt, unsigned int qp_num)
537 {
538 	struct ntb_transport_mw *mw;
539 	struct ntb_transport_qp *qp;
540 	vm_paddr_t mw_base;
541 	uint64_t mw_size, qp_offset;
542 	size_t tx_size;
543 	unsigned num_qps_mw, mw_num, mw_count;
544 
545 	mw_count = nt->mw_count;
546 	mw_num = QP_TO_MW(nt, qp_num);
547 	mw = &nt->mw_vec[mw_num];
548 
549 	qp = &nt->qp_vec[qp_num];
550 	qp->qp_num = qp_num;
551 	qp->transport = nt;
552 	qp->dev = nt->dev;
553 	qp->client_ready = false;
554 	qp->event_handler = NULL;
555 	ntb_qp_link_down_reset(qp);
556 
557 	if (mw_num < nt->qp_count % mw_count)
558 		num_qps_mw = nt->qp_count / mw_count + 1;
559 	else
560 		num_qps_mw = nt->qp_count / mw_count;
561 
562 	mw_base = mw->phys_addr;
563 	mw_size = mw->phys_size;
564 
565 	tx_size = mw_size / num_qps_mw;
566 	qp_offset = tx_size * (qp_num / mw_count);
567 
568 	qp->tx_mw = mw->vbase + qp_offset;
569 	KASSERT(qp->tx_mw != NULL, ("uh oh?"));
570 
571 	/* XXX Assumes that a vm_paddr_t is equivalent to bus_addr_t */
572 	qp->tx_mw_phys = mw_base + qp_offset;
573 	KASSERT(qp->tx_mw_phys != 0, ("uh oh?"));
574 
575 	tx_size -= sizeof(struct ntb_rx_info);
576 	qp->rx_info = (void *)(qp->tx_mw + tx_size);
577 
578 	/* Due to house-keeping, there must be at least 2 buffs */
579 	qp->tx_max_frame = qmin(transport_mtu, tx_size / 2);
580 	qp->tx_max_entry = tx_size / qp->tx_max_frame;
581 
582 	callout_init(&qp->link_work, 0);
583 	callout_init(&qp->rx_full, 1);
584 
585 	mtx_init(&qp->ntb_rx_q_lock, "ntb rx q", NULL, MTX_SPIN);
586 	mtx_init(&qp->ntb_tx_free_q_lock, "ntb tx free q", NULL, MTX_SPIN);
587 	mtx_init(&qp->tx_lock, "ntb transport tx", NULL, MTX_DEF);
588 	TASK_INIT(&qp->rxc_db_work, 0, ntb_transport_rxc_db, qp);
589 	qp->rxc_tq = taskqueue_create("ntbt_rx", M_WAITOK,
590 	    taskqueue_thread_enqueue, &qp->rxc_tq);
591 	taskqueue_start_threads(&qp->rxc_tq, 1, PI_NET, "%s rx%d",
592 	    device_get_nameunit(nt->dev), qp_num);
593 
594 	STAILQ_INIT(&qp->rx_post_q);
595 	STAILQ_INIT(&qp->rx_pend_q);
596 	STAILQ_INIT(&qp->tx_free_q);
597 }
598 
599 void
600 ntb_transport_free_queue(struct ntb_transport_qp *qp)
601 {
602 	struct ntb_transport_ctx *nt = qp->transport;
603 	struct ntb_queue_entry *entry;
604 
605 	callout_drain(&qp->link_work);
606 
607 	ntb_db_set_mask(qp->dev, 1ull << qp->qp_num);
608 	taskqueue_drain_all(qp->rxc_tq);
609 	taskqueue_free(qp->rxc_tq);
610 
611 	qp->cb_data = NULL;
612 	qp->rx_handler = NULL;
613 	qp->tx_handler = NULL;
614 	qp->event_handler = NULL;
615 
616 	while ((entry = ntb_list_rm(&qp->ntb_rx_q_lock, &qp->rx_pend_q)))
617 		free(entry, M_NTB_T);
618 
619 	while ((entry = ntb_list_rm(&qp->ntb_rx_q_lock, &qp->rx_post_q)))
620 		free(entry, M_NTB_T);
621 
622 	while ((entry = ntb_list_rm(&qp->ntb_tx_free_q_lock, &qp->tx_free_q)))
623 		free(entry, M_NTB_T);
624 
625 	nt->qp_bitmap &= ~(1 << qp->qp_num);
626 }
627 
628 /**
629  * ntb_transport_create_queue - Create a new NTB transport layer queue
630  * @rx_handler: receive callback function
631  * @tx_handler: transmit callback function
632  * @event_handler: event callback function
633  *
634  * Create a new NTB transport layer queue and provide the queue with a callback
635  * routine for both transmit and receive.  The receive callback routine will be
636  * used to pass up data when the transport has received it on the queue.   The
637  * transmit callback routine will be called when the transport has completed the
638  * transmission of the data on the queue and the data is ready to be freed.
639  *
640  * RETURNS: pointer to newly created ntb_queue, NULL on error.
641  */
642 struct ntb_transport_qp *
643 ntb_transport_create_queue(device_t dev, int q,
644     const struct ntb_queue_handlers *handlers, void *data)
645 {
646 	struct ntb_transport_child *nc = device_get_ivars(dev);
647 	struct ntb_transport_ctx *nt = device_get_softc(device_get_parent(dev));
648 	struct ntb_queue_entry *entry;
649 	struct ntb_transport_qp *qp;
650 	int i;
651 
652 	if (q < 0 || q >= nc->qpcnt)
653 		return (NULL);
654 
655 	qp = &nt->qp_vec[nc->qpoff + q];
656 	nt->qp_bitmap |= (1 << qp->qp_num);
657 	qp->cb_data = data;
658 	qp->rx_handler = handlers->rx_handler;
659 	qp->tx_handler = handlers->tx_handler;
660 	qp->event_handler = handlers->event_handler;
661 
662 	for (i = 0; i < NTB_QP_DEF_NUM_ENTRIES; i++) {
663 		entry = malloc(sizeof(*entry), M_NTB_T, M_WAITOK | M_ZERO);
664 		entry->cb_data = data;
665 		entry->buf = NULL;
666 		entry->len = transport_mtu;
667 		entry->qp = qp;
668 		ntb_list_add(&qp->ntb_rx_q_lock, entry, &qp->rx_pend_q);
669 	}
670 
671 	for (i = 0; i < NTB_QP_DEF_NUM_ENTRIES; i++) {
672 		entry = malloc(sizeof(*entry), M_NTB_T, M_WAITOK | M_ZERO);
673 		entry->qp = qp;
674 		ntb_list_add(&qp->ntb_tx_free_q_lock, entry, &qp->tx_free_q);
675 	}
676 
677 	ntb_db_clear(dev, 1ull << qp->qp_num);
678 	return (qp);
679 }
680 
681 /**
682  * ntb_transport_link_up - Notify NTB transport of client readiness to use queue
683  * @qp: NTB transport layer queue to be enabled
684  *
685  * Notify NTB transport layer of client readiness to use queue
686  */
687 void
688 ntb_transport_link_up(struct ntb_transport_qp *qp)
689 {
690 	struct ntb_transport_ctx *nt = qp->transport;
691 
692 	qp->client_ready = true;
693 
694 	ntb_printf(2, "qp %d client ready\n", qp->qp_num);
695 
696 	if (nt->link_is_up)
697 		callout_reset(&qp->link_work, 0, ntb_qp_link_work, qp);
698 }
699 
700 
701 
702 /* Transport Tx */
703 
704 /**
705  * ntb_transport_tx_enqueue - Enqueue a new NTB queue entry
706  * @qp: NTB transport layer queue the entry is to be enqueued on
707  * @cb: per buffer pointer for callback function to use
708  * @data: pointer to data buffer that will be sent
709  * @len: length of the data buffer
710  *
711  * Enqueue a new transmit buffer onto the transport queue from which a NTB
712  * payload will be transmitted.  This assumes that a lock is being held to
713  * serialize access to the qp.
714  *
715  * RETURNS: An appropriate ERRNO error value on error, or zero for success.
716  */
717 int
718 ntb_transport_tx_enqueue(struct ntb_transport_qp *qp, void *cb, void *data,
719     unsigned int len)
720 {
721 	struct ntb_queue_entry *entry;
722 	int rc;
723 
724 	if (!qp->link_is_up || len == 0) {
725 		CTR0(KTR_NTB, "TX: link not up");
726 		return (EINVAL);
727 	}
728 
729 	entry = ntb_list_rm(&qp->ntb_tx_free_q_lock, &qp->tx_free_q);
730 	if (entry == NULL) {
731 		CTR0(KTR_NTB, "TX: could not get entry from tx_free_q");
732 		qp->tx_err_no_buf++;
733 		return (EBUSY);
734 	}
735 	CTR1(KTR_NTB, "TX: got entry %p from tx_free_q", entry);
736 
737 	entry->cb_data = cb;
738 	entry->buf = data;
739 	entry->len = len;
740 	entry->flags = 0;
741 
742 	mtx_lock(&qp->tx_lock);
743 	rc = ntb_process_tx(qp, entry);
744 	mtx_unlock(&qp->tx_lock);
745 	if (rc != 0) {
746 		ntb_list_add(&qp->ntb_tx_free_q_lock, entry, &qp->tx_free_q);
747 		CTR1(KTR_NTB,
748 		    "TX: process_tx failed. Returning entry %p to tx_free_q",
749 		    entry);
750 	}
751 	return (rc);
752 }
753 
754 static void
755 ntb_tx_copy_callback(void *data)
756 {
757 	struct ntb_queue_entry *entry = data;
758 	struct ntb_transport_qp *qp = entry->qp;
759 	struct ntb_payload_header *hdr = entry->x_hdr;
760 
761 	iowrite32(entry->flags | NTBT_DESC_DONE_FLAG, &hdr->flags);
762 	CTR1(KTR_NTB, "TX: hdr %p set DESC_DONE", hdr);
763 
764 	ntb_peer_db_set(qp->dev, 1ull << qp->qp_num);
765 
766 	/*
767 	 * The entry length can only be zero if the packet is intended to be a
768 	 * "link down" or similar.  Since no payload is being sent in these
769 	 * cases, there is nothing to add to the completion queue.
770 	 */
771 	if (entry->len > 0) {
772 		qp->tx_bytes += entry->len;
773 
774 		if (qp->tx_handler)
775 			qp->tx_handler(qp, qp->cb_data, entry->buf,
776 			    entry->len);
777 		else
778 			m_freem(entry->buf);
779 		entry->buf = NULL;
780 	}
781 
782 	CTR3(KTR_NTB,
783 	    "TX: entry %p sent. hdr->ver = %u, hdr->flags = 0x%x, Returning "
784 	    "to tx_free_q", entry, hdr->ver, hdr->flags);
785 	ntb_list_add(&qp->ntb_tx_free_q_lock, entry, &qp->tx_free_q);
786 }
787 
788 static void
789 ntb_memcpy_tx(struct ntb_queue_entry *entry, void *offset)
790 {
791 
792 	CTR2(KTR_NTB, "TX: copying %d bytes to offset %p", entry->len, offset);
793 	if (entry->buf != NULL) {
794 		m_copydata((struct mbuf *)entry->buf, 0, entry->len, offset);
795 
796 		/*
797 		 * Ensure that the data is fully copied before setting the
798 		 * flags
799 		 */
800 		wmb();
801 	}
802 
803 	ntb_tx_copy_callback(entry);
804 }
805 
806 static void
807 ntb_async_tx(struct ntb_transport_qp *qp, struct ntb_queue_entry *entry)
808 {
809 	struct ntb_payload_header *hdr;
810 	void *offset;
811 
812 	offset = qp->tx_mw + qp->tx_max_frame * qp->tx_index;
813 	hdr = (struct ntb_payload_header *)((char *)offset + qp->tx_max_frame -
814 	    sizeof(struct ntb_payload_header));
815 	entry->x_hdr = hdr;
816 
817 	iowrite32(entry->len, &hdr->len);
818 	iowrite32(qp->tx_pkts, &hdr->ver);
819 
820 	ntb_memcpy_tx(entry, offset);
821 }
822 
823 static int
824 ntb_process_tx(struct ntb_transport_qp *qp, struct ntb_queue_entry *entry)
825 {
826 
827 	CTR3(KTR_NTB,
828 	    "TX: process_tx: tx_pkts=%lu, tx_index=%u, remote entry=%u",
829 	    qp->tx_pkts, qp->tx_index, qp->remote_rx_info->entry);
830 	if (qp->tx_index == qp->remote_rx_info->entry) {
831 		CTR0(KTR_NTB, "TX: ring full");
832 		qp->tx_ring_full++;
833 		return (EAGAIN);
834 	}
835 
836 	if (entry->len > qp->tx_max_frame - sizeof(struct ntb_payload_header)) {
837 		if (qp->tx_handler != NULL)
838 			qp->tx_handler(qp, qp->cb_data, entry->buf,
839 			    EIO);
840 		else
841 			m_freem(entry->buf);
842 
843 		entry->buf = NULL;
844 		ntb_list_add(&qp->ntb_tx_free_q_lock, entry, &qp->tx_free_q);
845 		CTR1(KTR_NTB,
846 		    "TX: frame too big. returning entry %p to tx_free_q",
847 		    entry);
848 		return (0);
849 	}
850 	CTR2(KTR_NTB, "TX: copying entry %p to index %u", entry, qp->tx_index);
851 	ntb_async_tx(qp, entry);
852 
853 	qp->tx_index++;
854 	qp->tx_index %= qp->tx_max_entry;
855 
856 	qp->tx_pkts++;
857 
858 	return (0);
859 }
860 
861 /* Transport Rx */
862 static void
863 ntb_transport_rxc_db(void *arg, int pending __unused)
864 {
865 	struct ntb_transport_qp *qp = arg;
866 	uint64_t qp_mask = 1ull << qp->qp_num;
867 	int rc;
868 
869 	CTR0(KTR_NTB, "RX: transport_rx");
870 again:
871 	while ((rc = ntb_process_rxc(qp)) == 0)
872 		;
873 	CTR1(KTR_NTB, "RX: process_rxc returned %d", rc);
874 
875 	if ((ntb_db_read(qp->dev) & qp_mask) != 0) {
876 		/* If db is set, clear it and check queue once more. */
877 		ntb_db_clear(qp->dev, qp_mask);
878 		goto again;
879 	}
880 	if (qp->link_is_up)
881 		ntb_db_clear_mask(qp->dev, qp_mask);
882 }
883 
884 static int
885 ntb_process_rxc(struct ntb_transport_qp *qp)
886 {
887 	struct ntb_payload_header *hdr;
888 	struct ntb_queue_entry *entry;
889 	caddr_t offset;
890 
891 	offset = qp->rx_buff + qp->rx_max_frame * qp->rx_index;
892 	hdr = (void *)(offset + qp->rx_max_frame -
893 	    sizeof(struct ntb_payload_header));
894 
895 	CTR1(KTR_NTB, "RX: process_rxc rx_index = %u", qp->rx_index);
896 	if ((hdr->flags & NTBT_DESC_DONE_FLAG) == 0) {
897 		CTR0(KTR_NTB, "RX: hdr not done");
898 		qp->rx_ring_empty++;
899 		return (EAGAIN);
900 	}
901 
902 	if ((hdr->flags & NTBT_LINK_DOWN_FLAG) != 0) {
903 		CTR0(KTR_NTB, "RX: link down");
904 		ntb_qp_link_down(qp);
905 		hdr->flags = 0;
906 		return (EAGAIN);
907 	}
908 
909 	if (hdr->ver != (uint32_t)qp->rx_pkts) {
910 		CTR2(KTR_NTB,"RX: ver != rx_pkts (%x != %lx). "
911 		    "Returning entry to rx_pend_q", hdr->ver, qp->rx_pkts);
912 		qp->rx_err_ver++;
913 		return (EIO);
914 	}
915 
916 	entry = ntb_list_mv(&qp->ntb_rx_q_lock, &qp->rx_pend_q, &qp->rx_post_q);
917 	if (entry == NULL) {
918 		qp->rx_err_no_buf++;
919 		CTR0(KTR_NTB, "RX: No entries in rx_pend_q");
920 		return (EAGAIN);
921 	}
922 	callout_stop(&qp->rx_full);
923 	CTR1(KTR_NTB, "RX: rx entry %p from rx_pend_q", entry);
924 
925 	entry->x_hdr = hdr;
926 	entry->index = qp->rx_index;
927 
928 	if (hdr->len > entry->len) {
929 		CTR2(KTR_NTB, "RX: len too long. Wanted %ju got %ju",
930 		    (uintmax_t)hdr->len, (uintmax_t)entry->len);
931 		qp->rx_err_oflow++;
932 
933 		entry->len = -EIO;
934 		entry->flags |= NTBT_DESC_DONE_FLAG;
935 
936 		ntb_complete_rxc(qp);
937 	} else {
938 		qp->rx_bytes += hdr->len;
939 		qp->rx_pkts++;
940 
941 		CTR1(KTR_NTB, "RX: received %ld rx_pkts", qp->rx_pkts);
942 
943 		entry->len = hdr->len;
944 
945 		ntb_memcpy_rx(qp, entry, offset);
946 	}
947 
948 	qp->rx_index++;
949 	qp->rx_index %= qp->rx_max_entry;
950 	return (0);
951 }
952 
953 static void
954 ntb_memcpy_rx(struct ntb_transport_qp *qp, struct ntb_queue_entry *entry,
955     void *offset)
956 {
957 	struct ifnet *ifp = entry->cb_data;
958 	unsigned int len = entry->len;
959 
960 	CTR2(KTR_NTB, "RX: copying %d bytes from offset %p", len, offset);
961 
962 	entry->buf = (void *)m_devget(offset, len, 0, ifp, NULL);
963 	if (entry->buf == NULL)
964 		entry->len = -ENOMEM;
965 
966 	/* Ensure that the data is globally visible before clearing the flag */
967 	wmb();
968 
969 	CTR2(KTR_NTB, "RX: copied entry %p to mbuf %p.", entry, entry->buf);
970 	ntb_rx_copy_callback(qp, entry);
971 }
972 
973 static inline void
974 ntb_rx_copy_callback(struct ntb_transport_qp *qp, void *data)
975 {
976 	struct ntb_queue_entry *entry;
977 
978 	entry = data;
979 	entry->flags |= NTBT_DESC_DONE_FLAG;
980 	ntb_complete_rxc(qp);
981 }
982 
983 static void
984 ntb_complete_rxc(struct ntb_transport_qp *qp)
985 {
986 	struct ntb_queue_entry *entry;
987 	struct mbuf *m;
988 	unsigned len;
989 
990 	CTR0(KTR_NTB, "RX: rx_completion_task");
991 
992 	mtx_lock_spin(&qp->ntb_rx_q_lock);
993 
994 	while (!STAILQ_EMPTY(&qp->rx_post_q)) {
995 		entry = STAILQ_FIRST(&qp->rx_post_q);
996 		if ((entry->flags & NTBT_DESC_DONE_FLAG) == 0)
997 			break;
998 
999 		entry->x_hdr->flags = 0;
1000 		iowrite32(entry->index, &qp->rx_info->entry);
1001 
1002 		STAILQ_REMOVE_HEAD(&qp->rx_post_q, entry);
1003 
1004 		len = entry->len;
1005 		m = entry->buf;
1006 
1007 		/*
1008 		 * Re-initialize queue_entry for reuse; rx_handler takes
1009 		 * ownership of the mbuf.
1010 		 */
1011 		entry->buf = NULL;
1012 		entry->len = transport_mtu;
1013 		entry->cb_data = qp->cb_data;
1014 
1015 		STAILQ_INSERT_TAIL(&qp->rx_pend_q, entry, entry);
1016 
1017 		mtx_unlock_spin(&qp->ntb_rx_q_lock);
1018 
1019 		CTR2(KTR_NTB, "RX: completing entry %p, mbuf %p", entry, m);
1020 		if (qp->rx_handler != NULL && qp->client_ready)
1021 			qp->rx_handler(qp, qp->cb_data, m, len);
1022 		else
1023 			m_freem(m);
1024 
1025 		mtx_lock_spin(&qp->ntb_rx_q_lock);
1026 	}
1027 
1028 	mtx_unlock_spin(&qp->ntb_rx_q_lock);
1029 }
1030 
1031 static void
1032 ntb_transport_doorbell_callback(void *data, uint32_t vector)
1033 {
1034 	struct ntb_transport_ctx *nt = data;
1035 	struct ntb_transport_qp *qp;
1036 	uint64_t vec_mask;
1037 	unsigned qp_num;
1038 
1039 	vec_mask = ntb_db_vector_mask(nt->dev, vector);
1040 	vec_mask &= nt->qp_bitmap;
1041 	if ((vec_mask & (vec_mask - 1)) != 0)
1042 		vec_mask &= ntb_db_read(nt->dev);
1043 	if (vec_mask != 0) {
1044 		ntb_db_set_mask(nt->dev, vec_mask);
1045 		ntb_db_clear(nt->dev, vec_mask);
1046 	}
1047 	while (vec_mask != 0) {
1048 		qp_num = ffsll(vec_mask) - 1;
1049 
1050 		qp = &nt->qp_vec[qp_num];
1051 		if (qp->link_is_up)
1052 			taskqueue_enqueue(qp->rxc_tq, &qp->rxc_db_work);
1053 
1054 		vec_mask &= ~(1ull << qp_num);
1055 	}
1056 }
1057 
1058 /* Link Event handler */
1059 static void
1060 ntb_transport_event_callback(void *data)
1061 {
1062 	struct ntb_transport_ctx *nt = data;
1063 
1064 	if (ntb_link_is_up(nt->dev, &nt->link_speed, &nt->link_width)) {
1065 		ntb_printf(1, "HW link up\n");
1066 		callout_reset(&nt->link_work, 0, ntb_transport_link_work, nt);
1067 	} else {
1068 		ntb_printf(1, "HW link down\n");
1069 		taskqueue_enqueue(taskqueue_swi, &nt->link_cleanup);
1070 	}
1071 }
1072 
1073 /* Link bring up */
1074 static void
1075 ntb_transport_link_work(void *arg)
1076 {
1077 	struct ntb_transport_ctx *nt = arg;
1078 	device_t dev = nt->dev;
1079 	struct ntb_transport_qp *qp;
1080 	uint64_t val64, size;
1081 	uint32_t val;
1082 	unsigned i;
1083 	int rc;
1084 
1085 	/* send the local info, in the opposite order of the way we read it */
1086 	for (i = 0; i < nt->mw_count; i++) {
1087 		size = nt->mw_vec[i].phys_size;
1088 
1089 		if (max_mw_size != 0 && size > max_mw_size)
1090 			size = max_mw_size;
1091 
1092 		ntb_peer_spad_write(dev, NTBT_MW0_SZ_HIGH + (i * 2),
1093 		    size >> 32);
1094 		ntb_peer_spad_write(dev, NTBT_MW0_SZ_LOW + (i * 2), size);
1095 	}
1096 	ntb_peer_spad_write(dev, NTBT_NUM_MWS, nt->mw_count);
1097 	ntb_peer_spad_write(dev, NTBT_NUM_QPS, nt->qp_count);
1098 	ntb_peer_spad_write(dev, NTBT_QP_LINKS, 0);
1099 	ntb_peer_spad_write(dev, NTBT_VERSION, NTB_TRANSPORT_VERSION);
1100 
1101 	/* Query the remote side for its info */
1102 	val = 0;
1103 	ntb_spad_read(dev, NTBT_VERSION, &val);
1104 	if (val != NTB_TRANSPORT_VERSION)
1105 		goto out;
1106 
1107 	ntb_spad_read(dev, NTBT_NUM_QPS, &val);
1108 	if (val != nt->qp_count)
1109 		goto out;
1110 
1111 	ntb_spad_read(dev, NTBT_NUM_MWS, &val);
1112 	if (val != nt->mw_count)
1113 		goto out;
1114 
1115 	for (i = 0; i < nt->mw_count; i++) {
1116 		ntb_spad_read(dev, NTBT_MW0_SZ_HIGH + (i * 2), &val);
1117 		val64 = (uint64_t)val << 32;
1118 
1119 		ntb_spad_read(dev, NTBT_MW0_SZ_LOW + (i * 2), &val);
1120 		val64 |= val;
1121 
1122 		rc = ntb_set_mw(nt, i, val64);
1123 		if (rc != 0)
1124 			goto free_mws;
1125 	}
1126 
1127 	nt->link_is_up = true;
1128 	ntb_printf(1, "transport link up\n");
1129 
1130 	for (i = 0; i < nt->qp_count; i++) {
1131 		qp = &nt->qp_vec[i];
1132 
1133 		ntb_transport_setup_qp_mw(nt, i);
1134 
1135 		if (qp->client_ready)
1136 			callout_reset(&qp->link_work, 0, ntb_qp_link_work, qp);
1137 	}
1138 
1139 	return;
1140 
1141 free_mws:
1142 	for (i = 0; i < nt->mw_count; i++)
1143 		ntb_free_mw(nt, i);
1144 out:
1145 	if (ntb_link_is_up(dev, &nt->link_speed, &nt->link_width))
1146 		callout_reset(&nt->link_work,
1147 		    NTB_LINK_DOWN_TIMEOUT * hz / 1000, ntb_transport_link_work, nt);
1148 }
1149 
1150 static int
1151 ntb_set_mw(struct ntb_transport_ctx *nt, int num_mw, size_t size)
1152 {
1153 	struct ntb_transport_mw *mw = &nt->mw_vec[num_mw];
1154 	size_t xlat_size, buff_size;
1155 	int rc;
1156 
1157 	if (size == 0)
1158 		return (EINVAL);
1159 
1160 	xlat_size = roundup(size, mw->xlat_align_size);
1161 	buff_size = xlat_size;
1162 
1163 	/* No need to re-setup */
1164 	if (mw->xlat_size == xlat_size)
1165 		return (0);
1166 
1167 	if (mw->buff_size != 0)
1168 		ntb_free_mw(nt, num_mw);
1169 
1170 	/* Alloc memory for receiving data.  Must be aligned */
1171 	mw->xlat_size = xlat_size;
1172 	mw->buff_size = buff_size;
1173 
1174 	mw->virt_addr = contigmalloc(mw->buff_size, M_NTB_T, M_ZERO, 0,
1175 	    mw->addr_limit, mw->xlat_align, 0);
1176 	if (mw->virt_addr == NULL) {
1177 		ntb_printf(0, "Unable to allocate MW buffer of size %zu/%zu\n",
1178 		    mw->buff_size, mw->xlat_size);
1179 		mw->xlat_size = 0;
1180 		mw->buff_size = 0;
1181 		return (ENOMEM);
1182 	}
1183 	/* TODO: replace with bus_space_* functions */
1184 	mw->dma_addr = vtophys(mw->virt_addr);
1185 
1186 	/*
1187 	 * Ensure that the allocation from contigmalloc is aligned as
1188 	 * requested.  XXX: This may not be needed -- brought in for parity
1189 	 * with the Linux driver.
1190 	 */
1191 	if (mw->dma_addr % mw->xlat_align != 0) {
1192 		ntb_printf(0,
1193 		    "DMA memory 0x%jx not aligned to BAR size 0x%zx\n",
1194 		    (uintmax_t)mw->dma_addr, size);
1195 		ntb_free_mw(nt, num_mw);
1196 		return (ENOMEM);
1197 	}
1198 
1199 	/* Notify HW the memory location of the receive buffer */
1200 	rc = ntb_mw_set_trans(nt->dev, num_mw, mw->dma_addr, mw->xlat_size);
1201 	if (rc) {
1202 		ntb_printf(0, "Unable to set mw%d translation\n", num_mw);
1203 		ntb_free_mw(nt, num_mw);
1204 		return (rc);
1205 	}
1206 
1207 	return (0);
1208 }
1209 
1210 static void
1211 ntb_free_mw(struct ntb_transport_ctx *nt, int num_mw)
1212 {
1213 	struct ntb_transport_mw *mw = &nt->mw_vec[num_mw];
1214 
1215 	if (mw->virt_addr == NULL)
1216 		return;
1217 
1218 	ntb_mw_clear_trans(nt->dev, num_mw);
1219 	contigfree(mw->virt_addr, mw->xlat_size, M_NTB_T);
1220 	mw->xlat_size = 0;
1221 	mw->buff_size = 0;
1222 	mw->virt_addr = NULL;
1223 }
1224 
1225 static int
1226 ntb_transport_setup_qp_mw(struct ntb_transport_ctx *nt, unsigned int qp_num)
1227 {
1228 	struct ntb_transport_qp *qp = &nt->qp_vec[qp_num];
1229 	struct ntb_transport_mw *mw;
1230 	void *offset;
1231 	ntb_q_idx_t i;
1232 	size_t rx_size;
1233 	unsigned num_qps_mw, mw_num, mw_count;
1234 
1235 	mw_count = nt->mw_count;
1236 	mw_num = QP_TO_MW(nt, qp_num);
1237 	mw = &nt->mw_vec[mw_num];
1238 
1239 	if (mw->virt_addr == NULL)
1240 		return (ENOMEM);
1241 
1242 	if (mw_num < nt->qp_count % mw_count)
1243 		num_qps_mw = nt->qp_count / mw_count + 1;
1244 	else
1245 		num_qps_mw = nt->qp_count / mw_count;
1246 
1247 	rx_size = mw->xlat_size / num_qps_mw;
1248 	qp->rx_buff = mw->virt_addr + rx_size * (qp_num / mw_count);
1249 	rx_size -= sizeof(struct ntb_rx_info);
1250 
1251 	qp->remote_rx_info = (void*)(qp->rx_buff + rx_size);
1252 
1253 	/* Due to house-keeping, there must be at least 2 buffs */
1254 	qp->rx_max_frame = qmin(transport_mtu, rx_size / 2);
1255 	qp->rx_max_entry = rx_size / qp->rx_max_frame;
1256 	qp->rx_index = 0;
1257 
1258 	qp->remote_rx_info->entry = qp->rx_max_entry - 1;
1259 
1260 	/* Set up the hdr offsets with 0s */
1261 	for (i = 0; i < qp->rx_max_entry; i++) {
1262 		offset = (void *)(qp->rx_buff + qp->rx_max_frame * (i + 1) -
1263 		    sizeof(struct ntb_payload_header));
1264 		memset(offset, 0, sizeof(struct ntb_payload_header));
1265 	}
1266 
1267 	qp->rx_pkts = 0;
1268 	qp->tx_pkts = 0;
1269 	qp->tx_index = 0;
1270 
1271 	return (0);
1272 }
1273 
1274 static void
1275 ntb_qp_link_work(void *arg)
1276 {
1277 	struct ntb_transport_qp *qp = arg;
1278 	device_t dev = qp->dev;
1279 	struct ntb_transport_ctx *nt = qp->transport;
1280 	int i;
1281 	uint32_t val;
1282 
1283 	/* Report queues that are up on our side */
1284 	for (i = 0, val = 0; i < nt->qp_count; i++) {
1285 		if (nt->qp_vec[i].client_ready)
1286 			val |= (1 << i);
1287 	}
1288 	ntb_peer_spad_write(dev, NTBT_QP_LINKS, val);
1289 
1290 	/* See if the remote side is up */
1291 	ntb_spad_read(dev, NTBT_QP_LINKS, &val);
1292 	if ((val & (1ull << qp->qp_num)) != 0) {
1293 		ntb_printf(2, "qp %d link up\n", qp->qp_num);
1294 		qp->link_is_up = true;
1295 
1296 		if (qp->event_handler != NULL)
1297 			qp->event_handler(qp->cb_data, NTB_LINK_UP);
1298 
1299 		ntb_db_clear_mask(dev, 1ull << qp->qp_num);
1300 	} else if (nt->link_is_up)
1301 		callout_reset(&qp->link_work,
1302 		    NTB_LINK_DOWN_TIMEOUT * hz / 1000, ntb_qp_link_work, qp);
1303 }
1304 
1305 /* Link down event*/
1306 static void
1307 ntb_transport_link_cleanup(struct ntb_transport_ctx *nt)
1308 {
1309 	struct ntb_transport_qp *qp;
1310 	int i;
1311 
1312 	callout_drain(&nt->link_work);
1313 	nt->link_is_up = 0;
1314 
1315 	/* Pass along the info to any clients */
1316 	for (i = 0; i < nt->qp_count; i++) {
1317 		if ((nt->qp_bitmap & (1 << i)) != 0) {
1318 			qp = &nt->qp_vec[i];
1319 			ntb_qp_link_cleanup(qp);
1320 			callout_drain(&qp->link_work);
1321 		}
1322 	}
1323 
1324 	/*
1325 	 * The scratchpad registers keep the values if the remote side
1326 	 * goes down, blast them now to give them a sane value the next
1327 	 * time they are accessed
1328 	 */
1329 	ntb_spad_clear(nt->dev);
1330 }
1331 
1332 static void
1333 ntb_transport_link_cleanup_work(void *arg, int pending __unused)
1334 {
1335 
1336 	ntb_transport_link_cleanup(arg);
1337 }
1338 
1339 static void
1340 ntb_qp_link_down(struct ntb_transport_qp *qp)
1341 {
1342 
1343 	ntb_qp_link_cleanup(qp);
1344 }
1345 
1346 static void
1347 ntb_qp_link_down_reset(struct ntb_transport_qp *qp)
1348 {
1349 
1350 	qp->link_is_up = false;
1351 	ntb_db_set_mask(qp->dev, 1ull << qp->qp_num);
1352 
1353 	qp->tx_index = qp->rx_index = 0;
1354 	qp->tx_bytes = qp->rx_bytes = 0;
1355 	qp->tx_pkts = qp->rx_pkts = 0;
1356 
1357 	qp->rx_ring_empty = 0;
1358 	qp->tx_ring_full = 0;
1359 
1360 	qp->rx_err_no_buf = qp->tx_err_no_buf = 0;
1361 	qp->rx_err_oflow = qp->rx_err_ver = 0;
1362 }
1363 
1364 static void
1365 ntb_qp_link_cleanup(struct ntb_transport_qp *qp)
1366 {
1367 
1368 	callout_drain(&qp->link_work);
1369 	ntb_qp_link_down_reset(qp);
1370 
1371 	if (qp->event_handler != NULL)
1372 		qp->event_handler(qp->cb_data, NTB_LINK_DOWN);
1373 }
1374 
1375 /* Link commanded down */
1376 /**
1377  * ntb_transport_link_down - Notify NTB transport to no longer enqueue data
1378  * @qp: NTB transport layer queue to be disabled
1379  *
1380  * Notify NTB transport layer of client's desire to no longer receive data on
1381  * transport queue specified.  It is the client's responsibility to ensure all
1382  * entries on queue are purged or otherwise handled appropriately.
1383  */
1384 void
1385 ntb_transport_link_down(struct ntb_transport_qp *qp)
1386 {
1387 	struct ntb_transport_ctx *nt = qp->transport;
1388 	int i;
1389 	uint32_t val;
1390 
1391 	qp->client_ready = false;
1392 	for (i = 0, val = 0; i < nt->qp_count; i++) {
1393 		if (nt->qp_vec[i].client_ready)
1394 			val |= (1 << i);
1395 	}
1396 	ntb_peer_spad_write(qp->dev, NTBT_QP_LINKS, val);
1397 
1398 	if (qp->link_is_up)
1399 		ntb_send_link_down(qp);
1400 	else
1401 		callout_drain(&qp->link_work);
1402 }
1403 
1404 /**
1405  * ntb_transport_link_query - Query transport link state
1406  * @qp: NTB transport layer queue to be queried
1407  *
1408  * Query connectivity to the remote system of the NTB transport queue
1409  *
1410  * RETURNS: true for link up or false for link down
1411  */
1412 bool
1413 ntb_transport_link_query(struct ntb_transport_qp *qp)
1414 {
1415 
1416 	return (qp->link_is_up);
1417 }
1418 
1419 /**
1420  * ntb_transport_link_speed - Query transport link speed
1421  * @qp: NTB transport layer queue to be queried
1422  *
1423  * Query connection speed to the remote system of the NTB transport queue
1424  *
1425  * RETURNS: link speed in bits per second
1426  */
1427 uint64_t
1428 ntb_transport_link_speed(struct ntb_transport_qp *qp)
1429 {
1430 	struct ntb_transport_ctx *nt = qp->transport;
1431 	uint64_t rate;
1432 
1433 	if (!nt->link_is_up)
1434 		return (0);
1435 	switch (nt->link_speed) {
1436 	case NTB_SPEED_GEN1:
1437 		rate = 2500000000 * 8 / 10;
1438 		break;
1439 	case NTB_SPEED_GEN2:
1440 		rate = 5000000000 * 8 / 10;
1441 		break;
1442 	case NTB_SPEED_GEN3:
1443 		rate = 8000000000 * 128 / 130;
1444 		break;
1445 	case NTB_SPEED_GEN4:
1446 		rate = 16000000000 * 128 / 130;
1447 		break;
1448 	default:
1449 		return (0);
1450 	}
1451 	if (nt->link_width <= 0)
1452 		return (0);
1453 	return (rate * nt->link_width);
1454 }
1455 
1456 static void
1457 ntb_send_link_down(struct ntb_transport_qp *qp)
1458 {
1459 	struct ntb_queue_entry *entry;
1460 	int i, rc;
1461 
1462 	if (!qp->link_is_up)
1463 		return;
1464 
1465 	for (i = 0; i < NTB_LINK_DOWN_TIMEOUT; i++) {
1466 		entry = ntb_list_rm(&qp->ntb_tx_free_q_lock, &qp->tx_free_q);
1467 		if (entry != NULL)
1468 			break;
1469 		pause("NTB Wait for link down", hz / 10);
1470 	}
1471 
1472 	if (entry == NULL)
1473 		return;
1474 
1475 	entry->cb_data = NULL;
1476 	entry->buf = NULL;
1477 	entry->len = 0;
1478 	entry->flags = NTBT_LINK_DOWN_FLAG;
1479 
1480 	mtx_lock(&qp->tx_lock);
1481 	rc = ntb_process_tx(qp, entry);
1482 	mtx_unlock(&qp->tx_lock);
1483 	if (rc != 0)
1484 		printf("ntb: Failed to send link down\n");
1485 
1486 	ntb_qp_link_down_reset(qp);
1487 }
1488 
1489 
1490 /* List Management */
1491 
1492 static void
1493 ntb_list_add(struct mtx *lock, struct ntb_queue_entry *entry,
1494     struct ntb_queue_list *list)
1495 {
1496 
1497 	mtx_lock_spin(lock);
1498 	STAILQ_INSERT_TAIL(list, entry, entry);
1499 	mtx_unlock_spin(lock);
1500 }
1501 
1502 static struct ntb_queue_entry *
1503 ntb_list_rm(struct mtx *lock, struct ntb_queue_list *list)
1504 {
1505 	struct ntb_queue_entry *entry;
1506 
1507 	mtx_lock_spin(lock);
1508 	if (STAILQ_EMPTY(list)) {
1509 		entry = NULL;
1510 		goto out;
1511 	}
1512 	entry = STAILQ_FIRST(list);
1513 	STAILQ_REMOVE_HEAD(list, entry);
1514 out:
1515 	mtx_unlock_spin(lock);
1516 
1517 	return (entry);
1518 }
1519 
1520 static struct ntb_queue_entry *
1521 ntb_list_mv(struct mtx *lock, struct ntb_queue_list *from,
1522     struct ntb_queue_list *to)
1523 {
1524 	struct ntb_queue_entry *entry;
1525 
1526 	mtx_lock_spin(lock);
1527 	if (STAILQ_EMPTY(from)) {
1528 		entry = NULL;
1529 		goto out;
1530 	}
1531 	entry = STAILQ_FIRST(from);
1532 	STAILQ_REMOVE_HEAD(from, entry);
1533 	STAILQ_INSERT_TAIL(to, entry, entry);
1534 
1535 out:
1536 	mtx_unlock_spin(lock);
1537 	return (entry);
1538 }
1539 
1540 /**
1541  * ntb_transport_qp_num - Query the qp number
1542  * @qp: NTB transport layer queue to be queried
1543  *
1544  * Query qp number of the NTB transport queue
1545  *
1546  * RETURNS: a zero based number specifying the qp number
1547  */
1548 unsigned char ntb_transport_qp_num(struct ntb_transport_qp *qp)
1549 {
1550 
1551 	return (qp->qp_num);
1552 }
1553 
1554 /**
1555  * ntb_transport_max_size - Query the max payload size of a qp
1556  * @qp: NTB transport layer queue to be queried
1557  *
1558  * Query the maximum payload size permissible on the given qp
1559  *
1560  * RETURNS: the max payload size of a qp
1561  */
1562 unsigned int
1563 ntb_transport_max_size(struct ntb_transport_qp *qp)
1564 {
1565 
1566 	return (qp->tx_max_frame - sizeof(struct ntb_payload_header));
1567 }
1568 
1569 unsigned int
1570 ntb_transport_tx_free_entry(struct ntb_transport_qp *qp)
1571 {
1572 	unsigned int head = qp->tx_index;
1573 	unsigned int tail = qp->remote_rx_info->entry;
1574 
1575 	return (tail >= head ? tail - head : qp->tx_max_entry + tail - head);
1576 }
1577 
1578 static device_method_t ntb_transport_methods[] = {
1579 	/* Device interface */
1580 	DEVMETHOD(device_probe,     ntb_transport_probe),
1581 	DEVMETHOD(device_attach,    ntb_transport_attach),
1582 	DEVMETHOD(device_detach,    ntb_transport_detach),
1583 	/* Bus interface */
1584 	DEVMETHOD(bus_child_location_str, ntb_transport_child_location_str),
1585 	DEVMETHOD(bus_print_child,  ntb_transport_print_child),
1586 	DEVMETHOD_END
1587 };
1588 
1589 devclass_t ntb_transport_devclass;
1590 static DEFINE_CLASS_0(ntb_transport, ntb_transport_driver,
1591     ntb_transport_methods, sizeof(struct ntb_transport_ctx));
1592 DRIVER_MODULE(ntb_transport, ntb_hw, ntb_transport_driver,
1593     ntb_transport_devclass, NULL, NULL);
1594 MODULE_DEPEND(ntb_transport, ntb, 1, 1, 1);
1595 MODULE_VERSION(ntb_transport, 1);
1596