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