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