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