Whamcloud - gitweb
LU-16548 lnet: report actual timeout used by lnd
[fs/lustre-release.git] / lnet / klnds / gnilnd / gnilnd.h
1 /*
2  * Copyright (C) 2004 Cluster File Systems, Inc.
3  *
4  * Copyright (C) 2009-2012 Cray, Inc.
5  *
6  * Copyright (c) 2014, 2016, Intel Corporation.
7  *
8  *   Derived from work by: Eric Barton <eric@bartonsoftware.com>
9  *   Author: Nic Henke <nic@cray.com>
10  *   Author: James Shimek <jshimek@cray.com>
11  *
12  *   This file is part of Lustre, http://www.lustre.org.
13  *
14  *   Lustre is free software; you can redistribute it and/or
15  *   modify it under the terms of version 2 of the GNU General Public
16  *   License as published by the Free Software Foundation.
17  *
18  *   Lustre is distributed in the hope that it will be useful,
19  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
20  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  *   GNU General Public License for more details.
22  *
23  *   You should have received a copy of the GNU General Public License
24  *   along with Lustre; if not, write to the Free Software
25  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26  *
27  */
28 #ifndef _GNILND_GNILND_H_
29 #define _GNILND_GNILND_H_
30
31 #define DEBUG_SUBSYSTEM S_LND
32
33 #include <linux/module.h>
34 #include <linux/kernel.h>
35 #include <linux/mm.h>
36 #include <linux/string.h>
37 #include <linux/stat.h>
38 #include <linux/errno.h>
39 #ifdef HAVE_LINUX_KERNEL_LOCK
40 #include <linux/smp_lock.h>
41 #endif
42 #include <linux/unistd.h>
43 #include <linux/uio.h>
44 #include <linux/time.h>
45 #include <asm/timex.h>
46
47 #include <asm/uaccess.h>
48 #include <asm/io.h>
49
50 #include <linux/init.h>
51 #include <linux/fs.h>
52 #include <linux/file.h>
53 #include <linux/stat.h>
54 #include <linux/list.h>
55 #include <linux/kmod.h>
56 #include <linux/sysctl.h>
57 #include <linux/kthread.h>
58 #include <linux/nmi.h>
59
60 #include <net/sock.h>
61 #include <linux/in.h>
62 #include <linux/nmi.h>
63
64 #include <lnet/lib-lnet.h>
65
66 #include <gni_pub.h>
67
68 static inline time_t cfs_duration_sec(long duration_jiffies)
69 {
70         return jiffies_to_msecs(duration_jiffies) / MSEC_PER_SEC;
71 }
72
73 #ifdef CONFIG_SLAB
74 #define GNILND_MBOX_SIZE        KMALLOC_MAX_SIZE
75 #else
76 #define GNILND_SHIFT_HIGH       ((MAX_ORDER + PAGE_SHIFT - 1) <= 25 ? \
77                                 (MAX_ORDER + PAGE_SHIFT - 1) : 25)
78 #define GNILND_SHIFT_MAX        GNILND_SHIFT_HIGH
79 #define GNILND_MBOX_SIZE        (1UL << GNILND_SHIFT_MAX)
80 #endif
81
82
83 /* tunables determined at compile time */
84 #define GNILND_MIN_TIMEOUT      5               /* minimum timeout interval (seconds) */
85 #define GNILND_TO2KA(t)         (((t)-1)/2)     /* timeout -> keepalive interval */
86 #define GNILND_MIN_RECONNECT_TO (GNILND_BASE_TIMEOUT/4)
87 #define GNILND_MAX_RECONNECT_TO GNILND_BASE_TIMEOUT
88 #define GNILND_HARDWARE_TIMEOUT 15              /* maximum time for data to travel between nodes */
89 #define GNILND_MDD_TIMEOUT      15              /* MDD hold timeout in minutes */
90 #define GNILND_SCHED_TIMEOUT       1
91 #define GNILND_DGRAM_TIMEOUT       2
92 #define GNILND_FAST_MAPPING_TRY   \
93         *kgnilnd_tunables.kgn_max_retransmits   /* maximum number to attempt mapping of a tx */
94 #define GNILND_MAP_RETRY_RATE      1            /* interval between mapping attempts in jiffies */
95
96 /* map failure timeout */
97 #define GNILND_MAP_TIMEOUT         \
98         (cfs_time_seconds(*kgnilnd_tunables.kgn_timeout * \
99          *kgnilnd_tunables.kgn_timeout))
100
101 /* Should we use the no_retry flag with vzalloc */
102 #define GNILND_VZALLOC_RETRY 0
103
104 /* reaper thread wakup interval */
105 #define GNILND_REAPER_THREAD_WAKE  1
106 /* reaper thread checks each conn NCHECKS time every kgnilnd_data.kgn_new_min_timeout */
107 #define GNILND_REAPER_NCHECKS      4
108
109 /* fixed constants */
110 #define GNILND_MAXDEVS          1               /* max # of GNI devices currently supported */
111 #define GNILND_MBOX_CREDITS     256             /* number of credits per mailbox */
112 #define GNILND_CONN_MAGIC         0xa100f       /* magic value for verifying connection validity */
113 /* checksum values */
114 #define GNILND_CHECKSUM_OFF             0       /* checksum turned off */
115 #define GNILND_CHECKSUM_SMSG_HEADER     1       /* Only checksum SMSG header */
116 #define GNILND_CHECKSUM_SMSG            2       /* checksum entire SMSG packet */
117 #define GNILND_CHECKSUM_SMSG_BTE        3       /* Full checksum support */
118
119 /* tune down some COMPUTE options as they won't see the same number of connections and
120  * don't need the throughput of multiple threads by default */
121 #if defined(CONFIG_CRAY_COMPUTE)
122 #ifdef CONFIG_MK1OM
123 #define GNILND_SCHED_THREADS      2             /* default # of kgnilnd_scheduler threads */
124 #else
125 #define GNILND_SCHED_THREADS      1             /* default # of kgnilnd_scheduler threads */
126 #endif
127 #define GNILND_FMABLK             64            /* default number of mboxes per fmablk */
128 #define GNILND_SCHED_NICE         0             /* default nice value for scheduler threads */
129 #define GNILND_COMPUTE            1             /* compute image */
130 #define GNILND_FAST_RECONNECT     1             /* Fast Reconnect option */
131 #define GNILND_DEFAULT_CREDITS    64            /* Default number of simultaneous transmits */
132 #else
133 #define GNILND_FMABLK             1024          /* default number of mboxes per fmablk */
134 #define GNILND_SCHED_NICE         -20           /* default nice value for scheduler threads */
135 #define GNILND_COMPUTE            0             /* service image */
136 #define GNILND_FAST_RECONNECT     0             /* Fast Reconnect option */
137 #define GNILND_DEFAULT_CREDITS    256           /* Default number of simultaneous transmits */
138 #endif
139
140 /* EXTRA_BITS are there to allow us to hide NOOP/CLOSE and anything else out of band */
141 #define GNILND_EXTRA_BITS         1
142 /* maximum number of conns & bits for cqid in the SMSG event data */
143 #define GNILND_CQID_NBITS         (21 - GNILND_EXTRA_BITS)
144 #define GNILND_MSGID_TX_NBITS     (32 - GNILND_CQID_NBITS)
145 #define GNILND_MAX_CQID           (1 << GNILND_CQID_NBITS)
146 #define GNILND_MAX_MSG_ID         (1 << GNILND_MSGID_TX_NBITS)
147 #define GNILND_MAX_MSG_SIZE       (*kgnilnd_tunables.kgn_max_immediate + sizeof(kgn_msg_t))
148
149 /* need sane upper bound to limit copy overhead */
150 #define GNILND_MAX_IMMEDIATE      (64<<10)
151 /* allow for 4M transfers over gni. Note 2.5M used by DVS */
152 #define GNILND_MAX_IOV            1024
153
154 /* Max number of connections to keep in purgatory per peer */
155 #define GNILND_PURGATORY_MAX      5
156 /* Closing, don't put in purgatory */
157 #define GNILND_NOPURG             222
158
159 /* payload size to add to the base mailbox size
160  * This is subtracting 2 from the concurrent_sends as 4 messages are included in the size
161  * gni_smsg_buff_size_needed calculates, the MAX_PAYLOAD is added to
162  * the calculation return from that function.*/
163 #define GNILND_MBOX_PAYLOAD     \
164           (GNILND_MAX_MSG_SIZE * \
165           ((*kgnilnd_tunables.kgn_concurrent_sends - 2) * 2));
166
167 /* timeout -> deadman timer for kgni mdd holds */
168 #define GNILND_TIMEOUT2DEADMAN   ((*kgnilnd_tunables.kgn_mdd_timeout) * 1000 * 60)
169
170 /* timeout for failing sends in t is in jiffies*/
171 #define GNILND_TIMEOUTRX(t)     (t + cfs_time_seconds(*kgnilnd_tunables.kgn_hardware_timeout))
172
173 /* time when to release from purgatory in the reaper thread in jiffies */
174 #define GNILND_PURG_RELEASE(t)   (GNILND_TIMEOUTRX(t) * 3)
175
176 /* Macro for finding last_rx 2 datapoints are compared
177  * and the most recent one in jiffies is returned.
178  */
179 #define GNILND_LASTRX(conn) (time_after(conn->gnc_last_rx, conn->gnc_last_rx_cq) \
180                                 ? conn->gnc_last_rx : conn->gnc_last_rx_cq)
181
182 /* fmablk registration failures timeout before failing node */
183 #define GNILND_REGFAILTO_DISABLE  -1
184
185 /************************************************************************
186  * Enum, flag and tag data
187  */
188 #define GNILND_INIT_NOTHING         0
189 #define GNILND_INIT_DATA            1
190 #define GNILND_INIT_ALL             2
191
192 /* If you change the ordering away from MAPPED = UNMAPPED + 1, things break */
193 #define GNILND_BUF_NONE           0              /* buffer type not set */
194 #define GNILND_BUF_IMMEDIATE      1              /* immediate data */
195 #define GNILND_BUF_IMMEDIATE_KIOV 2              /* immediate data */
196 #define GNILND_BUF_PHYS_UNMAPPED  3              /* physical: not mapped yet */
197 #define GNILND_BUF_PHYS_MAPPED    4              /* physical: mapped already */
198
199 #define GNILND_TX_WAITING_REPLY      (1<<1)     /* expecting to receive reply */
200 #define GNILND_TX_WAITING_COMPLETION (1<<2)     /* waiting for smsg_send to complete */
201 #define GNILND_TX_PENDING_RDMA       (1<<3)     /* RDMA transaction pending until we get prev. completion */
202 #define GNILND_TX_QUIET_ERROR        (1<<4)     /* don't print error on tx_done */
203 #define GNILND_TX_FAIL_SMSG          (1<<5)     /* pass down error injection for SMSG fail */
204
205 /* stash above max CQID to avoid any collision */
206 #define GNILND_MSGID_NOOP           (GNILND_MAX_CQID + 128)
207 #define GNILND_MSGID_CLOSE          (GNILND_MSGID_NOOP + 1)
208
209 /* kgn_msg_t::gnm_type */
210 #define GNILND_MSG_NONE              0x00        /* illegal message */
211 #define GNILND_MSG_NOOP              0x01        /* empty gnm_u (keepalive) */
212 #define GNILND_MSG_IMMEDIATE         0x02        /* gnm_u.immediate */
213 #define GNILND_MSG_PUT_REQ           0x03        /* gnm_u.putreq (src->sink) */
214 #define GNILND_MSG_PUT_NAK           0x04        /* gnm_u.completion (no PUT match: sink->src) */
215 #define GNILND_MSG_PUT_ACK           0x05        /* gnm_u.putack (PUT matched: sink->src) */
216 #define GNILND_MSG_PUT_DONE          0x06        /* gnm_u.completion (src->sink) */
217 #define GNILND_MSG_GET_REQ           0x07        /* gnm_u.get (sink->src) */
218 #define GNILND_MSG_GET_NAK           0x08        /* gnm_u.completion (no GET match: src->sink) */
219 #define GNILND_MSG_GET_DONE          0x09        /* gnm_u.completion (src->sink) */
220 #define GNILND_MSG_CLOSE             0x0a        /* empty gnm_u */
221 #define GNILND_MSG_PUT_REQ_REV       0x0b        /* gnm_u.get (src->sink) */
222 #define GNILND_MSG_PUT_DONE_REV      0x0c        /* gnm_u.completion (sink->src) */
223 #define GNILND_MSG_PUT_NAK_REV       0x0d        /* gnm_u.completion (no PUT match: sink->src) */
224 #define GNILND_MSG_GET_REQ_REV       0x0e        /* gnm_u.get (sink->src ) */
225 #define GNILND_MSG_GET_ACK_REV       0x0f        /* gnm_u.getack (GET matched: src->sink) */
226 #define GNILND_MSG_GET_DONE_REV      0x10        /* gnm_u.completion (sink -> src) */
227 #define GNILND_MSG_GET_NAK_REV       0x11        /* gnm_u.completeion (no GET match: sink -> src) */
228
229 /* defines for gnc_*scheduled states */
230 #define GNILND_CONN_IDLE             0
231 #define GNILND_CONN_SCHED            1
232 #define GNILND_CONN_WANTS_SCHED      2
233 #define GNILND_CONN_PROCESS          3
234
235 #define GNILND_DEV_IDLE              0
236 #define GNILND_DEV_IRQ               1
237 #define GNILND_DEV_LOOP              2
238
239 #define GNILND_DGRAM_IDLE            0
240 #define GNILND_DGRAM_SCHED           1
241 #define GNILND_DGRAM_PROCESS         2
242
243 #define GNILND_PEER_IDLE             0
244 #define GNILND_PEER_CONNECT          1
245 #define GNILND_PEER_POSTING          2
246 #define GNILND_PEER_POSTED           3
247 #define GNILND_PEER_NEEDS_DEATH      4
248 #define GNILND_PEER_KILL             5
249
250 /* for gnc_close_recvd */
251 #define GNILND_CLOSE_RX              1
252 #define GNILND_CLOSE_INJECT1         2
253 #define GNILND_CLOSE_INJECT2         3
254 #define GNILND_CLOSE_EARLY           4
255
256 /* defines for why quiesce trigger set */
257 #define GNILND_QUIESCE_IDLE          0
258 #define GNILND_QUIESCE_ADMIN         1
259 #define GNILND_QUIESCE_RESET         2
260 #define GNILND_QUIESCE_HW_QUIESCE    3
261
262 #define GNILND_PEER_CLEAN            0
263 #define GNILND_PEER_PERSISTING       1
264
265 #define GNILND_DEL_CONN              0
266 #define GNILND_DEL_PEER              1
267 #define GNILND_CLEAR_PURGATORY       2
268
269 #define GNILND_PEER_UP               0
270 #define GNILND_PEER_DOWN             1
271 #define GNILND_PEER_TIMED_OUT        2
272 #define GNILND_PEER_UNKNOWN          3
273
274 /* defines for reverse RDMA states */
275 #define GNILND_REVERSE_NONE             0
276 #define GNILND_REVERSE_GET              1
277 #define GNILND_REVERSE_PUT              2
278 #define GNILND_REVERSE_BOTH             (GNILND_REVERSE_GET | GNILND_REVERSE_PUT)
279
280 typedef enum kgn_fmablk_state {
281         GNILND_FMABLK_IDLE = 0, /* is allocated or ready to be freed */
282         GNILND_FMABLK_PHYS,     /* allocated out of slab of physical memory */
283         GNILND_FMABLK_VIRT,     /* 'standard' vmalloc hunk */
284         GNILND_FMABLK_FREED,    /* after free */
285 } kgn_fmablk_state_t;
286
287 typedef enum kgn_tx_list_state {
288         GNILND_TX_IDLE = 0,     /* TX is on the idle list, kgn_idle_txs */
289         GNILND_TX_ALLOCD,       /* TX has been alloced (off of idle), could be in any state transition */
290         GNILND_TX_PEERQ,        /* TX on peer->gnp_tx_queue (no live conn) */
291         GNILND_TX_MAPQ,         /* TX on dev:gnd_map_tx for buffer mapping */
292         GNILND_TX_FMAQ,         /* TX waiting to be send on conn FMA */
293         GNILND_TX_LIVE_FMAQ,    /* TX live on the FMA wire, waiting for completion or reply */
294         GNILND_TX_RDMAQ,        /* TX waiting to send FMA confirmation to auth RDMA PUT */
295         GNILND_TX_LIVE_RDMAQ,   /* TX live on the RDMA wire, waiting for completion */
296         GNILND_TX_DYING,        /* TX got caught on MAPQ or RDMAQ while conn was closing, needs someone to call tx_done */
297         GNILND_TX_FREED         /* TX is free! */
298 } kgn_tx_list_state_t;
299
300 typedef enum kgn_conn_state {
301         /* don't start @ 0 - prevent memset(0) badness */
302         GNILND_CONN_DUMMY = 0,
303         GNILND_CONN_LISTEN,
304         GNILND_CONN_CONNECTING,
305         GNILND_CONN_ESTABLISHED,
306         GNILND_CONN_CLOSING,
307         GNILND_CONN_CLOSED,
308         GNILND_CONN_DONE,
309         GNILND_CONN_DESTROY_EP
310 } kgn_conn_state_t;
311
312 /* changing these requires a change to GNILND_CONNREQ_VERSION and
313  * will result in dropped packets instead of NAKs. Adding to this is
314  * acceptable without changing the CONNREQ_VERSION, but code should
315  * be ready to handle NAKs on version mismatch  */
316 typedef enum kgn_connreq_type {
317         GNILND_CONNREQ_REQ = 1,         /* how YOU doin' ? */
318         GNILND_CONNREQ_NAK,             /* NO soup for you! */
319         GNILND_CONNREQ_CLOSE,           /* we should see other people */
320 } kgn_connreq_type_t;
321
322 typedef enum kgn_dgram_state {
323         /* don't use 0 to avoid thinking a memset of zero is valid data */
324         GNILND_DGRAM_USED = 1,
325         GNILND_DGRAM_POSTING,
326         GNILND_DGRAM_POSTED,
327         GNILND_DGRAM_PROCESSING,
328         GNILND_DGRAM_CANCELED,
329         GNILND_DGRAM_DONE,
330 } kgn_dgram_state_t;
331
332 typedef enum kgn_dgram_type {
333         GNILND_DGRAM_REQ = 1,         /* how YOU doin' ? */
334         GNILND_DGRAM_WC_REQ,          /* you talkin' to ME? */
335         GNILND_DGRAM_NAK,             /* NO soup for you! */
336         GNILND_DGRAM_CLOSE,           /* we should see other people */
337 } kgn_dgram_type_t;
338
339 /************************************************************************
340  * Wire message structs.  These are sent in sender's byte order
341  * (i.e. receiver checks magic and flips if required).
342  */
343
344 #define GNILND_MSG_MAGIC     LNET_PROTO_GNI_MAGIC /* unique magic */
345 #define GNILND_DGRAM_MAGIC   0x0DDBA11
346
347 /*  kgn_msg_t - FMA/SMSG wire struct
348   v2:
349    * - added checksum to FMA
350    * moved seq before paylod
351    * __packed added for alignment
352   v3:
353    * added gnm_payload_len for FMA payload size
354   v4:
355    * added gncm_retval to completion, allowing return code transmission
356      on RDMA NAKs
357   v5:
358    * changed how CQID and TX ids are assigned
359   v6:
360    * added retval on CLOSE
361   v7:
362    * added payload checksumming
363   v8:
364    * reworked checksumming a bit, changed payload checksums
365 */
366 #define GNILND_MSG_VERSION              8
367 /* kgn_connreq_t connection request datagram wire struct
368   v2:
369    * added NAKs
370 */
371
372 #define GNILND_CONNREQ_VERSION          2
373
374 typedef struct kgn_gniparams {
375         __u32            gnpr_host_id;          /* ph. host ID of the NIC */
376         __u32            gnpr_cqid;             /* cqid I want peer to use when sending events to me */
377         gni_smsg_attr_t  gnpr_smsg_attr;        /* my short msg. attributes */
378 } __packed kgn_gniparams_t;
379
380 typedef struct kgn_nak_data {
381         __s32            gnnd_errno;            /* errno reason for NAK */
382
383 } __packed kgn_nak_data_t;
384
385 /* the first bits of the connreq struct CANNOT CHANGE FORM EVER
386  * without breaking the ability for us to properly NAK someone */
387 typedef struct kgn_connreq {                    /* connection request/response */
388         __u32             gncr_magic;           /* I'm an gnilnd connreq */
389         __u32             gncr_cksum;           /* checksum (0 == disabled) */
390         __u16             gncr_type;            /* REQ, NAK, etc */
391         __u16             gncr_version;         /* this is my version number */
392         __u32             gncr_timeout;         /* sender's timeout */
393         __u64             gncr_srcnid;          /* sender's NID */
394         __u64             gncr_dstnid;          /* who sender expects to listen */
395         __u64             gncr_peerstamp;       /* sender's instance stamp */
396         __u64             gncr_connstamp;       /* sender's connection stamp */
397
398         /* everything before this needs to stay static, adding after should
399          * result in a change to GNILND_CONNREQ_VERSION */
400
401         union {
402                 kgn_gniparams_t   gncr_gnparams;        /* sender's endpoint info */
403                 kgn_nak_data_t    gncr_nakdata;         /* data (rc, etc) for NAK */
404         };
405 } __packed kgn_connreq_t;
406
407 typedef struct {
408         gni_mem_handle_t  gnrd_key;
409         __u64             gnrd_addr;
410         __u32             gnrd_nob;
411 } __packed kgn_rdma_desc_t;
412
413 typedef struct {
414         struct lnet_hdr_nid4    gnim_hdr;       /* LNet header */
415         /* LNet payload is in FMA "Message Data" */
416 } __packed kgn_immediate_msg_t;
417
418 typedef struct {
419         struct lnet_hdr_nid4    gnprm_hdr;      /* LNet header */
420         __u64                   gnprm_cookie;   /* opaque completion cookie */
421 } __packed kgn_putreq_msg_t;
422
423 typedef struct {
424         __u64             gnpam_src_cookie;     /* reflected completion cookie */
425         __u64             gnpam_dst_cookie;     /* opaque completion cookie */
426         __u16             gnpam_payload_cksum;  /* checksum for get msg */
427         kgn_rdma_desc_t   gnpam_desc;           /* sender's sink buffer */
428 } __packed kgn_putack_msg_t;
429
430 typedef struct {
431         struct lnet_hdr_nid4    gngm_hdr;       /* LNet header */
432         __u64                   gngm_cookie;    /* opaque completion cookie */
433         __u16                   gngm_payload_cksum; /* checksum for put msg */
434         kgn_rdma_desc_t         gngm_desc;      /* sender's sink buffer */
435 } __packed kgn_get_msg_t;
436
437 typedef struct {
438         int               gncm_retval;          /* error on NAK, size on REQ */
439         __u64             gncm_cookie;          /* reflected completion cookie */
440 } __packed kgn_completion_msg_t;
441
442 typedef struct {                                /* NB must fit in FMA "Prefix" */
443         __u32             gnm_magic;            /* I'm an gni message */
444         __u16             gnm_version;          /* this is my version number */
445         __u16             gnm_type;             /* msg type */
446         __u64             gnm_srcnid;           /* sender's NID */
447         __u64             gnm_connstamp;        /* sender's connection stamp */
448         __u32             gnm_seq;              /* incrementing sequence number */
449         __u16             gnm_cksum;            /* checksum (0 == no checksum ) */
450         __u16             gnm_payload_cksum;    /* payload checksum (0 == no checksum ) */
451         __u32             gnm_payload_len;      /* size of the FMA payload sent */
452         union {
453                 kgn_immediate_msg_t   immediate;
454                 kgn_putreq_msg_t      putreq;
455                 kgn_putack_msg_t      putack;
456                 kgn_get_msg_t         get;
457                 kgn_completion_msg_t  completion;
458         } gnm_u;
459 } __packed kgn_msg_t;
460
461 /************************************************************************
462  * runtime tunable data
463  */
464
465 typedef struct kgn_tunables {
466         int              *kgn_min_reconnect_interval; /* connreq starting timeout & retransmit interval */
467         int              *kgn_max_reconnect_interval; /* ...exponentially increasing to this */
468         int              *kgn_credits;          /* # concurrent sends */
469         int              *kgn_fma_cq_size;      /* # entries in receive CQ */
470         int              *kgn_peer_credits;     /* # LNet peer credits */
471         int              *kgn_concurrent_sends; /* max # of max_immediate in mbox */
472         int              *kgn_timeout;          /* comms timeout (seconds) */
473         int              *kgn_max_immediate;    /* immediate payload breakpoint */
474         int              *kgn_checksum;         /* checksum data */
475         int              *kgn_checksum_dump;    /* dump raw data to D_INFO log when checksumming */
476         int              *kgn_bte_put_dlvr_mode; /* BTE Put delivery mode */
477         int              *kgn_bte_get_dlvr_mode; /* BTE Get delivery mode */
478         int              *kgn_bte_relaxed_ordering; /* relaxed ordering (PASSPW) on BTE transfers */
479         int              *kgn_ptag;             /* PTAG for cdm_create */
480         int              *kgn_pkey;             /* PKEY for cdm_create */
481         int              *kgn_max_retransmits;  /* max number of FMA retransmits before entering delay list */
482         int              *kgn_nwildcard;        /* # wildcard per net to post */
483         int              *kgn_nice;             /* nice value for kgnilnd threads */
484         int              *kgn_rdmaq_intervals;  /* # intervals per second for rdmaq throttle */
485         int              *kgn_loops;            /* # of loops sched does before flush/heartbeat tickle */
486         int              *kgn_peer_hash_size;   /* size of kgn_peers */
487         int              *kgn_peer_health;      /* enable/disable peer health */
488         int              *kgn_peer_timeout;     /* Override of the default peer_timeout used by peer_health */
489         int              *kgn_vmap_cksum;       /* enable/disable vmap of kiov checksums */
490         int              *kgn_mbox_per_block;   /* mailboxes per fmablk */
491         int              *kgn_nphys_mbox;       /* # mailboxes to preallocate with physical memory */
492         int              *kgn_mbox_credits;     /* max credits per fma */
493         int              *kgn_sched_threads;    /* number of kgnilnd_scheduler threads */
494         int              *kgn_net_hash_size;    /* size of kgn_net_ht */
495         int              *kgn_hardware_timeout; /* max time for a message to get across the network */
496         int              *kgn_mdd_timeout;      /* max time for ghal to hold an mdd in minutes */
497         int              *kgn_sched_timeout;    /* max time for scheduler to run before yielding */
498         int              *kgn_dgram_timeout;    /* max time for dgram mover to run before scheduling */
499         int              *kgn_sched_nice;       /* nice value for kgnilnd scheduler threads */
500         int              *kgn_reverse_rdma;     /* Reverse RDMA setting */
501         int              *kgn_eager_credits;    /* allocated eager buffers */
502         int     *kgn_fast_reconn;      /* fast reconnection on conn timeout */
503         int     *kgn_efault_lbug;      /* LBUG on receiving an EFAULT */
504         int     *kgn_max_purgatory;    /* # conns/peer to keep in purgatory */
505         int     *kgn_reg_fail_timeout; /* registration failure timeout */
506         int     *kgn_thread_affinity;  /* bind scheduler threads to cpus */
507         int     *kgn_to_reconn_disable;/* disable reconnect after timeout */
508         int     *kgn_thread_safe;      /* use thread safe kgni API */
509         int     *kgn_vzalloc_noretry;  /* Should we pass the noretry flag */
510 } kgn_tunables_t;
511
512 typedef struct kgn_mbox_info {
513         lnet_nid_t mbx_prev_nid;
514         lnet_nid_t mbx_prev_purg_nid;
515         unsigned long mbx_create_conn_memset;
516         unsigned long mbx_add_purgatory;
517         unsigned long mbx_detach_of_purgatory;
518         unsigned long mbx_release_from_purgatory;
519         unsigned long mbx_release_purg_active_dgram;
520         int           mbx_nallocs;
521         int           mbx_nallocs_total;
522 } kgn_mbox_info_t;
523
524 typedef struct kgn_fma_memblock {
525         struct list_head    gnm_bufflist;                          /* memblock is part of device's  gnd_fma_buffs */
526         kgn_fmablk_state_t  gnm_state;                             /* how this memory allocated & state of it */
527         int                 gnm_hold_timeout;                      /* hold_timeout if used at unmap time */
528         int                 gnm_num_mboxs;                         /* total mboxes allocated */
529         int                 gnm_avail_mboxs;                       /* number of available mailboxes in the block */
530         int                 gnm_held_mboxs;                        /* number of purgatory held  mailboxes */
531         int                 gnm_mbox_size;                         /* size of the single mailbox */
532         int                 gnm_next_avail_mbox;                   /* next available mailbox */
533         long                gnm_max_timeout;                       /* max timeout for possible purgatory hold */
534         unsigned int        gnm_blk_size;                          /* how big is our hunk o memory ? */
535         void               *gnm_block;                             /* pointer to mem. block */
536         gni_mem_handle_t    gnm_hndl;                              /* mem. handle of the block */
537         unsigned long      *gnm_bit_array;                         /* bit array tracking allocation of mailboxes */
538         kgn_mbox_info_t    *gnm_mbox_info;                         /* array of mbox_information about each mbox */
539 } kgn_fma_memblock_t;
540
541 typedef struct kgn_device {
542         gni_nic_handle_t        gnd_handle;       /* device handle */
543         gni_cdm_handle_t        gnd_domain;       /* GNI communication domain */
544         gni_err_handle_t        gnd_err_handle;   /* device error handle */
545         unsigned long           gnd_sched_alive;  /* scheduler thread alive stamp */
546         gni_cq_handle_t         gnd_rcv_fma_cqh;  /* FMA rcv. completion queue handle */
547         gni_cq_handle_t         gnd_snd_rdma_cqh; /* rdma send completion queue handle */
548         gni_cq_handle_t         gnd_snd_fma_cqh;  /* rdma send completion queue handle */
549         struct mutex            gnd_cq_mutex;     /* CQ access serialization */
550         __u32                   gnd_host_id;      /* ph. host ID of the NIC */
551         int                     gnd_id;           /* device id, also index in kgn_devices */
552         __u32                   gnd_nid;          /* ph host ID translated to NID */
553         struct list_head        gnd_fma_buffs;    /* list of FMA memory blocks */
554         struct mutex            gnd_fmablk_mutex; /* mutex for FMA block memory alloc/free */
555         spinlock_t              gnd_fmablk_lock;  /* lock for mbox alloc/release */
556         atomic_t                gnd_nfmablk;      /* # of fmablk live */
557         atomic_t                gnd_fmablk_vers;  /* gnd_fma_bufs stamp */
558         atomic_t                gnd_neps;         /* # EP allocated to conns */
559         short                   gnd_ready;        /* stuff to do in scheduler thread */
560         struct list_head        gnd_ready_conns;  /* connections ready to tx/rx */
561         struct list_head        gnd_delay_conns;  /* connections in need of dla/or smsg credits */
562         struct list_head        gnd_map_tx;       /* TX: needing buffer mapping */
563         wait_queue_head_t       gnd_waitq;        /* scheduler wakeup */
564         spinlock_t              gnd_lock;         /* serialise gnd_ready_conns */
565         struct list_head        gnd_connd_peers;  /* peers waiting for a connection */
566         spinlock_t              gnd_connd_lock;   /* serialise connd_peers */
567         wait_queue_head_t       gnd_dgram_waitq;  /* dgram_mover thread wakeup */
568         wait_queue_head_t       gnd_dgping_waitq; /* dgram thread ping-pong */
569         int                     gnd_dgram_ready;  /* dgrams need movin' */
570         struct list_head       *gnd_dgrams;       /* nid hash to dgrams */
571         atomic_t                gnd_ndgrams;      /* # dgrams extant */
572         atomic_t                gnd_nwcdgrams;    /* # wildcard dgrams to post*/
573         spinlock_t              gnd_dgram_lock;   /* serialize gnd_dgrams */
574         struct list_head        gnd_map_list;     /* list of all mapped regions */
575         int                     gnd_map_version;  /* version flag for map list */
576         struct timer_list       gnd_map_timer;    /* wakey-wakey */
577         atomic_t                gnd_n_mdd;        /* number of total MDD - fma, tx, etc */
578         atomic_t                gnd_n_mdd_held;   /* number of total MDD held - fma, tx, etc */
579         atomic_t                gnd_nq_map;       /* # queued waiting for mapping (MDD/GART) */
580         atomic64_t              gnd_nbytes_map;   /* bytes of total GART maps - fma, tx, etc */
581         __u32                   gnd_map_nphys;    /* # TX phys mappings */
582         __u32                   gnd_map_physnop;  /* # TX phys pages mapped */
583         spinlock_t              gnd_map_lock;     /* serialize gnd_map_XXX */
584         unsigned long           gnd_next_map;     /* next mapping attempt in jiffies */
585         int                     gnd_map_attempt;  /* last map attempt # */
586         unsigned long           gnd_last_map;     /* map timeout base */
587         struct list_head        gnd_rdmaq;        /* RDMA to be sent */
588         spinlock_t              gnd_rdmaq_lock;   /* play nice with others */
589         atomic64_t              gnd_rdmaq_bytes_out; /* # bytes authorized */
590         atomic64_t              gnd_rdmaq_bytes_ok;  /* # bytes allowed until deadline */
591         atomic_t                gnd_rdmaq_nstalls;   /* # stalls due to throttle */
592         unsigned long           gnd_rdmaq_deadline;  /* when does bucket roll over ? */
593         struct timer_list       gnd_rdmaq_timer;     /* wakey-wakey */
594         atomic_t                gnd_short_ntx;      /* TX stats: short messages */
595         atomic64_t              gnd_short_txbytes;  /* TX stats: short message  payload*/
596         atomic_t                gnd_rdma_ntx;       /* TX stats: rdma messages */
597         atomic64_t              gnd_rdma_txbytes;   /* TX stats: rdma message payload*/
598         atomic_t                gnd_short_nrx;      /* RX stats: short messages */
599         atomic64_t              gnd_short_rxbytes;  /* RX stats: short message  payload*/
600         atomic_t                gnd_rdma_nrx;       /* RX stats: rdma messages */
601         atomic64_t              gnd_rdma_rxbytes;   /* RX stats: rdma message payload*/
602         atomic_t                gnd_fast_try;       /* # of times fast send tried */
603         atomic_t                gnd_fast_ok;        /* # of times fast send ok */
604         atomic_t                gnd_fast_block;     /* # of times fast send blocked */
605         unsigned long           gnd_mutex_delay;
606         atomic_t                gnd_n_yield;
607         atomic_t                gnd_n_schedule;
608         atomic_t                gnd_canceled_dgrams; /* # of outstanding cancels */
609         struct rw_semaphore     gnd_conn_sem;       /* serialize connection changes/data movement */
610         void                   *gnd_smdd_hold_buf;  /* buffer to keep smdd */
611         gni_mem_handle_t        gnd_smdd_hold_hndl; /* buffer mem handle */
612 } kgn_device_t;
613
614 typedef struct kgn_net {
615         struct list_head    gnn_list;           /* chain on kgni_data::kgn_nets */
616         kgn_device_t       *gnn_dev;            /* device for this net */
617         struct lnet_ni          *gnn_ni;             /* network interface instance */
618         atomic_t            gnn_refcount;       /* # current references */
619         int                 gnn_shutdown;       /* lnd_shutdown set */
620         __u16               gnn_netnum;         /* stash netnum for quicker lookup */
621 } kgn_net_t;
622
623 static inline lnet_nid_t
624 kgnilnd_lnd2lnetnid(lnet_nid_t ni_nid, lnet_nid_t kgnilnd_nid)
625 {
626         return LNET_MKNID(LNET_NIDNET(ni_nid), LNET_NIDADDR(kgnilnd_nid));
627 }
628
629 static inline lnet_nid_t
630 kgnilnd_lnet2lndnid(lnet_nid_t lnet_nid, lnet_nid_t kgnilnd_nid)
631 {
632         return LNET_MKNID(LNET_NIDNET(kgnilnd_nid), LNET_NIDADDR(lnet_nid));
633 }
634
635 /* The code for this is a bit ugly - but really  this just boils down to a __u64
636  * that can have various parts accessed separately.
637  *
638  * The lower 32 bits is the ID
639  * we give to SMSG for our completion event - it needs to be globally unique across
640  * all TX currently in flight. We separate that out into the CQID so that we can
641  * reference the connection (kgnilnd_cqid2conn_locked) and then the msg_id to pull
642  * the actual TX out of the per-connection gnc_tx_ref_table.
643  *
644  * The upper 32 bits are just extra stuff we put into the cookie to ensure this TX
645  * has a unique value we can send with RDMA setup messages to ensure the completion for
646  * those is unique across the wire. The extra 32 bits are there to ensure that TX id
647  * reuse is separated.
648  */
649
650 typedef struct kgn_tx_ev_id {
651         union {
652                 __u64             txe_cookie;    /* are you my mommy ? */
653                 struct {
654                         __u32     txe_chips;     /* extra bits to ensure ID unique across reuse */
655                         union {
656                                 __u32     txe_smsg_id;      /* ID for SMSG CQ event */
657                                 /* N.B: Never ever ever ever use the bit shifts directly,
658                                  * you are just asking for a world of pain and are at the
659                                  * mercy of the compiler layouts */
660                                 struct {
661                                         __u32     txe_cqid :GNILND_CQID_NBITS;
662                                         __u32     txe_idx :GNILND_MSGID_TX_NBITS;
663                                 };
664                         };
665                 };
666         };
667 } kgn_tx_ev_id_t;
668
669 typedef struct kgn_dgram {
670         struct list_head     gndg_list;          /* on hash dev::gnd_dgrams */
671         kgn_dgram_state_t    gndg_state;         /* state of this dgram */
672         kgn_dgram_type_t     gndg_type;          /* REQ, NAK, etc */
673         __u32                gndg_magic;         /* saftey word */
674         unsigned long        gndg_post_time;     /* time when we posted */
675         struct kgn_conn     *gndg_conn;          /* unbound conn with ep & smsg */
676         kgn_connreq_t        gndg_conn_out;      /* connreq from local node */
677         kgn_connreq_t        gndg_conn_in;       /* connreq from remote node */
678 } kgn_dgram_t;
679
680 typedef struct kgn_tx {                         /* message descriptor */
681         struct list_head          tx_list;      /* TX queues - peer, conn, rdma */
682         kgn_tx_list_state_t       tx_list_state;/* where in state machine is this TX ? */
683         struct list_head         *tx_list_p;    /* pointer to current list */
684         struct kgn_conn          *tx_conn;      /* owning conn */
685         struct lnet_msg               *tx_lntmsg[2]; /* ptl msgs to finalize on completion */
686         unsigned long             tx_qtime;     /* when tx started to wait for something (jiffies) */
687         unsigned long             tx_cred_wait; /* time spend waiting for smsg creds */
688         struct list_head          tx_map_list;  /* list entry on device map list */
689         unsigned int              tx_nob;       /* # bytes of payload */
690         int                       tx_buftype;   /* payload buffer type */
691         int                       tx_phys_npages; /* # physical pages */
692         gni_mem_handle_t          tx_map_key;   /* mapping key */
693         gni_mem_handle_t          tx_buffer_copy_map_key;  /* mapping key for page aligned copy */
694         gni_mem_segment_t        *tx_phys;      /* page descriptors */
695         kgn_msg_t                 tx_msg;       /* FMA message buffer */
696         kgn_tx_ev_id_t            tx_id;        /* who are you, who ? who ? */
697         __u8                      tx_state;     /* state of the descriptor */
698         int                       tx_retrans;   /* retrans count of RDMA */
699         int                       tx_rc;        /* if we need to stash the ret code until we see completion */
700         void                     *tx_buffer;    /* source/sink buffer */
701         void                     *tx_buffer_copy;   /* pointer to page aligned buffer */
702         unsigned int              tx_nob_rdma;  /* nob actually rdma */
703         unsigned int              tx_offset;    /* offset of data into copied buffer */
704         union {
705                 gni_post_descriptor_t     tx_rdma_desc; /* rdma descriptor */
706                 struct page              *tx_imm_pages[GNILND_MAX_IMMEDIATE/PAGE_SIZE];  /* page array to map kiov for immediate send */
707         };
708
709         /* we only use one or the other */
710         union {
711                 kgn_putack_msg_t  tx_putinfo;   /* data for differed rdma & re-try */
712                 kgn_get_msg_t     tx_getinfo;   /* data for rdma re-try*/
713         };
714 } kgn_tx_t;
715
716 typedef struct kgn_conn {
717         kgn_device_t       *gnc_device;         /* which device */
718         struct kgn_peer    *gnc_peer;           /* owning peer */
719         int                 gnc_magic;          /* magic value cleared before free */
720         struct list_head    gnc_list;           /* stash on peer's conn list - or pending purgatory lists as we clear them */
721         struct list_head    gnc_hashlist;       /* stash in connection hash table */
722         struct list_head    gnc_schedlist;      /* schedule (on gnd_?_conns) for attention */
723         struct list_head    gnc_fmaq;           /* txs queued for FMA */
724         struct list_head    gnc_mdd_list;       /* hold list for MDD on hard conn reset */
725         struct list_head    gnc_delaylist;      /* If on this list schedule anytime we get interrupted */
726         __u64               gnc_peerstamp;      /* peer's unique stamp */
727         __u64               gnc_peer_connstamp; /* peer's unique connection stamp */
728         __u64               gnc_my_connstamp;   /* my unique connection stamp */
729         unsigned long       gnc_first_rx;       /* when I first received an FMA message (jiffies) */
730         unsigned long       gnc_last_tx;        /* when I last sent an FMA message (jiffies) */
731         unsigned long       gnc_last_rx;        /* when I last sent an FMA message (jiffies) */
732         unsigned long       gnc_last_tx_cq;     /* when I last received an FMA CQ (jiffies) */
733         unsigned long       gnc_last_rx_cq;     /* when I last received an FMA CQ (jiffies) */
734         unsigned long       gnc_last_noop_want; /* time I wanted to send NOOP */
735         unsigned long       gnc_last_noop_sent; /* time I did gni_smsg_send on NOOP */
736         unsigned long       gnc_last_noop_cq;   /* time when NOOP completed */
737         unsigned long       gnc_last_sched_ask; /* time when conn added to ready_conns */
738         unsigned long       gnc_last_sched_do;  /* time when conn processed from ready_conns */
739         atomic_t            gnc_reaper_noop;    /* # reaper triggered NOOP */
740         atomic_t            gnc_sched_noop;     /* # sched triggered NOOP */
741         unsigned int        gnc_timeout;        /* infer peer death if no rx for this many seconds */
742         __u32               gnc_cqid;           /* my completion callback id (non-unique) */
743         atomic_t            gnc_tx_seq;         /* tx msg sequence number */
744         atomic_t            gnc_rx_seq;         /* rx msg sequence number */
745         struct mutex        gnc_smsg_mutex;     /* tx smsg sequence serialization */
746         struct mutex        gnc_rdma_mutex;     /* tx rdma sequence serialization */
747         __u64               gnc_tx_retrans;     /* # retrans on SMSG */
748         atomic_t            gnc_nlive_fma;      /* # live FMA */
749         atomic_t            gnc_nq_rdma;        /* # queued (on device) RDMA */
750         atomic_t            gnc_nlive_rdma;     /* # live RDMA */
751         short               gnc_close_sent;     /* I've sent CLOSE */
752         short               gnc_close_recvd;    /* I've received CLOSE */
753         short               gnc_in_purgatory;   /* in the sin bin */
754         int                 gnc_error;          /* errno when conn being closed due to error */
755         int                 gnc_peer_error;     /* errno peer sent us on CLOSE */
756         kgn_conn_state_t    gnc_state;          /* connection state */
757         int                 gnc_scheduled;      /* being attented to */
758         char                gnc_sched_caller[30]; /* what function last called schedule */
759         int                 gnc_sched_line;     /* what line # last called schedule */
760         atomic_t            gnc_refcount;       /* # users */
761         spinlock_t          gnc_list_lock;      /* serialise tx lists, max_rx_age */
762         gni_ep_handle_t     gnc_ephandle;       /* GNI endpoint */
763         kgn_fma_memblock_t *gnc_fma_blk;        /* pointer to fma block for our mailbox */
764         gni_smsg_attr_t     gnpr_smsg_attr;     /* my short msg. attributes */
765         spinlock_t          gnc_tx_lock;        /* protect tx alloc/free */
766         unsigned long       gnc_tx_bits[(GNILND_MAX_MSG_ID/8)/sizeof(unsigned long)]; /* bit table for tx id */
767         int                 gnc_next_tx;        /* next tx to use in tx_ref_table */
768         kgn_tx_t          **gnc_tx_ref_table;   /* table of TX descriptors for this conn */
769         int                 gnc_mbox_id;        /* id of mbox in fma_blk                 */
770         short               gnc_needs_detach;   /* flag set in detach_purgatory_all_locked so reaper will clear out purgatory */
771         short               gnc_needs_closing;  /* flag set in del_conns when called from kgnilnd_del_peer_or_conn */
772         atomic_t            gnc_tx_in_use;      /* # of tx's currently in use by another thread use kgnilnd_peer_conn_lock */
773         kgn_dgram_type_t    gnc_dgram_type;     /* save dgram type used to establish this conn */
774         void               *remote_mbox_addr;   /* save remote mbox address */
775 } kgn_conn_t;
776
777 typedef struct kgn_mdd_purgatory {
778         gni_mem_handle_t    gmp_map_key;        /* mapping key */
779         struct list_head    gmp_list;           /* entry point for purgatory list */
780 } kgn_mdd_purgatory_t;
781
782 typedef struct kgn_peer {
783         struct list_head    gnp_list;                   /* stash on global peer list */
784         struct list_head    gnp_connd_list;             /* schedule on kgn_connd_peers */
785         struct list_head    gnp_conns;                  /* all active connections and all conns in purgatory for the peer */
786         struct list_head    gnp_tx_queue;               /* msgs waiting for a conn */
787         kgn_net_t          *gnp_net;                    /* net instance for this peer */
788         lnet_nid_t          gnp_nid;                    /* who's on the other end(s) */
789         atomic_t            gnp_refcount;               /* # users */
790         __u32               gnp_host_id;                /* ph. host ID of the peer */
791         short               gnp_connecting;             /* connection forming */
792         short               gnp_pending_unlink;         /* need last conn close to trigger unlink */
793         int                 gnp_last_errno;             /* last error conn saw */
794         time64_t            gnp_last_alive;             /* last time I had valid comms */
795         int                 gnp_last_dgram_errno;       /* last error dgrams saw */
796         unsigned long       gnp_last_dgram_time;        /* last time I tried to connect */
797         unsigned long       gnp_reconnect_time;         /* get_seconds() when reconnect OK */
798         unsigned long       gnp_reconnect_interval;     /* exponential backoff */
799         atomic_t            gnp_dirty_eps;              /* # of old but yet to be destroyed EPs from conns */
800         int                 gnp_state;                  /* up/down/timedout */
801         unsigned long       gnp_down_event_time;        /* time peer down */
802         unsigned long       gnp_up_event_time;          /* time peer back up */
803 } kgn_peer_t;
804
805 /* the kgn_rx_t is a struct for handing to LNET as the private pointer for things
806  * like lnet_parse. It allows a single pointer to let us get enough
807  * information in _recv and friends */
808 typedef struct kgn_rx {
809         kgn_conn_t              *grx_conn;      /* connection */
810         kgn_msg_t               *grx_msg;       /* message */
811         struct lnet_msg              *grx_lntmsg;    /* lnet msg for this rx (eager only) */
812         int                      grx_eager;     /* if eager, we copied msg to somewhere */
813         struct timespec64        grx_received;  /* time this msg received */
814 } kgn_rx_t;
815
816 typedef struct kgn_data {
817         int                     kgn_init;             /* initialisation state */
818         int                     kgn_shutdown;         /* shut down? */
819         int                     kgn_wc_kill;          /* Should I repost the WC */
820         atomic_t                kgn_nthreads;         /* # live threads */
821         int                     kgn_nresets;          /* number of stack resets */
822         int                     kgn_in_reset;         /* are we in stack reset ? */
823
824         __u64                   kgn_nid_trans_private;/* private data for each of the HW nid2nic arenas */
825
826         kgn_device_t            kgn_devices[GNILND_MAXDEVS]; /* device/ptag/cq etc */
827         int                     kgn_ndevs;            /* # devices */
828
829         int                     kgn_ruhroh_running;   /* ruhroh thread is running */
830         int                     kgn_ruhroh_shutdown;  /* ruhroh thread should or is shut down */
831         wait_queue_head_t       kgn_ruhroh_waitq;     /* ruhroh thread wakeup */
832         int                     kgn_quiesce_trigger;  /* should we quiesce ? */
833         atomic_t                kgn_nquiesce;         /* how many quiesced ? */
834         struct mutex            kgn_quiesce_mutex;    /* serialize ruhroh task, startup and shutdown */
835         int                     kgn_needs_reset;      /* we need stack reset */
836
837         /* These next three members implement communication from gnilnd into
838          * the ruhroh task.  To ensure correct operation of the task, code that
839          * writes into them must use memory barriers to ensure that the changes
840          * are visible to other cores in the order the members appear below.  */
841         __u32                   kgn_quiesce_secs;     /* seconds to bump timeouts */
842         int                     kgn_bump_info_rdy;    /* we have info needed to bump */
843         int                     kgn_needs_pause;      /* we need to pause for network quiesce */
844
845         struct list_head       *kgn_nets;             /* hashtable of kgn_net instances */
846         struct rw_semaphore     kgn_net_rw_sem;       /* serialise gnn_shutdown, kgn_nets */
847
848         rwlock_t                kgn_peer_conn_lock;   /* stabilize peer/conn ops */
849         struct list_head       *kgn_peers;            /* hash table of all my known peers */
850         atomic_t                kgn_npeers;           /* # peers extant */
851         int                     kgn_peer_version;     /* version flag for peer tables */
852
853         struct list_head       *kgn_conns;            /* conns hashed by cqid */
854         atomic_t                kgn_nconns;           /* # connections extant */
855         atomic_t                kgn_neager_allocs;    /* # of eager allocations */
856         __u64                   kgn_peerstamp;        /* when I started up */
857         __u64                   kgn_connstamp;        /* conn stamp generator */
858         int                     kgn_conn_version;     /* version flag for conn tables */
859         int                     kgn_next_cqid;        /* cqid generator */
860
861         long                    kgn_new_min_timeout;  /* minimum timeout on any new conn */
862         wait_queue_head_t       kgn_reaper_waitq;     /* reaper sleeps here */
863         spinlock_t              kgn_reaper_lock;      /* serialise */
864
865         struct kmem_cache      *kgn_rx_cache;         /* rx descriptor space */
866         struct kmem_cache      *kgn_tx_cache;         /* tx descriptor memory */
867         struct kmem_cache      *kgn_tx_phys_cache;    /* tx phys descriptor memory */
868         atomic_t                kgn_ntx;              /* # tx in use */
869         struct kmem_cache      *kgn_dgram_cache;      /* outgoing datagrams */
870
871         struct page          ***kgn_cksum_map_pages;  /* page arrays for mapping pages on checksum */
872         __u64                   kgn_cksum_npages;     /* # pages alloc'd for checksumming */
873         atomic_t                kgn_nvmap_cksum;      /* # times we vmapped for checksums */
874         atomic_t                kgn_nvmap_short;      /* # times we vmapped for short kiov */
875
876         atomic_t                kgn_nkmap_short;      /* # time we kmapped for a short kiov */
877         long                    kgn_rdmaq_override;   /* bytes per second override */
878
879         struct kmem_cache      *kgn_mbox_cache;       /* mailboxes from not-GART */
880
881         atomic_t                kgn_npending_unlink;  /* # of peers pending unlink */
882         atomic_t                kgn_npending_conns;   /* # of conns with pending closes */
883         atomic_t                kgn_npending_detach;  /* # of conns with a pending detach */
884         unsigned long           kgn_last_scheduled;   /* last time schedule was called */
885         unsigned long           kgn_last_condresched; /* last time cond_resched was called */
886         atomic_t                kgn_rev_offset;       /* # of REV rdma w/misaligned offsets */
887         atomic_t                kgn_rev_length;       /* # of REV rdma have misaligned len */
888         atomic_t                kgn_rev_copy_buff;    /* # of REV rdma buffer copies */
889         unsigned long           free_pages_limit;     /* # of free pages reserve from fma block allocations */
890         int                     kgn_enable_gl_mutex;  /* kgni api mtx enable */
891 } kgn_data_t;
892
893 extern kgn_data_t         kgnilnd_data;
894 extern kgn_tunables_t     kgnilnd_tunables;
895
896 extern void kgnilnd_destroy_peer(kgn_peer_t *peer);
897 extern void kgnilnd_destroy_conn(kgn_conn_t *conn);
898 extern int _kgnilnd_schedule_conn(kgn_conn_t *conn, const char *caller, int line, int refheld, int lock_held);
899 extern int _kgnilnd_schedule_delay_conn(kgn_conn_t *conn);
900
901 static inline int kgnilnd_timeout(void)
902 {
903         return *kgnilnd_tunables.kgn_timeout ?
904                *kgnilnd_tunables.kgn_timeout :
905                lnet_get_lnd_timeout();
906 }
907
908 /* Macro wrapper for _kgnilnd_schedule_conn. This will store the function
909  * and the line of the calling function to allow us to debug problematic
910  * schedule calls in the future without the programmer having to mark
911  * the location manually.
912  */
913 #define kgnilnd_schedule_conn(conn)                                     \
914         _kgnilnd_schedule_conn(conn, __func__, __LINE__, 0, 0);
915
916 #define kgnilnd_schedule_conn_refheld(conn, refheld)                    \
917         _kgnilnd_schedule_conn(conn, __func__, __LINE__, refheld, 0);
918
919 #define kgnilnd_schedule_conn_nolock(conn)                              \
920         _kgnilnd_schedule_conn(conn, __func__, __LINE__, 0, 1);
921
922
923 /* Macro wrapper for _kgnilnd_schedule_delay_conn. This will allow us to store
924  * extra data if we need to.
925  */
926 #define kgnilnd_schedule_delay_conn(conn) \
927         _kgnilnd_schedule_delay_conn(conn);
928
929 static inline void
930 kgnilnd_thread_fini(void)
931 {
932         atomic_dec(&kgnilnd_data.kgn_nthreads);
933 }
934
935 static inline void kgnilnd_gl_mutex_lock(struct mutex *lock)
936 {
937         if (kgnilnd_data.kgn_enable_gl_mutex)
938                 mutex_lock(lock);
939 }
940
941 static inline void kgnilnd_gl_mutex_unlock(struct mutex *lock)
942 {
943         if (kgnilnd_data.kgn_enable_gl_mutex)
944                 mutex_unlock(lock);
945 }
946
947 static inline void kgnilnd_conn_mutex_lock(struct mutex *lock)
948 {
949         if (!kgnilnd_data.kgn_enable_gl_mutex)
950                 mutex_lock(lock);
951 }
952
953 static inline void kgnilnd_conn_mutex_unlock(struct mutex *lock)
954 {
955         if (!kgnilnd_data.kgn_enable_gl_mutex)
956                 mutex_unlock(lock);
957 }
958
959 /* like mutex_trylock but with a jiffies spinner. This is to allow certain
960  * parts of the code to avoid a scheduler trip when the mutex is held
961  *
962  * Try to acquire the mutex atomically for 1 jiffie. Returns 1 if the mutex
963  * has been acquired successfully, and 0 on contention.
964  *
965  * NOTE: this function follows the spin_trylock() convention, so
966  * it is negated to the down_trylock() return values! Be careful
967  * about this when converting semaphore users to mutexes.
968  *
969  * This function must not be used in interrupt context. The
970  * mutex must be released by the same task that acquired it.
971  */
972 static inline int __kgnilnd_mutex_trylock(struct mutex *lock)
973 {
974         int             ret;
975         unsigned long   timeout;
976
977         LASSERT(!in_interrupt());
978
979         for (timeout = jiffies + 1; time_before(jiffies, timeout);) {
980
981                 ret = mutex_trylock(lock);
982                 if (ret)
983                         return ret;
984         }
985         return 0;
986 }
987
988 static inline int kgnilnd_mutex_trylock(struct mutex *lock)
989 {
990         if (!kgnilnd_data.kgn_enable_gl_mutex)
991                 return 1;
992
993         return __kgnilnd_mutex_trylock(lock);
994 }
995
996 static inline int kgnilnd_trylock(struct mutex *cq_lock,
997                                   struct mutex *c_lock)
998 {
999         if (kgnilnd_data.kgn_enable_gl_mutex)
1000                 return __kgnilnd_mutex_trylock(cq_lock);
1001         else
1002                 return __kgnilnd_mutex_trylock(c_lock);
1003 }
1004
1005 static inline void *kgnilnd_vzalloc(int size)
1006 {
1007         void *ret;
1008         if (*kgnilnd_tunables.kgn_vzalloc_noretry)
1009                 ret = __ll_vmalloc(size, __GFP_HIGHMEM | GFP_NOIO | __GFP_ZERO |
1010                                    __GFP_NORETRY);
1011         else
1012                 ret = __ll_vmalloc(size, __GFP_HIGHMEM | GFP_NOIO | __GFP_ZERO);
1013
1014         LIBCFS_ALLOC_POST(ret, size, "alloc");
1015         return ret;
1016 }
1017
1018 static inline void kgnilnd_vfree(void *ptr, int size)
1019 {
1020         LIBCFS_FREE_PRE(ptr, size, "vfree");
1021         vfree(ptr);
1022 }
1023
1024 /* as of kernel version 4.2, set_mb is replaced with smp_store_mb */
1025 #ifndef set_mb
1026 #define set_mb smp_store_mb
1027 #endif
1028
1029 /* Copied from DEBUG_REQ in Lustre - the dance is needed to save stack space */
1030
1031 extern void
1032 _kgnilnd_debug_msg(kgn_msg_t *msg,
1033                 struct libcfs_debug_msg_data *data, const char *fmt, ... );
1034
1035 #define kgnilnd_debug_msg(msgdata, mask, cdls, msg, fmt, a...)                \
1036 do {                                                                          \
1037         CFS_CHECK_STACK(msgdata, mask, cdls);                                 \
1038                                                                               \
1039         if (((mask) & D_CANTMASK) != 0 ||                                     \
1040             ((libcfs_debug & (mask)) != 0 &&                                  \
1041              (libcfs_subsystem_debug & DEBUG_SUBSYSTEM) != 0))                \
1042                 _kgnilnd_debug_msg((msg), msgdata, fmt, ##a);                 \
1043 } while(0)
1044
1045 /* for most callers (level is a constant) this is resolved at compile time */
1046 #define GNIDBG_MSG(level, msg, fmt, args...)                                  \
1047 do {                                                                          \
1048         if ((level) & (D_ERROR | D_WARNING | D_NETERROR)) {                   \
1049             static struct cfs_debug_limit_state cdls;                         \
1050             LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, level, &cdls);                \
1051             kgnilnd_debug_msg(&msgdata, level, &cdls, msg,                    \
1052                               "$$ "fmt" from %s ", ## args,                   \
1053                               libcfs_nid2str((msg)->gnm_srcnid));             \
1054         } else {                                                              \
1055             LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, level, NULL);                 \
1056             kgnilnd_debug_msg(&msgdata, level, NULL, msg,                     \
1057                               "$$ "fmt" from %s ", ## args,                   \
1058                               libcfs_nid2str((msg)->gnm_srcnid));             \
1059         }                                                                     \
1060 } while (0)
1061
1062 /* user puts 'to nid' in msg for us */
1063 #define GNIDBG_TOMSG(level, msg, fmt, args...)                                \
1064 do {                                                                          \
1065         if ((level) & (D_ERROR | D_WARNING | D_NETERROR)) {                   \
1066             static struct cfs_debug_limit_state cdls;                         \
1067             LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, level, &cdls);                \
1068             kgnilnd_debug_msg(&msgdata, level, &cdls, msg,                    \
1069                               "$$ "fmt" ", ## args);                          \
1070         } else {                                                              \
1071             LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, level, NULL);                 \
1072             kgnilnd_debug_msg(&msgdata, level, NULL, msg,                     \
1073                               "$$ "fmt" ", ## args);                          \
1074         }                                                                     \
1075 } while (0)
1076
1077 extern void
1078 _kgnilnd_debug_conn(kgn_conn_t *conn,
1079                 struct libcfs_debug_msg_data *data, const char *fmt, ... );
1080
1081 #define kgnilnd_debug_conn(msgdata, mask, cdls, conn, fmt, a...)               \
1082 do {                                                                           \
1083         CFS_CHECK_STACK(msgdata, mask, cdls);                                  \
1084                                                                                \
1085         if (((mask) & D_CANTMASK) != 0 ||                                      \
1086             ((libcfs_debug & (mask)) != 0 &&                                   \
1087              (libcfs_subsystem_debug & DEBUG_SUBSYSTEM) != 0))                 \
1088                 _kgnilnd_debug_conn((conn), msgdata, fmt, ##a);                \
1089 } while(0)
1090
1091 /* for most callers (level is a constant) this is resolved at compile time */
1092 #define GNIDBG_CONN(level, conn, fmt, args...)                                  \
1093 do {                                                                            \
1094         if ((level) & (D_ERROR | D_WARNING | D_NETERROR)) {                     \
1095             static struct cfs_debug_limit_state cdls;                           \
1096             LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, level, &cdls);                  \
1097             kgnilnd_debug_conn(&msgdata, level, &cdls, conn,                    \
1098                                "$$ "fmt" ", ## args);                           \
1099         } else {                                                                \
1100             LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, level, NULL);                   \
1101             kgnilnd_debug_conn(&msgdata, level, NULL, conn,                     \
1102                                "$$ "fmt" ", ## args);                           \
1103         }                                                                       \
1104 } while (0)
1105
1106 extern void
1107 _kgnilnd_debug_tx(kgn_tx_t *tx,
1108                 struct libcfs_debug_msg_data *data, const char *fmt, ... );
1109
1110 #define kgnilnd_debug_tx(msgdata, mask, cdls, tx, fmt, a...)                   \
1111 do {                                                                           \
1112         CFS_CHECK_STACK(msgdata, mask, cdls);                                  \
1113                                                                                \
1114         if (((mask) & D_CANTMASK) != 0 ||                                      \
1115             ((libcfs_debug & (mask)) != 0 &&                                   \
1116              (libcfs_subsystem_debug & DEBUG_SUBSYSTEM) != 0))                 \
1117                 _kgnilnd_debug_tx((tx), msgdata, fmt, ##a);                    \
1118 } while(0)
1119
1120 /* for most callers (level is a constant) this is resolved at compile time */
1121 #define GNIDBG_TX(level, tx, fmt, args...)                                      \
1122 do {                                                                            \
1123         if ((level) & (D_ERROR | D_WARNING | D_NETERROR)) {                     \
1124             static struct cfs_debug_limit_state cdls;                           \
1125             LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, level, &cdls);                  \
1126             kgnilnd_debug_tx(&msgdata, level, &cdls, tx,                        \
1127                               "$$ "fmt" ", ## args);                            \
1128         } else {                                                                \
1129             LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, level, NULL);                   \
1130             kgnilnd_debug_tx(&msgdata, level, NULL, tx,                         \
1131                               "$$ "fmt" ", ## args);                            \
1132         }                                                                       \
1133 } while (0)
1134
1135 #define GNITX_ASSERTF(tx, cond, fmt, a...)                                      \
1136 ({                                                                              \
1137         if (unlikely(!(cond))) {                                                \
1138                 GNIDBG_TX(D_EMERG, tx, "ASSERTION(" #cond ") failed:" fmt, a);  \
1139                 LBUG();                                                         \
1140         }                                                                       \
1141 })
1142
1143 #define GNILND_IS_QUIESCED                                                      \
1144         (atomic_read(&kgnilnd_data.kgn_nquiesce) ==                             \
1145                 atomic_read(&kgnilnd_data.kgn_nthreads))
1146
1147 #define KGNILND_SPIN_QUIESCE                                            \
1148 do {                                                                    \
1149         /* E.T phone home */                                            \
1150         atomic_inc(&kgnilnd_data.kgn_nquiesce);                         \
1151         CDEBUG(D_NET, "Waiting for thread pause to be over...\n");      \
1152         while (kgnilnd_data.kgn_quiesce_trigger) {                      \
1153                 msleep_interruptible(MSEC_PER_SEC);                     \
1154         }                                                               \
1155         /* Mom, my homework is done */                                  \
1156         CDEBUG(D_NET, "Waking up from thread pause\n");                 \
1157         atomic_dec(&kgnilnd_data.kgn_nquiesce);                         \
1158 } while(0)
1159
1160 /* use macros for addref/decref to get the calling function name in the CDEBUG */
1161 #ifndef LIBCFS_DEBUG
1162 #error "this code uses actions inside LASSERT for ref counting"
1163 #endif
1164
1165 #define kgnilnd_admin_addref(atomic)                                    \
1166 do {                                                                    \
1167         int val = atomic_inc_return(&atomic);                           \
1168         LASSERTF(val > 0,  #atomic " refcount %d\n", val);              \
1169         CDEBUG(D_NETTRACE, #atomic " refcount %d\n", val);              \
1170 } while (0)
1171
1172 #define kgnilnd_admin_decref(atomic)                                    \
1173 do {                                                                    \
1174         int val = atomic_dec_return(&atomic);                           \
1175         LASSERTF(val >= 0,  #atomic " refcount %d\n", val);             \
1176         CDEBUG(D_NETTRACE, #atomic " refcount %d\n", val);              \
1177         if (!val)                                                       \
1178                 wake_up_var(&kgnilnd_data);                             \
1179 }while (0)
1180
1181 #define kgnilnd_net_addref(net)                                         \
1182 do {                                                                    \
1183         int     val = atomic_inc_return(&net->gnn_refcount);            \
1184         LASSERTF(val > 1, "net %p refcount %d\n", net, val);            \
1185         CDEBUG(D_NETTRACE, "net %p->%s++ (%d)\n", net,                  \
1186                 libcfs_nidstr(&net->gnn_ni->ni_nid), val);              \
1187 } while (0)
1188
1189 #define kgnilnd_net_decref(net)                                         \
1190 do {                                                                    \
1191         int     val = atomic_dec_return(&net->gnn_refcount);            \
1192         LASSERTF(val >= 0, "net %p refcount %d\n", net, val);           \
1193         CDEBUG(D_NETTRACE, "net %p->%s-- (%d)\n", net,                  \
1194                libcfs_nidstr(&net->gnn_ni->ni_nid), val);               \
1195 } while (0)
1196
1197 #define kgnilnd_peer_addref(peer)                                               \
1198 do {                                                                            \
1199         int     val = atomic_inc_return(&peer->gnp_refcount);                   \
1200         LASSERTF(val > 1, "peer %p refcount %d\n", peer, val);                  \
1201         CDEBUG(D_NETTRACE, "peer %p->%s++ (%d)\n", peer,                        \
1202                libcfs_nid2str(peer->gnp_nid), val);                             \
1203 } while (0)
1204
1205 #define kgnilnd_peer_decref(peer)                                               \
1206 do {                                                                            \
1207         int     val = atomic_dec_return(&peer->gnp_refcount);                   \
1208         LASSERTF(val >= 0, "peer %p refcount %d\n", peer, val);                 \
1209         CDEBUG(D_NETTRACE, "peer %p->%s--(%d)\n", peer,                         \
1210                libcfs_nid2str(peer->gnp_nid), val);                             \
1211         if (val == 0)                                                           \
1212                 kgnilnd_destroy_peer(peer);                                     \
1213 } while(0)
1214
1215 #define kgnilnd_conn_addref(conn)                                       \
1216 do {                                                                    \
1217         int     val;                                                    \
1218                                                                         \
1219         smp_wmb();                                                      \
1220         val = atomic_inc_return(&conn->gnc_refcount);                   \
1221         LASSERTF(val > 1 && conn->gnc_magic == GNILND_CONN_MAGIC,       \
1222                 "conn %p refc %d to %s\n",                              \
1223                 conn, val,                                              \
1224                 conn->gnc_peer                                          \
1225                         ? libcfs_nid2str(conn->gnc_peer->gnp_nid)       \
1226                         : "<?>");                                       \
1227         CDEBUG(D_NETTRACE, "conn %p->%s++ (%d)\n", conn,                \
1228                 conn->gnc_peer                                          \
1229                         ? libcfs_nid2str(conn->gnc_peer->gnp_nid)       \
1230                         : "<?>",                                        \
1231                 val);                                                   \
1232 } while (0)
1233
1234 /* we hijack conn_decref && gnc_refcount = 1 to allow us to push the conn
1235  * through the scheduler thread to get the EP destroyed. This avoids some
1236  * messy semaphore business and allows us to reuse the connd_list and existing
1237  * linkage and avoid creating extra lists just for destroying EPs */
1238
1239 /* Safety Disclaimer:
1240  * Q: If we decrement the refcount and then check it again, is it possible that
1241  *    another caller could have passed through this macro concurrently? If so,
1242  *    then it is possible that both will attempt to call kgnilnd_destroy_conn().
1243  *
1244  * A: Yes, entirely possible in most cases, but we can't get concurrent users
1245  * once we are refcount <= 2. It hinges around gnc_state and membership of
1246  * gnc_hashlist. There are two ways to find a connection - either ask for
1247  * it from the peer, kgnilnd_find_conn_locked(peer) or from the CQ id,
1248  * kgnilnd_cqid2conn_locked(id). While a conn is live, we'll have at least
1249  * 4 refcounts
1250  *
1251  * - #1 from create (kgnilnd_create_conn)
1252  * - #2 for EP (kgnilnd_create_conn)
1253  * - #3 - living on peer (gnc_list, kgnilnd_finish_connect)
1254  * - #4 living in global hash (gnc_hashlist, kgnilnd_finish_connect).
1255  *
1256  * Actually, only 3 live, as at the end of kgnilnd_finish_connect, we drop:
1257  * - #1 - the ref the dgram inherited from kgnilnd_create_conn.
1258  *
1259  * There could be more from TX descriptors during the lifetime of a live
1260  * conn.
1261  *
1262  * If we nuke the conn before finish_connect, we won't have parallel paths
1263  * because nobody besides the dgram handler for the single outstanding
1264  * dgram can find the connection as it isn't in any searchable tables yet.
1265  *
1266  * This leaves connection close, we'll drop 2 refs (#4 and #3) but only
1267  * after calling kgnilnd_schedule_conn, which would add a new ref (#5). At
1268  * this point gnc_refcount=2 (#2, #5). We have a 'maybe' send of the CLOSE
1269  * now on the next scheduler loop, this could be #6 (schedule_conn again)
1270  * and #7 (TX on gnc_fmaq). Both would be cleared quickly as that TX is
1271  * sent. Now the gnc_state == CLOSED, so we hit
1272  * kgnilnd_complete_closed_conn. At this point, nobody can 'find' this conn
1273  * - we've nuked them from the peer and CQ id tables, so we own them and
1274  * are guaranteed serial access - hence the complete lack of conn list
1275  * locking in kgnilnd_complete_closed_conn. We are free then to mark the
1276  * conn DESTROY_EP (add #6 for schedule_conn), then lose #5 in
1277  * kgnilnd_process_conns. Then the next scheduler loop would call
1278  * kgnilnd_destroy_conn_ep (drop #2 for EP) and lose #6 (refcount=0) in
1279  * kgnilnd_process_conns.
1280  *
1281  * Clearly, we are totally safe. Clearly.
1282  */
1283
1284 #define kgnilnd_conn_decref(conn)                                       \
1285 do {                                                                    \
1286         int     val;                                                    \
1287                                                                         \
1288         smp_wmb();                                                      \
1289         val = atomic_dec_return(&conn->gnc_refcount);                   \
1290         LASSERTF(val >= 0, "conn %p refc %d to %s\n",                   \
1291                 conn, val,                                              \
1292                 conn->gnc_peer                                          \
1293                         ? libcfs_nid2str(conn->gnc_peer->gnp_nid)       \
1294                         : "<?>");                                       \
1295         CDEBUG(D_NETTRACE, "conn %p->%s-- (%d)\n", conn,                \
1296                 conn->gnc_peer                                          \
1297                         ? libcfs_nid2str(conn->gnc_peer->gnp_nid)       \
1298                         : "<?>",                                        \
1299                 val);                                                   \
1300         smp_rmb();                                                      \
1301         if ((val == 1) &&                                               \
1302             (conn->gnc_ephandle != NULL) &&                             \
1303             (conn->gnc_state != GNILND_CONN_DESTROY_EP)) {              \
1304                 set_mb(conn->gnc_state, GNILND_CONN_DESTROY_EP);        \
1305                 kgnilnd_schedule_conn(conn);                            \
1306         } else if (val == 0) {                                          \
1307                 kgnilnd_destroy_conn(conn);                             \
1308         }                                                               \
1309 } while (0)
1310
1311 static inline struct list_head *
1312 kgnilnd_nid2peerlist(lnet_nid_t nid)
1313 {
1314         unsigned int hash = ((unsigned int)LNET_NIDADDR(nid)) % *kgnilnd_tunables.kgn_peer_hash_size;
1315
1316         RETURN(&kgnilnd_data.kgn_peers[hash]);
1317 }
1318
1319 static inline struct list_head *
1320 kgnilnd_netnum2netlist(__u16 netnum)
1321 {
1322         unsigned int hash = ((unsigned int) netnum) % *kgnilnd_tunables.kgn_net_hash_size;
1323
1324         RETURN(&kgnilnd_data.kgn_nets[hash]);
1325 }
1326
1327 static inline int
1328 kgnilnd_peer_active(kgn_peer_t *peer)
1329 {
1330         /* Am I in the peer hash table? */
1331         return (!list_empty(&peer->gnp_list));
1332 }
1333
1334 /* need write_lock on kgn_peer_conn_lock */
1335 static inline int
1336 kgnilnd_can_unlink_peer_locked(kgn_peer_t *peer)
1337 {
1338         CDEBUG(D_NET, "peer 0x%p->%s conns? %d tx? %d\n",
1339                 peer, libcfs_nid2str(peer->gnp_nid),
1340                 !list_empty(&peer->gnp_conns),
1341                 !list_empty(&peer->gnp_tx_queue));
1342
1343         /* kgn_peer_conn_lock protects us from conflict with
1344          * kgnilnd_peer_notify and gnp_persistent */
1345         RETURN ((list_empty(&peer->gnp_conns)) &&
1346                 (list_empty(&peer->gnp_tx_queue)));
1347 }
1348
1349 /* returns positive if error was for a clean shutdown of conn */
1350 static inline int
1351 kgnilnd_conn_clean_errno(int errno)
1352 {
1353         /*  - ESHUTDOWN - LND is unloading
1354          *  - EUCLEAN - admin requested via "lctl del_peer"
1355          *  - ENETRESET - admin requested via "lctl disconnect" or rca event
1356          *  - ENOTRECOVERABLE - stack reset
1357          *  - EISCONN - cleared via "lctl push"
1358          *  not doing ESTALE - that isn't clean */
1359         RETURN ((errno == 0) ||
1360                 (errno == -ESHUTDOWN) ||
1361                 (errno == -EUCLEAN) ||
1362                 (errno == -ENETRESET) ||
1363                 (errno == -EISCONN) ||
1364                 (errno == -ENOTRECOVERABLE));
1365 }
1366
1367 /* returns positive if error results in purgatory hold */
1368 static inline int
1369 kgnilnd_check_purgatory_errno(int errno)
1370 {
1371         /* We don't want to save the purgatory lists these cases:
1372          *  - EUCLEAN - admin requested via "lctl del_peer"
1373          *  - ESHUTDOWN - LND is unloading
1374          */
1375         RETURN ((errno != -ESHUTDOWN) &&
1376                 (errno != -EUCLEAN));
1377
1378 }
1379
1380 /* returns positive if a purgatory hold is needed */
1381 static inline int
1382 kgnilnd_check_purgatory_conn(kgn_conn_t *conn)
1383 {
1384         int loopback = 0;
1385
1386         if (conn->gnc_peer) {
1387                 loopback = conn->gnc_peer->gnp_nid ==
1388                         lnet_nid_to_nid4(&conn->gnc_peer->gnp_net->gnn_ni->ni_nid);
1389         } else {
1390                 /* short circuit - a conn that didn't complete
1391                  * setup never needs a purgatory hold */
1392                 RETURN(0);
1393         }
1394         CDEBUG(D_NETTRACE, "conn 0x%p->%s loopback %d close_recvd %d\n",
1395                 conn, conn->gnc_peer ?
1396                                 libcfs_nid2str(conn->gnc_peer->gnp_nid) :
1397                                 "<?>",
1398                 loopback, conn->gnc_close_recvd);
1399
1400         /* we only use a purgatory hold if we've not received the CLOSE msg
1401          * from our peer - without that message, we can't know the state of
1402          * the other end of this connection and must put it into purgatory
1403          * to prevent reuse and corruption.
1404          * The theory is that a TX error can be communicated in all other cases
1405          */
1406         RETURN(likely(!loopback) && !conn->gnc_close_recvd &&
1407                 kgnilnd_check_purgatory_errno(conn->gnc_error));
1408 }
1409
1410 static inline const char *
1411 kgnilnd_tx_state2str(kgn_tx_list_state_t state);
1412
1413 static inline struct list_head *
1414 kgnilnd_tx_state2list(kgn_peer_t *peer, kgn_conn_t *conn,
1415                         kgn_tx_list_state_t to_state)
1416 {
1417         switch (to_state) {
1418         case GNILND_TX_PEERQ:
1419                 return &peer->gnp_tx_queue;
1420         case GNILND_TX_FMAQ:
1421                 return &conn->gnc_fmaq;
1422         case GNILND_TX_LIVE_FMAQ:
1423         case GNILND_TX_LIVE_RDMAQ:
1424         case GNILND_TX_DYING:
1425                 return NULL;
1426         case GNILND_TX_MAPQ:
1427                 return &conn->gnc_device->gnd_map_tx;
1428         case GNILND_TX_RDMAQ:
1429                 return &conn->gnc_device->gnd_rdmaq;
1430         default:
1431                 /* IDLE, FREED or ALLOCD is not valid "on list" state */
1432                 CERROR("invalid state requested: %s\n",
1433                         kgnilnd_tx_state2str(to_state));
1434                 LBUG();
1435                 break;
1436         }
1437 }
1438
1439 /* should hold tx, conn or peer lock when calling */
1440 static inline void
1441 kgnilnd_tx_add_state_locked(kgn_tx_t *tx, kgn_peer_t *peer,
1442                         kgn_conn_t *conn, kgn_tx_list_state_t state,
1443                         int add_tail)
1444 {
1445         struct list_head        *list = NULL;
1446
1447         /* make sure we have a sane TX state to start */
1448         GNITX_ASSERTF(tx, (tx->tx_list_p == NULL &&
1449                   tx->tx_list_state == GNILND_TX_ALLOCD) &&
1450                 list_empty(&tx->tx_list),
1451                 "bad state with tx_list %s",
1452                 list_empty(&tx->tx_list) ? "empty" : "not empty");
1453
1454         /* WTF - you are already on that state buttmunch */
1455         GNITX_ASSERTF(tx, state != tx->tx_list_state,
1456                       "already at %s", kgnilnd_tx_state2str(state));
1457
1458         /* get proper list from the state requested */
1459         list = kgnilnd_tx_state2list(peer, conn, state);
1460
1461         /* add refcount */
1462         switch (state) {
1463         case GNILND_TX_PEERQ:
1464                 kgnilnd_peer_addref(peer);
1465                 break;
1466         case GNILND_TX_ALLOCD:
1467                 /* no refs needed */
1468                 break;
1469         case GNILND_TX_FMAQ:
1470                 kgnilnd_conn_addref(conn);
1471                 break;
1472         case GNILND_TX_MAPQ:
1473                 atomic_inc(&conn->gnc_device->gnd_nq_map);
1474                 kgnilnd_conn_addref(conn);
1475                 break;
1476         case GNILND_TX_LIVE_FMAQ:
1477                 atomic_inc(&conn->gnc_nlive_fma);
1478                 kgnilnd_conn_addref(conn);
1479                 break;
1480         case GNILND_TX_LIVE_RDMAQ:
1481                 atomic_inc(&conn->gnc_nlive_rdma);
1482                 kgnilnd_conn_addref(conn);
1483                 break;
1484         case GNILND_TX_RDMAQ:
1485                 atomic_inc(&conn->gnc_nq_rdma);
1486                 kgnilnd_conn_addref(conn);
1487                 break;
1488         case GNILND_TX_DYING:
1489                 kgnilnd_conn_addref(conn);
1490                 break;
1491         default:
1492                 CERROR("invalid state requested: %s\n",
1493                         kgnilnd_tx_state2str(state));
1494                 LBUG();
1495                 break;;
1496         }
1497
1498         /* if this changes, change kgnilnd_alloc_tx */
1499         tx->tx_list_state = state;
1500
1501         /* some states don't have lists - we track them in the per conn
1502          * TX table instead. Waste not, want not! */
1503         if (list != NULL) {
1504                 tx->tx_list_p = list;
1505                 if (add_tail)
1506                         list_add_tail(&tx->tx_list, list);
1507                 else
1508                         list_add(&tx->tx_list, list);
1509         } else {
1510                 /* set dummy list_p to make book keeping happy and let debugging
1511                  * be a hair easier */
1512                 tx->tx_list_p = (void *)state;
1513         }
1514
1515         GNIDBG_TX(D_NET, tx, "onto %s->0x%p",
1516                   kgnilnd_tx_state2str(state), list);
1517 }
1518
1519 static inline void
1520 kgnilnd_tx_del_state_locked(kgn_tx_t *tx, kgn_peer_t *peer,
1521                         kgn_conn_t *conn, kgn_tx_list_state_t new_state)
1522 {
1523         /* These is only 1 "off-list" state */
1524         GNITX_ASSERTF(tx, new_state == GNILND_TX_ALLOCD,
1525                       "invalid new_state %s", kgnilnd_tx_state2str(new_state));
1526
1527         /* new_state == ALLOCD means we are deallocating this tx,
1528          * so make sure it was on a valid list to start with */
1529         GNITX_ASSERTF(tx, (tx->tx_list_p != NULL) &&
1530                       (((tx->tx_list_state == GNILND_TX_LIVE_FMAQ) ||
1531                         (tx->tx_list_state == GNILND_TX_LIVE_RDMAQ) ||
1532                         (tx->tx_list_state == GNILND_TX_DYING)) == list_empty(&tx->tx_list)),
1533                       "bad state", NULL);
1534
1535         GNIDBG_TX(D_NET, tx, "off %p", tx->tx_list_p);
1536
1537         /* drop refcount */
1538         switch (tx->tx_list_state) {
1539         case GNILND_TX_PEERQ:
1540                 kgnilnd_peer_decref(peer);
1541                 break;
1542         case GNILND_TX_FREED:
1543         case GNILND_TX_IDLE:
1544         case GNILND_TX_ALLOCD:
1545                 /* no refs needed */
1546                 break;
1547         case GNILND_TX_DYING:
1548                 kgnilnd_conn_decref(conn);
1549                 break;
1550         case GNILND_TX_FMAQ:
1551                 kgnilnd_conn_decref(conn);
1552                 break;
1553         case GNILND_TX_MAPQ:
1554                 atomic_dec(&conn->gnc_device->gnd_nq_map);
1555                 kgnilnd_conn_decref(conn);
1556                 break;
1557         case GNILND_TX_LIVE_FMAQ:
1558                 atomic_dec(&conn->gnc_nlive_fma);
1559                 kgnilnd_conn_decref(conn);
1560                 break;
1561         case GNILND_TX_LIVE_RDMAQ:
1562                 atomic_dec(&conn->gnc_nlive_rdma);
1563                 kgnilnd_conn_decref(conn);
1564                 break;
1565         case GNILND_TX_RDMAQ:
1566                 atomic_dec(&conn->gnc_nq_rdma);
1567                 kgnilnd_conn_decref(conn);
1568         /* don't need to assert on default, already did in set */
1569         }
1570
1571         /* for ALLOCD, this might already be true, but no harm doing it again */
1572         list_del_init(&tx->tx_list);
1573         tx->tx_list_p = NULL;
1574         tx->tx_list_state = new_state;
1575 }
1576
1577 static inline int
1578 kgnilnd_tx_mapped(kgn_tx_t *tx)
1579 {
1580         return tx->tx_buftype == GNILND_BUF_PHYS_MAPPED;
1581 }
1582
1583 static inline struct list_head *
1584 kgnilnd_cqid2connlist(__u32 cqid)
1585 {
1586         unsigned int hash = cqid % *kgnilnd_tunables.kgn_peer_hash_size;
1587
1588         return (&kgnilnd_data.kgn_conns [hash]);
1589 }
1590
1591 static inline kgn_conn_t *
1592 kgnilnd_cqid2conn_locked(__u32 cqid)
1593 {
1594         struct list_head *conns = kgnilnd_cqid2connlist(cqid);
1595         struct list_head *tmp;
1596         kgn_conn_t       *conn;
1597
1598         list_for_each(tmp, conns) {
1599                 conn = list_entry(tmp, kgn_conn_t, gnc_hashlist);
1600
1601                 if (conn->gnc_cqid == cqid)
1602                         return conn;
1603         }
1604
1605         return NULL;
1606 }
1607
1608 /* returns 1..GNILND_MAX_CQID on success, 0 on failure */
1609 static inline __u32
1610 kgnilnd_get_cqid_locked(void)
1611 {
1612         int     looped = 0;
1613         __u32   cqid;
1614
1615         do {
1616                 cqid = kgnilnd_data.kgn_next_cqid++;
1617                 if (kgnilnd_data.kgn_next_cqid >= GNILND_MAX_CQID) {
1618                         if (looped) {
1619                                 return 0;
1620                         }
1621                         kgnilnd_data.kgn_next_cqid = 1;
1622                         looped = 1;
1623                 }
1624         } while (kgnilnd_cqid2conn_locked(cqid) != NULL);
1625
1626         return cqid;
1627 }
1628
1629 static inline void
1630 kgnilnd_validate_tx_ev_id(kgn_tx_ev_id_t *ev_id, kgn_tx_t **txp, kgn_conn_t **connp)
1631 {
1632         kgn_tx_t        *tx = NULL;
1633         kgn_conn_t      *conn = NULL;
1634
1635         /* set to NULL so any early return is an error */
1636         *txp = NULL;
1637         *connp = NULL;
1638
1639         LASSERTF((ev_id->txe_idx > 0) &&
1640                  (ev_id->txe_idx < GNILND_MAX_MSG_ID),
1641                 "bogus txe_idx %d >= %d\n",
1642                 ev_id->txe_idx, GNILND_MAX_MSG_ID);
1643
1644         LASSERTF((ev_id->txe_cqid > 0) &&
1645                  (ev_id->txe_cqid < GNILND_MAX_CQID),
1646                 "bogus txe_cqid %d >= %d\n",
1647                 ev_id->txe_cqid, GNILND_MAX_CQID);
1648
1649         read_lock(&kgnilnd_data.kgn_peer_conn_lock);
1650         conn = kgnilnd_cqid2conn_locked(ev_id->txe_cqid);
1651
1652         if (conn == NULL) {
1653                 /* Conn was destroyed? */
1654                 read_unlock(&kgnilnd_data.kgn_peer_conn_lock);
1655                 CDEBUG(D_NET, "CQID %d lookup failed\n", ev_id->txe_cqid);
1656                 return;
1657         }
1658         /* just insurance */
1659         kgnilnd_conn_addref(conn);
1660         kgnilnd_admin_addref(conn->gnc_tx_in_use);
1661         read_unlock(&kgnilnd_data.kgn_peer_conn_lock);
1662
1663         /* we know this is safe - as the TX won't be reused until AFTER
1664          * the conn is unlinked from the cqid hash, so we can use the TX
1665          * (serializing to avoid any cache oddness) freely from the conn tx ref table */
1666
1667         spin_lock(&conn->gnc_tx_lock);
1668         tx = conn->gnc_tx_ref_table[ev_id->txe_idx];
1669         spin_unlock(&conn->gnc_tx_lock);
1670
1671         /* We could have a tx that was cleared out by other forces
1672          * lctl disconnect or del_peer. */
1673         if (tx == NULL) {
1674                 CNETERR("txe_idx %d is gone, ignoring event\n", ev_id->txe_idx);
1675                 kgnilnd_admin_decref(conn->gnc_tx_in_use);
1676                 kgnilnd_conn_decref(conn);
1677                 return;
1678         }
1679
1680         /* check tx->tx_msg magic to make sure kgni didn't eat it */
1681         GNITX_ASSERTF(tx, tx->tx_msg.gnm_magic == GNILND_MSG_MAGIC,
1682                       "came back from kgni with bad magic %x", tx->tx_msg.gnm_magic);
1683
1684         GNITX_ASSERTF(tx, tx->tx_id.txe_idx == ev_id->txe_idx,
1685                       "conn 0x%p->%s tx_ref_table hosed: wanted txe_idx %d "
1686                       "found tx %p txe_idx %d",
1687                       conn, libcfs_nid2str(conn->gnc_peer->gnp_nid),
1688                       ev_id->txe_idx, tx, tx->tx_id.txe_idx);
1689
1690         GNITX_ASSERTF(tx, tx->tx_conn != NULL, "tx with NULL connection", NULL);
1691
1692         GNITX_ASSERTF(tx, tx->tx_conn == conn, "tx conn does not equal conn", NULL);
1693
1694         *txp = tx;
1695         *connp = conn;
1696
1697         GNIDBG_TX(D_NET, tx, "validated to 0x%p", conn);
1698 }
1699
1700 /* set_normalized_timepsec isn't exported from the kernel, so
1701  * we need to do the same thing inline */
1702 static inline struct timespec
1703 kgnilnd_ts_sub(struct timespec lhs, struct timespec rhs)
1704 {
1705         time_t                  sec;
1706         long                    nsec;
1707         struct timespec         ts;
1708
1709         sec = lhs.tv_sec - rhs.tv_sec;
1710         nsec = lhs.tv_nsec - rhs.tv_nsec;
1711
1712         while (nsec >= NSEC_PER_SEC) {
1713                 nsec -= NSEC_PER_SEC;
1714                 ++sec;
1715         }
1716         while (nsec < 0) {
1717                 nsec += NSEC_PER_SEC;
1718                 --sec;
1719         }
1720         ts.tv_sec = sec;
1721         ts.tv_nsec = nsec;
1722         return ts;
1723 }
1724
1725 static inline int
1726 kgnilnd_count_list(struct list_head *q)
1727 {
1728         struct list_head *e;
1729         int               n = 0;
1730
1731         list_for_each(e, q) {
1732                 n++;
1733         }
1734
1735         return n;
1736 }
1737
1738 /* kgnilnd_find_net adds a reference to the net it finds
1739  * this is so the net will not be removed before the calling function
1740  * has time to use the data returned. This reference needs to be released
1741  * by the calling function once it has finished using the returned net
1742  */
1743
1744 static inline int
1745 kgnilnd_find_net(lnet_nid_t nid, kgn_net_t **netp)
1746 {
1747         kgn_net_t *net;
1748         int rc;
1749
1750         rc = down_read_trylock(&kgnilnd_data.kgn_net_rw_sem);
1751
1752         if (!rc) {
1753                 return -ESHUTDOWN;
1754         }
1755
1756         list_for_each_entry(net,
1757                             kgnilnd_netnum2netlist(LNET_NETNUM(LNET_NIDNET(nid))),
1758                             gnn_list) {
1759                 if (!net->gnn_shutdown &&
1760                     LNET_NID_NET(&net->gnn_ni->ni_nid) == LNET_NIDNET(nid)) {
1761                         kgnilnd_net_addref(net);
1762                         up_read(&kgnilnd_data.kgn_net_rw_sem);
1763                         *netp = net;
1764                         return 0;
1765                 }
1766         }
1767
1768         up_read(&kgnilnd_data.kgn_net_rw_sem);
1769
1770         return -ENONET;
1771 }
1772
1773 #ifdef CONFIG_DEBUG_SLAB
1774 #define KGNILND_POISON(ptr, c, s) do {} while(0)
1775 #else
1776 #define KGNILND_POISON(ptr, c, s) memset(ptr, c, s)
1777 #endif
1778
1779 int kgnilnd_dev_init(kgn_device_t *dev);
1780 void kgnilnd_dev_fini(kgn_device_t *dev);
1781 int kgnilnd_startup(struct lnet_ni *ni);
1782 void kgnilnd_shutdown(struct lnet_ni *ni);
1783 int kgnilnd_base_startup(void);
1784 void kgnilnd_base_shutdown(void);
1785
1786 int kgnilnd_allocate_phys_fmablk(kgn_device_t *device);
1787 int kgnilnd_map_phys_fmablk(kgn_device_t *device);
1788 void kgnilnd_unmap_fma_blocks(kgn_device_t *device);
1789 void kgnilnd_free_phys_fmablk(kgn_device_t *device);
1790
1791 int kgnilnd_ctl(struct lnet_ni *ni, unsigned int cmd, void *arg);
1792 int kgnilnd_send(struct lnet_ni *ni, void *private, struct lnet_msg *lntmsg);
1793 int kgnilnd_eager_recv(struct lnet_ni *ni, void *private,
1794                         struct lnet_msg *lntmsg, void **new_private);
1795 int kgnilnd_recv(struct lnet_ni *ni, void *private, struct lnet_msg *lntmsg,
1796                 int delayed, unsigned int niov,
1797                 struct bio_vec *kiov,
1798                 unsigned int offset, unsigned int mlen, unsigned int rlen);
1799
1800 __u16 kgnilnd_cksum_kiov(unsigned int nkiov, struct bio_vec *kiov,
1801                          unsigned int offset, unsigned int nob, int dump_blob);
1802
1803 /* purgatory functions */
1804 void kgnilnd_add_purgatory_locked(kgn_conn_t *conn, kgn_peer_t *peer);
1805 void kgnilnd_mark_for_detach_purgatory_all_locked(kgn_peer_t *peer);
1806 void kgnilnd_detach_purgatory_locked(kgn_conn_t *conn, struct list_head *conn_list);
1807 void kgnilnd_release_purgatory_list(struct list_head *conn_list);
1808
1809 void kgnilnd_update_reaper_timeout(long timeout);
1810 void kgnilnd_unmap_buffer(kgn_tx_t *tx, int error);
1811 kgn_tx_t *kgnilnd_new_tx_msg(int type, lnet_nid_t source);
1812 void kgnilnd_tx_done(kgn_tx_t *tx, int completion);
1813 void kgnilnd_txlist_done(struct list_head *txlist, int error);
1814 void kgnilnd_unlink_peer_locked(kgn_peer_t *peer);
1815 int _kgnilnd_schedule_conn(kgn_conn_t *conn, const char *caller, int line, int refheld, int lock_held);
1816 int kgnilnd_schedule_process_conn(kgn_conn_t *conn, int sched_intent);
1817
1818 void kgnilnd_schedule_dgram(kgn_device_t *dev);
1819 int kgnilnd_create_peer_safe(kgn_peer_t **peerp, lnet_nid_t nid, kgn_net_t *net, int node_state);
1820 void kgnilnd_add_peer_locked(lnet_nid_t nid, kgn_peer_t *new_stub_peer, kgn_peer_t **peerp);
1821 int kgnilnd_add_peer(kgn_net_t *net, lnet_nid_t nid, kgn_peer_t **peerp);
1822
1823 kgn_peer_t *kgnilnd_find_peer_locked(lnet_nid_t nid);
1824 int kgnilnd_del_conn_or_peer(kgn_net_t *net, lnet_nid_t nid, int command, int error);
1825 void kgnilnd_peer_increase_reconnect_locked(kgn_peer_t *peer);
1826 void kgnilnd_queue_reply(kgn_conn_t *conn, kgn_tx_t *tx);
1827 void kgnilnd_queue_tx(kgn_conn_t *conn, kgn_tx_t *tx);
1828 void kgnilnd_launch_tx(kgn_tx_t *tx, kgn_net_t *net,
1829                        struct lnet_processid *target);
1830 int kgnilnd_send_mapped_tx(kgn_tx_t *tx, int try_map_if_full);
1831 void kgnilnd_consume_rx(kgn_rx_t *rx);
1832
1833 void kgnilnd_schedule_device(kgn_device_t *dev);
1834 void kgnilnd_device_callback(__u32 devid, __u64 arg);
1835 void kgnilnd_schedule_device_timer(cfs_timer_cb_arg_t data);
1836 void kgnilnd_schedule_device_timer_rd(cfs_timer_cb_arg_t data);
1837
1838 int kgnilnd_reaper(void *arg);
1839 int kgnilnd_scheduler(void *arg);
1840 int kgnilnd_dgram_mover(void *arg);
1841 int kgnilnd_rca(void *arg);
1842 int kgnilnd_thread_start(int(*fn)(void *arg), void *arg, char *name, int id);
1843
1844 int kgnilnd_create_conn(kgn_conn_t **connp, kgn_device_t *dev);
1845 int kgnilnd_conn_isdup_locked(kgn_peer_t *peer, kgn_conn_t *newconn);
1846 kgn_conn_t *kgnilnd_find_conn_locked(kgn_peer_t *peer);
1847 int kgnilnd_get_conn(kgn_conn_t **connp, kgn_peer_t);
1848 kgn_conn_t *kgnilnd_find_or_create_conn_locked(kgn_peer_t *peer);
1849 void kgnilnd_peer_cancel_tx_queue(kgn_peer_t *peer);
1850 void kgnilnd_cancel_peer_connect_locked(kgn_peer_t *peer, struct list_head *zombies);
1851 int kgnilnd_close_stale_conns_locked(kgn_peer_t *peer, kgn_conn_t *newconn);
1852 void kgnilnd_peer_alive(kgn_peer_t *peer);
1853 void kgnilnd_peer_notify(kgn_peer_t *peer, int error, int alive);
1854 void kgnilnd_close_conn_locked(kgn_conn_t *conn, int error);
1855 void kgnilnd_close_conn(kgn_conn_t *conn, int error);
1856 void kgnilnd_complete_closed_conn(kgn_conn_t *conn);
1857 void kgnilnd_destroy_conn_ep(kgn_conn_t *conn);
1858
1859 int kgnilnd_close_peer_conns_locked(kgn_peer_t *peer, int why);
1860 int kgnilnd_report_node_state(lnet_nid_t nid, int down);
1861 void kgnilnd_wakeup_rca_thread(void);
1862 int kgnilnd_start_rca_thread(void);
1863 int kgnilnd_get_node_state(__u32 nid);
1864
1865 int kgnilnd_tunables_init(void);
1866 void kgnilnd_init_msg(kgn_msg_t *msg, int type, lnet_nid_t source);
1867
1868 void kgnilnd_bump_timeouts(__u32 nap_time, char *reason);
1869 void kgnilnd_pause_threads(void);
1870 int kgnilnd_hw_in_quiesce(void);
1871 int kgnilnd_check_hw_quiesce(void);
1872 void kgnilnd_quiesce_wait(char *reason);
1873 void kgnilnd_quiesce_end_callback(gni_nic_handle_t nic_handle, uint64_t msecs);
1874 int kgnilnd_ruhroh_thread(void *arg);
1875 void kgnilnd_reset_stack(void);
1876 void kgnilnd_critical_error(gni_err_handle_t err_handle);
1877
1878 void kgnilnd_insert_sysctl(void);
1879 void kgnilnd_remove_sysctl(void);
1880 void kgnilnd_proc_init(void);
1881 void kgnilnd_proc_fini(void);
1882
1883 /* gnilnd_conn.c */
1884 void kgnilnd_release_mbox(kgn_conn_t *conn, int purgatory_hold);
1885
1886 int kgnilnd_find_and_cancel_dgram(kgn_device_t *dev, lnet_nid_t dst_nid);
1887 void kgnilnd_cancel_dgram_locked(kgn_dgram_t *dgram);
1888 void kgnilnd_release_dgram(kgn_device_t *dev, kgn_dgram_t *dgram, int shutdown);
1889
1890 int kgnilnd_setup_wildcard_dgram(kgn_device_t *dev);
1891 int kgnilnd_cancel_net_dgrams(kgn_net_t *net);
1892 int kgnilnd_cancel_wc_dgrams(kgn_device_t *dev);
1893 int kgnilnd_cancel_dgrams(kgn_device_t *dev);
1894 void kgnilnd_wait_for_canceled_dgrams(kgn_device_t *dev);
1895
1896 int kgnilnd_dgram_waitq(void *arg);
1897
1898 int kgnilnd_set_conn_params(kgn_dgram_t *dgram);
1899
1900 /* struct2str functions - we don't use a default: case to cause the compile
1901  * to fail if there is a missing case. This allows us to hide these down here
1902  * out of the way but ensure we'll catch any updates to the enum/types
1903  * above */
1904
1905 #define DO_TYPE(x) case x: return #x;
1906 static inline const char *
1907 kgnilnd_fmablk_state2str(kgn_fmablk_state_t state)
1908 {
1909         /* Only want single char string for this */
1910         switch (state) {
1911         case GNILND_FMABLK_IDLE:
1912                 return "I";
1913         case GNILND_FMABLK_PHYS:
1914                 return "P";
1915         case GNILND_FMABLK_VIRT:
1916                 return "V";
1917         case GNILND_FMABLK_FREED:
1918                 return "F";
1919         }
1920         return "<unknown state>";
1921 }
1922
1923 static inline const char *
1924 kgnilnd_msgtype2str(int type)
1925 {
1926         switch (type) {
1927                 DO_TYPE(GNILND_MSG_NONE);
1928                 DO_TYPE(GNILND_MSG_NOOP);
1929                 DO_TYPE(GNILND_MSG_IMMEDIATE);
1930                 DO_TYPE(GNILND_MSG_PUT_REQ);
1931                 DO_TYPE(GNILND_MSG_PUT_NAK);
1932                 DO_TYPE(GNILND_MSG_PUT_ACK);
1933                 DO_TYPE(GNILND_MSG_PUT_DONE);
1934                 DO_TYPE(GNILND_MSG_GET_REQ);
1935                 DO_TYPE(GNILND_MSG_GET_NAK);
1936                 DO_TYPE(GNILND_MSG_GET_DONE);
1937                 DO_TYPE(GNILND_MSG_CLOSE);
1938                 DO_TYPE(GNILND_MSG_PUT_REQ_REV);
1939                 DO_TYPE(GNILND_MSG_PUT_DONE_REV);
1940                 DO_TYPE(GNILND_MSG_PUT_NAK_REV);
1941                 DO_TYPE(GNILND_MSG_GET_REQ_REV);
1942                 DO_TYPE(GNILND_MSG_GET_ACK_REV);
1943                 DO_TYPE(GNILND_MSG_GET_DONE_REV);
1944                 DO_TYPE(GNILND_MSG_GET_NAK_REV);
1945         }
1946         return "<unknown msg type>";
1947 }
1948
1949 static inline const char *
1950 kgnilnd_tx_state2str(kgn_tx_list_state_t state)
1951 {
1952         switch (state) {
1953                 DO_TYPE(GNILND_TX_IDLE);
1954                 DO_TYPE(GNILND_TX_ALLOCD);
1955                 DO_TYPE(GNILND_TX_PEERQ);
1956                 DO_TYPE(GNILND_TX_MAPQ);
1957                 DO_TYPE(GNILND_TX_FMAQ);
1958                 DO_TYPE(GNILND_TX_LIVE_FMAQ);
1959                 DO_TYPE(GNILND_TX_RDMAQ);
1960                 DO_TYPE(GNILND_TX_LIVE_RDMAQ);
1961                 DO_TYPE(GNILND_TX_DYING);
1962                 DO_TYPE(GNILND_TX_FREED);
1963         }
1964         return "<unknown state>";
1965 }
1966
1967 static inline const char *
1968 kgnilnd_conn_state2str(kgn_conn_t *conn)
1969 {
1970         kgn_conn_state_t state = conn->gnc_state;
1971         switch (state) {
1972                 DO_TYPE(GNILND_CONN_DUMMY);
1973                 DO_TYPE(GNILND_CONN_LISTEN);
1974                 DO_TYPE(GNILND_CONN_CONNECTING);
1975                 DO_TYPE(GNILND_CONN_ESTABLISHED);
1976                 DO_TYPE(GNILND_CONN_CLOSING);
1977                 DO_TYPE(GNILND_CONN_CLOSED);
1978                 DO_TYPE(GNILND_CONN_DONE);
1979                 DO_TYPE(GNILND_CONN_DESTROY_EP);
1980         }
1981         return "<?state?>";
1982 }
1983
1984 static inline const char *
1985 kgnilnd_connreq_type2str(kgn_connreq_t *connreq)
1986 {
1987         kgn_connreq_type_t type = connreq->gncr_type;
1988
1989         switch (type) {
1990                 DO_TYPE(GNILND_CONNREQ_REQ);
1991                 DO_TYPE(GNILND_CONNREQ_NAK);
1992                 DO_TYPE(GNILND_CONNREQ_CLOSE);
1993         }
1994         return "<?type?>";
1995 }
1996
1997 static inline const char *
1998 kgnilnd_dgram_state2str(kgn_dgram_t *dgram)
1999 {
2000         kgn_dgram_state_t state = dgram->gndg_state;
2001
2002         switch (state) {
2003                 DO_TYPE(GNILND_DGRAM_USED);
2004                 DO_TYPE(GNILND_DGRAM_POSTING);
2005                 DO_TYPE(GNILND_DGRAM_POSTED);
2006                 DO_TYPE(GNILND_DGRAM_PROCESSING);
2007                 DO_TYPE(GNILND_DGRAM_DONE);
2008                 DO_TYPE(GNILND_DGRAM_CANCELED);
2009         }
2010         return "<?state?>";
2011 }
2012
2013 static inline const char *
2014 kgnilnd_dgram_type2str(kgn_dgram_t *dgram)
2015 {
2016         kgn_dgram_type_t type = dgram->gndg_type;
2017
2018         switch (type) {
2019                 DO_TYPE(GNILND_DGRAM_REQ);
2020                 DO_TYPE(GNILND_DGRAM_WC_REQ);
2021                 DO_TYPE(GNILND_DGRAM_NAK);
2022                 DO_TYPE(GNILND_DGRAM_CLOSE);
2023         }
2024         return "<?type?>";
2025 }
2026
2027 static inline const char *
2028 kgnilnd_conn_dgram_type2str(kgn_dgram_type_t type)
2029 {
2030         switch (type) {
2031                 DO_TYPE(GNILND_DGRAM_REQ);
2032                 DO_TYPE(GNILND_DGRAM_WC_REQ);
2033                 DO_TYPE(GNILND_DGRAM_NAK);
2034                 DO_TYPE(GNILND_DGRAM_CLOSE);
2035         }
2036         return "<?type?>";
2037 }
2038
2039 #undef DO_TYPE
2040
2041 /* pulls in tunables per platform and adds in nid/nic conversion
2042  * if RCA wasn't available at build time */
2043 #include "gnilnd_hss_ops.h"
2044 /* API wrapper functions - include late to pick up all of the other defines */
2045 #include "gnilnd_api_wrap.h"
2046
2047 #if defined(CONFIG_CRAY_GEMINI)
2048  #include "gnilnd_gemini.h"
2049 #elif defined(CONFIG_CRAY_ARIES)
2050  #include "gnilnd_aries.h"
2051 #else
2052  #error "Undefined Network Hardware Type"
2053 #endif
2054
2055 extern uint32_t kgni_driver_version;
2056
2057 static inline void
2058 kgnilnd_check_kgni_version(void)
2059 {
2060         uint32_t *kdv;
2061
2062         kgnilnd_data.kgn_enable_gl_mutex = 1;
2063         kdv = symbol_get(kgni_driver_version);
2064         if (!kdv) {
2065                 LCONSOLE_INFO("Not using thread safe locking -"
2066                         " no symbol kgni_driver_version\n");
2067                 return;
2068         }
2069
2070         /* Thread-safe kgni implemented in minor ver 0x44/45, code rev 0xb9 */
2071         if (*kdv < GNI_VERSION_CHECK(0, GNILND_KGNI_TS_MINOR_VER, 0xb9)) {
2072                 symbol_put(kgni_driver_version);
2073                 LCONSOLE_INFO("Not using thread safe locking, gni version 0x%x,"
2074                         " need >= 0x%x\n", *kdv,
2075                         GNI_VERSION_CHECK(0, GNILND_KGNI_TS_MINOR_VER, 0xb9));
2076                 return;
2077         }
2078
2079         symbol_put(kgni_driver_version);
2080
2081         if (!*kgnilnd_tunables.kgn_thread_safe) {
2082                 return;
2083         }
2084
2085         /* Use thread-safe locking */
2086         kgnilnd_data.kgn_enable_gl_mutex = 0;
2087 }
2088
2089 #endif /* _GNILND_GNILND_H_ */