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