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