Whamcloud - gitweb
LU-6142 lnet: discard lnet_current_net_count
[fs/lustre-release.git] / lnet / klnds / o2iblnd / o2iblnd.h
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lnet/klnds/o2iblnd/o2iblnd.h
32  *
33  * Author: Eric Barton <eric@bartonsoftware.com>
34  */
35
36 #include <linux/module.h>
37 #include <linux/kernel.h>
38
39 #if defined(NEED_LOCKDEP_IS_HELD_DISCARD_CONST) \
40  && defined(CONFIG_LOCKDEP) \
41  && defined(lockdep_is_held)
42 #undef lockdep_is_held
43         #define lockdep_is_held(lock) \
44                 lock_is_held((struct lockdep_map *)&(lock)->dep_map)
45 #endif
46
47 #ifdef HAVE_COMPAT_RDMA
48 #include <linux/compat-2.6.h>
49
50 #ifdef LINUX_3_17_COMPAT_H
51 #undef NEED_KTIME_GET_REAL_NS
52 #endif
53
54 #define HAVE_NLA_PUT_U64_64BIT 1
55 #define HAVE_NLA_PARSE_6_PARAMS 1
56 #define HAVE_NETLINK_EXTACK 1
57
58
59 /* MOFED has its own bitmap_alloc backport */
60 #define HAVE_BITMAP_ALLOC 1
61
62 #endif
63
64 #include <linux/kthread.h>
65 #include <linux/mm.h>
66 #include <linux/string.h>
67 #include <linux/stat.h>
68 #include <linux/errno.h>
69 #include <linux/unistd.h>
70 #include <linux/uio.h>
71
72 #include <asm/uaccess.h>
73 #include <asm/io.h>
74
75 #include <linux/init.h>
76 #include <linux/fs.h>
77 #include <linux/file.h>
78 #include <linux/stat.h>
79 #include <linux/list.h>
80 #include <linux/kmod.h>
81 #include <linux/sysctl.h>
82 #include <linux/pci.h>
83
84 #include <net/sock.h>
85 #include <linux/in.h>
86
87 #include <rdma/rdma_cm.h>
88 #include <rdma/ib_cm.h>
89 #include <rdma/ib_verbs.h>
90 #ifdef HAVE_FMR_POOL_API
91 #include <rdma/ib_fmr_pool.h>
92 #endif
93
94 #define DEBUG_SUBSYSTEM S_LND
95
96 #include <lnet/lib-lnet.h>
97 #include "o2iblnd-idl.h"
98
99 #define IBLND_PEER_HASH_BITS            7       /* log2 of # peer_ni lists */
100
101 #define IBLND_N_SCHED                   2
102 #define IBLND_N_SCHED_HIGH              4
103
104 struct kib_tunables {
105         int              *kib_dev_failover;     /* HCA failover */
106         unsigned int     *kib_service;          /* IB service number */
107         int              *kib_cksum;            /* checksum struct kib_msg? */
108         int              *kib_timeout;          /* comms timeout (seconds) */
109         int              *kib_keepalive;        /* keepalive timeout (seconds) */
110         char            **kib_default_ipif;     /* default IPoIB interface */
111         int              *kib_retry_count;
112         int              *kib_rnr_retry_count;
113         int              *kib_ib_mtu;           /* IB MTU */
114         int              *kib_require_priv_port;/* accept only privileged ports */
115         int              *kib_use_priv_port;    /* use privileged port for active connect */
116         /* # threads on each CPT */
117         int              *kib_nscheds;
118         int              *kib_wrq_sge;          /* # sg elements per wrq */
119         int              *kib_use_fastreg_gaps; /* enable discontiguous fastreg fragment support */
120 };
121
122 extern struct kib_tunables  kiblnd_tunables;
123
124 #define IBLND_MSG_QUEUE_SIZE_V1      8          /* V1 only : # messages/RDMAs in-flight */
125 #define IBLND_CREDIT_HIGHWATER_V1    7          /* V1 only : when eagerly to return credits */
126
127 #define IBLND_CREDITS_DEFAULT        8          /* default # of peer_ni credits */
128 #define IBLND_CREDITS_MAX          ((typeof(((struct kib_msg *) 0)->ibm_credits)) - 1)  /* Max # of peer_ni credits */
129
130 /* when eagerly to return credits */
131 #define IBLND_CREDITS_HIGHWATER(t, conn) ((conn->ibc_version) == IBLND_MSG_VERSION_1 ? \
132                                         IBLND_CREDIT_HIGHWATER_V1 : \
133                         min(t->lnd_peercredits_hiw, (__u32)conn->ibc_queue_depth - 1))
134
135 #ifdef HAVE_RDMA_CREATE_ID_5ARG
136 # define kiblnd_rdma_create_id(ns, cb, dev, ps, qpt) \
137          rdma_create_id((ns) ? (ns) : &init_net, cb, dev, ps, qpt)
138 #else
139 # ifdef HAVE_RDMA_CREATE_ID_4ARG
140 #  define kiblnd_rdma_create_id(ns, cb, dev, ps, qpt) \
141           rdma_create_id(cb, dev, ps, qpt)
142 # else
143 #  define kiblnd_rdma_create_id(ns, cb, dev, ps, qpt) \
144           rdma_create_id(cb, dev, ps)
145 # endif
146 #endif
147
148 /* 2 OOB shall suffice for 1 keepalive and 1 returning credits */
149 #define IBLND_OOB_CAPABLE(v)       ((v) != IBLND_MSG_VERSION_1)
150 #define IBLND_OOB_MSGS(v)           (IBLND_OOB_CAPABLE(v) ? 2 : 0)
151
152 #define IBLND_MSG_SIZE              (4<<10)                 /* max size of queued messages (inc hdr) */
153 #define IBLND_MAX_RDMA_FRAGS         LNET_MAX_IOV           /* max # of fragments supported */
154
155 /************************/
156 /* derived constants... */
157 /* Pools (shared by connections on each CPT) */
158 /* These pools can grow at runtime, so don't need give a very large value */
159 #define IBLND_TX_POOL                   256
160 #define IBLND_FMR_POOL                  256
161 #define IBLND_FMR_POOL_FLUSH            192
162
163 /* RX messages (per connection) */
164 #define IBLND_RX_MSGS(c)        \
165         ((c->ibc_queue_depth) * 2 + IBLND_OOB_MSGS(c->ibc_version))
166 #define IBLND_RX_MSG_BYTES(c)       (IBLND_RX_MSGS(c) * IBLND_MSG_SIZE)
167 #define IBLND_RX_MSG_PAGES(c)   \
168         ((IBLND_RX_MSG_BYTES(c) + PAGE_SIZE - 1) / PAGE_SIZE)
169
170 /* WRs and CQEs (per connection) */
171 #define IBLND_RECV_WRS(c)            IBLND_RX_MSGS(c)
172
173 /* 2 = LNet msg + Transfer chain */
174 #define IBLND_CQ_ENTRIES(c) (IBLND_RECV_WRS(c) + kiblnd_send_wrs(c))
175
176 struct kib_hca_dev;
177
178 /* o2iblnd can run over aliased interface */
179 #ifdef IFALIASZ
180 #define KIB_IFNAME_SIZE              IFALIASZ
181 #else
182 #define KIB_IFNAME_SIZE              256
183 #endif
184
185 enum kib_dev_caps {
186         IBLND_DEV_CAPS_FASTREG_ENABLED          = BIT(0),
187         IBLND_DEV_CAPS_FASTREG_GAPS_SUPPORT     = BIT(1),
188 #ifdef HAVE_FMR_POOL_API
189         IBLND_DEV_CAPS_FMR_ENABLED              = BIT(2),
190 #endif
191 };
192
193 struct kib_dev {
194         struct list_head        ibd_list;       /* chain on kib_devs */
195         struct list_head        ibd_fail_list;  /* chain on kib_failed_devs */
196         __u32                   ibd_ifip;       /* IPoIB interface IP */
197         /** IPoIB interface name */
198         char                    ibd_ifname[KIB_IFNAME_SIZE];
199         int                     ibd_nnets;      /* # nets extant */
200
201         time64_t                ibd_next_failover;
202         /* # failover failures */
203         int                     ibd_failed_failover;
204         /* failover in progress */
205         unsigned int            ibd_failover;
206         /* IPoIB interface is a bonding master */
207         unsigned int            ibd_can_failover;
208         struct list_head        ibd_nets;
209         struct kib_hca_dev      *ibd_hdev;
210         enum kib_dev_caps       ibd_dev_caps;
211 };
212
213 struct kib_hca_dev {
214         struct rdma_cm_id   *ibh_cmid;          /* listener cmid */
215         struct ib_device    *ibh_ibdev;         /* IB device */
216         int                  ibh_page_shift;    /* page shift of current HCA */
217         int                  ibh_page_size;     /* page size of current HCA */
218         __u64                ibh_page_mask;     /* page mask of current HCA */
219         __u64                ibh_mr_size;       /* size of MR */
220         int                  ibh_max_qp_wr;     /* maximum work requests size */
221 #ifdef HAVE_IB_GET_DMA_MR
222         struct ib_mr        *ibh_mrs;           /* global MR */
223 #endif
224         struct ib_pd        *ibh_pd;            /* PD */
225         u8                   ibh_port;          /* port number */
226         struct ib_event_handler
227                              ibh_event_handler; /* IB event handler */
228         int                  ibh_state;         /* device status */
229 #define IBLND_DEV_PORT_DOWN     0
230 #define IBLND_DEV_PORT_ACTIVE   1
231 #define IBLND_DEV_FATAL         2
232         struct kib_dev           *ibh_dev;           /* owner */
233         atomic_t             ibh_ref;           /* refcount */
234 };
235
236 /** # of seconds to keep pool alive */
237 #define IBLND_POOL_DEADLINE     300
238 /** # of seconds to retry if allocation failed */
239 #define IBLND_POOL_RETRY        1
240
241 struct kib_pages {
242         int                     ibp_npages;             /* # pages */
243         struct page            *ibp_pages[0];           /* page array */
244 };
245
246 struct kib_pool;
247 struct kib_poolset;
248
249 typedef int  (*kib_ps_pool_create_t)(struct kib_poolset *ps,
250                                      int inc, struct kib_pool **pp_po);
251 typedef void (*kib_ps_pool_destroy_t)(struct kib_pool *po);
252 typedef void (*kib_ps_node_init_t)(struct kib_pool *po, struct list_head *node);
253 typedef void (*kib_ps_node_fini_t)(struct kib_pool *po, struct list_head *node);
254
255 struct kib_net;
256
257 #define IBLND_POOL_NAME_LEN     32
258
259 struct kib_poolset {
260         /* serialize */
261         spinlock_t              ps_lock;
262         /* network it belongs to */
263         struct kib_net          *ps_net;
264         /* pool set name */
265         char                    ps_name[IBLND_POOL_NAME_LEN];
266         /* list of pools */
267         struct list_head        ps_pool_list;
268         /* failed pool list */
269         struct list_head        ps_failed_pool_list;
270         /* time stamp for retry if failed to allocate */
271         time64_t                ps_next_retry;
272         /* is allocating new pool */
273         int                     ps_increasing;
274         /* new pool size */
275         int                     ps_pool_size;
276         /* CPT id */
277         int                     ps_cpt;
278
279         /* create a new pool */
280         kib_ps_pool_create_t    ps_pool_create;
281         /* destroy a pool */
282         kib_ps_pool_destroy_t   ps_pool_destroy;
283         /* initialize new allocated node */
284         kib_ps_node_init_t      ps_node_init;
285         /* finalize node */
286         kib_ps_node_fini_t      ps_node_fini;
287 };
288
289 struct kib_pool {
290         /* chain on pool list */
291         struct list_head        po_list;
292         /* pre-allocated node */
293         struct list_head        po_free_list;
294         /* pool_set of this pool */
295         struct kib_poolset     *po_owner;
296         /* deadline of this pool */
297         time64_t                po_deadline;
298         /* # of elements in use */
299         int                     po_allocated;
300         /* pool is created on failed HCA */
301         int                     po_failed;
302         /* # of pre-allocated elements */
303         int                     po_size;
304 };
305
306 struct kib_tx_poolset {
307         struct kib_poolset      tps_poolset;            /* pool-set */
308         __u64                   tps_next_tx_cookie;     /* cookie of TX */
309 };
310
311 struct kib_tx_pool {
312         struct kib_pool         tpo_pool;               /* pool */
313         struct kib_hca_dev     *tpo_hdev;               /* device for this pool */
314         struct kib_tx          *tpo_tx_descs;           /* all the tx descriptors */
315         struct kib_pages       *tpo_tx_pages;           /* premapped tx msg pages */
316 };
317
318 struct kib_fmr_poolset {
319         spinlock_t              fps_lock;               /* serialize */
320         struct kib_net         *fps_net;                /* IB network */
321         struct list_head        fps_pool_list;          /* FMR pool list */
322         struct list_head        fps_failed_pool_list;   /* FMR pool list */
323         __u64                   fps_version;            /* validity stamp */
324         int                     fps_cpt;                /* CPT id */
325         int                     fps_pool_size;
326         int                     fps_flush_trigger;
327         int                     fps_cache;
328         /* is allocating new pool */
329         int                     fps_increasing;
330         /* time stamp for retry if failed to allocate */
331         time64_t                fps_next_retry;
332 };
333
334 #ifndef HAVE_IB_RDMA_WR
335 struct ib_rdma_wr {
336         struct ib_send_wr wr;
337 };
338 #endif
339
340 struct kib_fast_reg_descriptor { /* For fast registration */
341         struct list_head                 frd_list;
342         struct ib_rdma_wr                frd_inv_wr;
343 #ifdef HAVE_IB_MAP_MR_SG
344         struct ib_reg_wr                 frd_fastreg_wr;
345 #else
346         struct ib_rdma_wr                frd_fastreg_wr;
347         struct ib_fast_reg_page_list    *frd_frpl;
348 #endif
349         struct ib_mr                    *frd_mr;
350         bool                             frd_valid;
351         bool                             frd_posted;
352 };
353
354 struct kib_fmr_pool {
355         struct list_head        fpo_list;       /* chain on pool list */
356         struct kib_hca_dev     *fpo_hdev;       /* device for this pool */
357         struct kib_fmr_poolset      *fpo_owner; /* owner of this pool */
358 #ifdef HAVE_FMR_POOL_API
359         union {
360                 struct {
361                         struct ib_fmr_pool *fpo_fmr_pool; /* IB FMR pool */
362                 } fmr;
363 #endif
364                 struct { /* For fast registration */
365                         struct list_head  fpo_pool_list;
366                         int               fpo_pool_size;
367                 } fast_reg;
368 #ifdef HAVE_FMR_POOL_API
369         };
370         bool                    fpo_is_fmr; /* True if FMR pools allocated */
371 #endif
372         time64_t                fpo_deadline;   /* deadline of this pool */
373         int                     fpo_failed;     /* fmr pool is failed */
374         int                     fpo_map_count;  /* # of mapped FMR */
375 };
376
377 struct kib_fmr {
378         struct kib_fmr_pool             *fmr_pool;      /* pool of FMR */
379 #ifdef HAVE_FMR_POOL_API
380         struct ib_pool_fmr              *fmr_pfmr;      /* IB pool fmr */
381 #endif /* HAVE_FMR_POOL_API */
382         struct kib_fast_reg_descriptor  *fmr_frd;
383         u32                              fmr_key;
384 };
385
386 #ifdef HAVE_FMR_POOL_API
387
388 #ifdef HAVE_ORACLE_OFED_EXTENSIONS
389 #define kib_fmr_pool_map(pool, pgs, n, iov) \
390         ib_fmr_pool_map_phys((pool), (pgs), (n), (iov), NULL)
391 #else
392 #define kib_fmr_pool_map(pool, pgs, n, iov) \
393         ib_fmr_pool_map_phys((pool), (pgs), (n), (iov))
394 #endif
395
396 #endif /* HAVE_FMR_POOL_API */
397
398 struct kib_net {
399         /* chain on struct kib_dev::ibd_nets */
400         struct list_head        ibn_list;
401         __u64                   ibn_incarnation;/* my epoch */
402         int                     ibn_init;       /* initialisation state */
403         int                     ibn_shutdown;   /* shutting down? */
404
405         atomic_t                ibn_npeers;     /* # peers extant */
406         atomic_t                ibn_nconns;     /* # connections extant */
407
408         struct kib_tx_poolset   **ibn_tx_ps;    /* tx pool-set */
409         struct kib_fmr_poolset  **ibn_fmr_ps;   /* fmr pool-set */
410
411         struct kib_dev          *ibn_dev;       /* underlying IB device */
412         struct lnet_ni          *ibn_ni;        /* LNet interface */
413 };
414
415 #define KIB_THREAD_SHIFT                16
416 #define KIB_THREAD_ID(cpt, tid)         ((cpt) << KIB_THREAD_SHIFT | (tid))
417 #define KIB_THREAD_CPT(id)              ((id) >> KIB_THREAD_SHIFT)
418 #define KIB_THREAD_TID(id)              ((id) & ((1UL << KIB_THREAD_SHIFT) - 1))
419
420 struct kib_sched_info {
421         /* serialise */
422         spinlock_t              ibs_lock;
423         /* schedulers sleep here */
424         wait_queue_head_t       ibs_waitq;
425         /* conns to check for rx completions */
426         struct list_head        ibs_conns;
427         /* number of scheduler threads */
428         int                     ibs_nthreads;
429         /* max allowed scheduler threads */
430         int                     ibs_nthreads_max;
431         int                     ibs_cpt;        /* CPT id */
432 };
433
434 struct kib_data {
435         int                     kib_init;       /* initialisation state */
436         int                     kib_shutdown;   /* shut down? */
437         struct list_head        kib_devs;       /* IB devices extant */
438         /* list head of failed devices */
439         struct list_head        kib_failed_devs;
440         /* schedulers sleep here */
441         wait_queue_head_t       kib_failover_waitq;
442         atomic_t                kib_nthreads;   /* # live threads */
443         /* stabilize net/dev/peer_ni/conn ops */
444         rwlock_t                kib_global_lock;
445         /* hash table of all my known peers */
446         DECLARE_HASHTABLE(kib_peers, IBLND_PEER_HASH_BITS);
447         /* the connd task (serialisation assertions) */
448         void                    *kib_connd;
449         /* connections to setup/teardown */
450         struct list_head        kib_connd_conns;
451         /* connections with zero refcount */
452         struct list_head        kib_connd_zombies;
453         /* connections to reconnect */
454         struct list_head        kib_reconn_list;
455         /* peers wait for reconnection */
456         struct list_head        kib_reconn_wait;
457         /* connections wait for completion */
458         struct list_head        kib_connd_waits;
459         /*
460          * The second that peers are pulled out from \a kib_reconn_wait
461          * for reconnection.
462          */
463         time64_t                kib_reconn_sec;
464         /* connection daemon sleeps here */
465         wait_queue_head_t       kib_connd_waitq;
466         spinlock_t              kib_connd_lock; /* serialise */
467         struct ib_qp_attr       kib_error_qpa;  /* QP->ERROR */
468         /* percpt data for schedulers */
469         struct kib_sched_info   **kib_scheds;
470 };
471
472 #define IBLND_INIT_NOTHING         0
473 #define IBLND_INIT_DATA            1
474 #define IBLND_INIT_ALL             2
475
476 struct kib_rx {                                 /* receive message */
477         /* queue for attention */
478         struct list_head        rx_list;
479         /* owning conn */
480         struct kib_conn        *rx_conn;
481         /* # bytes received (-1 while posted) */
482         int                     rx_nob;
483         /* message buffer (host vaddr) */
484         struct kib_msg         *rx_msg;
485         /* message buffer (I/O addr) */
486         __u64                   rx_msgaddr;
487         /* for dma_unmap_single() */
488         DEFINE_DMA_UNMAP_ADDR(rx_msgunmap);
489         /* receive work item... */
490         struct ib_recv_wr       rx_wrq;
491         /* ...and its memory */
492         struct ib_sge           rx_sge;
493 };
494
495 #define IBLND_POSTRX_DONT_POST    0             /* don't post */
496 #define IBLND_POSTRX_NO_CREDIT    1             /* post: no credits */
497 #define IBLND_POSTRX_PEER_CREDIT  2             /* post: give peer_ni back 1 credit */
498 #define IBLND_POSTRX_RSRVD_CREDIT 3             /* post: give myself back 1 reserved credit */
499
500 struct kib_tx {                                 /* transmit message */
501         /* queue on idle_txs ibc_tx_queue etc. */
502         struct list_head        tx_list;
503         /* pool I'm from */
504         struct kib_tx_pool      *tx_pool;
505         /* owning conn */
506         struct kib_conn         *tx_conn;
507         /* # tx callbacks outstanding */
508         short                   tx_sending;
509         /* queued for sending */
510         short                   tx_queued;
511         /* waiting for peer_ni */
512         short                   tx_waiting;
513         /* LNET completion status */
514         int                     tx_status;
515         /* health status of the transmit */
516         enum lnet_msg_hstatus   tx_hstatus;
517         /* completion deadline */
518         ktime_t                 tx_deadline;
519         /* completion cookie */
520         __u64                   tx_cookie;
521         /* lnet msgs to finalize on completion */
522         struct lnet_msg         *tx_lntmsg[2];
523         /* message buffer (host vaddr) */
524         struct kib_msg          *tx_msg;
525         /* message buffer (I/O addr) */
526         __u64                   tx_msgaddr;
527         /* for dma_unmap_single() */
528         DEFINE_DMA_UNMAP_ADDR(tx_msgunmap);
529         /** sge for tx_msgaddr */
530         struct ib_sge           tx_msgsge;
531         /* # send work items */
532         int                     tx_nwrq;
533         /* # used scatter/gather elements */
534         int                     tx_nsge;
535         /* send work items... */
536         struct ib_rdma_wr       *tx_wrq;
537         /* ...and their memory */
538         struct ib_sge           *tx_sge;
539         /* rdma descriptor */
540         struct kib_rdma_desc    *tx_rd;
541         /* # entries in... */
542         int                     tx_nfrags;
543         /* dma_map_sg descriptor */
544         struct scatterlist      *tx_frags;
545         /* rdma phys page addrs */
546         __u64                   *tx_pages;
547         /* gaps in fragments */
548         bool                    tx_gaps;
549         /* FMR */
550         struct kib_fmr          tx_fmr;
551                                 /* dma direction */
552         int                     tx_dmadir;
553 };
554
555 struct kib_connvars {
556         /* connection-in-progress variables */
557         struct kib_msg          cv_msg;
558 };
559
560 struct kib_conn {
561         /* scheduler information */
562         struct kib_sched_info   *ibc_sched;
563         /* owning peer_ni */
564         struct kib_peer_ni      *ibc_peer;
565         /* HCA bound on */
566         struct kib_hca_dev      *ibc_hdev;
567         /* stash on peer_ni's conn list */
568         struct list_head        ibc_list;
569         /* schedule for attention */
570         struct list_head        ibc_sched_list;
571         /* version of connection */
572         __u16                   ibc_version;
573         /* reconnect later */
574         __u16                   ibc_reconnect:1;
575         /* which instance of the peer */
576         __u64                   ibc_incarnation;
577         /* # users */
578         atomic_t                ibc_refcount;
579         /* what's happening */
580         int                     ibc_state;
581         /* # uncompleted sends */
582         int                     ibc_nsends_posted;
583         /* # uncompleted NOOPs */
584         int                     ibc_noops_posted;
585         /* # credits I have */
586         int                     ibc_credits;
587         /* # credits to return */
588         int                     ibc_outstanding_credits;
589         /* # ACK/DONE msg credits */
590         int                     ibc_reserved_credits;
591         /* set on comms error */
592         int                     ibc_comms_error;
593         /* connections queue depth */
594         __u16                   ibc_queue_depth;
595         /* connections max frags */
596         __u16                   ibc_max_frags;
597         /* count of timeout txs waiting on cq */
598         __u16                   ibc_waits;
599         /* receive buffers owned */
600         unsigned int            ibc_nrx:16;
601         /* scheduled for attention */
602         unsigned int            ibc_scheduled:1;
603         /* CQ callback fired */
604         unsigned int            ibc_ready:1;
605         /* time of last send */
606         ktime_t                 ibc_last_send;
607         /** link chain for kiblnd_check_conns only */
608         struct list_head        ibc_connd_list;
609         /** rxs completed before ESTABLISHED */
610         struct list_head        ibc_early_rxs;
611         /** IBLND_MSG_NOOPs for IBLND_MSG_VERSION_1 */
612         struct list_head        ibc_tx_noops;
613         /* sends that need a credit */
614         struct list_head        ibc_tx_queue;
615         /* sends that don't need a credit */
616         struct list_head        ibc_tx_queue_nocred;
617         /* sends that need to reserve an ACK/DONE msg */
618         struct list_head        ibc_tx_queue_rsrvd;
619         /* active tx awaiting completion */
620         struct list_head        ibc_active_txs;
621         /* zombie tx awaiting done */
622         struct list_head        ibc_zombie_txs;
623         /* serialise */
624         spinlock_t              ibc_lock;
625         /* the rx descs */
626         struct kib_rx           *ibc_rxs;
627         /* premapped rx msg pages */
628         struct kib_pages        *ibc_rx_pages;
629
630         /* CM id */
631         struct rdma_cm_id       *ibc_cmid;
632         /* completion queue */
633         struct ib_cq            *ibc_cq;
634
635         /* in-progress connection state */
636         struct kib_connvars     *ibc_connvars;
637 };
638
639 #define IBLND_CONN_INIT               0         /* being initialised */
640 #define IBLND_CONN_ACTIVE_CONNECT     1         /* active sending req */
641 #define IBLND_CONN_PASSIVE_WAIT       2         /* passive waiting for rtu */
642 #define IBLND_CONN_ESTABLISHED        3         /* connection established */
643 #define IBLND_CONN_CLOSING            4         /* being closed */
644 #define IBLND_CONN_DISCONNECTED       5         /* disconnected */
645
646 struct kib_peer_ni {
647         /* on peer_ni hash chain */
648         struct hlist_node       ibp_list;
649         /* who's on the other end(s) */
650         lnet_nid_t              ibp_nid;
651         /* LNet interface */
652         struct lnet_ni          *ibp_ni;
653         /* all active connections */
654         struct list_head        ibp_conns;
655         /* next connection to send on for round robin */
656         struct kib_conn         *ibp_next_conn;
657         /* msgs waiting for a conn */
658         struct list_head        ibp_tx_queue;
659         /* incarnation of peer_ni */
660         __u64                   ibp_incarnation;
661         /* when (in seconds) I was last alive */
662         time64_t                ibp_last_alive;
663         /* # users */
664         atomic_t                ibp_refcount;
665         /* version of peer_ni */
666         __u16                   ibp_version;
667         /* current passive connection attempts */
668         unsigned short          ibp_accepting;
669         /* current active connection attempts */
670         unsigned short          ibp_connecting;
671         /* reconnect this peer_ni later */
672         unsigned char           ibp_reconnecting;
673         /* counter of how many times we triggered a conn race */
674         unsigned char           ibp_races;
675         /* # consecutive reconnection attempts to this peer */
676         unsigned int            ibp_reconnected;
677         /* errno on closing this peer_ni */
678         int                     ibp_error;
679         /* max map_on_demand */
680         __u16                   ibp_max_frags;
681         /* max_peer_credits */
682         __u16                   ibp_queue_depth;
683         /* reduced value which allows conn to be created if max fails */
684         __u16                   ibp_queue_depth_mod;
685 };
686
687 #ifndef HAVE_IB_INC_RKEY
688 /**
689  * ib_inc_rkey - increments the key portion of the given rkey. Can be used
690  * for calculating a new rkey for type 2 memory windows.
691  * @rkey - the rkey to increment.
692  */
693 static inline u32 ib_inc_rkey(u32 rkey)
694 {
695         const u32 mask = 0x000000ff;
696         return ((rkey + 1) & mask) | (rkey & ~mask);
697 }
698 #endif
699
700 extern struct kib_data kiblnd_data;
701
702 extern void kiblnd_hdev_destroy(struct kib_hca_dev *hdev);
703
704 int kiblnd_msg_queue_size(int version, struct lnet_ni *ni);
705
706 static inline int kiblnd_timeout(void)
707 {
708         return *kiblnd_tunables.kib_timeout ? *kiblnd_tunables.kib_timeout :
709                 lnet_get_lnd_timeout();
710 }
711
712 static inline int
713 kiblnd_concurrent_sends(int version, struct lnet_ni *ni)
714 {
715         struct lnet_ioctl_config_o2iblnd_tunables *tunables;
716         int concurrent_sends;
717
718         tunables = &ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
719         concurrent_sends = tunables->lnd_concurrent_sends;
720
721         if (version == IBLND_MSG_VERSION_1) {
722                 if (concurrent_sends > IBLND_MSG_QUEUE_SIZE_V1 * 2)
723                         return IBLND_MSG_QUEUE_SIZE_V1 * 2;
724
725                 if (concurrent_sends < IBLND_MSG_QUEUE_SIZE_V1 / 2)
726                         return IBLND_MSG_QUEUE_SIZE_V1 / 2;
727         }
728
729         return concurrent_sends;
730 }
731
732 static inline void
733 kiblnd_hdev_addref_locked(struct kib_hca_dev *hdev)
734 {
735         LASSERT(atomic_read(&hdev->ibh_ref) > 0);
736         atomic_inc(&hdev->ibh_ref);
737 }
738
739 static inline void
740 kiblnd_hdev_decref(struct kib_hca_dev *hdev)
741 {
742         LASSERT(atomic_read(&hdev->ibh_ref) > 0);
743         if (atomic_dec_and_test(&hdev->ibh_ref))
744                 kiblnd_hdev_destroy(hdev);
745 }
746
747 static inline int
748 kiblnd_dev_can_failover(struct kib_dev *dev)
749 {
750         if (!list_empty(&dev->ibd_fail_list)) /* already scheduled */
751                 return 0;
752
753         if (*kiblnd_tunables.kib_dev_failover == 0) /* disabled */
754                 return 0;
755
756         if (*kiblnd_tunables.kib_dev_failover > 1) /* force failover */
757                 return 1;
758
759         return dev->ibd_can_failover;
760 }
761
762 #define kiblnd_conn_addref(conn)                                \
763 do {                                                            \
764         CDEBUG(D_NET, "conn[%p] (%d)++\n",                      \
765                (conn), atomic_read(&(conn)->ibc_refcount)); \
766         atomic_inc(&(conn)->ibc_refcount);                  \
767 } while (0)
768
769 #define kiblnd_conn_decref(conn)                                        \
770 do {                                                                    \
771         unsigned long flags;                                            \
772                                                                         \
773         CDEBUG(D_NET, "conn[%p] (%d)--\n",                              \
774                (conn), atomic_read(&(conn)->ibc_refcount));             \
775         LASSERT_ATOMIC_POS(&(conn)->ibc_refcount);                      \
776         if (atomic_dec_and_test(&(conn)->ibc_refcount)) {               \
777                 spin_lock_irqsave(&kiblnd_data.kib_connd_lock, flags);  \
778                 list_add_tail(&(conn)->ibc_list,                        \
779                                   &kiblnd_data.kib_connd_zombies);      \
780                 wake_up(&kiblnd_data.kib_connd_waitq);          \
781                 spin_unlock_irqrestore(&kiblnd_data.kib_connd_lock, flags);\
782         }                                                               \
783 } while (0)
784
785 #define kiblnd_peer_addref(peer_ni)                                \
786 do {                                                            \
787         CDEBUG(D_NET, "peer_ni[%p] -> %s (%d)++\n",                \
788                (peer_ni), libcfs_nid2str((peer_ni)->ibp_nid),         \
789                atomic_read (&(peer_ni)->ibp_refcount));         \
790         atomic_inc(&(peer_ni)->ibp_refcount);                   \
791 } while (0)
792
793 #define kiblnd_peer_decref(peer_ni)                                \
794 do {                                                            \
795         CDEBUG(D_NET, "peer_ni[%p] -> %s (%d)--\n",                \
796                (peer_ni), libcfs_nid2str((peer_ni)->ibp_nid),         \
797                atomic_read (&(peer_ni)->ibp_refcount));         \
798         LASSERT_ATOMIC_POS(&(peer_ni)->ibp_refcount);              \
799         if (atomic_dec_and_test(&(peer_ni)->ibp_refcount))      \
800                 kiblnd_destroy_peer(peer_ni);                      \
801 } while (0)
802
803 static inline bool
804 kiblnd_peer_connecting(struct kib_peer_ni *peer_ni)
805 {
806         return peer_ni->ibp_connecting != 0 ||
807                peer_ni->ibp_reconnecting != 0 ||
808                peer_ni->ibp_accepting != 0;
809 }
810
811 static inline bool
812 kiblnd_peer_idle(struct kib_peer_ni *peer_ni)
813 {
814         return !kiblnd_peer_connecting(peer_ni) && list_empty(&peer_ni->ibp_conns);
815 }
816
817 static inline int
818 kiblnd_peer_active(struct kib_peer_ni *peer_ni)
819 {
820         /* Am I in the peer_ni hash table? */
821         return !hlist_unhashed(&peer_ni->ibp_list);
822 }
823
824 static inline struct kib_conn *
825 kiblnd_get_conn_locked(struct kib_peer_ni *peer_ni)
826 {
827         struct list_head *next;
828
829         LASSERT(!list_empty(&peer_ni->ibp_conns));
830
831         /* Advance to next connection, be sure to skip the head node */
832         if (!peer_ni->ibp_next_conn ||
833             peer_ni->ibp_next_conn->ibc_list.next == &peer_ni->ibp_conns)
834                 next = peer_ni->ibp_conns.next;
835         else
836                 next = peer_ni->ibp_next_conn->ibc_list.next;
837         peer_ni->ibp_next_conn = list_entry(next, struct kib_conn, ibc_list);
838
839         return peer_ni->ibp_next_conn;
840 }
841
842 static inline int
843 kiblnd_send_keepalive(struct kib_conn *conn)
844 {
845         s64 keepalive_ns = *kiblnd_tunables.kib_keepalive * NSEC_PER_SEC;
846
847         return (*kiblnd_tunables.kib_keepalive > 0) &&
848                 ktime_after(ktime_get(),
849                             ktime_add_ns(conn->ibc_last_send, keepalive_ns));
850 }
851
852 static inline int
853 kiblnd_need_noop(struct kib_conn *conn)
854 {
855         struct lnet_ni *ni = conn->ibc_peer->ibp_ni;
856         struct lnet_ioctl_config_o2iblnd_tunables *tunables;
857
858         LASSERT(conn->ibc_state >= IBLND_CONN_ESTABLISHED);
859         tunables = &ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib;
860
861         if (conn->ibc_outstanding_credits <
862             IBLND_CREDITS_HIGHWATER(tunables, conn) &&
863             !kiblnd_send_keepalive(conn))
864                 return 0; /* No need to send NOOP */
865
866         if (IBLND_OOB_CAPABLE(conn->ibc_version)) {
867                 if (!list_empty(&conn->ibc_tx_queue_nocred))
868                         return 0; /* NOOP can be piggybacked */
869
870                 /* No tx to piggyback NOOP onto or no credit to send a tx */
871                 return (list_empty(&conn->ibc_tx_queue) ||
872                         conn->ibc_credits == 0);
873         }
874
875         if (!list_empty(&conn->ibc_tx_noops) || /* NOOP already queued */
876             !list_empty(&conn->ibc_tx_queue_nocred) || /* piggyback NOOP */
877             conn->ibc_credits == 0)                    /* no credit */
878                 return 0;
879
880         if (conn->ibc_credits == 1 &&      /* last credit reserved for */
881             conn->ibc_outstanding_credits == 0) /* giving back credits */
882                 return 0;
883
884         /* No tx to piggyback NOOP onto or no credit to send a tx */
885         return (list_empty(&conn->ibc_tx_queue) || conn->ibc_credits == 1);
886 }
887
888 static inline void
889 kiblnd_abort_receives(struct kib_conn *conn)
890 {
891         ib_modify_qp(conn->ibc_cmid->qp,
892                      &kiblnd_data.kib_error_qpa, IB_QP_STATE);
893 }
894
895 static inline const char *
896 kiblnd_queue2str(struct kib_conn *conn, struct list_head *q)
897 {
898         if (q == &conn->ibc_tx_queue)
899                 return "tx_queue";
900
901         if (q == &conn->ibc_tx_queue_rsrvd)
902                 return "tx_queue_rsrvd";
903
904         if (q == &conn->ibc_tx_queue_nocred)
905                 return "tx_queue_nocred";
906
907         if (q == &conn->ibc_active_txs)
908                 return "active_txs";
909
910         LBUG();
911         return NULL;
912 }
913
914 /* CAVEAT EMPTOR: We rely on descriptor alignment to allow us to use the
915  * lowest bits of the work request id to stash the work item type. */
916
917 #define IBLND_WID_INVAL 0
918 #define IBLND_WID_TX    1
919 #define IBLND_WID_RX    2
920 #define IBLND_WID_RDMA  3
921 #define IBLND_WID_MR    4
922 #define IBLND_WID_MASK  7UL
923
924 static inline __u64
925 kiblnd_ptr2wreqid (void *ptr, int type)
926 {
927         unsigned long lptr = (unsigned long)ptr;
928
929         LASSERT ((lptr & IBLND_WID_MASK) == 0);
930         LASSERT ((type & ~IBLND_WID_MASK) == 0);
931         return (__u64)(lptr | type);
932 }
933
934 static inline void *
935 kiblnd_wreqid2ptr (__u64 wreqid)
936 {
937         return (void *)(((unsigned long)wreqid) & ~IBLND_WID_MASK);
938 }
939
940 static inline int
941 kiblnd_wreqid2type (__u64 wreqid)
942 {
943         return (wreqid & IBLND_WID_MASK);
944 }
945
946 static inline void
947 kiblnd_set_conn_state(struct kib_conn *conn, int state)
948 {
949         conn->ibc_state = state;
950         smp_mb();
951 }
952
953 static inline void
954 kiblnd_init_msg(struct kib_msg *msg, int type, int body_nob)
955 {
956         msg->ibm_type = type;
957         msg->ibm_nob = offsetof(struct kib_msg, ibm_u) + body_nob;
958 }
959
960 static inline int
961 kiblnd_rd_size(struct kib_rdma_desc *rd)
962 {
963         int   i;
964         int   size;
965
966         for (i = size = 0; i < rd->rd_nfrags; i++)
967                 size += rd->rd_frags[i].rf_nob;
968
969         return size;
970 }
971
972 static inline __u64
973 kiblnd_rd_frag_addr(struct kib_rdma_desc *rd, int index)
974 {
975         return rd->rd_frags[index].rf_addr;
976 }
977
978 static inline int
979 kiblnd_rd_frag_size(struct kib_rdma_desc *rd, int index)
980 {
981         return rd->rd_frags[index].rf_nob;
982 }
983
984 static inline __u32
985 kiblnd_rd_frag_key(struct kib_rdma_desc *rd, int index)
986 {
987         return rd->rd_key;
988 }
989
990 static inline int
991 kiblnd_rd_consume_frag(struct kib_rdma_desc *rd, int index, __u32 nob)
992 {
993         if (nob < rd->rd_frags[index].rf_nob) {
994                 rd->rd_frags[index].rf_addr += nob;
995                 rd->rd_frags[index].rf_nob  -= nob;
996         } else {
997                 index ++;
998         }
999
1000         return index;
1001 }
1002
1003 static inline int
1004 kiblnd_rd_msg_size(struct kib_rdma_desc *rd, int msgtype, int n)
1005 {
1006         LASSERT (msgtype == IBLND_MSG_GET_REQ ||
1007                  msgtype == IBLND_MSG_PUT_ACK);
1008
1009         return msgtype == IBLND_MSG_GET_REQ ?
1010                offsetof(struct kib_get_msg, ibgm_rd.rd_frags[n]) :
1011                offsetof(struct kib_putack_msg, ibpam_rd.rd_frags[n]);
1012 }
1013
1014 static inline __u64
1015 kiblnd_dma_mapping_error(struct ib_device *dev, u64 dma_addr)
1016 {
1017         return ib_dma_mapping_error(dev, dma_addr);
1018 }
1019
1020 static inline __u64 kiblnd_dma_map_single(struct ib_device *dev,
1021                                           void *msg, size_t size,
1022                                           enum dma_data_direction direction)
1023 {
1024         return ib_dma_map_single(dev, msg, size, direction);
1025 }
1026
1027 static inline void kiblnd_dma_unmap_single(struct ib_device *dev,
1028                                            __u64 addr, size_t size,
1029                                           enum dma_data_direction direction)
1030 {
1031         ib_dma_unmap_single(dev, addr, size, direction);
1032 }
1033
1034 #define KIBLND_UNMAP_ADDR_SET(p, m, a)  do {} while (0)
1035 #define KIBLND_UNMAP_ADDR(p, m, a)      (a)
1036
1037 static inline int kiblnd_dma_map_sg(struct ib_device *dev,
1038                                     struct scatterlist *sg, int nents,
1039                                     enum dma_data_direction direction)
1040 {
1041         return ib_dma_map_sg(dev, sg, nents, direction);
1042 }
1043
1044 static inline void kiblnd_dma_unmap_sg(struct ib_device *dev,
1045                                        struct scatterlist *sg, int nents,
1046                                        enum dma_data_direction direction)
1047 {
1048         ib_dma_unmap_sg(dev, sg, nents, direction);
1049 }
1050
1051 #ifndef HAVE_IB_SG_DMA_ADDRESS
1052 #include <linux/scatterlist.h>
1053 #define ib_sg_dma_address(dev, sg)      sg_dma_address(sg)
1054 #define ib_sg_dma_len(dev, sg)          sg_dma_len(sg)
1055 #endif
1056
1057 static inline __u64 kiblnd_sg_dma_address(struct ib_device *dev,
1058                                           struct scatterlist *sg)
1059 {
1060         return ib_sg_dma_address(dev, sg);
1061 }
1062
1063 static inline unsigned int kiblnd_sg_dma_len(struct ib_device *dev,
1064                                              struct scatterlist *sg)
1065 {
1066         return ib_sg_dma_len(dev, sg);
1067 }
1068
1069 #ifndef HAVE_RDMA_CONNECT_LOCKED
1070 #define rdma_connect_locked(cmid, cpp)  rdma_connect(cmid, cpp)
1071 #endif
1072
1073 /* XXX We use KIBLND_CONN_PARAM(e) as writable buffer, it's not strictly
1074  * right because OFED1.2 defines it as const, to use it we have to add
1075  * (void *) cast to overcome "const" */
1076
1077 #define KIBLND_CONN_PARAM(e)            ((e)->param.conn.private_data)
1078 #define KIBLND_CONN_PARAM_LEN(e)        ((e)->param.conn.private_data_len)
1079
1080 void kiblnd_abort_txs(struct kib_conn *conn, struct list_head *txs);
1081 void kiblnd_map_rx_descs(struct kib_conn *conn);
1082 void kiblnd_unmap_rx_descs(struct kib_conn *conn);
1083 void kiblnd_pool_free_node(struct kib_pool *pool, struct list_head *node);
1084 struct list_head *kiblnd_pool_alloc_node(struct kib_poolset *ps);
1085
1086 int kiblnd_fmr_pool_map(struct kib_fmr_poolset *fps, struct kib_tx *tx,
1087                         struct kib_rdma_desc *rd, u32 nob, u64 iov,
1088                         struct kib_fmr *fmr);
1089 void kiblnd_fmr_pool_unmap(struct kib_fmr *fmr, int status);
1090
1091 int  kiblnd_tunables_setup(struct lnet_ni *ni);
1092 int  kiblnd_tunables_init(void);
1093
1094 int  kiblnd_connd (void *arg);
1095 int  kiblnd_scheduler(void *arg);
1096 int  kiblnd_thread_start(int (*fn)(void *arg), void *arg, char *name);
1097 int  kiblnd_failover_thread (void *arg);
1098
1099 int kiblnd_alloc_pages(struct kib_pages **pp, int cpt, int npages);
1100
1101 int  kiblnd_cm_callback(struct rdma_cm_id *cmid,
1102                         struct rdma_cm_event *event);
1103 int  kiblnd_translate_mtu(int value);
1104
1105 int  kiblnd_dev_failover(struct kib_dev *dev, struct net *ns);
1106 int kiblnd_create_peer(struct lnet_ni *ni, struct kib_peer_ni **peerp,
1107                        lnet_nid_t nid);
1108 void kiblnd_destroy_peer(struct kib_peer_ni *peer);
1109 bool kiblnd_reconnect_peer(struct kib_peer_ni *peer);
1110 void kiblnd_destroy_dev(struct kib_dev *dev);
1111 void kiblnd_unlink_peer_locked(struct kib_peer_ni *peer_ni);
1112 struct kib_peer_ni *kiblnd_find_peer_locked(struct lnet_ni *ni, lnet_nid_t nid);
1113 int  kiblnd_close_stale_conns_locked(struct kib_peer_ni *peer_ni,
1114                                      int version, u64 incarnation);
1115 int  kiblnd_close_peer_conns_locked(struct kib_peer_ni *peer_ni, int why);
1116
1117 struct kib_conn *kiblnd_create_conn(struct kib_peer_ni *peer_ni,
1118                                     struct rdma_cm_id *cmid,
1119                                     int state, int version);
1120 void kiblnd_destroy_conn(struct kib_conn *conn);
1121 void kiblnd_close_conn(struct kib_conn *conn, int error);
1122 void kiblnd_close_conn_locked(struct kib_conn *conn, int error);
1123
1124 void kiblnd_launch_tx(struct lnet_ni *ni, struct kib_tx *tx, lnet_nid_t nid);
1125 void kiblnd_txlist_done(struct list_head *txlist, int status,
1126                         enum lnet_msg_hstatus hstatus);
1127
1128 void kiblnd_qp_event(struct ib_event *event, void *arg);
1129 void kiblnd_cq_event(struct ib_event *event, void *arg);
1130 void kiblnd_cq_completion(struct ib_cq *cq, void *arg);
1131
1132 void kiblnd_pack_msg(struct lnet_ni *ni, struct kib_msg *msg, int version,
1133                      int credits, lnet_nid_t dstnid, __u64 dststamp);
1134 int kiblnd_unpack_msg(struct kib_msg *msg, int nob);
1135 int kiblnd_post_rx(struct kib_rx *rx, int credit);
1136
1137 int kiblnd_send(struct lnet_ni *ni, void *private, struct lnet_msg *lntmsg);
1138 int kiblnd_recv(struct lnet_ni *ni, void *private, struct lnet_msg *lntmsg,
1139                 int delayed, unsigned int niov,
1140                 struct bio_vec *kiov, unsigned int offset, unsigned int mlen,
1141                 unsigned int rlen);
1142