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