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