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