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