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