Whamcloud - gitweb
LU-15370 ksocklnd: remove verbose debug messages
[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_LOCAL_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 %pIS reset our connection while we were sending data; it may have rebooted.\n",
609                                       &conn->ksnc_peeraddr);
610                         break;
611                 default:
612                         LCONSOLE_WARN("There was an unexpected network error while writing to %pIS: %d.\n",
613                                       &conn->ksnc_peeraddr, rc);
614                         break;
615                 }
616                 CDEBUG(D_NET, "[%p] Error %d on write to %s ip %pISp\n",
617                        conn, rc, libcfs_idstr(&conn->ksnc_peer->ksnp_id),
618                        &conn->ksnc_peeraddr);
619         }
620
621         if (tx->tx_zc_checked)
622                 ksocknal_uncheck_zc_req(tx);
623
624         /* it's not an error if conn is being closed */
625         ksocknal_close_conn_and_siblings(conn,
626                                           (conn->ksnc_closing) ? 0 : rc);
627
628         return rc;
629 }
630
631 static void
632 ksocknal_launch_connection_locked(struct ksock_conn_cb *conn_cb)
633 {
634         /* called holding write lock on ksnd_global_lock */
635
636         LASSERT(!conn_cb->ksnr_scheduled);
637         LASSERT(!conn_cb->ksnr_connecting);
638         LASSERT((ksocknal_conn_cb_mask() & ~conn_cb->ksnr_connected) != 0);
639
640         /* scheduling conn for connd */
641         conn_cb->ksnr_scheduled = 1;
642
643         /* extra ref for connd */
644         ksocknal_conn_cb_addref(conn_cb);
645
646         spin_lock_bh(&ksocknal_data.ksnd_connd_lock);
647
648         list_add_tail(&conn_cb->ksnr_connd_list,
649                       &ksocknal_data.ksnd_connd_routes);
650         wake_up(&ksocknal_data.ksnd_connd_waitq);
651
652         spin_unlock_bh(&ksocknal_data.ksnd_connd_lock);
653 }
654
655 void
656 ksocknal_launch_all_connections_locked(struct ksock_peer_ni *peer_ni)
657 {
658         struct ksock_conn_cb *conn_cb;
659
660         /* called holding write lock on ksnd_global_lock */
661         for (;;) {
662                 /* launch any/all connections that need it */
663                 conn_cb = ksocknal_find_connectable_conn_cb_locked(peer_ni);
664                 if (conn_cb == NULL)
665                         return;
666
667                 ksocknal_launch_connection_locked(conn_cb);
668         }
669 }
670
671 struct ksock_conn *
672 ksocknal_find_conn_locked(struct ksock_peer_ni *peer_ni, struct ksock_tx *tx, int nonblk)
673 {
674         struct ksock_conn *c;
675         struct ksock_conn *conn;
676         struct ksock_conn *typed = NULL;
677         struct ksock_conn *fallback = NULL;
678         int tnob = 0;
679         int fnob = 0;
680
681         list_for_each_entry(c, &peer_ni->ksnp_conns, ksnc_list) {
682                 int nob = atomic_read(&c->ksnc_tx_nob) +
683                           c->ksnc_sock->sk->sk_wmem_queued;
684                 int rc;
685
686                 LASSERT (!c->ksnc_closing);
687                 LASSERT (c->ksnc_proto != NULL &&
688                          c->ksnc_proto->pro_match_tx != NULL);
689
690                 rc = c->ksnc_proto->pro_match_tx(c, tx, nonblk);
691
692                 switch (rc) {
693                 default:
694                         LBUG();
695                 case SOCKNAL_MATCH_NO: /* protocol rejected the tx */
696                         continue;
697
698                 case SOCKNAL_MATCH_YES: /* typed connection */
699                         if (typed == NULL || tnob > nob ||
700                             (tnob == nob && *ksocknal_tunables.ksnd_round_robin &&
701                              typed->ksnc_tx_last_post > c->ksnc_tx_last_post)) {
702                                 typed = c;
703                                 tnob  = nob;
704                         }
705                         break;
706
707                 case SOCKNAL_MATCH_MAY: /* fallback connection */
708                         if (fallback == NULL || fnob > nob ||
709                             (fnob == nob && *ksocknal_tunables.ksnd_round_robin &&
710                              fallback->ksnc_tx_last_post > c->ksnc_tx_last_post)) {
711                                 fallback = c;
712                                 fnob     = nob;
713                         }
714                         break;
715                 }
716         }
717
718         /* prefer the typed selection */
719         conn = (typed != NULL) ? typed : fallback;
720
721         if (conn != NULL)
722                 conn->ksnc_tx_last_post = ktime_get_seconds();
723
724         return conn;
725 }
726
727 void
728 ksocknal_tx_prep(struct ksock_conn *conn, struct ksock_tx *tx)
729 {
730         conn->ksnc_proto->pro_pack(tx);
731
732         atomic_add (tx->tx_nob, &conn->ksnc_tx_nob);
733         ksocknal_conn_addref(conn); /* +1 ref for tx */
734         tx->tx_conn = conn;
735 }
736
737 void
738 ksocknal_queue_tx_locked(struct ksock_tx *tx, struct ksock_conn *conn)
739 {
740         struct ksock_sched *sched = conn->ksnc_scheduler;
741         struct ksock_msg *msg = &tx->tx_msg;
742         struct ksock_tx *ztx = NULL;
743         int bufnob = 0;
744
745         /* called holding global lock (read or irq-write) and caller may
746          * not have dropped this lock between finding conn and calling me,
747          * so we don't need the {get,put}connsock dance to deref
748          * ksnc_sock... */
749         LASSERT(!conn->ksnc_closing);
750
751         CDEBUG(D_NET, "Sending to %s ip %pISp\n",
752                libcfs_idstr(&conn->ksnc_peer->ksnp_id),
753                &conn->ksnc_peeraddr);
754
755         ksocknal_tx_prep(conn, tx);
756
757         /* Ensure the frags we've been given EXACTLY match the number of
758          * bytes we want to send.  Many TCP/IP stacks disregard any total
759          * size parameters passed to them and just look at the frags.
760          *
761          * We always expect at least 1 mapped fragment containing the
762          * complete ksocknal message header.
763          */
764         LASSERT(lnet_iov_nob(tx->tx_niov, &tx->tx_hdr) +
765                 lnet_kiov_nob(tx->tx_nkiov, tx->tx_kiov) ==
766                 (unsigned int)tx->tx_nob);
767         LASSERT(tx->tx_niov >= 1);
768         LASSERT(tx->tx_resid == tx->tx_nob);
769
770         CDEBUG(D_NET, "Packet %p type %d, nob %d niov %d nkiov %d\n",
771                tx, tx->tx_lnetmsg ? tx->tx_lnetmsg->msg_type : KSOCK_MSG_NOOP,
772                tx->tx_nob, tx->tx_niov, tx->tx_nkiov);
773
774         bufnob = conn->ksnc_sock->sk->sk_wmem_queued;
775         spin_lock_bh(&sched->kss_lock);
776
777         if (list_empty(&conn->ksnc_tx_queue) && bufnob == 0) {
778                 /* First packet starts the timeout */
779                 conn->ksnc_tx_deadline = ktime_get_seconds() +
780                                          ksocknal_timeout();
781                 if (conn->ksnc_tx_bufnob > 0) /* something got ACKed */
782                         conn->ksnc_peer->ksnp_last_alive = ktime_get_seconds();
783                 conn->ksnc_tx_bufnob = 0;
784                 smp_mb(); /* order with adding to tx_queue */
785         }
786
787         if (msg->ksm_type == KSOCK_MSG_NOOP) {
788                 /* The packet is noop ZC ACK, try to piggyback the ack_cookie
789                  * on a normal packet so I don't need to send it */
790                 LASSERT (msg->ksm_zc_cookies[1] != 0);
791                 LASSERT (conn->ksnc_proto->pro_queue_tx_zcack != NULL);
792
793                 if (conn->ksnc_proto->pro_queue_tx_zcack(conn, tx, 0))
794                         ztx = tx; /* ZC ACK piggybacked on ztx release tx later */
795
796         } else {
797                 /* It's a normal packet - can it piggback a noop zc-ack that
798                  * has been queued already? */
799                 LASSERT (msg->ksm_zc_cookies[1] == 0);
800                 LASSERT (conn->ksnc_proto->pro_queue_tx_msg != NULL);
801
802                 ztx = conn->ksnc_proto->pro_queue_tx_msg(conn, tx);
803                 /* ztx will be released later */
804         }
805
806         if (ztx != NULL) {
807                 atomic_sub (ztx->tx_nob, &conn->ksnc_tx_nob);
808                 list_add_tail(&ztx->tx_list, &sched->kss_zombie_noop_txs);
809         }
810
811         if (conn->ksnc_tx_ready &&      /* able to send */
812             !conn->ksnc_tx_scheduled) { /* not scheduled to send */
813                 /* +1 ref for scheduler */
814                 ksocknal_conn_addref(conn);
815                 list_add_tail(&conn->ksnc_tx_list,
816                                    &sched->kss_tx_conns);
817                 conn->ksnc_tx_scheduled = 1;
818                 wake_up(&sched->kss_waitq);
819         }
820
821         spin_unlock_bh(&sched->kss_lock);
822 }
823
824
825 struct ksock_conn_cb *
826 ksocknal_find_connectable_conn_cb_locked(struct ksock_peer_ni *peer_ni)
827 {
828         time64_t now = ktime_get_seconds();
829         struct ksock_conn_cb *conn_cb;
830
831         conn_cb = peer_ni->ksnp_conn_cb;
832         if (!conn_cb)
833                 return NULL;
834
835         LASSERT(!conn_cb->ksnr_connecting || conn_cb->ksnr_scheduled);
836
837         if (conn_cb->ksnr_scheduled)    /* connections being established */
838                 return NULL;
839
840         /* all conn types connected ? */
841         if ((ksocknal_conn_cb_mask() & ~conn_cb->ksnr_connected) == 0)
842                 return NULL;
843
844         if (!(conn_cb->ksnr_retry_interval == 0 || /* first attempt */
845               now >= conn_cb->ksnr_timeout)) {
846                 CDEBUG(D_NET,
847                        "Too soon to retry route %pIS (cnted %d, interval %lld, %lld secs later)\n",
848                        &conn_cb->ksnr_addr,
849                        conn_cb->ksnr_connected,
850                        conn_cb->ksnr_retry_interval,
851                        conn_cb->ksnr_timeout - now);
852                 return NULL;
853         }
854
855         return conn_cb;
856 }
857
858 struct ksock_conn_cb *
859 ksocknal_find_connecting_conn_cb_locked(struct ksock_peer_ni *peer_ni)
860 {
861         struct ksock_conn_cb *conn_cb;
862
863         conn_cb = peer_ni->ksnp_conn_cb;
864         if (!conn_cb)
865                 return NULL;
866
867         LASSERT(!conn_cb->ksnr_connecting || conn_cb->ksnr_scheduled);
868
869         return conn_cb->ksnr_scheduled ? conn_cb : NULL;
870 }
871
872 int
873 ksocknal_launch_packet(struct lnet_ni *ni, struct ksock_tx *tx,
874                        struct lnet_processid *id)
875 {
876         struct ksock_peer_ni *peer_ni;
877         struct ksock_conn *conn;
878         struct sockaddr_in sa;
879         rwlock_t *g_lock;
880         int retry;
881         int rc;
882
883         LASSERT(tx->tx_conn == NULL);
884
885         g_lock = &ksocknal_data.ksnd_global_lock;
886
887         for (retry = 0;; retry = 1) {
888                 read_lock(g_lock);
889                 peer_ni = ksocknal_find_peer_locked(ni, id);
890                 if (peer_ni != NULL) {
891                         if (ksocknal_find_connectable_conn_cb_locked(peer_ni) == NULL) {
892                                 conn = ksocknal_find_conn_locked(peer_ni, tx, tx->tx_nonblk);
893                                 if (conn != NULL) {
894                                         /* I've got nothing that need to be
895                                          * connecting and I do have an actual
896                                          * connection...
897                                          */
898                                         ksocknal_queue_tx_locked(tx, conn);
899                                         read_unlock(g_lock);
900                                         return 0;
901                                 }
902                         }
903                 }
904
905                 /* I'll need a write lock... */
906                 read_unlock(g_lock);
907
908                 write_lock_bh(g_lock);
909
910                 peer_ni = ksocknal_find_peer_locked(ni, id);
911                 if (peer_ni != NULL)
912                         break;
913
914                 write_unlock_bh(g_lock);
915
916                 if ((id->pid & LNET_PID_USERFLAG) != 0) {
917                         CERROR("Refusing to create a connection to userspace process %s\n",
918                                libcfs_idstr(id));
919                         return -EHOSTUNREACH;
920                 }
921
922                 if (retry) {
923                         CERROR("Can't find peer_ni %s\n", libcfs_idstr(id));
924                         return -EHOSTUNREACH;
925                 }
926
927                 memset(&sa, 0, sizeof(sa));
928                 sa.sin_family = AF_INET;
929                 sa.sin_addr.s_addr = id->nid.nid_addr[0];
930                 sa.sin_port = htons(lnet_acceptor_port());
931                 {
932                         struct lnet_process_id id4 = {
933                                 .pid = id->pid,
934                                 .nid = lnet_nid_to_nid4(&id->nid),
935                         };
936                         rc = ksocknal_add_peer(ni, id4, (struct sockaddr *)&sa);
937                 }
938                 if (rc != 0) {
939                         CERROR("Can't add peer_ni %s: %d\n",
940                                libcfs_idstr(id), rc);
941                         return rc;
942                 }
943         }
944
945         ksocknal_launch_all_connections_locked(peer_ni);
946
947         conn = ksocknal_find_conn_locked(peer_ni, tx, tx->tx_nonblk);
948         if (conn != NULL) {
949                 /* Connection exists; queue message on it */
950                 ksocknal_queue_tx_locked (tx, conn);
951                 write_unlock_bh(g_lock);
952                 return (0);
953         }
954
955         if (peer_ni->ksnp_accepting > 0 ||
956             ksocknal_find_connecting_conn_cb_locked(peer_ni) != NULL) {
957                 /* the message is going to be pinned to the peer_ni */
958                 tx->tx_deadline = ktime_get_seconds() +
959                                   ksocknal_timeout();
960
961                 /* Queue the message until a connection is established */
962                 list_add_tail(&tx->tx_list, &peer_ni->ksnp_tx_queue);
963                 write_unlock_bh(g_lock);
964                 return 0;
965         }
966
967         write_unlock_bh(g_lock);
968
969         /* NB Routes may be ignored if connections to them failed recently */
970         CNETERR("No usable routes to %s\n", libcfs_idstr(id));
971         tx->tx_hstatus = LNET_MSG_STATUS_REMOTE_ERROR;
972         return (-EHOSTUNREACH);
973 }
974
975 int
976 ksocknal_send(struct lnet_ni *ni, void *private, struct lnet_msg *lntmsg)
977 {
978         /* '1' for consistency with code that checks !mpflag to restore */
979         unsigned int mpflag = 1;
980         int type = lntmsg->msg_type;
981         struct lnet_processid *target = &lntmsg->msg_target;
982         unsigned int payload_niov = lntmsg->msg_niov;
983         struct bio_vec *payload_kiov = lntmsg->msg_kiov;
984         unsigned int payload_offset = lntmsg->msg_offset;
985         unsigned int payload_nob = lntmsg->msg_len;
986         struct ksock_tx *tx;
987         int desc_size;
988         int rc;
989
990         /* NB 'private' is different depending on what we're sending.
991          * Just ignore it...
992          */
993
994         CDEBUG(D_NET, "sending %u bytes in %d frags to %s\n",
995                payload_nob, payload_niov, libcfs_idstr(target));
996
997         LASSERT (payload_nob == 0 || payload_niov > 0);
998         LASSERT (payload_niov <= LNET_MAX_IOV);
999         LASSERT (!in_interrupt ());
1000
1001         desc_size = offsetof(struct ksock_tx,
1002                              tx_payload[payload_niov]);
1003
1004         if (lntmsg->msg_vmflush)
1005                 mpflag = memalloc_noreclaim_save();
1006
1007         tx = ksocknal_alloc_tx(KSOCK_MSG_LNET, desc_size);
1008         if (tx == NULL) {
1009                 CERROR("Can't allocate tx desc type %d size %d\n",
1010                        type, desc_size);
1011                 if (lntmsg->msg_vmflush)
1012                         memalloc_noreclaim_restore(mpflag);
1013                 return -ENOMEM;
1014         }
1015
1016         tx->tx_conn = NULL;                     /* set when assigned a conn */
1017         tx->tx_lnetmsg = lntmsg;
1018
1019         tx->tx_niov = 1;
1020         tx->tx_kiov = tx->tx_payload;
1021         tx->tx_nkiov = lnet_extract_kiov(payload_niov, tx->tx_kiov,
1022                                          payload_niov, payload_kiov,
1023                                          payload_offset, payload_nob);
1024
1025         if (payload_nob >= *ksocknal_tunables.ksnd_zc_min_payload)
1026                 tx->tx_zc_capable = 1;
1027
1028         tx->tx_msg.ksm_csum = 0;
1029         tx->tx_msg.ksm_type = KSOCK_MSG_LNET;
1030         tx->tx_msg.ksm_zc_cookies[0] = 0;
1031         tx->tx_msg.ksm_zc_cookies[1] = 0;
1032
1033         /* The first fragment will be set later in pro_pack */
1034         rc = ksocknal_launch_packet(ni, tx, target);
1035         /*
1036          * We can't test lntsmg->msg_vmflush again as lntmsg may
1037          * have been freed.
1038          */
1039         if (!mpflag)
1040                 memalloc_noreclaim_restore(mpflag);
1041
1042         if (rc == 0)
1043                 return (0);
1044
1045         lntmsg->msg_health_status = tx->tx_hstatus;
1046         ksocknal_free_tx(tx);
1047         return -EIO;
1048 }
1049
1050 void
1051 ksocknal_thread_fini (void)
1052 {
1053         if (atomic_dec_and_test(&ksocknal_data.ksnd_nthreads))
1054                 wake_up_var(&ksocknal_data.ksnd_nthreads);
1055 }
1056
1057 int
1058 ksocknal_new_packet(struct ksock_conn *conn, int nob_to_skip)
1059 {
1060         static char ksocknal_slop_buffer[4096];
1061         int nob;
1062         unsigned int niov;
1063         int skipped;
1064
1065         LASSERT(conn->ksnc_proto != NULL);
1066
1067         if ((*ksocknal_tunables.ksnd_eager_ack & conn->ksnc_type) != 0) {
1068                 /* Remind the socket to ack eagerly... */
1069                 ksocknal_lib_eager_ack(conn);
1070         }
1071
1072         if (nob_to_skip == 0) {         /* right at next packet boundary now */
1073                 conn->ksnc_rx_started = 0;
1074                 smp_mb();                       /* racing with timeout thread */
1075
1076                 switch (conn->ksnc_proto->pro_version) {
1077                 case  KSOCK_PROTO_V2:
1078                 case  KSOCK_PROTO_V3:
1079                         conn->ksnc_rx_state = SOCKNAL_RX_KSM_HEADER;
1080                         conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
1081                         conn->ksnc_rx_iov[0].iov_base = (char *)&conn->ksnc_msg;
1082
1083                         conn->ksnc_rx_nob_wanted = sizeof(struct ksock_msg_hdr);
1084                         conn->ksnc_rx_nob_left = sizeof(struct ksock_msg_hdr);
1085                         conn->ksnc_rx_iov[0].iov_len =
1086                                 sizeof(struct ksock_msg_hdr);
1087                         break;
1088
1089                 case KSOCK_PROTO_V1:
1090                         /* Receiving bare struct lnet_hdr */
1091                         conn->ksnc_rx_state = SOCKNAL_RX_LNET_HEADER;
1092                         conn->ksnc_rx_nob_wanted = sizeof(struct lnet_hdr);
1093                         conn->ksnc_rx_nob_left = sizeof(struct lnet_hdr);
1094
1095                         conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
1096                         conn->ksnc_rx_iov[0].iov_base = (char *)&conn->ksnc_msg.ksm_u.lnetmsg;
1097                         conn->ksnc_rx_iov[0].iov_len = sizeof(struct lnet_hdr);
1098                         break;
1099
1100                 default:
1101                         LBUG ();
1102                 }
1103                 conn->ksnc_rx_niov = 1;
1104
1105                 conn->ksnc_rx_kiov = NULL;
1106                 conn->ksnc_rx_nkiov = 0;
1107                 conn->ksnc_rx_csum = ~0;
1108                 return (1);
1109         }
1110
1111         /* Set up to skip as much as possible now.  If there's more left
1112          * (ran out of iov entries) we'll get called again */
1113
1114         conn->ksnc_rx_state = SOCKNAL_RX_SLOP;
1115         conn->ksnc_rx_nob_left = nob_to_skip;
1116         conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
1117         skipped = 0;
1118         niov = 0;
1119
1120         do {
1121                 nob = min_t(int, nob_to_skip, sizeof(ksocknal_slop_buffer));
1122
1123                 conn->ksnc_rx_iov[niov].iov_base = ksocknal_slop_buffer;
1124                 conn->ksnc_rx_iov[niov].iov_len  = nob;
1125                 niov++;
1126                 skipped += nob;
1127                 nob_to_skip -= nob;
1128
1129         } while (nob_to_skip != 0 &&    /* mustn't overflow conn's rx iov */
1130                  niov < sizeof(conn->ksnc_rx_iov_space) / sizeof(struct kvec));
1131
1132         conn->ksnc_rx_niov = niov;
1133         conn->ksnc_rx_kiov = NULL;
1134         conn->ksnc_rx_nkiov = 0;
1135         conn->ksnc_rx_nob_wanted = skipped;
1136         return (0);
1137 }
1138
1139 static int
1140 ksocknal_process_receive(struct ksock_conn *conn,
1141                          struct page **rx_scratch_pgs,
1142                          struct kvec *scratch_iov)
1143 {
1144         struct lnet_hdr *lhdr;
1145         struct lnet_processid *id;
1146         int rc;
1147
1148         LASSERT(refcount_read(&conn->ksnc_conn_refcount) > 0);
1149
1150         /* NB: sched lock NOT held */
1151         /* SOCKNAL_RX_LNET_HEADER is here for backward compatibility */
1152         LASSERT(conn->ksnc_rx_state == SOCKNAL_RX_KSM_HEADER ||
1153                 conn->ksnc_rx_state == SOCKNAL_RX_LNET_PAYLOAD ||
1154                 conn->ksnc_rx_state == SOCKNAL_RX_LNET_HEADER ||
1155                 conn->ksnc_rx_state == SOCKNAL_RX_SLOP);
1156  again:
1157         if (conn->ksnc_rx_nob_wanted != 0) {
1158                 rc = ksocknal_receive(conn, rx_scratch_pgs,
1159                                       scratch_iov);
1160
1161                 if (rc <= 0) {
1162                         struct lnet_processid *ksnp_id;
1163
1164                         ksnp_id = &conn->ksnc_peer->ksnp_id;
1165
1166                         LASSERT(rc != -EAGAIN);
1167                         if (rc == 0)
1168                                 CDEBUG(D_NET, "[%p] EOF from %s ip %pISp\n",
1169                                        conn, libcfs_idstr(ksnp_id),
1170                                        &conn->ksnc_peeraddr);
1171                         else if (!conn->ksnc_closing)
1172                                 CERROR("[%p] Error %d on read from %s ip %pISp\n",
1173                                        conn, rc, libcfs_idstr(ksnp_id),
1174                                        &conn->ksnc_peeraddr);
1175
1176                         /* it's not an error if conn is being closed */
1177                         ksocknal_close_conn_and_siblings (conn,
1178                                                           (conn->ksnc_closing) ? 0 : rc);
1179                         return (rc == 0 ? -ESHUTDOWN : rc);
1180                 }
1181
1182                 if (conn->ksnc_rx_nob_wanted != 0) {
1183                         /* short read */
1184                         return (-EAGAIN);
1185                 }
1186         }
1187         switch (conn->ksnc_rx_state) {
1188         case SOCKNAL_RX_KSM_HEADER:
1189                 if (conn->ksnc_flip) {
1190                         __swab32s(&conn->ksnc_msg.ksm_type);
1191                         __swab32s(&conn->ksnc_msg.ksm_csum);
1192                         __swab64s(&conn->ksnc_msg.ksm_zc_cookies[0]);
1193                         __swab64s(&conn->ksnc_msg.ksm_zc_cookies[1]);
1194                 }
1195
1196                 if (conn->ksnc_msg.ksm_type == KSOCK_MSG_NOOP &&
1197                     conn->ksnc_msg.ksm_csum != 0 &&     /* has checksum */
1198                     conn->ksnc_msg.ksm_csum != conn->ksnc_rx_csum) {
1199                         /* NOOP Checksum error */
1200                         CERROR("%s: Checksum error, wire:0x%08X data:0x%08X\n",
1201                                libcfs_idstr(&conn->ksnc_peer->ksnp_id),
1202                                conn->ksnc_msg.ksm_csum, conn->ksnc_rx_csum);
1203                         ksocknal_new_packet(conn, 0);
1204                         ksocknal_close_conn_and_siblings(conn, -EPROTO);
1205                         return (-EIO);
1206                 }
1207
1208                 if (conn->ksnc_msg.ksm_zc_cookies[1] != 0) {
1209                         __u64 cookie = 0;
1210
1211                         LASSERT(conn->ksnc_proto != &ksocknal_protocol_v1x);
1212
1213                         if (conn->ksnc_msg.ksm_type == KSOCK_MSG_NOOP)
1214                                 cookie = conn->ksnc_msg.ksm_zc_cookies[0];
1215
1216                         rc = conn->ksnc_proto->pro_handle_zcack(
1217                                 conn, cookie, conn->ksnc_msg.ksm_zc_cookies[1]);
1218
1219                         if (rc != 0) {
1220                                 CERROR("%s: Unknown ZC-ACK cookie: %llu, %llu\n",
1221                                        libcfs_idstr(&conn->ksnc_peer->ksnp_id),
1222                                        cookie,
1223                                        conn->ksnc_msg.ksm_zc_cookies[1]);
1224                                 ksocknal_new_packet(conn, 0);
1225                                 ksocknal_close_conn_and_siblings(conn, -EPROTO);
1226                                 return rc;
1227                         }
1228                 }
1229
1230                 switch (conn->ksnc_msg.ksm_type) {
1231                 case KSOCK_MSG_NOOP:
1232                         ksocknal_new_packet(conn, 0);
1233                         return 0;       /* NOOP is done and just return */
1234
1235                 case KSOCK_MSG_LNET:
1236
1237                         conn->ksnc_rx_state = SOCKNAL_RX_LNET_HEADER;
1238                         conn->ksnc_rx_nob_wanted = sizeof(struct lnet_hdr);
1239                         conn->ksnc_rx_nob_left = sizeof(struct lnet_hdr);
1240
1241                         conn->ksnc_rx_iov = conn->ksnc_rx_iov_space.iov;
1242                         conn->ksnc_rx_iov[0].iov_base =
1243                                 (void *)&conn->ksnc_msg.ksm_u.lnetmsg;
1244                         conn->ksnc_rx_iov[0].iov_len = sizeof(struct lnet_hdr);
1245
1246                         conn->ksnc_rx_niov = 1;
1247                         conn->ksnc_rx_kiov = NULL;
1248                         conn->ksnc_rx_nkiov = 0;
1249
1250                         goto again;     /* read lnet header now */
1251
1252                 default:
1253                         CERROR("%s: Unknown message type: %x\n",
1254                                libcfs_idstr(&conn->ksnc_peer->ksnp_id),
1255                                conn->ksnc_msg.ksm_type);
1256                         ksocknal_new_packet(conn, 0);
1257                         ksocknal_close_conn_and_siblings(conn, -EPROTO);
1258                         return -EPROTO;
1259                 }
1260
1261         case SOCKNAL_RX_LNET_HEADER:
1262                 /* unpack message header */
1263                 conn->ksnc_proto->pro_unpack(&conn->ksnc_msg);
1264
1265                 if ((conn->ksnc_peer->ksnp_id.pid & LNET_PID_USERFLAG) != 0) {
1266                         /* Userspace peer_ni */
1267                         lhdr = &conn->ksnc_msg.ksm_u.lnetmsg;
1268                         id = &conn->ksnc_peer->ksnp_id;
1269
1270                         /* Substitute process ID assigned at connection time */
1271                         lhdr->src_pid = cpu_to_le32(id->pid);
1272                         lhdr->src_nid = cpu_to_le64(lnet_nid_to_nid4(&id->nid));
1273                 }
1274
1275                 conn->ksnc_rx_state = SOCKNAL_RX_PARSE;
1276                 ksocknal_conn_addref(conn);     /* ++ref while parsing */
1277
1278                 rc = lnet_parse(conn->ksnc_peer->ksnp_ni,
1279                                 &conn->ksnc_msg.ksm_u.lnetmsg,
1280                                 lnet_nid_to_nid4(&conn->ksnc_peer->ksnp_id.nid),
1281                                 conn, 0);
1282                 if (rc < 0) {
1283                         /* I just received garbage: give up on this conn */
1284                         ksocknal_new_packet(conn, 0);
1285                         ksocknal_close_conn_and_siblings(conn, rc);
1286                         ksocknal_conn_decref(conn);
1287                         return (-EPROTO);
1288                 }
1289
1290                 /* I'm racing with ksocknal_recv() */
1291                 LASSERT(conn->ksnc_rx_state == SOCKNAL_RX_PARSE ||
1292                         conn->ksnc_rx_state == SOCKNAL_RX_LNET_PAYLOAD);
1293
1294                 if (conn->ksnc_rx_state != SOCKNAL_RX_LNET_PAYLOAD)
1295                         return 0;
1296
1297                 /* ksocknal_recv() got called */
1298                 goto again;
1299
1300         case SOCKNAL_RX_LNET_PAYLOAD:
1301                 /* payload all received */
1302                 rc = 0;
1303
1304                 if (conn->ksnc_rx_nob_left == 0 &&   /* not truncating */
1305                     conn->ksnc_msg.ksm_csum != 0 &&  /* has checksum */
1306                     conn->ksnc_msg.ksm_csum != conn->ksnc_rx_csum) {
1307                         CERROR("%s: Checksum error, wire:0x%08X data:0x%08X\n",
1308                                libcfs_idstr(&conn->ksnc_peer->ksnp_id),
1309                                conn->ksnc_msg.ksm_csum, conn->ksnc_rx_csum);
1310                         rc = -EIO;
1311                 }
1312
1313                 if (rc == 0 && conn->ksnc_msg.ksm_zc_cookies[0] != 0) {
1314                         LASSERT(conn->ksnc_proto != &ksocknal_protocol_v1x);
1315
1316                         lhdr = &conn->ksnc_msg.ksm_u.lnetmsg;
1317                         id = &conn->ksnc_peer->ksnp_id;
1318
1319                         rc = conn->ksnc_proto->pro_handle_zcreq(
1320                                 conn,
1321                                 conn->ksnc_msg.ksm_zc_cookies[0],
1322                                 *ksocknal_tunables.ksnd_nonblk_zcack ||
1323                                 le64_to_cpu(lhdr->src_nid) !=
1324                                 lnet_nid_to_nid4(&id->nid));
1325                 }
1326
1327                 if (rc && conn->ksnc_lnet_msg)
1328                         conn->ksnc_lnet_msg->msg_health_status =
1329                                 LNET_MSG_STATUS_REMOTE_ERROR;
1330                 lnet_finalize(conn->ksnc_lnet_msg, rc);
1331
1332                 if (rc != 0) {
1333                         ksocknal_new_packet(conn, 0);
1334                         ksocknal_close_conn_and_siblings(conn, rc);
1335                         return (-EPROTO);
1336                 }
1337                 /* Fall through */
1338
1339         case SOCKNAL_RX_SLOP:
1340                 /* starting new packet? */
1341                 if (ksocknal_new_packet(conn, conn->ksnc_rx_nob_left))
1342                         return 0;       /* come back later */
1343                 goto again;             /* try to finish reading slop now */
1344
1345         default:
1346                 break;
1347         }
1348
1349         /* Not Reached */
1350         LBUG ();
1351         return (-EINVAL);                       /* keep gcc happy */
1352 }
1353
1354 int
1355 ksocknal_recv(struct lnet_ni *ni, void *private, struct lnet_msg *msg,
1356               int delayed, unsigned int niov,
1357               struct bio_vec *kiov, unsigned int offset, unsigned int mlen,
1358               unsigned int rlen)
1359 {
1360         struct ksock_conn *conn = private;
1361         struct ksock_sched *sched = conn->ksnc_scheduler;
1362
1363         LASSERT (mlen <= rlen);
1364         LASSERT (niov <= LNET_MAX_IOV);
1365
1366         conn->ksnc_lnet_msg = msg;
1367         conn->ksnc_rx_nob_wanted = mlen;
1368         conn->ksnc_rx_nob_left   = rlen;
1369
1370         if (mlen == 0) {
1371                 conn->ksnc_rx_nkiov = 0;
1372                 conn->ksnc_rx_kiov = NULL;
1373                 conn->ksnc_rx_iov = conn->ksnc_rx_iov_space.iov;
1374                 conn->ksnc_rx_niov = 0;
1375         } else {
1376                 conn->ksnc_rx_niov = 0;
1377                 conn->ksnc_rx_iov  = NULL;
1378                 conn->ksnc_rx_kiov = conn->ksnc_rx_iov_space.kiov;
1379                 conn->ksnc_rx_nkiov =
1380                         lnet_extract_kiov(LNET_MAX_IOV, conn->ksnc_rx_kiov,
1381                                           niov, kiov, offset, mlen);
1382         }
1383
1384         LASSERT (mlen ==
1385                  lnet_iov_nob (conn->ksnc_rx_niov, conn->ksnc_rx_iov) +
1386                  lnet_kiov_nob (conn->ksnc_rx_nkiov, conn->ksnc_rx_kiov));
1387
1388         LASSERT (conn->ksnc_rx_scheduled);
1389
1390         spin_lock_bh(&sched->kss_lock);
1391
1392         switch (conn->ksnc_rx_state) {
1393         case SOCKNAL_RX_PARSE_WAIT:
1394                 list_add_tail(&conn->ksnc_rx_list, &sched->kss_rx_conns);
1395                 wake_up(&sched->kss_waitq);
1396                 LASSERT(conn->ksnc_rx_ready);
1397                 break;
1398
1399         case SOCKNAL_RX_PARSE:
1400                 /* scheduler hasn't noticed I'm parsing yet */
1401                 break;
1402         }
1403
1404         conn->ksnc_rx_state = SOCKNAL_RX_LNET_PAYLOAD;
1405
1406         spin_unlock_bh(&sched->kss_lock);
1407         ksocknal_conn_decref(conn);
1408         return 0;
1409 }
1410
1411 static inline int
1412 ksocknal_sched_cansleep(struct ksock_sched *sched)
1413 {
1414         int           rc;
1415
1416         spin_lock_bh(&sched->kss_lock);
1417
1418         rc = (!ksocknal_data.ksnd_shuttingdown &&
1419               list_empty(&sched->kss_rx_conns) &&
1420               list_empty(&sched->kss_tx_conns));
1421
1422         spin_unlock_bh(&sched->kss_lock);
1423         return rc;
1424 }
1425
1426 int ksocknal_scheduler(void *arg)
1427 {
1428         struct ksock_sched *sched;
1429         struct ksock_conn *conn;
1430         struct ksock_tx *tx;
1431         int rc;
1432         long id = (long)arg;
1433         struct page **rx_scratch_pgs;
1434         struct kvec *scratch_iov;
1435
1436         sched = ksocknal_data.ksnd_schedulers[KSOCK_THREAD_CPT(id)];
1437
1438         LIBCFS_CPT_ALLOC(rx_scratch_pgs, lnet_cpt_table(), sched->kss_cpt,
1439                          sizeof(*rx_scratch_pgs) * LNET_MAX_IOV);
1440         if (!rx_scratch_pgs) {
1441                 CERROR("Unable to allocate scratch pages\n");
1442                 return -ENOMEM;
1443         }
1444
1445         LIBCFS_CPT_ALLOC(scratch_iov, lnet_cpt_table(), sched->kss_cpt,
1446                          sizeof(*scratch_iov) * LNET_MAX_IOV);
1447         if (!scratch_iov) {
1448                 CERROR("Unable to allocate scratch iov\n");
1449                 return -ENOMEM;
1450         }
1451
1452         rc = cfs_cpt_bind(lnet_cpt_table(), sched->kss_cpt);
1453         if (rc != 0) {
1454                 CWARN("Can't set CPU partition affinity to %d: %d\n",
1455                         sched->kss_cpt, rc);
1456         }
1457
1458         spin_lock_bh(&sched->kss_lock);
1459
1460         while (!ksocknal_data.ksnd_shuttingdown) {
1461                 bool did_something = false;
1462
1463                 /* Ensure I progress everything semi-fairly */
1464                 conn = list_first_entry_or_null(&sched->kss_rx_conns,
1465                                                 struct ksock_conn,
1466                                                 ksnc_rx_list);
1467                 if (conn) {
1468                         list_del(&conn->ksnc_rx_list);
1469
1470                         LASSERT(conn->ksnc_rx_scheduled);
1471                         LASSERT(conn->ksnc_rx_ready);
1472
1473                         /* clear rx_ready in case receive isn't complete.
1474                          * Do it BEFORE we call process_recv, since
1475                          * data_ready can set it any time after we release
1476                          * kss_lock. */
1477                         conn->ksnc_rx_ready = 0;
1478                         spin_unlock_bh(&sched->kss_lock);
1479
1480                         rc = ksocknal_process_receive(conn, rx_scratch_pgs,
1481                                                       scratch_iov);
1482
1483                         spin_lock_bh(&sched->kss_lock);
1484
1485                         /* I'm the only one that can clear this flag */
1486                         LASSERT(conn->ksnc_rx_scheduled);
1487
1488                         /* Did process_receive get everything it wanted? */
1489                         if (rc == 0)
1490                                 conn->ksnc_rx_ready = 1;
1491
1492                         if (conn->ksnc_rx_state == SOCKNAL_RX_PARSE) {
1493                                 /* Conn blocked waiting for ksocknal_recv()
1494                                  * I change its state (under lock) to signal
1495                                  * it can be rescheduled */
1496                                 conn->ksnc_rx_state = SOCKNAL_RX_PARSE_WAIT;
1497                         } else if (conn->ksnc_rx_ready) {
1498                                 /* reschedule for rx */
1499                                 list_add_tail(&conn->ksnc_rx_list,
1500                                                    &sched->kss_rx_conns);
1501                         } else {
1502                                 conn->ksnc_rx_scheduled = 0;
1503                                 /* drop my ref */
1504                                 ksocknal_conn_decref(conn);
1505                         }
1506
1507                         did_something = true;
1508                 }
1509
1510                 if (!list_empty(&sched->kss_tx_conns)) {
1511                         LIST_HEAD(zlist);
1512
1513                         list_splice_init(&sched->kss_zombie_noop_txs, &zlist);
1514
1515                         conn = list_first_entry(&sched->kss_tx_conns,
1516                                                 struct ksock_conn,
1517                                                 ksnc_tx_list);
1518                         list_del(&conn->ksnc_tx_list);
1519
1520                         LASSERT(conn->ksnc_tx_scheduled);
1521                         LASSERT(conn->ksnc_tx_ready);
1522                         LASSERT(!list_empty(&conn->ksnc_tx_queue));
1523
1524                         tx = list_first_entry(&conn->ksnc_tx_queue,
1525                                               struct ksock_tx, tx_list);
1526
1527                         if (conn->ksnc_tx_carrier == tx)
1528                                 ksocknal_next_tx_carrier(conn);
1529
1530                         /* dequeue now so empty list => more to send */
1531                         list_del(&tx->tx_list);
1532
1533                         /* Clear tx_ready in case send isn't complete.  Do
1534                          * it BEFORE we call process_transmit, since
1535                          * write_space can set it any time after we release
1536                          * kss_lock. */
1537                         conn->ksnc_tx_ready = 0;
1538                         spin_unlock_bh(&sched->kss_lock);
1539
1540                         if (!list_empty(&zlist)) {
1541                                 /* free zombie noop txs, it's fast because
1542                                  * noop txs are just put in freelist */
1543                                 ksocknal_txlist_done(NULL, &zlist, 0);
1544                         }
1545
1546                         rc = ksocknal_process_transmit(conn, tx, scratch_iov);
1547
1548                         if (rc == -ENOMEM || rc == -EAGAIN) {
1549                                 /* Incomplete send: replace tx on HEAD of tx_queue */
1550                                 spin_lock_bh(&sched->kss_lock);
1551                                 list_add(&tx->tx_list,
1552                                          &conn->ksnc_tx_queue);
1553                         } else {
1554                                 /* Complete send; tx -ref */
1555                                 ksocknal_tx_decref(tx);
1556
1557                                 spin_lock_bh(&sched->kss_lock);
1558                                 /* assume space for more */
1559                                 conn->ksnc_tx_ready = 1;
1560                         }
1561
1562                         if (rc == -ENOMEM) {
1563                                 /* Do nothing; after a short timeout, this
1564                                  * conn will be reposted on kss_tx_conns. */
1565                         } else if (conn->ksnc_tx_ready &&
1566                                    !list_empty(&conn->ksnc_tx_queue)) {
1567                                 /* reschedule for tx */
1568                                 list_add_tail(&conn->ksnc_tx_list,
1569                                               &sched->kss_tx_conns);
1570                         } else {
1571                                 conn->ksnc_tx_scheduled = 0;
1572                                 /* drop my ref */
1573                                 ksocknal_conn_decref(conn);
1574                         }
1575
1576                         did_something = true;
1577                 }
1578                 if (!did_something ||   /* nothing to do */
1579                     need_resched()) {   /* hogging CPU? */
1580                         spin_unlock_bh(&sched->kss_lock);
1581
1582                         if (!did_something) {   /* wait for something to do */
1583                                 rc = wait_event_interruptible_exclusive(
1584                                         sched->kss_waitq,
1585                                         !ksocknal_sched_cansleep(sched));
1586                                 LASSERT (rc == 0);
1587                         } else {
1588                                 cond_resched();
1589                         }
1590
1591                         spin_lock_bh(&sched->kss_lock);
1592                 }
1593         }
1594
1595         spin_unlock_bh(&sched->kss_lock);
1596         CFS_FREE_PTR_ARRAY(rx_scratch_pgs, LNET_MAX_IOV);
1597         CFS_FREE_PTR_ARRAY(scratch_iov, LNET_MAX_IOV);
1598         ksocknal_thread_fini();
1599         return 0;
1600 }
1601
1602 /*
1603  * Add connection to kss_rx_conns of scheduler
1604  * and wakeup the scheduler.
1605  */
1606 void ksocknal_read_callback(struct ksock_conn *conn)
1607 {
1608         struct ksock_sched *sched;
1609
1610         sched = conn->ksnc_scheduler;
1611
1612         spin_lock_bh(&sched->kss_lock);
1613
1614         conn->ksnc_rx_ready = 1;
1615
1616         if (!conn->ksnc_rx_scheduled) {  /* not being progressed */
1617                 list_add_tail(&conn->ksnc_rx_list,
1618                                   &sched->kss_rx_conns);
1619                 conn->ksnc_rx_scheduled = 1;
1620                 /* extra ref for scheduler */
1621                 ksocknal_conn_addref(conn);
1622
1623                 wake_up (&sched->kss_waitq);
1624         }
1625         spin_unlock_bh(&sched->kss_lock);
1626 }
1627
1628 /*
1629  * Add connection to kss_tx_conns of scheduler
1630  * and wakeup the scheduler.
1631  */
1632 void ksocknal_write_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_tx_ready = 1;
1641
1642         if (!conn->ksnc_tx_scheduled && /* not being progressed */
1643             !list_empty(&conn->ksnc_tx_queue)) { /* packets to send */
1644                 list_add_tail(&conn->ksnc_tx_list, &sched->kss_tx_conns);
1645                 conn->ksnc_tx_scheduled = 1;
1646                 /* extra ref for scheduler */
1647                 ksocknal_conn_addref(conn);
1648
1649                 wake_up(&sched->kss_waitq);
1650         }
1651
1652         spin_unlock_bh(&sched->kss_lock);
1653 }
1654
1655 static const struct ksock_proto *
1656 ksocknal_parse_proto_version(struct ksock_hello_msg *hello)
1657 {
1658         __u32   version = 0;
1659
1660         if (hello->kshm_magic == LNET_PROTO_MAGIC)
1661                 version = hello->kshm_version;
1662         else if (hello->kshm_magic == __swab32(LNET_PROTO_MAGIC))
1663                 version = __swab32(hello->kshm_version);
1664
1665         if (version != 0) {
1666 #if SOCKNAL_VERSION_DEBUG
1667                 if (*ksocknal_tunables.ksnd_protocol == 1)
1668                         return NULL;
1669
1670                 if (*ksocknal_tunables.ksnd_protocol == 2 &&
1671                     version == KSOCK_PROTO_V3)
1672                         return NULL;
1673 #endif
1674                 if (version == KSOCK_PROTO_V2)
1675                         return &ksocknal_protocol_v2x;
1676
1677                 if (version == KSOCK_PROTO_V3)
1678                         return &ksocknal_protocol_v3x;
1679
1680                 return NULL;
1681         }
1682
1683         if (hello->kshm_magic == le32_to_cpu(LNET_PROTO_TCP_MAGIC)) {
1684                 struct lnet_magicversion *hmv;
1685
1686                 BUILD_BUG_ON(sizeof(struct lnet_magicversion) !=
1687                          offsetof(struct ksock_hello_msg, kshm_src_nid));
1688
1689                 hmv = (struct lnet_magicversion *)hello;
1690
1691                 if (hmv->version_major == cpu_to_le16 (KSOCK_PROTO_V1_MAJOR) &&
1692                     hmv->version_minor == cpu_to_le16 (KSOCK_PROTO_V1_MINOR))
1693                         return &ksocknal_protocol_v1x;
1694         }
1695
1696         return NULL;
1697 }
1698
1699 int
1700 ksocknal_send_hello(struct lnet_ni *ni, struct ksock_conn *conn,
1701                     lnet_nid_t peer_nid, struct ksock_hello_msg *hello)
1702 {
1703         /* CAVEAT EMPTOR: this byte flips 'ipaddrs' */
1704         struct ksock_net *net = (struct ksock_net *)ni->ni_data;
1705
1706         LASSERT(hello->kshm_nips <= LNET_INTERFACES_NUM);
1707
1708         /* rely on caller to hold a ref on socket so it wouldn't disappear */
1709         LASSERT(conn->ksnc_proto != NULL);
1710
1711         hello->kshm_src_nid         = lnet_nid_to_nid4(&ni->ni_nid);
1712         hello->kshm_dst_nid         = peer_nid;
1713         hello->kshm_src_pid         = the_lnet.ln_pid;
1714
1715         hello->kshm_src_incarnation = net->ksnn_incarnation;
1716         hello->kshm_ctype           = conn->ksnc_type;
1717
1718         return conn->ksnc_proto->pro_send_hello(conn, hello);
1719 }
1720
1721 static int
1722 ksocknal_invert_type(int type)
1723 {
1724         switch (type)
1725         {
1726         case SOCKLND_CONN_ANY:
1727         case SOCKLND_CONN_CONTROL:
1728                 return (type);
1729         case SOCKLND_CONN_BULK_IN:
1730                 return SOCKLND_CONN_BULK_OUT;
1731         case SOCKLND_CONN_BULK_OUT:
1732                 return SOCKLND_CONN_BULK_IN;
1733         default:
1734                 return (SOCKLND_CONN_NONE);
1735         }
1736 }
1737
1738 int
1739 ksocknal_recv_hello(struct lnet_ni *ni, struct ksock_conn *conn,
1740                     struct ksock_hello_msg *hello,
1741                     struct lnet_process_id *peerid,
1742                     __u64 *incarnation)
1743 {
1744         /* Return < 0        fatal error
1745          *        0          success
1746          *        EALREADY   lost connection race
1747          *        EPROTO     protocol version mismatch
1748          */
1749         struct socket        *sock = conn->ksnc_sock;
1750         int                  active = (conn->ksnc_proto != NULL);
1751         int                  timeout;
1752         int                  proto_match;
1753         int                  rc;
1754         const struct ksock_proto *proto;
1755         struct lnet_process_id recv_id;
1756
1757         /* socket type set on active connections - not set on passive */
1758         LASSERT(!active == !(conn->ksnc_type != SOCKLND_CONN_NONE));
1759
1760         timeout = active ? ksocknal_timeout() :
1761                 lnet_acceptor_timeout();
1762
1763         rc = lnet_sock_read(sock, &hello->kshm_magic,
1764                             sizeof(hello->kshm_magic), timeout);
1765         if (rc != 0) {
1766                 CERROR("Error %d reading HELLO from %pIS\n",
1767                        rc, &conn->ksnc_peeraddr);
1768                 LASSERT(rc < 0);
1769                 return rc;
1770         }
1771
1772         if (hello->kshm_magic != LNET_PROTO_MAGIC &&
1773             hello->kshm_magic != __swab32(LNET_PROTO_MAGIC) &&
1774             hello->kshm_magic != le32_to_cpu(LNET_PROTO_TCP_MAGIC)) {
1775                 /* Unexpected magic! */
1776                 CERROR("Bad magic(1) %#08x (%#08x expected) from %pIS\n",
1777                        __cpu_to_le32 (hello->kshm_magic),
1778                        LNET_PROTO_TCP_MAGIC, &conn->ksnc_peeraddr);
1779                 return -EPROTO;
1780         }
1781
1782         rc = lnet_sock_read(sock, &hello->kshm_version,
1783                             sizeof(hello->kshm_version), timeout);
1784         if (rc != 0) {
1785                 CERROR("Error %d reading HELLO from %pIS\n",
1786                        rc, &conn->ksnc_peeraddr);
1787                 LASSERT(rc < 0);
1788                 return rc;
1789         }
1790
1791         proto = ksocknal_parse_proto_version(hello);
1792         if (proto == NULL) {
1793                 if (!active) {
1794                         /* unknown protocol from peer_ni,
1795                          * tell peer_ni my protocol.
1796                          */
1797                         conn->ksnc_proto = &ksocknal_protocol_v3x;
1798 #if SOCKNAL_VERSION_DEBUG
1799                         if (*ksocknal_tunables.ksnd_protocol == 2)
1800                                 conn->ksnc_proto = &ksocknal_protocol_v2x;
1801                         else if (*ksocknal_tunables.ksnd_protocol == 1)
1802                                 conn->ksnc_proto = &ksocknal_protocol_v1x;
1803 #endif
1804                         hello->kshm_nips = 0;
1805                         ksocknal_send_hello(ni, conn,
1806                                             lnet_nid_to_nid4(&ni->ni_nid),
1807                                             hello);
1808                 }
1809
1810                 CERROR("Unknown protocol version (%d.x expected) from %pIS\n",
1811                        conn->ksnc_proto->pro_version, &conn->ksnc_peeraddr);
1812
1813                 return -EPROTO;
1814         }
1815
1816         proto_match = (conn->ksnc_proto == proto);
1817         conn->ksnc_proto = proto;
1818
1819         /* receive the rest of hello message anyway */
1820         rc = conn->ksnc_proto->pro_recv_hello(conn, hello, timeout);
1821         if (rc != 0) {
1822                 CERROR("Error %d reading or checking hello from from %pIS\n",
1823                        rc, &conn->ksnc_peeraddr);
1824                 LASSERT(rc < 0);
1825                 return rc;
1826         }
1827
1828         *incarnation = hello->kshm_src_incarnation;
1829
1830         if (hello->kshm_src_nid == LNET_NID_ANY) {
1831                 CERROR("Expecting a HELLO hdr with a NID, but got LNET_NID_ANY from %pIS\n",
1832                        &conn->ksnc_peeraddr);
1833                 return -EPROTO;
1834         }
1835
1836         if (!active &&
1837             rpc_get_port((struct sockaddr *)&conn->ksnc_peeraddr) >
1838             LNET_ACCEPTOR_MAX_RESERVED_PORT) {
1839                 /* Userspace NAL assigns peer_ni process ID from socket */
1840                 recv_id.pid = rpc_get_port((struct sockaddr *)
1841                                            &conn->ksnc_peeraddr) |
1842                         LNET_PID_USERFLAG;
1843                 LASSERT(conn->ksnc_peeraddr.ss_family == AF_INET);
1844                 recv_id.nid = LNET_MKNID(
1845                         LNET_NID_NET(&ni->ni_nid),
1846                         ntohl(((struct sockaddr_in *)
1847                                &conn->ksnc_peeraddr)->sin_addr.s_addr));
1848         } else {
1849                 recv_id.nid = hello->kshm_src_nid;
1850                 recv_id.pid = hello->kshm_src_pid;
1851         }
1852
1853         if (!active) {
1854                 *peerid = recv_id;
1855
1856                 /* peer_ni determines type */
1857                 conn->ksnc_type = ksocknal_invert_type(hello->kshm_ctype);
1858                 if (conn->ksnc_type == SOCKLND_CONN_NONE) {
1859                         CERROR("Unexpected type %d from %s ip %pIS\n",
1860                                hello->kshm_ctype, libcfs_id2str(*peerid),
1861                                &conn->ksnc_peeraddr);
1862                         return -EPROTO;
1863                 }
1864                 return 0;
1865         }
1866
1867         if (peerid->pid != recv_id.pid ||
1868             peerid->nid != recv_id.nid) {
1869                 LCONSOLE_ERROR_MSG(0x130,
1870                                    "Connected successfully to %s on host %pIS, but they claimed they were %s; please check your Lustre configuration.\n",
1871                                    libcfs_id2str(*peerid),
1872                                    &conn->ksnc_peeraddr,
1873                                    libcfs_id2str(recv_id));
1874                 return -EPROTO;
1875         }
1876
1877         if (hello->kshm_ctype == SOCKLND_CONN_NONE) {
1878                 /* Possible protocol mismatch or I lost the connection race */
1879                 return proto_match ? EALREADY : EPROTO;
1880         }
1881
1882         if (ksocknal_invert_type(hello->kshm_ctype) != conn->ksnc_type) {
1883                 CERROR("Mismatched types: me %d, %s ip %pIS %d\n",
1884                        conn->ksnc_type, libcfs_id2str(*peerid),
1885                        &conn->ksnc_peeraddr,
1886                        hello->kshm_ctype);
1887                 return -EPROTO;
1888         }
1889         return 0;
1890 }
1891
1892 static bool
1893 ksocknal_connect(struct ksock_conn_cb *conn_cb)
1894 {
1895         LIST_HEAD(zombies);
1896         struct ksock_peer_ni *peer_ni = conn_cb->ksnr_peer;
1897         int type;
1898         int wanted;
1899         struct socket *sock;
1900         time64_t deadline;
1901         bool retry_later = false;
1902         int rc = 0;
1903
1904         deadline = ktime_get_seconds() + ksocknal_timeout();
1905
1906         write_lock_bh(&ksocknal_data.ksnd_global_lock);
1907
1908         LASSERT(conn_cb->ksnr_scheduled);
1909         LASSERT(!conn_cb->ksnr_connecting);
1910
1911         conn_cb->ksnr_connecting = 1;
1912
1913         for (;;) {
1914                 wanted = ksocknal_conn_cb_mask() & ~conn_cb->ksnr_connected;
1915
1916                 /* stop connecting if peer_ni/cb got closed under me, or
1917                  * conn cb got connected while queued
1918                  */
1919                 if (peer_ni->ksnp_closing || conn_cb->ksnr_deleted ||
1920                     wanted == 0) {
1921                         retry_later = false;
1922                         break;
1923                 }
1924
1925                 /* reschedule if peer_ni is connecting to me */
1926                 if (peer_ni->ksnp_accepting > 0) {
1927                         CDEBUG(D_NET,
1928                                "peer_ni %s(%d) already connecting to me, retry later.\n",
1929                                libcfs_nidstr(&peer_ni->ksnp_id.nid),
1930                                peer_ni->ksnp_accepting);
1931                         retry_later = true;
1932                 }
1933
1934                 if (retry_later) /* needs reschedule */
1935                         break;
1936
1937                 if ((wanted & BIT(SOCKLND_CONN_ANY)) != 0) {
1938                         type = SOCKLND_CONN_ANY;
1939                 } else if ((wanted & BIT(SOCKLND_CONN_CONTROL)) != 0) {
1940                         type = SOCKLND_CONN_CONTROL;
1941                 } else if ((wanted & BIT(SOCKLND_CONN_BULK_IN)) != 0 &&
1942                            conn_cb->ksnr_blki_conn_count <= conn_cb->ksnr_blko_conn_count) {
1943                         type = SOCKLND_CONN_BULK_IN;
1944                 } else {
1945                         LASSERT ((wanted & BIT(SOCKLND_CONN_BULK_OUT)) != 0);
1946                         type = SOCKLND_CONN_BULK_OUT;
1947                 }
1948
1949                 write_unlock_bh(&ksocknal_data.ksnd_global_lock);
1950
1951                 if (ktime_get_seconds() >= deadline) {
1952                         rc = -ETIMEDOUT;
1953                         lnet_connect_console_error(
1954                                 rc, &peer_ni->ksnp_id.nid,
1955                                 (struct sockaddr *)&conn_cb->ksnr_addr);
1956                         goto failed;
1957                 }
1958
1959                 sock = lnet_connect(&peer_ni->ksnp_id.nid,
1960                                     conn_cb->ksnr_myiface,
1961                                     (struct sockaddr *)&conn_cb->ksnr_addr,
1962                                     peer_ni->ksnp_ni->ni_net_ns);
1963                 if (IS_ERR(sock)) {
1964                         rc = PTR_ERR(sock);
1965                         goto failed;
1966                 }
1967
1968                 rc = ksocknal_create_conn(peer_ni->ksnp_ni, conn_cb, sock,
1969                                           type);
1970                 if (rc < 0) {
1971                         lnet_connect_console_error(
1972                                 rc, &peer_ni->ksnp_id.nid,
1973                                 (struct sockaddr *)&conn_cb->ksnr_addr);
1974                         goto failed;
1975                 }
1976
1977                 /* A +ve RC means I have to retry because I lost the connection
1978                  * race or I have to renegotiate protocol version
1979                  */
1980                 retry_later = (rc != 0);
1981                 if (retry_later)
1982                         CDEBUG(D_NET, "peer_ni %s: conn race, retry later.\n",
1983                                libcfs_nidstr(&peer_ni->ksnp_id.nid));
1984
1985                 write_lock_bh(&ksocknal_data.ksnd_global_lock);
1986         }
1987
1988         conn_cb->ksnr_scheduled = 0;
1989         conn_cb->ksnr_connecting = 0;
1990
1991         if (retry_later) {
1992                 /* re-queue for attention; this frees me up to handle
1993                  * the peer_ni's incoming connection request
1994                  */
1995
1996                 if (rc == EALREADY ||
1997                     (rc == 0 && peer_ni->ksnp_accepting > 0)) {
1998                         /* We want to introduce a delay before next
1999                          * attempt to connect if we lost conn race, but
2000                          * the race is resolved quickly usually, so
2001                          * min_reconnectms should be good heuristic
2002                          */
2003                         conn_cb->ksnr_retry_interval =
2004                                 *ksocknal_tunables.ksnd_min_reconnectms / 1000;
2005                         conn_cb->ksnr_timeout = ktime_get_seconds() +
2006                                                 conn_cb->ksnr_retry_interval;
2007                 }
2008
2009                 ksocknal_launch_connection_locked(conn_cb);
2010         }
2011
2012         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
2013         return retry_later;
2014
2015  failed:
2016         write_lock_bh(&ksocknal_data.ksnd_global_lock);
2017
2018         conn_cb->ksnr_scheduled = 0;
2019         conn_cb->ksnr_connecting = 0;
2020
2021         /* This is a retry rather than a new connection */
2022         conn_cb->ksnr_retry_interval *= 2;
2023         conn_cb->ksnr_retry_interval =
2024                 max_t(time64_t, conn_cb->ksnr_retry_interval,
2025                       *ksocknal_tunables.ksnd_min_reconnectms / 1000);
2026         conn_cb->ksnr_retry_interval =
2027                 min_t(time64_t, conn_cb->ksnr_retry_interval,
2028                       *ksocknal_tunables.ksnd_max_reconnectms / 1000);
2029
2030         LASSERT(conn_cb->ksnr_retry_interval);
2031         conn_cb->ksnr_timeout = ktime_get_seconds() +
2032                                 conn_cb->ksnr_retry_interval;
2033
2034         if (!list_empty(&peer_ni->ksnp_tx_queue) &&
2035             peer_ni->ksnp_accepting == 0 &&
2036             !ksocknal_find_connecting_conn_cb_locked(peer_ni)) {
2037                 struct ksock_conn *conn;
2038
2039                 /* ksnp_tx_queue is queued on a conn on successful
2040                  * connection for V1.x and V2.x
2041                  */
2042                 conn = list_first_entry_or_null(&peer_ni->ksnp_conns,
2043                                                 struct ksock_conn, ksnc_list);
2044                 if (conn)
2045                         LASSERT(conn->ksnc_proto == &ksocknal_protocol_v3x);
2046
2047                 /* take all the blocked packets while I've got the lock and
2048                  * complete below...
2049                  */
2050                 list_splice_init(&peer_ni->ksnp_tx_queue, &zombies);
2051         }
2052
2053         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
2054
2055         ksocknal_peer_failed(peer_ni);
2056         ksocknal_txlist_done(peer_ni->ksnp_ni, &zombies, rc);
2057         return 0;
2058 }
2059
2060 /*
2061  * check whether we need to create more connds.
2062  * It will try to create new thread if it's necessary, @timeout can
2063  * be updated if failed to create, so caller wouldn't keep try while
2064  * running out of resource.
2065  */
2066 static int
2067 ksocknal_connd_check_start(time64_t sec, long *timeout)
2068 {
2069         int rc;
2070         int total = ksocknal_data.ksnd_connd_starting +
2071                     ksocknal_data.ksnd_connd_running;
2072
2073         if (unlikely(ksocknal_data.ksnd_init < SOCKNAL_INIT_ALL)) {
2074                 /* still in initializing */
2075                 return 0;
2076         }
2077
2078         if (total >= *ksocknal_tunables.ksnd_nconnds_max ||
2079             total > ksocknal_data.ksnd_connd_connecting + SOCKNAL_CONND_RESV) {
2080                 /* can't create more connd, or still have enough
2081                  * threads to handle more connecting */
2082                 return 0;
2083         }
2084
2085         if (list_empty(&ksocknal_data.ksnd_connd_routes)) {
2086                 /* no pending connecting request */
2087                 return 0;
2088         }
2089
2090         if (sec - ksocknal_data.ksnd_connd_failed_stamp <= 1) {
2091                 /* may run out of resource, retry later */
2092                 *timeout = cfs_time_seconds(1);
2093                 return 0;
2094         }
2095
2096         if (ksocknal_data.ksnd_connd_starting > 0) {
2097                 /* serialize starting to avoid flood */
2098                 return 0;
2099         }
2100
2101         ksocknal_data.ksnd_connd_starting_stamp = sec;
2102         ksocknal_data.ksnd_connd_starting++;
2103         spin_unlock_bh(&ksocknal_data.ksnd_connd_lock);
2104
2105         /* NB: total is the next id */
2106         rc = ksocknal_thread_start(ksocknal_connd, NULL,
2107                                    "socknal_cd%02d", total);
2108
2109         spin_lock_bh(&ksocknal_data.ksnd_connd_lock);
2110         if (rc == 0)
2111                 return 1;
2112
2113         /* we tried ... */
2114         LASSERT(ksocknal_data.ksnd_connd_starting > 0);
2115         ksocknal_data.ksnd_connd_starting--;
2116         ksocknal_data.ksnd_connd_failed_stamp = ktime_get_real_seconds();
2117
2118         return 1;
2119 }
2120
2121 /*
2122  * check whether current thread can exit, it will return 1 if there are too
2123  * many threads and no creating in past 120 seconds.
2124  * Also, this function may update @timeout to make caller come back
2125  * again to recheck these conditions.
2126  */
2127 static int
2128 ksocknal_connd_check_stop(time64_t sec, long *timeout)
2129 {
2130         int val;
2131
2132         if (unlikely(ksocknal_data.ksnd_init < SOCKNAL_INIT_ALL)) {
2133                 /* still in initializing */
2134                 return 0;
2135         }
2136
2137         if (ksocknal_data.ksnd_connd_starting > 0) {
2138                 /* in progress of starting new thread */
2139                 return 0;
2140         }
2141
2142         if (ksocknal_data.ksnd_connd_running <=
2143             *ksocknal_tunables.ksnd_nconnds) { /* can't shrink */
2144                 return 0;
2145         }
2146
2147         /* created thread in past 120 seconds? */
2148         val = (int)(ksocknal_data.ksnd_connd_starting_stamp +
2149                     SOCKNAL_CONND_TIMEOUT - sec);
2150
2151         *timeout = (val > 0) ? cfs_time_seconds(val) :
2152                                cfs_time_seconds(SOCKNAL_CONND_TIMEOUT);
2153         if (val > 0)
2154                 return 0;
2155
2156         /* no creating in past 120 seconds */
2157
2158         return ksocknal_data.ksnd_connd_running >
2159                ksocknal_data.ksnd_connd_connecting + SOCKNAL_CONND_RESV;
2160 }
2161
2162 /* Go through connd_cbs queue looking for a conn_cb that we can process
2163  * right now, @timeout_p can be updated if we need to come back later */
2164 static struct ksock_conn_cb *
2165 ksocknal_connd_get_conn_cb_locked(signed long *timeout_p)
2166 {
2167         time64_t now = ktime_get_seconds();
2168         time64_t conn_timeout;
2169         struct ksock_conn_cb *conn_cb;
2170
2171         /* connd_routes can contain both pending and ordinary routes */
2172         list_for_each_entry(conn_cb, &ksocknal_data.ksnd_connd_routes,
2173                             ksnr_connd_list) {
2174
2175                 conn_timeout = conn_cb->ksnr_timeout;
2176
2177                 if (conn_cb->ksnr_retry_interval == 0 ||
2178                     now >= conn_timeout)
2179                         return conn_cb;
2180
2181                 if (*timeout_p == MAX_SCHEDULE_TIMEOUT ||
2182                     *timeout_p > cfs_time_seconds(conn_timeout - now))
2183                         *timeout_p = cfs_time_seconds(conn_timeout - now);
2184         }
2185
2186         return NULL;
2187 }
2188
2189 int
2190 ksocknal_connd(void *arg)
2191 {
2192         spinlock_t *connd_lock = &ksocknal_data.ksnd_connd_lock;
2193         struct ksock_connreq *cr;
2194         wait_queue_entry_t wait;
2195         int cons_retry = 0;
2196
2197         init_wait(&wait);
2198
2199         spin_lock_bh(connd_lock);
2200
2201         LASSERT(ksocknal_data.ksnd_connd_starting > 0);
2202         ksocknal_data.ksnd_connd_starting--;
2203         ksocknal_data.ksnd_connd_running++;
2204
2205         while (!ksocknal_data.ksnd_shuttingdown) {
2206                 struct ksock_conn_cb *conn_cb = NULL;
2207                 time64_t sec = ktime_get_real_seconds();
2208                 long timeout = MAX_SCHEDULE_TIMEOUT;
2209                 bool dropped_lock = false;
2210
2211                 if (ksocknal_connd_check_stop(sec, &timeout)) {
2212                         /* wakeup another one to check stop */
2213                         wake_up(&ksocknal_data.ksnd_connd_waitq);
2214                         break;
2215                 }
2216
2217                 if (ksocknal_connd_check_start(sec, &timeout)) {
2218                         /* created new thread */
2219                         dropped_lock = true;
2220                 }
2221
2222                 cr = list_first_entry_or_null(&ksocknal_data.ksnd_connd_connreqs,
2223                                               struct ksock_connreq, ksncr_list);
2224                 if (cr) {
2225                         /* Connection accepted by the listener */
2226                         list_del(&cr->ksncr_list);
2227                         spin_unlock_bh(connd_lock);
2228                         dropped_lock = true;
2229
2230                         ksocknal_create_conn(cr->ksncr_ni, NULL,
2231                                              cr->ksncr_sock, SOCKLND_CONN_NONE);
2232                         lnet_ni_decref(cr->ksncr_ni);
2233                         LIBCFS_FREE(cr, sizeof(*cr));
2234
2235                         spin_lock_bh(connd_lock);
2236                 }
2237
2238                 /* Only handle an outgoing connection request if there
2239                  * is a thread left to handle incoming connections and
2240                  * create new connd
2241                  */
2242                 if (ksocknal_data.ksnd_connd_connecting + SOCKNAL_CONND_RESV <
2243                     ksocknal_data.ksnd_connd_running)
2244                         conn_cb = ksocknal_connd_get_conn_cb_locked(&timeout);
2245
2246                 if (conn_cb) {
2247                         list_del(&conn_cb->ksnr_connd_list);
2248                         ksocknal_data.ksnd_connd_connecting++;
2249                         spin_unlock_bh(connd_lock);
2250                         dropped_lock = true;
2251
2252                         if (ksocknal_connect(conn_cb)) {
2253                                 /* consecutive retry */
2254                                 if (cons_retry++ > SOCKNAL_INSANITY_RECONN) {
2255                                         CWARN("massive consecutive re-connecting to %pIS\n",
2256                                               &conn_cb->ksnr_addr);
2257                                         cons_retry = 0;
2258                                 }
2259                         } else {
2260                                 cons_retry = 0;
2261                         }
2262
2263                         ksocknal_conn_cb_decref(conn_cb);
2264
2265                         spin_lock_bh(connd_lock);
2266                         ksocknal_data.ksnd_connd_connecting--;
2267                 }
2268
2269                 if (dropped_lock) {
2270                         if (!need_resched())
2271                                 continue;
2272                         spin_unlock_bh(connd_lock);
2273                         cond_resched();
2274                         spin_lock_bh(connd_lock);
2275                         continue;
2276                 }
2277
2278                 /* Nothing to do for 'timeout'  */
2279                 set_current_state(TASK_INTERRUPTIBLE);
2280                 add_wait_queue_exclusive(&ksocknal_data.ksnd_connd_waitq,
2281                                          &wait);
2282                 spin_unlock_bh(connd_lock);
2283
2284                 schedule_timeout(timeout);
2285
2286                 remove_wait_queue(&ksocknal_data.ksnd_connd_waitq, &wait);
2287                 spin_lock_bh(connd_lock);
2288         }
2289         ksocknal_data.ksnd_connd_running--;
2290         spin_unlock_bh(connd_lock);
2291
2292         ksocknal_thread_fini();
2293         return 0;
2294 }
2295
2296 static struct ksock_conn *
2297 ksocknal_find_timed_out_conn(struct ksock_peer_ni *peer_ni)
2298 {
2299         /* We're called with a shared lock on ksnd_global_lock */
2300         struct ksock_conn *conn;
2301         struct ksock_tx *tx;
2302         struct ksock_sched *sched;
2303
2304         list_for_each_entry(conn, &peer_ni->ksnp_conns, ksnc_list) {
2305                 int error;
2306
2307                 /* Don't need the {get,put}connsock dance to deref ksnc_sock */
2308                 LASSERT (!conn->ksnc_closing);
2309                 sched = conn->ksnc_scheduler;
2310
2311                 error = conn->ksnc_sock->sk->sk_err;
2312                 if (error != 0) {
2313                         ksocknal_conn_addref(conn);
2314
2315                         switch (error) {
2316                         case ECONNRESET:
2317                                 CNETERR("A connection with %s (%pISp) was reset; it may have rebooted.\n",
2318                                         libcfs_idstr(&peer_ni->ksnp_id),
2319                                         &conn->ksnc_peeraddr);
2320                                 break;
2321                         case ETIMEDOUT:
2322                                 CNETERR("A connection with %s (%pISp) timed out; the network or node may be down.\n",
2323                                         libcfs_idstr(&peer_ni->ksnp_id),
2324                                         &conn->ksnc_peeraddr);
2325                                 break;
2326                         default:
2327                                 CNETERR("An unexpected network error %d occurred with %s (%pISp\n",
2328                                         error,
2329                                         libcfs_idstr(&peer_ni->ksnp_id),
2330                                         &conn->ksnc_peeraddr);
2331                                 break;
2332                         }
2333
2334                         return conn;
2335                 }
2336
2337                 if (conn->ksnc_rx_started &&
2338                     ktime_get_seconds() >= conn->ksnc_rx_deadline) {
2339                         /* Timed out incomplete incoming message */
2340                         ksocknal_conn_addref(conn);
2341                         CNETERR("Timeout receiving from %s (%pISp), state %d wanted %d left %d\n",
2342                                 libcfs_idstr(&peer_ni->ksnp_id),
2343                                 &conn->ksnc_peeraddr,
2344                                 conn->ksnc_rx_state,
2345                                 conn->ksnc_rx_nob_wanted,
2346                                 conn->ksnc_rx_nob_left);
2347                         return conn;
2348                 }
2349
2350                 spin_lock_bh(&sched->kss_lock);
2351                 if ((!list_empty(&conn->ksnc_tx_queue) ||
2352                      conn->ksnc_sock->sk->sk_wmem_queued != 0) &&
2353                     ktime_get_seconds() >= conn->ksnc_tx_deadline) {
2354                         /* Timed out messages queued for sending or
2355                          * buffered in the socket's send buffer
2356                          */
2357                         ksocknal_conn_addref(conn);
2358                         list_for_each_entry(tx, &conn->ksnc_tx_queue,
2359                                             tx_list)
2360                                 tx->tx_hstatus =
2361                                         LNET_MSG_STATUS_LOCAL_TIMEOUT;
2362                         CNETERR("Timeout sending data to %s (%pISp) the network or that node may be down.\n",
2363                                 libcfs_idstr(&peer_ni->ksnp_id),
2364                                 &conn->ksnc_peeraddr);
2365                                 spin_unlock_bh(&sched->kss_lock);
2366                                 return conn;
2367                 }
2368                 spin_unlock_bh(&sched->kss_lock);
2369         }
2370
2371         return (NULL);
2372 }
2373
2374 static inline void
2375 ksocknal_flush_stale_txs(struct ksock_peer_ni *peer_ni)
2376 {
2377         struct ksock_tx *tx;
2378         LIST_HEAD(stale_txs);
2379
2380         write_lock_bh(&ksocknal_data.ksnd_global_lock);
2381
2382         while ((tx = list_first_entry_or_null(&peer_ni->ksnp_tx_queue,
2383                                               struct ksock_tx,
2384                                               tx_list)) != NULL) {
2385                 if (ktime_get_seconds() < tx->tx_deadline)
2386                         break;
2387
2388                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_TIMEOUT;
2389
2390                 list_move_tail(&tx->tx_list, &stale_txs);
2391         }
2392
2393         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
2394
2395         ksocknal_txlist_done(peer_ni->ksnp_ni, &stale_txs, -ETIMEDOUT);
2396 }
2397
2398 static int
2399 ksocknal_send_keepalive_locked(struct ksock_peer_ni *peer_ni)
2400 __must_hold(&ksocknal_data.ksnd_global_lock)
2401 {
2402         struct ksock_sched *sched;
2403         struct ksock_conn *conn;
2404         struct ksock_tx *tx;
2405
2406         /* last_alive will be updated by create_conn */
2407         if (list_empty(&peer_ni->ksnp_conns))
2408                 return 0;
2409
2410         if (peer_ni->ksnp_proto != &ksocknal_protocol_v3x)
2411                 return 0;
2412
2413         if (*ksocknal_tunables.ksnd_keepalive <= 0 ||
2414             ktime_get_seconds() < peer_ni->ksnp_last_alive +
2415                                   *ksocknal_tunables.ksnd_keepalive)
2416                 return 0;
2417
2418         if (ktime_get_seconds() < peer_ni->ksnp_send_keepalive)
2419                 return 0;
2420
2421         /* retry 10 secs later, so we wouldn't put pressure
2422          * on this peer_ni if we failed to send keepalive this time */
2423         peer_ni->ksnp_send_keepalive = ktime_get_seconds() + 10;
2424
2425         conn = ksocknal_find_conn_locked(peer_ni, NULL, 1);
2426         if (conn != NULL) {
2427                 sched = conn->ksnc_scheduler;
2428
2429                 spin_lock_bh(&sched->kss_lock);
2430                 if (!list_empty(&conn->ksnc_tx_queue)) {
2431                         spin_unlock_bh(&sched->kss_lock);
2432                         /* there is an queued ACK, don't need keepalive */
2433                         return 0;
2434                 }
2435
2436                 spin_unlock_bh(&sched->kss_lock);
2437         }
2438
2439         read_unlock(&ksocknal_data.ksnd_global_lock);
2440
2441         /* cookie = 1 is reserved for keepalive PING */
2442         tx = ksocknal_alloc_tx_noop(1, 1);
2443         if (tx == NULL) {
2444                 read_lock(&ksocknal_data.ksnd_global_lock);
2445                 return -ENOMEM;
2446         }
2447
2448         if (ksocknal_launch_packet(peer_ni->ksnp_ni, tx, &peer_ni->ksnp_id)
2449             == 0) {
2450                 read_lock(&ksocknal_data.ksnd_global_lock);
2451                 return 1;
2452         }
2453
2454         ksocknal_free_tx(tx);
2455         read_lock(&ksocknal_data.ksnd_global_lock);
2456
2457         return -EIO;
2458 }
2459
2460
2461 static void
2462 ksocknal_check_peer_timeouts(int idx)
2463 {
2464         struct hlist_head *peers = &ksocknal_data.ksnd_peers[idx];
2465         struct ksock_peer_ni *peer_ni;
2466         struct ksock_conn *conn;
2467         struct ksock_tx *tx;
2468
2469  again:
2470         /* NB. We expect to have a look at all the peers and not find any
2471          * connections to time out, so we just use a shared lock while we
2472          * take a look...
2473          */
2474         read_lock(&ksocknal_data.ksnd_global_lock);
2475
2476         hlist_for_each_entry(peer_ni, peers, ksnp_list) {
2477                 struct ksock_tx *tx_stale;
2478                 time64_t deadline = 0;
2479                 int resid = 0;
2480                 int n = 0;
2481
2482                 if (ksocknal_send_keepalive_locked(peer_ni) != 0) {
2483                         read_unlock(&ksocknal_data.ksnd_global_lock);
2484                         goto again;
2485                 }
2486
2487                 conn = ksocknal_find_timed_out_conn(peer_ni);
2488
2489                 if (conn != NULL) {
2490                         read_unlock(&ksocknal_data.ksnd_global_lock);
2491
2492                         ksocknal_close_conn_and_siblings(conn, -ETIMEDOUT);
2493
2494                         /* NB we won't find this one again, but we can't
2495                          * just proceed with the next peer_ni, since we dropped
2496                          * ksnd_global_lock and it might be dead already!
2497                          */
2498                         ksocknal_conn_decref(conn);
2499                         goto again;
2500                 }
2501
2502                 /* we can't process stale txs right here because we're
2503                  * holding only shared lock
2504                  */
2505                 tx = list_first_entry_or_null(&peer_ni->ksnp_tx_queue,
2506                                               struct ksock_tx, tx_list);
2507                 if (tx && ktime_get_seconds() >= tx->tx_deadline) {
2508                         ksocknal_peer_addref(peer_ni);
2509                         read_unlock(&ksocknal_data.ksnd_global_lock);
2510
2511                         ksocknal_flush_stale_txs(peer_ni);
2512
2513                         ksocknal_peer_decref(peer_ni);
2514                         goto again;
2515                 }
2516
2517                 if (list_empty(&peer_ni->ksnp_zc_req_list))
2518                         continue;
2519
2520                 tx_stale = NULL;
2521                 spin_lock(&peer_ni->ksnp_lock);
2522                 list_for_each_entry(tx, &peer_ni->ksnp_zc_req_list, tx_zc_list) {
2523                         if (ktime_get_seconds() < tx->tx_deadline)
2524                                 break;
2525                         /* ignore the TX if connection is being closed */
2526                         if (tx->tx_conn->ksnc_closing)
2527                                 continue;
2528                         n++;
2529                         if (tx_stale == NULL)
2530                                 tx_stale = tx;
2531                 }
2532
2533                 if (tx_stale == NULL) {
2534                         spin_unlock(&peer_ni->ksnp_lock);
2535                         continue;
2536                 }
2537
2538                 deadline = tx_stale->tx_deadline;
2539                 resid    = tx_stale->tx_resid;
2540                 conn     = tx_stale->tx_conn;
2541                 ksocknal_conn_addref(conn);
2542
2543                 spin_unlock(&peer_ni->ksnp_lock);
2544                 read_unlock(&ksocknal_data.ksnd_global_lock);
2545
2546                 CERROR("Total %d stale ZC_REQs for peer_ni %s detected; the "
2547                        "oldest(%p) timed out %lld secs ago, "
2548                        "resid: %d, wmem: %d\n",
2549                        n, libcfs_nidstr(&peer_ni->ksnp_id.nid), tx_stale,
2550                        ktime_get_seconds() - deadline,
2551                        resid, conn->ksnc_sock->sk->sk_wmem_queued);
2552
2553                 ksocknal_close_conn_and_siblings (conn, -ETIMEDOUT);
2554                 ksocknal_conn_decref(conn);
2555                 goto again;
2556         }
2557
2558         read_unlock(&ksocknal_data.ksnd_global_lock);
2559 }
2560
2561 int ksocknal_reaper(void *arg)
2562 {
2563         wait_queue_entry_t wait;
2564         struct ksock_conn *conn;
2565         struct ksock_sched *sched;
2566         LIST_HEAD(enomem_conns);
2567         int nenomem_conns;
2568         time64_t timeout;
2569         int i;
2570         int peer_index = 0;
2571         time64_t deadline = ktime_get_seconds();
2572
2573         init_wait(&wait);
2574
2575         spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
2576
2577         while (!ksocknal_data.ksnd_shuttingdown) {
2578                 conn = list_first_entry_or_null(&ksocknal_data.ksnd_deathrow_conns,
2579                                                 struct ksock_conn, ksnc_list);
2580                 if (conn) {
2581                         list_del(&conn->ksnc_list);
2582
2583                         spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
2584
2585                         ksocknal_terminate_conn(conn);
2586                         ksocknal_conn_decref(conn);
2587
2588                         spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
2589                         continue;
2590                 }
2591
2592                 conn = list_first_entry_or_null(&ksocknal_data.ksnd_zombie_conns,
2593                                                 struct ksock_conn, ksnc_list);
2594                 if (conn) {
2595                         list_del(&conn->ksnc_list);
2596
2597                         spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
2598
2599                         ksocknal_destroy_conn(conn);
2600
2601                         spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
2602                         continue;
2603                 }
2604
2605                 list_splice_init(&ksocknal_data.ksnd_enomem_conns,
2606                                  &enomem_conns);
2607
2608                 spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
2609
2610                 /* reschedule all the connections that stalled with ENOMEM... */
2611                 nenomem_conns = 0;
2612                 while ((conn = list_first_entry_or_null(&enomem_conns,
2613                                                         struct ksock_conn,
2614                                                         ksnc_tx_list)) != NULL) {
2615                         list_del(&conn->ksnc_tx_list);
2616
2617                         sched = conn->ksnc_scheduler;
2618
2619                         spin_lock_bh(&sched->kss_lock);
2620
2621                         LASSERT(conn->ksnc_tx_scheduled);
2622                         conn->ksnc_tx_ready = 1;
2623                         list_add_tail(&conn->ksnc_tx_list,
2624                                           &sched->kss_tx_conns);
2625                         wake_up(&sched->kss_waitq);
2626
2627                         spin_unlock_bh(&sched->kss_lock);
2628                         nenomem_conns++;
2629                 }
2630
2631                 /* careful with the jiffy wrap... */
2632                 while ((timeout = deadline - ktime_get_seconds()) <= 0) {
2633                         const int n = 4;
2634                         const int p = 1;
2635                         int  chunk = HASH_SIZE(ksocknal_data.ksnd_peers);
2636                         unsigned int lnd_timeout;
2637
2638                         /* Time to check for timeouts on a few more peers: I
2639                          * do checks every 'p' seconds on a proportion of the
2640                          * peer_ni table and I need to check every connection
2641                          * 'n' times within a timeout interval, to ensure I
2642                          * detect a timeout on any connection within (n+1)/n
2643                          * times the timeout interval.
2644                          */
2645
2646                         lnd_timeout = ksocknal_timeout();
2647                         if (lnd_timeout > n * p)
2648                                 chunk = (chunk * n * p) / lnd_timeout;
2649                         if (chunk == 0)
2650                                 chunk = 1;
2651
2652                         for (i = 0; i < chunk; i++) {
2653                                 ksocknal_check_peer_timeouts(peer_index);
2654                                 peer_index = (peer_index + 1) %
2655                                         HASH_SIZE(ksocknal_data.ksnd_peers);
2656                         }
2657
2658                         deadline += p;
2659                 }
2660
2661                 if (nenomem_conns != 0) {
2662                         /* Reduce my timeout if I rescheduled ENOMEM conns.
2663                          * This also prevents me getting woken immediately
2664                          * if any go back on my enomem list. */
2665                         timeout = SOCKNAL_ENOMEM_RETRY;
2666                 }
2667                 ksocknal_data.ksnd_reaper_waketime = ktime_get_seconds() +
2668                                                      timeout;
2669
2670                 set_current_state(TASK_INTERRUPTIBLE);
2671                 add_wait_queue(&ksocknal_data.ksnd_reaper_waitq, &wait);
2672
2673                 if (!ksocknal_data.ksnd_shuttingdown &&
2674                     list_empty(&ksocknal_data.ksnd_deathrow_conns) &&
2675                     list_empty(&ksocknal_data.ksnd_zombie_conns))
2676                         schedule_timeout(cfs_time_seconds(timeout));
2677
2678                 set_current_state(TASK_RUNNING);
2679                 remove_wait_queue(&ksocknal_data.ksnd_reaper_waitq, &wait);
2680
2681                 spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
2682         }
2683
2684         spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
2685
2686         ksocknal_thread_fini();
2687         return 0;
2688 }