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