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