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