Whamcloud - gitweb
54fd6b69e5951c2e45e0c5c3699babc356ac3496
[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         = lnet_nid_to_nid4(&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,
1791                          * tell peer_ni my protocol.
1792                          */
1793                         conn->ksnc_proto = &ksocknal_protocol_v3x;
1794 #if SOCKNAL_VERSION_DEBUG
1795                         if (*ksocknal_tunables.ksnd_protocol == 2)
1796                                 conn->ksnc_proto = &ksocknal_protocol_v2x;
1797                         else if (*ksocknal_tunables.ksnd_protocol == 1)
1798                                 conn->ksnc_proto = &ksocknal_protocol_v1x;
1799 #endif
1800                         hello->kshm_nips = 0;
1801                         ksocknal_send_hello(ni, conn,
1802                                             lnet_nid_to_nid4(&ni->ni_nid),
1803                                             hello);
1804                 }
1805
1806                 CERROR("Unknown protocol version (%d.x expected) from %pIS\n",
1807                        conn->ksnc_proto->pro_version, &conn->ksnc_peeraddr);
1808
1809                 return -EPROTO;
1810         }
1811
1812         proto_match = (conn->ksnc_proto == proto);
1813         conn->ksnc_proto = proto;
1814
1815         /* receive the rest of hello message anyway */
1816         rc = conn->ksnc_proto->pro_recv_hello(conn, hello, timeout);
1817         if (rc != 0) {
1818                 CERROR("Error %d reading or checking hello from from %pIS\n",
1819                        rc, &conn->ksnc_peeraddr);
1820                 LASSERT(rc < 0);
1821                 return rc;
1822         }
1823
1824         *incarnation = hello->kshm_src_incarnation;
1825
1826         if (hello->kshm_src_nid == LNET_NID_ANY) {
1827                 CERROR("Expecting a HELLO hdr with a NID, but got LNET_NID_ANY from %pIS\n",
1828                        &conn->ksnc_peeraddr);
1829                 return -EPROTO;
1830         }
1831
1832         if (!active &&
1833             rpc_get_port((struct sockaddr *)&conn->ksnc_peeraddr) >
1834             LNET_ACCEPTOR_MAX_RESERVED_PORT) {
1835                 /* Userspace NAL assigns peer_ni process ID from socket */
1836                 recv_id.pid = rpc_get_port((struct sockaddr *)
1837                                            &conn->ksnc_peeraddr) |
1838                         LNET_PID_USERFLAG;
1839                 LASSERT(conn->ksnc_peeraddr.ss_family == AF_INET);
1840                 recv_id.nid = LNET_MKNID(
1841                         LNET_NID_NET(&ni->ni_nid),
1842                         ntohl(((struct sockaddr_in *)
1843                                &conn->ksnc_peeraddr)->sin_addr.s_addr));
1844         } else {
1845                 recv_id.nid = hello->kshm_src_nid;
1846                 recv_id.pid = hello->kshm_src_pid;
1847         }
1848
1849         if (!active) {
1850                 *peerid = recv_id;
1851
1852                 /* peer_ni determines type */
1853                 conn->ksnc_type = ksocknal_invert_type(hello->kshm_ctype);
1854                 if (conn->ksnc_type == SOCKLND_CONN_NONE) {
1855                         CERROR("Unexpected type %d from %s ip %pIS\n",
1856                                hello->kshm_ctype, libcfs_id2str(*peerid),
1857                                &conn->ksnc_peeraddr);
1858                         return -EPROTO;
1859                 }
1860                 return 0;
1861         }
1862
1863         if (peerid->pid != recv_id.pid ||
1864             peerid->nid != recv_id.nid) {
1865                 LCONSOLE_ERROR_MSG(0x130,
1866                                    "Connected successfully to %s on host %pIS, but they claimed they were %s; please check your Lustre configuration.\n",
1867                                    libcfs_id2str(*peerid),
1868                                    &conn->ksnc_peeraddr,
1869                                    libcfs_id2str(recv_id));
1870                 return -EPROTO;
1871         }
1872
1873         if (hello->kshm_ctype == SOCKLND_CONN_NONE) {
1874                 /* Possible protocol mismatch or I lost the connection race */
1875                 return proto_match ? EALREADY : EPROTO;
1876         }
1877
1878         if (ksocknal_invert_type(hello->kshm_ctype) != conn->ksnc_type) {
1879                 CERROR("Mismatched types: me %d, %s ip %pIS %d\n",
1880                        conn->ksnc_type, libcfs_id2str(*peerid),
1881                        &conn->ksnc_peeraddr,
1882                        hello->kshm_ctype);
1883                 return -EPROTO;
1884         }
1885         return 0;
1886 }
1887
1888 static bool
1889 ksocknal_connect(struct ksock_conn_cb *conn_cb)
1890 {
1891         LIST_HEAD(zombies);
1892         struct ksock_peer_ni *peer_ni = conn_cb->ksnr_peer;
1893         int type;
1894         int wanted;
1895         struct socket *sock;
1896         time64_t deadline;
1897         bool retry_later = false;
1898         int rc = 0;
1899
1900         deadline = ktime_get_seconds() + ksocknal_timeout();
1901
1902         write_lock_bh(&ksocknal_data.ksnd_global_lock);
1903
1904         LASSERT(conn_cb->ksnr_scheduled);
1905         LASSERT(!conn_cb->ksnr_connecting);
1906
1907         conn_cb->ksnr_connecting = 1;
1908
1909         for (;;) {
1910                 wanted = ksocknal_conn_cb_mask() & ~conn_cb->ksnr_connected;
1911
1912                 /* stop connecting if peer_ni/cb got closed under me, or
1913                  * conn cb got connected while queued
1914                  */
1915                 if (peer_ni->ksnp_closing || conn_cb->ksnr_deleted ||
1916                     wanted == 0) {
1917                         retry_later = false;
1918                         break;
1919                 }
1920
1921                 /* reschedule if peer_ni is connecting to me */
1922                 if (peer_ni->ksnp_accepting > 0) {
1923                         CDEBUG(D_NET,
1924                                "peer_ni %s(%d) already connecting to me, retry later.\n",
1925                                libcfs_nid2str(peer_ni->ksnp_id.nid), peer_ni->ksnp_accepting);
1926                         retry_later = true;
1927                 }
1928
1929                 if (retry_later) /* needs reschedule */
1930                         break;
1931
1932                 if ((wanted & BIT(SOCKLND_CONN_ANY)) != 0) {
1933                         type = SOCKLND_CONN_ANY;
1934                 } else if ((wanted & BIT(SOCKLND_CONN_CONTROL)) != 0) {
1935                         type = SOCKLND_CONN_CONTROL;
1936                 } else if ((wanted & BIT(SOCKLND_CONN_BULK_IN)) != 0 &&
1937                            conn_cb->ksnr_blki_conn_count <= conn_cb->ksnr_blko_conn_count) {
1938                         type = SOCKLND_CONN_BULK_IN;
1939                 } else {
1940                         LASSERT ((wanted & BIT(SOCKLND_CONN_BULK_OUT)) != 0);
1941                         type = SOCKLND_CONN_BULK_OUT;
1942                 }
1943
1944                 write_unlock_bh(&ksocknal_data.ksnd_global_lock);
1945
1946                 if (ktime_get_seconds() >= deadline) {
1947                         rc = -ETIMEDOUT;
1948                         lnet_connect_console_error(rc, peer_ni->ksnp_id.nid,
1949                                                    (struct sockaddr *)
1950                                                    &conn_cb->ksnr_addr);
1951                         goto failed;
1952                 }
1953
1954                 sock = lnet_connect(peer_ni->ksnp_id.nid,
1955                                     conn_cb->ksnr_myiface,
1956                                     (struct sockaddr *)&conn_cb->ksnr_addr,
1957                                     peer_ni->ksnp_ni->ni_net_ns);
1958                 if (IS_ERR(sock)) {
1959                         rc = PTR_ERR(sock);
1960                         goto failed;
1961                 }
1962
1963                 rc = ksocknal_create_conn(peer_ni->ksnp_ni, conn_cb, sock,
1964                                           type);
1965                 if (rc < 0) {
1966                         lnet_connect_console_error(rc, peer_ni->ksnp_id.nid,
1967                                                    (struct sockaddr *)
1968                                                    &conn_cb->ksnr_addr);
1969                         goto failed;
1970                 }
1971
1972                 /* A +ve RC means I have to retry because I lost the connection
1973                  * race or I have to renegotiate protocol version */
1974                 retry_later = (rc != 0);
1975                 if (retry_later)
1976                         CDEBUG(D_NET, "peer_ni %s: conn race, retry later.\n",
1977                                libcfs_nid2str(peer_ni->ksnp_id.nid));
1978
1979                 write_lock_bh(&ksocknal_data.ksnd_global_lock);
1980         }
1981
1982         conn_cb->ksnr_scheduled = 0;
1983         conn_cb->ksnr_connecting = 0;
1984
1985         if (retry_later) {
1986                 /* re-queue for attention; this frees me up to handle
1987                  * the peer_ni's incoming connection request
1988                  */
1989
1990                 if (rc == EALREADY ||
1991                     (rc == 0 && peer_ni->ksnp_accepting > 0)) {
1992                         /* We want to introduce a delay before next
1993                          * attempt to connect if we lost conn race, but
1994                          * the race is resolved quickly usually, so
1995                          * min_reconnectms should be good heuristic
1996                          */
1997                         conn_cb->ksnr_retry_interval =
1998                                 *ksocknal_tunables.ksnd_min_reconnectms / 1000;
1999                         conn_cb->ksnr_timeout = ktime_get_seconds() +
2000                                                 conn_cb->ksnr_retry_interval;
2001                 }
2002
2003                 ksocknal_launch_connection_locked(conn_cb);
2004         }
2005
2006         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
2007         return retry_later;
2008
2009  failed:
2010         write_lock_bh(&ksocknal_data.ksnd_global_lock);
2011
2012         conn_cb->ksnr_scheduled = 0;
2013         conn_cb->ksnr_connecting = 0;
2014
2015         /* This is a retry rather than a new connection */
2016         conn_cb->ksnr_retry_interval *= 2;
2017         conn_cb->ksnr_retry_interval =
2018                 max_t(time64_t, conn_cb->ksnr_retry_interval,
2019                       *ksocknal_tunables.ksnd_min_reconnectms / 1000);
2020         conn_cb->ksnr_retry_interval =
2021                 min_t(time64_t, conn_cb->ksnr_retry_interval,
2022                       *ksocknal_tunables.ksnd_max_reconnectms / 1000);
2023
2024         LASSERT(conn_cb->ksnr_retry_interval);
2025         conn_cb->ksnr_timeout = ktime_get_seconds() +
2026                                 conn_cb->ksnr_retry_interval;
2027
2028         if (!list_empty(&peer_ni->ksnp_tx_queue) &&
2029             peer_ni->ksnp_accepting == 0 &&
2030             !ksocknal_find_connecting_conn_cb_locked(peer_ni)) {
2031                 struct ksock_conn *conn;
2032
2033                 /* ksnp_tx_queue is queued on a conn on successful
2034                  * connection for V1.x and V2.x
2035                  */
2036                 conn = list_first_entry_or_null(&peer_ni->ksnp_conns,
2037                                                 struct ksock_conn, ksnc_list);
2038                 if (conn)
2039                         LASSERT(conn->ksnc_proto == &ksocknal_protocol_v3x);
2040
2041                 /* take all the blocked packets while I've got the lock and
2042                  * complete below...
2043                  */
2044                 list_splice_init(&peer_ni->ksnp_tx_queue, &zombies);
2045         }
2046
2047         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
2048
2049         ksocknal_peer_failed(peer_ni);
2050         ksocknal_txlist_done(peer_ni->ksnp_ni, &zombies, rc);
2051         return 0;
2052 }
2053
2054 /*
2055  * check whether we need to create more connds.
2056  * It will try to create new thread if it's necessary, @timeout can
2057  * be updated if failed to create, so caller wouldn't keep try while
2058  * running out of resource.
2059  */
2060 static int
2061 ksocknal_connd_check_start(time64_t sec, long *timeout)
2062 {
2063         int rc;
2064         int total = ksocknal_data.ksnd_connd_starting +
2065                     ksocknal_data.ksnd_connd_running;
2066
2067         if (unlikely(ksocknal_data.ksnd_init < SOCKNAL_INIT_ALL)) {
2068                 /* still in initializing */
2069                 return 0;
2070         }
2071
2072         if (total >= *ksocknal_tunables.ksnd_nconnds_max ||
2073             total > ksocknal_data.ksnd_connd_connecting + SOCKNAL_CONND_RESV) {
2074                 /* can't create more connd, or still have enough
2075                  * threads to handle more connecting */
2076                 return 0;
2077         }
2078
2079         if (list_empty(&ksocknal_data.ksnd_connd_routes)) {
2080                 /* no pending connecting request */
2081                 return 0;
2082         }
2083
2084         if (sec - ksocknal_data.ksnd_connd_failed_stamp <= 1) {
2085                 /* may run out of resource, retry later */
2086                 *timeout = cfs_time_seconds(1);
2087                 return 0;
2088         }
2089
2090         if (ksocknal_data.ksnd_connd_starting > 0) {
2091                 /* serialize starting to avoid flood */
2092                 return 0;
2093         }
2094
2095         ksocknal_data.ksnd_connd_starting_stamp = sec;
2096         ksocknal_data.ksnd_connd_starting++;
2097         spin_unlock_bh(&ksocknal_data.ksnd_connd_lock);
2098
2099         /* NB: total is the next id */
2100         rc = ksocknal_thread_start(ksocknal_connd, NULL,
2101                                    "socknal_cd%02d", total);
2102
2103         spin_lock_bh(&ksocknal_data.ksnd_connd_lock);
2104         if (rc == 0)
2105                 return 1;
2106
2107         /* we tried ... */
2108         LASSERT(ksocknal_data.ksnd_connd_starting > 0);
2109         ksocknal_data.ksnd_connd_starting--;
2110         ksocknal_data.ksnd_connd_failed_stamp = ktime_get_real_seconds();
2111
2112         return 1;
2113 }
2114
2115 /*
2116  * check whether current thread can exit, it will return 1 if there are too
2117  * many threads and no creating in past 120 seconds.
2118  * Also, this function may update @timeout to make caller come back
2119  * again to recheck these conditions.
2120  */
2121 static int
2122 ksocknal_connd_check_stop(time64_t sec, long *timeout)
2123 {
2124         int val;
2125
2126         if (unlikely(ksocknal_data.ksnd_init < SOCKNAL_INIT_ALL)) {
2127                 /* still in initializing */
2128                 return 0;
2129         }
2130
2131         if (ksocknal_data.ksnd_connd_starting > 0) {
2132                 /* in progress of starting new thread */
2133                 return 0;
2134         }
2135
2136         if (ksocknal_data.ksnd_connd_running <=
2137             *ksocknal_tunables.ksnd_nconnds) { /* can't shrink */
2138                 return 0;
2139         }
2140
2141         /* created thread in past 120 seconds? */
2142         val = (int)(ksocknal_data.ksnd_connd_starting_stamp +
2143                     SOCKNAL_CONND_TIMEOUT - sec);
2144
2145         *timeout = (val > 0) ? cfs_time_seconds(val) :
2146                                cfs_time_seconds(SOCKNAL_CONND_TIMEOUT);
2147         if (val > 0)
2148                 return 0;
2149
2150         /* no creating in past 120 seconds */
2151
2152         return ksocknal_data.ksnd_connd_running >
2153                ksocknal_data.ksnd_connd_connecting + SOCKNAL_CONND_RESV;
2154 }
2155
2156 /* Go through connd_cbs queue looking for a conn_cb that we can process
2157  * right now, @timeout_p can be updated if we need to come back later */
2158 static struct ksock_conn_cb *
2159 ksocknal_connd_get_conn_cb_locked(signed long *timeout_p)
2160 {
2161         time64_t now = ktime_get_seconds();
2162         time64_t conn_timeout;
2163         struct ksock_conn_cb *conn_cb;
2164
2165         /* connd_routes can contain both pending and ordinary routes */
2166         list_for_each_entry(conn_cb, &ksocknal_data.ksnd_connd_routes,
2167                             ksnr_connd_list) {
2168
2169                 conn_timeout = conn_cb->ksnr_timeout;
2170
2171                 if (conn_cb->ksnr_retry_interval == 0 ||
2172                     now >= conn_timeout)
2173                         return conn_cb;
2174
2175                 if (*timeout_p == MAX_SCHEDULE_TIMEOUT ||
2176                     *timeout_p > cfs_time_seconds(conn_timeout - now))
2177                         *timeout_p = cfs_time_seconds(conn_timeout - now);
2178         }
2179
2180         return NULL;
2181 }
2182
2183 int
2184 ksocknal_connd(void *arg)
2185 {
2186         spinlock_t *connd_lock = &ksocknal_data.ksnd_connd_lock;
2187         struct ksock_connreq *cr;
2188         wait_queue_entry_t wait;
2189         int cons_retry = 0;
2190
2191         init_wait(&wait);
2192
2193         spin_lock_bh(connd_lock);
2194
2195         LASSERT(ksocknal_data.ksnd_connd_starting > 0);
2196         ksocknal_data.ksnd_connd_starting--;
2197         ksocknal_data.ksnd_connd_running++;
2198
2199         while (!ksocknal_data.ksnd_shuttingdown) {
2200                 struct ksock_conn_cb *conn_cb = NULL;
2201                 time64_t sec = ktime_get_real_seconds();
2202                 long timeout = MAX_SCHEDULE_TIMEOUT;
2203                 bool dropped_lock = false;
2204
2205                 if (ksocknal_connd_check_stop(sec, &timeout)) {
2206                         /* wakeup another one to check stop */
2207                         wake_up(&ksocknal_data.ksnd_connd_waitq);
2208                         break;
2209                 }
2210
2211                 if (ksocknal_connd_check_start(sec, &timeout)) {
2212                         /* created new thread */
2213                         dropped_lock = true;
2214                 }
2215
2216                 cr = list_first_entry_or_null(&ksocknal_data.ksnd_connd_connreqs,
2217                                               struct ksock_connreq, ksncr_list);
2218                 if (cr) {
2219                         /* Connection accepted by the listener */
2220                         list_del(&cr->ksncr_list);
2221                         spin_unlock_bh(connd_lock);
2222                         dropped_lock = true;
2223
2224                         ksocknal_create_conn(cr->ksncr_ni, NULL,
2225                                              cr->ksncr_sock, SOCKLND_CONN_NONE);
2226                         lnet_ni_decref(cr->ksncr_ni);
2227                         LIBCFS_FREE(cr, sizeof(*cr));
2228
2229                         spin_lock_bh(connd_lock);
2230                 }
2231
2232                 /* Only handle an outgoing connection request if there
2233                  * is a thread left to handle incoming connections and
2234                  * create new connd
2235                  */
2236                 if (ksocknal_data.ksnd_connd_connecting + SOCKNAL_CONND_RESV <
2237                     ksocknal_data.ksnd_connd_running)
2238                         conn_cb = ksocknal_connd_get_conn_cb_locked(&timeout);
2239
2240                 if (conn_cb) {
2241                         list_del(&conn_cb->ksnr_connd_list);
2242                         ksocknal_data.ksnd_connd_connecting++;
2243                         spin_unlock_bh(connd_lock);
2244                         dropped_lock = true;
2245
2246                         if (ksocknal_connect(conn_cb)) {
2247                                 /* consecutive retry */
2248                                 if (cons_retry++ > SOCKNAL_INSANITY_RECONN) {
2249                                         CWARN("massive consecutive re-connecting to %pIS\n",
2250                                               &conn_cb->ksnr_addr);
2251                                         cons_retry = 0;
2252                                 }
2253                         } else {
2254                                 cons_retry = 0;
2255                         }
2256
2257                         ksocknal_conn_cb_decref(conn_cb);
2258
2259                         spin_lock_bh(connd_lock);
2260                         ksocknal_data.ksnd_connd_connecting--;
2261                 }
2262
2263                 if (dropped_lock) {
2264                         if (!need_resched())
2265                                 continue;
2266                         spin_unlock_bh(connd_lock);
2267                         cond_resched();
2268                         spin_lock_bh(connd_lock);
2269                         continue;
2270                 }
2271
2272                 /* Nothing to do for 'timeout'  */
2273                 set_current_state(TASK_INTERRUPTIBLE);
2274                 add_wait_queue_exclusive(&ksocknal_data.ksnd_connd_waitq,
2275                                          &wait);
2276                 spin_unlock_bh(connd_lock);
2277
2278                 schedule_timeout(timeout);
2279
2280                 remove_wait_queue(&ksocknal_data.ksnd_connd_waitq, &wait);
2281                 spin_lock_bh(connd_lock);
2282         }
2283         ksocknal_data.ksnd_connd_running--;
2284         spin_unlock_bh(connd_lock);
2285
2286         ksocknal_thread_fini();
2287         return 0;
2288 }
2289
2290 static struct ksock_conn *
2291 ksocknal_find_timed_out_conn(struct ksock_peer_ni *peer_ni)
2292 {
2293         /* We're called with a shared lock on ksnd_global_lock */
2294         struct ksock_conn *conn;
2295         struct ksock_tx *tx;
2296
2297         list_for_each_entry(conn, &peer_ni->ksnp_conns, ksnc_list) {
2298                 int error;
2299
2300                 /* Don't need the {get,put}connsock dance to deref ksnc_sock */
2301                 LASSERT (!conn->ksnc_closing);
2302
2303                 error = conn->ksnc_sock->sk->sk_err;
2304                 if (error != 0) {
2305                         ksocknal_conn_addref(conn);
2306
2307                         switch (error) {
2308                         case ECONNRESET:
2309                                 CNETERR("A connection with %s (%pISp) was reset; it may have rebooted.\n",
2310                                         libcfs_id2str(peer_ni->ksnp_id),
2311                                         &conn->ksnc_peeraddr);
2312                                 break;
2313                         case ETIMEDOUT:
2314                                 CNETERR("A connection with %s (%pISp) timed out; the network or node may be down.\n",
2315                                         libcfs_id2str(peer_ni->ksnp_id),
2316                                         &conn->ksnc_peeraddr);
2317                                 break;
2318                         default:
2319                                 CNETERR("An unexpected network error %d occurred with %s (%pISp\n",
2320                                         error,
2321                                         libcfs_id2str(peer_ni->ksnp_id),
2322                                         &conn->ksnc_peeraddr);
2323                                 break;
2324                         }
2325
2326                         return conn;
2327                 }
2328
2329                 if (conn->ksnc_rx_started &&
2330                     ktime_get_seconds() >= conn->ksnc_rx_deadline) {
2331                         /* Timed out incomplete incoming message */
2332                         ksocknal_conn_addref(conn);
2333                         CNETERR("Timeout receiving from %s (%pISp), state %d wanted %d left %d\n",
2334                                 libcfs_id2str(peer_ni->ksnp_id),
2335                                 &conn->ksnc_peeraddr,
2336                                 conn->ksnc_rx_state,
2337                                 conn->ksnc_rx_nob_wanted,
2338                                 conn->ksnc_rx_nob_left);
2339                         return conn;
2340                 }
2341
2342                 if ((!list_empty(&conn->ksnc_tx_queue) ||
2343                      conn->ksnc_sock->sk->sk_wmem_queued != 0) &&
2344                     ktime_get_seconds() >= conn->ksnc_tx_deadline) {
2345                         /* Timed out messages queued for sending or
2346                          * buffered in the socket's send buffer
2347                          */
2348                         ksocknal_conn_addref(conn);
2349                         list_for_each_entry(tx, &conn->ksnc_tx_queue,
2350                                             tx_list)
2351                                 tx->tx_hstatus =
2352                                         LNET_MSG_STATUS_LOCAL_TIMEOUT;
2353                         CNETERR("Timeout sending data to %s (%pISp) the network or that node may be down.\n",
2354                                 libcfs_id2str(peer_ni->ksnp_id),
2355                                 &conn->ksnc_peeraddr);
2356                                 return conn;
2357                 }
2358         }
2359
2360         return (NULL);
2361 }
2362
2363 static inline void
2364 ksocknal_flush_stale_txs(struct ksock_peer_ni *peer_ni)
2365 {
2366         struct ksock_tx *tx;
2367         LIST_HEAD(stale_txs);
2368
2369         write_lock_bh(&ksocknal_data.ksnd_global_lock);
2370
2371         while ((tx = list_first_entry_or_null(&peer_ni->ksnp_tx_queue,
2372                                               struct ksock_tx,
2373                                               tx_list)) != NULL) {
2374                 if (ktime_get_seconds() < tx->tx_deadline)
2375                         break;
2376
2377                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_TIMEOUT;
2378
2379                 list_move_tail(&tx->tx_list, &stale_txs);
2380         }
2381
2382         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
2383
2384         ksocknal_txlist_done(peer_ni->ksnp_ni, &stale_txs, -ETIMEDOUT);
2385 }
2386
2387 static int
2388 ksocknal_send_keepalive_locked(struct ksock_peer_ni *peer_ni)
2389 __must_hold(&ksocknal_data.ksnd_global_lock)
2390 {
2391         struct ksock_sched *sched;
2392         struct ksock_conn *conn;
2393         struct ksock_tx *tx;
2394
2395         /* last_alive will be updated by create_conn */
2396         if (list_empty(&peer_ni->ksnp_conns))
2397                 return 0;
2398
2399         if (peer_ni->ksnp_proto != &ksocknal_protocol_v3x)
2400                 return 0;
2401
2402         if (*ksocknal_tunables.ksnd_keepalive <= 0 ||
2403             ktime_get_seconds() < peer_ni->ksnp_last_alive +
2404                                   *ksocknal_tunables.ksnd_keepalive)
2405                 return 0;
2406
2407         if (ktime_get_seconds() < peer_ni->ksnp_send_keepalive)
2408                 return 0;
2409
2410         /* retry 10 secs later, so we wouldn't put pressure
2411          * on this peer_ni if we failed to send keepalive this time */
2412         peer_ni->ksnp_send_keepalive = ktime_get_seconds() + 10;
2413
2414         conn = ksocknal_find_conn_locked(peer_ni, NULL, 1);
2415         if (conn != NULL) {
2416                 sched = conn->ksnc_scheduler;
2417
2418                 spin_lock_bh(&sched->kss_lock);
2419                 if (!list_empty(&conn->ksnc_tx_queue)) {
2420                         spin_unlock_bh(&sched->kss_lock);
2421                         /* there is an queued ACK, don't need keepalive */
2422                         return 0;
2423                 }
2424
2425                 spin_unlock_bh(&sched->kss_lock);
2426         }
2427
2428         read_unlock(&ksocknal_data.ksnd_global_lock);
2429
2430         /* cookie = 1 is reserved for keepalive PING */
2431         tx = ksocknal_alloc_tx_noop(1, 1);
2432         if (tx == NULL) {
2433                 read_lock(&ksocknal_data.ksnd_global_lock);
2434                 return -ENOMEM;
2435         }
2436
2437         if (ksocknal_launch_packet(peer_ni->ksnp_ni, tx, peer_ni->ksnp_id) == 0) {
2438                 read_lock(&ksocknal_data.ksnd_global_lock);
2439                 return 1;
2440         }
2441
2442         ksocknal_free_tx(tx);
2443         read_lock(&ksocknal_data.ksnd_global_lock);
2444
2445         return -EIO;
2446 }
2447
2448
2449 static void
2450 ksocknal_check_peer_timeouts(int idx)
2451 {
2452         struct hlist_head *peers = &ksocknal_data.ksnd_peers[idx];
2453         struct ksock_peer_ni *peer_ni;
2454         struct ksock_conn *conn;
2455         struct ksock_tx *tx;
2456
2457  again:
2458         /* NB. We expect to have a look at all the peers and not find any
2459          * connections to time out, so we just use a shared lock while we
2460          * take a look...
2461          */
2462         read_lock(&ksocknal_data.ksnd_global_lock);
2463
2464         hlist_for_each_entry(peer_ni, peers, ksnp_list) {
2465                 struct ksock_tx *tx_stale;
2466                 time64_t deadline = 0;
2467                 int resid = 0;
2468                 int n = 0;
2469
2470                 if (ksocknal_send_keepalive_locked(peer_ni) != 0) {
2471                         read_unlock(&ksocknal_data.ksnd_global_lock);
2472                         goto again;
2473                 }
2474
2475                 conn = ksocknal_find_timed_out_conn(peer_ni);
2476
2477                 if (conn != NULL) {
2478                         read_unlock(&ksocknal_data.ksnd_global_lock);
2479
2480                         ksocknal_close_conn_and_siblings(conn, -ETIMEDOUT);
2481
2482                         /* NB we won't find this one again, but we can't
2483                          * just proceed with the next peer_ni, since we dropped
2484                          * ksnd_global_lock and it might be dead already!
2485                          */
2486                         ksocknal_conn_decref(conn);
2487                         goto again;
2488                 }
2489
2490                 /* we can't process stale txs right here because we're
2491                  * holding only shared lock
2492                  */
2493                 tx = list_first_entry_or_null(&peer_ni->ksnp_tx_queue,
2494                                               struct ksock_tx, tx_list);
2495                 if (tx && ktime_get_seconds() >= tx->tx_deadline) {
2496                         ksocknal_peer_addref(peer_ni);
2497                         read_unlock(&ksocknal_data.ksnd_global_lock);
2498
2499                         ksocknal_flush_stale_txs(peer_ni);
2500
2501                         ksocknal_peer_decref(peer_ni);
2502                         goto again;
2503                 }
2504
2505                 if (list_empty(&peer_ni->ksnp_zc_req_list))
2506                         continue;
2507
2508                 tx_stale = NULL;
2509                 spin_lock(&peer_ni->ksnp_lock);
2510                 list_for_each_entry(tx, &peer_ni->ksnp_zc_req_list, tx_zc_list) {
2511                         if (ktime_get_seconds() < tx->tx_deadline)
2512                                 break;
2513                         /* ignore the TX if connection is being closed */
2514                         if (tx->tx_conn->ksnc_closing)
2515                                 continue;
2516                         n++;
2517                         if (tx_stale == NULL)
2518                                 tx_stale = tx;
2519                 }
2520
2521                 if (tx_stale == NULL) {
2522                         spin_unlock(&peer_ni->ksnp_lock);
2523                         continue;
2524                 }
2525
2526                 deadline = tx_stale->tx_deadline;
2527                 resid    = tx_stale->tx_resid;
2528                 conn     = tx_stale->tx_conn;
2529                 ksocknal_conn_addref(conn);
2530
2531                 spin_unlock(&peer_ni->ksnp_lock);
2532                 read_unlock(&ksocknal_data.ksnd_global_lock);
2533
2534                 CERROR("Total %d stale ZC_REQs for peer_ni %s detected; the "
2535                        "oldest(%p) timed out %lld secs ago, "
2536                        "resid: %d, wmem: %d\n",
2537                        n, libcfs_nid2str(peer_ni->ksnp_id.nid), tx_stale,
2538                        ktime_get_seconds() - deadline,
2539                        resid, conn->ksnc_sock->sk->sk_wmem_queued);
2540
2541                 ksocknal_close_conn_and_siblings (conn, -ETIMEDOUT);
2542                 ksocknal_conn_decref(conn);
2543                 goto again;
2544         }
2545
2546         read_unlock(&ksocknal_data.ksnd_global_lock);
2547 }
2548
2549 int ksocknal_reaper(void *arg)
2550 {
2551         wait_queue_entry_t wait;
2552         struct ksock_conn *conn;
2553         struct ksock_sched *sched;
2554         LIST_HEAD(enomem_conns);
2555         int nenomem_conns;
2556         time64_t timeout;
2557         int i;
2558         int peer_index = 0;
2559         time64_t deadline = ktime_get_seconds();
2560
2561         init_wait(&wait);
2562
2563         spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
2564
2565         while (!ksocknal_data.ksnd_shuttingdown) {
2566                 conn = list_first_entry_or_null(&ksocknal_data.ksnd_deathrow_conns,
2567                                                 struct ksock_conn, ksnc_list);
2568                 if (conn) {
2569                         list_del(&conn->ksnc_list);
2570
2571                         spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
2572
2573                         ksocknal_terminate_conn(conn);
2574                         ksocknal_conn_decref(conn);
2575
2576                         spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
2577                         continue;
2578                 }
2579
2580                 conn = list_first_entry_or_null(&ksocknal_data.ksnd_zombie_conns,
2581                                                 struct ksock_conn, ksnc_list);
2582                 if (conn) {
2583                         list_del(&conn->ksnc_list);
2584
2585                         spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
2586
2587                         ksocknal_destroy_conn(conn);
2588
2589                         spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
2590                         continue;
2591                 }
2592
2593                 list_splice_init(&ksocknal_data.ksnd_enomem_conns,
2594                                  &enomem_conns);
2595
2596                 spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
2597
2598                 /* reschedule all the connections that stalled with ENOMEM... */
2599                 nenomem_conns = 0;
2600                 while ((conn = list_first_entry_or_null(&enomem_conns,
2601                                                         struct ksock_conn,
2602                                                         ksnc_tx_list)) != NULL) {
2603                         list_del(&conn->ksnc_tx_list);
2604
2605                         sched = conn->ksnc_scheduler;
2606
2607                         spin_lock_bh(&sched->kss_lock);
2608
2609                         LASSERT(conn->ksnc_tx_scheduled);
2610                         conn->ksnc_tx_ready = 1;
2611                         list_add_tail(&conn->ksnc_tx_list,
2612                                           &sched->kss_tx_conns);
2613                         wake_up(&sched->kss_waitq);
2614
2615                         spin_unlock_bh(&sched->kss_lock);
2616                         nenomem_conns++;
2617                 }
2618
2619                 /* careful with the jiffy wrap... */
2620                 while ((timeout = deadline - ktime_get_seconds()) <= 0) {
2621                         const int n = 4;
2622                         const int p = 1;
2623                         int  chunk = HASH_SIZE(ksocknal_data.ksnd_peers);
2624                         unsigned int lnd_timeout;
2625
2626                         /* Time to check for timeouts on a few more peers: I
2627                          * do checks every 'p' seconds on a proportion of the
2628                          * peer_ni table and I need to check every connection
2629                          * 'n' times within a timeout interval, to ensure I
2630                          * detect a timeout on any connection within (n+1)/n
2631                          * times the timeout interval.
2632                          */
2633
2634                         lnd_timeout = ksocknal_timeout();
2635                         if (lnd_timeout > n * p)
2636                                 chunk = (chunk * n * p) / lnd_timeout;
2637                         if (chunk == 0)
2638                                 chunk = 1;
2639
2640                         for (i = 0; i < chunk; i++) {
2641                                 ksocknal_check_peer_timeouts(peer_index);
2642                                 peer_index = (peer_index + 1) %
2643                                         HASH_SIZE(ksocknal_data.ksnd_peers);
2644                         }
2645
2646                         deadline += p;
2647                 }
2648
2649                 if (nenomem_conns != 0) {
2650                         /* Reduce my timeout if I rescheduled ENOMEM conns.
2651                          * This also prevents me getting woken immediately
2652                          * if any go back on my enomem list. */
2653                         timeout = SOCKNAL_ENOMEM_RETRY;
2654                 }
2655                 ksocknal_data.ksnd_reaper_waketime = ktime_get_seconds() +
2656                                                      timeout;
2657
2658                 set_current_state(TASK_INTERRUPTIBLE);
2659                 add_wait_queue(&ksocknal_data.ksnd_reaper_waitq, &wait);
2660
2661                 if (!ksocknal_data.ksnd_shuttingdown &&
2662                     list_empty(&ksocknal_data.ksnd_deathrow_conns) &&
2663                     list_empty(&ksocknal_data.ksnd_zombie_conns))
2664                         schedule_timeout(cfs_time_seconds(timeout));
2665
2666                 set_current_state(TASK_RUNNING);
2667                 remove_wait_queue(&ksocknal_data.ksnd_reaper_waitq, &wait);
2668
2669                 spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
2670         }
2671
2672         spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
2673
2674         ksocknal_thread_fini();
2675         return 0;
2676 }