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