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