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