Whamcloud - gitweb
LU-17258 socklnd: stop connecting on too many retries
[fs/lustre-release.git] / lnet / klnds / socklnd / socklnd_cb.c
1 /*
2  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
3  *
4  * Copyright (c) 2011, 2017, Intel Corporation.
5  *
6  *   Author: Zach Brown <zab@zabbo.net>
7  *   Author: Peter J. Braam <braam@clusterfs.com>
8  *   Author: Phil Schwan <phil@clusterfs.com>
9  *   Author: Eric Barton <eric@bartonsoftware.com>
10  *
11  *   This file is part of Lustre, https://wiki.whamcloud.com/
12  *
13  *   Portals is free software; you can redistribute it and/or
14  *   modify it under the terms of version 2 of the GNU General Public
15  *   License as published by the Free Software Foundation.
16  *
17  *   Portals is distributed in the hope that it will be useful,
18  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
19  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  *   GNU General Public License for more details.
21  *
22  *   You should have received a copy of the GNU General Public License
23  *   along with Portals; if not, write to the Free Software
24  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25  */
26
27 #include <libcfs/linux/linux-mem.h>
28 #include "socklnd.h"
29 #include <linux/sunrpc/addr.h>
30
31 struct ksock_tx *
32 ksocknal_alloc_tx(int type, int size)
33 {
34         struct ksock_tx *tx = NULL;
35
36         if (type == KSOCK_MSG_NOOP) {
37                 LASSERT(size == KSOCK_NOOP_TX_SIZE);
38
39                 /* searching for a noop tx in free list */
40                 spin_lock(&ksocknal_data.ksnd_tx_lock);
41
42                 tx = list_first_entry_or_null(&ksocknal_data.ksnd_idle_noop_txs,
43                                               struct ksock_tx, tx_list);
44                 if (tx) {
45                         LASSERT(tx->tx_desc_size == size);
46                         list_del(&tx->tx_list);
47                 }
48
49                 spin_unlock(&ksocknal_data.ksnd_tx_lock);
50         }
51
52         if (tx == NULL)
53                 LIBCFS_ALLOC(tx, size);
54
55         if (tx == NULL)
56                 return NULL;
57
58         refcount_set(&tx->tx_refcount, 1);
59         tx->tx_zc_aborted = 0;
60         tx->tx_zc_capable = 0;
61         tx->tx_zc_checked = 0;
62         tx->tx_hstatus = LNET_MSG_STATUS_OK;
63         tx->tx_desc_size  = size;
64
65         atomic_inc(&ksocknal_data.ksnd_nactive_txs);
66
67         return tx;
68 }
69
70 struct ksock_tx *
71 ksocknal_alloc_tx_noop(__u64 cookie, int nonblk)
72 {
73         struct ksock_tx *tx;
74
75         tx = ksocknal_alloc_tx(KSOCK_MSG_NOOP, KSOCK_NOOP_TX_SIZE);
76         if (tx == NULL) {
77                 CERROR("Can't allocate noop tx desc\n");
78                 return NULL;
79         }
80
81         tx->tx_conn     = NULL;
82         tx->tx_lnetmsg  = NULL;
83         tx->tx_kiov     = NULL;
84         tx->tx_nkiov    = 0;
85         tx->tx_niov     = 1;
86         tx->tx_nonblk   = nonblk;
87
88         tx->tx_msg.ksm_csum = 0;
89         tx->tx_msg.ksm_type = KSOCK_MSG_NOOP;
90         tx->tx_msg.ksm_zc_cookies[0] = 0;
91         tx->tx_msg.ksm_zc_cookies[1] = cookie;
92
93         return tx;
94 }
95
96
97 void
98 ksocknal_free_tx(struct ksock_tx *tx)
99 {
100         atomic_dec(&ksocknal_data.ksnd_nactive_txs);
101
102         if (tx->tx_lnetmsg == NULL && tx->tx_desc_size == KSOCK_NOOP_TX_SIZE) {
103                 /* it's a noop tx */
104                 spin_lock(&ksocknal_data.ksnd_tx_lock);
105
106                 list_add(&tx->tx_list, &ksocknal_data.ksnd_idle_noop_txs);
107
108                 spin_unlock(&ksocknal_data.ksnd_tx_lock);
109         } else {
110                 LIBCFS_FREE(tx, tx->tx_desc_size);
111         }
112 }
113
114 static int
115 ksocknal_send_hdr(struct ksock_conn *conn, struct ksock_tx *tx,
116                   struct kvec *scratch_iov)
117 {
118         struct kvec *iov = &tx->tx_hdr;
119         int    nob;
120         int    rc;
121
122         LASSERT(tx->tx_niov > 0);
123
124         /* Never touch tx->tx_hdr inside ksocknal_lib_send_hdr() */
125         rc = ksocknal_lib_send_hdr(conn, tx, scratch_iov);
126
127         if (rc <= 0)                            /* sent nothing? */
128                 return rc;
129
130         nob = rc;
131         LASSERT(nob <= tx->tx_resid);
132         tx->tx_resid -= nob;
133
134         /* "consume" iov */
135         LASSERT(tx->tx_niov == 1);
136
137         if (nob < (int) iov->iov_len) {
138                 iov->iov_base += nob;
139                 iov->iov_len -= nob;
140                 return rc;
141         }
142
143         LASSERT(nob == iov->iov_len);
144         tx->tx_niov--;
145
146         return rc;
147 }
148
149 static int
150 ksocknal_send_kiov(struct ksock_conn *conn, struct ksock_tx *tx,
151                    struct kvec *scratch_iov)
152 {
153         struct bio_vec *kiov = tx->tx_kiov;
154         int nob;
155         int rc;
156
157         LASSERT(tx->tx_niov == 0);
158         LASSERT(tx->tx_nkiov > 0);
159
160         /* Never touch tx->tx_kiov inside ksocknal_lib_send_kiov() */
161         rc = ksocknal_lib_send_kiov(conn, tx, scratch_iov);
162
163         if (rc <= 0)                            /* sent nothing? */
164                 return rc;
165
166         nob = rc;
167         LASSERT(nob <= tx->tx_resid);
168         tx->tx_resid -= nob;
169
170         /* "consume" kiov */
171         do {
172                 LASSERT(tx->tx_nkiov > 0);
173
174                 if (nob < (int)kiov->bv_len) {
175                         kiov->bv_offset += nob;
176                         kiov->bv_len -= nob;
177                         return rc;
178                 }
179
180                 nob -= (int)kiov->bv_len;
181                 tx->tx_kiov = ++kiov;
182                 tx->tx_nkiov--;
183         } while (nob != 0);
184
185         return rc;
186 }
187
188 static int
189 ksocknal_transmit(struct ksock_conn *conn, struct ksock_tx *tx,
190                   struct kvec *scratch_iov)
191 {
192         int     rc;
193         int     bufnob;
194
195         if (ksocknal_data.ksnd_stall_tx != 0)
196                 schedule_timeout_uninterruptible(
197                         cfs_time_seconds(ksocknal_data.ksnd_stall_tx));
198
199         LASSERT(tx->tx_resid != 0);
200
201         rc = ksocknal_connsock_addref(conn);
202         if (rc != 0) {
203                 LASSERT(conn->ksnc_closing);
204                 return -ESHUTDOWN;
205         }
206
207         do {
208                 if (ksocknal_data.ksnd_enomem_tx > 0) {
209                         /* testing... */
210                         ksocknal_data.ksnd_enomem_tx--;
211                         rc = -EAGAIN;
212                 } else if (tx->tx_niov != 0) {
213                         rc = ksocknal_send_hdr(conn, tx, scratch_iov);
214                 } else {
215                         rc = ksocknal_send_kiov(conn, tx, scratch_iov);
216                 }
217
218                 bufnob = conn->ksnc_sock->sk->sk_wmem_queued;
219                 if (rc > 0)                     /* sent something? */
220                         conn->ksnc_tx_bufnob += rc; /* account it */
221
222                 if (bufnob < conn->ksnc_tx_bufnob) {
223                         /* allocated send buffer bytes < computed; infer
224                          * something got ACKed */
225                         conn->ksnc_tx_deadline = ktime_get_seconds() +
226                                                  ksocknal_timeout();
227                         conn->ksnc_peer->ksnp_last_alive = ktime_get_seconds();
228                         conn->ksnc_tx_bufnob = bufnob;
229                         smp_mb();
230                 }
231
232                 if (rc <= 0) { /* Didn't write anything? */
233                         /* some stacks return 0 instead of -EAGAIN */
234                         if (rc == 0)
235                                 rc = -EAGAIN;
236
237                         /* Check if EAGAIN is due to memory pressure */
238                         if (rc == -EAGAIN && ksocknal_lib_memory_pressure(conn))
239                                 rc = -ENOMEM;
240
241                         break;
242                 }
243
244                 /* socket's wmem_queued now includes 'rc' bytes */
245                 atomic_sub (rc, &conn->ksnc_tx_nob);
246                 rc = 0;
247
248         } while (tx->tx_resid != 0);
249
250         ksocknal_connsock_decref(conn);
251         return rc;
252 }
253
254 static int
255 ksocknal_recv_iov(struct ksock_conn *conn, struct kvec *scratchiov)
256 {
257         struct kvec *iov = conn->ksnc_rx_iov;
258         int     nob;
259         int     rc;
260
261         LASSERT(conn->ksnc_rx_niov > 0);
262
263         /* Never touch conn->ksnc_rx_iov or change connection
264          * status inside ksocknal_lib_recv_iov */
265         rc = ksocknal_lib_recv_iov(conn, scratchiov);
266
267         if (rc <= 0)
268                 return rc;
269
270         /* received something... */
271         nob = rc;
272
273         conn->ksnc_peer->ksnp_last_alive = ktime_get_seconds();
274         conn->ksnc_rx_deadline = ktime_get_seconds() +
275                                  ksocknal_timeout();
276         smp_mb();                       /* order with setting rx_started */
277         conn->ksnc_rx_started = 1;
278
279         conn->ksnc_rx_nob_wanted -= nob;
280         conn->ksnc_rx_nob_left -= nob;
281
282         do {
283                 LASSERT(conn->ksnc_rx_niov > 0);
284
285                 if (nob < (int)iov->iov_len) {
286                         iov->iov_len -= nob;
287                         iov->iov_base += nob;
288                         return -EAGAIN;
289                 }
290
291                 nob -= iov->iov_len;
292                 conn->ksnc_rx_iov = ++iov;
293                 conn->ksnc_rx_niov--;
294         } while (nob != 0);
295
296         return rc;
297 }
298
299 static int
300 ksocknal_recv_kiov(struct ksock_conn *conn, struct page **rx_scratch_pgs,
301                    struct kvec *scratch_iov)
302 {
303         struct bio_vec *kiov = conn->ksnc_rx_kiov;
304         int nob;
305         int rc;
306
307         LASSERT(conn->ksnc_rx_nkiov > 0);
308         /* Never touch conn->ksnc_rx_kiov or change connection
309          * status inside ksocknal_lib_recv_iov */
310         rc = ksocknal_lib_recv_kiov(conn, rx_scratch_pgs, scratch_iov);
311
312         if (rc <= 0)
313                 return rc;
314
315         /* received something... */
316         nob = rc;
317
318         conn->ksnc_peer->ksnp_last_alive = ktime_get_seconds();
319         conn->ksnc_rx_deadline = ktime_get_seconds() +
320                                  ksocknal_timeout();
321         smp_mb();                       /* order with setting rx_started */
322         conn->ksnc_rx_started = 1;
323
324         conn->ksnc_rx_nob_wanted -= nob;
325         conn->ksnc_rx_nob_left -= nob;
326
327         do {
328                 LASSERT(conn->ksnc_rx_nkiov > 0);
329
330                 if (nob < (int) kiov->bv_len) {
331                         kiov->bv_offset += nob;
332                         kiov->bv_len -= nob;
333                         return -EAGAIN;
334                 }
335
336                 nob -= kiov->bv_len;
337                 conn->ksnc_rx_kiov = ++kiov;
338                 conn->ksnc_rx_nkiov--;
339         } while (nob != 0);
340
341         return 1;
342 }
343
344 static int
345 ksocknal_receive(struct ksock_conn *conn, struct page **rx_scratch_pgs,
346                  struct kvec *scratch_iov)
347 {
348         /* Return 1 on success, 0 on EOF, < 0 on error.
349          * Caller checks ksnc_rx_nob_wanted to determine
350          * progress/completion. */
351         int     rc;
352         ENTRY;
353
354         if (ksocknal_data.ksnd_stall_rx != 0)
355                 schedule_timeout_uninterruptible(
356                         cfs_time_seconds(ksocknal_data.ksnd_stall_rx));
357
358         rc = ksocknal_connsock_addref(conn);
359         if (rc != 0) {
360                 LASSERT(conn->ksnc_closing);
361                 return -ESHUTDOWN;
362         }
363
364         for (;;) {
365                 if (conn->ksnc_rx_niov != 0)
366                         rc = ksocknal_recv_iov(conn, scratch_iov);
367                 else
368                         rc = ksocknal_recv_kiov(conn, rx_scratch_pgs,
369                                                  scratch_iov);
370
371                 if (rc <= 0) {
372                         /* error/EOF or partial receive */
373                         if (rc == -EAGAIN) {
374                                 rc = 1;
375                         } else if (rc == 0 && conn->ksnc_rx_started) {
376                                 /* EOF in the middle of a message */
377                                 rc = -EPROTO;
378                         }
379                         break;
380                 }
381
382                 /* Completed a fragment */
383
384                 if (conn->ksnc_rx_nob_wanted == 0) {
385                         rc = 1;
386                         break;
387                 }
388         }
389
390         ksocknal_connsock_decref(conn);
391         RETURN(rc);
392 }
393
394 void
395 ksocknal_tx_done(struct lnet_ni *ni, struct ksock_tx *tx, int rc)
396 {
397         struct lnet_msg *lnetmsg = tx->tx_lnetmsg;
398         enum lnet_msg_hstatus hstatus = tx->tx_hstatus;
399
400         LASSERT(ni != NULL || tx->tx_conn != NULL);
401
402         if (!rc && (tx->tx_resid != 0 || tx->tx_zc_aborted)) {
403                 rc = -EIO;
404                 if (hstatus == LNET_MSG_STATUS_OK)
405                         hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
406         }
407
408         if (tx->tx_conn != NULL)
409                 ksocknal_conn_decref(tx->tx_conn);
410
411         ksocknal_free_tx(tx);
412         if (lnetmsg != NULL) { /* KSOCK_MSG_NOOP go without lnetmsg */
413                 lnetmsg->msg_health_status = hstatus;
414                 lnet_finalize(lnetmsg, rc);
415         }
416 }
417
418 void
419 ksocknal_txlist_done(struct lnet_ni *ni, struct list_head *txlist, int error)
420 {
421         struct ksock_tx *tx;
422
423         while ((tx = list_first_entry_or_null(txlist, struct ksock_tx,
424                                               tx_list)) != NULL) {
425                 if (error && tx->tx_lnetmsg) {
426                         CNETERR("Deleting packet type %d len %d %s->%s\n",
427                                 tx->tx_lnetmsg->msg_type,
428                                 tx->tx_lnetmsg->msg_len,
429                                 libcfs_nidstr(&tx->tx_lnetmsg->msg_initiator),
430                                 libcfs_nidstr(&tx->tx_lnetmsg->msg_target.nid));
431                 } else if (error) {
432                         CNETERR("Deleting noop packet\n");
433                 }
434
435                 list_del(&tx->tx_list);
436
437                 if (tx->tx_hstatus == LNET_MSG_STATUS_OK) {
438                         if (error == -ETIMEDOUT)
439                                 tx->tx_hstatus =
440                                         LNET_MSG_STATUS_NETWORK_TIMEOUT;
441                         else if (error == -ENETDOWN ||
442                                  error == -EHOSTUNREACH ||
443                                  error == -ENETUNREACH ||
444                                  error == -ECONNREFUSED ||
445                                  error == -ECONNRESET)
446                                 tx->tx_hstatus = LNET_MSG_STATUS_REMOTE_DROPPED;
447                         /*
448                          * for all other errors we don't want to
449                          * retransmit
450                          */
451                         else if (error)
452                                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
453                 }
454
455                 LASSERT(refcount_read(&tx->tx_refcount) == 1);
456                 ksocknal_tx_done(ni, tx, error);
457         }
458 }
459
460 static void
461 ksocknal_check_zc_req(struct ksock_tx *tx)
462 {
463         struct ksock_conn *conn = tx->tx_conn;
464         struct ksock_peer_ni *peer_ni = conn->ksnc_peer;
465
466         /* Set tx_msg.ksm_zc_cookies[0] to a unique non-zero cookie and add tx
467          * to ksnp_zc_req_list if some fragment of this message should be sent
468          * zero-copy.  Our peer_ni will send an ACK containing this cookie when
469          * she has received this message to tell us we can signal completion.
470          * tx_msg.ksm_zc_cookies[0] remains non-zero while tx is on
471          * ksnp_zc_req_list. */
472         LASSERT (tx->tx_msg.ksm_type != KSOCK_MSG_NOOP);
473         LASSERT (tx->tx_zc_capable);
474
475         tx->tx_zc_checked = 1;
476
477         if (conn->ksnc_proto == &ksocknal_protocol_v1x ||
478             !conn->ksnc_zc_capable)
479                 return;
480
481         /* assign cookie and queue tx to pending list, it will be released when
482          * a matching ack is received. See ksocknal_handle_zcack() */
483
484         ksocknal_tx_addref(tx);
485
486         spin_lock(&peer_ni->ksnp_lock);
487
488         /* ZC_REQ is going to be pinned to the peer_ni */
489         tx->tx_deadline = ktime_get_seconds() +
490                           ksocknal_timeout();
491
492         LASSERT (tx->tx_msg.ksm_zc_cookies[0] == 0);
493
494         tx->tx_msg.ksm_zc_cookies[0] = peer_ni->ksnp_zc_next_cookie++;
495
496         if (peer_ni->ksnp_zc_next_cookie == 0)
497                 peer_ni->ksnp_zc_next_cookie = SOCKNAL_KEEPALIVE_PING + 1;
498
499         list_add_tail(&tx->tx_zc_list, &peer_ni->ksnp_zc_req_list);
500
501         spin_unlock(&peer_ni->ksnp_lock);
502 }
503
504 static void
505 ksocknal_uncheck_zc_req(struct ksock_tx *tx)
506 {
507         struct ksock_peer_ni *peer_ni = tx->tx_conn->ksnc_peer;
508
509         LASSERT(tx->tx_msg.ksm_type != KSOCK_MSG_NOOP);
510         LASSERT(tx->tx_zc_capable);
511
512         tx->tx_zc_checked = 0;
513
514         spin_lock(&peer_ni->ksnp_lock);
515
516         if (tx->tx_msg.ksm_zc_cookies[0] == 0) {
517                 /* Not waiting for an ACK */
518                 spin_unlock(&peer_ni->ksnp_lock);
519                 return;
520         }
521
522         tx->tx_msg.ksm_zc_cookies[0] = 0;
523         list_del(&tx->tx_zc_list);
524
525         spin_unlock(&peer_ni->ksnp_lock);
526
527         ksocknal_tx_decref(tx);
528 }
529
530 static int
531 ksocknal_process_transmit(struct ksock_conn *conn, struct ksock_tx *tx,
532                           struct kvec *scratch_iov)
533 {
534         int rc;
535         bool error_sim = false;
536
537         if (lnet_send_error_simulation(tx->tx_lnetmsg, &tx->tx_hstatus)) {
538                 error_sim = true;
539                 rc = -EINVAL;
540                 goto simulate_error;
541         }
542
543         if (tx->tx_zc_capable && !tx->tx_zc_checked)
544                 ksocknal_check_zc_req(tx);
545
546         rc = ksocknal_transmit(conn, tx, scratch_iov);
547
548         CDEBUG(D_NET, "send(%d) %d\n", tx->tx_resid, rc);
549
550         if (tx->tx_resid == 0) {
551                 /* Sent everything OK */
552                 LASSERT(rc == 0);
553
554                 return 0;
555         }
556
557         if (rc == -EAGAIN)
558                 return rc;
559
560         if (rc == -ENOMEM) {
561                 static int counter;
562
563                 counter++;   /* exponential backoff warnings */
564                 if ((counter & (-counter)) == counter)
565                         CWARN("%u ENOMEM tx %p (%lld allocated)\n",
566                               counter, conn, libcfs_kmem_read());
567
568                 /* Queue on ksnd_enomem_conns for retry after a timeout */
569                 spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
570
571                 /* enomem list takes over scheduler's ref... */
572                 LASSERT(conn->ksnc_tx_scheduled);
573                 list_add_tail(&conn->ksnc_tx_list,
574                                   &ksocknal_data.ksnd_enomem_conns);
575                 if (ktime_get_seconds() + SOCKNAL_ENOMEM_RETRY <
576                     ksocknal_data.ksnd_reaper_waketime)
577                         wake_up(&ksocknal_data.ksnd_reaper_waitq);
578
579                 spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
580
581                 /*
582                  * set the health status of the message which determines
583                  * whether we should retry the transmit
584                  */
585                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
586                 return (rc);
587         }
588
589 simulate_error:
590
591         /* Actual error */
592         LASSERT(rc < 0);
593
594         if (!error_sim) {
595                 /*
596                 * set the health status of the message which determines
597                 * whether we should retry the transmit
598                 */
599                 if (rc == -ETIMEDOUT)
600                         tx->tx_hstatus = LNET_MSG_STATUS_REMOTE_TIMEOUT;
601                 else
602                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
603         }
604
605         if (!conn->ksnc_closing) {
606                 switch (rc) {
607                 case -ECONNRESET:
608                         LCONSOLE_WARN("Host %pISc reset our connection while we were sending data; it may have rebooted: rc = %d\n",
609                                       &conn->ksnc_peeraddr, rc);
610                         break;
611                 case -ETIMEDOUT:
612                         LCONSOLE_WARN("Timeout error while writing to %pISp. Closing socket: rc = %d\n",
613                                       &conn->ksnc_peeraddr, rc);
614                         break;
615                 default:
616                         LCONSOLE_WARN("There was an unexpected network error while writing to %pISc: rc = %d\n",
617                                       &conn->ksnc_peeraddr, rc);
618                         break;
619                 }
620                 CDEBUG(D_NET, "[%p] Error %d on write to %s ip %pIScp\n",
621                        conn, rc, libcfs_idstr(&conn->ksnc_peer->ksnp_id),
622                        &conn->ksnc_peeraddr);
623         }
624
625         if (tx->tx_zc_checked)
626                 ksocknal_uncheck_zc_req(tx);
627
628         /* it's not an error if conn is being closed */
629         ksocknal_close_conn_and_siblings(conn,
630                                           (conn->ksnc_closing) ? 0 : rc);
631
632         return rc;
633 }
634
635 static void
636 ksocknal_launch_connection_locked(struct ksock_conn_cb *conn_cb)
637 {
638         /* called holding write lock on ksnd_global_lock */
639
640         LASSERT(!conn_cb->ksnr_scheduled);
641         LASSERT(!conn_cb->ksnr_connecting);
642         LASSERT((ksocknal_conn_cb_mask() & ~conn_cb->ksnr_connected) != 0);
643
644         /* scheduling conn for connd */
645         conn_cb->ksnr_scheduled = 1;
646
647         /* extra ref for connd */
648         ksocknal_conn_cb_addref(conn_cb);
649
650         spin_lock_bh(&ksocknal_data.ksnd_connd_lock);
651
652         list_add_tail(&conn_cb->ksnr_connd_list,
653                       &ksocknal_data.ksnd_connd_routes);
654         wake_up(&ksocknal_data.ksnd_connd_waitq);
655
656         spin_unlock_bh(&ksocknal_data.ksnd_connd_lock);
657 }
658
659 void
660 ksocknal_launch_all_connections_locked(struct ksock_peer_ni *peer_ni)
661 {
662         struct ksock_conn_cb *conn_cb;
663
664         /* called holding write lock on ksnd_global_lock */
665         for (;;) {
666                 /* launch any/all connections that need it */
667                 conn_cb = ksocknal_find_connectable_conn_cb_locked(peer_ni);
668                 if (conn_cb == NULL)
669                         return;
670
671                 ksocknal_launch_connection_locked(conn_cb);
672         }
673 }
674
675 struct ksock_conn *
676 ksocknal_find_conn_locked(struct ksock_peer_ni *peer_ni, struct ksock_tx *tx, int nonblk)
677 {
678         struct ksock_conn *c;
679         struct ksock_conn *conn;
680         struct ksock_conn *typed = NULL;
681         struct ksock_conn *fallback = NULL;
682         int tnob = 0;
683         int fnob = 0;
684
685         list_for_each_entry(c, &peer_ni->ksnp_conns, ksnc_list) {
686                 int nob = atomic_read(&c->ksnc_tx_nob) +
687                           c->ksnc_sock->sk->sk_wmem_queued;
688                 int rc;
689
690                 LASSERT (!c->ksnc_closing);
691                 LASSERT (c->ksnc_proto != NULL &&
692                          c->ksnc_proto->pro_match_tx != NULL);
693
694                 rc = c->ksnc_proto->pro_match_tx(c, tx, nonblk);
695
696                 switch (rc) {
697                 default:
698                         LBUG();
699                 case SOCKNAL_MATCH_NO: /* protocol rejected the tx */
700                         continue;
701
702                 case SOCKNAL_MATCH_YES: /* typed connection */
703                         if (typed == NULL || tnob > nob ||
704                             (tnob == nob && *ksocknal_tunables.ksnd_round_robin &&
705                              typed->ksnc_tx_last_post > c->ksnc_tx_last_post)) {
706                                 typed = c;
707                                 tnob  = nob;
708                         }
709                         break;
710
711                 case SOCKNAL_MATCH_MAY: /* fallback connection */
712                         if (fallback == NULL || fnob > nob ||
713                             (fnob == nob && *ksocknal_tunables.ksnd_round_robin &&
714                              fallback->ksnc_tx_last_post > c->ksnc_tx_last_post)) {
715                                 fallback = c;
716                                 fnob     = nob;
717                         }
718                         break;
719                 }
720         }
721
722         /* prefer the typed selection */
723         conn = (typed != NULL) ? typed : fallback;
724
725         if (conn != NULL)
726                 conn->ksnc_tx_last_post = ktime_get_seconds();
727
728         return conn;
729 }
730
731 void
732 ksocknal_tx_prep(struct ksock_conn *conn, struct ksock_tx *tx)
733 {
734         conn->ksnc_proto->pro_pack(tx);
735
736         atomic_add (tx->tx_nob, &conn->ksnc_tx_nob);
737         ksocknal_conn_addref(conn); /* +1 ref for tx */
738         tx->tx_conn = conn;
739 }
740
741 void
742 ksocknal_queue_tx_locked(struct ksock_tx *tx, struct ksock_conn *conn)
743 {
744         struct ksock_sched *sched = conn->ksnc_scheduler;
745         struct ksock_msg *msg = &tx->tx_msg;
746         struct ksock_tx *ztx = NULL;
747         int bufnob = 0;
748
749         /* called holding global lock (read or irq-write) and caller may
750          * not have dropped this lock between finding conn and calling me,
751          * so we don't need the {get,put}connsock dance to deref
752          * ksnc_sock... */
753         LASSERT(!conn->ksnc_closing);
754
755         CDEBUG(D_NET, "Sending to %s ip %pIScp\n",
756                libcfs_idstr(&conn->ksnc_peer->ksnp_id),
757                &conn->ksnc_peeraddr);
758
759         ksocknal_tx_prep(conn, tx);
760
761         /* Ensure the frags we've been given EXACTLY match the number of
762          * bytes we want to send.  Many TCP/IP stacks disregard any total
763          * size parameters passed to them and just look at the frags.
764          *
765          * We always expect at least 1 mapped fragment containing the
766          * complete ksocknal message header.
767          */
768         LASSERT(lnet_iov_nob(tx->tx_niov, &tx->tx_hdr) +
769                 lnet_kiov_nob(tx->tx_nkiov, tx->tx_kiov) ==
770                 (unsigned int)tx->tx_nob);
771         LASSERT(tx->tx_niov >= 1);
772         LASSERT(tx->tx_resid == tx->tx_nob);
773
774         CDEBUG(D_NET, "Packet %p type %d, nob %d niov %d nkiov %d\n",
775                tx, tx->tx_lnetmsg ? tx->tx_lnetmsg->msg_type : KSOCK_MSG_NOOP,
776                tx->tx_nob, tx->tx_niov, tx->tx_nkiov);
777
778         bufnob = conn->ksnc_sock->sk->sk_wmem_queued;
779         spin_lock_bh(&sched->kss_lock);
780
781         if (list_empty(&conn->ksnc_tx_queue) && bufnob == 0) {
782                 /* First packet starts the timeout */
783                 conn->ksnc_tx_deadline = ktime_get_seconds() +
784                                          ksocknal_timeout();
785                 if (conn->ksnc_tx_bufnob > 0) /* something got ACKed */
786                         conn->ksnc_peer->ksnp_last_alive = ktime_get_seconds();
787                 conn->ksnc_tx_bufnob = 0;
788                 smp_mb(); /* order with adding to tx_queue */
789         }
790
791         if (msg->ksm_type == KSOCK_MSG_NOOP) {
792                 /* The packet is noop ZC ACK, try to piggyback the ack_cookie
793                  * on a normal packet so I don't need to send it */
794                 LASSERT (msg->ksm_zc_cookies[1] != 0);
795                 LASSERT (conn->ksnc_proto->pro_queue_tx_zcack != NULL);
796
797                 if (conn->ksnc_proto->pro_queue_tx_zcack(conn, tx, 0))
798                         ztx = tx; /* ZC ACK piggybacked on ztx release tx later */
799
800         } else {
801                 /* It's a normal packet - can it piggback a noop zc-ack that
802                  * has been queued already? */
803                 LASSERT (msg->ksm_zc_cookies[1] == 0);
804                 LASSERT (conn->ksnc_proto->pro_queue_tx_msg != NULL);
805
806                 ztx = conn->ksnc_proto->pro_queue_tx_msg(conn, tx);
807                 /* ztx will be released later */
808         }
809
810         if (ztx != NULL) {
811                 atomic_sub (ztx->tx_nob, &conn->ksnc_tx_nob);
812                 list_add_tail(&ztx->tx_list, &sched->kss_zombie_noop_txs);
813         }
814
815         if (conn->ksnc_tx_ready &&      /* able to send */
816             !conn->ksnc_tx_scheduled) { /* not scheduled to send */
817                 /* +1 ref for scheduler */
818                 ksocknal_conn_addref(conn);
819                 list_add_tail(&conn->ksnc_tx_list,
820                                    &sched->kss_tx_conns);
821                 conn->ksnc_tx_scheduled = 1;
822                 wake_up(&sched->kss_waitq);
823         }
824
825         spin_unlock_bh(&sched->kss_lock);
826 }
827
828
829 struct ksock_conn_cb *
830 ksocknal_find_connectable_conn_cb_locked(struct ksock_peer_ni *peer_ni)
831 {
832         time64_t now = ktime_get_seconds();
833         struct ksock_conn_cb *conn_cb;
834
835         conn_cb = peer_ni->ksnp_conn_cb;
836         if (!conn_cb)
837                 return NULL;
838
839         LASSERT(!conn_cb->ksnr_connecting || conn_cb->ksnr_scheduled);
840
841         if (conn_cb->ksnr_scheduled)    /* connections being established */
842                 return NULL;
843
844         /* all conn types connected ? */
845         if ((ksocknal_conn_cb_mask() & ~conn_cb->ksnr_connected) == 0)
846                 return NULL;
847
848         if (!(conn_cb->ksnr_retry_interval == 0 || /* first attempt */
849               now >= conn_cb->ksnr_timeout)) {
850                 CDEBUG(D_NET,
851                        "Too soon to retry route %pISc (cnted %d, interval %lld, %lld secs later)\n",
852                        &conn_cb->ksnr_addr,
853                        conn_cb->ksnr_connected,
854                        conn_cb->ksnr_retry_interval,
855                        conn_cb->ksnr_timeout - now);
856                 return NULL;
857         }
858
859         return conn_cb;
860 }
861
862 struct ksock_conn_cb *
863 ksocknal_find_connecting_conn_cb_locked(struct ksock_peer_ni *peer_ni)
864 {
865         struct ksock_conn_cb *conn_cb;
866
867         conn_cb = peer_ni->ksnp_conn_cb;
868         if (!conn_cb)
869                 return NULL;
870
871         LASSERT(!conn_cb->ksnr_connecting || conn_cb->ksnr_scheduled);
872
873         return conn_cb->ksnr_scheduled ? conn_cb : NULL;
874 }
875
876 int
877 ksocknal_launch_packet(struct lnet_ni *ni, struct ksock_tx *tx,
878                        struct lnet_processid *id)
879 {
880         struct ksock_peer_ni *peer_ni;
881         struct ksock_conn *conn;
882         struct sockaddr_storage sa;
883         rwlock_t *g_lock;
884         int retry;
885         int rc;
886
887         LASSERT(tx->tx_conn == NULL);
888
889         g_lock = &ksocknal_data.ksnd_global_lock;
890
891         for (retry = 0;; retry = 1) {
892                 read_lock(g_lock);
893                 peer_ni = ksocknal_find_peer_locked(ni, id);
894                 if (peer_ni != NULL) {
895                         if (ksocknal_find_connectable_conn_cb_locked(peer_ni) == NULL) {
896                                 conn = ksocknal_find_conn_locked(peer_ni, tx, tx->tx_nonblk);
897                                 if (conn != NULL) {
898                                         /* I've got nothing that need to be
899                                          * connecting and I do have an actual
900                                          * connection...
901                                          */
902                                         ksocknal_queue_tx_locked(tx, conn);
903                                         read_unlock(g_lock);
904                                         return 0;
905                                 }
906                         }
907                 }
908
909                 /* I'll need a write lock... */
910                 read_unlock(g_lock);
911
912                 write_lock_bh(g_lock);
913
914                 peer_ni = ksocknal_find_peer_locked(ni, id);
915                 if (peer_ni != NULL)
916                         break;
917
918                 write_unlock_bh(g_lock);
919
920                 if ((id->pid & LNET_PID_USERFLAG) != 0) {
921                         CERROR("Refusing to create a connection to userspace process %s\n",
922                                libcfs_idstr(id));
923                         return -EHOSTUNREACH;
924                 }
925
926                 if (retry) {
927                         CERROR("Can't find peer_ni %s\n", libcfs_idstr(id));
928                         return -EHOSTUNREACH;
929                 }
930
931                 memset(&sa, 0, sizeof(sa));
932                 switch (NID_ADDR_BYTES(&id->nid)) {
933                         struct sockaddr_in *sin;
934                         struct sockaddr_in6 *sin6;
935                 case 4:
936                         sin = (void *)&sa;
937                         sin->sin_family = AF_INET;
938                         sin->sin_addr.s_addr = id->nid.nid_addr[0];
939                         sin->sin_port = htons(lnet_acceptor_port());
940                         break;
941                 case 16:
942                         sin6 = (void *)&sa;
943                         sin6->sin6_family = AF_INET6;
944                         memcpy(&sin6->sin6_addr, id->nid.nid_addr,
945                                sizeof(sin6->sin6_addr));
946                         sin6->sin6_port = htons(lnet_acceptor_port());
947                         break;
948                 }
949                 rc = ksocknal_add_peer(ni, id, (struct sockaddr *)&sa);
950                 if (rc != 0) {
951                         CERROR("Can't add peer_ni %s: %d\n",
952                                libcfs_idstr(id), rc);
953                         return rc;
954                 }
955         }
956
957         ksocknal_launch_all_connections_locked(peer_ni);
958
959         conn = ksocknal_find_conn_locked(peer_ni, tx, tx->tx_nonblk);
960         if (conn != NULL) {
961                 /* Connection exists; queue message on it */
962                 ksocknal_queue_tx_locked (tx, conn);
963                 write_unlock_bh(g_lock);
964                 return (0);
965         }
966
967         if (peer_ni->ksnp_accepting > 0 ||
968             ksocknal_find_connecting_conn_cb_locked(peer_ni) != NULL) {
969                 /* the message is going to be pinned to the peer_ni */
970                 tx->tx_deadline = ktime_get_seconds() +
971                                   ksocknal_timeout();
972
973                 /* Queue the message until a connection is established */
974                 list_add_tail(&tx->tx_list, &peer_ni->ksnp_tx_queue);
975                 write_unlock_bh(g_lock);
976                 return 0;
977         }
978
979         write_unlock_bh(g_lock);
980
981         /* NB Routes may be ignored if connections to them failed recently */
982         CNETERR("No usable routes to %s\n", libcfs_idstr(id));
983         tx->tx_hstatus = LNET_MSG_STATUS_REMOTE_ERROR;
984         return (-EHOSTUNREACH);
985 }
986
987 int
988 ksocknal_send(struct lnet_ni *ni, void *private, struct lnet_msg *lntmsg)
989 {
990         /* '1' for consistency with code that checks !mpflag to restore */
991         unsigned int mpflag = 1;
992         int type = lntmsg->msg_type;
993         struct lnet_processid *target = &lntmsg->msg_target;
994         unsigned int payload_niov = lntmsg->msg_niov;
995         struct bio_vec *payload_kiov = lntmsg->msg_kiov;
996         unsigned int payload_offset = lntmsg->msg_offset;
997         unsigned int payload_nob = lntmsg->msg_len;
998         struct ksock_tx *tx;
999         int desc_size;
1000         int rc;
1001
1002         /* NB 'private' is different depending on what we're sending.
1003          * Just ignore it...
1004          */
1005
1006         CDEBUG(D_NET, "sending %u bytes in %d frags to %s\n",
1007                payload_nob, payload_niov, libcfs_idstr(target));
1008
1009         LASSERT (payload_nob == 0 || payload_niov > 0);
1010         LASSERT (!in_interrupt ());
1011
1012         desc_size = offsetof(struct ksock_tx,
1013                              tx_payload[payload_niov]);
1014
1015         if (lntmsg->msg_vmflush)
1016                 mpflag = memalloc_noreclaim_save();
1017
1018         tx = ksocknal_alloc_tx(KSOCK_MSG_LNET, desc_size);
1019         if (tx == NULL) {
1020                 CERROR("Can't allocate tx desc type %d size %d\n",
1021                        type, desc_size);
1022                 if (lntmsg->msg_vmflush)
1023                         memalloc_noreclaim_restore(mpflag);
1024                 return -ENOMEM;
1025         }
1026
1027         tx->tx_conn = NULL;                     /* set when assigned a conn */
1028         tx->tx_lnetmsg = lntmsg;
1029
1030         tx->tx_niov = 1;
1031         tx->tx_kiov = tx->tx_payload;
1032         tx->tx_nkiov = lnet_extract_kiov(payload_niov, tx->tx_kiov,
1033                                          payload_niov, payload_kiov,
1034                                          payload_offset, payload_nob);
1035
1036         LASSERT(tx->tx_nkiov <= LNET_MAX_IOV);
1037
1038         if (payload_nob >= *ksocknal_tunables.ksnd_zc_min_payload)
1039                 tx->tx_zc_capable = 1;
1040
1041         tx->tx_msg.ksm_csum = 0;
1042         tx->tx_msg.ksm_type = KSOCK_MSG_LNET;
1043         tx->tx_msg.ksm_zc_cookies[0] = 0;
1044         tx->tx_msg.ksm_zc_cookies[1] = 0;
1045
1046         /* The first fragment will be set later in pro_pack */
1047         rc = ksocknal_launch_packet(ni, tx, target);
1048         /*
1049          * We can't test lntsmg->msg_vmflush again as lntmsg may
1050          * have been freed.
1051          */
1052         if (!mpflag)
1053                 memalloc_noreclaim_restore(mpflag);
1054
1055         if (rc == 0)
1056                 return (0);
1057
1058         lntmsg->msg_health_status = tx->tx_hstatus;
1059         ksocknal_free_tx(tx);
1060         return -EIO;
1061 }
1062
1063 void
1064 ksocknal_thread_fini (void)
1065 {
1066         if (atomic_dec_and_test(&ksocknal_data.ksnd_nthreads))
1067                 wake_up_var(&ksocknal_data.ksnd_nthreads);
1068 }
1069
1070 int
1071 ksocknal_new_packet(struct ksock_conn *conn, int nob_to_skip)
1072 {
1073         static char ksocknal_slop_buffer[4096];
1074         int nob;
1075         unsigned int niov;
1076         int skipped;
1077
1078         LASSERT(conn->ksnc_proto != NULL);
1079
1080         if ((*ksocknal_tunables.ksnd_eager_ack & conn->ksnc_type) != 0) {
1081                 /* Remind the socket to ack eagerly... */
1082                 ksocknal_lib_eager_ack(conn);
1083         }
1084
1085         if (nob_to_skip == 0) {         /* right at next packet boundary now */
1086                 conn->ksnc_rx_started = 0;
1087                 smp_mb();                       /* racing with timeout thread */
1088
1089                 switch (conn->ksnc_proto->pro_version) {
1090                 case KSOCK_PROTO_V2:
1091                 case KSOCK_PROTO_V3:
1092                 case KSOCK_PROTO_V4:
1093                         conn->ksnc_rx_state = SOCKNAL_RX_KSM_HEADER;
1094                         conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
1095                         conn->ksnc_rx_iov[0].iov_base = (char *)&conn->ksnc_msg;
1096
1097                         conn->ksnc_rx_nob_wanted = sizeof(struct ksock_msg_hdr);
1098                         conn->ksnc_rx_nob_left = sizeof(struct ksock_msg_hdr);
1099                         conn->ksnc_rx_iov[0].iov_len =
1100                                 sizeof(struct ksock_msg_hdr);
1101                         break;
1102
1103                 case KSOCK_PROTO_V1:
1104                         /* Receiving bare struct lnet_hdr_nid4 */
1105                         conn->ksnc_rx_state = SOCKNAL_RX_LNET_HEADER;
1106                         conn->ksnc_rx_nob_wanted = sizeof(struct lnet_hdr_nid4);
1107                         conn->ksnc_rx_nob_left = sizeof(struct lnet_hdr_nid4);
1108
1109                         conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
1110                         conn->ksnc_rx_iov[0].iov_base =
1111                                 (void *)&conn->ksnc_msg.ksm_u.lnetmsg_nid4;
1112                         conn->ksnc_rx_iov[0].iov_len =
1113                                 sizeof(struct lnet_hdr_nid4);
1114                         break;
1115
1116                 default:
1117                         LBUG();
1118                 }
1119                 conn->ksnc_rx_niov = 1;
1120
1121                 conn->ksnc_rx_kiov = NULL;
1122                 conn->ksnc_rx_nkiov = 0;
1123                 conn->ksnc_rx_csum = ~0;
1124                 return (1);
1125         }
1126
1127         /* Set up to skip as much as possible now.  If there's more left
1128          * (ran out of iov entries) we'll get called again */
1129
1130         conn->ksnc_rx_state = SOCKNAL_RX_SLOP;
1131         conn->ksnc_rx_nob_left = nob_to_skip;
1132         conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
1133         skipped = 0;
1134         niov = 0;
1135
1136         do {
1137                 nob = min_t(int, nob_to_skip, sizeof(ksocknal_slop_buffer));
1138
1139                 conn->ksnc_rx_iov[niov].iov_base = ksocknal_slop_buffer;
1140                 conn->ksnc_rx_iov[niov].iov_len  = nob;
1141                 niov++;
1142                 skipped += nob;
1143                 nob_to_skip -= nob;
1144
1145         } while (nob_to_skip != 0 &&    /* mustn't overflow conn's rx iov */
1146                  niov < sizeof(conn->ksnc_rx_iov_space) / sizeof(struct kvec));
1147
1148         conn->ksnc_rx_niov = niov;
1149         conn->ksnc_rx_kiov = NULL;
1150         conn->ksnc_rx_nkiov = 0;
1151         conn->ksnc_rx_nob_wanted = skipped;
1152         return (0);
1153 }
1154
1155 static int
1156 ksocknal_process_receive(struct ksock_conn *conn,
1157                          struct page **rx_scratch_pgs,
1158                          struct kvec *scratch_iov)
1159 {
1160         struct lnet_processid *id;
1161         struct lnet_hdr hdr;
1162         int rc;
1163
1164         LASSERT(refcount_read(&conn->ksnc_conn_refcount) > 0);
1165
1166         /* NB: sched lock NOT held */
1167         /* SOCKNAL_RX_LNET_HEADER is here for backward compatibility */
1168         LASSERT(conn->ksnc_rx_state == SOCKNAL_RX_KSM_HEADER ||
1169                 conn->ksnc_rx_state == SOCKNAL_RX_LNET_PAYLOAD ||
1170                 conn->ksnc_rx_state == SOCKNAL_RX_LNET_HEADER ||
1171                 conn->ksnc_rx_state == SOCKNAL_RX_SLOP);
1172  again:
1173         if (conn->ksnc_rx_nob_wanted != 0) {
1174                 rc = ksocknal_receive(conn, rx_scratch_pgs,
1175                                       scratch_iov);
1176
1177                 if (rc <= 0) {
1178                         struct lnet_processid *ksnp_id;
1179
1180                         ksnp_id = &conn->ksnc_peer->ksnp_id;
1181
1182                         LASSERT(rc != -EAGAIN);
1183                         if (rc == 0)
1184                                 CDEBUG(D_NET, "[%p] EOF from %s ip %pIScp\n",
1185                                        conn, libcfs_idstr(ksnp_id),
1186                                        &conn->ksnc_peeraddr);
1187                         else if (!conn->ksnc_closing)
1188                                 CERROR("[%p] Error %d on read from %s ip %pIScp\n",
1189                                        conn, rc, libcfs_idstr(ksnp_id),
1190                                        &conn->ksnc_peeraddr);
1191
1192                         /* it's not an error if conn is being closed */
1193                         ksocknal_close_conn_and_siblings (conn,
1194                                                           (conn->ksnc_closing) ? 0 : rc);
1195                         return (rc == 0 ? -ESHUTDOWN : rc);
1196                 }
1197
1198                 if (conn->ksnc_rx_nob_wanted != 0) {
1199                         /* short read */
1200                         return (-EAGAIN);
1201                 }
1202         }
1203         switch (conn->ksnc_rx_state) {
1204         case SOCKNAL_RX_KSM_HEADER:
1205                 if (conn->ksnc_flip) {
1206                         __swab32s(&conn->ksnc_msg.ksm_type);
1207                         __swab32s(&conn->ksnc_msg.ksm_csum);
1208                         __swab64s(&conn->ksnc_msg.ksm_zc_cookies[0]);
1209                         __swab64s(&conn->ksnc_msg.ksm_zc_cookies[1]);
1210                 }
1211
1212                 if (conn->ksnc_msg.ksm_type == KSOCK_MSG_NOOP &&
1213                     conn->ksnc_msg.ksm_csum != 0 &&     /* has checksum */
1214                     conn->ksnc_msg.ksm_csum != conn->ksnc_rx_csum) {
1215                         /* NOOP Checksum error */
1216                         CERROR("%s: Checksum error, wire:0x%08X data:0x%08X\n",
1217                                libcfs_idstr(&conn->ksnc_peer->ksnp_id),
1218                                conn->ksnc_msg.ksm_csum, conn->ksnc_rx_csum);
1219                         ksocknal_new_packet(conn, 0);
1220                         ksocknal_close_conn_and_siblings(conn, -EPROTO);
1221                         return (-EIO);
1222                 }
1223
1224                 if (conn->ksnc_msg.ksm_zc_cookies[1] != 0) {
1225                         __u64 cookie = 0;
1226
1227                         LASSERT(conn->ksnc_proto != &ksocknal_protocol_v1x);
1228
1229                         if (conn->ksnc_msg.ksm_type == KSOCK_MSG_NOOP)
1230                                 cookie = conn->ksnc_msg.ksm_zc_cookies[0];
1231
1232                         rc = conn->ksnc_proto->pro_handle_zcack(
1233                                 conn, cookie, conn->ksnc_msg.ksm_zc_cookies[1]);
1234
1235                         if (rc != 0) {
1236                                 CERROR("%s: Unknown ZC-ACK cookie: %llu, %llu\n",
1237                                        libcfs_idstr(&conn->ksnc_peer->ksnp_id),
1238                                        cookie,
1239                                        conn->ksnc_msg.ksm_zc_cookies[1]);
1240                                 ksocknal_new_packet(conn, 0);
1241                                 ksocknal_close_conn_and_siblings(conn, -EPROTO);
1242                                 return rc;
1243                         }
1244                 }
1245
1246                 switch (conn->ksnc_msg.ksm_type) {
1247                 case KSOCK_MSG_NOOP:
1248                         ksocknal_new_packet(conn, 0);
1249                         return 0;       /* NOOP is done and just return */
1250
1251                 case KSOCK_MSG_LNET: {
1252                         int msg_len = sizeof(struct lnet_hdr_nid4);
1253
1254                         if (conn->ksnc_proto->pro_version == KSOCK_PROTO_V4)
1255                                 msg_len = sizeof(struct lnet_hdr_nid16);
1256
1257                         conn->ksnc_rx_state = SOCKNAL_RX_LNET_HEADER;
1258                         conn->ksnc_rx_nob_wanted = msg_len;
1259                         conn->ksnc_rx_nob_left = msg_len;
1260
1261                         conn->ksnc_rx_iov = conn->ksnc_rx_iov_space.iov;
1262                         if (conn->ksnc_proto->pro_version == KSOCK_PROTO_V4)
1263                                 conn->ksnc_rx_iov[0].iov_base =
1264                                         (void *)&conn->ksnc_msg.ksm_u.lnetmsg_nid16;
1265                         else
1266                                 conn->ksnc_rx_iov[0].iov_base =
1267                                         (void *)&conn->ksnc_msg.ksm_u.lnetmsg_nid4;
1268                         conn->ksnc_rx_iov[0].iov_len = msg_len;
1269
1270                         conn->ksnc_rx_niov = 1;
1271                         conn->ksnc_rx_kiov = NULL;
1272                         conn->ksnc_rx_nkiov = 0;
1273
1274                         goto again;     /* read lnet header now */
1275                 }
1276                 default:
1277                         CERROR("%s: Unknown message type: %x\n",
1278                                libcfs_idstr(&conn->ksnc_peer->ksnp_id),
1279                                conn->ksnc_msg.ksm_type);
1280                         ksocknal_new_packet(conn, 0);
1281                         ksocknal_close_conn_and_siblings(conn, -EPROTO);
1282                         return -EPROTO;
1283                 }
1284
1285         case SOCKNAL_RX_LNET_HEADER:
1286                 /* unpack message header */
1287                 conn->ksnc_proto->pro_unpack(&conn->ksnc_msg, &hdr);
1288
1289                 if ((conn->ksnc_peer->ksnp_id.pid & LNET_PID_USERFLAG) != 0) {
1290                         /* Userspace peer_ni */
1291                         id = &conn->ksnc_peer->ksnp_id;
1292
1293                         /* Substitute process ID assigned at connection time */
1294                         hdr.src_pid = id->pid;
1295                         hdr.src_nid = id->nid;
1296                 }
1297
1298                 conn->ksnc_rx_state = SOCKNAL_RX_PARSE;
1299                 ksocknal_conn_addref(conn);     /* ++ref while parsing */
1300
1301
1302                 rc = lnet_parse(conn->ksnc_peer->ksnp_ni,
1303                                 &hdr,
1304                                 &conn->ksnc_peer->ksnp_id.nid,
1305                                 conn, 0);
1306                 if (rc < 0) {
1307                         /* I just received garbage: give up on this conn */
1308                         ksocknal_new_packet(conn, 0);
1309                         ksocknal_close_conn_and_siblings(conn, rc);
1310                         ksocknal_conn_decref(conn);
1311                         return (-EPROTO);
1312                 }
1313
1314                 /* I'm racing with ksocknal_recv() */
1315                 LASSERT(conn->ksnc_rx_state == SOCKNAL_RX_PARSE ||
1316                         conn->ksnc_rx_state == SOCKNAL_RX_LNET_PAYLOAD);
1317
1318                 if (conn->ksnc_rx_state != SOCKNAL_RX_LNET_PAYLOAD)
1319                         return 0;
1320
1321                 /* ksocknal_recv() got called */
1322                 goto again;
1323
1324         case SOCKNAL_RX_LNET_PAYLOAD:
1325                 /* payload all received */
1326                 rc = 0;
1327
1328                 if (conn->ksnc_rx_nob_left == 0 &&   /* not truncating */
1329                     conn->ksnc_msg.ksm_csum != 0 &&  /* has checksum */
1330                     conn->ksnc_msg.ksm_csum != conn->ksnc_rx_csum) {
1331                         CERROR("%s: Checksum error, wire:0x%08X data:0x%08X\n",
1332                                libcfs_idstr(&conn->ksnc_peer->ksnp_id),
1333                                conn->ksnc_msg.ksm_csum, conn->ksnc_rx_csum);
1334                         rc = -EIO;
1335                 }
1336
1337                 if (rc == 0 && conn->ksnc_msg.ksm_zc_cookies[0] != 0) {
1338                         LASSERT(conn->ksnc_proto != &ksocknal_protocol_v1x);
1339                         if (conn->ksnc_proto->pro_version == KSOCK_PROTO_V4)
1340                                 lnet_hdr_from_nid16(&hdr,
1341                                                     &conn->ksnc_msg.ksm_u.lnetmsg_nid16);
1342                         else
1343                                 lnet_hdr_from_nid4(&hdr,
1344                                                    &conn->ksnc_msg.ksm_u.lnetmsg_nid4);
1345                         id = &conn->ksnc_peer->ksnp_id;
1346                         rc = conn->ksnc_proto->pro_handle_zcreq(
1347                                 conn,
1348                                 conn->ksnc_msg.ksm_zc_cookies[0],
1349                                 *ksocknal_tunables.ksnd_nonblk_zcack ||
1350                                 !nid_same(&hdr.src_nid, &id->nid));
1351                 }
1352
1353                 if (rc && conn->ksnc_lnet_msg)
1354                         conn->ksnc_lnet_msg->msg_health_status =
1355                                 LNET_MSG_STATUS_REMOTE_ERROR;
1356                 lnet_finalize(conn->ksnc_lnet_msg, rc);
1357
1358                 if (rc != 0) {
1359                         ksocknal_new_packet(conn, 0);
1360                         ksocknal_close_conn_and_siblings(conn, rc);
1361                         return (-EPROTO);
1362                 }
1363                 fallthrough;
1364
1365         case SOCKNAL_RX_SLOP:
1366                 /* starting new packet? */
1367                 if (ksocknal_new_packet(conn, conn->ksnc_rx_nob_left))
1368                         return 0;       /* come back later */
1369                 goto again;             /* try to finish reading slop now */
1370
1371         default:
1372                 break;
1373         }
1374
1375         /* Not Reached */
1376         LBUG ();
1377         return (-EINVAL);                       /* keep gcc happy */
1378 }
1379
1380 int
1381 ksocknal_recv(struct lnet_ni *ni, void *private, struct lnet_msg *msg,
1382               int delayed, unsigned int niov,
1383               struct bio_vec *kiov, unsigned int offset, unsigned int mlen,
1384               unsigned int rlen)
1385 {
1386         struct ksock_conn *conn = private;
1387         struct ksock_sched *sched = conn->ksnc_scheduler;
1388
1389         LASSERT (mlen <= rlen);
1390
1391         conn->ksnc_lnet_msg = msg;
1392         conn->ksnc_rx_nob_wanted = mlen;
1393         conn->ksnc_rx_nob_left   = rlen;
1394
1395         if (mlen == 0) {
1396                 conn->ksnc_rx_nkiov = 0;
1397                 conn->ksnc_rx_kiov = NULL;
1398                 conn->ksnc_rx_iov = conn->ksnc_rx_iov_space.iov;
1399                 conn->ksnc_rx_niov = 0;
1400         } else {
1401                 conn->ksnc_rx_niov = 0;
1402                 conn->ksnc_rx_iov  = NULL;
1403                 conn->ksnc_rx_kiov = conn->ksnc_rx_iov_space.kiov;
1404                 conn->ksnc_rx_nkiov =
1405                         lnet_extract_kiov(LNET_MAX_IOV, conn->ksnc_rx_kiov,
1406                                           niov, kiov, offset, mlen);
1407         }
1408
1409         LASSERT(conn->ksnc_rx_nkiov <= LNET_MAX_IOV);
1410         LASSERT (mlen ==
1411                  lnet_iov_nob (conn->ksnc_rx_niov, conn->ksnc_rx_iov) +
1412                  lnet_kiov_nob (conn->ksnc_rx_nkiov, conn->ksnc_rx_kiov));
1413
1414         LASSERT (conn->ksnc_rx_scheduled);
1415
1416         spin_lock_bh(&sched->kss_lock);
1417
1418         switch (conn->ksnc_rx_state) {
1419         case SOCKNAL_RX_PARSE_WAIT:
1420                 list_add_tail(&conn->ksnc_rx_list, &sched->kss_rx_conns);
1421                 wake_up(&sched->kss_waitq);
1422                 LASSERT(conn->ksnc_rx_ready);
1423                 break;
1424
1425         case SOCKNAL_RX_PARSE:
1426                 /* scheduler hasn't noticed I'm parsing yet */
1427                 break;
1428         }
1429
1430         conn->ksnc_rx_state = SOCKNAL_RX_LNET_PAYLOAD;
1431
1432         spin_unlock_bh(&sched->kss_lock);
1433         ksocknal_conn_decref(conn);
1434         return 0;
1435 }
1436
1437 static inline int
1438 ksocknal_sched_cansleep(struct ksock_sched *sched)
1439 {
1440         int           rc;
1441
1442         spin_lock_bh(&sched->kss_lock);
1443
1444         rc = (!ksocknal_data.ksnd_shuttingdown &&
1445               list_empty(&sched->kss_rx_conns) &&
1446               list_empty(&sched->kss_tx_conns));
1447
1448         spin_unlock_bh(&sched->kss_lock);
1449         return rc;
1450 }
1451
1452 int ksocknal_scheduler(void *arg)
1453 {
1454         struct ksock_sched *sched;
1455         struct ksock_conn *conn;
1456         struct ksock_tx *tx;
1457         int rc;
1458         long id = (long)arg;
1459         struct page **rx_scratch_pgs;
1460         struct kvec *scratch_iov;
1461
1462         sched = ksocknal_data.ksnd_schedulers[KSOCK_THREAD_CPT(id)];
1463
1464         LIBCFS_CPT_ALLOC(rx_scratch_pgs, lnet_cpt_table(), sched->kss_cpt,
1465                          sizeof(*rx_scratch_pgs) * LNET_MAX_IOV);
1466         if (!rx_scratch_pgs) {
1467                 CERROR("Unable to allocate scratch pages\n");
1468                 return -ENOMEM;
1469         }
1470
1471         LIBCFS_CPT_ALLOC(scratch_iov, lnet_cpt_table(), sched->kss_cpt,
1472                          sizeof(*scratch_iov) * LNET_MAX_IOV);
1473         if (!scratch_iov) {
1474                 CERROR("Unable to allocate scratch iov\n");
1475                 return -ENOMEM;
1476         }
1477
1478         rc = cfs_cpt_bind(lnet_cpt_table(), sched->kss_cpt);
1479         if (rc != 0) {
1480                 CWARN("Can't set CPU partition affinity to %d: %d\n",
1481                         sched->kss_cpt, rc);
1482         }
1483
1484         spin_lock_bh(&sched->kss_lock);
1485
1486         while (!ksocknal_data.ksnd_shuttingdown) {
1487                 bool did_something = false;
1488
1489                 /* Ensure I progress everything semi-fairly */
1490                 conn = list_first_entry_or_null(&sched->kss_rx_conns,
1491                                                 struct ksock_conn,
1492                                                 ksnc_rx_list);
1493                 if (conn) {
1494                         list_del(&conn->ksnc_rx_list);
1495
1496                         LASSERT(conn->ksnc_rx_scheduled);
1497                         LASSERT(conn->ksnc_rx_ready);
1498
1499                         /* clear rx_ready in case receive isn't complete.
1500                          * Do it BEFORE we call process_recv, since
1501                          * data_ready can set it any time after we release
1502                          * kss_lock. */
1503                         conn->ksnc_rx_ready = 0;
1504                         spin_unlock_bh(&sched->kss_lock);
1505
1506                         rc = ksocknal_process_receive(conn, rx_scratch_pgs,
1507                                                       scratch_iov);
1508
1509                         spin_lock_bh(&sched->kss_lock);
1510
1511                         /* I'm the only one that can clear this flag */
1512                         LASSERT(conn->ksnc_rx_scheduled);
1513
1514                         /* Did process_receive get everything it wanted? */
1515                         if (rc == 0)
1516                                 conn->ksnc_rx_ready = 1;
1517
1518                         if (conn->ksnc_rx_state == SOCKNAL_RX_PARSE) {
1519                                 /* Conn blocked waiting for ksocknal_recv()
1520                                  * I change its state (under lock) to signal
1521                                  * it can be rescheduled */
1522                                 conn->ksnc_rx_state = SOCKNAL_RX_PARSE_WAIT;
1523                         } else if (conn->ksnc_rx_ready) {
1524                                 /* reschedule for rx */
1525                                 list_add_tail(&conn->ksnc_rx_list,
1526                                                    &sched->kss_rx_conns);
1527                         } else {
1528                                 conn->ksnc_rx_scheduled = 0;
1529                                 /* drop my ref */
1530                                 ksocknal_conn_decref(conn);
1531                         }
1532
1533                         did_something = true;
1534                 }
1535
1536                 if (!list_empty(&sched->kss_tx_conns)) {
1537                         LIST_HEAD(zlist);
1538
1539                         list_splice_init(&sched->kss_zombie_noop_txs, &zlist);
1540
1541                         conn = list_first_entry(&sched->kss_tx_conns,
1542                                                 struct ksock_conn,
1543                                                 ksnc_tx_list);
1544                         list_del(&conn->ksnc_tx_list);
1545
1546                         LASSERT(conn->ksnc_tx_scheduled);
1547                         LASSERT(conn->ksnc_tx_ready);
1548                         LASSERT(!list_empty(&conn->ksnc_tx_queue));
1549
1550                         tx = list_first_entry(&conn->ksnc_tx_queue,
1551                                               struct ksock_tx, tx_list);
1552
1553                         if (conn->ksnc_tx_carrier == tx)
1554                                 ksocknal_next_tx_carrier(conn);
1555
1556                         /* dequeue now so empty list => more to send */
1557                         list_del(&tx->tx_list);
1558
1559                         /* Clear tx_ready in case send isn't complete.  Do
1560                          * it BEFORE we call process_transmit, since
1561                          * write_space can set it any time after we release
1562                          * kss_lock. */
1563                         conn->ksnc_tx_ready = 0;
1564                         spin_unlock_bh(&sched->kss_lock);
1565
1566                         if (!list_empty(&zlist)) {
1567                                 /* free zombie noop txs, it's fast because
1568                                  * noop txs are just put in freelist */
1569                                 ksocknal_txlist_done(NULL, &zlist, 0);
1570                         }
1571
1572                         rc = ksocknal_process_transmit(conn, tx, scratch_iov);
1573
1574                         if (rc == -ENOMEM || rc == -EAGAIN) {
1575                                 /* Incomplete send: replace tx on HEAD of tx_queue */
1576                                 spin_lock_bh(&sched->kss_lock);
1577                                 list_add(&tx->tx_list,
1578                                          &conn->ksnc_tx_queue);
1579                         } else {
1580                                 /* Complete send; tx -ref */
1581                                 ksocknal_tx_decref(tx);
1582
1583                                 spin_lock_bh(&sched->kss_lock);
1584                                 /* assume space for more */
1585                                 conn->ksnc_tx_ready = 1;
1586                         }
1587
1588                         if (rc == -ENOMEM) {
1589                                 /* Do nothing; after a short timeout, this
1590                                  * conn will be reposted on kss_tx_conns. */
1591                         } else if (conn->ksnc_tx_ready &&
1592                                    !list_empty(&conn->ksnc_tx_queue)) {
1593                                 /* reschedule for tx */
1594                                 list_add_tail(&conn->ksnc_tx_list,
1595                                               &sched->kss_tx_conns);
1596                         } else {
1597                                 conn->ksnc_tx_scheduled = 0;
1598                                 /* drop my ref */
1599                                 ksocknal_conn_decref(conn);
1600                         }
1601
1602                         did_something = true;
1603                 }
1604                 if (!did_something ||   /* nothing to do */
1605                     need_resched()) {   /* hogging CPU? */
1606                         spin_unlock_bh(&sched->kss_lock);
1607
1608                         if (!did_something) {   /* wait for something to do */
1609                                 rc = wait_event_interruptible_exclusive(
1610                                         sched->kss_waitq,
1611                                         !ksocknal_sched_cansleep(sched));
1612                                 LASSERT (rc == 0);
1613                         } else {
1614                                 cond_resched();
1615                         }
1616
1617                         spin_lock_bh(&sched->kss_lock);
1618                 }
1619         }
1620
1621         spin_unlock_bh(&sched->kss_lock);
1622         CFS_FREE_PTR_ARRAY(rx_scratch_pgs, LNET_MAX_IOV);
1623         CFS_FREE_PTR_ARRAY(scratch_iov, LNET_MAX_IOV);
1624         ksocknal_thread_fini();
1625         return 0;
1626 }
1627
1628 /*
1629  * Add connection to kss_rx_conns of scheduler
1630  * and wakeup the scheduler.
1631  */
1632 void ksocknal_read_callback(struct ksock_conn *conn)
1633 {
1634         struct ksock_sched *sched;
1635
1636         sched = conn->ksnc_scheduler;
1637
1638         spin_lock_bh(&sched->kss_lock);
1639
1640         conn->ksnc_rx_ready = 1;
1641
1642         if (!conn->ksnc_rx_scheduled) {  /* not being progressed */
1643                 list_add_tail(&conn->ksnc_rx_list,
1644                                   &sched->kss_rx_conns);
1645                 conn->ksnc_rx_scheduled = 1;
1646                 /* extra ref for scheduler */
1647                 ksocknal_conn_addref(conn);
1648
1649                 wake_up (&sched->kss_waitq);
1650         }
1651         spin_unlock_bh(&sched->kss_lock);
1652 }
1653
1654 /*
1655  * Add connection to kss_tx_conns of scheduler
1656  * and wakeup the scheduler.
1657  */
1658 void ksocknal_write_callback(struct ksock_conn *conn)
1659 {
1660         struct ksock_sched *sched;
1661
1662         sched = conn->ksnc_scheduler;
1663
1664         spin_lock_bh(&sched->kss_lock);
1665
1666         conn->ksnc_tx_ready = 1;
1667
1668         if (!conn->ksnc_tx_scheduled && /* not being progressed */
1669             !list_empty(&conn->ksnc_tx_queue)) { /* packets to send */
1670                 list_add_tail(&conn->ksnc_tx_list, &sched->kss_tx_conns);
1671                 conn->ksnc_tx_scheduled = 1;
1672                 /* extra ref for scheduler */
1673                 ksocknal_conn_addref(conn);
1674
1675                 wake_up(&sched->kss_waitq);
1676         }
1677
1678         spin_unlock_bh(&sched->kss_lock);
1679 }
1680
1681 static const struct ksock_proto *
1682 ksocknal_parse_proto_version(struct ksock_hello_msg *hello)
1683 {
1684         __u32   version = 0;
1685
1686         if (hello->kshm_magic == LNET_PROTO_MAGIC)
1687                 version = hello->kshm_version;
1688         else if (hello->kshm_magic == __swab32(LNET_PROTO_MAGIC))
1689                 version = __swab32(hello->kshm_version);
1690
1691         if (version) {
1692 #if SOCKNAL_VERSION_DEBUG
1693                 if (*ksocknal_tunables.ksnd_protocol == 1)
1694                         return NULL;
1695
1696                 if (*ksocknal_tunables.ksnd_protocol == 2 &&
1697                     version == KSOCK_PROTO_V3)
1698                         return NULL;
1699 #endif
1700                 if (version == KSOCK_PROTO_V2)
1701                         return &ksocknal_protocol_v2x;
1702
1703                 if (version == KSOCK_PROTO_V3)
1704                         return &ksocknal_protocol_v3x;
1705
1706                 if (version == KSOCK_PROTO_V4)
1707                         return &ksocknal_protocol_v4x;
1708
1709                 return NULL;
1710         }
1711
1712         if (hello->kshm_magic == le32_to_cpu(LNET_PROTO_TCP_MAGIC)) {
1713                 struct lnet_magicversion *hmv;
1714
1715                 BUILD_BUG_ON(sizeof(struct lnet_magicversion) !=
1716                              offsetof(struct ksock_hello_msg, kshm_src_nid));
1717
1718                 hmv = (struct lnet_magicversion *)hello;
1719
1720                 if (hmv->version_major == cpu_to_le16 (KSOCK_PROTO_V1_MAJOR) &&
1721                     hmv->version_minor == cpu_to_le16 (KSOCK_PROTO_V1_MINOR))
1722                         return &ksocknal_protocol_v1x;
1723         }
1724
1725         return NULL;
1726 }
1727
1728 int
1729 ksocknal_send_hello(struct lnet_ni *ni, struct ksock_conn *conn,
1730                     struct lnet_nid *peer_nid, struct ksock_hello_msg *hello)
1731 {
1732         /* CAVEAT EMPTOR: this byte flips 'ipaddrs' */
1733         struct ksock_net *net = (struct ksock_net *)ni->ni_data;
1734
1735         LASSERT(hello->kshm_nips <= LNET_INTERFACES_NUM);
1736
1737         /* rely on caller to hold a ref on socket so it wouldn't disappear */
1738         LASSERT(conn->ksnc_proto != NULL);
1739
1740         hello->kshm_src_nid = ni->ni_nid;
1741         hello->kshm_dst_nid = *peer_nid;
1742         hello->kshm_src_pid = the_lnet.ln_pid;
1743
1744         hello->kshm_src_incarnation = net->ksnn_incarnation;
1745         hello->kshm_ctype = conn->ksnc_type;
1746
1747         return conn->ksnc_proto->pro_send_hello(conn, hello);
1748 }
1749
1750 static int
1751 ksocknal_invert_type(int type)
1752 {
1753         switch (type) {
1754         case SOCKLND_CONN_ANY:
1755         case SOCKLND_CONN_CONTROL:
1756                 return (type);
1757         case SOCKLND_CONN_BULK_IN:
1758                 return SOCKLND_CONN_BULK_OUT;
1759         case SOCKLND_CONN_BULK_OUT:
1760                 return SOCKLND_CONN_BULK_IN;
1761         default:
1762                 return (SOCKLND_CONN_NONE);
1763         }
1764 }
1765
1766 int
1767 ksocknal_recv_hello(struct lnet_ni *ni, struct ksock_conn *conn,
1768                     struct ksock_hello_msg *hello,
1769                     struct lnet_processid *peerid,
1770                     __u64 *incarnation)
1771 {
1772         /* Return < 0        fatal error
1773          *        0          success
1774          *        EALREADY   lost connection race
1775          *        EPROTO     protocol version mismatch
1776          */
1777         struct socket *sock = conn->ksnc_sock;
1778         int active = (conn->ksnc_proto != NULL);
1779         int timeout;
1780         int proto_match;
1781         int rc;
1782         const struct ksock_proto *proto;
1783         struct lnet_processid recv_id;
1784
1785         /* socket type set on active connections - not set on passive */
1786         LASSERT(!active == !(conn->ksnc_type != SOCKLND_CONN_NONE));
1787
1788         timeout = active ? ksocknal_timeout() :
1789                 lnet_acceptor_timeout();
1790
1791         rc = lnet_sock_read(sock, &hello->kshm_magic,
1792                             sizeof(hello->kshm_magic), timeout);
1793         if (rc != 0) {
1794                 CERROR("Error %d reading HELLO from %pISc\n",
1795                        rc, &conn->ksnc_peeraddr);
1796                 LASSERT(rc < 0);
1797                 goto out_fatal;
1798         }
1799
1800         if (hello->kshm_magic != LNET_PROTO_MAGIC &&
1801             hello->kshm_magic != __swab32(LNET_PROTO_MAGIC) &&
1802             hello->kshm_magic != le32_to_cpu(LNET_PROTO_TCP_MAGIC)) {
1803                 /* Unexpected magic! */
1804                 CERROR("Bad magic(1) %#08x (%#08x expected) from %pISc\n",
1805                        __cpu_to_le32 (hello->kshm_magic),
1806                        LNET_PROTO_TCP_MAGIC, &conn->ksnc_peeraddr);
1807                 goto out_unknown;
1808         }
1809
1810         rc = lnet_sock_read(sock, &hello->kshm_version,
1811                             sizeof(hello->kshm_version), timeout);
1812         if (rc != 0) {
1813                 CERROR("Error %d reading HELLO from %pISc\n",
1814                        rc, &conn->ksnc_peeraddr);
1815                 LASSERT(rc < 0);
1816                 goto out_fatal;
1817         }
1818
1819         proto = ksocknal_parse_proto_version(hello);
1820         if (proto == NULL) {
1821                 if (!active) {
1822                         struct sockaddr_in *psa = (void *)&conn->ksnc_peeraddr;
1823
1824                         /* unknown protocol from peer_ni,
1825                          * tell peer_ni my protocol.
1826                          */
1827                         if (psa->sin_family == AF_INET6)
1828                                 conn->ksnc_proto = &ksocknal_protocol_v4x;
1829                         else if (psa->sin_family == AF_INET)
1830                                 conn->ksnc_proto = &ksocknal_protocol_v3x;
1831 #if SOCKNAL_VERSION_DEBUG
1832                         if (*ksocknal_tunables.ksnd_protocol == 2)
1833                                 conn->ksnc_proto = &ksocknal_protocol_v2x;
1834                         else if (*ksocknal_tunables.ksnd_protocol == 1)
1835                                 conn->ksnc_proto = &ksocknal_protocol_v1x;
1836 #endif
1837                         if (!conn->ksnc_proto) {
1838                                 CERROR("Unknown protocol.Error reading HELLO from %pISc\n",
1839                                        &conn->ksnc_peeraddr);
1840                                 goto out_unknown;
1841                         }
1842
1843                         hello->kshm_nips = 0;
1844                         ksocknal_send_hello(ni, conn, &ni->ni_nid,
1845                                             hello);
1846                 }
1847                 CERROR("Unknown protocol version (%d.x expected) from %pISc\n",
1848                        conn->ksnc_proto->pro_version, &conn->ksnc_peeraddr);
1849 out_unknown:
1850                 rc = -EPROTO;
1851 out_fatal:
1852                 return rc;
1853         }
1854
1855         proto_match = (conn->ksnc_proto == proto);
1856         conn->ksnc_proto = proto;
1857
1858         /* receive the rest of hello message anyway */
1859         rc = conn->ksnc_proto->pro_recv_hello(conn, hello, timeout);
1860         if (rc != 0) {
1861                 CERROR("Error %d reading or checking hello from from %pISc\n",
1862                        rc, &conn->ksnc_peeraddr);
1863                 LASSERT(rc < 0);
1864                 return rc;
1865         }
1866
1867         *incarnation = hello->kshm_src_incarnation;
1868
1869         if (LNET_NID_IS_ANY(&hello->kshm_src_nid)) {
1870                 CERROR("Expecting a HELLO hdr with a NID, but got LNET_NID_ANY from %pISc\n",
1871                        &conn->ksnc_peeraddr);
1872                 return -EPROTO;
1873         }
1874
1875         if (!active &&
1876             rpc_get_port((struct sockaddr *)&conn->ksnc_peeraddr) >
1877             LNET_ACCEPTOR_MAX_RESERVED_PORT) {
1878                 /* Userspace NAL assigns peer_ni process ID from socket */
1879                 recv_id.pid = rpc_get_port((struct sockaddr *)
1880                                            &conn->ksnc_peeraddr) |
1881                         LNET_PID_USERFLAG;
1882                 LASSERT(conn->ksnc_peeraddr.ss_family == AF_INET);
1883                 memset(&recv_id.nid, 0, sizeof(recv_id.nid));
1884                 recv_id.nid.nid_type = ni->ni_nid.nid_type;
1885                 recv_id.nid.nid_num = ni->ni_nid.nid_num;
1886                 recv_id.nid.nid_addr[0] =
1887                         ((struct sockaddr_in *)
1888                          &conn->ksnc_peeraddr)->sin_addr.s_addr;
1889         } else {
1890                 recv_id.nid = hello->kshm_src_nid;
1891                 recv_id.pid = hello->kshm_src_pid;
1892         }
1893
1894         if (!active) {
1895                 *peerid = recv_id;
1896
1897                 /* peer_ni determines type */
1898                 conn->ksnc_type = ksocknal_invert_type(hello->kshm_ctype);
1899                 if (conn->ksnc_type == SOCKLND_CONN_NONE) {
1900                         CERROR("Unexpected type %d from %s ip %pISc\n",
1901                                hello->kshm_ctype, libcfs_idstr(peerid),
1902                                &conn->ksnc_peeraddr);
1903                         return -EPROTO;
1904                 }
1905                 return 0;
1906         }
1907
1908         if (peerid->pid != recv_id.pid ||
1909             !nid_same(&peerid->nid,  &recv_id.nid)) {
1910                 LCONSOLE_ERROR_MSG(0x130,
1911                                    "Connected successfully to %s on host %pISc, but they claimed they were %s; please check your Lustre configuration.\n",
1912                                    libcfs_idstr(peerid),
1913                                    &conn->ksnc_peeraddr,
1914                                    libcfs_idstr(&recv_id));
1915                 return -EPROTO;
1916         }
1917
1918         if (hello->kshm_ctype == SOCKLND_CONN_NONE) {
1919                 /* Possible protocol mismatch or I lost the connection race */
1920                 return proto_match ? EALREADY : EPROTO;
1921         }
1922
1923         if (ksocknal_invert_type(hello->kshm_ctype) != conn->ksnc_type) {
1924                 CERROR("Mismatched types: me %d, %s ip %pISc %d\n",
1925                        conn->ksnc_type, libcfs_idstr(peerid),
1926                        &conn->ksnc_peeraddr,
1927                        hello->kshm_ctype);
1928                 return -EPROTO;
1929         }
1930         return 0;
1931 }
1932
1933 static bool
1934 ksocknal_connect(struct ksock_conn_cb *conn_cb)
1935 {
1936         LIST_HEAD(zombies);
1937         struct ksock_peer_ni *peer_ni = conn_cb->ksnr_peer;
1938         int type = SOCKLND_CONN_NONE;
1939         int wanted;
1940         struct socket *sock;
1941         time64_t deadline;
1942         bool retry_later = false;
1943         int rc = 0;
1944         struct ksock_net *net;
1945
1946         deadline = ktime_get_seconds() + ksocknal_timeout();
1947
1948         write_lock_bh(&ksocknal_data.ksnd_global_lock);
1949
1950         LASSERT(conn_cb->ksnr_scheduled);
1951         LASSERT(!conn_cb->ksnr_connecting);
1952
1953         conn_cb->ksnr_connecting = 1;
1954
1955         for (;;) {
1956                 wanted = ksocknal_conn_cb_mask() & ~conn_cb->ksnr_connected;
1957
1958                 /* stop connecting if peer_ni/cb got closed under me, or
1959                  * conn cb got connected while queued
1960                  */
1961                 if (peer_ni->ksnp_closing || conn_cb->ksnr_deleted ||
1962                     wanted == 0) {
1963                         retry_later = false;
1964                         break;
1965                 }
1966
1967                 /* reschedule if peer_ni is connecting to me */
1968                 if (peer_ni->ksnp_accepting > 0) {
1969                         CDEBUG(D_NET,
1970                                "peer_ni %s(%d) already connecting to me, retry later.\n",
1971                                libcfs_nidstr(&peer_ni->ksnp_id.nid),
1972                                peer_ni->ksnp_accepting);
1973                         retry_later = true;
1974                 }
1975
1976                 if (retry_later) /* needs reschedule */
1977                         break;
1978
1979                 if ((wanted & BIT(SOCKLND_CONN_ANY)) != 0) {
1980                         type = SOCKLND_CONN_ANY;
1981                 } else if ((wanted & BIT(SOCKLND_CONN_CONTROL)) != 0) {
1982                         type = SOCKLND_CONN_CONTROL;
1983                 } else if ((wanted & BIT(SOCKLND_CONN_BULK_IN)) != 0 &&
1984                            conn_cb->ksnr_blki_conn_count <= conn_cb->ksnr_blko_conn_count) {
1985                         type = SOCKLND_CONN_BULK_IN;
1986                 } else {
1987                         LASSERT ((wanted & BIT(SOCKLND_CONN_BULK_OUT)) != 0);
1988                         type = SOCKLND_CONN_BULK_OUT;
1989                 }
1990
1991                 write_unlock_bh(&ksocknal_data.ksnd_global_lock);
1992
1993                 if (ktime_get_seconds() >= deadline) {
1994                         rc = -ETIMEDOUT;
1995                         lnet_connect_console_error(
1996                                 rc, &peer_ni->ksnp_id.nid,
1997                                 (struct sockaddr *)&conn_cb->ksnr_addr);
1998                         goto failed;
1999                 }
2000
2001                 net = (struct ksock_net *)(peer_ni->ksnp_ni->ni_data);
2002                 sock = lnet_connect(&peer_ni->ksnp_id.nid,
2003                                     net->ksnn_interface.ksni_index,
2004                                     (struct sockaddr *)&conn_cb->ksnr_addr,
2005                                     peer_ni->ksnp_ni->ni_net_ns);
2006                 if (IS_ERR(sock)) {
2007                         rc = PTR_ERR(sock);
2008                         goto failed;
2009                 }
2010
2011                 rc = ksocknal_create_conn(peer_ni->ksnp_ni, conn_cb, sock,
2012                                           type);
2013                 if (rc < 0) {
2014                         lnet_connect_console_error(
2015                                 rc, &peer_ni->ksnp_id.nid,
2016                                 (struct sockaddr *)&conn_cb->ksnr_addr);
2017                         goto failed;
2018                 }
2019
2020                 if (rc == EALREADY &&
2021                     ksocknal_get_conn_count_by_type(conn_cb, type) > 0)
2022                         conn_cb->ksnr_busy_retry_count += 1;
2023                 else
2024                         conn_cb->ksnr_busy_retry_count = 0;
2025
2026                 /* A +ve RC means I have to retry because I lost the connection
2027                  * race or I have to renegotiate protocol version
2028                  */
2029                 retry_later = (rc != 0);
2030
2031                 if (retry_later)
2032                         CDEBUG(D_NET, "peer_ni %s: conn race, retry later. rc %d\n",
2033                                libcfs_nidstr(&peer_ni->ksnp_id.nid), rc);
2034
2035                 write_lock_bh(&ksocknal_data.ksnd_global_lock);
2036         }
2037
2038         conn_cb->ksnr_scheduled = 0;
2039         conn_cb->ksnr_connecting = 0;
2040
2041         if (conn_cb->ksnr_busy_retry_count >= SOCKNAL_MAX_BUSY_RETRIES &&
2042             type > SOCKLND_CONN_NONE) {
2043                 /* After so many retries due to EALREADY assume that
2044                  * the peer doesn't support as many connections as we want
2045                  */
2046                 if (conn_cb->ksnr_blki_conn_count &&
2047                     conn_cb->ksnr_blko_conn_count &&
2048                     conn_cb->ksnr_ctrl_conn_count) {
2049                         /* Don't create any more connections of any type */
2050                         conn_cb->ksnr_connected |= (BIT(SOCKLND_CONN_CONTROL) |
2051                                                     BIT(SOCKLND_CONN_BULK_IN) |
2052                                                     BIT(SOCKLND_CONN_BULK_OUT));
2053                 } else {
2054                         /* If don't have at least one connection of each
2055                          * type, fail
2056                          */
2057                         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
2058                         goto failed;
2059                 }
2060                 retry_later = false;
2061         }
2062
2063         if (retry_later) {
2064                 /* re-queue for attention; this frees me up to handle
2065                  * the peer_ni's incoming connection request
2066                  */
2067
2068                 if (rc == EALREADY ||
2069                     (rc == 0 && peer_ni->ksnp_accepting > 0)) {
2070                         /* We want to introduce a delay before next
2071                          * attempt to connect if we lost conn race, but
2072                          * the race is resolved quickly usually, so
2073                          * min_reconnectms should be good heuristic
2074                          */
2075                         conn_cb->ksnr_retry_interval =
2076                                 *ksocknal_tunables.ksnd_min_reconnectms / 1000;
2077                         conn_cb->ksnr_timeout = ktime_get_seconds() +
2078                                                 conn_cb->ksnr_retry_interval;
2079                 }
2080
2081                 ksocknal_launch_connection_locked(conn_cb);
2082         }
2083
2084         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
2085         return retry_later;
2086
2087  failed:
2088         write_lock_bh(&ksocknal_data.ksnd_global_lock);
2089
2090         conn_cb->ksnr_scheduled = 0;
2091         conn_cb->ksnr_connecting = 0;
2092
2093         /* This is a retry rather than a new connection */
2094         conn_cb->ksnr_retry_interval *= 2;
2095         conn_cb->ksnr_retry_interval =
2096                 max_t(time64_t, conn_cb->ksnr_retry_interval,
2097                       *ksocknal_tunables.ksnd_min_reconnectms / 1000);
2098         conn_cb->ksnr_retry_interval =
2099                 min_t(time64_t, conn_cb->ksnr_retry_interval,
2100                       *ksocknal_tunables.ksnd_max_reconnectms / 1000);
2101
2102         LASSERT(conn_cb->ksnr_retry_interval);
2103         conn_cb->ksnr_timeout = ktime_get_seconds() +
2104                                 conn_cb->ksnr_retry_interval;
2105
2106         if (!list_empty(&peer_ni->ksnp_tx_queue) &&
2107             peer_ni->ksnp_accepting == 0 &&
2108             !ksocknal_find_connecting_conn_cb_locked(peer_ni)) {
2109                 struct ksock_conn *conn;
2110
2111                 /* ksnp_tx_queue is queued on a conn on successful
2112                  * connection for V1.x and V2.x
2113                  */
2114                 conn = list_first_entry_or_null(&peer_ni->ksnp_conns,
2115                                                 struct ksock_conn, ksnc_list);
2116                 if (conn)
2117                         LASSERT(conn->ksnc_proto == &ksocknal_protocol_v3x ||
2118                                 conn->ksnc_proto == &ksocknal_protocol_v4x);
2119
2120                 /* take all the blocked packets while I've got the lock and
2121                  * complete below...
2122                  */
2123                 list_splice_init(&peer_ni->ksnp_tx_queue, &zombies);
2124         }
2125
2126         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
2127
2128         ksocknal_peer_failed(peer_ni);
2129         ksocknal_txlist_done(peer_ni->ksnp_ni, &zombies, rc);
2130         return 0;
2131 }
2132
2133 /*
2134  * check whether we need to create more connds.
2135  * It will try to create new thread if it's necessary, @timeout can
2136  * be updated if failed to create, so caller wouldn't keep try while
2137  * running out of resource.
2138  */
2139 static int
2140 ksocknal_connd_check_start(time64_t sec, long *timeout)
2141 {
2142         int rc;
2143         int total = ksocknal_data.ksnd_connd_starting +
2144                     ksocknal_data.ksnd_connd_running;
2145
2146         if (unlikely(ksocknal_data.ksnd_init < SOCKNAL_INIT_ALL)) {
2147                 /* still in initializing */
2148                 return 0;
2149         }
2150
2151         if (total >= *ksocknal_tunables.ksnd_nconnds_max ||
2152             total > ksocknal_data.ksnd_connd_connecting + SOCKNAL_CONND_RESV) {
2153                 /* can't create more connd, or still have enough
2154                  * threads to handle more connecting */
2155                 return 0;
2156         }
2157
2158         if (list_empty(&ksocknal_data.ksnd_connd_routes)) {
2159                 /* no pending connecting request */
2160                 return 0;
2161         }
2162
2163         if (sec - ksocknal_data.ksnd_connd_failed_stamp <= 1) {
2164                 /* may run out of resource, retry later */
2165                 *timeout = cfs_time_seconds(1);
2166                 return 0;
2167         }
2168
2169         if (ksocknal_data.ksnd_connd_starting > 0) {
2170                 /* serialize starting to avoid flood */
2171                 return 0;
2172         }
2173
2174         ksocknal_data.ksnd_connd_starting_stamp = sec;
2175         ksocknal_data.ksnd_connd_starting++;
2176         spin_unlock_bh(&ksocknal_data.ksnd_connd_lock);
2177
2178         /* NB: total is the next id */
2179         rc = ksocknal_thread_start(ksocknal_connd, NULL,
2180                                    "socknal_cd%02d", total);
2181
2182         spin_lock_bh(&ksocknal_data.ksnd_connd_lock);
2183         if (rc == 0)
2184                 return 1;
2185
2186         /* we tried ... */
2187         LASSERT(ksocknal_data.ksnd_connd_starting > 0);
2188         ksocknal_data.ksnd_connd_starting--;
2189         ksocknal_data.ksnd_connd_failed_stamp = ktime_get_real_seconds();
2190
2191         return 1;
2192 }
2193
2194 /*
2195  * check whether current thread can exit, it will return 1 if there are too
2196  * many threads and no creating in past 120 seconds.
2197  * Also, this function may update @timeout to make caller come back
2198  * again to recheck these conditions.
2199  */
2200 static int
2201 ksocknal_connd_check_stop(time64_t sec, long *timeout)
2202 {
2203         int val;
2204
2205         if (unlikely(ksocknal_data.ksnd_init < SOCKNAL_INIT_ALL)) {
2206                 /* still in initializing */
2207                 return 0;
2208         }
2209
2210         if (ksocknal_data.ksnd_connd_starting > 0) {
2211                 /* in progress of starting new thread */
2212                 return 0;
2213         }
2214
2215         if (ksocknal_data.ksnd_connd_running <=
2216             *ksocknal_tunables.ksnd_nconnds) { /* can't shrink */
2217                 return 0;
2218         }
2219
2220         /* created thread in past 120 seconds? */
2221         val = (int)(ksocknal_data.ksnd_connd_starting_stamp +
2222                     SOCKNAL_CONND_TIMEOUT - sec);
2223
2224         *timeout = (val > 0) ? cfs_time_seconds(val) :
2225                                cfs_time_seconds(SOCKNAL_CONND_TIMEOUT);
2226         if (val > 0)
2227                 return 0;
2228
2229         /* no creating in past 120 seconds */
2230
2231         return ksocknal_data.ksnd_connd_running >
2232                ksocknal_data.ksnd_connd_connecting + SOCKNAL_CONND_RESV;
2233 }
2234
2235 /* Go through connd_cbs queue looking for a conn_cb that we can process
2236  * right now, @timeout_p can be updated if we need to come back later */
2237 static struct ksock_conn_cb *
2238 ksocknal_connd_get_conn_cb_locked(signed long *timeout_p)
2239 {
2240         time64_t now = ktime_get_seconds();
2241         time64_t conn_timeout;
2242         struct ksock_conn_cb *conn_cb;
2243
2244         /* connd_routes can contain both pending and ordinary routes */
2245         list_for_each_entry(conn_cb, &ksocknal_data.ksnd_connd_routes,
2246                             ksnr_connd_list) {
2247
2248                 conn_timeout = conn_cb->ksnr_timeout;
2249
2250                 if (conn_cb->ksnr_retry_interval == 0 ||
2251                     now >= conn_timeout)
2252                         return conn_cb;
2253
2254                 if (*timeout_p == MAX_SCHEDULE_TIMEOUT ||
2255                     *timeout_p > cfs_time_seconds(conn_timeout - now))
2256                         *timeout_p = cfs_time_seconds(conn_timeout - now);
2257         }
2258
2259         return NULL;
2260 }
2261
2262 int
2263 ksocknal_connd(void *arg)
2264 {
2265         spinlock_t *connd_lock = &ksocknal_data.ksnd_connd_lock;
2266         struct ksock_connreq *cr;
2267         wait_queue_entry_t wait;
2268         int cons_retry = 0;
2269
2270         init_wait(&wait);
2271
2272         spin_lock_bh(connd_lock);
2273
2274         LASSERT(ksocknal_data.ksnd_connd_starting > 0);
2275         ksocknal_data.ksnd_connd_starting--;
2276         ksocknal_data.ksnd_connd_running++;
2277
2278         while (!ksocknal_data.ksnd_shuttingdown) {
2279                 struct ksock_conn_cb *conn_cb = NULL;
2280                 time64_t sec = ktime_get_real_seconds();
2281                 long timeout = MAX_SCHEDULE_TIMEOUT;
2282                 bool dropped_lock = false;
2283
2284                 if (ksocknal_connd_check_stop(sec, &timeout)) {
2285                         /* wakeup another one to check stop */
2286                         wake_up(&ksocknal_data.ksnd_connd_waitq);
2287                         break;
2288                 }
2289
2290                 if (ksocknal_connd_check_start(sec, &timeout)) {
2291                         /* created new thread */
2292                         dropped_lock = true;
2293                 }
2294
2295                 cr = list_first_entry_or_null(&ksocknal_data.ksnd_connd_connreqs,
2296                                               struct ksock_connreq, ksncr_list);
2297                 if (cr) {
2298                         /* Connection accepted by the listener */
2299                         list_del(&cr->ksncr_list);
2300                         spin_unlock_bh(connd_lock);
2301                         dropped_lock = true;
2302
2303                         ksocknal_create_conn(cr->ksncr_ni, NULL,
2304                                              cr->ksncr_sock, SOCKLND_CONN_NONE);
2305                         lnet_ni_decref(cr->ksncr_ni);
2306                         LIBCFS_FREE(cr, sizeof(*cr));
2307
2308                         spin_lock_bh(connd_lock);
2309                 }
2310
2311                 /* Only handle an outgoing connection request if there
2312                  * is a thread left to handle incoming connections and
2313                  * create new connd
2314                  */
2315                 if (ksocknal_data.ksnd_connd_connecting + SOCKNAL_CONND_RESV <
2316                     ksocknal_data.ksnd_connd_running)
2317                         conn_cb = ksocknal_connd_get_conn_cb_locked(&timeout);
2318
2319                 if (conn_cb) {
2320                         list_del(&conn_cb->ksnr_connd_list);
2321                         ksocknal_data.ksnd_connd_connecting++;
2322                         spin_unlock_bh(connd_lock);
2323                         dropped_lock = true;
2324
2325                         if (ksocknal_connect(conn_cb)) {
2326                                 /* consecutive retry */
2327                                 if (cons_retry++ > SOCKNAL_INSANITY_RECONN) {
2328                                         CWARN("massive consecutive re-connecting to %pISc\n",
2329                                               &conn_cb->ksnr_addr);
2330                                         cons_retry = 0;
2331                                 }
2332                         } else {
2333                                 cons_retry = 0;
2334                         }
2335
2336                         ksocknal_conn_cb_decref(conn_cb);
2337
2338                         spin_lock_bh(connd_lock);
2339                         ksocknal_data.ksnd_connd_connecting--;
2340                 }
2341
2342                 if (dropped_lock) {
2343                         if (!need_resched())
2344                                 continue;
2345                         spin_unlock_bh(connd_lock);
2346                         cond_resched();
2347                         spin_lock_bh(connd_lock);
2348                         continue;
2349                 }
2350
2351                 /* Nothing to do for 'timeout'  */
2352                 set_current_state(TASK_INTERRUPTIBLE);
2353                 add_wait_queue_exclusive(&ksocknal_data.ksnd_connd_waitq,
2354                                          &wait);
2355                 spin_unlock_bh(connd_lock);
2356
2357                 schedule_timeout(timeout);
2358
2359                 remove_wait_queue(&ksocknal_data.ksnd_connd_waitq, &wait);
2360                 spin_lock_bh(connd_lock);
2361         }
2362         ksocknal_data.ksnd_connd_running--;
2363         spin_unlock_bh(connd_lock);
2364
2365         ksocknal_thread_fini();
2366         return 0;
2367 }
2368
2369 static struct ksock_conn *
2370 ksocknal_find_timed_out_conn(struct ksock_peer_ni *peer_ni)
2371 {
2372         /* We're called with a shared lock on ksnd_global_lock */
2373         struct ksock_conn *conn;
2374         struct ksock_tx *tx;
2375         struct ksock_sched *sched;
2376
2377         list_for_each_entry(conn, &peer_ni->ksnp_conns, ksnc_list) {
2378                 int error;
2379
2380                 /* Don't need the {get,put}connsock dance to deref ksnc_sock */
2381                 LASSERT (!conn->ksnc_closing);
2382                 sched = conn->ksnc_scheduler;
2383
2384                 error = conn->ksnc_sock->sk->sk_err;
2385                 if (error != 0) {
2386                         ksocknal_conn_addref(conn);
2387
2388                         switch (error) {
2389                         case ECONNRESET:
2390                                 CNETERR("A connection with %s (%pIScp) was reset; it may have rebooted.\n",
2391                                         libcfs_idstr(&peer_ni->ksnp_id),
2392                                         &conn->ksnc_peeraddr);
2393                                 break;
2394                         case ETIMEDOUT:
2395                                 CNETERR("A connection with %s (%pIScp) timed out; the network or node may be down.\n",
2396                                         libcfs_idstr(&peer_ni->ksnp_id),
2397                                         &conn->ksnc_peeraddr);
2398                                 break;
2399                         default:
2400                                 CNETERR("An unexpected network error %d occurred with %s (%pIScp\n",
2401                                         error,
2402                                         libcfs_idstr(&peer_ni->ksnp_id),
2403                                         &conn->ksnc_peeraddr);
2404                                 break;
2405                         }
2406
2407                         return conn;
2408                 }
2409
2410                 if (conn->ksnc_rx_started &&
2411                     ktime_get_seconds() >= conn->ksnc_rx_deadline) {
2412                         /* Timed out incomplete incoming message */
2413                         ksocknal_conn_addref(conn);
2414                         CNETERR("Timeout receiving from %s (%pIScp), state %d wanted %d left %d\n",
2415                                 libcfs_idstr(&peer_ni->ksnp_id),
2416                                 &conn->ksnc_peeraddr,
2417                                 conn->ksnc_rx_state,
2418                                 conn->ksnc_rx_nob_wanted,
2419                                 conn->ksnc_rx_nob_left);
2420                         return conn;
2421                 }
2422
2423                 spin_lock_bh(&sched->kss_lock);
2424                 if ((!list_empty(&conn->ksnc_tx_queue) ||
2425                      conn->ksnc_sock->sk->sk_wmem_queued != 0) &&
2426                     ktime_get_seconds() >= conn->ksnc_tx_deadline) {
2427                         /* Timed out messages queued for sending or
2428                          * buffered in the socket's send buffer
2429                          */
2430                         ksocknal_conn_addref(conn);
2431                         list_for_each_entry(tx, &conn->ksnc_tx_queue,
2432                                             tx_list)
2433                                 tx->tx_hstatus =
2434                                         LNET_MSG_STATUS_NETWORK_TIMEOUT;
2435                         CNETERR("Timeout sending data to %s (%pIScp) the network or that node may be down.\n",
2436                                 libcfs_idstr(&peer_ni->ksnp_id),
2437                                 &conn->ksnc_peeraddr);
2438                                 spin_unlock_bh(&sched->kss_lock);
2439                                 return conn;
2440                 }
2441                 spin_unlock_bh(&sched->kss_lock);
2442         }
2443
2444         return (NULL);
2445 }
2446
2447 static inline void
2448 ksocknal_flush_stale_txs(struct ksock_peer_ni *peer_ni)
2449 {
2450         struct ksock_tx *tx;
2451         LIST_HEAD(stale_txs);
2452
2453         write_lock_bh(&ksocknal_data.ksnd_global_lock);
2454
2455         while ((tx = list_first_entry_or_null(&peer_ni->ksnp_tx_queue,
2456                                               struct ksock_tx,
2457                                               tx_list)) != NULL) {
2458                 if (ktime_get_seconds() < tx->tx_deadline)
2459                         break;
2460
2461                 tx->tx_hstatus = LNET_MSG_STATUS_NETWORK_TIMEOUT;
2462
2463                 list_move_tail(&tx->tx_list, &stale_txs);
2464         }
2465
2466         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
2467
2468         ksocknal_txlist_done(peer_ni->ksnp_ni, &stale_txs, -ETIMEDOUT);
2469 }
2470
2471 static int
2472 ksocknal_send_keepalive_locked(struct ksock_peer_ni *peer_ni)
2473 __must_hold(&ksocknal_data.ksnd_global_lock)
2474 {
2475         struct ksock_sched *sched;
2476         struct ksock_conn *conn;
2477         struct ksock_tx *tx;
2478
2479         /* last_alive will be updated by create_conn */
2480         if (list_empty(&peer_ni->ksnp_conns))
2481                 return 0;
2482
2483         if (peer_ni->ksnp_proto != &ksocknal_protocol_v3x &&
2484             peer_ni->ksnp_proto != &ksocknal_protocol_v4x)
2485                 return 0;
2486
2487         if (*ksocknal_tunables.ksnd_keepalive <= 0 ||
2488             ktime_get_seconds() < peer_ni->ksnp_last_alive +
2489                                   *ksocknal_tunables.ksnd_keepalive)
2490                 return 0;
2491
2492         if (ktime_get_seconds() < peer_ni->ksnp_send_keepalive)
2493                 return 0;
2494
2495         /* retry 10 secs later, so we wouldn't put pressure
2496          * on this peer_ni if we failed to send keepalive this time */
2497         peer_ni->ksnp_send_keepalive = ktime_get_seconds() + 10;
2498
2499         conn = ksocknal_find_conn_locked(peer_ni, NULL, 1);
2500         if (conn != NULL) {
2501                 sched = conn->ksnc_scheduler;
2502
2503                 spin_lock_bh(&sched->kss_lock);
2504                 if (!list_empty(&conn->ksnc_tx_queue)) {
2505                         spin_unlock_bh(&sched->kss_lock);
2506                         /* there is an queued ACK, don't need keepalive */
2507                         return 0;
2508                 }
2509
2510                 spin_unlock_bh(&sched->kss_lock);
2511         }
2512
2513         read_unlock(&ksocknal_data.ksnd_global_lock);
2514
2515         /* cookie = 1 is reserved for keepalive PING */
2516         tx = ksocknal_alloc_tx_noop(1, 1);
2517         if (tx == NULL) {
2518                 read_lock(&ksocknal_data.ksnd_global_lock);
2519                 return -ENOMEM;
2520         }
2521
2522         if (ksocknal_launch_packet(peer_ni->ksnp_ni, tx, &peer_ni->ksnp_id)
2523             == 0) {
2524                 read_lock(&ksocknal_data.ksnd_global_lock);
2525                 return 1;
2526         }
2527
2528         ksocknal_free_tx(tx);
2529         read_lock(&ksocknal_data.ksnd_global_lock);
2530
2531         return -EIO;
2532 }
2533
2534
2535 static void
2536 ksocknal_check_peer_timeouts(int idx)
2537 {
2538         struct hlist_head *peers = &ksocknal_data.ksnd_peers[idx];
2539         struct ksock_peer_ni *peer_ni;
2540         struct ksock_conn *conn;
2541         struct ksock_tx *tx;
2542
2543  again:
2544         /* NB. We expect to have a look at all the peers and not find any
2545          * connections to time out, so we just use a shared lock while we
2546          * take a look...
2547          */
2548         read_lock(&ksocknal_data.ksnd_global_lock);
2549
2550         hlist_for_each_entry(peer_ni, peers, ksnp_list) {
2551                 struct ksock_tx *tx_stale;
2552                 time64_t deadline = 0;
2553                 int resid = 0;
2554                 int n = 0;
2555
2556                 if (ksocknal_send_keepalive_locked(peer_ni) != 0) {
2557                         read_unlock(&ksocknal_data.ksnd_global_lock);
2558                         goto again;
2559                 }
2560
2561                 conn = ksocknal_find_timed_out_conn(peer_ni);
2562
2563                 if (conn != NULL) {
2564                         read_unlock(&ksocknal_data.ksnd_global_lock);
2565
2566                         ksocknal_close_conn_and_siblings(conn, -ETIMEDOUT);
2567
2568                         /* NB we won't find this one again, but we can't
2569                          * just proceed with the next peer_ni, since we dropped
2570                          * ksnd_global_lock and it might be dead already!
2571                          */
2572                         ksocknal_conn_decref(conn);
2573                         goto again;
2574                 }
2575
2576                 /* we can't process stale txs right here because we're
2577                  * holding only shared lock
2578                  */
2579                 tx = list_first_entry_or_null(&peer_ni->ksnp_tx_queue,
2580                                               struct ksock_tx, tx_list);
2581                 if (tx && ktime_get_seconds() >= tx->tx_deadline) {
2582                         ksocknal_peer_addref(peer_ni);
2583                         read_unlock(&ksocknal_data.ksnd_global_lock);
2584
2585                         ksocknal_flush_stale_txs(peer_ni);
2586
2587                         ksocknal_peer_decref(peer_ni);
2588                         goto again;
2589                 }
2590
2591                 if (list_empty(&peer_ni->ksnp_zc_req_list))
2592                         continue;
2593
2594                 tx_stale = NULL;
2595                 spin_lock(&peer_ni->ksnp_lock);
2596                 list_for_each_entry(tx, &peer_ni->ksnp_zc_req_list, tx_zc_list) {
2597                         if (ktime_get_seconds() < tx->tx_deadline)
2598                                 break;
2599                         /* ignore the TX if connection is being closed */
2600                         if (tx->tx_conn->ksnc_closing)
2601                                 continue;
2602                         n++;
2603                         if (tx_stale == NULL)
2604                                 tx_stale = tx;
2605                 }
2606
2607                 if (tx_stale == NULL) {
2608                         spin_unlock(&peer_ni->ksnp_lock);
2609                         continue;
2610                 }
2611
2612                 deadline = tx_stale->tx_deadline;
2613                 resid    = tx_stale->tx_resid;
2614                 conn     = tx_stale->tx_conn;
2615                 ksocknal_conn_addref(conn);
2616
2617                 spin_unlock(&peer_ni->ksnp_lock);
2618                 read_unlock(&ksocknal_data.ksnd_global_lock);
2619
2620                 CERROR("Total %d stale ZC_REQs for peer_ni %s detected; the "
2621                        "oldest(%p) timed out %lld secs ago, "
2622                        "resid: %d, wmem: %d\n",
2623                        n, libcfs_nidstr(&peer_ni->ksnp_id.nid), tx_stale,
2624                        ktime_get_seconds() - deadline,
2625                        resid, conn->ksnc_sock->sk->sk_wmem_queued);
2626
2627                 ksocknal_close_conn_and_siblings (conn, -ETIMEDOUT);
2628                 ksocknal_conn_decref(conn);
2629                 goto again;
2630         }
2631
2632         read_unlock(&ksocknal_data.ksnd_global_lock);
2633 }
2634
2635 int ksocknal_reaper(void *arg)
2636 {
2637         wait_queue_entry_t wait;
2638         struct ksock_conn *conn;
2639         struct ksock_sched *sched;
2640         LIST_HEAD(enomem_conns);
2641         int nenomem_conns;
2642         time64_t timeout;
2643         int i;
2644         int peer_index = 0;
2645         time64_t deadline = ktime_get_seconds();
2646
2647         init_wait(&wait);
2648
2649         spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
2650
2651         while (!ksocknal_data.ksnd_shuttingdown) {
2652                 conn = list_first_entry_or_null(&ksocknal_data.ksnd_deathrow_conns,
2653                                                 struct ksock_conn, ksnc_list);
2654                 if (conn) {
2655                         list_del(&conn->ksnc_list);
2656
2657                         spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
2658
2659                         ksocknal_terminate_conn(conn);
2660                         ksocknal_conn_decref(conn);
2661
2662                         spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
2663                         continue;
2664                 }
2665
2666                 conn = list_first_entry_or_null(&ksocknal_data.ksnd_zombie_conns,
2667                                                 struct ksock_conn, ksnc_list);
2668                 if (conn) {
2669                         list_del(&conn->ksnc_list);
2670
2671                         spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
2672
2673                         ksocknal_destroy_conn(conn);
2674
2675                         spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
2676                         continue;
2677                 }
2678
2679                 list_splice_init(&ksocknal_data.ksnd_enomem_conns,
2680                                  &enomem_conns);
2681
2682                 spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
2683
2684                 /* reschedule all the connections that stalled with ENOMEM... */
2685                 nenomem_conns = 0;
2686                 while ((conn = list_first_entry_or_null(&enomem_conns,
2687                                                         struct ksock_conn,
2688                                                         ksnc_tx_list)) != NULL) {
2689                         list_del(&conn->ksnc_tx_list);
2690
2691                         sched = conn->ksnc_scheduler;
2692
2693                         spin_lock_bh(&sched->kss_lock);
2694
2695                         LASSERT(conn->ksnc_tx_scheduled);
2696                         conn->ksnc_tx_ready = 1;
2697                         list_add_tail(&conn->ksnc_tx_list,
2698                                           &sched->kss_tx_conns);
2699                         wake_up(&sched->kss_waitq);
2700
2701                         spin_unlock_bh(&sched->kss_lock);
2702                         nenomem_conns++;
2703                 }
2704
2705                 /* careful with the jiffy wrap... */
2706                 while ((timeout = deadline - ktime_get_seconds()) <= 0) {
2707                         const int n = 4;
2708                         const int p = 1;
2709                         int  chunk = HASH_SIZE(ksocknal_data.ksnd_peers);
2710                         unsigned int lnd_timeout;
2711
2712                         /* Time to check for timeouts on a few more peers: I
2713                          * do checks every 'p' seconds on a proportion of the
2714                          * peer_ni table and I need to check every connection
2715                          * 'n' times within a timeout interval, to ensure I
2716                          * detect a timeout on any connection within (n+1)/n
2717                          * times the timeout interval.
2718                          */
2719
2720                         lnd_timeout = ksocknal_timeout();
2721                         if (lnd_timeout > n * p)
2722                                 chunk = (chunk * n * p) / lnd_timeout;
2723                         if (chunk == 0)
2724                                 chunk = 1;
2725
2726                         for (i = 0; i < chunk; i++) {
2727                                 ksocknal_check_peer_timeouts(peer_index);
2728                                 peer_index = (peer_index + 1) %
2729                                         HASH_SIZE(ksocknal_data.ksnd_peers);
2730                         }
2731
2732                         deadline += p;
2733                 }
2734
2735                 if (nenomem_conns != 0) {
2736                         /* Reduce my timeout if I rescheduled ENOMEM conns.
2737                          * This also prevents me getting woken immediately
2738                          * if any go back on my enomem list. */
2739                         timeout = SOCKNAL_ENOMEM_RETRY;
2740                 }
2741                 ksocknal_data.ksnd_reaper_waketime = ktime_get_seconds() +
2742                                                      timeout;
2743
2744                 set_current_state(TASK_INTERRUPTIBLE);
2745                 add_wait_queue(&ksocknal_data.ksnd_reaper_waitq, &wait);
2746
2747                 if (!ksocknal_data.ksnd_shuttingdown &&
2748                     list_empty(&ksocknal_data.ksnd_deathrow_conns) &&
2749                     list_empty(&ksocknal_data.ksnd_zombie_conns))
2750                         schedule_timeout(cfs_time_seconds(timeout));
2751
2752                 set_current_state(TASK_RUNNING);
2753                 remove_wait_queue(&ksocknal_data.ksnd_reaper_waitq, &wait);
2754
2755                 spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
2756         }
2757
2758         spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
2759
2760         ksocknal_thread_fini();
2761         return 0;
2762 }