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