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