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