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