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