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