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