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