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