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