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