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