Whamcloud - gitweb
LU-6261 gnilnd: Thread-safe optimizations.
[fs/lustre-release.git] / lnet / klnds / gnilnd / gnilnd_cb.c
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: James Shimek <jshimek@cray.com>
8  *   Author: Nic Henke <nic@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
27 #include <asm/page.h>
28 #include <linux/nmi.h>
29 #include "gnilnd.h"
30
31 /* this is useful when needed to debug wire corruption. */
32 static void
33 kgnilnd_dump_blob(int level, char *prefix, void *buf, int len) {
34         __u64 *ptr;
35
36         ptr = (__u64 *) buf;
37
38         while (len > 0) {
39                 if (len >= 32) {
40                         CDEBUG(level,
41                                "%s 0x%p: 0x%16.16llx 0x%16.16llx 0x%16.16llx 0x%16.16llx\n",
42                                prefix, ptr, *(ptr), *(ptr + 1), *(ptr + 2), *(ptr + 3));
43                         ptr += 4;
44                         len -= 32;
45                 } else if (len >= 16) {
46                         CDEBUG(level,
47                                "%s 0x%p: 0x%16.16llx 0x%16.16llx\n",
48                                prefix, ptr, *(ptr), *(ptr + 1));
49                         ptr += 2;
50                         len -= 16;
51                 } else {
52                         CDEBUG(level, "%s 0x%p: 0x%16.16llx\n",
53                                prefix, ptr, *(ptr));
54                         ptr++;
55                         len -= 8;
56                 }
57         }
58 }
59
60 static void
61 kgnilnd_dump_msg(int mask, kgn_msg_t *msg)
62 {
63         CDEBUG(mask, "0x%8.8x 0x%4.4x 0x%4.4x 0x%16.16llx"
64                 " 0x%16.16llx 0x%8.8x 0x%4.4x 0x%4.4x 0x%8.8x\n",
65                 msg->gnm_magic, msg->gnm_version,
66                 msg->gnm_type, msg->gnm_srcnid,
67                 msg->gnm_connstamp, msg->gnm_seq,
68                 msg->gnm_cksum, msg->gnm_payload_cksum,
69                 msg->gnm_payload_len);
70 }
71
72 void
73 kgnilnd_schedule_device(kgn_device_t *dev)
74 {
75         short         already_live = 0;
76
77         /* we'll only want to wake if the scheduler thread
78          * has come around and set ready to zero */
79         already_live = cmpxchg(&dev->gnd_ready, GNILND_DEV_IDLE, GNILND_DEV_IRQ);
80
81         if (!already_live) {
82                 wake_up_all(&dev->gnd_waitq);
83         }
84         return;
85 }
86
87 void kgnilnd_schedule_device_timer(unsigned long arg)
88 {
89         kgn_device_t *dev = (kgn_device_t *) arg;
90
91         kgnilnd_schedule_device(dev);
92 }
93
94 void
95 kgnilnd_device_callback(__u32 devid, __u64 arg)
96 {
97         kgn_device_t *dev;
98         int           index = (int) arg;
99
100         if (index >= kgnilnd_data.kgn_ndevs) {
101                 /* use _EMERG instead of an LBUG to prevent LBUG'ing in
102                  * interrupt context. */
103                 LCONSOLE_EMERG("callback for unknown device %d->%d\n",
104                                 devid, index);
105                 return;
106         }
107
108         dev = &kgnilnd_data.kgn_devices[index];
109         /* just basic sanity */
110         if (dev->gnd_id == devid) {
111                 kgnilnd_schedule_device(dev);
112         } else {
113                 LCONSOLE_EMERG("callback for bad device %d devid %d\n",
114                                 dev->gnd_id, devid);
115         }
116 }
117
118 /* sched_intent values:
119  * < 0 : do not reschedule under any circumstances
120  * == 0: reschedule if someone marked him WANTS_SCHED
121  * > 0 : force a reschedule */
122 /* Return code 0 means it did not schedule the conn, 1
123  * means it successfully scheduled the conn.
124  */
125
126 int
127 kgnilnd_schedule_process_conn(kgn_conn_t *conn, int sched_intent)
128 {
129         int     conn_sched;
130
131         /* move back to IDLE but save previous state.
132          * if we see WANTS_SCHED, we'll call kgnilnd_schedule_conn and
133          * let the xchg there handle any racing callers to get it
134          * onto gnd_ready_conns */
135
136         conn_sched = xchg(&conn->gnc_scheduled, GNILND_CONN_IDLE);
137         LASSERTF(conn_sched == GNILND_CONN_WANTS_SCHED ||
138                  conn_sched == GNILND_CONN_PROCESS,
139                  "conn %p after process in bad state: %d\n",
140                  conn, conn_sched);
141
142         if (sched_intent >= 0) {
143                 if ((sched_intent > 0 || (conn_sched == GNILND_CONN_WANTS_SCHED))) {
144                         return kgnilnd_schedule_conn_refheld(conn, 1);
145                 }
146         }
147         return 0;
148 }
149
150 /* Return of 0 for conn not scheduled, 1 returned if conn was scheduled or marked
151  * as scheduled */
152
153 int
154 _kgnilnd_schedule_conn(kgn_conn_t *conn, const char *caller, int line, int refheld)
155 {
156         kgn_device_t        *dev = conn->gnc_device;
157         int                  sched;
158         int                  rc;
159
160         sched = xchg(&conn->gnc_scheduled, GNILND_CONN_WANTS_SCHED);
161         /* we only care about the last person who marked want_sched since they
162          * are most likely the culprit
163          */
164         memcpy(conn->gnc_sched_caller, caller, sizeof(conn->gnc_sched_caller));
165         conn->gnc_sched_line = line;
166         /* if we are IDLE, add to list - only one guy sees IDLE and "wins"
167          * the chance to put it onto gnd_ready_conns.
168          * otherwise, leave marked as WANTS_SCHED and the thread that "owns"
169          *  the conn in process_conns will take care of moving it back to
170          *  SCHED when it is done processing */
171
172         if (sched == GNILND_CONN_IDLE) {
173                 /* if the conn is already scheduled, we've already requested
174                  * the scheduler thread wakeup */
175                 if (!refheld) {
176                         /* Add a reference to the conn if we are not holding a reference
177                          * already from the exisiting scheduler. We now use the same
178                          * reference if we need to reschedule a conn while in a scheduler
179                          * thread.
180                          */
181                         kgnilnd_conn_addref(conn);
182                 }
183                 LASSERTF(list_empty(&conn->gnc_schedlist), "conn %p already sched state %d\n",
184                          conn, sched);
185
186                 CDEBUG(D_INFO, "scheduling conn 0x%p caller %s:%d\n", conn, caller, line);
187
188                 spin_lock(&dev->gnd_lock);
189                 list_add_tail(&conn->gnc_schedlist, &dev->gnd_ready_conns);
190                 spin_unlock(&dev->gnd_lock);
191                 set_mb(conn->gnc_last_sched_ask, jiffies);
192                 rc = 1;
193         } else {
194                 CDEBUG(D_INFO, "not scheduling conn 0x%p: %d caller %s:%d\n", conn, sched, caller, line);
195                 rc = 0;
196         }
197
198         /* make sure thread(s) going to process conns - but let it make
199          * separate decision from conn schedule */
200         kgnilnd_schedule_device(dev);
201         return rc;
202 }
203
204 void
205 kgnilnd_schedule_dgram(kgn_device_t *dev)
206 {
207         int                  wake;
208
209         wake = xchg(&dev->gnd_dgram_ready, GNILND_DGRAM_SCHED);
210         if (wake != GNILND_DGRAM_SCHED)  {
211                 wake_up(&dev->gnd_dgram_waitq);
212         } else {
213                 CDEBUG(D_NETTRACE, "not waking: %d\n", wake);
214         }
215 }
216
217 void
218 kgnilnd_free_tx(kgn_tx_t *tx)
219 {
220         /* taken from kgnilnd_tx_add_state_locked */
221
222         LASSERTF((tx->tx_list_p == NULL &&
223                   tx->tx_list_state == GNILND_TX_ALLOCD) &&
224                 list_empty(&tx->tx_list),
225                 "tx %p with bad state %s (list_p %p) tx_list %s\n",
226                 tx, kgnilnd_tx_state2str(tx->tx_list_state), tx->tx_list_p,
227                 list_empty(&tx->tx_list) ? "empty" : "not empty");
228
229         atomic_dec(&kgnilnd_data.kgn_ntx);
230
231         /* we only allocate this if we need to */
232         if (tx->tx_phys != NULL) {
233                 kmem_cache_free(kgnilnd_data.kgn_tx_phys_cache, tx->tx_phys);
234                 CDEBUG(D_MALLOC, "slab-freed 'tx_phys': %lu at %p.\n",
235                        LNET_MAX_IOV * sizeof(gni_mem_segment_t), tx->tx_phys);
236         }
237
238         /* Only free the buffer if we used it */
239         if (tx->tx_buffer_copy != NULL) {
240                 vfree(tx->tx_buffer_copy);
241                 tx->tx_buffer_copy = NULL;
242                 CDEBUG(D_MALLOC, "vfreed buffer2\n");
243         }
244 #if 0
245         KGNILND_POISON(tx, 0x5a, sizeof(kgn_tx_t));
246 #endif
247         CDEBUG(D_MALLOC, "slab-freed 'tx': %lu at %p.\n", sizeof(*tx), tx);
248         kmem_cache_free(kgnilnd_data.kgn_tx_cache, tx);
249 }
250
251 kgn_tx_t *
252 kgnilnd_alloc_tx (void)
253 {
254         kgn_tx_t        *tx = NULL;
255
256         if (CFS_FAIL_CHECK(CFS_FAIL_GNI_ALLOC_TX))
257                 return tx;
258
259         tx = kmem_cache_alloc(kgnilnd_data.kgn_tx_cache, GFP_ATOMIC);
260         if (tx == NULL) {
261                 CERROR("failed to allocate tx\n");
262                 return NULL;
263         }
264         CDEBUG(D_MALLOC, "slab-alloced 'tx': %lu at %p.\n",
265                sizeof(*tx), tx);
266
267         /* need this memset, cache alloc'd memory is not cleared */
268         memset(tx, 0, sizeof(*tx));
269
270         /* setup everything here to minimize time under the lock */
271         tx->tx_buftype = GNILND_BUF_NONE;
272         tx->tx_msg.gnm_type = GNILND_MSG_NONE;
273         INIT_LIST_HEAD(&tx->tx_list);
274         INIT_LIST_HEAD(&tx->tx_map_list);
275         tx->tx_list_state = GNILND_TX_ALLOCD;
276
277         atomic_inc(&kgnilnd_data.kgn_ntx);
278
279         return tx;
280 }
281
282 /* csum_fold needs to be run on the return value before shipping over the wire */
283 #define _kgnilnd_cksum(seed, ptr, nob)  csum_partial(ptr, nob, seed)
284
285 /* we don't use offset as every one is passing a buffer reference that already
286  * includes the offset into the base address -
287  *  see kgnilnd_setup_virt_buffer and kgnilnd_setup_immediate_buffer */
288 static inline __u16
289 kgnilnd_cksum(void *ptr, size_t nob)
290 {
291         __u16   sum;
292
293         sum = csum_fold(_kgnilnd_cksum(0, ptr, nob));
294
295         /* don't use magic 'no checksum' value */
296         if (sum == 0)
297                 sum = 1;
298
299         CDEBUG(D_INFO, "cksum 0x%x for ptr 0x%p sz %zu\n",
300                sum, ptr, nob);
301
302         return sum;
303 }
304
305 inline __u16
306 kgnilnd_cksum_kiov(unsigned int nkiov, lnet_kiov_t *kiov,
307                     unsigned int offset, unsigned int nob, int dump_blob)
308 {
309         __wsum             cksum = 0;
310         __wsum             tmpck;
311         __u16              retsum;
312         void              *addr;
313         unsigned int       fraglen;
314         int                i, odd;
315
316         LASSERT(nkiov > 0);
317         LASSERT(nob > 0);
318
319         CDEBUG(D_BUFFS, "calc cksum for kiov 0x%p nkiov %u offset %u nob %u, dump %d\n",
320                kiov, nkiov, offset, nob, dump_blob);
321
322         /* if loops changes, please change kgnilnd_setup_phys_buffer */
323
324         while (offset >= kiov->kiov_len) {
325                 offset -= kiov->kiov_len;
326                 nkiov--;
327                 kiov++;
328                 LASSERT(nkiov > 0);
329         }
330
331         /* ignore nob here, if nob < (kiov_len - offset), kiov == 1 */
332         odd = (unsigned long) (kiov[0].kiov_len - offset) & 1;
333
334         if ((odd || *kgnilnd_tunables.kgn_vmap_cksum) && nkiov > 1) {
335                 struct page **pages = kgnilnd_data.kgn_cksum_map_pages[get_cpu()];
336
337                 LASSERTF(pages != NULL, "NULL pages for cpu %d map_pages 0x%p\n",
338                          get_cpu(), kgnilnd_data.kgn_cksum_map_pages);
339
340                 CDEBUG(D_BUFFS, "odd %d len %u offset %u nob %u\n",
341                        odd, kiov[0].kiov_len, offset, nob);
342
343                 for (i = 0; i < nkiov; i++) {
344                         pages[i] = kiov[i].kiov_page;
345                 }
346
347                 addr = vmap(pages, nkiov, VM_MAP, PAGE_KERNEL);
348                 if (addr == NULL) {
349                         CNETERR("Couldn't vmap %d frags on %d bytes to avoid odd length fragment in cksum\n",
350                                 nkiov, nob);
351                         /* return zero to avoid killing tx - we'll just get warning on console
352                          * when remote end sees zero checksum */
353                         RETURN(0);
354                 }
355                 atomic_inc(&kgnilnd_data.kgn_nvmap_cksum);
356
357                 tmpck = _kgnilnd_cksum(0, (void *) addr + kiov[0].kiov_offset + offset, nob);
358                 cksum = tmpck;
359
360                 if (dump_blob) {
361                         kgnilnd_dump_blob(D_BUFFS, "flat kiov RDMA payload",
362                                           (void *)addr + kiov[0].kiov_offset + offset, nob);
363                 }
364                 CDEBUG(D_BUFFS, "cksum 0x%x (+0x%x) for addr 0x%p+%u len %u offset %u\n",
365                        cksum, tmpck, addr, kiov[0].kiov_offset, nob, offset);
366                 vunmap(addr);
367         } else {
368                 do {
369                         fraglen = min(kiov->kiov_len - offset, nob);
370
371                         /* make dang sure we don't send a bogus checksum if somehow we get
372                          * an odd length fragment on anything but the last entry in a kiov  -
373                          * we know from kgnilnd_setup_rdma_buffer that we can't have non
374                          * PAGE_SIZE pages in the middle, so if nob < PAGE_SIZE, it is the last one */
375                         LASSERTF(!(fraglen&1) || (nob < PAGE_SIZE),
376                                  "odd fraglen %u on nkiov %d, nob %u kiov_len %u offset %u kiov 0x%p\n",
377                                  fraglen, nkiov, nob, kiov->kiov_len, offset, kiov);
378
379                         addr = (void *)kmap(kiov->kiov_page) + kiov->kiov_offset + offset;
380                         tmpck = _kgnilnd_cksum(cksum, addr, fraglen);
381
382                         CDEBUG(D_BUFFS,
383                                "cksum 0x%x (+0x%x) for page 0x%p+%u (0x%p) len %u offset %u\n",
384                                cksum, tmpck, kiov->kiov_page, kiov->kiov_offset, addr,
385                                fraglen, offset);
386
387                         cksum = tmpck;
388
389                         if (dump_blob)
390                                 kgnilnd_dump_blob(D_BUFFS, "kiov cksum", addr, fraglen);
391
392                         kunmap(kiov->kiov_page);
393
394                         kiov++;
395                         nkiov--;
396                         nob -= fraglen;
397                         offset = 0;
398
399                         /* iov must not run out before end of data */
400                         LASSERTF(nob == 0 || nkiov > 0, "nob %u nkiov %u\n", nob, nkiov);
401
402                 } while (nob > 0);
403         }
404
405         retsum = csum_fold(cksum);
406
407         /* don't use magic 'no checksum' value */
408         if (retsum == 0)
409                 retsum = 1;
410
411         CDEBUG(D_BUFFS, "retsum 0x%x from cksum 0x%x\n", retsum, cksum);
412
413         return retsum;
414 }
415
416 void
417 kgnilnd_init_msg(kgn_msg_t *msg, int type, lnet_nid_t source)
418 {
419         msg->gnm_magic = GNILND_MSG_MAGIC;
420         msg->gnm_version = GNILND_MSG_VERSION;
421         msg->gnm_type = type;
422         msg->gnm_payload_len = 0;
423         msg->gnm_srcnid = source;
424         /* gnm_connstamp gets set when FMA is sent */
425         /* gnm_srcnid is set on creation via function argument
426          * The right interface/net and nid is passed in when the message
427          * is created.
428          */
429 }
430
431 kgn_tx_t *
432 kgnilnd_new_tx_msg(int type, lnet_nid_t source)
433 {
434         kgn_tx_t *tx = kgnilnd_alloc_tx();
435
436         if (tx != NULL) {
437                 kgnilnd_init_msg(&tx->tx_msg, type, source);
438         } else {
439                 CERROR("couldn't allocate new tx type %s!\n",
440                        kgnilnd_msgtype2str(type));
441         }
442
443         return tx;
444 }
445
446 static void
447 kgnilnd_nak_rdma(kgn_conn_t *conn, int rx_type, int error, __u64 cookie, lnet_nid_t source) {
448         kgn_tx_t        *tx;
449
450         int             nak_type;
451
452         switch (rx_type) {
453         case GNILND_MSG_GET_REQ:
454         case GNILND_MSG_GET_DONE:
455                 nak_type = GNILND_MSG_GET_NAK;
456                 break;
457         case GNILND_MSG_PUT_REQ:
458         case GNILND_MSG_PUT_ACK:
459         case GNILND_MSG_PUT_DONE:
460                 nak_type = GNILND_MSG_PUT_NAK;
461                 break;
462         case GNILND_MSG_PUT_REQ_REV:
463         case GNILND_MSG_PUT_DONE_REV:
464                 nak_type = GNILND_MSG_PUT_NAK_REV;
465                 break;
466         case GNILND_MSG_GET_REQ_REV:
467         case GNILND_MSG_GET_ACK_REV:
468         case GNILND_MSG_GET_DONE_REV:
469                 nak_type = GNILND_MSG_GET_NAK_REV;
470                 break;
471         default:
472                 CERROR("invalid msg type %s (%d)\n",
473                         kgnilnd_msgtype2str(rx_type), rx_type);
474                 LBUG();
475         }
476         /* only allow NAK on error and truncate to zero */
477         LASSERTF(error <= 0, "error %d conn 0x%p, cookie "LPU64"\n",
478                  error, conn, cookie);
479
480         tx = kgnilnd_new_tx_msg(nak_type, source);
481         if (tx == NULL) {
482                 CNETERR("can't get TX to NAK RDMA to %s\n",
483                         libcfs_nid2str(conn->gnc_peer->gnp_nid));
484                 return;
485         }
486
487         tx->tx_msg.gnm_u.completion.gncm_retval = error;
488         tx->tx_msg.gnm_u.completion.gncm_cookie = cookie;
489         kgnilnd_queue_tx(conn, tx);
490 }
491
492 int
493 kgnilnd_setup_immediate_buffer(kgn_tx_t *tx, unsigned int niov, struct iovec *iov,
494                                lnet_kiov_t *kiov, unsigned int offset, unsigned int nob)
495
496 {
497         kgn_msg_t       *msg = &tx->tx_msg;
498         int              i;
499
500         /* To help save on MDDs for short messages, we'll vmap a kiov to allow
501          * gni_smsg_send to send that as the payload */
502
503         LASSERT(tx->tx_buftype == GNILND_BUF_NONE);
504
505         if (nob == 0) {
506                 tx->tx_buffer = NULL;
507         } else if (kiov != NULL) {
508                 LASSERTF(niov > 0 && niov < GNILND_MAX_IMMEDIATE/PAGE_SIZE,
509                          "bad niov %d\n", niov);
510
511                 while (offset >= kiov->kiov_len) {
512                         offset -= kiov->kiov_len;
513                         niov--;
514                         kiov++;
515                         LASSERT(niov > 0);
516                 }
517                 for (i = 0; i < niov; i++) {
518                         /* We can't have a kiov_offset on anything but the first entry,
519                          * otherwise we'll have a hole at the end of the mapping as we only map
520                          * whole pages.
521                          * Also, if we have a kiov_len < PAGE_SIZE but we need to map more
522                          * than kiov_len, we will also have a whole at the end of that page
523                          * which isn't allowed */
524                         if ((kiov[i].kiov_offset != 0 && i > 0) ||
525                             (kiov[i].kiov_offset + kiov[i].kiov_len != PAGE_SIZE && i < niov - 1)) {
526                                 CNETERR("Can't make payload contiguous in I/O VM:"
527                                        "page %d, offset %u, nob %u, kiov_offset %u kiov_len %u \n",
528                                        i, offset, nob, kiov->kiov_offset, kiov->kiov_len);
529                                 RETURN(-EINVAL);
530                         }
531                         tx->tx_imm_pages[i] = kiov[i].kiov_page;
532                 }
533
534                 /* hijack tx_phys for the later unmap */
535                 if (niov == 1) {
536                         /* tx->phyx being equal to NULL is the signal for unmap to discern between kmap and vmap */
537                         tx->tx_phys = NULL;
538                         tx->tx_buffer = (void *)kmap(tx->tx_imm_pages[0]) + kiov[0].kiov_offset + offset;
539                         atomic_inc(&kgnilnd_data.kgn_nkmap_short);
540                         GNIDBG_TX(D_NET, tx, "kmapped page for %d bytes for kiov 0x%p, buffer 0x%p",
541                                 nob, kiov, tx->tx_buffer);
542                 } else {
543                         tx->tx_phys = vmap(tx->tx_imm_pages, niov, VM_MAP, PAGE_KERNEL);
544                         if (tx->tx_phys == NULL) {
545                                 CNETERR("Couldn't vmap %d frags on %d bytes\n", niov, nob);
546                                 RETURN(-ENOMEM);
547
548                         }
549                         atomic_inc(&kgnilnd_data.kgn_nvmap_short);
550                         /* make sure we take into account the kiov offset as the start of the buffer */
551                         tx->tx_buffer = (void *)tx->tx_phys + kiov[0].kiov_offset + offset;
552                         GNIDBG_TX(D_NET, tx, "mapped %d pages for %d bytes from kiov 0x%p to 0x%p, buffer 0x%p",
553                                 niov, nob, kiov, tx->tx_phys, tx->tx_buffer);
554                 }
555                 tx->tx_buftype = GNILND_BUF_IMMEDIATE_KIOV;
556                 tx->tx_nob = nob;
557
558         } else {
559                 /* For now this is almost identical to kgnilnd_setup_virt_buffer, but we
560                  * could "flatten" the payload into a single contiguous buffer ready
561                  * for sending direct over an FMA if we ever needed to. */
562
563                 LASSERT(niov > 0);
564
565                 while (offset >= iov->iov_len) {
566                         offset -= iov->iov_len;
567                         niov--;
568                         iov++;
569                         LASSERT(niov > 0);
570                 }
571
572                 if (nob > iov->iov_len - offset) {
573                         CERROR("Can't handle multiple vaddr fragments\n");
574                         return -EMSGSIZE;
575                 }
576
577                 tx->tx_buffer = (void *)(((unsigned long)iov->iov_base) + offset);
578
579                 tx->tx_buftype = GNILND_BUF_IMMEDIATE;
580                 tx->tx_nob = nob;
581         }
582
583         /* checksum payload early - it shouldn't be changing after lnd_send */
584         if (*kgnilnd_tunables.kgn_checksum >= 2) {
585                 msg->gnm_payload_cksum = kgnilnd_cksum(tx->tx_buffer, nob);
586                 if (CFS_FAIL_CHECK(CFS_FAIL_GNI_SMSG_CKSUM2)) {
587                         msg->gnm_payload_cksum += 0xe00e;
588                 }
589                 if (*kgnilnd_tunables.kgn_checksum_dump > 1) {
590                         kgnilnd_dump_blob(D_BUFFS, "payload checksum",
591                                           tx->tx_buffer, nob);
592                 }
593         } else {
594                 msg->gnm_payload_cksum = 0;
595         }
596
597         return 0;
598 }
599
600 int
601 kgnilnd_setup_virt_buffer(kgn_tx_t *tx,
602                           unsigned int niov, struct iovec *iov,
603                           unsigned int offset, unsigned int nob)
604
605 {
606         LASSERT(nob > 0);
607         LASSERT(niov > 0);
608         LASSERT(tx->tx_buftype == GNILND_BUF_NONE);
609
610         while (offset >= iov->iov_len) {
611                 offset -= iov->iov_len;
612                 niov--;
613                 iov++;
614                 LASSERT(niov > 0);
615         }
616
617         if (nob > iov->iov_len - offset) {
618                 CERROR("Can't handle multiple vaddr fragments\n");
619                 return -EMSGSIZE;
620         }
621
622         tx->tx_buftype = GNILND_BUF_VIRT_UNMAPPED;
623         tx->tx_nob = nob;
624         tx->tx_buffer = (void *)(((unsigned long)iov->iov_base) + offset);
625         return 0;
626 }
627
628 int
629 kgnilnd_setup_phys_buffer(kgn_tx_t *tx, int nkiov, lnet_kiov_t *kiov,
630                           unsigned int offset, unsigned int nob)
631 {
632         gni_mem_segment_t *phys;
633         int             rc = 0;
634         unsigned int    fraglen;
635
636         GNIDBG_TX(D_NET, tx, "niov %d kiov 0x%p offset %u nob %u", nkiov, kiov, offset, nob);
637
638         LASSERT(nob > 0);
639         LASSERT(nkiov > 0);
640         LASSERT(tx->tx_buftype == GNILND_BUF_NONE);
641
642         /* only allocate this if we are going to use it */
643         tx->tx_phys = kmem_cache_alloc(kgnilnd_data.kgn_tx_phys_cache,
644                                               GFP_ATOMIC);
645         if (tx->tx_phys == NULL) {
646                 CERROR("failed to allocate tx_phys\n");
647                 rc = -ENOMEM;
648                 GOTO(error, rc);
649         }
650
651         CDEBUG(D_MALLOC, "slab-alloced 'tx->tx_phys': %lu at %p.\n",
652                LNET_MAX_IOV * sizeof(gni_mem_segment_t), tx->tx_phys);
653
654         /* if loops changes, please change kgnilnd_cksum_kiov
655          *   and kgnilnd_setup_immediate_buffer */
656
657         while (offset >= kiov->kiov_len) {
658                 offset -= kiov->kiov_len;
659                 nkiov--;
660                 kiov++;
661                 LASSERT(nkiov > 0);
662         }
663
664         /* at this point, kiov points to the first page that we'll actually map
665          * now that we've seeked into the koiv for offset and dropped any
666          * leading pages that fall entirely within the offset */
667         tx->tx_buftype = GNILND_BUF_PHYS_UNMAPPED;
668         tx->tx_nob = nob;
669
670         /* kiov_offset is start of 'valid' buffer, so index offset past that */
671         tx->tx_buffer = (void *)((unsigned long)(kiov->kiov_offset + offset));
672         phys = tx->tx_phys;
673
674         CDEBUG(D_NET, "tx 0x%p buffer 0x%p map start kiov 0x%p+%u niov %d offset %u\n",
675                tx, tx->tx_buffer, kiov, kiov->kiov_offset, nkiov, offset);
676
677         do {
678                 fraglen = min(kiov->kiov_len - offset, nob);
679
680                 /* We can't have a kiov_offset on anything but the first entry,
681                  * otherwise we'll have a hole at the end of the mapping as we only map
682                  * whole pages. Only the first page is allowed to have an offset -
683                  * we'll add that into tx->tx_buffer and that will get used when we
684                  * map in the segments (see kgnilnd_map_buffer).
685                  * Also, if we have a kiov_len < PAGE_SIZE but we need to map more
686                  * than kiov_len, we will also have a whole at the end of that page
687                  * which isn't allowed */
688                 if ((phys != tx->tx_phys) &&
689                     ((kiov->kiov_offset != 0) ||
690                      ((kiov->kiov_len < PAGE_SIZE) && (nob > kiov->kiov_len)))) {
691                         CERROR("Can't make payload contiguous in I/O VM:"
692                                "page %d, offset %u, nob %u, kiov_offset %u kiov_len %u \n",
693                                (int)(phys - tx->tx_phys),
694                                offset, nob, kiov->kiov_offset, kiov->kiov_len);
695                         rc = -EINVAL;
696                         GOTO(error, rc);
697                 }
698
699                 if ((phys - tx->tx_phys) == LNET_MAX_IOV) {
700                         CERROR ("payload too big (%d)\n", (int)(phys - tx->tx_phys));
701                         rc = -EMSGSIZE;
702                         GOTO(error, rc);
703                 }
704
705                 if (CFS_FAIL_CHECK(CFS_FAIL_GNI_PHYS_SETUP)) {
706                         rc = -EINVAL;
707                         GOTO(error, rc);
708                 }
709
710                 CDEBUG(D_BUFFS, "page 0x%p kiov_offset %u kiov_len %u nob %u "
711                                "nkiov %u offset %u\n",
712                       kiov->kiov_page, kiov->kiov_offset, kiov->kiov_len, nob, nkiov, offset);
713
714                 phys->address = page_to_phys(kiov->kiov_page);
715                 phys++;
716                 kiov++;
717                 nkiov--;
718                 nob -= fraglen;
719                 offset = 0;
720
721                 /* iov must not run out before end of data */
722                 LASSERTF(nob == 0 || nkiov > 0, "nob %u nkiov %u\n", nob, nkiov);
723
724         } while (nob > 0);
725
726         tx->tx_phys_npages = phys - tx->tx_phys;
727
728         return 0;
729
730 error:
731         if (tx->tx_phys != NULL) {
732                 kmem_cache_free(kgnilnd_data.kgn_tx_phys_cache, tx->tx_phys);
733                 CDEBUG(D_MALLOC, "slab-freed 'tx_phys': %lu at %p.\n",
734                        sizeof(*tx->tx_phys), tx->tx_phys);
735                 tx->tx_phys = NULL;
736         }
737         return rc;
738 }
739
740 static inline int
741 kgnilnd_setup_rdma_buffer(kgn_tx_t *tx, unsigned int niov,
742                           struct iovec *iov, lnet_kiov_t *kiov,
743                           unsigned int offset, unsigned int nob)
744 {
745         int     rc;
746
747         LASSERTF((iov == NULL) != (kiov == NULL), "iov 0x%p, kiov 0x%p, tx 0x%p,"
748                                                 " offset %d, nob %d, niov %d\n"
749                                                 , iov, kiov, tx, offset, nob, niov);
750
751         if (kiov != NULL) {
752                 rc = kgnilnd_setup_phys_buffer(tx, niov, kiov, offset, nob);
753         } else {
754                 rc = kgnilnd_setup_virt_buffer(tx, niov, iov, offset, nob);
755         }
756         return rc;
757 }
758
759 /* kgnilnd_parse_lnet_rdma()
760  * lntmsg - message passed in from lnet.
761  * niov, kiov, offset - see lnd_t in lib-types.h for descriptions.
762  * nob - actual number of bytes to in this message.
763  * put_len - It is possible for PUTs to have a different length than the
764  *           length stored in lntmsg->msg_len since LNET can adjust this
765  *           length based on it's buffer size and offset.
766  *           lnet_try_match_md() sets the mlength that we use to do the RDMA
767  *           transfer.
768  */
769 static void
770 kgnilnd_parse_lnet_rdma(lnet_msg_t *lntmsg, unsigned int *niov,
771                         unsigned int *offset, unsigned int *nob,
772                         lnet_kiov_t **kiov, int put_len)
773 {
774         /* GETs are weird, see kgnilnd_send */
775         if (lntmsg->msg_type == LNET_MSG_GET) {
776                 if ((lntmsg->msg_md->md_options & LNET_MD_KIOV) == 0) {
777                         *kiov = NULL;
778                 } else {
779                         *kiov = lntmsg->msg_md->md_iov.kiov;
780                 }
781                 *niov = lntmsg->msg_md->md_niov;
782                 *nob = lntmsg->msg_md->md_length;
783                 *offset = 0;
784         } else {
785                 *kiov = lntmsg->msg_kiov;
786                 *niov = lntmsg->msg_niov;
787                 *nob = put_len;
788                 *offset = lntmsg->msg_offset;
789         }
790 }
791
792 static inline void
793 kgnilnd_compute_rdma_cksum(kgn_tx_t *tx, int put_len)
794 {
795         unsigned int     niov, offset, nob;
796         lnet_kiov_t     *kiov;
797         lnet_msg_t      *lntmsg = tx->tx_lntmsg[0];
798         int              dump_cksum = (*kgnilnd_tunables.kgn_checksum_dump > 1);
799
800         GNITX_ASSERTF(tx, ((tx->tx_msg.gnm_type == GNILND_MSG_PUT_DONE) ||
801                            (tx->tx_msg.gnm_type == GNILND_MSG_GET_DONE) ||
802                            (tx->tx_msg.gnm_type == GNILND_MSG_PUT_DONE_REV) ||
803                            (tx->tx_msg.gnm_type == GNILND_MSG_GET_DONE_REV) ||
804                            (tx->tx_msg.gnm_type == GNILND_MSG_GET_ACK_REV) ||
805                            (tx->tx_msg.gnm_type == GNILND_MSG_PUT_REQ_REV)),
806                       "bad type %s", kgnilnd_msgtype2str(tx->tx_msg.gnm_type));
807
808         if ((tx->tx_msg.gnm_type == GNILND_MSG_PUT_DONE_REV) ||
809             (tx->tx_msg.gnm_type == GNILND_MSG_GET_DONE_REV)) {
810                 tx->tx_msg.gnm_payload_cksum = 0;
811                 return;
812         }
813         if (*kgnilnd_tunables.kgn_checksum < 3) {
814                 tx->tx_msg.gnm_payload_cksum = 0;
815                 return;
816         }
817
818         GNITX_ASSERTF(tx, lntmsg, "no LNet message!", NULL);
819
820         kgnilnd_parse_lnet_rdma(lntmsg, &niov, &offset, &nob, &kiov,
821                                 put_len);
822
823         if (kiov != NULL) {
824                 tx->tx_msg.gnm_payload_cksum = kgnilnd_cksum_kiov(niov, kiov, offset, nob, dump_cksum);
825         } else {
826                 tx->tx_msg.gnm_payload_cksum = kgnilnd_cksum(tx->tx_buffer, nob);
827                 if (dump_cksum) {
828                         kgnilnd_dump_blob(D_BUFFS, "peer RDMA payload", tx->tx_buffer, nob);
829                 }
830         }
831
832         if (CFS_FAIL_CHECK(CFS_FAIL_GNI_SMSG_CKSUM3)) {
833                 tx->tx_msg.gnm_payload_cksum += 0xd00d;
834         }
835 }
836
837 /* kgnilnd_verify_rdma_cksum()
838  * tx - PUT_DONE/GET_DONE matched tx.
839  * rx_cksum - received checksum to compare against.
840  * put_len - see kgnilnd_parse_lnet_rdma comments.
841  */
842 static inline int
843 kgnilnd_verify_rdma_cksum(kgn_tx_t *tx, __u16 rx_cksum, int put_len)
844 {
845         int              rc = 0;
846         __u16            cksum;
847         unsigned int     niov, offset, nob;
848         lnet_kiov_t     *kiov;
849         lnet_msg_t      *lntmsg = tx->tx_lntmsg[0];
850         int dump_on_err = *kgnilnd_tunables.kgn_checksum_dump;
851
852         /* we can only match certain requests */
853         GNITX_ASSERTF(tx, ((tx->tx_msg.gnm_type == GNILND_MSG_GET_REQ) ||
854                            (tx->tx_msg.gnm_type == GNILND_MSG_PUT_ACK) ||
855                            (tx->tx_msg.gnm_type == GNILND_MSG_PUT_REQ_REV) ||
856                            (tx->tx_msg.gnm_type == GNILND_MSG_GET_ACK_REV) ||
857                            (tx->tx_msg.gnm_type == GNILND_MSG_GET_DONE_REV) ||
858                            (tx->tx_msg.gnm_type == GNILND_MSG_PUT_DONE_REV)),
859                       "bad type %s", kgnilnd_msgtype2str(tx->tx_msg.gnm_type));
860
861         if ((tx->tx_msg.gnm_type == GNILND_MSG_PUT_REQ_REV) ||
862             (tx->tx_msg.gnm_type == GNILND_MSG_GET_ACK_REV)) {
863                 return 0;
864         }
865
866         if (rx_cksum == 0)  {
867                 if (*kgnilnd_tunables.kgn_checksum >= 3) {
868                         GNIDBG_MSG(D_WARNING, &tx->tx_msg,
869                                    "no RDMA payload checksum when enabled");
870                 }
871                 return 0;
872         }
873
874         GNITX_ASSERTF(tx, lntmsg, "no LNet message!", NULL);
875
876         kgnilnd_parse_lnet_rdma(lntmsg, &niov, &offset, &nob, &kiov, put_len);
877
878         if (kiov != NULL) {
879                 cksum = kgnilnd_cksum_kiov(niov, kiov, offset, nob, 0);
880         } else {
881                 cksum = kgnilnd_cksum(tx->tx_buffer, nob);
882         }
883
884         if (cksum != rx_cksum) {
885                 GNIDBG_MSG(D_NETERROR, &tx->tx_msg,
886                            "Bad RDMA payload checksum (%x expected %x); "
887                            "kiov 0x%p niov %d nob %u offset %u",
888                             cksum, rx_cksum, kiov, niov, nob, offset);
889                 switch (dump_on_err) {
890                 case 2:
891                         if (kiov != NULL) {
892                                 kgnilnd_cksum_kiov(niov, kiov, offset, nob, 1);
893                         } else {
894                                 kgnilnd_dump_blob(D_BUFFS, "RDMA payload",
895                                                   tx->tx_buffer, nob);
896                         }
897                         /* fall through to dump log */
898                 case 1:
899                         libcfs_debug_dumplog();
900                         break;
901                 default:
902                         break;
903                 }
904                 rc = -ENOKEY;
905                 /* kgnilnd_check_fma_rx will close conn, kill tx with error */
906         }
907         return rc;
908 }
909
910 void
911 kgnilnd_mem_add_map_list(kgn_device_t *dev, kgn_tx_t *tx)
912 {
913         int     bytes;
914
915         GNITX_ASSERTF(tx, list_empty(&tx->tx_map_list),
916                 "already mapped!", NULL);
917
918         spin_lock(&dev->gnd_map_lock);
919         switch (tx->tx_buftype) {
920         default:
921                 GNIDBG_TX(D_EMERG, tx,
922                         "SOFTWARE BUG: invalid mapping %d", tx->tx_buftype);
923                 spin_unlock(&dev->gnd_map_lock);
924                 LBUG();
925                 break;
926
927         case GNILND_BUF_PHYS_MAPPED:
928                 bytes = tx->tx_phys_npages * PAGE_SIZE;
929                 dev->gnd_map_nphys++;
930                 dev->gnd_map_physnop += tx->tx_phys_npages;
931                 break;
932
933         case GNILND_BUF_VIRT_MAPPED:
934                 bytes = tx->tx_nob;
935                 dev->gnd_map_nvirt++;
936                 dev->gnd_map_virtnob += tx->tx_nob;
937                 break;
938         }
939
940         if (tx->tx_msg.gnm_type == GNILND_MSG_PUT_ACK ||
941             tx->tx_msg.gnm_type == GNILND_MSG_GET_REQ) {
942                 atomic64_add(bytes, &dev->gnd_rdmaq_bytes_out);
943                 GNIDBG_TX(D_NETTRACE, tx, "rdma ++ %d to "LPD64"",
944                           bytes, atomic64_read(&dev->gnd_rdmaq_bytes_out));
945         }
946
947         atomic_inc(&dev->gnd_n_mdd);
948         atomic64_add(bytes, &dev->gnd_nbytes_map);
949
950         /* clear retrans to prevent any SMSG goofiness as that code uses the same counter */
951         tx->tx_retrans = 0;
952
953         /* we only get here in the valid cases */
954         list_add_tail(&tx->tx_map_list, &dev->gnd_map_list);
955         dev->gnd_map_version++;
956         spin_unlock(&dev->gnd_map_lock);
957 }
958
959 void
960 kgnilnd_mem_del_map_list(kgn_device_t *dev, kgn_tx_t *tx)
961 {
962         int     bytes;
963
964         GNITX_ASSERTF(tx, !list_empty(&tx->tx_map_list),
965                 "not mapped!", NULL);
966         spin_lock(&dev->gnd_map_lock);
967
968         switch (tx->tx_buftype) {
969         default:
970                 GNIDBG_TX(D_EMERG, tx,
971                         "SOFTWARE BUG: invalid mapping %d", tx->tx_buftype);
972                 spin_unlock(&dev->gnd_map_lock);
973                 LBUG();
974                 break;
975
976         case GNILND_BUF_PHYS_UNMAPPED:
977                 bytes = tx->tx_phys_npages * PAGE_SIZE;
978                 dev->gnd_map_nphys--;
979                 dev->gnd_map_physnop -= tx->tx_phys_npages;
980                 break;
981
982         case GNILND_BUF_VIRT_UNMAPPED:
983                 bytes = tx->tx_nob;
984                 dev->gnd_map_nvirt--;
985                 dev->gnd_map_virtnob -= tx->tx_nob;
986                 break;
987         }
988
989         if (tx->tx_msg.gnm_type == GNILND_MSG_PUT_ACK ||
990             tx->tx_msg.gnm_type == GNILND_MSG_GET_REQ) {
991                 atomic64_sub(bytes, &dev->gnd_rdmaq_bytes_out);
992                 LASSERTF(atomic64_read(&dev->gnd_rdmaq_bytes_out) >= 0,
993                          "bytes_out negative! %ld\n", atomic64_read(&dev->gnd_rdmaq_bytes_out));
994                 GNIDBG_TX(D_NETTRACE, tx, "rdma -- %d to "LPD64"",
995                           bytes, atomic64_read(&dev->gnd_rdmaq_bytes_out));
996         }
997
998         atomic_dec(&dev->gnd_n_mdd);
999         atomic64_sub(bytes, &dev->gnd_nbytes_map);
1000
1001         /* we only get here in the valid cases */
1002         list_del_init(&tx->tx_map_list);
1003         dev->gnd_map_version++;
1004         spin_unlock(&dev->gnd_map_lock);
1005 }
1006
1007 int
1008 kgnilnd_map_buffer(kgn_tx_t *tx)
1009 {
1010         kgn_conn_t       *conn = tx->tx_conn;
1011         kgn_device_t     *dev = conn->gnc_device;
1012         __u32             flags = GNI_MEM_READWRITE;
1013         gni_return_t      rrc;
1014
1015         /* The kgnilnd_mem_register(_segments) Gemini Driver functions can
1016          * be called concurrently as there are internal locks that protect
1017          * any data structures or HW resources. We just need to ensure
1018          * that our concurrency doesn't result in the kgn_device_t
1019          * getting nuked while we are in here */
1020
1021         LASSERTF(conn != NULL, "tx %p with NULL conn, someone forgot"
1022                 " to set tx_conn before calling %s\n", tx, __FUNCTION__);
1023
1024         if (unlikely(CFS_FAIL_CHECK(CFS_FAIL_GNI_MAP_TX)))
1025                 RETURN(-ENOMEM);
1026
1027         if (*kgnilnd_tunables.kgn_bte_relaxed_ordering) {
1028                 flags |= GNI_MEM_RELAXED_PI_ORDERING;
1029         }
1030
1031         switch (tx->tx_buftype) {
1032         default:
1033                 LBUG();
1034
1035         case GNILND_BUF_NONE:
1036         case GNILND_BUF_IMMEDIATE:
1037         case GNILND_BUF_IMMEDIATE_KIOV:
1038         case GNILND_BUF_PHYS_MAPPED:
1039         case GNILND_BUF_VIRT_MAPPED:
1040                 return 0;
1041
1042         case GNILND_BUF_PHYS_UNMAPPED:
1043                 GNITX_ASSERTF(tx, tx->tx_phys != NULL, "physical buffer not there!", NULL);
1044                 rrc = kgnilnd_mem_register_segments(dev->gnd_handle,
1045                         tx->tx_phys, tx->tx_phys_npages, NULL,
1046                         GNI_MEM_PHYS_SEGMENTS | flags,
1047                         &tx->tx_map_key);
1048                 /* could race with other uses of the map counts, but this is ok
1049                  * - this needs to turn into a non-fatal error soon to allow
1050                  *  GART resource, etc starvation handling */
1051                 if (rrc != GNI_RC_SUCCESS) {
1052                         GNIDBG_TX(D_NET, tx, "Can't map %d pages: dev %d "
1053                                 "phys %u pp %u, virt %u nob "LPU64"",
1054                                 tx->tx_phys_npages, dev->gnd_id,
1055                                 dev->gnd_map_nphys, dev->gnd_map_physnop,
1056                                 dev->gnd_map_nvirt, dev->gnd_map_virtnob);
1057                         RETURN(rrc == GNI_RC_ERROR_RESOURCE ? -ENOMEM : -EINVAL);
1058                 }
1059
1060                 tx->tx_buftype = GNILND_BUF_PHYS_MAPPED;
1061                 kgnilnd_mem_add_map_list(dev, tx);
1062                 return 0;
1063
1064         case GNILND_BUF_VIRT_UNMAPPED:
1065                 rrc = kgnilnd_mem_register(dev->gnd_handle,
1066                         (__u64)tx->tx_buffer, tx->tx_nob,
1067                         NULL, flags, &tx->tx_map_key);
1068                 if (rrc != GNI_RC_SUCCESS) {
1069                         GNIDBG_TX(D_NET, tx, "Can't map %u bytes: dev %d "
1070                                 "phys %u pp %u, virt %u nob "LPU64"",
1071                                 tx->tx_nob, dev->gnd_id,
1072                                 dev->gnd_map_nphys, dev->gnd_map_physnop,
1073                                 dev->gnd_map_nvirt, dev->gnd_map_virtnob);
1074                         RETURN(rrc == GNI_RC_ERROR_RESOURCE ? -ENOMEM : -EINVAL);
1075                 }
1076
1077                 tx->tx_buftype = GNILND_BUF_VIRT_MAPPED;
1078                 kgnilnd_mem_add_map_list(dev, tx);
1079                 if (tx->tx_msg.gnm_type == GNILND_MSG_PUT_ACK ||
1080                     tx->tx_msg.gnm_type == GNILND_MSG_GET_REQ) {
1081                         atomic64_add(tx->tx_nob, &dev->gnd_rdmaq_bytes_out);
1082                         GNIDBG_TX(D_NETTRACE, tx, "rdma ++ %d to %ld\n",
1083                                tx->tx_nob, atomic64_read(&dev->gnd_rdmaq_bytes_out));
1084                 }
1085
1086                 return 0;
1087         }
1088 }
1089
1090 void
1091 kgnilnd_add_purgatory_tx(kgn_tx_t *tx)
1092 {
1093         kgn_conn_t              *conn = tx->tx_conn;
1094         kgn_mdd_purgatory_t     *gmp;
1095
1096         LIBCFS_ALLOC(gmp, sizeof(*gmp));
1097         LASSERTF(gmp != NULL, "couldn't allocate MDD purgatory member;"
1098                 " asserting to avoid data corruption\n");
1099         if (tx->tx_buffer_copy)
1100                 gmp->gmp_map_key = tx->tx_buffer_copy_map_key;
1101         else
1102                 gmp->gmp_map_key = tx->tx_map_key;
1103
1104         atomic_inc(&conn->gnc_device->gnd_n_mdd_held);
1105
1106         /* ensure that we don't have a blank purgatory - indicating the
1107          * conn is not already on purgatory lists - we'd never recover these
1108          * MDD if that were the case */
1109         GNITX_ASSERTF(tx, conn->gnc_in_purgatory,
1110                 "conn 0x%p->%s with NULL purgatory",
1111                 conn, libcfs_nid2str(conn->gnc_peer->gnp_nid));
1112
1113         /* link 'er up! - only place we really need to lock for
1114          * concurrent access */
1115         spin_lock(&conn->gnc_list_lock);
1116         list_add_tail(&gmp->gmp_list, &conn->gnc_mdd_list);
1117         spin_unlock(&conn->gnc_list_lock);
1118 }
1119
1120 void
1121 kgnilnd_unmap_buffer(kgn_tx_t *tx, int error)
1122 {
1123         kgn_device_t     *dev;
1124         gni_return_t      rrc;
1125         int               hold_timeout = 0;
1126
1127         /* code below relies on +1 relationship ... */
1128         CLASSERT(GNILND_BUF_PHYS_MAPPED == (GNILND_BUF_PHYS_UNMAPPED + 1));
1129         CLASSERT(GNILND_BUF_VIRT_MAPPED == (GNILND_BUF_VIRT_UNMAPPED + 1));
1130
1131         switch (tx->tx_buftype) {
1132         default:
1133                 LBUG();
1134
1135         case GNILND_BUF_NONE:
1136         case GNILND_BUF_IMMEDIATE:
1137         case GNILND_BUF_PHYS_UNMAPPED:
1138         case GNILND_BUF_VIRT_UNMAPPED:
1139                 break;
1140         case GNILND_BUF_IMMEDIATE_KIOV:
1141                 if (tx->tx_phys != NULL) {
1142                         vunmap(tx->tx_phys);
1143                 } else if (tx->tx_phys == NULL && tx->tx_buffer != NULL) {
1144                         kunmap(tx->tx_imm_pages[0]);
1145                 }
1146                 /* clear to prevent kgnilnd_free_tx from thinking
1147                  * this is a RDMA descriptor */
1148                 tx->tx_phys = NULL;
1149                 break;
1150
1151         case GNILND_BUF_PHYS_MAPPED:
1152         case GNILND_BUF_VIRT_MAPPED:
1153                 LASSERT(tx->tx_conn != NULL);
1154
1155                 dev = tx->tx_conn->gnc_device;
1156
1157                 /* only want to hold if we are closing conn without
1158                  * verified peer notification  - the theory is that
1159                  * a TX error can be communicated in all other cases */
1160                 if (tx->tx_conn->gnc_state != GNILND_CONN_ESTABLISHED &&
1161                     kgnilnd_check_purgatory_conn(tx->tx_conn)) {
1162                         kgnilnd_add_purgatory_tx(tx);
1163
1164                         /* The timeout we give to kgni is a deadman stop only.
1165                          *  we are setting high to ensure we don't have the kgni timer
1166                          *  fire before ours fires _and_ is handled */
1167                         hold_timeout = GNILND_TIMEOUT2DEADMAN;
1168
1169                         GNIDBG_TX(D_NET, tx,
1170                                  "dev %p delaying MDD release for %dms key "LPX64"."LPX64"",
1171                                  tx->tx_conn->gnc_device, hold_timeout,
1172                                  tx->tx_map_key.qword1, tx->tx_map_key.qword2);
1173                 }
1174                 if (tx->tx_buffer_copy != NULL) {
1175                         rrc = kgnilnd_mem_deregister(dev->gnd_handle, &tx->tx_buffer_copy_map_key, hold_timeout);
1176                         LASSERTF(rrc == GNI_RC_SUCCESS, "rrc %d\n", rrc);
1177                         rrc = kgnilnd_mem_deregister(dev->gnd_handle, &tx->tx_map_key, 0);
1178                         LASSERTF(rrc == GNI_RC_SUCCESS, "rrc %d\n", rrc);
1179                 } else {
1180                         rrc = kgnilnd_mem_deregister(dev->gnd_handle, &tx->tx_map_key, hold_timeout);
1181                         LASSERTF(rrc == GNI_RC_SUCCESS, "rrc %d\n", rrc);
1182                 }
1183
1184                 tx->tx_buftype--;
1185                 kgnilnd_mem_del_map_list(dev, tx);
1186                 break;
1187         }
1188 }
1189
1190 void
1191 kgnilnd_tx_done(kgn_tx_t *tx, int completion)
1192 {
1193         lnet_msg_t      *lntmsg0, *lntmsg1;
1194         int             status0, status1;
1195         lnet_ni_t       *ni = NULL;
1196         kgn_conn_t      *conn = tx->tx_conn;
1197
1198         LASSERT(!in_interrupt());
1199
1200         lntmsg0 = tx->tx_lntmsg[0]; tx->tx_lntmsg[0] = NULL;
1201         lntmsg1 = tx->tx_lntmsg[1]; tx->tx_lntmsg[1] = NULL;
1202
1203         if (completion &&
1204             !(tx->tx_state & GNILND_TX_QUIET_ERROR) &&
1205             !kgnilnd_conn_clean_errno(completion)) {
1206                 GNIDBG_TOMSG(D_NETERROR, &tx->tx_msg,
1207                        "error %d on tx 0x%p->%s id %u/%d state %s age %ds",
1208                        completion, tx, conn ?
1209                        libcfs_nid2str(conn->gnc_peer->gnp_nid) : "<?>",
1210                        tx->tx_id.txe_smsg_id, tx->tx_id.txe_idx,
1211                        kgnilnd_tx_state2str(tx->tx_list_state),
1212                        cfs_duration_sec((unsigned long)jiffies - tx->tx_qtime));
1213         }
1214
1215         /* The error codes determine if we hold onto the MDD */
1216         kgnilnd_unmap_buffer(tx, completion);
1217
1218         /* we have to deliver a reply on lntmsg[1] for the GET, so make sure
1219          * we play nice with the error codes to avoid delivering a failed
1220          * REQUEST and then a REPLY event as well */
1221
1222         /* return -EIO to lnet - it is the magic value for failed sends */
1223         if (tx->tx_msg.gnm_type == GNILND_MSG_GET_REQ) {
1224                 status0 = 0;
1225                 status1 = completion;
1226         } else {
1227                 status0 = status1 = completion;
1228         }
1229
1230         tx->tx_buftype = GNILND_BUF_NONE;
1231         tx->tx_msg.gnm_type = GNILND_MSG_NONE;
1232
1233         /* lnet_finalize doesn't do anything with the *ni, so ok for us to
1234          * set NULL when we are a tx without a conn */
1235         if (conn != NULL) {
1236                 ni = conn->gnc_peer->gnp_net->gnn_ni;
1237
1238                 spin_lock(&conn->gnc_tx_lock);
1239
1240                 LASSERTF(test_and_clear_bit(tx->tx_id.txe_idx,
1241                         (volatile unsigned long *)&conn->gnc_tx_bits),
1242                         "conn %p tx %p bit %d already cleared\n",
1243                         conn, tx, tx->tx_id.txe_idx);
1244
1245                 LASSERTF(conn->gnc_tx_ref_table[tx->tx_id.txe_idx] != NULL,
1246                          "msg_id %d already NULL\n", tx->tx_id.txe_idx);
1247
1248                 conn->gnc_tx_ref_table[tx->tx_id.txe_idx] = NULL;
1249                 spin_unlock(&conn->gnc_tx_lock);
1250         }
1251
1252         kgnilnd_free_tx(tx);
1253
1254         /* finalize AFTER freeing lnet msgs */
1255
1256         /* warning - we should hold no locks here - calling lnet_finalize
1257          * could free up lnet credits, resulting in a call chain back into
1258          * the LND via kgnilnd_send and friends */
1259
1260         lnet_finalize(ni, lntmsg0, status0);
1261
1262         if (lntmsg1 != NULL) {
1263                 lnet_finalize(ni, lntmsg1, status1);
1264         }
1265 }
1266
1267 void
1268 kgnilnd_txlist_done(struct list_head *txlist, int error)
1269 {
1270         kgn_tx_t        *tx, *txn;
1271         int              err_printed = 0;
1272
1273         if (list_empty(txlist))
1274                 return;
1275
1276         list_for_each_entry_safe(tx, txn, txlist, tx_list) {
1277                 /* only print the first error */
1278                 if (err_printed)
1279                         tx->tx_state |= GNILND_TX_QUIET_ERROR;
1280                 list_del_init(&tx->tx_list);
1281                 kgnilnd_tx_done(tx, error);
1282                 err_printed++;
1283         }
1284 }
1285 int
1286 kgnilnd_set_tx_id(kgn_tx_t *tx, kgn_conn_t *conn)
1287 {
1288         int     id;
1289
1290         spin_lock(&conn->gnc_tx_lock);
1291
1292         /* ID zero is NOT ALLOWED!!! */
1293
1294 search_again:
1295         id = find_next_zero_bit((unsigned long *)&conn->gnc_tx_bits,
1296                                  GNILND_MAX_MSG_ID, conn->gnc_next_tx);
1297         if (id == GNILND_MAX_MSG_ID) {
1298                 if (conn->gnc_next_tx != 1) {
1299                         /* we only searched from next_tx to end and didn't find
1300                          * one, so search again from start */
1301                         conn->gnc_next_tx = 1;
1302                         goto search_again;
1303                 }
1304                 /* couldn't find one! */
1305                 spin_unlock(&conn->gnc_tx_lock);
1306                 return -E2BIG;
1307         }
1308
1309         /* bump next_tx to prevent immediate reuse */
1310         conn->gnc_next_tx = id + 1;
1311
1312         set_bit(id, (volatile unsigned long *)&conn->gnc_tx_bits);
1313         LASSERTF(conn->gnc_tx_ref_table[id] == NULL,
1314                  "tx 0x%p already at id %d\n",
1315                  conn->gnc_tx_ref_table[id], id);
1316
1317         /* delay these until we have a valid ID - prevents bad clear of the bit
1318          * in kgnilnd_tx_done */
1319         tx->tx_conn = conn;
1320         tx->tx_id.txe_cqid = conn->gnc_cqid;
1321
1322         tx->tx_id.txe_idx = id;
1323         conn->gnc_tx_ref_table[id] = tx;
1324
1325         /* Using jiffies to help differentiate against TX reuse - with
1326          * the usual minimum of a 250HZ clock, we wrap jiffies on the same TX
1327          * if we are sending to the same node faster than 256000/sec.
1328          * To help guard against this, we OR in the tx_seq - that is 32 bits */
1329
1330         tx->tx_id.txe_chips = (__u32)(jiffies | atomic_read(&conn->gnc_tx_seq));
1331
1332         GNIDBG_TX(D_NET, tx, "set cookie/id/bits", NULL);
1333
1334         spin_unlock(&conn->gnc_tx_lock);
1335         return 0;
1336 }
1337
1338 static inline int
1339 kgnilnd_tx_should_retry(kgn_conn_t *conn, kgn_tx_t *tx)
1340 {
1341         int             max_retrans = *kgnilnd_tunables.kgn_max_retransmits;
1342         int             log_retrans;
1343         int             log_retrans_level;
1344
1345         /* I need kgni credits to send this.  Replace tx at the head of the
1346          * fmaq and I'll get rescheduled when credits appear */
1347         tx->tx_state = 0;
1348         tx->tx_retrans++;
1349         conn->gnc_tx_retrans++;
1350         log_retrans = ((tx->tx_retrans < 25) || ((tx->tx_retrans % 25) == 0) ||
1351                         (tx->tx_retrans > (max_retrans / 2)));
1352         log_retrans_level = tx->tx_retrans < (max_retrans / 2) ? D_NET : D_NETERROR;
1353
1354         /* Decision time - either error, warn or just retransmit */
1355
1356         /* we don't care about TX timeout - it could be that the network is slower
1357          * or throttled. We'll keep retranmitting - so if the network is so slow
1358          * that we fill up our mailbox, we'll keep trying to resend that msg
1359          * until we exceed the max_retrans _or_ gnc_last_rx expires, indicating
1360          * that he hasn't send us any traffic in return */
1361
1362         if (tx->tx_retrans > max_retrans) {
1363                 /* this means we are not backing off the retransmits
1364                  * in a healthy manner and are likely chewing up the
1365                  * CPU cycles quite badly */
1366                 GNIDBG_TOMSG(D_ERROR, &tx->tx_msg,
1367                         "SOFTWARE BUG: too many retransmits (%d) for tx id %x "
1368                         "conn 0x%p->%s\n",
1369                         tx->tx_retrans, tx->tx_id, conn,
1370                         libcfs_nid2str(conn->gnc_peer->gnp_nid));
1371
1372                 /* yes - double errors to help debug this condition */
1373                 GNIDBG_TOMSG(D_NETERROR, &tx->tx_msg, "connection dead. "
1374                         "unable to send to %s for %lu secs (%d tries)",
1375                         libcfs_nid2str(tx->tx_conn->gnc_peer->gnp_nid),
1376                         cfs_duration_sec(jiffies - tx->tx_cred_wait),
1377                         tx->tx_retrans);
1378
1379                 kgnilnd_close_conn(conn, -ETIMEDOUT);
1380
1381                 /* caller should terminate */
1382                 RETURN(0);
1383         } else {
1384                 /* some reasonable throttling of the debug message */
1385                 if (log_retrans) {
1386                         unsigned long now = jiffies;
1387                         /* XXX Nic: Mystical TX debug here... */
1388                         GNIDBG_SMSG_CREDS(log_retrans_level, conn);
1389                         GNIDBG_TOMSG(log_retrans_level, &tx->tx_msg,
1390                                 "NOT_DONE on conn 0x%p->%s id %x retrans %d wait %dus"
1391                                 " last_msg %uus/%uus last_cq %uus/%uus",
1392                                 conn, libcfs_nid2str(conn->gnc_peer->gnp_nid),
1393                                 tx->tx_id, tx->tx_retrans,
1394                                 jiffies_to_usecs(now - tx->tx_cred_wait),
1395                                 jiffies_to_usecs(now - conn->gnc_last_tx),
1396                                 jiffies_to_usecs(now - conn->gnc_last_rx),
1397                                 jiffies_to_usecs(now - conn->gnc_last_tx_cq),
1398                                 jiffies_to_usecs(now - conn->gnc_last_rx_cq));
1399                 }
1400                 /* caller should retry */
1401                 RETURN(1);
1402         }
1403 }
1404
1405 /* caller must be holding gnd_cq_mutex and not unlock it afterwards, as we need to drop it
1406  * to avoid bad ordering with state_lock */
1407
1408 static inline int
1409 kgnilnd_sendmsg_nolock(kgn_tx_t *tx, void *immediate, unsigned int immediatenob,
1410                 spinlock_t *state_lock, kgn_tx_list_state_t state)
1411 {
1412         kgn_conn_t      *conn = tx->tx_conn;
1413         kgn_msg_t       *msg = &tx->tx_msg;
1414         int              retry_send;
1415         gni_return_t     rrc;
1416         unsigned long    newest_last_rx, timeout;
1417         unsigned long    now;
1418
1419         LASSERTF((msg->gnm_type == GNILND_MSG_IMMEDIATE) ?
1420                 immediatenob <= *kgnilnd_tunables.kgn_max_immediate :
1421                 immediatenob == 0,
1422                 "msg 0x%p type %d wrong payload size %d\n",
1423                 msg, msg->gnm_type, immediatenob);
1424
1425         /* make sure we catch all the cases where we'd send on a dirty old mbox
1426          * but allow case for sending CLOSE. Since this check is within the CQ
1427          * mutex barrier and the close message is only sent through
1428          * kgnilnd_send_conn_close the last message out the door will be the
1429          * close message.
1430          */
1431         if (atomic_read(&conn->gnc_peer->gnp_dirty_eps) != 0 && msg->gnm_type != GNILND_MSG_CLOSE) {
1432                 kgnilnd_conn_mutex_unlock(&conn->gnc_smsg_mutex);
1433                 kgnilnd_gl_mutex_unlock(&conn->gnc_device->gnd_cq_mutex);
1434                 /* Return -ETIME, we are closing the connection already so we dont want to
1435                  * have this tx hit the wire. The tx will be killed by the calling function.
1436                  * Once the EP is marked dirty the close message will be the last
1437                  * thing to hit the wire */
1438                 return -ETIME;
1439         }
1440
1441         now = jiffies;
1442         timeout = cfs_time_seconds(conn->gnc_timeout);
1443
1444         newest_last_rx = GNILND_LASTRX(conn);
1445
1446         if (CFS_FAIL_CHECK(CFS_FAIL_GNI_SEND_TIMEOUT)) {
1447                 now = now + (GNILND_TIMEOUTRX(timeout) * 2);
1448         }
1449
1450         if (time_after_eq(now, newest_last_rx + GNILND_TIMEOUTRX(timeout))) {
1451                 GNIDBG_CONN(D_NETERROR|D_CONSOLE, conn,
1452                             "Cant send to %s after timeout lapse of %lu; TO %lu\n",
1453                 libcfs_nid2str(conn->gnc_peer->gnp_nid),
1454                 cfs_duration_sec(now - newest_last_rx),
1455                 cfs_duration_sec(GNILND_TIMEOUTRX(timeout)));
1456                 kgnilnd_conn_mutex_unlock(&conn->gnc_smsg_mutex);
1457                 kgnilnd_gl_mutex_unlock(&conn->gnc_device->gnd_cq_mutex);
1458                 return -ETIME;
1459         }
1460
1461         GNITX_ASSERTF(tx, (conn != NULL) && (tx->tx_id.txe_idx != 0), "tx id unset!", NULL);
1462         /* msg->gnm_srcnid is set when the message is initialized by whatever function is
1463          * creating the message this allows the message to contain the correct LNET NID/NET needed
1464          * instead of the one that the peer/conn uses for sending the data.
1465          */
1466         msg->gnm_connstamp = conn->gnc_my_connstamp;
1467         msg->gnm_payload_len = immediatenob;
1468         kgnilnd_conn_mutex_lock(&conn->gnc_smsg_mutex);
1469         msg->gnm_seq = atomic_read(&conn->gnc_tx_seq);
1470
1471         /* always init here - kgn_checksum is a /sys module tunable
1472          * and can be flipped at any point, even between msg init and sending */
1473         msg->gnm_cksum = 0;
1474         if (*kgnilnd_tunables.kgn_checksum) {
1475                 /* We must set here and not in kgnilnd_init_msg,
1476                  * we could resend this msg many times
1477                  * (NOT_DONE from gni_smsg_send below) and wouldn't pass
1478                  * through init_msg again */
1479                 msg->gnm_cksum = kgnilnd_cksum(msg, sizeof(kgn_msg_t));
1480                 if (CFS_FAIL_CHECK(CFS_FAIL_GNI_SMSG_CKSUM1)) {
1481                         msg->gnm_cksum += 0xf00f;
1482                 }
1483         }
1484
1485         GNIDBG_TOMSG(D_NET, msg, "tx 0x%p conn 0x%p->%s sending SMSG sz %u id %x/%d [%p for %u]",
1486                tx, conn, libcfs_nid2str(conn->gnc_peer->gnp_nid),
1487                sizeof(kgn_msg_t), tx->tx_id.txe_smsg_id,
1488                tx->tx_id.txe_idx, immediate, immediatenob);
1489
1490         if (unlikely(tx->tx_state & GNILND_TX_FAIL_SMSG)) {
1491                 rrc = cfs_fail_val ? cfs_fail_val : GNI_RC_NOT_DONE;
1492         } else {
1493                 rrc = kgnilnd_smsg_send(conn->gnc_ephandle,
1494                                         msg, sizeof(*msg), immediate,
1495                                         immediatenob,
1496                                         tx->tx_id.txe_smsg_id);
1497         }
1498
1499         switch (rrc) {
1500         case GNI_RC_SUCCESS:
1501                 atomic_inc(&conn->gnc_tx_seq);
1502                 conn->gnc_last_tx = jiffies;
1503                 /* no locking here as LIVE isn't a list */
1504                 kgnilnd_tx_add_state_locked(tx, NULL, conn, GNILND_TX_LIVE_FMAQ, 1);
1505
1506                 /* this needs to be checked under lock as it might be freed from a completion
1507                  * event.
1508                  */
1509                 if (msg->gnm_type == GNILND_MSG_NOOP) {
1510                         set_mb(conn->gnc_last_noop_sent, jiffies);
1511                 }
1512
1513                 /* serialize with seeing CQ events for completion on this, as well as
1514                  * tx_seq */
1515                 kgnilnd_conn_mutex_unlock(&conn->gnc_smsg_mutex);
1516                 kgnilnd_gl_mutex_unlock(&conn->gnc_device->gnd_cq_mutex);
1517
1518                 atomic_inc(&conn->gnc_device->gnd_short_ntx);
1519                 atomic64_add(immediatenob, &conn->gnc_device->gnd_short_txbytes);
1520                 kgnilnd_peer_alive(conn->gnc_peer);
1521                 GNIDBG_SMSG_CREDS(D_NET, conn);
1522                 return 0;
1523
1524         case GNI_RC_NOT_DONE:
1525                 /* XXX Nic: We need to figure out how to track this
1526                  * - there are bound to be good reasons for it,
1527                  * but we want to know when it happens */
1528                 kgnilnd_conn_mutex_unlock(&conn->gnc_smsg_mutex);
1529                 kgnilnd_gl_mutex_unlock(&conn->gnc_device->gnd_cq_mutex);
1530                 /* We'll handle this error inline - makes the calling logic much more
1531                  * clean */
1532
1533                 /* If no lock, caller doesn't want us to retry */
1534                 if (state_lock == NULL) {
1535                         return -EAGAIN;
1536                 }
1537
1538                 retry_send = kgnilnd_tx_should_retry(conn, tx);
1539                 if (retry_send) {
1540                         /* add to head of list for the state and retries */
1541                         spin_lock(state_lock);
1542                         kgnilnd_tx_add_state_locked(tx, conn->gnc_peer, conn, state, 0);
1543                         spin_unlock(state_lock);
1544
1545                         /* We only reschedule for a certain number of retries, then
1546                          * we will wait for the CQ events indicating a release of SMSG
1547                          * credits */
1548                         if (tx->tx_retrans < (*kgnilnd_tunables.kgn_max_retransmits/4)) {
1549                                 kgnilnd_schedule_conn(conn);
1550                                 return 0;
1551                         } else {
1552                                 /* CQ event coming in signifies either TX completed or
1553                                  * RX receive. Either of these *could* free up credits
1554                                  * in the SMSG mbox and we should try sending again */
1555                                 GNIDBG_TX(D_NET, tx, "waiting for CQID %u event to resend",
1556                                          tx->tx_conn->gnc_cqid);
1557                                 /* use +ve return code to let upper layers know they
1558                                  * should stop looping on sends */
1559                                 return EAGAIN;
1560                         }
1561                 } else {
1562                         return -EAGAIN;
1563                 }
1564         default:
1565                 /* handle bad retcode gracefully */
1566                 kgnilnd_conn_mutex_unlock(&conn->gnc_smsg_mutex);
1567                 kgnilnd_gl_mutex_unlock(&conn->gnc_device->gnd_cq_mutex);
1568                 return -EIO;
1569         }
1570 }
1571
1572 /* kgnilnd_sendmsg has hard wait on gnd_cq_mutex */
1573 static inline int
1574 kgnilnd_sendmsg(kgn_tx_t *tx, void *immediate, unsigned int immediatenob,
1575                 spinlock_t *state_lock, kgn_tx_list_state_t state)
1576 {
1577         kgn_device_t    *dev = tx->tx_conn->gnc_device;
1578         unsigned long    timestamp;
1579         int              rc;
1580
1581         timestamp = jiffies;
1582         kgnilnd_gl_mutex_lock(&dev->gnd_cq_mutex);
1583         /* delay in jiffies - we are really concerned only with things that
1584          * result in a schedule() or really holding this off for long times .
1585          * NB - mutex_lock could spin for 2 jiffies before going to sleep to wait */
1586         dev->gnd_mutex_delay += (long) jiffies - timestamp;
1587
1588         rc = kgnilnd_sendmsg_nolock(tx, immediate, immediatenob, state_lock, state);
1589
1590         RETURN(rc);
1591 }
1592
1593
1594 /* returns -EAGAIN for lock miss, anything else < 0 is hard error, >=0 for success */
1595 static inline int
1596 kgnilnd_sendmsg_trylock(kgn_tx_t *tx, void *immediate, unsigned int immediatenob,
1597                 spinlock_t *state_lock, kgn_tx_list_state_t state)
1598 {
1599         kgn_conn_t      *conn = tx->tx_conn;
1600         kgn_device_t    *dev = conn->gnc_device;
1601         unsigned long    timestamp;
1602         int              rc;
1603
1604         timestamp = jiffies;
1605
1606         /* technically we are doing bad things with the read_lock on the peer_conn
1607          * table, but we shouldn't be sleeping inside here - and we don't sleep/block
1608          * for the mutex. I bet lockdep is gonna flag this one though... */
1609
1610         /* there are a few cases where we don't want the immediate send - like
1611          * when we are in the scheduler thread and it'd harm the latency of
1612          * getting messages up to LNet */
1613
1614         /* rmb for gnd_ready */
1615         smp_rmb();
1616         if (conn->gnc_device->gnd_ready == GNILND_DEV_LOOP) {
1617                 rc = 0;
1618                 atomic_inc(&conn->gnc_device->gnd_fast_block);
1619         } else if (unlikely(kgnilnd_data.kgn_quiesce_trigger)) {
1620                /* dont hit HW during quiesce */
1621                 rc = 0;
1622         } else if (unlikely(atomic_read(&conn->gnc_peer->gnp_dirty_eps))) {
1623                /* dont hit HW if stale EPs and conns left to close */
1624                 rc = 0;
1625         } else {
1626                 atomic_inc(&conn->gnc_device->gnd_fast_try);
1627                 rc = kgnilnd_gl_mutex_trylock(&conn->gnc_device->gnd_cq_mutex);
1628         }
1629         if (!rc) {
1630                 rc = -EAGAIN;
1631         } else {
1632                 /* we got the mutex and weren't blocked */
1633
1634                 /* delay in jiffies - we are really concerned only with things that
1635                  * result in a schedule() or really holding this off for long times .
1636                  * NB - mutex_lock could spin for 2 jiffies before going to sleep to wait */
1637                 dev->gnd_mutex_delay += (long) jiffies - timestamp;
1638
1639                 atomic_inc(&conn->gnc_device->gnd_fast_ok);
1640                 tx->tx_qtime = jiffies;
1641                 tx->tx_state = GNILND_TX_WAITING_COMPLETION;
1642                 rc = kgnilnd_sendmsg_nolock(tx, tx->tx_buffer, tx->tx_nob, &conn->gnc_list_lock, GNILND_TX_FMAQ);
1643                 /* _nolock unlocks the mutex for us */
1644         }
1645
1646         RETURN(rc);
1647 }
1648
1649 /* lets us know if we can push this RDMA through now */
1650 inline int
1651 kgnilnd_auth_rdma_bytes(kgn_device_t *dev, kgn_tx_t *tx)
1652 {
1653         long    bytes_left;
1654
1655         bytes_left = atomic64_sub_return(tx->tx_nob, &dev->gnd_rdmaq_bytes_ok);
1656
1657         if (bytes_left < 0) {
1658                 atomic64_add(tx->tx_nob, &dev->gnd_rdmaq_bytes_ok);
1659                 atomic_inc(&dev->gnd_rdmaq_nstalls);
1660                 smp_wmb();
1661
1662                 CDEBUG(D_NET, "no bytes to send, turning on timer for %lu\n",
1663                        dev->gnd_rdmaq_deadline);
1664                 mod_timer(&dev->gnd_rdmaq_timer, dev->gnd_rdmaq_deadline);
1665                 /* we never del this timer - at worst it schedules us.. */
1666                 return -EAGAIN;
1667         } else {
1668                 return 0;
1669         }
1670 }
1671
1672 /* this adds a TX to the queue pending throttling authorization before
1673  * we allow our remote peer to launch a PUT at us */
1674 void
1675 kgnilnd_queue_rdma(kgn_conn_t *conn, kgn_tx_t *tx)
1676 {
1677         int     rc;
1678
1679         /* we cannot go into send_mapped_tx from here as we are holding locks
1680          * and mem registration might end up allocating memory in kgni.
1681          * That said, we'll push this as far as we can into the queue process */
1682         rc = kgnilnd_auth_rdma_bytes(conn->gnc_device, tx);
1683
1684         if (rc < 0) {
1685                 spin_lock(&conn->gnc_device->gnd_rdmaq_lock);
1686                 kgnilnd_tx_add_state_locked(tx, NULL, conn, GNILND_TX_RDMAQ, 0);
1687                 /* lets us know how delayed RDMA is */
1688                 tx->tx_qtime = jiffies;
1689                 spin_unlock(&conn->gnc_device->gnd_rdmaq_lock);
1690         } else {
1691                 /* we have RDMA authorized, now it just needs a MDD and to hit the wire */
1692                 spin_lock(&tx->tx_conn->gnc_device->gnd_lock);
1693                 kgnilnd_tx_add_state_locked(tx, NULL, tx->tx_conn, GNILND_TX_MAPQ, 0);
1694                 /* lets us know how delayed mapping is */
1695                 tx->tx_qtime = jiffies;
1696                 spin_unlock(&tx->tx_conn->gnc_device->gnd_lock);
1697         }
1698
1699         /* make sure we wake up sched to run this */
1700         kgnilnd_schedule_device(tx->tx_conn->gnc_device);
1701 }
1702
1703 /* push TX through state machine */
1704 void
1705 kgnilnd_queue_tx(kgn_conn_t *conn, kgn_tx_t *tx)
1706 {
1707         int            rc = 0;
1708         int            add_tail = 1;
1709
1710         /* set the tx_id here, we delay it until we have an actual conn
1711          * to fiddle with
1712          * in some cases, the tx_id is already set to provide for things
1713          * like RDMA completion cookies, etc */
1714         if (tx->tx_id.txe_idx == 0) {
1715                 rc = kgnilnd_set_tx_id(tx, conn);
1716                 if (rc != 0) {
1717                         kgnilnd_tx_done(tx, rc);
1718                         return;
1719                 }
1720         }
1721
1722         CDEBUG(D_NET, "%s to conn %p for %s\n", kgnilnd_msgtype2str(tx->tx_msg.gnm_type),
1723                 conn, libcfs_nid2str(conn->gnc_peer->gnp_nid));
1724
1725         /* Only let NOOPs to be sent while fail loc is set, otherwise kill the tx.
1726          */
1727         if (CFS_FAIL_CHECK(CFS_FAIL_GNI_ONLY_NOOP) && (tx->tx_msg.gnm_type != GNILND_MSG_NOOP)) {
1728                 kgnilnd_tx_done(tx, rc);
1729                 return;
1730         }
1731
1732         switch (tx->tx_msg.gnm_type) {
1733         case GNILND_MSG_PUT_ACK:
1734         case GNILND_MSG_GET_REQ:
1735         case GNILND_MSG_PUT_REQ_REV:
1736         case GNILND_MSG_GET_ACK_REV:
1737                 /* hijacking time! If this messages will authorize our peer to
1738                  * send his dirty little bytes in an RDMA, we need to get permission */
1739                 kgnilnd_queue_rdma(conn, tx);
1740                 break;
1741         case GNILND_MSG_IMMEDIATE:
1742                 /* try to send right now, can help reduce latency */
1743                 rc = kgnilnd_sendmsg_trylock(tx, tx->tx_buffer, tx->tx_nob, &conn->gnc_list_lock, GNILND_TX_FMAQ);
1744
1745                 if (rc >= 0) {
1746                         /* it was sent, break out of switch to avoid default case of queueing */
1747                         break;
1748                 }
1749                 /* needs to queue to try again, so fall through to default case */
1750         case GNILND_MSG_NOOP:
1751                 /* Just make sure this goes out first for this conn */
1752                 add_tail = 0;
1753                 /* fall through... */
1754         default:
1755                 spin_lock(&conn->gnc_list_lock);
1756                 kgnilnd_tx_add_state_locked(tx, conn->gnc_peer, conn, GNILND_TX_FMAQ, add_tail);
1757                 tx->tx_qtime = jiffies;
1758                 spin_unlock(&conn->gnc_list_lock);
1759                 kgnilnd_schedule_conn(conn);
1760         }
1761 }
1762
1763 void
1764 kgnilnd_launch_tx(kgn_tx_t *tx, kgn_net_t *net, lnet_process_id_t *target)
1765 {
1766         kgn_peer_t      *peer;
1767         kgn_peer_t      *new_peer = NULL;
1768         kgn_conn_t      *conn = NULL;
1769         int              rc;
1770         int              node_state;
1771
1772         ENTRY;
1773
1774         /* If I get here, I've committed to send, so I complete the tx with
1775          * failure on any problems */
1776
1777         GNITX_ASSERTF(tx, tx->tx_conn == NULL,
1778                       "tx already has connection %p", tx->tx_conn);
1779
1780         /* do all of the peer & conn searching in one swoop - this avoids
1781          * nastiness when dropping locks and needing to maintain a sane state
1782          * in the face of stack reset or something else nuking peers & conns */
1783
1784         /* I expect to find him, so only take a read lock */
1785         read_lock(&kgnilnd_data.kgn_peer_conn_lock);
1786
1787         peer = kgnilnd_find_peer_locked(target->nid);
1788         if (peer != NULL) {
1789                 conn = kgnilnd_find_conn_locked(peer);
1790                 /* this could be NULL during quiesce */
1791                 if (conn != NULL)  {
1792                         /* Connection exists; queue message on it */
1793                         kgnilnd_queue_tx(conn, tx);
1794                         read_unlock(&kgnilnd_data.kgn_peer_conn_lock);
1795                         RETURN_EXIT;
1796                 }
1797
1798                 /* don't create a connection if the peer is marked down */
1799                 if (peer->gnp_down == GNILND_RCA_NODE_DOWN) {
1800                         read_unlock(&kgnilnd_data.kgn_peer_conn_lock);
1801                         rc = -ENETRESET;
1802                         GOTO(no_peer, rc);
1803                 }
1804         }
1805
1806         /* creating peer or conn; I'll need a write lock... */
1807         read_unlock(&kgnilnd_data.kgn_peer_conn_lock);
1808
1809         CFS_RACE(CFS_FAIL_GNI_FIND_TARGET);
1810
1811         node_state = kgnilnd_get_node_state(LNET_NIDADDR(target->nid));
1812
1813         /* NB - this will not block during normal operations -
1814          * the only writer of this is in the startup/shutdown path. */
1815         rc = down_read_trylock(&kgnilnd_data.kgn_net_rw_sem);
1816         if (!rc) {
1817                 rc = -ESHUTDOWN;
1818                 GOTO(no_peer, rc);
1819         }
1820
1821         /* ignore previous peer entirely - we cycled the lock, so we
1822          * will create new peer and at worst drop it if peer is still
1823          * in the tables */
1824         rc = kgnilnd_create_peer_safe(&new_peer, target->nid, net, node_state);
1825         if (rc != 0) {
1826                 up_read(&kgnilnd_data.kgn_net_rw_sem);
1827                 GOTO(no_peer, rc);
1828         }
1829
1830         write_lock(&kgnilnd_data.kgn_peer_conn_lock);
1831         up_read(&kgnilnd_data.kgn_net_rw_sem);
1832
1833         /* search for peer again now that we have the lock
1834          * if we don't find it, add our new one to the list */
1835         kgnilnd_add_peer_locked(target->nid, new_peer, &peer);
1836
1837         /* don't create a connection if the peer is not up */
1838         if (peer->gnp_down != GNILND_RCA_NODE_UP) {
1839                 write_unlock(&kgnilnd_data.kgn_peer_conn_lock);
1840                 rc = -ENETRESET;
1841                 GOTO(no_peer, rc);
1842         }
1843
1844         conn = kgnilnd_find_or_create_conn_locked(peer);
1845
1846         if (CFS_FAIL_CHECK(CFS_FAIL_GNI_DGRAM_DROP_TX)) {
1847                 write_unlock(&kgnilnd_data.kgn_peer_conn_lock);
1848                 GOTO(no_peer, rc);
1849         }
1850
1851         if (conn != NULL) {
1852                 /* oh hey, found a conn now... magical */
1853                 kgnilnd_queue_tx(conn, tx);
1854         } else {
1855                 /* no conn, must be trying to connect - so we queue for now */
1856                 tx->tx_qtime = jiffies;
1857                 kgnilnd_tx_add_state_locked(tx, peer, NULL, GNILND_TX_PEERQ, 1);
1858         }
1859         write_unlock(&kgnilnd_data.kgn_peer_conn_lock);
1860         RETURN_EXIT;
1861 no_peer:
1862         kgnilnd_tx_done(tx, rc);
1863         RETURN_EXIT;
1864 }
1865
1866 int
1867 kgnilnd_rdma(kgn_tx_t *tx, int type,
1868             kgn_rdma_desc_t *sink, unsigned int nob, __u64 cookie)
1869 {
1870         kgn_conn_t   *conn = tx->tx_conn;
1871         unsigned long timestamp;
1872         gni_post_type_t post_type;
1873         gni_return_t  rrc;
1874         int rc = 0;
1875         unsigned int desc_nob = nob;
1876         void *desc_buffer = tx->tx_buffer;
1877         gni_mem_handle_t desc_map_key = tx->tx_map_key;
1878         LASSERTF(kgnilnd_tx_mapped(tx),
1879                 "unmapped tx %p\n", tx);
1880         LASSERTF(conn != NULL,
1881                 "NULL conn on tx %p, naughty, naughty\n", tx);
1882         LASSERTF(nob <= sink->gnrd_nob,
1883                 "nob %u > sink->gnrd_nob %d (%p)\n",
1884                 nob, sink->gnrd_nob, sink);
1885         LASSERTF(nob <= tx->tx_nob,
1886                 "nob %d > tx(%p)->tx_nob %d\n",
1887                 nob, tx, tx->tx_nob);
1888
1889         switch (type) {
1890         case GNILND_MSG_GET_DONE:
1891         case GNILND_MSG_PUT_DONE:
1892                 post_type = GNI_POST_RDMA_PUT;
1893                 break;
1894         case GNILND_MSG_GET_DONE_REV:
1895         case GNILND_MSG_PUT_DONE_REV:
1896                 post_type = GNI_POST_RDMA_GET;
1897                 break;
1898         default:
1899                 CERROR("invalid msg type %s (%d)\n",
1900                         kgnilnd_msgtype2str(type), type);
1901                 LBUG();
1902         }
1903         if (post_type == GNI_POST_RDMA_GET) {
1904                 /* Check for remote buffer / local buffer / length alignment. All must be 4 byte
1905                  * aligned. If the local buffer is not aligned correctly using the copy buffer
1906                  * will fix that issue. If length is misaligned copy buffer will also fix the issue, we end
1907                  * up transferring extra bytes into the buffer but only copy the correct nob into the original
1908                  * buffer.  Remote offset correction is done through a combination of adjusting the offset,
1909                  * making sure the length and addr are aligned and copying the data into the correct location
1910                  * once the transfer has completed.
1911                  */
1912                 if ((((__u64)((unsigned long)tx->tx_buffer)) & 3) ||
1913                       (sink->gnrd_addr & 3) ||
1914                       (nob & 3)) {
1915
1916                         tx->tx_offset = ((__u64)((unsigned long)sink->gnrd_addr)) & 3;
1917                         if (tx->tx_offset)
1918                                 kgnilnd_admin_addref(kgnilnd_data.kgn_rev_offset);
1919
1920                         if ((nob + tx->tx_offset) & 3) {
1921                                 desc_nob = ((nob + tx->tx_offset) + (4 - ((nob + tx->tx_offset) & 3)));
1922                                 kgnilnd_admin_addref(kgnilnd_data.kgn_rev_length);
1923                         } else {
1924                                 desc_nob = (nob + tx->tx_offset);
1925                         }
1926
1927                         if (tx->tx_buffer_copy == NULL) {
1928                                 /* Allocate the largest copy buffer we will need, this will prevent us from overwriting data
1929                                  * and require at most we allocate a few extra bytes. */
1930                                 tx->tx_buffer_copy = vmalloc(desc_nob);
1931
1932                                 if (!tx->tx_buffer_copy) {
1933                                         /* allocation of buffer failed nak the rdma */
1934                                         kgnilnd_nak_rdma(tx->tx_conn, tx->tx_msg.gnm_type, -EFAULT, cookie, tx->tx_msg.gnm_srcnid);
1935                                         kgnilnd_tx_done(tx, -EFAULT);
1936                                         return 0;
1937                                 }
1938                                 kgnilnd_admin_addref(kgnilnd_data.kgn_rev_copy_buff);
1939                                 rc = kgnilnd_mem_register(conn->gnc_device->gnd_handle, (__u64)tx->tx_buffer_copy, desc_nob, NULL, GNI_MEM_READWRITE, &tx->tx_buffer_copy_map_key);
1940                                 if (rc != GNI_RC_SUCCESS) {
1941                                         /* Registration Failed nak rdma and kill the tx. */
1942                                         vfree(tx->tx_buffer_copy);
1943                                         tx->tx_buffer_copy = NULL;
1944                                         kgnilnd_nak_rdma(tx->tx_conn, tx->tx_msg.gnm_type, -EFAULT, cookie, tx->tx_msg.gnm_srcnid);
1945                                         kgnilnd_tx_done(tx, -EFAULT);
1946                                         return 0;
1947                                 }
1948                         }
1949                         desc_map_key = tx->tx_buffer_copy_map_key;
1950                         desc_buffer = tx->tx_buffer_copy;
1951                 }
1952         }
1953
1954         memset(&tx->tx_rdma_desc, 0, sizeof(tx->tx_rdma_desc));
1955         tx->tx_rdma_desc.post_id = tx->tx_id.txe_cookie;
1956         tx->tx_rdma_desc.type = post_type;
1957         tx->tx_rdma_desc.cq_mode = GNI_CQMODE_GLOBAL_EVENT;
1958         tx->tx_rdma_desc.local_addr = (__u64)((unsigned long)desc_buffer);
1959         tx->tx_rdma_desc.local_mem_hndl = desc_map_key;
1960         tx->tx_rdma_desc.remote_addr = sink->gnrd_addr - tx->tx_offset;
1961         tx->tx_rdma_desc.remote_mem_hndl = sink->gnrd_key;
1962         tx->tx_rdma_desc.length = desc_nob;
1963         tx->tx_nob_rdma = nob;
1964         if (*kgnilnd_tunables.kgn_bte_dlvr_mode)
1965                 tx->tx_rdma_desc.dlvr_mode = *kgnilnd_tunables.kgn_bte_dlvr_mode;
1966         /* prep final completion message */
1967         kgnilnd_init_msg(&tx->tx_msg, type, tx->tx_msg.gnm_srcnid);
1968         tx->tx_msg.gnm_u.completion.gncm_cookie = cookie;
1969         /* send actual size RDMA'd in retval */
1970         tx->tx_msg.gnm_u.completion.gncm_retval = nob;
1971
1972         kgnilnd_compute_rdma_cksum(tx, nob);
1973
1974         if (nob == 0) {
1975                 kgnilnd_queue_tx(conn, tx);
1976                 return 0;
1977         }
1978
1979         /* Don't lie (CLOSE == RDMA idle) */
1980         LASSERTF(!conn->gnc_close_sent, "tx %p on conn %p after close sent %d\n",
1981                  tx, conn, conn->gnc_close_sent);
1982
1983         GNIDBG_TX(D_NET, tx, "Post RDMA type 0x%02x conn %p dlvr_mode "
1984                 "0x%x cookie:"LPX64,
1985                 type, conn, tx->tx_rdma_desc.dlvr_mode, cookie);
1986
1987         /* set CQ dedicated for RDMA */
1988         tx->tx_rdma_desc.src_cq_hndl = conn->gnc_device->gnd_snd_rdma_cqh;
1989
1990         timestamp = jiffies;
1991         kgnilnd_conn_mutex_lock(&conn->gnc_rdma_mutex);
1992         kgnilnd_gl_mutex_lock(&conn->gnc_device->gnd_cq_mutex);
1993         /* delay in jiffies - we are really concerned only with things that
1994          * result in a schedule() or really holding this off for long times .
1995          * NB - mutex_lock could spin for 2 jiffies before going to sleep to wait */
1996         conn->gnc_device->gnd_mutex_delay += (long) jiffies - timestamp;
1997
1998         rrc = kgnilnd_post_rdma(conn->gnc_ephandle, &tx->tx_rdma_desc);
1999
2000         if (rrc == GNI_RC_ERROR_RESOURCE) {
2001                 kgnilnd_conn_mutex_unlock(&conn->gnc_rdma_mutex);
2002                 kgnilnd_gl_mutex_unlock(&conn->gnc_device->gnd_cq_mutex);
2003                 kgnilnd_unmap_buffer(tx, 0);
2004
2005                 if (tx->tx_buffer_copy != NULL) {
2006                         vfree(tx->tx_buffer_copy);
2007                         tx->tx_buffer_copy = NULL;
2008                 }
2009
2010                 spin_lock(&tx->tx_conn->gnc_device->gnd_lock);
2011                 kgnilnd_tx_add_state_locked(tx, NULL, tx->tx_conn,
2012                                             GNILND_TX_MAPQ, 0);
2013                 spin_unlock(&tx->tx_conn->gnc_device->gnd_lock);
2014                 kgnilnd_schedule_device(tx->tx_conn->gnc_device);
2015                 return -EAGAIN;
2016         }
2017
2018         spin_lock(&conn->gnc_list_lock);
2019         kgnilnd_tx_add_state_locked(tx, conn->gnc_peer, conn, GNILND_TX_LIVE_RDMAQ, 1);
2020         tx->tx_qtime = jiffies;
2021         spin_unlock(&conn->gnc_list_lock);
2022         kgnilnd_gl_mutex_unlock(&conn->gnc_device->gnd_cq_mutex);
2023         kgnilnd_conn_mutex_unlock(&conn->gnc_rdma_mutex);
2024
2025         /* XXX Nic: is this a place we should handle more errors for
2026          * robustness sake */
2027         LASSERT(rrc == GNI_RC_SUCCESS);
2028         return 0;
2029 }
2030
2031 kgn_rx_t *
2032 kgnilnd_alloc_rx(void)
2033 {
2034         kgn_rx_t        *rx;
2035
2036         rx = kmem_cache_alloc(kgnilnd_data.kgn_rx_cache, GFP_ATOMIC);
2037         if (rx == NULL) {
2038                 CERROR("failed to allocate rx\n");
2039                 return NULL;
2040         }
2041         CDEBUG(D_MALLOC, "slab-alloced 'rx': %lu at %p.\n",
2042                sizeof(*rx), rx);
2043
2044         /* no memset to zero, we'll always fill all members */
2045         return rx;
2046 }
2047
2048 /* release is to just free connection resources
2049  * we use this for the eager path after copying */
2050 void
2051 kgnilnd_release_msg(kgn_conn_t *conn)
2052 {
2053         gni_return_t    rrc;
2054         unsigned long   timestamp;
2055
2056         CDEBUG(D_NET, "consuming %p\n", conn);
2057
2058         timestamp = jiffies;
2059         kgnilnd_gl_mutex_lock(&conn->gnc_device->gnd_cq_mutex);
2060         /* delay in jiffies - we are really concerned only with things that
2061          * result in a schedule() or really holding this off for long times .
2062          * NB - mutex_lock could spin for 2 jiffies before going to sleep to wait */
2063         conn->gnc_device->gnd_mutex_delay += (long) jiffies - timestamp;
2064
2065         rrc = kgnilnd_smsg_release(conn->gnc_ephandle);
2066         kgnilnd_gl_mutex_unlock(&conn->gnc_device->gnd_cq_mutex);
2067
2068         LASSERTF(rrc == GNI_RC_SUCCESS, "bad rrc %d\n", rrc);
2069         GNIDBG_SMSG_CREDS(D_NET, conn);
2070
2071         return;
2072 }
2073
2074 void
2075 kgnilnd_consume_rx(kgn_rx_t *rx)
2076 {
2077         kgn_conn_t      *conn = rx->grx_conn;
2078         kgn_msg_t       *rxmsg = rx->grx_msg;
2079
2080         /* if we are eager, free the cache alloc'd msg */
2081         if (unlikely(rx->grx_eager)) {
2082                 LIBCFS_FREE(rxmsg, sizeof(*rxmsg) + *kgnilnd_tunables.kgn_max_immediate);
2083                 atomic_dec(&kgnilnd_data.kgn_neager_allocs);
2084
2085                 /* release ref from eager_recv */
2086                 kgnilnd_conn_decref(conn);
2087         } else {
2088                 GNIDBG_MSG(D_NET, rxmsg, "rx %p processed", rx);
2089                 kgnilnd_release_msg(conn);
2090         }
2091
2092         kmem_cache_free(kgnilnd_data.kgn_rx_cache, rx);
2093         CDEBUG(D_MALLOC, "slab-freed 'rx': %lu at %p.\n",
2094                sizeof(*rx), rx);
2095
2096         return;
2097 }
2098
2099 int
2100 kgnilnd_send(lnet_ni_t *ni, void *private, lnet_msg_t *lntmsg)
2101 {
2102         lnet_hdr_t       *hdr = &lntmsg->msg_hdr;
2103         int               type = lntmsg->msg_type;
2104         lnet_process_id_t target = lntmsg->msg_target;
2105         int               target_is_router = lntmsg->msg_target_is_router;
2106         int               routing = lntmsg->msg_routing;
2107         unsigned int      niov = lntmsg->msg_niov;
2108         struct iovec     *iov = lntmsg->msg_iov;
2109         lnet_kiov_t      *kiov = lntmsg->msg_kiov;
2110         unsigned int      offset = lntmsg->msg_offset;
2111         unsigned int      nob = lntmsg->msg_len;
2112         unsigned int      msg_vmflush = lntmsg->msg_vmflush;
2113         kgn_net_t        *net = ni->ni_data;
2114         kgn_tx_t         *tx;
2115         int               rc = 0;
2116         int               mpflag = 0;
2117         int               reverse_rdma_flag = *kgnilnd_tunables.kgn_reverse_rdma;
2118
2119         /* NB 'private' is different depending on what we're sending.... */
2120         LASSERT(!in_interrupt());
2121
2122         CDEBUG(D_NET, "sending msg type %d with %d bytes in %d frags to %s\n",
2123                type, nob, niov, libcfs_id2str(target));
2124
2125         LASSERTF(nob == 0 || niov > 0,
2126                 "lntmsg %p nob %d niov %d\n", lntmsg, nob, niov);
2127         LASSERTF(niov <= LNET_MAX_IOV,
2128                 "lntmsg %p niov %d\n", lntmsg, niov);
2129
2130         /* payload is either all vaddrs or all pages */
2131         LASSERTF(!(kiov != NULL && iov != NULL),
2132                 "lntmsg %p kiov %p iov %p\n", lntmsg, kiov, iov);
2133
2134         if (msg_vmflush)
2135                 mpflag = cfs_memory_pressure_get_and_set();
2136
2137         switch (type) {
2138         default:
2139                 CERROR("lntmsg %p with unexpected type %d\n",
2140                         lntmsg, type);
2141                 LBUG();
2142
2143         case LNET_MSG_ACK:
2144                 LASSERTF(nob == 0, "lntmsg %p nob %d\n",
2145                         lntmsg, nob);
2146                 break;
2147
2148         case LNET_MSG_GET:
2149                 LASSERT(niov == 0);
2150                 LASSERT(nob == 0);
2151
2152                 if (routing || target_is_router)
2153                         break;                  /* send IMMEDIATE */
2154
2155                 /* it is safe to do direct GET with out mapping buffer for RDMA as we
2156                  * check the eventual sink buffer here - if small enough, remote
2157                  * end is perfectly capable of returning data in short message -
2158                  * The magic is that we call lnet_parse in kgnilnd_recv with rdma_req=0
2159                  * for IMMEDIATE messages which will have it send a real reply instead
2160                  * of doing kgnilnd_recv to have the RDMA continued */
2161                 if (lntmsg->msg_md->md_length <= *kgnilnd_tunables.kgn_max_immediate)
2162                        break;
2163
2164                 if ((reverse_rdma_flag & GNILND_REVERSE_GET) == 0)
2165                         tx = kgnilnd_new_tx_msg(GNILND_MSG_GET_REQ, ni->ni_nid);
2166                 else
2167                         tx = kgnilnd_new_tx_msg(GNILND_MSG_GET_REQ_REV, ni->ni_nid);
2168
2169                 if (tx == NULL) {
2170                         rc = -ENOMEM;
2171                         goto out;
2172                 }
2173                 /* slightly different options as we might actually have a GET with a
2174                  * MD_KIOV set but a non-NULL md_iov.iov */
2175                 if ((lntmsg->msg_md->md_options & LNET_MD_KIOV) == 0)
2176                         rc = kgnilnd_setup_rdma_buffer(tx, lntmsg->msg_md->md_niov,
2177                                                       lntmsg->msg_md->md_iov.iov, NULL,
2178                                                       0, lntmsg->msg_md->md_length);
2179                 else
2180                         rc = kgnilnd_setup_rdma_buffer(tx, lntmsg->msg_md->md_niov,
2181                                                       NULL, lntmsg->msg_md->md_iov.kiov,
2182                                                       0, lntmsg->msg_md->md_length);
2183                 if (rc != 0) {
2184                         CERROR("unable to setup buffer: %d\n", rc);
2185                         kgnilnd_tx_done(tx, rc);
2186                         rc = -EIO;
2187                         goto out;
2188                 }
2189
2190                 tx->tx_lntmsg[1] = lnet_create_reply_msg(ni, lntmsg);
2191                 if (tx->tx_lntmsg[1] == NULL) {
2192                         CERROR("Can't create reply for GET to %s\n",
2193                                libcfs_nid2str(target.nid));
2194                         kgnilnd_tx_done(tx, rc);
2195                         rc = -EIO;
2196                         goto out;
2197                 }
2198
2199                 tx->tx_lntmsg[0] = lntmsg;
2200                 if ((reverse_rdma_flag & GNILND_REVERSE_GET) == 0)
2201                         tx->tx_msg.gnm_u.get.gngm_hdr = *hdr;
2202                 else
2203                         tx->tx_msg.gnm_u.putreq.gnprm_hdr = *hdr;
2204
2205                 /* rest of tx_msg is setup just before it is sent */
2206                 kgnilnd_launch_tx(tx, net, &target);
2207                 goto out;
2208         case LNET_MSG_REPLY:
2209         case LNET_MSG_PUT:
2210                 /* to save on MDDs, we'll handle short kiov by vmap'ing
2211                  * and sending via SMSG */
2212                 if (nob <= *kgnilnd_tunables.kgn_max_immediate)
2213                        break;
2214
2215                 if ((reverse_rdma_flag & GNILND_REVERSE_PUT) == 0)
2216                         tx = kgnilnd_new_tx_msg(GNILND_MSG_PUT_REQ, ni->ni_nid);
2217                 else
2218                         tx = kgnilnd_new_tx_msg(GNILND_MSG_PUT_REQ_REV, ni->ni_nid);
2219
2220                 if (tx == NULL) {
2221                         rc = -ENOMEM;
2222                         goto out;
2223                 }
2224
2225                 rc = kgnilnd_setup_rdma_buffer(tx, niov, iov, kiov, offset, nob);
2226                 if (rc != 0) {
2227                         kgnilnd_tx_done(tx, rc);
2228                         rc = -EIO;
2229                         goto out;
2230                 }
2231
2232                 tx->tx_lntmsg[0] = lntmsg;
2233                 if ((reverse_rdma_flag & GNILND_REVERSE_PUT) == 0)
2234                         tx->tx_msg.gnm_u.putreq.gnprm_hdr = *hdr;
2235                 else
2236                         tx->tx_msg.gnm_u.get.gngm_hdr = *hdr;
2237
2238                 /* rest of tx_msg is setup just before it is sent */
2239                 kgnilnd_launch_tx(tx, net, &target);
2240                 goto out;
2241         }
2242
2243         /* send IMMEDIATE */
2244
2245         LASSERTF(nob <= *kgnilnd_tunables.kgn_max_immediate,
2246                 "lntmsg 0x%p too large %d\n", lntmsg, nob);
2247
2248         tx = kgnilnd_new_tx_msg(GNILND_MSG_IMMEDIATE, ni->ni_nid);
2249         if (tx == NULL) {
2250                 rc = -ENOMEM;
2251                 goto out;
2252         }
2253
2254         rc = kgnilnd_setup_immediate_buffer(tx, niov, iov, kiov, offset, nob);
2255         if (rc != 0) {
2256                 kgnilnd_tx_done(tx, rc);
2257                 goto out;
2258         }
2259
2260         tx->tx_msg.gnm_u.immediate.gnim_hdr = *hdr;
2261         tx->tx_lntmsg[0] = lntmsg;
2262         kgnilnd_launch_tx(tx, net, &target);
2263
2264 out:
2265         /* use stored value as we could have already finalized lntmsg here from a failed launch */
2266         if (msg_vmflush)
2267                 cfs_memory_pressure_restore(mpflag);
2268         return rc;
2269 }
2270
2271 void
2272 kgnilnd_setup_rdma(lnet_ni_t *ni, kgn_rx_t *rx, lnet_msg_t *lntmsg, int mlen)
2273 {
2274         kgn_conn_t    *conn = rx->grx_conn;
2275         kgn_msg_t     *rxmsg = rx->grx_msg;
2276         unsigned int   niov = lntmsg->msg_niov;
2277         struct iovec  *iov = lntmsg->msg_iov;
2278         lnet_kiov_t   *kiov = lntmsg->msg_kiov;
2279         unsigned int   offset = lntmsg->msg_offset;
2280         unsigned int   nob = lntmsg->msg_len;
2281         int            done_type;
2282         kgn_tx_t      *tx;
2283         int            rc = 0;
2284
2285         switch (rxmsg->gnm_type) {
2286         case GNILND_MSG_PUT_REQ_REV:
2287                 done_type = GNILND_MSG_PUT_DONE_REV;
2288                 nob = mlen;
2289                 break;
2290         case GNILND_MSG_GET_REQ:
2291                 done_type = GNILND_MSG_GET_DONE;
2292                 break;
2293         default:
2294                 CERROR("invalid msg type %s (%d)\n",
2295                         kgnilnd_msgtype2str(rxmsg->gnm_type),
2296                         rxmsg->gnm_type);
2297                 LBUG();
2298         }
2299
2300         tx = kgnilnd_new_tx_msg(done_type, ni->ni_nid);
2301         if (tx == NULL)
2302                 goto failed_0;
2303
2304         rc = kgnilnd_set_tx_id(tx, conn);
2305         if (rc != 0)
2306                 goto failed_1;
2307
2308         rc = kgnilnd_setup_rdma_buffer(tx, niov, iov, kiov, offset, nob);
2309         if (rc != 0)
2310                 goto failed_1;
2311
2312         tx->tx_lntmsg[0] = lntmsg;
2313         tx->tx_getinfo = rxmsg->gnm_u.get;
2314
2315         /* we only queue from kgnilnd_recv - we might get called from other contexts
2316          * and we don't want to block the mutex in those cases */
2317
2318         spin_lock(&tx->tx_conn->gnc_device->gnd_lock);
2319         kgnilnd_tx_add_state_locked(tx, NULL, tx->tx_conn, GNILND_TX_MAPQ, 1);
2320         spin_unlock(&tx->tx_conn->gnc_device->gnd_lock);
2321         kgnilnd_schedule_device(tx->tx_conn->gnc_device);
2322
2323         return;
2324
2325  failed_1:
2326         kgnilnd_tx_done(tx, rc);
2327         kgnilnd_nak_rdma(conn, done_type, rc, rxmsg->gnm_u.get.gngm_cookie, ni->ni_nid);
2328  failed_0:
2329         lnet_finalize(ni, lntmsg, rc);
2330 }
2331
2332 int
2333 kgnilnd_eager_recv(lnet_ni_t *ni, void *private, lnet_msg_t *lntmsg,
2334                    void **new_private)
2335 {
2336         kgn_rx_t        *rx = private;
2337         kgn_conn_t      *conn = rx->grx_conn;
2338         kgn_msg_t       *rxmsg = rx->grx_msg;
2339         kgn_msg_t       *eagermsg = NULL;
2340         kgn_peer_t      *peer = NULL;
2341         kgn_conn_t      *found_conn = NULL;
2342
2343         GNIDBG_MSG(D_NET, rxmsg, "eager recv for conn %p, rxmsg %p, lntmsg %p",
2344                 conn, rxmsg, lntmsg);
2345
2346         if (rxmsg->gnm_payload_len > *kgnilnd_tunables.kgn_max_immediate) {
2347                 GNIDBG_MSG(D_ERROR, rxmsg, "payload too large %d",
2348                         rxmsg->gnm_payload_len);
2349                 return -EPROTO;
2350         }
2351         /* Grab a read lock so the connection doesnt disappear on us
2352          * while we look it up
2353          */
2354         read_lock(&kgnilnd_data.kgn_peer_conn_lock);
2355
2356         peer = kgnilnd_find_peer_locked(rxmsg->gnm_srcnid);
2357         if (peer != NULL)
2358                 found_conn = kgnilnd_find_conn_locked(peer);
2359
2360
2361         /* Verify the connection found is the same one that the message
2362          * is supposed to be using, if it is not output an error message
2363          * and return.
2364          */
2365         if (!peer || !found_conn
2366             || found_conn->gnc_peer_connstamp != rxmsg->gnm_connstamp) {
2367                 read_unlock(&kgnilnd_data.kgn_peer_conn_lock);
2368                 CERROR("Couldnt find matching peer %p or conn %p / %p\n",
2369                         peer, conn, found_conn);
2370                 if (found_conn) {
2371                         CERROR("Unexpected connstamp "LPX64"("LPX64" expected)"
2372                                 " from %s", rxmsg->gnm_connstamp,
2373                                 found_conn->gnc_peer_connstamp,
2374                                 libcfs_nid2str(peer->gnp_nid));
2375                 }
2376                 return -ENOTCONN;
2377         }
2378
2379         /* add conn ref to ensure it doesn't go away until all eager
2380          * messages processed */
2381         kgnilnd_conn_addref(conn);
2382
2383         /* Now that we have verified the connection is valid and added a
2384          * reference we can remove the read_lock on the peer_conn_lock */
2385         read_unlock(&kgnilnd_data.kgn_peer_conn_lock);
2386
2387         /* we have no credits or buffers for this message, so copy it
2388          * somewhere for a later kgnilnd_recv */
2389         if (atomic_read(&kgnilnd_data.kgn_neager_allocs) >=
2390                         *kgnilnd_tunables.kgn_eager_credits) {
2391                 CERROR("Out of eager credits to %s\n",
2392                         libcfs_nid2str(conn->gnc_peer->gnp_nid));
2393                 return -ENOMEM;
2394         }
2395
2396         atomic_inc(&kgnilnd_data.kgn_neager_allocs);
2397
2398         LIBCFS_ALLOC(eagermsg, sizeof(*eagermsg) + *kgnilnd_tunables.kgn_max_immediate);
2399         if (eagermsg == NULL) {
2400                 kgnilnd_conn_decref(conn);
2401                 CERROR("couldn't allocate eager rx message for conn %p to %s\n",
2402                         conn, libcfs_nid2str(conn->gnc_peer->gnp_nid));
2403                 return -ENOMEM;
2404         }
2405
2406         /* copy msg and payload */
2407         memcpy(eagermsg, rxmsg, sizeof(*rxmsg) + rxmsg->gnm_payload_len);
2408         rx->grx_msg = eagermsg;
2409         rx->grx_eager = 1;
2410
2411         /* stash this for lnet_finalize on cancel-on-conn-close */
2412         rx->grx_lntmsg = lntmsg;
2413
2414         /* keep the same rx_t, it just has a new grx_msg now */
2415         *new_private = private;
2416
2417         /* release SMSG buffer */
2418         kgnilnd_release_msg(conn);
2419
2420         return 0;
2421 }
2422
2423 int
2424 kgnilnd_recv(lnet_ni_t *ni, void *private, lnet_msg_t *lntmsg,
2425              int delayed, unsigned int niov,
2426              struct iovec *iov, lnet_kiov_t *kiov,
2427              unsigned int offset, unsigned int mlen, unsigned int rlen)
2428 {
2429         kgn_rx_t    *rx = private;
2430         kgn_conn_t  *conn = rx->grx_conn;
2431         kgn_msg_t   *rxmsg = rx->grx_msg;
2432         kgn_tx_t    *tx;
2433         int          rc = 0;
2434         __u32        pload_cksum;
2435         ENTRY;
2436
2437         LASSERT(!in_interrupt());
2438         LASSERTF(mlen <= rlen, "%d <= %d\n", mlen, rlen);
2439         /* Either all pages or all vaddrs */
2440         LASSERTF(!(kiov != NULL && iov != NULL), "kiov %p iov %p\n",
2441                 kiov, iov);
2442
2443         GNIDBG_MSG(D_NET, rxmsg, "conn %p, rxmsg %p, lntmsg %p"
2444                 " niov=%d kiov=%p iov=%p offset=%d mlen=%d rlen=%d",
2445                 conn, rxmsg, lntmsg,
2446                 niov, kiov, iov, offset, mlen, rlen);
2447
2448         /* we need to lock here as recv can be called from any context */
2449         read_lock(&kgnilnd_data.kgn_peer_conn_lock);
2450         if (rx->grx_eager && conn->gnc_state != GNILND_CONN_ESTABLISHED) {
2451                 read_unlock(&kgnilnd_data.kgn_peer_conn_lock);
2452
2453                 /* someone closed the conn after we copied this out, nuke it */
2454                 kgnilnd_consume_rx(rx);
2455                 lnet_finalize(ni, lntmsg, conn->gnc_error);
2456                 RETURN(0);
2457         }
2458         read_unlock(&kgnilnd_data.kgn_peer_conn_lock);
2459
2460         switch (rxmsg->gnm_type) {
2461         default:
2462                 GNIDBG_MSG(D_NETERROR, rxmsg, "conn %p, rx %p, rxmsg %p, lntmsg %p"
2463                 " niov=%d kiov=%p iov=%p offset=%d mlen=%d rlen=%d",
2464                 conn, rx, rxmsg, lntmsg, niov, kiov, iov, offset, mlen, rlen);
2465                 LBUG();
2466
2467         case GNILND_MSG_IMMEDIATE:
2468                 if (mlen > rxmsg->gnm_payload_len) {
2469                         GNIDBG_MSG(D_ERROR, rxmsg,
2470                                 "Immediate message from %s too big: %d > %d",
2471                                 libcfs_nid2str(conn->gnc_peer->gnp_nid), mlen,
2472                                 rxmsg->gnm_payload_len);
2473                         rc = -EINVAL;
2474                         kgnilnd_consume_rx(rx);
2475                         RETURN(rc);
2476                 }
2477
2478                 /* rxmsg[1] is a pointer to the payload, sitting in the buffer
2479                  * right after the kgn_msg_t header - so just 'cute' way of saying
2480                  * rxmsg + sizeof(kgn_msg_t) */
2481
2482                 /* check payload checksum if sent */
2483
2484                 if (*kgnilnd_tunables.kgn_checksum >= 2 &&
2485                         !rxmsg->gnm_payload_cksum &&
2486                         rxmsg->gnm_payload_len != 0)
2487                         GNIDBG_MSG(D_WARNING, rxmsg, "no msg payload checksum when enabled");
2488
2489                 if (rxmsg->gnm_payload_cksum != 0) {
2490                         /* gnm_payload_len set in kgnilnd_sendmsg from tx->tx_nob,
2491                          * which is what is used to calculate the cksum on the TX side */
2492                         pload_cksum = kgnilnd_cksum(&rxmsg[1], rxmsg->gnm_payload_len);
2493
2494                         if (rxmsg->gnm_payload_cksum != pload_cksum) {
2495                                 GNIDBG_MSG(D_NETERROR, rxmsg,
2496                                            "Bad payload checksum (%x expected %x)",
2497                                             pload_cksum, rxmsg->gnm_payload_cksum);
2498                                 switch (*kgnilnd_tunables.kgn_checksum_dump) {
2499                                 case 2:
2500                                         kgnilnd_dump_blob(D_BUFFS, "bad payload checksum",
2501                                                           &rxmsg[1], rxmsg->gnm_payload_len);
2502                                         /* fall through to dump */
2503                                 case 1:
2504                                         libcfs_debug_dumplog();
2505                                         break;
2506                                 default:
2507                                         break;
2508                                 }
2509                                 rc = -ENOKEY;
2510                                 /* checksum problems are fatal, kill the conn */
2511                                 kgnilnd_consume_rx(rx);
2512                                 kgnilnd_close_conn(conn, rc);
2513                                 RETURN(rc);
2514                         }
2515                 }
2516
2517                 if (kiov != NULL)
2518                         lnet_copy_flat2kiov(
2519                                 niov, kiov, offset,
2520                                 *kgnilnd_tunables.kgn_max_immediate,
2521                                 &rxmsg[1], 0, mlen);
2522                 else
2523                         lnet_copy_flat2iov(
2524                                 niov, iov, offset,
2525                                 *kgnilnd_tunables.kgn_max_immediate,
2526                                 &rxmsg[1], 0, mlen);
2527
2528                 kgnilnd_consume_rx(rx);
2529                 lnet_finalize(ni, lntmsg, 0);
2530                 RETURN(0);
2531
2532         case GNILND_MSG_PUT_REQ:
2533                 /* LNET wants to truncate or drop transaction, sending NAK */
2534                 if (mlen == 0) {
2535                         kgnilnd_consume_rx(rx);
2536                         lnet_finalize(ni, lntmsg, 0);
2537
2538                         /* only error if lntmsg == NULL, otherwise we are just
2539                          * short circuiting the rdma process of 0 bytes */
2540                         kgnilnd_nak_rdma(conn, rxmsg->gnm_type,
2541                                         lntmsg == NULL ? -ENOENT : 0,
2542                                         rxmsg->gnm_u.get.gngm_cookie,
2543                                         ni->ni_nid);
2544                         RETURN(0);
2545                 }
2546                 /* sending ACK with sink buff. info */
2547                 tx = kgnilnd_new_tx_msg(GNILND_MSG_PUT_ACK, ni->ni_nid);
2548                 if (tx == NULL) {
2549                         kgnilnd_consume_rx(rx);
2550                         RETURN(-ENOMEM);
2551                 }
2552
2553                 rc = kgnilnd_set_tx_id(tx, conn);
2554                 if (rc != 0) {
2555                         GOTO(nak_put_req, rc);
2556                 }
2557
2558                 rc = kgnilnd_setup_rdma_buffer(tx, niov, iov, kiov, offset, mlen);
2559                 if (rc != 0) {
2560                         GOTO(nak_put_req, rc);
2561                 }
2562
2563                 tx->tx_msg.gnm_u.putack.gnpam_src_cookie =
2564                         rxmsg->gnm_u.putreq.gnprm_cookie;
2565                 tx->tx_msg.gnm_u.putack.gnpam_dst_cookie = tx->tx_id.txe_cookie;
2566                 tx->tx_msg.gnm_u.putack.gnpam_desc.gnrd_addr =
2567                         (__u64)((unsigned long)tx->tx_buffer);
2568                 tx->tx_msg.gnm_u.putack.gnpam_desc.gnrd_nob = mlen;
2569
2570                 tx->tx_lntmsg[0] = lntmsg; /* finalize this on RDMA_DONE */
2571                 tx->tx_qtime = jiffies;
2572                 /* we only queue from kgnilnd_recv - we might get called from other contexts
2573                  * and we don't want to block the mutex in those cases */
2574
2575                 spin_lock(&tx->tx_conn->gnc_device->gnd_lock);
2576                 kgnilnd_tx_add_state_locked(tx, NULL, tx->tx_conn, GNILND_TX_MAPQ, 1);
2577                 spin_unlock(&tx->tx_conn->gnc_device->gnd_lock);
2578                 kgnilnd_schedule_device(tx->tx_conn->gnc_device);
2579
2580                 kgnilnd_consume_rx(rx);
2581                 RETURN(0);
2582
2583 nak_put_req:
2584                 /* make sure we send an error back when the PUT fails */
2585                 kgnilnd_nak_rdma(conn, rxmsg->gnm_type, rc, rxmsg->gnm_u.get.gngm_cookie, ni->ni_nid);
2586                 kgnilnd_tx_done(tx, rc);
2587                 kgnilnd_consume_rx(rx);
2588
2589                 /* return magic LNet network error */
2590                 RETURN(-EIO);
2591         case GNILND_MSG_GET_REQ_REV:
2592                 /* LNET wants to truncate or drop transaction, sending NAK */
2593                 if (mlen == 0) {
2594                         kgnilnd_consume_rx(rx);
2595                         lnet_finalize(ni, lntmsg, 0);
2596
2597                         /* only error if lntmsg == NULL, otherwise we are just
2598                          * short circuiting the rdma process of 0 bytes */
2599                         kgnilnd_nak_rdma(conn, rxmsg->gnm_type,
2600                                         lntmsg == NULL ? -ENOENT : 0,
2601                                         rxmsg->gnm_u.get.gngm_cookie,
2602                                         ni->ni_nid);
2603                         RETURN(0);
2604                 }
2605                 /* lntmsg can be null when parsing a LNET_GET */
2606                 if (lntmsg != NULL) {
2607                         /* sending ACK with sink buff. info */
2608                         tx = kgnilnd_new_tx_msg(GNILND_MSG_GET_ACK_REV, ni->ni_nid);
2609                         if (tx == NULL) {
2610                                 kgnilnd_consume_rx(rx);
2611                                 RETURN(-ENOMEM);
2612                         }
2613
2614                         rc = kgnilnd_set_tx_id(tx, conn);
2615                         if (rc != 0)
2616                                 GOTO(nak_get_req_rev, rc);
2617
2618
2619                         rc = kgnilnd_setup_rdma_buffer(tx, niov, iov, kiov, offset, mlen);
2620                         if (rc != 0)
2621                                 GOTO(nak_get_req_rev, rc);
2622
2623
2624                         tx->tx_msg.gnm_u.putack.gnpam_src_cookie =
2625                                 rxmsg->gnm_u.putreq.gnprm_cookie;
2626                         tx->tx_msg.gnm_u.putack.gnpam_dst_cookie = tx->tx_id.txe_cookie;
2627                         tx->tx_msg.gnm_u.putack.gnpam_desc.gnrd_addr =
2628                                 (__u64)((unsigned long)tx->tx_buffer);
2629                         tx->tx_msg.gnm_u.putack.gnpam_desc.gnrd_nob = mlen;
2630
2631                         tx->tx_lntmsg[0] = lntmsg; /* finalize this on RDMA_DONE */
2632
2633                         /* we only queue from kgnilnd_recv - we might get called from other contexts
2634                          * and we don't want to block the mutex in those cases */
2635
2636                         spin_lock(&tx->tx_conn->gnc_device->gnd_lock);
2637                         kgnilnd_tx_add_state_locked(tx, NULL, tx->tx_conn, GNILND_TX_MAPQ, 1);
2638                         spin_unlock(&tx->tx_conn->gnc_device->gnd_lock);
2639                         kgnilnd_schedule_device(tx->tx_conn->gnc_device);
2640                 } else {
2641                         /* No match */
2642                         kgnilnd_nak_rdma(conn, rxmsg->gnm_type,
2643                                         -ENOENT,
2644                                         rxmsg->gnm_u.get.gngm_cookie,
2645                                         ni->ni_nid);
2646                 }
2647
2648                 kgnilnd_consume_rx(rx);
2649                 RETURN(0);
2650
2651 nak_get_req_rev:
2652                 /* make sure we send an error back when the GET fails */
2653                 kgnilnd_nak_rdma(conn, rxmsg->gnm_type, rc, rxmsg->gnm_u.get.gngm_cookie, ni->ni_nid);
2654                 kgnilnd_tx_done(tx, rc);
2655                 kgnilnd_consume_rx(rx);
2656
2657                 /* return magic LNet network error */
2658                 RETURN(-EIO);
2659
2660
2661         case GNILND_MSG_PUT_REQ_REV:
2662                 /* LNET wants to truncate or drop transaction, sending NAK */
2663                 if (mlen == 0) {
2664                         kgnilnd_consume_rx(rx);
2665                         lnet_finalize(ni, lntmsg, 0);
2666
2667                         /* only error if lntmsg == NULL, otherwise we are just
2668                          * short circuiting the rdma process of 0 bytes */
2669                         kgnilnd_nak_rdma(conn, rxmsg->gnm_type,
2670                                         lntmsg == NULL ? -ENOENT : 0,
2671                                         rxmsg->gnm_u.get.gngm_cookie,
2672                                         ni->ni_nid);
2673                         RETURN(0);
2674                 }
2675
2676                 if (lntmsg != NULL) {
2677                         /* Matched! */
2678                         kgnilnd_setup_rdma(ni, rx, lntmsg, mlen);
2679                 } else {
2680                         /* No match */
2681                         kgnilnd_nak_rdma(conn, rxmsg->gnm_type,
2682                                         -ENOENT,
2683                                         rxmsg->gnm_u.get.gngm_cookie,
2684                                         ni->ni_nid);
2685                 }
2686                 kgnilnd_consume_rx(rx);
2687                 RETURN(0);
2688         case GNILND_MSG_GET_REQ:
2689                 if (lntmsg != NULL) {
2690                         /* Matched! */
2691                         kgnilnd_setup_rdma(ni, rx, lntmsg, mlen);
2692                 } else {
2693                         /* No match */
2694                         kgnilnd_nak_rdma(conn, rxmsg->gnm_type,
2695                                         -ENOENT,
2696                                         rxmsg->gnm_u.get.gngm_cookie,
2697                                         ni->ni_nid);
2698                 }
2699                 kgnilnd_consume_rx(rx);
2700                 RETURN(0);
2701         }
2702         RETURN(0);
2703 }
2704
2705 /* needs write_lock on kgn_peer_conn_lock held */
2706 int
2707 kgnilnd_check_conn_timeouts_locked(kgn_conn_t *conn)
2708 {
2709         unsigned long      timeout, keepalive;
2710         unsigned long      now = jiffies;
2711         unsigned long      newest_last_rx;
2712         kgn_tx_t          *tx;
2713
2714         /* given that we found this conn hanging off a peer, it better damned
2715          * well be connected */
2716         LASSERTF(conn->gnc_state == GNILND_CONN_ESTABLISHED,
2717                  "conn 0x%p->%s with bad state%s\n", conn,
2718                  conn->gnc_peer ? libcfs_nid2str(conn->gnc_peer->gnp_nid)
2719                                : "<?>",
2720                  kgnilnd_conn_state2str(conn));
2721
2722         CDEBUG(D_NET, "checking conn %p->%s timeout %d keepalive %d "
2723                       "rx_diff %lu tx_diff %lu\n",
2724                 conn, libcfs_nid2str(conn->gnc_peer->gnp_nid),
2725                 conn->gnc_timeout, GNILND_TO2KA(conn->gnc_timeout),
2726                 cfs_duration_sec(now - conn->gnc_last_rx_cq),
2727                 cfs_duration_sec(now - conn->gnc_last_tx));
2728
2729         timeout = cfs_time_seconds(conn->gnc_timeout);
2730         keepalive = cfs_time_seconds(GNILND_TO2KA(conn->gnc_timeout));
2731
2732         /* just in case our lack of RX msg processing is gumming up the works - give the
2733          * remove an extra chance */
2734
2735         newest_last_rx = GNILND_LASTRX(conn);
2736
2737         if (time_after_eq(now, newest_last_rx + timeout)) {
2738                 uint32_t level = D_CONSOLE|D_NETERROR;
2739
2740                 if (conn->gnc_peer->gnp_down == GNILND_RCA_NODE_DOWN) {
2741                         level = D_NET;
2742                 }
2743                         GNIDBG_CONN(level, conn,
2744                         "No gnilnd traffic received from %s for %lu "
2745                         "seconds, terminating connection. Is node down? ",
2746                         libcfs_nid2str(conn->gnc_peer->gnp_nid),
2747                         cfs_duration_sec(now - newest_last_rx));
2748                 return -ETIMEDOUT;
2749         }
2750
2751         /* we don't timeout on last_tx stalls - we are going to trust the
2752          * underlying network to let us know when sends are failing.
2753          * At worst, the peer will timeout our RX stamp and drop the connection
2754          * at that point. We'll then see his CLOSE or at worst his RX
2755          * stamp stop and drop the connection on our end */
2756
2757         if (time_after_eq(now, conn->gnc_last_tx + keepalive)) {
2758                 CDEBUG(D_NET, "sending NOOP -> %s (%p idle %lu(%lu)) "
2759                        "last %lu/%lu/%lu %lus/%lus/%lus\n",
2760                        libcfs_nid2str(conn->gnc_peer->gnp_nid), conn,
2761                        cfs_duration_sec(jiffies - conn->gnc_last_tx),
2762                        keepalive,
2763                        conn->gnc_last_noop_want, conn->gnc_last_noop_sent,
2764                        conn->gnc_last_noop_cq,
2765                        cfs_duration_sec(jiffies - conn->gnc_last_noop_want),
2766                        cfs_duration_sec(jiffies - conn->gnc_last_noop_sent),
2767                        cfs_duration_sec(jiffies - conn->gnc_last_noop_cq));
2768                 set_mb(conn->gnc_last_noop_want, jiffies);
2769                 atomic_inc(&conn->gnc_reaper_noop);
2770                 if (CFS_FAIL_CHECK(CFS_FAIL_GNI_NOOP_SEND))
2771                         return 0;
2772
2773                 tx = kgnilnd_new_tx_msg(GNILND_MSG_NOOP, conn->gnc_peer->gnp_net->gnn_ni->ni_nid);
2774                 if (tx == NULL)
2775                         return 0;
2776                 kgnilnd_queue_tx(conn, tx);
2777         }
2778
2779         return 0;
2780 }
2781
2782 /* needs write_lock on kgn_peer_conn_lock held */
2783 void
2784 kgnilnd_check_peer_timeouts_locked(kgn_peer_t *peer, struct list_head *todie,
2785                                     struct list_head *souls)
2786 {
2787         unsigned long           timeout;
2788         kgn_conn_t             *conn, *connN = NULL;
2789         kgn_tx_t               *tx, *txN;
2790         int                     rc = 0;
2791         int                     count = 0;
2792         int                     reconnect;
2793         int                     to_reconn;
2794         short                   releaseconn = 0;
2795         unsigned long           first_rx = 0;
2796         int                     purgatory_conn_cnt = 0;
2797
2798         CDEBUG(D_NET, "checking peer 0x%p->%s for timeouts; interval %lus\n",
2799                 peer, libcfs_nid2str(peer->gnp_nid),
2800                 peer->gnp_reconnect_interval);
2801
2802         timeout = cfs_time_seconds(MAX(*kgnilnd_tunables.kgn_timeout,
2803                                        GNILND_MIN_TIMEOUT));
2804
2805         conn = kgnilnd_find_conn_locked(peer);
2806         if (conn) {
2807                 /* if there is a valid conn, check the queues for timeouts */
2808                 rc = kgnilnd_check_conn_timeouts_locked(conn);
2809                 if (rc) {
2810                         if (CFS_FAIL_CHECK(CFS_FAIL_GNI_RX_CLOSE_CLOSING)) {
2811                                 /* simulate a RX CLOSE after the timeout but before
2812                                  * the scheduler thread gets it */
2813                                 conn->gnc_close_recvd = GNILND_CLOSE_INJECT1;
2814                                 conn->gnc_peer_error = -ETIMEDOUT;
2815                         }
2816                         /* Once we mark closed, any of the scheduler threads could
2817                          * get it and move through before we hit the fail loc code */
2818                         kgnilnd_close_conn_locked(conn, rc);
2819                 } else {
2820                         /* first_rx is used to decide when to release a conn from purgatory.
2821                          */
2822                         first_rx = conn->gnc_first_rx;
2823                 }
2824         }
2825
2826         /* now regardless of starting new conn, find tx on peer queue that
2827          * are old and smell bad - do this first so we don't trigger
2828          * reconnect on empty queue if we timeout all */
2829         list_for_each_entry_safe(tx, txN, &peer->gnp_tx_queue, tx_list) {
2830                 if (time_after_eq(jiffies, tx->tx_qtime + timeout)) {
2831                         if (count == 0) {
2832                                 LCONSOLE_INFO("could not send to %s due to connection"
2833                                        " setup failure after %lu seconds\n",
2834                                        libcfs_nid2str(peer->gnp_nid),
2835                                        cfs_duration_sec(jiffies - tx->tx_qtime));
2836                         }
2837                         kgnilnd_tx_del_state_locked(tx, peer, NULL,
2838                                                    GNILND_TX_ALLOCD);
2839                         list_add_tail(&tx->tx_list, todie);
2840                         count++;
2841                 }
2842         }
2843
2844         if (count || peer->gnp_connecting == GNILND_PEER_KILL) {
2845                 CDEBUG(D_NET, "canceling %d tx for peer 0x%p->%s\n",
2846                         count, peer, libcfs_nid2str(peer->gnp_nid));
2847                 /* if we nuked all the TX, stop peer connection attempt (if there is one..) */
2848                 if (list_empty(&peer->gnp_tx_queue) ||
2849                         peer->gnp_connecting == GNILND_PEER_KILL) {
2850                         /* we pass down todie to use a common function - but we know there are
2851                          * no TX to add */
2852                         kgnilnd_cancel_peer_connect_locked(peer, todie);
2853                 }
2854         }
2855
2856         /* Don't reconnect if we are still trying to clear out old conns.
2857          * This prevents us sending traffic on the new mbox before ensuring we are done
2858          * with the old one */
2859         reconnect = (peer->gnp_down == GNILND_RCA_NODE_UP) &&
2860                     (atomic_read(&peer->gnp_dirty_eps) == 0);
2861
2862         /* fast reconnect after a timeout */
2863         to_reconn = !conn &&
2864                     (peer->gnp_last_errno == -ETIMEDOUT) &&
2865                     *kgnilnd_tunables.kgn_fast_reconn;
2866
2867         /* if we are not connected and there are tx on the gnp_tx_queue waiting
2868          * to be sent, we'll check the reconnect interval and fire up a new
2869          * connection request */
2870
2871         if (reconnect &&
2872             (peer->gnp_connecting == GNILND_PEER_IDLE) &&
2873             (time_after_eq(jiffies, peer->gnp_reconnect_time)) &&
2874             (!list_empty(&peer->gnp_tx_queue) || to_reconn)) {
2875
2876                 CDEBUG(D_NET, "starting connect to %s\n",
2877                         libcfs_nid2str(peer->gnp_nid));
2878                 LASSERTF(peer->gnp_connecting == GNILND_PEER_IDLE, "Peer was idle and we"
2879                         "have a write_lock, state issue %d\n", peer->gnp_connecting);
2880
2881                 peer->gnp_connecting = GNILND_PEER_CONNECT;
2882                 kgnilnd_peer_addref(peer); /* extra ref for connd */
2883
2884                 spin_lock(&peer->gnp_net->gnn_dev->gnd_connd_lock);
2885                 list_add_tail(&peer->gnp_connd_list,
2886                               &peer->gnp_net->gnn_dev->gnd_connd_peers);
2887                 spin_unlock(&peer->gnp_net->gnn_dev->gnd_connd_lock);
2888
2889                 kgnilnd_schedule_dgram(peer->gnp_net->gnn_dev);
2890         }
2891
2892         /* fail_loc to allow us to delay release of purgatory */
2893         if (CFS_FAIL_CHECK(CFS_FAIL_GNI_PURG_REL_DELAY))
2894                 return;
2895
2896         /* This check allows us to verify that the new conn is actually being used. This allows us to
2897          * pull the old conns out of purgatory if they have actually seen traffic.
2898          * We only release a conn from purgatory during stack reset, admin command, or when a peer reconnects
2899          */
2900         if (first_rx &&
2901                 time_after(jiffies, first_rx + cfs_time_seconds(*kgnilnd_tunables.kgn_hardware_timeout))) {
2902                 CDEBUG(D_INFO, "We can release peer %s conn's from purgatory %lu\n",
2903                         libcfs_nid2str(peer->gnp_nid), first_rx + cfs_time_seconds(*kgnilnd_tunables.kgn_hardware_timeout));
2904                 releaseconn = 1;
2905         }
2906
2907         list_for_each_entry_safe (conn, connN, &peer->gnp_conns, gnc_list) {
2908         /* check for purgatory timeouts */
2909                 if (conn->gnc_in_purgatory) {
2910                         /* We cannot detach this conn from purgatory if it has not been closed so we reschedule it
2911                          * that way the next time we check it we can detach it from purgatory
2912                          */
2913
2914                         if (conn->gnc_state != GNILND_CONN_DONE) {
2915                                 /* Skip over conns that are currently not DONE. If they arent already scheduled
2916                                  * for completion something in the state machine is broken.
2917                                  */
2918                                 continue;
2919                         }
2920
2921                         /* We only detach a conn that is in purgatory if we have received a close message,
2922                          * we have a new valid connection that has successfully received data, or an admin
2923                          * command tells us we need to detach.
2924                          */
2925
2926                         if (conn->gnc_close_recvd || releaseconn || conn->gnc_needs_detach) {
2927                                 unsigned long   waiting;
2928
2929                                 waiting = (long) jiffies - conn->gnc_last_rx_cq;
2930
2931                                 /* C.E: The remote peer is expected to close the
2932                                  * connection (see kgnilnd_check_conn_timeouts)
2933                                  * via the reaper thread and nuke out the MDD and
2934                                  * FMA resources after conn->gnc_timeout has expired
2935                                  * without an FMA RX */
2936                                 CDEBUG(D_NET, "Reconnected to %s in %lds or admin forced detach, dropping "
2937                                         " held resources\n",
2938                                         libcfs_nid2str(conn->gnc_peer->gnp_nid),
2939                                         cfs_duration_sec(waiting));
2940
2941                                 kgnilnd_detach_purgatory_locked(conn, souls);
2942                         } else {
2943                                 purgatory_conn_cnt++;
2944                         }
2945                 }
2946         }
2947
2948         /* If we have too many connections in purgatory we could run out of
2949          * resources. Limit the number of connections to a tunable number,
2950          * clean up to the minimum all in one fell swoop... there are
2951          * situations where dvs will retry tx's and we can eat up several
2952          * hundread connection requests at once.
2953          */
2954         if (purgatory_conn_cnt > *kgnilnd_tunables.kgn_max_purgatory) {
2955                 list_for_each_entry_safe(conn, connN, &peer->gnp_conns,
2956                                          gnc_list) {
2957                         if (conn->gnc_in_purgatory &&
2958                             conn->gnc_state == GNILND_CONN_DONE) {
2959                                 CDEBUG(D_NET, "Dropping Held resource due to"
2960                                               " resource limits being hit\n");
2961                                 kgnilnd_detach_purgatory_locked(conn, souls);
2962
2963                                 if (purgatory_conn_cnt-- <
2964                                     *kgnilnd_tunables.kgn_max_purgatory)
2965                                         break;
2966                         }
2967                 }
2968         }
2969
2970         return;
2971 }
2972
2973 void
2974 kgnilnd_reaper_check(int idx)
2975 {
2976         struct list_head  *peers = &kgnilnd_data.kgn_peers[idx];
2977         struct list_head  *ctmp, *ctmpN;
2978         struct list_head   geriatrics;
2979         struct list_head   souls;
2980
2981         INIT_LIST_HEAD(&geriatrics);
2982         INIT_LIST_HEAD(&souls);
2983
2984         write_lock(&kgnilnd_data.kgn_peer_conn_lock);
2985
2986         list_for_each_safe(ctmp, ctmpN, peers) {
2987                 kgn_peer_t        *peer = NULL;
2988
2989                 /* don't timeout stuff if the network is mucked or shutting down */
2990                 if (kgnilnd_check_hw_quiesce()) {
2991                         break;
2992                 }
2993                 peer = list_entry(ctmp, kgn_peer_t, gnp_list);
2994
2995                 kgnilnd_check_peer_timeouts_locked(peer, &geriatrics, &souls);
2996         }
2997
2998         write_unlock(&kgnilnd_data.kgn_peer_conn_lock);
2999
3000         kgnilnd_txlist_done(&geriatrics, -EHOSTUNREACH);
3001         kgnilnd_release_purgatory_list(&souls);
3002 }
3003
3004 void
3005 kgnilnd_update_reaper_timeout(long timeout)
3006 {
3007         LASSERT(timeout > 0);
3008
3009         spin_lock(&kgnilnd_data.kgn_reaper_lock);
3010
3011         if (timeout < kgnilnd_data.kgn_new_min_timeout)
3012                 kgnilnd_data.kgn_new_min_timeout = timeout;
3013
3014         spin_unlock(&kgnilnd_data.kgn_reaper_lock);
3015 }
3016
3017 static void
3018 kgnilnd_reaper_poke_with_stick(unsigned long arg)
3019 {
3020         wake_up(&kgnilnd_data.kgn_reaper_waitq);
3021 }
3022
3023 int
3024 kgnilnd_reaper(void *arg)
3025 {
3026         long               timeout;
3027         int                i;
3028         int                hash_index = 0;
3029         unsigned long      next_check_time = jiffies;
3030         long               current_min_timeout = MAX_SCHEDULE_TIMEOUT;
3031         struct timer_list  timer;
3032         DEFINE_WAIT(wait);
3033
3034         cfs_block_allsigs();
3035
3036         /* all gnilnd threads need to run fairly urgently */
3037         set_user_nice(current, *kgnilnd_tunables.kgn_nice);
3038         spin_lock(&kgnilnd_data.kgn_reaper_lock);
3039
3040         while (!kgnilnd_data.kgn_shutdown) {
3041                 /* I wake up every 'p' seconds to check for timeouts on some
3042                  * more peers.  I try to check every connection 'n' times
3043                  * within the global minimum of all keepalive and timeout
3044                  * intervals, to ensure I attend to every connection within
3045                  * (n+1)/n times its timeout intervals. */
3046                 const int     p = GNILND_REAPER_THREAD_WAKE;
3047                 const int     n = GNILND_REAPER_NCHECKS;
3048                 int           chunk;
3049                 /* to quiesce or to not quiesce, that is the question */
3050                 if (unlikely(kgnilnd_data.kgn_quiesce_trigger)) {
3051                         spin_unlock(&kgnilnd_data.kgn_reaper_lock);
3052                         KGNILND_SPIN_QUIESCE;
3053                         spin_lock(&kgnilnd_data.kgn_reaper_lock);
3054                 }
3055
3056                 /* careful with the jiffy wrap... */
3057                 timeout = (long)(next_check_time - jiffies);
3058
3059                 if (timeout > 0) {
3060                         prepare_to_wait(&kgnilnd_data.kgn_reaper_waitq, &wait,
3061                                         TASK_INTERRUPTIBLE);
3062                         spin_unlock(&kgnilnd_data.kgn_reaper_lock);
3063                         setup_timer(&timer, kgnilnd_reaper_poke_with_stick,
3064                                     next_check_time);
3065                         mod_timer(&timer, (long) jiffies + timeout);
3066
3067                         /* check flag variables before comitting */
3068                         if (!kgnilnd_data.kgn_shutdown &&
3069                             !kgnilnd_data.kgn_quiesce_trigger) {
3070                                 CDEBUG(D_INFO, "schedule timeout %ld (%lu sec)\n",
3071                                        timeout, cfs_duration_sec(timeout));
3072                                 schedule();
3073                                 CDEBUG(D_INFO, "awake after schedule\n");
3074                         }
3075
3076                         del_singleshot_timer_sync(&timer);
3077                         spin_lock(&kgnilnd_data.kgn_reaper_lock);
3078                         finish_wait(&kgnilnd_data.kgn_reaper_waitq, &wait);
3079                         continue;
3080                 }
3081
3082                 /* new_min_timeout is set from the conn timeouts and keepalive
3083                  * this should end up with a min timeout of
3084                  * GNILND_TIMEOUT2KEEPALIVE(t) or roughly LND_TIMEOUT/2 */
3085                 if (kgnilnd_data.kgn_new_min_timeout < current_min_timeout) {
3086                         current_min_timeout = kgnilnd_data.kgn_new_min_timeout;
3087                         CDEBUG(D_NET, "Set new min timeout %ld\n",
3088                                current_min_timeout);
3089                 }
3090
3091                 spin_unlock(&kgnilnd_data.kgn_reaper_lock);
3092
3093                 /* Compute how many table entries to check now so I get round
3094                  * the whole table fast enough given that I do this at fixed
3095                  * intervals of 'p' seconds) */
3096                 chunk = *kgnilnd_tunables.kgn_peer_hash_size;
3097                 if (kgnilnd_data.kgn_new_min_timeout > n * p)
3098                         chunk = (chunk * n * p) /
3099                                 kgnilnd_data.kgn_new_min_timeout;
3100                 if (chunk == 0)
3101                         chunk = 1;
3102                 for (i = 0; i < chunk; i++) {
3103                         kgnilnd_reaper_check(hash_index);
3104                         hash_index = (hash_index + 1) %
3105                                 *kgnilnd_tunables.kgn_peer_hash_size;
3106                 }
3107                 next_check_time = (long) jiffies + cfs_time_seconds(p);
3108                 CDEBUG(D_INFO, "next check at %lu or in %d sec\n", next_check_time, p);
3109
3110                 spin_lock(&kgnilnd_data.kgn_reaper_lock);
3111         }
3112
3113         spin_unlock(&kgnilnd_data.kgn_reaper_lock);
3114
3115         kgnilnd_thread_fini();
3116         return 0;
3117 }
3118
3119 int
3120 kgnilnd_recv_bte_get(kgn_tx_t *tx) {
3121         unsigned niov, offset, nob;
3122         lnet_kiov_t     *kiov;
3123         lnet_msg_t *lntmsg = tx->tx_lntmsg[0];
3124         kgnilnd_parse_lnet_rdma(lntmsg, &niov, &offset, &nob, &kiov, tx->tx_nob_rdma);
3125
3126         if (kiov != NULL) {
3127                 lnet_copy_flat2kiov(
3128                         niov, kiov, offset,
3129                         nob,
3130                         tx->tx_buffer_copy + tx->tx_offset, 0, nob);
3131         } else {
3132                 memcpy(tx->tx_buffer, tx->tx_buffer_copy + tx->tx_offset, nob);
3133         }
3134         return 0;
3135 }
3136
3137
3138 int
3139 kgnilnd_check_rdma_cq(kgn_device_t *dev)
3140 {
3141         gni_return_t           rrc;
3142         gni_post_descriptor_t *desc;
3143         __u64                  event_data;
3144         kgn_tx_ev_id_t         ev_id;
3145         char                   err_str[256];
3146         int                    should_retry, rc;
3147         long                   num_processed = 0;
3148         kgn_conn_t            *conn = NULL;
3149         kgn_tx_t              *tx = NULL;
3150         kgn_rdma_desc_t       *rdesc;
3151         unsigned int           rnob;
3152         __u64                  rcookie;
3153
3154         for (;;) {
3155                 /* make sure we don't keep looping if we need to reset */
3156                 if (unlikely(kgnilnd_data.kgn_quiesce_trigger)) {
3157                         return num_processed;
3158                 }
3159                 rc = kgnilnd_mutex_trylock(&dev->gnd_cq_mutex);
3160                 if (!rc) {
3161                         /* we didn't get the mutex, so return that there is still work
3162                          * to be done */
3163                         return 1;
3164                 }
3165                 if (CFS_FAIL_CHECK(CFS_FAIL_GNI_DELAY_RDMA)) {
3166                         /* a bit gross - but we need a good way to test for
3167                          * delayed RDMA completions and the easiest way to do
3168                          * that is to delay the RDMA CQ events */
3169                         rrc = GNI_RC_NOT_DONE;
3170                 } else {
3171                         rrc = kgnilnd_cq_get_event(dev->gnd_snd_rdma_cqh, &event_data);
3172                 }
3173
3174                 if (rrc == GNI_RC_NOT_DONE) {
3175                         kgnilnd_gl_mutex_unlock(&dev->gnd_cq_mutex);
3176                         CDEBUG(D_INFO, "SEND RDMA CQ %d empty processed %ld\n",
3177                                dev->gnd_id, num_processed);
3178                         return num_processed;
3179                 }
3180                 dev->gnd_sched_alive = jiffies;
3181                 num_processed++;
3182
3183                 LASSERTF(!GNI_CQ_OVERRUN(event_data),
3184                         "this is bad, somehow our credits didn't protect us"
3185                         " from CQ overrun\n");
3186                 LASSERTF(GNI_CQ_GET_TYPE(event_data) == GNI_CQ_EVENT_TYPE_POST,
3187                         "rrc %d, GNI_CQ_GET_TYPE("LPX64") = "LPX64"\n", rrc,
3188                         event_data, GNI_CQ_GET_TYPE(event_data));
3189
3190                 rrc = kgnilnd_get_completed(dev->gnd_snd_rdma_cqh, event_data,
3191                                             &desc);
3192                 kgnilnd_gl_mutex_unlock(&dev->gnd_cq_mutex);
3193
3194                 /* XXX Nic: Need better error handling here... */
3195                 LASSERTF((rrc == GNI_RC_SUCCESS) ||
3196                           (rrc == GNI_RC_TRANSACTION_ERROR),
3197                          "rrc %d\n", rrc);
3198
3199                 ev_id.txe_cookie = desc->post_id;
3200
3201                 kgnilnd_validate_tx_ev_id(&ev_id, &tx, &conn);
3202
3203                 if (conn == NULL || tx == NULL) {
3204                         /* either conn or tx was already nuked and this is a "late"
3205                          * completion, so drop it */
3206                         continue;
3207                 }
3208
3209                 GNITX_ASSERTF(tx, tx->tx_msg.gnm_type == GNILND_MSG_PUT_DONE ||
3210                         tx->tx_msg.gnm_type == GNILND_MSG_GET_DONE ||
3211                         tx->tx_msg.gnm_type == GNILND_MSG_PUT_DONE_REV ||
3212                         tx->tx_msg.gnm_type == GNILND_MSG_GET_DONE_REV,
3213                         "tx %p with type %d\n", tx, tx->tx_msg.gnm_type);
3214
3215                 GNIDBG_TX(D_NET, tx, "RDMA completion for %d bytes", tx->tx_nob);
3216
3217                 if (tx->tx_msg.gnm_type == GNILND_MSG_GET_DONE_REV) {
3218                         lnet_set_reply_msg_len(NULL, tx->tx_lntmsg[1],
3219                                                tx->tx_msg.gnm_u.completion.gncm_retval);
3220                 }
3221
3222                 rc = 0;
3223                 if (tx->tx_msg.gnm_type == GNILND_MSG_GET_DONE_REV && desc->status == GNI_RC_SUCCESS) {
3224                         if (tx->tx_buffer_copy != NULL)
3225                                 kgnilnd_recv_bte_get(tx);
3226                         rc = kgnilnd_verify_rdma_cksum(tx, tx->tx_putinfo.gnpam_payload_cksum, tx->tx_nob_rdma);
3227                 }
3228
3229                 if (tx->tx_msg.gnm_type == GNILND_MSG_PUT_DONE_REV && desc->status == GNI_RC_SUCCESS) {
3230                         if (tx->tx_buffer_copy != NULL)
3231                                 kgnilnd_recv_bte_get(tx);
3232                         rc = kgnilnd_verify_rdma_cksum(tx, tx->tx_getinfo.gngm_payload_cksum, tx->tx_nob_rdma);
3233                 }
3234
3235                 /* remove from rdmaq */
3236                 kgnilnd_conn_mutex_lock(&conn->gnc_rdma_mutex);
3237                 spin_lock(&conn->gnc_list_lock);
3238                 kgnilnd_tx_del_state_locked(tx, NULL, conn, GNILND_TX_ALLOCD);
3239                 spin_unlock(&conn->gnc_list_lock);
3240                 kgnilnd_conn_mutex_unlock(&conn->gnc_rdma_mutex);
3241
3242                 if (likely(desc->status == GNI_RC_SUCCESS) && rc == 0) {
3243                         atomic_inc(&dev->gnd_rdma_ntx);
3244                         atomic64_add(tx->tx_nob, &dev->gnd_rdma_txbytes);
3245                         /* transaction succeeded, add into fmaq */
3246                         kgnilnd_queue_tx(conn, tx);
3247                         kgnilnd_peer_alive(conn->gnc_peer);
3248
3249                         /* drop ref from kgnilnd_validate_tx_ev_id */
3250                         kgnilnd_admin_decref(conn->gnc_tx_in_use);
3251                         kgnilnd_conn_decref(conn);
3252
3253                         continue;
3254                 }
3255
3256                 /* fall through to the TRANSACTION_ERROR case */
3257                 tx->tx_retrans++;
3258
3259                 /* get stringified version for log messages */
3260                 kgnilnd_cq_error_str(event_data, &err_str, 256);
3261                 kgnilnd_cq_error_recoverable(event_data, &should_retry);
3262
3263                 /* make sure we are not off in the weeds with this tx */
3264                 if (tx->tx_retrans >
3265                         *kgnilnd_tunables.kgn_max_retransmits) {
3266                         GNIDBG_TX(D_NETERROR, tx,
3267                                "giving up on TX, too many retries", NULL);
3268                         should_retry = 0;
3269                 }
3270
3271                 GNIDBG_TX(D_NETERROR, tx, "RDMA %s error (%s)",
3272                         should_retry ? "transient" : "unrecoverable", err_str);
3273
3274                 if (tx->tx_msg.gnm_type == GNILND_MSG_PUT_DONE ||
3275                     tx->tx_msg.gnm_type == GNILND_MSG_GET_DONE_REV) {
3276                         rdesc    = &tx->tx_putinfo.gnpam_desc;
3277                         rnob     = tx->tx_putinfo.gnpam_desc.gnrd_nob;
3278                         rcookie  = tx->tx_putinfo.gnpam_dst_cookie;
3279                 } else {
3280                         rdesc    = &tx->tx_getinfo.gngm_desc;
3281                         rnob     = tx->tx_lntmsg[0]->msg_len;
3282                         rcookie  = tx->tx_getinfo.gngm_cookie;
3283                 }
3284
3285                 if (should_retry) {
3286                         kgnilnd_rdma(tx,
3287                                      tx->tx_msg.gnm_type,
3288                                      rdesc,
3289                                      rnob, rcookie);
3290                 } else {
3291                         kgnilnd_nak_rdma(conn,
3292                                          tx->tx_msg.gnm_type,
3293                                          -EFAULT,
3294                                          rcookie,
3295                                          tx->tx_msg.gnm_srcnid);
3296                         kgnilnd_tx_done(tx, -EFAULT);
3297                         kgnilnd_close_conn(conn, -ECOMM);
3298                 }
3299
3300                 /* drop ref from kgnilnd_validate_tx_ev_id */
3301                 kgnilnd_admin_decref(conn->gnc_tx_in_use);
3302                 kgnilnd_conn_decref(conn);
3303         }
3304 }
3305
3306 int
3307 kgnilnd_check_fma_send_cq(kgn_device_t *dev)
3308 {
3309         gni_return_t           rrc;
3310         __u64                  event_data;
3311         kgn_tx_ev_id_t         ev_id;
3312         kgn_tx_t              *tx = NULL;
3313         kgn_conn_t            *conn = NULL;
3314         int                    queued_fma, saw_reply, rc;
3315         long                   num_processed = 0;
3316
3317         for (;;) {
3318                 /* make sure we don't keep looping if we need to reset */
3319                 if (unlikely(kgnilnd_data.kgn_quiesce_trigger)) {
3320                         return num_processed;
3321                 }
3322
3323                 rc = kgnilnd_mutex_trylock(&dev->gnd_cq_mutex);
3324                 if (!rc) {
3325                         /* we didn't get the mutex, so return that there is still work
3326                          * to be done */
3327                         return 1;
3328                 }
3329
3330                 rrc = kgnilnd_cq_get_event(dev->gnd_snd_fma_cqh, &event_data);
3331                 kgnilnd_gl_mutex_unlock(&dev->gnd_cq_mutex);
3332
3333                 if (rrc == GNI_RC_NOT_DONE) {
3334                         CDEBUG(D_INFO,
3335                                "SMSG send CQ %d not ready (data "LPX64") "
3336                                "processed %ld\n", dev->gnd_id, event_data,
3337                                num_processed);
3338                         return num_processed;
3339                 }
3340
3341                 dev->gnd_sched_alive = jiffies;
3342                 num_processed++;
3343
3344                 LASSERTF(!GNI_CQ_OVERRUN(event_data),
3345                         "this is bad, somehow our credits didn't "
3346                         "protect us from CQ overrun\n");
3347                 LASSERTF(GNI_CQ_GET_TYPE(event_data) == GNI_CQ_EVENT_TYPE_SMSG,
3348                         "rrc %d, GNI_CQ_GET_TYPE("LPX64") = "LPX64"\n", rrc,
3349                         event_data, GNI_CQ_GET_TYPE(event_data));
3350
3351                 /* if SMSG couldn't handle an error, time for conn to die */
3352                 if (unlikely(rrc == GNI_RC_TRANSACTION_ERROR)) {
3353                         char            err_str[256];
3354
3355                         /* need to take the write_lock to ensure atomicity
3356                          * on the conn state if we need to close it */
3357                         write_lock(&kgnilnd_data.kgn_peer_conn_lock);
3358                         conn = kgnilnd_cqid2conn_locked(GNI_CQ_GET_INST_ID(event_data));
3359                         if (conn == NULL) {
3360                                 /* Conn was destroyed? */
3361                                 CDEBUG(D_NET,
3362                                         "SMSG CQID lookup "LPX64" failed\n",
3363                                         GNI_CQ_GET_INST_ID(event_data));
3364                                 write_unlock(&kgnilnd_data.kgn_peer_conn_lock);
3365                                 continue;
3366                         }
3367
3368                         kgnilnd_cq_error_str(event_data, &err_str, 256);
3369                         CNETERR("SMSG send error to %s: rc %d (%s)\n",
3370                                libcfs_nid2str(conn->gnc_peer->gnp_nid),
3371                                rrc, err_str);
3372                         kgnilnd_close_conn_locked(conn, -ECOMM);
3373
3374                         write_unlock(&kgnilnd_data.kgn_peer_conn_lock);
3375
3376                         /* no need to process rest of this tx -
3377                          * it is getting canceled */
3378                         continue;
3379                 }
3380
3381                 /* fall through to GNI_RC_SUCCESS case */
3382                 ev_id.txe_smsg_id = GNI_CQ_GET_MSG_ID(event_data);
3383
3384                 kgnilnd_validate_tx_ev_id(&ev_id, &tx, &conn);
3385                 if (conn == NULL || tx == NULL) {
3386                         /* either conn or tx was already nuked and this is a "late"
3387                          * completion, so drop it */
3388                         continue;
3389                 }
3390
3391                 tx->tx_conn->gnc_last_tx_cq = jiffies;
3392                 if (tx->tx_msg.gnm_type == GNILND_MSG_NOOP) {
3393                         set_mb(conn->gnc_last_noop_cq, jiffies);
3394                 }
3395
3396                 /* lock tx_list_state and tx_state */
3397                 kgnilnd_conn_mutex_lock(&conn->gnc_smsg_mutex);
3398                 spin_lock(&tx->tx_conn->gnc_list_lock);
3399
3400                 GNITX_ASSERTF(tx, tx->tx_list_state == GNILND_TX_LIVE_FMAQ,
3401                                 "state not GNILND_TX_LIVE_FMAQ", NULL);
3402                 GNITX_ASSERTF(tx, tx->tx_state & GNILND_TX_WAITING_COMPLETION,
3403                         "not waiting for completion", NULL);
3404
3405                 GNIDBG_TX(D_NET, tx, "SMSG complete tx_state %x rc %d",
3406                         tx->tx_state, rrc);
3407
3408                 tx->tx_state &= ~GNILND_TX_WAITING_COMPLETION;
3409
3410                 /* This will trigger other FMA sends that were
3411                  * pending this completion */
3412                 queued_fma = !list_empty(&tx->tx_conn->gnc_fmaq);
3413
3414                 /* we either did not expect reply or we already got it */
3415                 saw_reply = !(tx->tx_state & GNILND_TX_WAITING_REPLY);
3416
3417                 spin_unlock(&tx->tx_conn->gnc_list_lock);
3418                 kgnilnd_conn_mutex_unlock(&conn->gnc_smsg_mutex);
3419
3420                 if (queued_fma) {
3421                         CDEBUG(D_NET, "scheduling conn 0x%p->%s for fmaq\n",
3422                                conn,
3423                                libcfs_nid2str(conn->gnc_peer->gnp_nid));
3424                         kgnilnd_schedule_conn(conn);
3425                 }
3426
3427                 /* If saw_reply is false as soon as gnc_list_lock is dropped the tx could be nuked
3428                  * If saw_reply is true we know that the tx is safe to use as the other thread
3429                  * is already finished with it.
3430                  */
3431
3432                 if (saw_reply) {
3433                         /* no longer need to track on the live_fmaq */
3434                         kgnilnd_tx_del_state_locked(tx, NULL, tx->tx_conn, GNILND_TX_ALLOCD);
3435
3436                         if (tx->tx_state & GNILND_TX_PENDING_RDMA) {
3437                                 /* we already got reply & were waiting for
3438                                  * completion of initial send */
3439                                 /* to initiate RDMA transaction */
3440                                 GNIDBG_TX(D_NET, tx,
3441                                          "Pending RDMA 0x%p type 0x%02x",
3442                                          tx->tx_msg.gnm_type);
3443                                 tx->tx_state &= ~GNILND_TX_PENDING_RDMA;
3444                                 rc = kgnilnd_send_mapped_tx(tx, 0);
3445                                 GNITX_ASSERTF(tx, rc == 0, "RDMA send failed: %d\n", rc);
3446                         } else {
3447                                 /* we are done with this tx */
3448                                 GNIDBG_TX(D_NET, tx,
3449                                          "Done with tx type 0x%02x",
3450                                          tx->tx_msg.gnm_type);
3451                                 kgnilnd_tx_done(tx, tx->tx_rc);
3452                         }
3453                 }
3454
3455                 /* drop ref from kgnilnd_validate_tx_ev_id */
3456                 kgnilnd_admin_decref(conn->gnc_tx_in_use);
3457                 kgnilnd_conn_decref(conn);
3458
3459                 /* if we are waiting for a REPLY, we'll handle the tx then */
3460         } /* end for loop */
3461 }
3462
3463 int
3464 kgnilnd_check_fma_rcv_cq(kgn_device_t *dev)
3465 {
3466         kgn_conn_t         *conn;
3467         gni_return_t        rrc;
3468         __u64               event_data;
3469         long                num_processed = 0;
3470         struct list_head   *conns;
3471         struct list_head   *tmp;
3472         int                 rc;
3473
3474         for (;;) {
3475                 /* make sure we don't keep looping if we need to reset */
3476                 if (unlikely(kgnilnd_data.kgn_quiesce_trigger)) {
3477                         return num_processed;
3478                 }
3479
3480                 rc = kgnilnd_mutex_trylock(&dev->gnd_cq_mutex);
3481                 if (!rc) {
3482                         /* we didn't get the mutex, so return that there is still work
3483                          * to be done */
3484                         return 1;
3485                 }
3486                 rrc = kgnilnd_cq_get_event(dev->gnd_rcv_fma_cqh, &event_data);
3487                 kgnilnd_gl_mutex_unlock(&dev->gnd_cq_mutex);
3488
3489                 if (rrc == GNI_RC_NOT_DONE) {
3490                         CDEBUG(D_INFO, "SMSG RX CQ %d empty data "LPX64" "
3491                                 "processed %ld\n",
3492                                 dev->gnd_id, event_data, num_processed);
3493                         return num_processed;
3494                 }
3495                 dev->gnd_sched_alive = jiffies;
3496                 num_processed++;
3497
3498                 /* this is the only CQ that can really handle transient
3499                  * CQ errors */
3500                 if (CFS_FAIL_CHECK(CFS_FAIL_GNI_CQ_GET_EVENT)) {
3501                         rrc = cfs_fail_val ? cfs_fail_val
3502                                            : GNI_RC_ERROR_RESOURCE;
3503                         if (rrc == GNI_RC_ERROR_RESOURCE) {
3504                                 /* set overrun too */
3505                                 event_data |= (1UL << 63);
3506                                 LASSERTF(GNI_CQ_OVERRUN(event_data),
3507                                          "(1UL << 63) is no longer the bit to"
3508                                          "set to indicate CQ_OVERRUN\n");
3509                         }
3510                 }
3511                 /* sender should get error event too and take care
3512                 of failed transaction by re-transmitting */
3513                 if (rrc == GNI_RC_TRANSACTION_ERROR) {
3514                         CDEBUG(D_NET, "SMSG RX CQ error "LPX64"\n", event_data);
3515                         continue;
3516                 }
3517
3518                 if (likely(!GNI_CQ_OVERRUN(event_data))) {
3519                         read_lock(&kgnilnd_data.kgn_peer_conn_lock);
3520                         conn = kgnilnd_cqid2conn_locked(
3521                                                  GNI_CQ_GET_INST_ID(event_data));
3522                         if (conn == NULL) {
3523                                 CDEBUG(D_NET, "SMSG RX CQID lookup "LPU64" "
3524                                         "failed, dropping event "LPX64"\n",
3525                                         GNI_CQ_GET_INST_ID(event_data),
3526                                         event_data);
3527                         } else {
3528                                 CDEBUG(D_NET, "SMSG RX: CQID "LPU64" "
3529                                        "conn %p->%s\n",
3530                                         GNI_CQ_GET_INST_ID(event_data),
3531                                         conn, conn->gnc_peer ?
3532                                         libcfs_nid2str(conn->gnc_peer->gnp_nid) :
3533                                         "<?>");
3534
3535                                 conn->gnc_last_rx_cq = jiffies;
3536
3537                                 /* stash first rx so we can clear out purgatory.
3538                                  */
3539                                 if (conn->gnc_first_rx == 0) {
3540                                         conn->gnc_first_rx = jiffies;
3541                                 }
3542                                 kgnilnd_peer_alive(conn->gnc_peer);
3543                                 kgnilnd_schedule_conn(conn);
3544                         }
3545                         read_unlock(&kgnilnd_data.kgn_peer_conn_lock);
3546                         continue;
3547                 }
3548
3549                 /* FMA CQ has overflowed: check ALL conns */
3550                 CNETERR("SMSG RX CQ overflow: scheduling ALL "
3551                        "conns on device %d\n", dev->gnd_id);
3552
3553                 for (rc = 0; rc < *kgnilnd_tunables.kgn_peer_hash_size; rc++) {
3554
3555                         read_lock(&kgnilnd_data.kgn_peer_conn_lock);
3556                         conns = &kgnilnd_data.kgn_conns[rc];
3557
3558                         list_for_each(tmp, conns) {
3559                                 conn = list_entry(tmp, kgn_conn_t,
3560                                                   gnc_hashlist);
3561
3562                                 if (conn->gnc_device == dev) {
3563                                         kgnilnd_schedule_conn(conn);
3564                                         conn->gnc_last_rx_cq = jiffies;
3565                                 }
3566                         }
3567
3568                         /* don't block write lockers for too long... */
3569                         read_unlock(&kgnilnd_data.kgn_peer_conn_lock);
3570                 }
3571         }
3572 }
3573
3574 /* try_map_if_full should only be used when processing TX from list of
3575  * backlog TX waiting on mappings to free up
3576  *
3577  * Return Codes:
3578  *  try_map_if_full = 0: 0 (sent or queued), (-|+)errno failure of kgnilnd_sendmsg
3579  *  try_map_if_full = 1: 0 (sent), -ENOMEM for caller to requeue, (-|+)errno failure of kgnilnd_sendmsg */
3580
3581 int
3582 kgnilnd_send_mapped_tx(kgn_tx_t *tx, int try_map_if_full)
3583 {
3584         /* slight bit of race if multiple people calling, but at worst we'll have
3585          * order altered just a bit... which would not be determenistic anyways */
3586         int     rc = atomic_read(&tx->tx_conn->gnc_device->gnd_nq_map);
3587
3588         GNIDBG_TX(D_NET, tx, "try %d nq_map %d", try_map_if_full, rc);
3589
3590         /* We know that we have a GART reservation that should guarantee forward progress.
3591          * This means we don't need to take any extraordinary efforts if we are failing
3592          * mappings here - even if we are holding a very small number of these. */
3593
3594         if (try_map_if_full || (rc == 0)) {
3595                 rc = kgnilnd_map_buffer(tx);
3596         }
3597
3598         /* rc should be 0 if we mapped successfully here, if non-zero
3599          * we are queueing */
3600         if (rc != 0) {
3601                 /* if try_map_if_full set, they handle requeuing */
3602                 if (unlikely(try_map_if_full)) {
3603                         RETURN(rc);
3604                 } else {
3605                         spin_lock(&tx->tx_conn->gnc_device->gnd_lock);
3606                         kgnilnd_tx_add_state_locked(tx, NULL, tx->tx_conn, GNILND_TX_MAPQ, 1);
3607                         spin_unlock(&tx->tx_conn->gnc_device->gnd_lock);
3608                         /* make sure we wake up sched to run this */
3609                         kgnilnd_schedule_device(tx->tx_conn->gnc_device);
3610                         /* return 0 as this is now queued for later sending */
3611                         RETURN(0);
3612                 }
3613         }
3614
3615         switch (tx->tx_msg.gnm_type) {
3616         default:
3617                 LBUG();
3618                 break;
3619         /* GET_REQ and PUT_ACK are outbound messages sending our mapping key to
3620          * remote node where the RDMA will be started
3621          * Special case -EAGAIN logic - this should just queued as if the mapping couldn't
3622          * be satisified. The rest of the errors are "hard" errors that require
3623          * upper layers to handle themselves.
3624          * If kgnilnd_post_rdma returns a resource error, kgnilnd_rdma will put
3625          * the tx back on the TX_MAPQ. When this tx is pulled back off the MAPQ,
3626          * it's gnm_type will now be GNILND_MSG_PUT_DONE or
3627          * GNILND_MSG_GET_DONE_REV.
3628          */
3629         case GNILND_MSG_GET_REQ:
3630                 tx->tx_msg.gnm_u.get.gngm_desc.gnrd_key = tx->tx_map_key;
3631                 tx->tx_msg.gnm_u.get.gngm_cookie = tx->tx_id.txe_cookie;
3632                 tx->tx_msg.gnm_u.get.gngm_desc.gnrd_addr = (__u64)((unsigned long)tx->tx_buffer);
3633                 tx->tx_msg.gnm_u.get.gngm_desc.gnrd_nob = tx->tx_nob;
3634                 tx->tx_state = GNILND_TX_WAITING_COMPLETION | GNILND_TX_WAITING_REPLY;
3635                 if (CFS_FAIL_CHECK(CFS_FAIL_GNI_GET_REQ_AGAIN)) {
3636                         tx->tx_state |= GNILND_TX_FAIL_SMSG;
3637                 }
3638                 /* redirect to FMAQ on failure, no need to infinite loop here in MAPQ */
3639                 rc = kgnilnd_sendmsg(tx, NULL, 0, &tx->tx_conn->gnc_list_lock, GNILND_TX_FMAQ);
3640                 break;
3641         case GNILND_MSG_PUT_ACK:
3642                 tx->tx_msg.gnm_u.putack.gnpam_desc.gnrd_key = tx->tx_map_key;
3643                 tx->tx_state = GNILND_TX_WAITING_COMPLETION | GNILND_TX_WAITING_REPLY;
3644                 if (CFS_FAIL_CHECK(CFS_FAIL_GNI_PUT_ACK_AGAIN)) {
3645                         tx->tx_state |= GNILND_TX_FAIL_SMSG;
3646                 }
3647                 /* redirect to FMAQ on failure, no need to infinite loop here in MAPQ */
3648                 rc = kgnilnd_sendmsg(tx, NULL, 0, &tx->tx_conn->gnc_list_lock, GNILND_TX_FMAQ);
3649                 break;
3650
3651         /* PUT_REQ and GET_DONE are where we do the actual RDMA */
3652         case GNILND_MSG_PUT_DONE:
3653         case GNILND_MSG_PUT_REQ:
3654                 rc = kgnilnd_rdma(tx, GNILND_MSG_PUT_DONE,
3655                              &tx->tx_putinfo.gnpam_desc,
3656                              tx->tx_putinfo.gnpam_desc.gnrd_nob,
3657                              tx->tx_putinfo.gnpam_dst_cookie);
3658                 RETURN(try_map_if_full ? rc : 0);
3659                 break;
3660         case GNILND_MSG_GET_DONE:
3661                 rc = kgnilnd_rdma(tx, GNILND_MSG_GET_DONE,
3662                              &tx->tx_getinfo.gngm_desc,
3663                              tx->tx_lntmsg[0]->msg_len,
3664                              tx->tx_getinfo.gngm_cookie);
3665                 RETURN(try_map_if_full ? rc : 0);
3666                 break;
3667         case GNILND_MSG_PUT_REQ_REV:
3668                 tx->tx_msg.gnm_u.get.gngm_desc.gnrd_key = tx->tx_map_key;
3669                 tx->tx_msg.gnm_u.get.gngm_cookie = tx->tx_id.txe_cookie;
3670                 tx->tx_msg.gnm_u.get.gngm_desc.gnrd_addr = (__u64)((unsigned long)tx->tx_buffer);
3671                 tx->tx_msg.gnm_u.get.gngm_desc.gnrd_nob = tx->tx_nob;
3672                 tx->tx_state = GNILND_TX_WAITING_COMPLETION | GNILND_TX_WAITING_REPLY;
3673                 kgnilnd_compute_rdma_cksum(tx, tx->tx_nob);
3674                 tx->tx_msg.gnm_u.get.gngm_payload_cksum = tx->tx_msg.gnm_payload_cksum;
3675
3676                 rc = kgnilnd_sendmsg(tx, NULL, 0, &tx->tx_conn->gnc_list_lock, GNILND_TX_FMAQ);
3677                 break;
3678         case GNILND_MSG_PUT_DONE_REV:
3679                 rc = kgnilnd_rdma(tx, GNILND_MSG_PUT_DONE_REV,
3680                              &tx->tx_getinfo.gngm_desc,
3681                              tx->tx_nob,
3682                              tx->tx_getinfo.gngm_cookie);
3683                 RETURN(try_map_if_full ? rc : 0);
3684                 break;
3685         case GNILND_MSG_GET_ACK_REV:
3686                 tx->tx_msg.gnm_u.putack.gnpam_desc.gnrd_key = tx->tx_map_key;
3687                 tx->tx_state = GNILND_TX_WAITING_COMPLETION | GNILND_TX_WAITING_REPLY;
3688                 /* LNET_GETS are a special case for parse */
3689                 kgnilnd_compute_rdma_cksum(tx, tx->tx_msg.gnm_u.putack.gnpam_desc.gnrd_nob);
3690                 tx->tx_msg.gnm_u.putack.gnpam_payload_cksum = tx->tx_msg.gnm_payload_cksum;
3691
3692                 if (CFS_FAIL_CHECK(CFS_FAIL_GNI_PUT_ACK_AGAIN))
3693                         tx->tx_state |= GNILND_TX_FAIL_SMSG;
3694
3695                 /* redirect to FMAQ on failure, no need to infinite loop here in MAPQ */
3696                 rc = kgnilnd_sendmsg(tx, NULL, 0, &tx->tx_conn->gnc_list_lock, GNILND_TX_FMAQ);
3697                 break;
3698         case GNILND_MSG_GET_DONE_REV:
3699         case GNILND_MSG_GET_REQ_REV:
3700                 rc = kgnilnd_rdma(tx, GNILND_MSG_GET_DONE_REV,
3701                                 &tx->tx_putinfo.gnpam_desc,
3702                                 tx->tx_putinfo.gnpam_desc.gnrd_nob,
3703                                 tx->tx_putinfo.gnpam_dst_cookie);
3704                 RETURN(try_map_if_full ? rc : 0);
3705                 break;
3706         }
3707
3708         RETURN(rc);
3709 }
3710
3711 void
3712 kgnilnd_process_fmaq(kgn_conn_t *conn)
3713 {
3714         int           more_to_do = 0;
3715         kgn_tx_t     *tx = NULL;
3716         void         *buffer = NULL;
3717         unsigned int  nob = 0;
3718         int           rc;
3719
3720         /* NB 1. kgnilnd_sendmsg() may fail if I'm out of credits right now.
3721          *       However I will be rescheduled by an FMA completion event
3722          *       when I eventually get some.
3723          * NB 2. Sampling gnc_state here races with setting it elsewhere.
3724          *       But it doesn't matter if I try to send a "real" message just
3725          *       as I start closing because I'll get scheduled to send the
3726          *       close anyway. */
3727
3728         /* Short circuit if the ep_handle is null we cant send anyway. */
3729         if (conn->gnc_ephandle == NULL)
3730                 return;
3731
3732         LASSERTF(!conn->gnc_close_sent, "Conn %p close was sent\n", conn);
3733
3734         spin_lock(&conn->gnc_list_lock);
3735
3736         if (list_empty(&conn->gnc_fmaq)) {
3737                 int     keepalive = GNILND_TO2KA(conn->gnc_timeout);
3738
3739                 spin_unlock(&conn->gnc_list_lock);
3740
3741                 if (time_after_eq(jiffies, conn->gnc_last_tx + cfs_time_seconds(keepalive))) {
3742                         CDEBUG(D_NET, "sending NOOP -> %s (%p idle %lu(%d)) "
3743                                "last %lu/%lu/%lu %lus/%lus/%lus\n",
3744                                libcfs_nid2str(conn->gnc_peer->gnp_nid), conn,
3745                                cfs_duration_sec(jiffies - conn->gnc_last_tx),
3746                                keepalive,
3747                                conn->gnc_last_noop_want, conn->gnc_last_noop_sent,
3748                                conn->gnc_last_noop_cq,
3749                                cfs_duration_sec(jiffies - conn->gnc_last_noop_want),
3750                                cfs_duration_sec(jiffies - conn->gnc_last_noop_sent),
3751                                cfs_duration_sec(jiffies - conn->gnc_last_noop_cq));
3752                         atomic_inc(&conn->gnc_sched_noop);
3753                         set_mb(conn->gnc_last_noop_want, jiffies);
3754
3755                         if (CFS_FAIL_CHECK(CFS_FAIL_GNI_NOOP_SEND))
3756                                 return;
3757
3758                         tx = kgnilnd_new_tx_msg(GNILND_MSG_NOOP, conn->gnc_peer->gnp_net->gnn_ni->ni_nid);
3759                         if (tx != NULL) {
3760                                 int     rc;
3761
3762                                 rc = kgnilnd_set_tx_id(tx, conn);
3763                                 if (rc != 0) {
3764                                         kgnilnd_tx_done(tx, rc);
3765                                         return;
3766                                 }
3767                         }
3768                 }
3769         } else {
3770                 tx = list_first_entry(&conn->gnc_fmaq, kgn_tx_t, tx_list);
3771                 /* move from fmaq to allocd, kgnilnd_sendmsg will move to live_fmaq */
3772                 kgnilnd_tx_del_state_locked(tx, NULL, conn, GNILND_TX_ALLOCD);
3773                 more_to_do = !list_empty(&conn->gnc_fmaq);
3774                 spin_unlock(&conn->gnc_list_lock);
3775         }
3776
3777         /* if there is no real TX or no NOOP to send, bail */
3778         if (tx == NULL) {
3779                 return;
3780         }
3781
3782         if (!tx->tx_retrans)
3783                 tx->tx_cred_wait = jiffies;
3784
3785         GNITX_ASSERTF(tx, tx->tx_id.txe_smsg_id != 0,
3786                       "tx with zero id", NULL);
3787
3788         CDEBUG(D_NET, "sending regular msg: %p, type %s(0x%02x), cookie "LPX64"\n",
3789                tx, kgnilnd_msgtype2str(tx->tx_msg.gnm_type),
3790                tx->tx_msg.gnm_type, tx->tx_id.txe_cookie);
3791
3792         rc = 0;
3793
3794         switch (tx->tx_msg.gnm_type) {
3795         default:
3796                 LBUG();
3797
3798         case GNILND_MSG_NOOP:
3799         case GNILND_MSG_CLOSE:
3800         case GNILND_MSG_IMMEDIATE:
3801                 tx->tx_state = GNILND_TX_WAITING_COMPLETION;
3802                 buffer = tx->tx_buffer;
3803                 nob = tx->tx_nob;
3804                 break;
3805
3806         case GNILND_MSG_GET_DONE:
3807         case GNILND_MSG_PUT_DONE:
3808         case GNILND_MSG_PUT_DONE_REV:
3809         case GNILND_MSG_GET_DONE_REV:
3810         case GNILND_MSG_PUT_NAK:
3811         case GNILND_MSG_GET_NAK:
3812         case GNILND_MSG_GET_NAK_REV:
3813         case GNILND_MSG_PUT_NAK_REV:
3814                 tx->tx_state = GNILND_TX_WAITING_COMPLETION;
3815                 break;
3816
3817         case GNILND_MSG_PUT_REQ:
3818         case GNILND_MSG_GET_REQ_REV:
3819                 tx->tx_msg.gnm_u.putreq.gnprm_cookie = tx->tx_id.txe_cookie;
3820
3821         case GNILND_MSG_PUT_ACK:
3822         case GNILND_MSG_PUT_REQ_REV:
3823         case GNILND_MSG_GET_ACK_REV:
3824         case GNILND_MSG_GET_REQ:
3825                 /* This is really only to handle the retransmit of SMSG once these
3826                  * two messages are setup in send_mapped_tx */
3827                 tx->tx_state = GNILND_TX_WAITING_COMPLETION | GNILND_TX_WAITING_REPLY;
3828                 break;
3829         }
3830
3831         if (likely(rc == 0)) {
3832                 rc = kgnilnd_sendmsg(tx, buffer, nob, &conn->gnc_list_lock, GNILND_TX_FMAQ);
3833         }
3834
3835         if (rc > 0) {
3836                 /* don't explicitly reschedule here - we are short credits and will rely on
3837                  * kgnilnd_sendmsg to resched the conn if need be */
3838                 more_to_do = 0;
3839         } else if (rc < 0) {
3840                 /* bail: it wasn't sent and we didn't get EAGAIN indicating we should retrans
3841                  * almost certainly a software bug, but lets play nice with the other kids */
3842                 kgnilnd_tx_done(tx, rc);
3843                 /* just for fun, kick peer in arse - resetting conn might help to correct
3844                  * this almost certainly buggy software caused return code */
3845                 kgnilnd_close_conn(conn, rc);
3846         }
3847
3848         if (more_to_do) {
3849                 CDEBUG(D_NET, "Rescheduling %p (more to do)\n", conn);
3850                 kgnilnd_schedule_conn(conn);
3851         }
3852 }
3853
3854 int
3855 kgnilnd_process_rdmaq(kgn_device_t *dev)
3856 {
3857         int               found_work = 0;
3858         kgn_tx_t         *tx;
3859
3860         if (CFS_FAIL_CHECK(CFS_FAIL_GNI_DELAY_RDMAQ)) {
3861                 RETURN(found_work);
3862         }
3863
3864         if (time_after_eq(jiffies, dev->gnd_rdmaq_deadline)) {
3865                 unsigned long           dead_bump;
3866                 long                    new_ok;
3867
3868                 /* if we think we need to adjust, take lock to serialize and recheck */
3869                 spin_lock(&dev->gnd_rdmaq_lock);
3870                 if (time_after_eq(jiffies, dev->gnd_rdmaq_deadline)) {
3871                         del_singleshot_timer_sync(&dev->gnd_rdmaq_timer);
3872
3873                         dead_bump = cfs_time_seconds(1) / *kgnilnd_tunables.kgn_rdmaq_intervals;
3874
3875                         /* roll the bucket forward */
3876                         dev->gnd_rdmaq_deadline = jiffies + dead_bump;
3877
3878                         if (kgnilnd_data.kgn_rdmaq_override &&
3879                                 (*kgnilnd_tunables.kgn_rdmaq_intervals != 0)) {
3880                                 new_ok = kgnilnd_data.kgn_rdmaq_override / *kgnilnd_tunables.kgn_rdmaq_intervals;
3881                         }  else {
3882                                 new_ok = ~0UL >> 1;
3883                         }
3884
3885                         /* roll current outstanding forward to make sure we carry outstanding
3886                          * committment forward
3887                          * new_ok starts out as the whole interval value
3888                          *  - first subtract bytes_out from last interval, as that would push us over
3889                          *    strict limits for this interval
3890                          *  - second, set bytes_ok to new_ok to ensure it doesn't exceed the current auth
3891                          *
3892                          * there is a small race here if someone is actively processing mappings and
3893                          * adding to rdmaq_bytes_out, but it should be small as the mappings are triggered
3894                          * quite quickly after kgnilnd_auth_rdma_bytes gives us the go-ahead
3895                          * - if this gives us problems in the future, we could use a read/write lock
3896                          * to protect the resetting of these values */
3897                         new_ok -= atomic64_read(&dev->gnd_rdmaq_bytes_out);
3898                         atomic64_set(&dev->gnd_rdmaq_bytes_ok, new_ok);
3899
3900                         CDEBUG(D_NET, "resetting rdmaq bytes to %ld, deadline +%lu -> %lu, "
3901                                        "current out %ld\n",
3902                                atomic64_read(&dev->gnd_rdmaq_bytes_ok), dead_bump, dev->gnd_rdmaq_deadline,
3903                                atomic64_read(&dev->gnd_rdmaq_bytes_out));
3904                 }
3905                 spin_unlock(&dev->gnd_rdmaq_lock);
3906         }
3907
3908         spin_lock(&dev->gnd_rdmaq_lock);
3909         while (!list_empty(&dev->gnd_rdmaq)) {
3910                 int     rc;
3911
3912                 /* make sure we break out early on quiesce */
3913                 if (unlikely(kgnilnd_data.kgn_quiesce_trigger)) {
3914                         /* always break with lock held - we unlock outside loop */
3915                         break;
3916                 }
3917
3918                 tx = list_first_entry(&dev->gnd_rdmaq, kgn_tx_t, tx_list);
3919                 kgnilnd_tx_del_state_locked(tx, NULL, tx->tx_conn, GNILND_TX_ALLOCD);
3920                 found_work++;
3921
3922                 /* sample with lock held, serializing with kgnilnd_complete_closed_conn */
3923                 if (tx->tx_conn->gnc_state != GNILND_CONN_ESTABLISHED) {
3924                         /* if conn is dying, mark tx in tx_ref_table for
3925                          * kgnilnd_complete_closed_conn to finish up */
3926                         kgnilnd_tx_add_state_locked(tx, NULL, tx->tx_conn, GNILND_TX_DYING, 1);
3927
3928                         /* tx was moved to DYING, get next */
3929                         continue;
3930                 }
3931                 spin_unlock(&dev->gnd_rdmaq_lock);
3932
3933                 rc = kgnilnd_auth_rdma_bytes(dev, tx);
3934                 spin_lock(&dev->gnd_rdmaq_lock);
3935
3936                 if (rc < 0) {
3937                         /* no ticket! add back to head */
3938                         kgnilnd_tx_add_state_locked(tx, NULL, tx->tx_conn, GNILND_TX_RDMAQ, 0);
3939                         /* clear found_work so scheduler threads wait for timer */
3940                         found_work = 0;
3941                         break;
3942                 } else {
3943                         /* TX is GO for launch */
3944                         tx->tx_qtime = jiffies;
3945                         kgnilnd_send_mapped_tx(tx, 0);
3946                         found_work++;
3947                 }
3948         }
3949         spin_unlock(&dev->gnd_rdmaq_lock);
3950
3951         RETURN(found_work);
3952 }
3953
3954 static inline void
3955 kgnilnd_swab_rdma_desc(kgn_rdma_desc_t *d)
3956 {
3957         __swab64s(&d->gnrd_key.qword1);
3958         __swab64s(&d->gnrd_key.qword2);
3959         __swab64s(&d->gnrd_addr);
3960         __swab32s(&d->gnrd_nob);
3961 }
3962
3963 #define kgnilnd_match_reply_either(w, x, y, z) _kgnilnd_match_reply(w, x, y, z)
3964 #define kgnilnd_match_reply(x, y, z) _kgnilnd_match_reply(x, y, GNILND_MSG_NONE, z)
3965
3966 kgn_tx_t *
3967 _kgnilnd_match_reply(kgn_conn_t *conn, int type1, int type2, __u64 cookie)
3968 {
3969         kgn_tx_ev_id_t    ev_id;
3970         kgn_tx_t         *tx;
3971
3972         /* we use the cookie from the original TX, so we can find the match
3973          * by parsing that and using the txe_idx */
3974         ev_id.txe_cookie = cookie;
3975
3976         tx = conn->gnc_tx_ref_table[ev_id.txe_idx];
3977
3978         if (tx != NULL) {
3979                 /* check tx to make sure kgni didn't eat it */
3980                 GNITX_ASSERTF(tx, tx->tx_msg.gnm_magic == GNILND_MSG_MAGIC,
3981                               "came back from kgni with bad magic %x\n", tx->tx_msg.gnm_magic);
3982
3983                 GNITX_ASSERTF(tx, ((tx->tx_id.txe_idx == ev_id.txe_idx) &&
3984                                   (tx->tx_id.txe_cookie = cookie)),
3985                               "conn 0x%p->%s tx_ref_table hosed: wanted "
3986                               "txe_cookie "LPX64" txe_idx %d "
3987                               "found tx %p cookie "LPX64" txe_idx %d\n",
3988                               conn, libcfs_nid2str(conn->gnc_peer->gnp_nid),
3989                               cookie, ev_id.txe_idx,
3990                               tx, tx->tx_id.txe_cookie, tx->tx_id.txe_idx);
3991
3992                 LASSERTF((((tx->tx_msg.gnm_type == type1) || (tx->tx_msg.gnm_type == type2)) &&
3993                         (tx->tx_state & GNILND_TX_WAITING_REPLY)),
3994                         "Unexpected TX type (%x, %x or %x) "
3995                         "or state (%x, expected +%x) "
3996                         "matched reply from %s\n",
3997                         tx->tx_msg.gnm_type, type1, type2,
3998                         tx->tx_state, GNILND_TX_WAITING_REPLY,
3999                         libcfs_nid2str(conn->gnc_peer->gnp_nid));
4000         } else {
4001                 CWARN("Unmatched reply %02x, or %02x/"LPX64" from %s\n",
4002                       type1, type2, cookie, libcfs_nid2str(conn->gnc_peer->gnp_nid));
4003         }
4004         return tx;
4005 }
4006
4007 static inline void
4008 kgnilnd_complete_tx(kgn_tx_t *tx, int rc)
4009 {
4010         int             complete = 0;
4011         kgn_conn_t      *conn = tx->tx_conn;
4012         __u64 nob = tx->tx_nob;
4013         __u32 physnop = tx->tx_phys_npages;
4014         int   id = tx->tx_id.txe_smsg_id;
4015         int buftype = tx->tx_buftype;
4016         gni_mem_handle_t hndl;
4017         hndl.qword1 = tx->tx_map_key.qword1;
4018         hndl.qword2 = tx->tx_map_key.qword2;
4019
4020         spin_lock(&conn->gnc_list_lock);
4021
4022         GNITX_ASSERTF(tx, tx->tx_state & GNILND_TX_WAITING_REPLY,
4023                 "not waiting for reply", NULL);
4024
4025         tx->tx_rc = rc;
4026         tx->tx_state &= ~GNILND_TX_WAITING_REPLY;
4027
4028         if (rc == -EFAULT) {
4029                 CDEBUG(D_NETERROR, "Error %d TX data: TX %p tx_id %x nob %16"LPF64"u physnop %8d buffertype %#8x MemHandle "LPX64"."LPX64"x\n",
4030                         rc, tx, id, nob, physnop, buftype, hndl.qword1, hndl.qword2);
4031
4032                 if(*kgnilnd_tunables.kgn_efault_lbug) {
4033                         GNIDBG_TOMSG(D_NETERROR, &tx->tx_msg,
4034                         "error %d on tx 0x%p->%s id %u/%d state %s age %ds",
4035                         rc, tx, conn ?
4036                         libcfs_nid2str(conn->gnc_peer->gnp_nid) : "<?>",
4037                         tx->tx_id.txe_smsg_id, tx->tx_id.txe_idx,
4038                         kgnilnd_tx_state2str(tx->tx_list_state),
4039                         cfs_duration_sec((unsigned long) jiffies - tx->tx_qtime));
4040                         LBUG();
4041                 }
4042         }
4043
4044         if (!(tx->tx_state & GNILND_TX_WAITING_COMPLETION)) {
4045                 kgnilnd_tx_del_state_locked(tx, NULL, conn, GNILND_TX_ALLOCD);
4046                 /* sample under lock as follow on steps require gnc_list_lock
4047                  * - or call kgnilnd_tx_done which requires no locks held over
4048                  *   call to lnet_finalize */
4049                 complete = 1;
4050         }
4051         spin_unlock(&conn->gnc_list_lock);
4052
4053         if (complete) {
4054                 kgnilnd_tx_done(tx, tx->tx_rc);
4055         }
4056 }
4057
4058 static inline void
4059 kgnilnd_finalize_rx_done(kgn_tx_t *tx, kgn_msg_t *msg)
4060 {
4061         int              rc;
4062         kgn_conn_t      *conn = tx->tx_conn;
4063
4064         atomic_inc(&conn->gnc_device->gnd_rdma_nrx);
4065         atomic64_add(tx->tx_nob, &conn->gnc_device->gnd_rdma_rxbytes);
4066
4067         /* the gncm_retval is passed in for PUTs */
4068         rc = kgnilnd_verify_rdma_cksum(tx, msg->gnm_payload_cksum,
4069                                        msg->gnm_u.completion.gncm_retval);
4070
4071         kgnilnd_complete_tx(tx, rc);
4072 }
4073
4074 void
4075 kgnilnd_check_fma_rx(kgn_conn_t *conn)
4076 {
4077         __u32         seq;
4078         kgn_tx_t     *tx;
4079         kgn_rx_t     *rx;
4080         kgn_msg_t    *msg;
4081         void         *prefix;
4082         gni_return_t  rrc;
4083         kgn_peer_t   *peer = conn->gnc_peer;
4084         kgn_net_t    *net;
4085         int           rc = 0;
4086         __u16         tmp_cksum = 0, msg_cksum = 0;
4087         int           repost = 1, saw_complete;
4088         unsigned long timestamp, newest_last_rx, timeout;
4089         int           last_seq;
4090         ENTRY;
4091
4092         /* Short circuit if the ep_handle is null.
4093          * It's likely that its about to be closed as stale.
4094          */
4095         if (conn->gnc_ephandle == NULL)
4096                 RETURN_EXIT;
4097
4098         timestamp = jiffies;
4099         kgnilnd_gl_mutex_lock(&conn->gnc_device->gnd_cq_mutex);
4100         /* delay in jiffies - we are really concerned only with things that
4101          * result in a schedule() or really holding this off for long times .
4102          * NB - mutex_lock could spin for 2 jiffies before going to sleep to wait */
4103         conn->gnc_device->gnd_mutex_delay += (long) jiffies - timestamp;
4104
4105         /* Resample current time as we have no idea how long it took to get the mutex */
4106         timestamp = jiffies;
4107
4108         /* We check here when the last time we received an rx, we do this before
4109          * we call getnext in case the thread has been blocked for a while. If we
4110          * havent received an rx since our timeout value we close the connection
4111          * as we should assume the other side has closed the connection. This will
4112          * stop us from sending replies to a mailbox that is already in purgatory.
4113          */
4114
4115         timeout = cfs_time_seconds(conn->gnc_timeout);
4116         newest_last_rx = GNILND_LASTRX(conn);
4117
4118         /* Error injection to validate that timestamp checking works and closing the conn */
4119         if (CFS_FAIL_CHECK(CFS_FAIL_GNI_RECV_TIMEOUT)) {
4120                 timestamp = timestamp + (GNILND_TIMEOUTRX(timeout) * 2);
4121         }
4122
4123         if (time_after_eq(timestamp, newest_last_rx + (GNILND_TIMEOUTRX(timeout)))) {
4124                 GNIDBG_CONN(D_NETERROR|D_CONSOLE, conn, "Cant receive from %s after timeout lapse of %lu; TO %lu",
4125                 libcfs_nid2str(conn->gnc_peer->gnp_nid),
4126                 cfs_duration_sec(timestamp - newest_last_rx),
4127                 cfs_duration_sec(GNILND_TIMEOUTRX(timeout)));
4128                 kgnilnd_gl_mutex_unlock(&conn->gnc_device->gnd_cq_mutex);
4129                 rc = -ETIME;
4130                 kgnilnd_close_conn(conn, rc);
4131                 RETURN_EXIT;
4132         }
4133
4134         rrc = kgnilnd_smsg_getnext(conn->gnc_ephandle, &prefix);
4135
4136         if (rrc == GNI_RC_NOT_DONE) {
4137                 kgnilnd_gl_mutex_unlock(&conn->gnc_device->gnd_cq_mutex);
4138                 CDEBUG(D_INFO, "SMSG RX empty conn 0x%p\n", conn);
4139                 RETURN_EXIT;
4140         }
4141
4142         /* Instead of asserting when we get mailbox corruption lets attempt to
4143          * close the conn and recover. We can put the conn/mailbox into
4144          * purgatory and let purgatory deal with the problem. If we see
4145          * this NETTERROR reported on production systems in large amounts
4146          * we will need to revisit the state machine to see if we can tighten
4147          * it up further to improve data protection.
4148          */
4149
4150         if (rrc == GNI_RC_INVALID_STATE) {
4151                 kgnilnd_gl_mutex_unlock(&conn->gnc_device->gnd_cq_mutex);
4152                 GNIDBG_CONN(D_NETERROR | D_CONSOLE, conn, "Mailbox corruption "
4153                         "detected closing conn %p from peer %s\n", conn,
4154                         libcfs_nid2str(conn->gnc_peer->gnp_nid));
4155                 rc = -EIO;
4156                 kgnilnd_close_conn(conn, rc);
4157                 RETURN_EXIT;
4158         }
4159
4160         LASSERTF(rrc == GNI_RC_SUCCESS,
4161                 "bad rc %d on conn %p from peer %s\n",
4162                 rrc, conn, libcfs_nid2str(peer->gnp_nid));
4163
4164         msg = (kgn_msg_t *)prefix;
4165
4166         rx = kgnilnd_alloc_rx();
4167         if (rx == NULL) {
4168                 kgnilnd_gl_mutex_unlock(&conn->gnc_device->gnd_cq_mutex);
4169                 kgnilnd_release_msg(conn);
4170                 GNIDBG_MSG(D_NETERROR, msg, "Dropping SMSG RX from 0x%p->%s, no RX memory",
4171                            conn, libcfs_nid2str(peer->gnp_nid));
4172                 RETURN_EXIT;
4173         }
4174
4175         GNIDBG_MSG(D_INFO, msg, "SMSG RX on %p", conn);
4176
4177         timestamp = conn->gnc_last_rx;
4178         seq = last_seq = atomic_read(&conn->gnc_rx_seq);
4179         atomic_inc(&conn->gnc_rx_seq);
4180
4181         conn->gnc_last_rx = jiffies;
4182         /* stash first rx so we can clear out purgatory
4183          */
4184         if (conn->gnc_first_rx == 0)
4185                 conn->gnc_first_rx = jiffies;
4186
4187         /* needs to linger to protect gnc_rx_seq like we do with gnc_tx_seq */
4188         kgnilnd_gl_mutex_unlock(&conn->gnc_device->gnd_cq_mutex);
4189         kgnilnd_peer_alive(conn->gnc_peer);
4190
4191         rx->grx_msg = msg;
4192         rx->grx_conn = conn;
4193         rx->grx_eager = 0;
4194         rx->grx_received = current_kernel_time();
4195
4196         if (CFS_FAIL_CHECK(CFS_FAIL_GNI_NET_LOOKUP)) {
4197                 rc = -ENONET;
4198         } else {
4199                 rc = kgnilnd_find_net(msg->gnm_srcnid, &net);
4200         }
4201
4202         if (rc < 0) {
4203                 GOTO(out, rc);
4204         } else {
4205                 kgnilnd_net_decref(net);
4206         }
4207
4208         if (*kgnilnd_tunables.kgn_checksum && !msg->gnm_cksum)
4209                 GNIDBG_MSG(D_WARNING, msg, "no msg header checksum when enabled");
4210
4211         /* XXX Nic: Do we need to swab cksum */
4212         if (msg->gnm_cksum != 0) {
4213                 msg_cksum = msg->gnm_cksum;
4214                 msg->gnm_cksum = 0;
4215                 tmp_cksum = kgnilnd_cksum(msg, sizeof(kgn_msg_t));
4216
4217                 if (tmp_cksum != msg_cksum) {
4218                         GNIDBG_MSG(D_NETERROR, msg, "Bad hdr checksum (%x expected %x)",
4219                                         tmp_cksum, msg_cksum);
4220                         kgnilnd_dump_msg(D_BUFFS, msg);
4221                         rc = -ENOKEY;
4222                         GOTO(out, rc);
4223                 }
4224         }
4225         /* restore checksum for future debug messages */
4226         msg->gnm_cksum = tmp_cksum;
4227
4228         if (msg->gnm_magic != GNILND_MSG_MAGIC) {
4229                 if (__swab32(msg->gnm_magic) != GNILND_MSG_MAGIC) {
4230                         GNIDBG_MSG(D_NETERROR, msg, "Unexpected magic %08x from %s",
4231                                msg->gnm_magic, libcfs_nid2str(peer->gnp_nid));
4232                         rc = -EPROTO;
4233                         GOTO(out, rc);
4234                 }
4235
4236                 __swab32s(&msg->gnm_magic);
4237                 __swab16s(&msg->gnm_version);
4238                 __swab16s(&msg->gnm_type);
4239                 __swab64s(&msg->gnm_srcnid);
4240                 __swab64s(&msg->gnm_connstamp);
4241                 __swab32s(&msg->gnm_seq);
4242
4243                 /* NB message type checked below; NOT here... */
4244                 switch (msg->gnm_type) {
4245                 case GNILND_MSG_GET_ACK_REV:
4246                 case GNILND_MSG_PUT_ACK:
4247                         kgnilnd_swab_rdma_desc(&msg->gnm_u.putack.gnpam_desc);
4248                         break;
4249
4250                 case GNILND_MSG_PUT_REQ_REV:
4251                 case GNILND_MSG_GET_REQ:
4252                         kgnilnd_swab_rdma_desc(&msg->gnm_u.get.gngm_desc);
4253                         break;
4254
4255                 default:
4256                         break;
4257                 }
4258         }
4259
4260         if (msg->gnm_version != GNILND_MSG_VERSION) {
4261                 GNIDBG_MSG(D_NETERROR, msg, "Unexpected protocol version %d from %s",
4262                        msg->gnm_version, libcfs_nid2str(peer->gnp_nid));
4263                 rc = -EPROTO;
4264                 GOTO(out, rc);
4265         }
4266
4267         if (LNET_NIDADDR(msg->gnm_srcnid) != LNET_NIDADDR(peer->gnp_nid)) {
4268                 GNIDBG_MSG(D_NETERROR, msg, "Unexpected peer %s from %s",
4269                        libcfs_nid2str(msg->gnm_srcnid),
4270                        libcfs_nid2str(peer->gnp_nid));
4271                 rc = -EPROTO;
4272                 GOTO(out, rc);
4273         }
4274
4275         if (msg->gnm_connstamp != conn->gnc_peer_connstamp) {
4276                 GNIDBG_MSG(D_NETERROR, msg, "Unexpected connstamp "LPX64"("LPX64
4277                        " expected) from %s",
4278                        msg->gnm_connstamp, conn->gnc_peer_connstamp,
4279                        libcfs_nid2str(peer->gnp_nid));
4280                 rc = -EPROTO;
4281                 GOTO(out, rc);
4282         }
4283
4284         if (msg->gnm_seq != seq) {
4285                 GNIDBG_MSG(D_NETERROR, msg, "Unexpected sequence number %d(%d expected) from %s",
4286                        msg->gnm_seq, seq, libcfs_nid2str(peer->gnp_nid));
4287                 rc = -EPROTO;
4288                 GOTO(out, rc);
4289         }
4290
4291         atomic_inc(&conn->gnc_device->gnd_short_nrx);
4292
4293         if (msg->gnm_type == GNILND_MSG_CLOSE) {
4294                 CDEBUG(D_NETTRACE, "%s sent us CLOSE msg\n",
4295                               libcfs_nid2str(conn->gnc_peer->gnp_nid));
4296                 write_lock(&kgnilnd_data.kgn_peer_conn_lock);
4297                 conn->gnc_close_recvd = GNILND_CLOSE_RX;
4298                 conn->gnc_peer_error = msg->gnm_u.completion.gncm_retval;
4299                 /* double check state with lock held */
4300                 if (conn->gnc_state == GNILND_CONN_ESTABLISHED) {
4301                         /* only error if we are not already closing */
4302                         if (conn->gnc_peer_error == -ETIMEDOUT) {
4303                                 unsigned long           now = jiffies;
4304                                 CNETERR("peer 0x%p->%s closed connection 0x%p due to timeout. "
4305                                        "Is node down? "
4306                                        "RX %d @ %lus/%lus; TX %d @ %lus/%lus; "
4307                                        "NOOP %lus/%lus/%lus; sched %lus/%lus/%lus ago\n",
4308                                        conn->gnc_peer, libcfs_nid2str(conn->gnc_peer->gnp_nid),
4309                                        conn, last_seq,
4310                                        cfs_duration_sec(now - timestamp),
4311                                        cfs_duration_sec(now - conn->gnc_last_rx_cq),
4312                                        atomic_read(&conn->gnc_tx_seq),
4313                                        cfs_duration_sec(now - conn->gnc_last_tx),
4314                                        cfs_duration_sec(now - conn->gnc_last_tx_cq),
4315                                        cfs_duration_sec(now - conn->gnc_last_noop_want),
4316                                        cfs_duration_sec(now - conn->gnc_last_noop_sent),
4317                                        cfs_duration_sec(now - conn->gnc_last_noop_cq),
4318                                        cfs_duration_sec(now - conn->gnc_last_sched_ask),
4319                                        cfs_duration_sec(now - conn->gnc_last_sched_do),
4320                                        cfs_duration_sec(now - conn->gnc_device->gnd_sched_alive));
4321                         }
4322                         kgnilnd_close_conn_locked(conn, -ECONNRESET);
4323                 }
4324                 write_unlock(&kgnilnd_data.kgn_peer_conn_lock);
4325                 GOTO(out, rc);
4326         }
4327
4328         if (conn->gnc_close_recvd) {
4329                 GNIDBG_MSG(D_NETERROR, msg, "Unexpected message %s(%d/%d) after CLOSE from %s",
4330                        kgnilnd_msgtype2str(msg->gnm_type),
4331                        msg->gnm_type, conn->gnc_close_recvd,
4332                        libcfs_nid2str(conn->gnc_peer->gnp_nid));
4333                 rc = -EPROTO;
4334                 GOTO(out, rc);
4335         }
4336
4337         if (conn->gnc_state != GNILND_CONN_ESTABLISHED) {
4338                 /* XXX Nic: log message received on bad connection state */
4339                 GOTO(out, rc);
4340         }
4341
4342         switch (msg->gnm_type) {
4343         case GNILND_MSG_NOOP:
4344                 /* Nothing to do; just a keepalive */
4345                 break;
4346
4347         case GNILND_MSG_IMMEDIATE:
4348                 /* only get SMSG payload for IMMEDIATE */
4349                 atomic64_add(msg->gnm_payload_len, &conn->gnc_device->gnd_short_rxbytes);
4350                 rc = lnet_parse(net->gnn_ni, &msg->gnm_u.immediate.gnim_hdr,
4351                                 msg->gnm_srcnid, rx, 0);
4352                 repost = rc < 0;
4353                 break;
4354         case GNILND_MSG_GET_REQ_REV:
4355         case GNILND_MSG_PUT_REQ:
4356                 rc = lnet_parse(net->gnn_ni, &msg->gnm_u.putreq.gnprm_hdr,
4357                                 msg->gnm_srcnid, rx, 1);
4358                 repost = rc < 0;
4359                 break;
4360         case GNILND_MSG_GET_NAK_REV:
4361                 tx = kgnilnd_match_reply_either(conn, GNILND_MSG_GET_REQ_REV, GNILND_MSG_GET_ACK_REV,
4362                                         msg->gnm_u.completion.gncm_cookie);
4363                 if (tx == NULL)
4364                         break;
4365
4366                 kgnilnd_complete_tx(tx, msg->gnm_u.completion.gncm_retval);
4367                 break;
4368         case GNILND_MSG_PUT_NAK:
4369                 tx = kgnilnd_match_reply_either(conn, GNILND_MSG_PUT_REQ, GNILND_MSG_PUT_ACK,
4370                                         msg->gnm_u.completion.gncm_cookie);
4371                 if (tx == NULL)
4372                         break;
4373
4374                 kgnilnd_complete_tx(tx, msg->gnm_u.completion.gncm_retval);
4375                 break;
4376         case GNILND_MSG_PUT_ACK:
4377                 tx = kgnilnd_match_reply(conn, GNILND_MSG_PUT_REQ,
4378                                         msg->gnm_u.putack.gnpam_src_cookie);
4379                 if (tx == NULL)
4380                         break;
4381
4382                 /* store putack data for later: deferred rdma or re-try */
4383                 tx->tx_putinfo = msg->gnm_u.putack;
4384
4385                 saw_complete = 0;
4386                 spin_lock(&tx->tx_conn->gnc_list_lock);
4387
4388                 GNITX_ASSERTF(tx, tx->tx_state & GNILND_TX_WAITING_REPLY,
4389                         "not waiting for reply", NULL);
4390
4391                 tx->tx_state &= ~GNILND_TX_WAITING_REPLY;
4392
4393                 if (likely(!(tx->tx_state & GNILND_TX_WAITING_COMPLETION))) {
4394                         kgnilnd_tx_del_state_locked(tx, NULL, conn, GNILND_TX_ALLOCD);
4395                         /* sample under lock as follow on steps require gnc_list_lock
4396                          * - or call kgnilnd_tx_done which requires no locks held over
4397                          *   call to lnet_finalize */
4398                         saw_complete = 1;
4399                 } else {
4400                         /* cannot launch rdma if still waiting for fma-msg completion */
4401                         CDEBUG(D_NET, "tx 0x%p type 0x%02x will need to "
4402                                        "wait for SMSG completion\n", tx, tx->tx_msg.gnm_type);
4403                         tx->tx_state |= GNILND_TX_PENDING_RDMA;
4404                 }
4405                 spin_unlock(&tx->tx_conn->gnc_list_lock);
4406
4407                 if (saw_complete) {
4408                         rc = kgnilnd_send_mapped_tx(tx, 0);
4409                         if (rc < 0)
4410                                 kgnilnd_tx_done(tx, rc);
4411                 }
4412                 break;
4413         case GNILND_MSG_GET_ACK_REV:
4414                 tx = kgnilnd_match_reply(conn, GNILND_MSG_GET_REQ_REV,
4415                                         msg->gnm_u.putack.gnpam_src_cookie);
4416                 if (tx == NULL)
4417                         break;
4418
4419                 /* store putack data for later: deferred rdma or re-try */
4420                 tx->tx_putinfo = msg->gnm_u.putack;
4421                 saw_complete = 0;
4422                 spin_lock(&tx->tx_conn->gnc_list_lock);
4423
4424                 GNITX_ASSERTF(tx, tx->tx_state & GNILND_TX_WAITING_REPLY,
4425                         "not waiting for reply", NULL);
4426
4427                 tx->tx_state &= ~GNILND_TX_WAITING_REPLY;
4428
4429                 if (likely(!(tx->tx_state & GNILND_TX_WAITING_COMPLETION))) {
4430                         kgnilnd_tx_del_state_locked(tx, NULL, conn, GNILND_TX_ALLOCD);
4431                         /* sample under lock as follow on steps require gnc_list_lock
4432                          * - or call kgnilnd_tx_done which requires no locks held over
4433                          *   call to lnet_finalize */
4434                         saw_complete = 1;
4435                 } else {
4436                         /* cannot launch rdma if still waiting for fma-msg completion */
4437                         CDEBUG(D_NET, "tx 0x%p type 0x%02x will need to "
4438                                         "wait for SMSG completion\n", tx, tx->tx_msg.gnm_type);
4439                         tx->tx_state |= GNILND_TX_PENDING_RDMA;
4440                 }
4441                 spin_unlock(&tx->tx_conn->gnc_list_lock);
4442
4443                 if (saw_complete) {
4444                         rc = kgnilnd_send_mapped_tx(tx, 0);
4445                         if (rc < 0)
4446                                 kgnilnd_tx_done(tx, rc);
4447                 }
4448                 break;
4449         case GNILND_MSG_PUT_DONE:
4450                 tx = kgnilnd_match_reply(conn, GNILND_MSG_PUT_ACK,
4451                                         msg->gnm_u.completion.gncm_cookie);
4452                 if (tx == NULL)
4453                         break;
4454
4455                 GNITX_ASSERTF(tx, tx->tx_buftype == GNILND_BUF_PHYS_MAPPED ||
4456                                tx->tx_buftype == GNILND_BUF_VIRT_MAPPED,
4457                                "bad tx buftype %d", tx->tx_buftype);
4458
4459                 kgnilnd_finalize_rx_done(tx, msg);
4460                 break;
4461         case GNILND_MSG_PUT_REQ_REV:
4462         case GNILND_MSG_GET_REQ:
4463                 rc = lnet_parse(net->gnn_ni, &msg->gnm_u.get.gngm_hdr,
4464                                 msg->gnm_srcnid, rx, 1);
4465                 repost = rc < 0;
4466                 break;
4467
4468         case GNILND_MSG_GET_NAK:
4469                 tx = kgnilnd_match_reply(conn, GNILND_MSG_GET_REQ,
4470                                         msg->gnm_u.completion.gncm_cookie);
4471                 if (tx == NULL)
4472                         break;
4473
4474                 GNITX_ASSERTF(tx, tx->tx_buftype == GNILND_BUF_PHYS_MAPPED ||
4475                                tx->tx_buftype == GNILND_BUF_VIRT_MAPPED,
4476                                "bad tx buftype %d", tx->tx_buftype);
4477
4478                 kgnilnd_complete_tx(tx, msg->gnm_u.completion.gncm_retval);
4479                 break;
4480
4481         case GNILND_MSG_GET_DONE:
4482                 tx = kgnilnd_match_reply(conn, GNILND_MSG_GET_REQ,
4483                                         msg->gnm_u.completion.gncm_cookie);
4484                 if (tx == NULL)
4485                         break;
4486
4487                 GNITX_ASSERTF(tx, tx->tx_buftype == GNILND_BUF_PHYS_MAPPED ||
4488                                tx->tx_buftype == GNILND_BUF_VIRT_MAPPED,
4489                                "bad tx buftype %d", tx->tx_buftype);
4490
4491                 lnet_set_reply_msg_len(net->gnn_ni, tx->tx_lntmsg[1],
4492                                        msg->gnm_u.completion.gncm_retval);
4493
4494                 kgnilnd_finalize_rx_done(tx, msg);
4495                 break;
4496         case GNILND_MSG_GET_DONE_REV:
4497                 tx = kgnilnd_match_reply(conn, GNILND_MSG_GET_ACK_REV,
4498                                         msg->gnm_u.completion.gncm_cookie);
4499                 if (tx == NULL)
4500                         break;
4501
4502                 GNITX_ASSERTF(tx, tx->tx_buftype == GNILND_BUF_PHYS_MAPPED ||
4503                                 tx->tx_buftype == GNILND_BUF_VIRT_MAPPED,
4504                                 "bad tx buftype %d", tx->tx_buftype);
4505
4506                 kgnilnd_finalize_rx_done(tx, msg);
4507                 break;
4508
4509         case GNILND_MSG_PUT_DONE_REV:
4510                 tx = kgnilnd_match_reply(conn, GNILND_MSG_PUT_REQ_REV,
4511                                         msg->gnm_u.completion.gncm_cookie);
4512
4513                 if (tx == NULL)
4514                         break;
4515
4516                 GNITX_ASSERTF(tx, tx->tx_buftype == GNILND_BUF_PHYS_MAPPED ||
4517                                tx->tx_buftype == GNILND_BUF_VIRT_MAPPED,
4518                                "bad tx buftype %d", tx->tx_buftype);
4519
4520                 kgnilnd_finalize_rx_done(tx, msg);
4521                 break;
4522         case GNILND_MSG_PUT_NAK_REV:
4523                 tx = kgnilnd_match_reply(conn, GNILND_MSG_PUT_REQ_REV,
4524                                         msg->gnm_u.completion.gncm_cookie);
4525
4526                 if (tx == NULL)
4527                         break;
4528
4529                 GNITX_ASSERTF(tx, tx->tx_buftype == GNILND_BUF_PHYS_MAPPED ||
4530                                tx->tx_buftype == GNILND_BUF_VIRT_MAPPED,
4531                                 "bad tx buftype %d", tx->tx_buftype);
4532
4533                 kgnilnd_complete_tx(tx, msg->gnm_u.completion.gncm_retval);
4534                 break;
4535         }
4536
4537  out:
4538         if (rc < 0)                             /* protocol/comms error */
4539                 kgnilnd_close_conn(conn, rc);
4540
4541         if (repost && rx != NULL) {
4542                 kgnilnd_consume_rx(rx);
4543         }
4544
4545         /* we got an event so assume more there and call for reschedule */
4546         if (rc >= 0)
4547                 kgnilnd_schedule_conn(conn);
4548         EXIT;
4549 }
4550
4551 /* Do the failure injections that we need to affect conn processing in the following function.
4552  * When writing tests that use this function make sure to use a fail_loc with a fail mask.
4553  * If you dont you can cause the scheduler threads to spin on the conn without it leaving
4554  * process_conns.
4555  *
4556  * intent is used to signal the calling function whether or not the conn needs to be rescheduled.
4557  */
4558
4559 static inline int
4560 kgnilnd_check_conn_fail_loc(kgn_device_t *dev, kgn_conn_t *conn, int *intent)
4561 {
4562         int     rc = 0;
4563
4564         /* short circuit out when not set */
4565         if (likely(!cfs_fail_loc)) {
4566                 RETURN(rc);
4567         }
4568
4569         /* failure injection to test for stack reset clean ups */
4570         if (CFS_FAIL_CHECK(CFS_FAIL_GNI_DROP_CLOSING)) {
4571                 /* we can't rely on busy loops being nice enough to get the
4572                  *  stack reset triggered - it'd just spin on this conn */
4573                 CFS_RACE(CFS_FAIL_GNI_DROP_CLOSING);
4574                 rc = 1;
4575                 *intent = 1;
4576                 GOTO(did_fail_loc, rc);
4577         }
4578
4579         if (conn->gnc_state == GNILND_CONN_DESTROY_EP) {
4580                 /* DESTROY_EP set in kgnilnd_conn_decref on gnc_refcount = 1 */
4581
4582                 if (CFS_FAIL_CHECK(CFS_FAIL_GNI_DROP_DESTROY_EP)) {
4583                         CFS_RACE(CFS_FAIL_GNI_DROP_DESTROY_EP);
4584                         rc = 1;
4585                         *intent = 1;
4586                         GOTO(did_fail_loc, rc);
4587                 }
4588         }
4589
4590         /* CFS_FAIL_GNI_FINISH_PURG2 is used to stop a connection from fully closing. This scheduler
4591          * will spin on the CFS_FAIL_TIMEOUT until the fail_loc is cleared at which time the connection
4592          * will be closed by kgnilnd_complete_closed_conn.
4593          */
4594         if ((conn->gnc_state == GNILND_CONN_CLOSED) && CFS_FAIL_CHECK(CFS_FAIL_GNI_FINISH_PURG2)) {
4595                 while (CFS_FAIL_TIMEOUT(CFS_FAIL_GNI_FINISH_PURG2, 1)) {};
4596                 rc = 1;
4597                 *intent = 1;
4598                 GOTO(did_fail_loc, rc);
4599         }
4600
4601         /* this one is a bit gross - we can't hold the mutex from process_conns
4602          * across a CFS_RACE here - it'd block the conn threads from doing an ep_bind
4603          * and moving onto finish_connect
4604          * so, we'll just set the rc - kgnilnd_process_conns will clear
4605          * found_work on a fail_loc, getting the scheduler thread to call schedule()
4606          * and effectively getting this thread to sleep */
4607         if ((conn->gnc_state == GNILND_CONN_CLOSED) && CFS_FAIL_CHECK(CFS_FAIL_GNI_FINISH_PURG)) {
4608                 rc = 1;
4609                 *intent = 1;
4610                 GOTO(did_fail_loc, rc);
4611         }
4612
4613 did_fail_loc:
4614         RETURN(rc);
4615 }
4616
4617 static inline void
4618 kgnilnd_send_conn_close(kgn_conn_t *conn)
4619 {
4620         kgn_tx_t        *tx;
4621
4622         /* we are closing the conn - we will try to send the CLOSE msg
4623          * but will not wait for anything else to flush */
4624
4625         /* send the close if not already done so or received one */
4626         if (!conn->gnc_close_sent && !conn->gnc_close_recvd) {
4627                 /* set close_sent regardless of the success of the
4628                  * CLOSE message. We are going to try once and then
4629                  * kick him out of the sandbox */
4630                 conn->gnc_close_sent = 1;
4631                 mb();
4632
4633                 /* EP might be null already if remote side initiated a new connection.
4634                  * kgnilnd_finish_connect destroys existing ep_handles before wiring up the new connection,
4635                  * so this check is here to make sure we dont attempt to send with a null ep_handle.
4636                  */
4637                 if (conn->gnc_ephandle != NULL) {
4638                         int rc = 0;
4639
4640                         tx = kgnilnd_new_tx_msg(GNILND_MSG_CLOSE, conn->gnc_peer->gnp_net->gnn_ni->ni_nid);
4641                         if (tx != NULL) {
4642                                 tx->tx_msg.gnm_u.completion.gncm_retval = conn->gnc_error;
4643                                 tx->tx_state = GNILND_TX_WAITING_COMPLETION;
4644                                 tx->tx_qtime = jiffies;
4645
4646                                 if (tx->tx_id.txe_idx == 0) {
4647                                         rc = kgnilnd_set_tx_id(tx, conn);
4648                                         if (rc != 0) {
4649                                                 kgnilnd_tx_done(tx, rc);
4650                                         }
4651                                 }
4652
4653                                 CDEBUG(D_NETTRACE, "sending close with errno %d\n",
4654                                                 conn->gnc_error);
4655
4656                                 if (CFS_FAIL_CHECK(CFS_FAIL_GNI_CLOSE_SEND)) {
4657                                         kgnilnd_tx_done(tx, -EAGAIN);
4658                                 } else if (!rc) {
4659                                         rc = kgnilnd_sendmsg(tx, NULL, 0, NULL, GNILND_TX_FMAQ);
4660                                         if (rc) {
4661                                                 /* It wasnt sent and we dont care. */
4662                                                 kgnilnd_tx_done(tx, rc);
4663                                         }
4664                                 }
4665
4666                         }
4667                 }
4668         }
4669
4670         /* When changing gnc_state we need to take the kgn_peer_conn_lock */
4671         write_lock(&kgnilnd_data.kgn_peer_conn_lock);
4672         conn->gnc_state = GNILND_CONN_CLOSED;
4673         write_unlock(&kgnilnd_data.kgn_peer_conn_lock);
4674         /* mark this conn as CLOSED now that we processed it
4675          * do after TX, so we can use CLOSING in asserts */
4676
4677         mb();
4678
4679         if (CFS_FAIL_CHECK(CFS_FAIL_GNI_RX_CLOSE_CLOSED)) {
4680                 /* simulate a RX CLOSE after the timeout but before
4681                  * the scheduler thread gets it */
4682                 conn->gnc_close_recvd = GNILND_CLOSE_INJECT2;
4683                 conn->gnc_peer_error = -ETIMEDOUT;
4684         }
4685         /* schedule to allow potential CLOSE and get the complete phase run */
4686         kgnilnd_schedule_conn(conn);
4687 }
4688
4689 int
4690 kgnilnd_process_mapped_tx(kgn_device_t *dev)
4691 {
4692         int             found_work = 0;
4693         int             rc = 0;
4694         kgn_tx_t        *tx;
4695         int              fast_remaps = GNILND_FAST_MAPPING_TRY;
4696         int             log_retrans, log_retrans_level;
4697         static int      last_map_version;
4698         ENTRY;
4699
4700         spin_lock(&dev->gnd_lock);
4701         if (list_empty(&dev->gnd_map_tx)) {
4702                 /* if the list is empty make sure we dont have a timer running */
4703                 del_singleshot_timer_sync(&dev->gnd_map_timer);
4704                 spin_unlock(&dev->gnd_lock);
4705                 RETURN(0);
4706         }
4707
4708         dev->gnd_sched_alive = jiffies;
4709
4710         /* we'll retry as fast as possible up to 25% of the limit, then we start
4711          * backing off until our map version changes - indicating we unmapped
4712          * something */
4713         tx = list_first_entry(&dev->gnd_map_tx, kgn_tx_t, tx_list);
4714         if (likely(dev->gnd_map_attempt == 0) ||
4715                 time_after_eq(jiffies, dev->gnd_next_map) ||
4716                 last_map_version != dev->gnd_map_version) {
4717
4718                 /* if this is our first attempt at mapping set last mapped to current
4719                  * jiffies so we can timeout our attempt correctly.
4720                  */
4721                 if (dev->gnd_map_attempt == 0)
4722                         dev->gnd_last_map = jiffies;
4723         } else {
4724                 GNIDBG_TX(D_NET, tx, "waiting for mapping event event to retry", NULL);
4725                 spin_unlock(&dev->gnd_lock);
4726                 RETURN(0);
4727         }
4728
4729         /* delete the previous timer if it exists */
4730         del_singleshot_timer_sync(&dev->gnd_map_timer);
4731         /* stash the last map version to let us know when a good one was seen */
4732         last_map_version = dev->gnd_map_version;
4733
4734         /* we need to to take the lock and continually refresh the head of the list as
4735          * kgnilnd_complete_closed_conn might be nuking stuff and we are cycling the lock
4736          * allowing them to squeeze in */
4737
4738         while (!list_empty(&dev->gnd_map_tx)) {
4739                 /* make sure we break out early on quiesce */
4740                 if (unlikely(kgnilnd_data.kgn_quiesce_trigger)) {
4741                         /* always break with lock held - we unlock outside loop */
4742                         break;
4743                 }
4744
4745                 tx = list_first_entry(&dev->gnd_map_tx, kgn_tx_t, tx_list);
4746
4747                 kgnilnd_tx_del_state_locked(tx, NULL, tx->tx_conn, GNILND_TX_ALLOCD);
4748                 found_work++;
4749
4750                 /* sample with lock held, serializing with kgnilnd_complete_closed_conn */
4751                 if (tx->tx_conn->gnc_state != GNILND_CONN_ESTABLISHED) {
4752                         /* if conn is dying, mark tx in tx_ref_table for
4753                          * kgnilnd_complete_closed_conn to finish up */
4754                         kgnilnd_tx_add_state_locked(tx, NULL, tx->tx_conn, GNILND_TX_DYING, 1);
4755                         found_work++;
4756
4757                         /* tx was moved to DYING, get next */
4758                         continue;
4759                 }
4760
4761                 spin_unlock(&dev->gnd_lock);
4762                 rc = kgnilnd_send_mapped_tx(tx, 1);
4763
4764                 /* We made it! skip error handling.. */
4765                 if (rc >= 0) {
4766                         /* OK to continue on +ve errors as it won't get seen until
4767                          * this function is called again - we operate on a copy of the original
4768                          * list and not the live list */
4769                         spin_lock(&dev->gnd_lock);
4770                         /* reset map attempts back to zero we successfully
4771                          * mapped so we can reset our timers */
4772                         dev->gnd_map_attempt = 0;
4773                         continue;
4774                 } else if (rc == -EAGAIN) {
4775                         spin_lock(&dev->gnd_lock);
4776                         mod_timer(&dev->gnd_map_timer, dev->gnd_next_map);
4777                         spin_unlock(&dev->gnd_lock);
4778                         GOTO(get_out_mapped, rc);
4779                 } else if (rc != -ENOMEM) {
4780                         /* carp, failure we can't handle */
4781                         kgnilnd_tx_done(tx, rc);
4782                         spin_lock(&dev->gnd_lock);
4783                         /* reset map attempts back to zero we dont know what happened but it
4784                          * wasnt a failed mapping
4785                          */
4786                         dev->gnd_map_attempt = 0;
4787                         continue;
4788                 }
4789
4790                 /* time to handle the retry cases..  lock so we dont have 2 threads
4791                  * mucking with gnd_map_attempt, or gnd_next_map at the same time.
4792                  */
4793                 spin_lock(&dev->gnd_lock);
4794                 dev->gnd_map_attempt++;
4795                 if (dev->gnd_map_attempt < fast_remaps) {
4796                         /* do nothing we just want it to go as fast as possible.
4797                          * just set gnd_next_map to current jiffies so it will process
4798                          * as fast as possible.
4799                          */
4800                         dev->gnd_next_map = jiffies;
4801                 } else {
4802                         /* Retry based on GNILND_MAP_RETRY_RATE */
4803                         dev->gnd_next_map = jiffies + GNILND_MAP_RETRY_RATE;
4804                 }
4805
4806                 /* only log occasionally once we've retried fast_remaps */
4807                 log_retrans = (dev->gnd_map_attempt >= fast_remaps) &&
4808                               ((dev->gnd_map_attempt % fast_remaps) == 0);
4809                 log_retrans_level = log_retrans ? D_NETERROR : D_NET;
4810
4811                 /* make sure we are not off in the weeds with this tx */
4812                 if (time_after(jiffies, dev->gnd_last_map + GNILND_MAP_TIMEOUT)) {
4813                        GNIDBG_TX(D_NETERROR, tx,
4814                                "giving up on TX, too many retries", NULL);
4815                        spin_unlock(&dev->gnd_lock);
4816                        if (tx->tx_msg.gnm_type == GNILND_MSG_PUT_REQ ||
4817                            tx->tx_msg.gnm_type == GNILND_MSG_GET_REQ_REV) {
4818                                kgnilnd_nak_rdma(tx->tx_conn, tx->tx_msg.gnm_type,
4819                                                 -ENOMEM,
4820                                                 tx->tx_putinfo.gnpam_dst_cookie,
4821                                                 tx->tx_msg.gnm_srcnid);
4822                         } else {
4823                                 kgnilnd_nak_rdma(tx->tx_conn, tx->tx_msg.gnm_type,
4824                                                 -ENOMEM,
4825                                                 tx->tx_getinfo.gngm_cookie,
4826                                                 tx->tx_msg.gnm_srcnid);
4827                         }
4828                        kgnilnd_tx_done(tx, -ENOMEM);
4829                        GOTO(get_out_mapped, rc);
4830                 } else {
4831                        GNIDBG_TX(log_retrans_level, tx,
4832                                 "transient map failure #%d %d pages/%d bytes phys %u@%u "
4833                                 "virt %u@"LPU64" "
4834                                 "nq_map %d mdd# %d/%d GART %ld",
4835                                 dev->gnd_map_attempt, tx->tx_phys_npages, tx->tx_nob,
4836                                 dev->gnd_map_nphys, dev->gnd_map_physnop * PAGE_SIZE,
4837                                 dev->gnd_map_nvirt, dev->gnd_map_virtnob,
4838                                 atomic_read(&dev->gnd_nq_map),
4839                                 atomic_read(&dev->gnd_n_mdd), atomic_read(&dev->gnd_n_mdd_held),
4840                                 atomic64_read(&dev->gnd_nbytes_map));
4841                 }
4842
4843                 /* we need to stop processing the rest of the list, so add it back in */
4844                 /* set timer to wake device when we need to schedule this tx */
4845                 mod_timer(&dev->gnd_map_timer, dev->gnd_next_map);
4846                 kgnilnd_tx_add_state_locked(tx, NULL, tx->tx_conn, GNILND_TX_MAPQ, 0);
4847                 spin_unlock(&dev->gnd_lock);
4848                 GOTO(get_out_mapped, rc);
4849         }
4850         spin_unlock(&dev->gnd_lock);
4851 get_out_mapped:
4852         RETURN(found_work);
4853 }
4854
4855 int
4856 kgnilnd_process_conns(kgn_device_t *dev, unsigned long deadline)
4857 {
4858         int              found_work = 0;
4859         int              conn_sched;
4860         int              intent = 0;
4861         int              error_inject = 0;
4862         int              rc = 0;
4863         kgn_conn_t      *conn;
4864
4865         spin_lock(&dev->gnd_lock);
4866         while (!list_empty(&dev->gnd_ready_conns) && time_before(jiffies, deadline)) {
4867                 dev->gnd_sched_alive = jiffies;
4868                 error_inject = 0;
4869                 rc = 0;
4870
4871                 if (unlikely(kgnilnd_data.kgn_quiesce_trigger)) {
4872                         /* break with lock held */
4873                         break;
4874                 }
4875
4876                 conn = list_first_entry(&dev->gnd_ready_conns, kgn_conn_t, gnc_schedlist);
4877                 list_del_init(&conn->gnc_schedlist);
4878                 spin_unlock(&dev->gnd_lock);
4879
4880                 conn_sched = xchg(&conn->gnc_scheduled, GNILND_CONN_PROCESS);
4881
4882                 LASSERTF(conn_sched != GNILND_CONN_IDLE &&
4883                          conn_sched != GNILND_CONN_PROCESS,
4884                          "conn %p on ready list but in bad state: %d\n",
4885                          conn, conn_sched);
4886
4887                 CDEBUG(D_INFO, "conn %p@%s for processing\n",
4888                         conn, kgnilnd_conn_state2str(conn));
4889
4890                 found_work++;
4891                 set_mb(conn->gnc_last_sched_do, jiffies);
4892
4893                 if (kgnilnd_check_conn_fail_loc(dev, conn, &intent)) {
4894
4895                         /* based on intent see if we should run again. */
4896                         rc = kgnilnd_schedule_process_conn(conn, intent);
4897                         error_inject = 1;
4898                         /* drop ref from gnd_ready_conns */
4899                         if (atomic_read(&conn->gnc_refcount) == 1 && rc != 1) {
4900                                 down_write(&dev->gnd_conn_sem);
4901                                 kgnilnd_conn_decref(conn);
4902                                 up_write(&dev->gnd_conn_sem);
4903                         } else if (rc != 1) {
4904                         kgnilnd_conn_decref(conn);
4905                         }
4906                         /* clear this so that scheduler thread doesn't spin */
4907                         found_work = 0;
4908                         /* break with lock held... */
4909                         spin_lock(&dev->gnd_lock);
4910                         break;
4911                 }
4912
4913                 if (unlikely(conn->gnc_state == GNILND_CONN_CLOSED)) {
4914                         down_write(&dev->gnd_conn_sem);
4915
4916                         /* CONN_CLOSED set in procces_fmaq when CLOSE is sent */
4917                         if (unlikely(atomic_read(&conn->gnc_tx_in_use))) {
4918                                 /* If there are tx's currently in use in another
4919                                  * thread we dont want to complete the close
4920                                  * yet. Cycle this conn back through
4921                                  * the scheduler. */
4922                                 kgnilnd_schedule_conn(conn);
4923                         } else {
4924                                 kgnilnd_complete_closed_conn(conn);
4925                         }
4926                         up_write(&dev->gnd_conn_sem);
4927                 } else if (unlikely(conn->gnc_state == GNILND_CONN_DESTROY_EP)) {
4928                         /* DESTROY_EP set in kgnilnd_conn_decref on gnc_refcount = 1 */
4929                         /* serialize SMSG CQs with ep_bind and smsg_release */
4930                         down_write(&dev->gnd_conn_sem);
4931                         kgnilnd_destroy_conn_ep(conn);
4932                         up_write(&dev->gnd_conn_sem);
4933                 } else if (unlikely(conn->gnc_state == GNILND_CONN_CLOSING)) {
4934                        /* if we need to do some CLOSE sending, etc done here do it */
4935                         down_write(&dev->gnd_conn_sem);
4936                         kgnilnd_send_conn_close(conn);
4937                         kgnilnd_check_fma_rx(conn);
4938                         up_write(&dev->gnd_conn_sem);
4939                 } else if (atomic_read(&conn->gnc_peer->gnp_dirty_eps) == 0) {
4940                         /* start moving traffic if the old conns are cleared out */
4941                         down_read(&dev->gnd_conn_sem);
4942                         kgnilnd_check_fma_rx(conn);
4943                         kgnilnd_process_fmaq(conn);
4944                         up_read(&dev->gnd_conn_sem);
4945                 }
4946
4947                 rc = kgnilnd_schedule_process_conn(conn, 0);
4948
4949                 /* drop ref from gnd_ready_conns */
4950                 if (atomic_read(&conn->gnc_refcount) == 1 && rc != 1) {
4951                         down_write(&dev->gnd_conn_sem);
4952                         kgnilnd_conn_decref(conn);
4953                         up_write(&dev->gnd_conn_sem);
4954                 } else if (rc != 1) {
4955                 kgnilnd_conn_decref(conn);
4956                 }
4957
4958                 /* check list again with lock held */
4959                 spin_lock(&dev->gnd_lock);
4960         }
4961
4962         /* If we are short circuiting due to timing we want to be scheduled
4963          * as soon as possible.
4964          */
4965         if (!list_empty(&dev->gnd_ready_conns) && !error_inject)
4966                 found_work++;
4967
4968         spin_unlock(&dev->gnd_lock);
4969
4970         RETURN(found_work);
4971 }
4972
4973 int
4974 kgnilnd_scheduler(void *arg)
4975 {
4976         int               threadno = (long)arg;
4977         kgn_device_t            *dev;
4978         int                     busy_loops = 0;
4979         unsigned long     deadline = 0;
4980         DEFINE_WAIT(wait);
4981
4982         dev = &kgnilnd_data.kgn_devices[(threadno + 1) % kgnilnd_data.kgn_ndevs];
4983
4984         cfs_block_allsigs();
4985
4986         /* all gnilnd threads need to run fairly urgently */
4987         set_user_nice(current, *kgnilnd_tunables.kgn_sched_nice);
4988         deadline = jiffies + cfs_time_seconds(*kgnilnd_tunables.kgn_sched_timeout);
4989         while (!kgnilnd_data.kgn_shutdown) {
4990                 int     found_work = 0;
4991                 /* Safe: kgn_shutdown only set when quiescent */
4992
4993                 /* to quiesce or to not quiesce, that is the question */
4994
4995                 if (unlikely(kgnilnd_data.kgn_quiesce_trigger)) {
4996                         KGNILND_SPIN_QUIESCE;
4997                 }
4998
4999                 /* tracking for when thread goes AWOL */
5000                 dev->gnd_sched_alive = jiffies;
5001
5002                 CFS_FAIL_TIMEOUT(CFS_FAIL_GNI_SCHED_DEADLINE,
5003                         (*kgnilnd_tunables.kgn_sched_timeout + 1));
5004                 /* let folks know we are up and kicking
5005                  * - they can use this for latency savings, etc
5006                  * - only change if IRQ, if IDLE leave alone as that
5007                  *   schedule_device calls to put us back to IRQ */
5008                 (void)cmpxchg(&dev->gnd_ready, GNILND_DEV_IRQ, GNILND_DEV_LOOP);
5009
5010                 down_read(&dev->gnd_conn_sem);
5011                 /* always check these - they are super low cost  */
5012                 found_work += kgnilnd_check_fma_send_cq(dev);
5013                 found_work += kgnilnd_check_fma_rcv_cq(dev);
5014
5015                 /* rdma CQ doesn't care about eps */
5016                 found_work += kgnilnd_check_rdma_cq(dev);
5017
5018                 /* move some RDMA ? */
5019                 found_work += kgnilnd_process_rdmaq(dev);
5020
5021                 /* map some pending RDMA requests ? */
5022                 found_work += kgnilnd_process_mapped_tx(dev);
5023
5024                 /* the EP for a conn is not destroyed until all the references
5025                  * to it are gone, so these checks should be safe
5026                  * even if run in parallel with the CQ checking functions
5027                  * _AND_ a thread that processes the CLOSED->DONE
5028                  * transistion
5029                  * ...should.... */
5030
5031                 up_read(&dev->gnd_conn_sem);
5032
5033                 /* process all conns ready now */
5034                 found_work += kgnilnd_process_conns(dev, deadline);
5035
5036                 /* do an eager check to avoid the IRQ disabling in
5037                  * prepare_to_wait and friends */
5038
5039                 if (found_work &&
5040                    (busy_loops++ < *kgnilnd_tunables.kgn_loops) &&
5041                    time_before(jiffies, deadline)) {
5042                         found_work = 0;
5043                         if ((busy_loops % 10) == 0) {
5044                                 /* tickle heartbeat and watchdog to ensure our
5045                                  * piggishness doesn't turn into heartbeat failure */
5046                                 touch_nmi_watchdog();
5047                                 kgnilnd_hw_hb();
5048                         }
5049                         continue;
5050                 }
5051
5052                 /* if we got here, found_work was zero or busy_loops means we
5053                  * need to take a break. We'll clear gnd_ready but we'll check
5054                  * one last time if there is an IRQ that needs processing */
5055
5056                 prepare_to_wait(&dev->gnd_waitq, &wait, TASK_INTERRUPTIBLE);
5057
5058                 /* the first time this will go LOOP -> IDLE and let us do one final check
5059                  * during which we might get an IRQ, then IDLE->IDLE and schedule()
5060                  * - this might allow other threads to block us for a bit if they
5061                  *   try to get the mutex, but that is good as we'd need to wake
5062                  *   up soon to handle the CQ or other processing anyways */
5063
5064                 found_work += xchg(&dev->gnd_ready, GNILND_DEV_IDLE);
5065
5066                 if ((busy_loops >= *kgnilnd_tunables.kgn_loops) ||
5067                    time_after_eq(jiffies, deadline)) {
5068                         CDEBUG(D_INFO,
5069                                "yeilding: found_work %d busy_loops %d\n",
5070                                found_work, busy_loops);
5071                         busy_loops = 0;
5072                         /* use yield if we are bailing due to busy_loops
5073                          * - this will ensure we wake up soonish. This closes
5074                          * a race with kgnilnd_device_callback - where it'd
5075                          * not call wake_up() because gnd_ready == 1, but then
5076                          * we come down and schedule() because of busy_loops.
5077                          * We'd not be woken up until something poked our waitq
5078                          * again. yield() ensures we wake up without another
5079                          * waitq poke in that case */
5080                         atomic_inc(&dev->gnd_n_yield);
5081                         kgnilnd_data.kgn_last_condresched = jiffies;
5082                         yield();
5083                         CDEBUG(D_INFO, "awake after yeild\n");
5084                         deadline = jiffies + cfs_time_seconds(*kgnilnd_tunables.kgn_sched_timeout);
5085                 } else if (found_work == GNILND_DEV_IDLE) {
5086                         /* busy_loops is low and there is nothing to do,
5087                          * go to sleep and wait for a waitq poke */
5088                         CDEBUG(D_INFO,
5089                                "scheduling: found_work %d busy_loops %d\n",
5090                                found_work, busy_loops);
5091                         atomic_inc(&dev->gnd_n_schedule);
5092                         kgnilnd_data.kgn_last_scheduled = jiffies;
5093                         schedule();
5094                         CDEBUG(D_INFO, "awake after schedule\n");
5095                         deadline = jiffies + cfs_time_seconds(*kgnilnd_tunables.kgn_sched_timeout);
5096                 }
5097                 finish_wait(&dev->gnd_waitq, &wait);
5098         }
5099
5100         kgnilnd_thread_fini();
5101         return 0;
5102 }