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