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