Whamcloud - gitweb
LU-12678 socklnd: change ksnd_nthreads to atomic_t
[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         refcount_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(refcount_read(&tx->tx_refcount) == 1);
459                 ksocknal_tx_done(ni, tx, error);
460         }
461 }
462
463 static void
464 ksocknal_check_zc_req(struct ksock_tx *tx)
465 {
466         struct ksock_conn *conn = tx->tx_conn;
467         struct ksock_peer_ni *peer_ni = conn->ksnc_peer;
468
469         /* Set tx_msg.ksm_zc_cookies[0] to a unique non-zero cookie and add tx
470          * to ksnp_zc_req_list if some fragment of this message should be sent
471          * zero-copy.  Our peer_ni will send an ACK containing this cookie when
472          * she has received this message to tell us we can signal completion.
473          * tx_msg.ksm_zc_cookies[0] remains non-zero while tx is on
474          * ksnp_zc_req_list. */
475         LASSERT (tx->tx_msg.ksm_type != KSOCK_MSG_NOOP);
476         LASSERT (tx->tx_zc_capable);
477
478         tx->tx_zc_checked = 1;
479
480         if (conn->ksnc_proto == &ksocknal_protocol_v1x ||
481             !conn->ksnc_zc_capable)
482                 return;
483
484         /* assign cookie and queue tx to pending list, it will be released when
485          * a matching ack is received. See ksocknal_handle_zcack() */
486
487         ksocknal_tx_addref(tx);
488
489         spin_lock(&peer_ni->ksnp_lock);
490
491         /* ZC_REQ is going to be pinned to the peer_ni */
492         tx->tx_deadline = ktime_get_seconds() +
493                           ksocknal_timeout();
494
495         LASSERT (tx->tx_msg.ksm_zc_cookies[0] == 0);
496
497         tx->tx_msg.ksm_zc_cookies[0] = peer_ni->ksnp_zc_next_cookie++;
498
499         if (peer_ni->ksnp_zc_next_cookie == 0)
500                 peer_ni->ksnp_zc_next_cookie = SOCKNAL_KEEPALIVE_PING + 1;
501
502         list_add_tail(&tx->tx_zc_list, &peer_ni->ksnp_zc_req_list);
503
504         spin_unlock(&peer_ni->ksnp_lock);
505 }
506
507 static void
508 ksocknal_uncheck_zc_req(struct ksock_tx *tx)
509 {
510         struct ksock_peer_ni *peer_ni = tx->tx_conn->ksnc_peer;
511
512         LASSERT(tx->tx_msg.ksm_type != KSOCK_MSG_NOOP);
513         LASSERT(tx->tx_zc_capable);
514
515         tx->tx_zc_checked = 0;
516
517         spin_lock(&peer_ni->ksnp_lock);
518
519         if (tx->tx_msg.ksm_zc_cookies[0] == 0) {
520                 /* Not waiting for an ACK */
521                 spin_unlock(&peer_ni->ksnp_lock);
522                 return;
523         }
524
525         tx->tx_msg.ksm_zc_cookies[0] = 0;
526         list_del(&tx->tx_zc_list);
527
528         spin_unlock(&peer_ni->ksnp_lock);
529
530         ksocknal_tx_decref(tx);
531 }
532
533 static int
534 ksocknal_process_transmit(struct ksock_conn *conn, struct ksock_tx *tx,
535                           struct kvec *scratch_iov)
536 {
537         int rc;
538         bool error_sim = false;
539
540         if (lnet_send_error_simulation(tx->tx_lnetmsg, &tx->tx_hstatus)) {
541                 error_sim = true;
542                 rc = -EINVAL;
543                 goto simulate_error;
544         }
545
546         if (tx->tx_zc_capable && !tx->tx_zc_checked)
547                 ksocknal_check_zc_req(tx);
548
549         rc = ksocknal_transmit(conn, tx, scratch_iov);
550
551         CDEBUG(D_NET, "send(%d) %d\n", tx->tx_resid, rc);
552
553         if (tx->tx_resid == 0) {
554                 /* Sent everything OK */
555                 LASSERT(rc == 0);
556
557                 return 0;
558         }
559
560         if (rc == -EAGAIN)
561                 return rc;
562
563         if (rc == -ENOMEM) {
564                 static int counter;
565
566                 counter++;   /* exponential backoff warnings */
567                 if ((counter & (-counter)) == counter)
568                         CWARN("%u ENOMEM tx %p (%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         atomic_inc(&ksocknal_data.ksnd_nthreads);
1063         return 0;
1064 }
1065
1066 void
1067 ksocknal_thread_fini (void)
1068 {
1069         if (atomic_dec_and_test(&ksocknal_data.ksnd_nthreads))
1070                 wake_up_var(&ksocknal_data.ksnd_nthreads);
1071 }
1072
1073 int
1074 ksocknal_new_packet(struct ksock_conn *conn, int nob_to_skip)
1075 {
1076         static char ksocknal_slop_buffer[4096];
1077         int nob;
1078         unsigned int niov;
1079         int skipped;
1080
1081         LASSERT(conn->ksnc_proto != NULL);
1082
1083         if ((*ksocknal_tunables.ksnd_eager_ack & conn->ksnc_type) != 0) {
1084                 /* Remind the socket to ack eagerly... */
1085                 ksocknal_lib_eager_ack(conn);
1086         }
1087
1088         if (nob_to_skip == 0) {         /* right at next packet boundary now */
1089                 conn->ksnc_rx_started = 0;
1090                 smp_mb();                       /* racing with timeout thread */
1091
1092                 switch (conn->ksnc_proto->pro_version) {
1093                 case  KSOCK_PROTO_V2:
1094                 case  KSOCK_PROTO_V3:
1095                         conn->ksnc_rx_state = SOCKNAL_RX_KSM_HEADER;
1096                         conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
1097                         conn->ksnc_rx_iov[0].iov_base = (char *)&conn->ksnc_msg;
1098
1099                         conn->ksnc_rx_nob_wanted = offsetof(struct ksock_msg, ksm_u);
1100                         conn->ksnc_rx_nob_left = offsetof(struct ksock_msg, ksm_u);
1101                         conn->ksnc_rx_iov[0].iov_len  = offsetof(struct ksock_msg, ksm_u);
1102                         break;
1103
1104                 case KSOCK_PROTO_V1:
1105                         /* Receiving bare struct lnet_hdr */
1106                         conn->ksnc_rx_state = SOCKNAL_RX_LNET_HEADER;
1107                         conn->ksnc_rx_nob_wanted = sizeof(struct lnet_hdr);
1108                         conn->ksnc_rx_nob_left = sizeof(struct lnet_hdr);
1109
1110                         conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
1111                         conn->ksnc_rx_iov[0].iov_base = (char *)&conn->ksnc_msg.ksm_u.lnetmsg;
1112                         conn->ksnc_rx_iov[0].iov_len = sizeof(struct lnet_hdr);
1113                         break;
1114
1115                 default:
1116                         LBUG ();
1117                 }
1118                 conn->ksnc_rx_niov = 1;
1119
1120                 conn->ksnc_rx_kiov = NULL;
1121                 conn->ksnc_rx_nkiov = 0;
1122                 conn->ksnc_rx_csum = ~0;
1123                 return (1);
1124         }
1125
1126         /* Set up to skip as much as possible now.  If there's more left
1127          * (ran out of iov entries) we'll get called again */
1128
1129         conn->ksnc_rx_state = SOCKNAL_RX_SLOP;
1130         conn->ksnc_rx_nob_left = nob_to_skip;
1131         conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
1132         skipped = 0;
1133         niov = 0;
1134
1135         do {
1136                 nob = min_t(int, nob_to_skip, sizeof(ksocknal_slop_buffer));
1137
1138                 conn->ksnc_rx_iov[niov].iov_base = ksocknal_slop_buffer;
1139                 conn->ksnc_rx_iov[niov].iov_len  = nob;
1140                 niov++;
1141                 skipped += nob;
1142                 nob_to_skip -= nob;
1143
1144         } while (nob_to_skip != 0 &&    /* mustn't overflow conn's rx iov */
1145                  niov < sizeof(conn->ksnc_rx_iov_space) / sizeof(struct kvec));
1146
1147         conn->ksnc_rx_niov = niov;
1148         conn->ksnc_rx_kiov = NULL;
1149         conn->ksnc_rx_nkiov = 0;
1150         conn->ksnc_rx_nob_wanted = skipped;
1151         return (0);
1152 }
1153
1154 static int
1155 ksocknal_process_receive(struct ksock_conn *conn,
1156                          struct page **rx_scratch_pgs,
1157                          struct kvec *scratch_iov)
1158 {
1159         struct lnet_hdr *lhdr;
1160         struct lnet_process_id *id;
1161         int rc;
1162
1163         LASSERT(refcount_read(&conn->ksnc_conn_refcount) > 0);
1164
1165         /* NB: sched lock NOT held */
1166         /* SOCKNAL_RX_LNET_HEADER is here for backward compatibility */
1167         LASSERT(conn->ksnc_rx_state == SOCKNAL_RX_KSM_HEADER ||
1168                 conn->ksnc_rx_state == SOCKNAL_RX_LNET_PAYLOAD ||
1169                 conn->ksnc_rx_state == SOCKNAL_RX_LNET_HEADER ||
1170                 conn->ksnc_rx_state == SOCKNAL_RX_SLOP);
1171  again:
1172         if (conn->ksnc_rx_nob_wanted != 0) {
1173                 rc = ksocknal_receive(conn, rx_scratch_pgs,
1174                                       scratch_iov);
1175
1176                 if (rc <= 0) {
1177                         struct lnet_process_id ksnp_id;
1178
1179                         ksnp_id = conn->ksnc_peer->ksnp_id;
1180
1181                         LASSERT(rc != -EAGAIN);
1182                         if (rc == 0)
1183                                 CDEBUG(D_NET, "[%p] EOF from %s "
1184                                        "ip %pI4h:%d\n", conn,
1185                                         libcfs_id2str(ksnp_id),
1186                                         &conn->ksnc_ipaddr,
1187                                         conn->ksnc_port);
1188                         else if (!conn->ksnc_closing)
1189                                 CERROR("[%p] Error %d on read from %s "
1190                                        "ip %pI4h:%d\n", conn, rc,
1191                                        libcfs_id2str(ksnp_id),
1192                                        &conn->ksnc_ipaddr,
1193                                        conn->ksnc_port);
1194
1195                         /* it's not an error if conn is being closed */
1196                         ksocknal_close_conn_and_siblings (conn,
1197                                                           (conn->ksnc_closing) ? 0 : rc);
1198                         return (rc == 0 ? -ESHUTDOWN : rc);
1199                 }
1200
1201                 if (conn->ksnc_rx_nob_wanted != 0) {
1202                         /* short read */
1203                         return (-EAGAIN);
1204                 }
1205         }
1206         switch (conn->ksnc_rx_state) {
1207         case SOCKNAL_RX_KSM_HEADER:
1208                 if (conn->ksnc_flip) {
1209                         __swab32s(&conn->ksnc_msg.ksm_type);
1210                         __swab32s(&conn->ksnc_msg.ksm_csum);
1211                         __swab64s(&conn->ksnc_msg.ksm_zc_cookies[0]);
1212                         __swab64s(&conn->ksnc_msg.ksm_zc_cookies[1]);
1213                 }
1214
1215                 if (conn->ksnc_msg.ksm_type != KSOCK_MSG_NOOP &&
1216                     conn->ksnc_msg.ksm_type != KSOCK_MSG_LNET) {
1217                         CERROR("%s: Unknown message type: %x\n",
1218                                libcfs_id2str(conn->ksnc_peer->ksnp_id),
1219                                conn->ksnc_msg.ksm_type);
1220                         ksocknal_new_packet(conn, 0);
1221                         ksocknal_close_conn_and_siblings(conn, -EPROTO);
1222                         return (-EPROTO);
1223                 }
1224
1225                 if (conn->ksnc_msg.ksm_type == KSOCK_MSG_NOOP &&
1226                     conn->ksnc_msg.ksm_csum != 0 &&     /* has checksum */
1227                     conn->ksnc_msg.ksm_csum != conn->ksnc_rx_csum) {
1228                         /* NOOP Checksum error */
1229                         CERROR("%s: Checksum error, wire:0x%08X data:0x%08X\n",
1230                                libcfs_id2str(conn->ksnc_peer->ksnp_id),
1231                                conn->ksnc_msg.ksm_csum, conn->ksnc_rx_csum);
1232                         ksocknal_new_packet(conn, 0);
1233                         ksocknal_close_conn_and_siblings(conn, -EPROTO);
1234                         return (-EIO);
1235                 }
1236
1237                 if (conn->ksnc_msg.ksm_zc_cookies[1] != 0) {
1238                         __u64 cookie = 0;
1239
1240                         LASSERT (conn->ksnc_proto != &ksocknal_protocol_v1x);
1241
1242                         if (conn->ksnc_msg.ksm_type == KSOCK_MSG_NOOP)
1243                                 cookie = conn->ksnc_msg.ksm_zc_cookies[0];
1244
1245                         rc = conn->ksnc_proto->pro_handle_zcack(conn, cookie,
1246                                                conn->ksnc_msg.ksm_zc_cookies[1]);
1247
1248                         if (rc != 0) {
1249                                 CERROR("%s: Unknown ZC-ACK cookie: %llu, %llu\n",
1250                                        libcfs_id2str(conn->ksnc_peer->ksnp_id),
1251                                        cookie, conn->ksnc_msg.ksm_zc_cookies[1]);
1252                                 ksocknal_new_packet(conn, 0);
1253                                 ksocknal_close_conn_and_siblings(conn, -EPROTO);
1254                                 return (rc);
1255                         }
1256                 }
1257
1258                 if (conn->ksnc_msg.ksm_type == KSOCK_MSG_NOOP) {
1259                         ksocknal_new_packet (conn, 0);
1260                         return 0;       /* NOOP is done and just return */
1261                 }
1262
1263                 conn->ksnc_rx_state = SOCKNAL_RX_LNET_HEADER;
1264                 conn->ksnc_rx_nob_wanted = sizeof(struct ksock_lnet_msg);
1265                 conn->ksnc_rx_nob_left = sizeof(struct ksock_lnet_msg);
1266
1267                 conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
1268                 conn->ksnc_rx_iov[0].iov_base = (char *)&conn->ksnc_msg.ksm_u.lnetmsg;
1269                 conn->ksnc_rx_iov[0].iov_len  = sizeof(struct ksock_lnet_msg);
1270
1271                 conn->ksnc_rx_niov = 1;
1272                 conn->ksnc_rx_kiov = NULL;
1273                 conn->ksnc_rx_nkiov = 0;
1274
1275                 goto again;     /* read lnet header now */
1276
1277         case SOCKNAL_RX_LNET_HEADER:
1278                 /* unpack message header */
1279                 conn->ksnc_proto->pro_unpack(&conn->ksnc_msg);
1280
1281                 if ((conn->ksnc_peer->ksnp_id.pid & LNET_PID_USERFLAG) != 0) {
1282                         /* Userspace peer_ni */
1283                         lhdr = &conn->ksnc_msg.ksm_u.lnetmsg.ksnm_hdr;
1284                         id   = &conn->ksnc_peer->ksnp_id;
1285
1286                         /* Substitute process ID assigned at connection time */
1287                         lhdr->src_pid = cpu_to_le32(id->pid);
1288                         lhdr->src_nid = cpu_to_le64(id->nid);
1289                 }
1290
1291                 conn->ksnc_rx_state = SOCKNAL_RX_PARSE;
1292                 ksocknal_conn_addref(conn);     /* ++ref while parsing */
1293
1294                 rc = lnet_parse(conn->ksnc_peer->ksnp_ni,
1295                                 &conn->ksnc_msg.ksm_u.lnetmsg.ksnm_hdr,
1296                                 conn->ksnc_peer->ksnp_id.nid, conn, 0);
1297                 if (rc < 0) {
1298                         /* I just received garbage: give up on this conn */
1299                         ksocknal_new_packet(conn, 0);
1300                         ksocknal_close_conn_and_siblings (conn, rc);
1301                         ksocknal_conn_decref(conn);
1302                         return (-EPROTO);
1303                 }
1304
1305                 /* I'm racing with ksocknal_recv() */
1306                 LASSERT (conn->ksnc_rx_state == SOCKNAL_RX_PARSE ||
1307                          conn->ksnc_rx_state == SOCKNAL_RX_LNET_PAYLOAD);
1308
1309                 if (conn->ksnc_rx_state != SOCKNAL_RX_LNET_PAYLOAD)
1310                         return 0;
1311
1312                 /* ksocknal_recv() got called */
1313                 goto again;
1314
1315         case SOCKNAL_RX_LNET_PAYLOAD:
1316                 /* payload all received */
1317                 rc = 0;
1318
1319                 if (conn->ksnc_rx_nob_left == 0 &&   /* not truncating */
1320                     conn->ksnc_msg.ksm_csum != 0 &&  /* has checksum */
1321                     conn->ksnc_msg.ksm_csum != conn->ksnc_rx_csum) {
1322                         CERROR("%s: Checksum error, wire:0x%08X data:0x%08X\n",
1323                                libcfs_id2str(conn->ksnc_peer->ksnp_id),
1324                                conn->ksnc_msg.ksm_csum, conn->ksnc_rx_csum);
1325                         rc = -EIO;
1326                 }
1327
1328                 if (rc == 0 && conn->ksnc_msg.ksm_zc_cookies[0] != 0) {
1329                         LASSERT(conn->ksnc_proto != &ksocknal_protocol_v1x);
1330
1331                         lhdr = &conn->ksnc_msg.ksm_u.lnetmsg.ksnm_hdr;
1332                         id   = &conn->ksnc_peer->ksnp_id;
1333
1334                         rc = conn->ksnc_proto->pro_handle_zcreq(conn,
1335                                         conn->ksnc_msg.ksm_zc_cookies[0],
1336                                         *ksocknal_tunables.ksnd_nonblk_zcack ||
1337                                         le64_to_cpu(lhdr->src_nid) != id->nid);
1338                 }
1339
1340                 if (rc && conn->ksnc_lnet_msg)
1341                         conn->ksnc_lnet_msg->msg_health_status =
1342                                 LNET_MSG_STATUS_REMOTE_ERROR;
1343                 lnet_finalize(conn->ksnc_lnet_msg, rc);
1344
1345                 if (rc != 0) {
1346                         ksocknal_new_packet(conn, 0);
1347                         ksocknal_close_conn_and_siblings (conn, rc);
1348                         return (-EPROTO);
1349                 }
1350                 /* Fall through */
1351
1352         case SOCKNAL_RX_SLOP:
1353                 /* starting new packet? */
1354                 if (ksocknal_new_packet (conn, conn->ksnc_rx_nob_left))
1355                         return 0;       /* come back later */
1356                 goto again;             /* try to finish reading slop now */
1357
1358         default:
1359                 break;
1360         }
1361
1362         /* Not Reached */
1363         LBUG ();
1364         return (-EINVAL);                       /* keep gcc happy */
1365 }
1366
1367 int
1368 ksocknal_recv(struct lnet_ni *ni, void *private, struct lnet_msg *msg,
1369               int delayed, unsigned int niov,
1370               struct bio_vec *kiov, unsigned int offset, unsigned int mlen,
1371               unsigned int rlen)
1372 {
1373         struct ksock_conn *conn = private;
1374         struct ksock_sched *sched = conn->ksnc_scheduler;
1375
1376         LASSERT (mlen <= rlen);
1377         LASSERT (niov <= LNET_MAX_IOV);
1378
1379         conn->ksnc_lnet_msg = msg;
1380         conn->ksnc_rx_nob_wanted = mlen;
1381         conn->ksnc_rx_nob_left   = rlen;
1382
1383         if (mlen == 0) {
1384                 conn->ksnc_rx_nkiov = 0;
1385                 conn->ksnc_rx_kiov = NULL;
1386                 conn->ksnc_rx_iov = conn->ksnc_rx_iov_space.iov;
1387                 conn->ksnc_rx_niov = 0;
1388         } else {
1389                 conn->ksnc_rx_niov = 0;
1390                 conn->ksnc_rx_iov  = NULL;
1391                 conn->ksnc_rx_kiov = conn->ksnc_rx_iov_space.kiov;
1392                 conn->ksnc_rx_nkiov =
1393                         lnet_extract_kiov(LNET_MAX_IOV, conn->ksnc_rx_kiov,
1394                                           niov, kiov, offset, mlen);
1395         }
1396
1397         LASSERT (mlen ==
1398                  lnet_iov_nob (conn->ksnc_rx_niov, conn->ksnc_rx_iov) +
1399                  lnet_kiov_nob (conn->ksnc_rx_nkiov, conn->ksnc_rx_kiov));
1400
1401         LASSERT (conn->ksnc_rx_scheduled);
1402
1403         spin_lock_bh(&sched->kss_lock);
1404
1405         switch (conn->ksnc_rx_state) {
1406         case SOCKNAL_RX_PARSE_WAIT:
1407                 list_add_tail(&conn->ksnc_rx_list, &sched->kss_rx_conns);
1408                 wake_up(&sched->kss_waitq);
1409                 LASSERT(conn->ksnc_rx_ready);
1410                 break;
1411
1412         case SOCKNAL_RX_PARSE:
1413                 /* scheduler hasn't noticed I'm parsing yet */
1414                 break;
1415         }
1416
1417         conn->ksnc_rx_state = SOCKNAL_RX_LNET_PAYLOAD;
1418
1419         spin_unlock_bh(&sched->kss_lock);
1420         ksocknal_conn_decref(conn);
1421         return 0;
1422 }
1423
1424 static inline int
1425 ksocknal_sched_cansleep(struct ksock_sched *sched)
1426 {
1427         int           rc;
1428
1429         spin_lock_bh(&sched->kss_lock);
1430
1431         rc = (!ksocknal_data.ksnd_shuttingdown &&
1432               list_empty(&sched->kss_rx_conns) &&
1433               list_empty(&sched->kss_tx_conns));
1434
1435         spin_unlock_bh(&sched->kss_lock);
1436         return rc;
1437 }
1438
1439 int ksocknal_scheduler(void *arg)
1440 {
1441         struct ksock_sched *sched;
1442         struct ksock_conn *conn;
1443         struct ksock_tx *tx;
1444         int rc;
1445         long id = (long)arg;
1446         struct page **rx_scratch_pgs;
1447         struct kvec *scratch_iov;
1448
1449         sched = ksocknal_data.ksnd_schedulers[KSOCK_THREAD_CPT(id)];
1450
1451         LIBCFS_CPT_ALLOC(rx_scratch_pgs, lnet_cpt_table(), sched->kss_cpt,
1452                          sizeof(*rx_scratch_pgs) * LNET_MAX_IOV);
1453         if (!rx_scratch_pgs) {
1454                 CERROR("Unable to allocate scratch pages\n");
1455                 return -ENOMEM;
1456         }
1457
1458         LIBCFS_CPT_ALLOC(scratch_iov, lnet_cpt_table(), sched->kss_cpt,
1459                          sizeof(*scratch_iov) * LNET_MAX_IOV);
1460         if (!scratch_iov) {
1461                 CERROR("Unable to allocate scratch iov\n");
1462                 return -ENOMEM;
1463         }
1464
1465         rc = cfs_cpt_bind(lnet_cpt_table(), sched->kss_cpt);
1466         if (rc != 0) {
1467                 CWARN("Can't set CPU partition affinity to %d: %d\n",
1468                         sched->kss_cpt, rc);
1469         }
1470
1471         spin_lock_bh(&sched->kss_lock);
1472
1473         while (!ksocknal_data.ksnd_shuttingdown) {
1474                 int did_something = 0;
1475
1476                 /* Ensure I progress everything semi-fairly */
1477
1478                 if (!list_empty(&sched->kss_rx_conns)) {
1479                         conn = list_entry(sched->kss_rx_conns.next,
1480                                           struct ksock_conn, ksnc_rx_list);
1481                         list_del(&conn->ksnc_rx_list);
1482
1483                         LASSERT(conn->ksnc_rx_scheduled);
1484                         LASSERT(conn->ksnc_rx_ready);
1485
1486                         /* clear rx_ready in case receive isn't complete.
1487                          * Do it BEFORE we call process_recv, since
1488                          * data_ready can set it any time after we release
1489                          * kss_lock. */
1490                         conn->ksnc_rx_ready = 0;
1491                         spin_unlock_bh(&sched->kss_lock);
1492
1493                         rc = ksocknal_process_receive(conn, rx_scratch_pgs,
1494                                                       scratch_iov);
1495
1496                         spin_lock_bh(&sched->kss_lock);
1497
1498                         /* I'm the only one that can clear this flag */
1499                         LASSERT(conn->ksnc_rx_scheduled);
1500
1501                         /* Did process_receive get everything it wanted? */
1502                         if (rc == 0)
1503                                 conn->ksnc_rx_ready = 1;
1504
1505                         if (conn->ksnc_rx_state == SOCKNAL_RX_PARSE) {
1506                                 /* Conn blocked waiting for ksocknal_recv()
1507                                  * I change its state (under lock) to signal
1508                                  * it can be rescheduled */
1509                                 conn->ksnc_rx_state = SOCKNAL_RX_PARSE_WAIT;
1510                         } else if (conn->ksnc_rx_ready) {
1511                                 /* reschedule for rx */
1512                                 list_add_tail(&conn->ksnc_rx_list,
1513                                                    &sched->kss_rx_conns);
1514                         } else {
1515                                 conn->ksnc_rx_scheduled = 0;
1516                                 /* drop my ref */
1517                                 ksocknal_conn_decref(conn);
1518                         }
1519
1520                         did_something = 1;
1521                 }
1522
1523                 if (!list_empty(&sched->kss_tx_conns)) {
1524                         LIST_HEAD(zlist);
1525
1526                         list_splice_init(&sched->kss_zombie_noop_txs, &zlist);
1527
1528                         conn = list_entry(sched->kss_tx_conns.next,
1529                                           struct ksock_conn, ksnc_tx_list);
1530                         list_del(&conn->ksnc_tx_list);
1531
1532                         LASSERT(conn->ksnc_tx_scheduled);
1533                         LASSERT(conn->ksnc_tx_ready);
1534                         LASSERT(!list_empty(&conn->ksnc_tx_queue));
1535
1536                         tx = list_entry(conn->ksnc_tx_queue.next,
1537                                         struct ksock_tx, tx_list);
1538
1539                         if (conn->ksnc_tx_carrier == tx)
1540                                 ksocknal_next_tx_carrier(conn);
1541
1542                         /* dequeue now so empty list => more to send */
1543                         list_del(&tx->tx_list);
1544
1545                         /* Clear tx_ready in case send isn't complete.  Do
1546                          * it BEFORE we call process_transmit, since
1547                          * write_space can set it any time after we release
1548                          * kss_lock. */
1549                         conn->ksnc_tx_ready = 0;
1550                         spin_unlock_bh(&sched->kss_lock);
1551
1552                         if (!list_empty(&zlist)) {
1553                                 /* free zombie noop txs, it's fast because
1554                                  * noop txs are just put in freelist */
1555                                 ksocknal_txlist_done(NULL, &zlist, 0);
1556                         }
1557
1558                         rc = ksocknal_process_transmit(conn, tx, scratch_iov);
1559
1560                         if (rc == -ENOMEM || rc == -EAGAIN) {
1561                                 /* Incomplete send: replace tx on HEAD of tx_queue */
1562                                 spin_lock_bh(&sched->kss_lock);
1563                                 list_add(&tx->tx_list,
1564                                          &conn->ksnc_tx_queue);
1565                         } else {
1566                                 /* Complete send; tx -ref */
1567                                 ksocknal_tx_decref(tx);
1568
1569                                 spin_lock_bh(&sched->kss_lock);
1570                                 /* assume space for more */
1571                                 conn->ksnc_tx_ready = 1;
1572                         }
1573
1574                         if (rc == -ENOMEM) {
1575                                 /* Do nothing; after a short timeout, this
1576                                  * conn will be reposted on kss_tx_conns. */
1577                         } else if (conn->ksnc_tx_ready &&
1578                                    !list_empty(&conn->ksnc_tx_queue)) {
1579                                 /* reschedule for tx */
1580                                 list_add_tail(&conn->ksnc_tx_list,
1581                                               &sched->kss_tx_conns);
1582                         } else {
1583                                 conn->ksnc_tx_scheduled = 0;
1584                                 /* drop my ref */
1585                                 ksocknal_conn_decref(conn);
1586                         }
1587
1588                         did_something = 1;
1589                 }
1590                 if (!did_something ||   /* nothing to do */
1591                     need_resched()) {   /* hogging CPU? */
1592                         spin_unlock_bh(&sched->kss_lock);
1593
1594                         if (!did_something) {   /* wait for something to do */
1595                                 rc = wait_event_interruptible_exclusive(
1596                                         sched->kss_waitq,
1597                                         !ksocknal_sched_cansleep(sched));
1598                                 LASSERT (rc == 0);
1599                         } else {
1600                                 cond_resched();
1601                         }
1602
1603                         spin_lock_bh(&sched->kss_lock);
1604                 }
1605         }
1606
1607         spin_unlock_bh(&sched->kss_lock);
1608         CFS_FREE_PTR_ARRAY(rx_scratch_pgs, LNET_MAX_IOV);
1609         CFS_FREE_PTR_ARRAY(scratch_iov, LNET_MAX_IOV);
1610         ksocknal_thread_fini();
1611         return 0;
1612 }
1613
1614 /*
1615  * Add connection to kss_rx_conns of scheduler
1616  * and wakeup the scheduler.
1617  */
1618 void ksocknal_read_callback(struct ksock_conn *conn)
1619 {
1620         struct ksock_sched *sched;
1621         ENTRY;
1622
1623         sched = conn->ksnc_scheduler;
1624
1625         spin_lock_bh(&sched->kss_lock);
1626
1627         conn->ksnc_rx_ready = 1;
1628
1629         if (!conn->ksnc_rx_scheduled) {  /* not being progressed */
1630                 list_add_tail(&conn->ksnc_rx_list,
1631                                   &sched->kss_rx_conns);
1632                 conn->ksnc_rx_scheduled = 1;
1633                 /* extra ref for scheduler */
1634                 ksocknal_conn_addref(conn);
1635
1636                 wake_up (&sched->kss_waitq);
1637         }
1638         spin_unlock_bh(&sched->kss_lock);
1639
1640         EXIT;
1641 }
1642
1643 /*
1644  * Add connection to kss_tx_conns of scheduler
1645  * and wakeup the scheduler.
1646  */
1647 void ksocknal_write_callback(struct ksock_conn *conn)
1648 {
1649         struct ksock_sched *sched;
1650         ENTRY;
1651
1652         sched = conn->ksnc_scheduler;
1653
1654         spin_lock_bh(&sched->kss_lock);
1655
1656         conn->ksnc_tx_ready = 1;
1657
1658         if (!conn->ksnc_tx_scheduled && /* not being progressed */
1659             !list_empty(&conn->ksnc_tx_queue)) { /* packets to send */
1660                 list_add_tail(&conn->ksnc_tx_list, &sched->kss_tx_conns);
1661                 conn->ksnc_tx_scheduled = 1;
1662                 /* extra ref for scheduler */
1663                 ksocknal_conn_addref(conn);
1664
1665                 wake_up(&sched->kss_waitq);
1666         }
1667
1668         spin_unlock_bh(&sched->kss_lock);
1669
1670         EXIT;
1671 }
1672
1673 static const struct ksock_proto *
1674 ksocknal_parse_proto_version(struct ksock_hello_msg *hello)
1675 {
1676         __u32   version = 0;
1677
1678         if (hello->kshm_magic == LNET_PROTO_MAGIC)
1679                 version = hello->kshm_version;
1680         else if (hello->kshm_magic == __swab32(LNET_PROTO_MAGIC))
1681                 version = __swab32(hello->kshm_version);
1682
1683         if (version != 0) {
1684 #if SOCKNAL_VERSION_DEBUG
1685                 if (*ksocknal_tunables.ksnd_protocol == 1)
1686                         return NULL;
1687
1688                 if (*ksocknal_tunables.ksnd_protocol == 2 &&
1689                     version == KSOCK_PROTO_V3)
1690                         return NULL;
1691 #endif
1692                 if (version == KSOCK_PROTO_V2)
1693                         return &ksocknal_protocol_v2x;
1694
1695                 if (version == KSOCK_PROTO_V3)
1696                         return &ksocknal_protocol_v3x;
1697
1698                 return NULL;
1699         }
1700
1701         if (hello->kshm_magic == le32_to_cpu(LNET_PROTO_TCP_MAGIC)) {
1702                 struct lnet_magicversion *hmv;
1703
1704                 BUILD_BUG_ON(sizeof(struct lnet_magicversion) !=
1705                          offsetof(struct ksock_hello_msg, kshm_src_nid));
1706
1707                 hmv = (struct lnet_magicversion *)hello;
1708
1709                 if (hmv->version_major == cpu_to_le16 (KSOCK_PROTO_V1_MAJOR) &&
1710                     hmv->version_minor == cpu_to_le16 (KSOCK_PROTO_V1_MINOR))
1711                         return &ksocknal_protocol_v1x;
1712         }
1713
1714         return NULL;
1715 }
1716
1717 int
1718 ksocknal_send_hello(struct lnet_ni *ni, struct ksock_conn *conn,
1719                     lnet_nid_t peer_nid, struct ksock_hello_msg *hello)
1720 {
1721         /* CAVEAT EMPTOR: this byte flips 'ipaddrs' */
1722         struct ksock_net *net = (struct ksock_net *)ni->ni_data;
1723
1724         LASSERT(hello->kshm_nips <= LNET_INTERFACES_NUM);
1725
1726         /* rely on caller to hold a ref on socket so it wouldn't disappear */
1727         LASSERT(conn->ksnc_proto != NULL);
1728
1729         hello->kshm_src_nid         = ni->ni_nid;
1730         hello->kshm_dst_nid         = peer_nid;
1731         hello->kshm_src_pid         = the_lnet.ln_pid;
1732
1733         hello->kshm_src_incarnation = net->ksnn_incarnation;
1734         hello->kshm_ctype           = conn->ksnc_type;
1735
1736         return conn->ksnc_proto->pro_send_hello(conn, hello);
1737 }
1738
1739 static int
1740 ksocknal_invert_type(int type)
1741 {
1742         switch (type)
1743         {
1744         case SOCKLND_CONN_ANY:
1745         case SOCKLND_CONN_CONTROL:
1746                 return (type);
1747         case SOCKLND_CONN_BULK_IN:
1748                 return SOCKLND_CONN_BULK_OUT;
1749         case SOCKLND_CONN_BULK_OUT:
1750                 return SOCKLND_CONN_BULK_IN;
1751         default:
1752                 return (SOCKLND_CONN_NONE);
1753         }
1754 }
1755
1756 int
1757 ksocknal_recv_hello(struct lnet_ni *ni, struct ksock_conn *conn,
1758                     struct ksock_hello_msg *hello,
1759                     struct lnet_process_id *peerid,
1760                     __u64 *incarnation)
1761 {
1762         /* Return < 0        fatal error
1763          *        0          success
1764          *        EALREADY   lost connection race
1765          *        EPROTO     protocol version mismatch
1766          */
1767         struct socket        *sock = conn->ksnc_sock;
1768         int                  active = (conn->ksnc_proto != NULL);
1769         int                  timeout;
1770         int                  proto_match;
1771         int                  rc;
1772         const struct ksock_proto *proto;
1773         struct lnet_process_id recv_id;
1774
1775         /* socket type set on active connections - not set on passive */
1776         LASSERT(!active == !(conn->ksnc_type != SOCKLND_CONN_NONE));
1777
1778         timeout = active ? ksocknal_timeout() :
1779                             lnet_acceptor_timeout();
1780
1781         rc = lnet_sock_read(sock, &hello->kshm_magic,
1782                             sizeof(hello->kshm_magic), timeout);
1783         if (rc != 0) {
1784                 CERROR("Error %d reading HELLO from %pI4h\n",
1785                        rc, &conn->ksnc_ipaddr);
1786                 LASSERT (rc < 0);
1787                 return rc;
1788         }
1789
1790         if (hello->kshm_magic != LNET_PROTO_MAGIC &&
1791             hello->kshm_magic != __swab32(LNET_PROTO_MAGIC) &&
1792             hello->kshm_magic != le32_to_cpu (LNET_PROTO_TCP_MAGIC)) {
1793                 /* Unexpected magic! */
1794                 CERROR ("Bad magic(1) %#08x (%#08x expected) from "
1795                         "%pI4h\n", __cpu_to_le32 (hello->kshm_magic),
1796                         LNET_PROTO_TCP_MAGIC, &conn->ksnc_ipaddr);
1797                 return -EPROTO;
1798         }
1799
1800         rc = lnet_sock_read(sock, &hello->kshm_version,
1801                             sizeof(hello->kshm_version), timeout);
1802         if (rc != 0) {
1803                 CERROR("Error %d reading HELLO from %pI4h\n",
1804                        rc, &conn->ksnc_ipaddr);
1805                 LASSERT(rc < 0);
1806                 return rc;
1807         }
1808
1809         proto = ksocknal_parse_proto_version(hello);
1810         if (proto == NULL) {
1811                 if (!active) {
1812                         /* unknown protocol from peer_ni, tell peer_ni my protocol */
1813                         conn->ksnc_proto = &ksocknal_protocol_v3x;
1814 #if SOCKNAL_VERSION_DEBUG
1815                         if (*ksocknal_tunables.ksnd_protocol == 2)
1816                                 conn->ksnc_proto = &ksocknal_protocol_v2x;
1817                         else if (*ksocknal_tunables.ksnd_protocol == 1)
1818                                 conn->ksnc_proto = &ksocknal_protocol_v1x;
1819 #endif
1820                         hello->kshm_nips = 0;
1821                         ksocknal_send_hello(ni, conn, ni->ni_nid, hello);
1822                 }
1823
1824                 CERROR("Unknown protocol version (%d.x expected) from %pI4h\n",
1825                        conn->ksnc_proto->pro_version, &conn->ksnc_ipaddr);
1826
1827                 return -EPROTO;
1828         }
1829
1830         proto_match = (conn->ksnc_proto == proto);
1831         conn->ksnc_proto = proto;
1832
1833         /* receive the rest of hello message anyway */
1834         rc = conn->ksnc_proto->pro_recv_hello(conn, hello, timeout);
1835         if (rc != 0) {
1836                 CERROR("Error %d reading or checking hello from from %pI4h\n",
1837                        rc, &conn->ksnc_ipaddr);
1838                 LASSERT (rc < 0);
1839                 return rc;
1840         }
1841
1842         *incarnation = hello->kshm_src_incarnation;
1843
1844         if (hello->kshm_src_nid == LNET_NID_ANY) {
1845                 CERROR("Expecting a HELLO hdr with a NID, but got LNET_NID_ANY from %pI4h\n",
1846                        &conn->ksnc_ipaddr);
1847                 return -EPROTO;
1848         }
1849
1850         if (!active &&
1851             conn->ksnc_port > LNET_ACCEPTOR_MAX_RESERVED_PORT) {
1852                 /* Userspace NAL assigns peer_ni process ID from socket */
1853                 recv_id.pid = conn->ksnc_port | LNET_PID_USERFLAG;
1854                 recv_id.nid = LNET_MKNID(LNET_NIDNET(ni->ni_nid), conn->ksnc_ipaddr);
1855         } else {
1856                 recv_id.nid = hello->kshm_src_nid;
1857                 recv_id.pid = hello->kshm_src_pid;
1858         }
1859
1860         if (!active) {
1861                 *peerid = recv_id;
1862
1863                 /* peer_ni determines type */
1864                 conn->ksnc_type = ksocknal_invert_type(hello->kshm_ctype);
1865                 if (conn->ksnc_type == SOCKLND_CONN_NONE) {
1866                         CERROR("Unexpected type %d from %s ip %pI4h\n",
1867                                hello->kshm_ctype, libcfs_id2str(*peerid),
1868                                &conn->ksnc_ipaddr);
1869                         return -EPROTO;
1870                 }
1871                 return 0;
1872         }
1873
1874         if (peerid->pid != recv_id.pid ||
1875             peerid->nid != recv_id.nid) {
1876                 LCONSOLE_ERROR_MSG(0x130, "Connected successfully to %s on host"
1877                                    " %pI4h, but they claimed they were "
1878                                    "%s; please check your Lustre "
1879                                    "configuration.\n",
1880                                    libcfs_id2str(*peerid),
1881                                    &conn->ksnc_ipaddr,
1882                                    libcfs_id2str(recv_id));
1883                 return -EPROTO;
1884         }
1885
1886         if (hello->kshm_ctype == SOCKLND_CONN_NONE) {
1887                 /* Possible protocol mismatch or I lost the connection race */
1888                 return proto_match ? EALREADY : EPROTO;
1889         }
1890
1891         if (ksocknal_invert_type(hello->kshm_ctype) != conn->ksnc_type) {
1892                 CERROR("Mismatched types: me %d, %s ip %pI4h %d\n",
1893                        conn->ksnc_type, libcfs_id2str(*peerid),
1894                        &conn->ksnc_ipaddr,
1895                        hello->kshm_ctype);
1896                 return -EPROTO;
1897         }
1898         return 0;
1899 }
1900
1901 static int
1902 ksocknal_connect(struct ksock_route *route)
1903 {
1904         LIST_HEAD(zombies);
1905         struct ksock_peer_ni *peer_ni = route->ksnr_peer;
1906         int               type;
1907         int               wanted;
1908         struct socket     *sock;
1909         time64_t deadline;
1910         int               retry_later = 0;
1911         int               rc = 0;
1912
1913         deadline = ktime_get_seconds() + ksocknal_timeout();
1914
1915         write_lock_bh(&ksocknal_data.ksnd_global_lock);
1916
1917         LASSERT (route->ksnr_scheduled);
1918         LASSERT (!route->ksnr_connecting);
1919
1920         route->ksnr_connecting = 1;
1921
1922         for (;;) {
1923                 wanted = ksocknal_route_mask() & ~route->ksnr_connected;
1924
1925                 /* stop connecting if peer_ni/route got closed under me, or
1926                  * route got connected while queued */
1927                 if (peer_ni->ksnp_closing || route->ksnr_deleted ||
1928                     wanted == 0) {
1929                         retry_later = 0;
1930                         break;
1931                 }
1932
1933                 /* reschedule if peer_ni is connecting to me */
1934                 if (peer_ni->ksnp_accepting > 0) {
1935                         CDEBUG(D_NET,
1936                                "peer_ni %s(%d) already connecting to me, retry later.\n",
1937                                libcfs_nid2str(peer_ni->ksnp_id.nid), peer_ni->ksnp_accepting);
1938                         retry_later = 1;
1939                 }
1940
1941                 if (retry_later) /* needs reschedule */
1942                         break;
1943
1944                 if ((wanted & BIT(SOCKLND_CONN_ANY)) != 0) {
1945                         type = SOCKLND_CONN_ANY;
1946                 } else if ((wanted & BIT(SOCKLND_CONN_CONTROL)) != 0) {
1947                         type = SOCKLND_CONN_CONTROL;
1948                 } else if ((wanted & BIT(SOCKLND_CONN_BULK_IN)) != 0) {
1949                         type = SOCKLND_CONN_BULK_IN;
1950                 } else {
1951                         LASSERT ((wanted & BIT(SOCKLND_CONN_BULK_OUT)) != 0);
1952                         type = SOCKLND_CONN_BULK_OUT;
1953                 }
1954
1955                 write_unlock_bh(&ksocknal_data.ksnd_global_lock);
1956
1957                 if (ktime_get_seconds() >= deadline) {
1958                         rc = -ETIMEDOUT;
1959                         lnet_connect_console_error(rc, peer_ni->ksnp_id.nid,
1960                                                    route->ksnr_ipaddr,
1961                                                    route->ksnr_port);
1962                         goto failed;
1963                 }
1964
1965                 sock = lnet_connect(peer_ni->ksnp_id.nid,
1966                                     route->ksnr_myiface,
1967                                     route->ksnr_ipaddr, route->ksnr_port,
1968                                     peer_ni->ksnp_ni->ni_net_ns);
1969                 if (IS_ERR(sock)) {
1970                         rc = PTR_ERR(sock);
1971                         goto failed;
1972                 }
1973
1974                 rc = ksocknal_create_conn(peer_ni->ksnp_ni, route, sock, type);
1975                 if (rc < 0) {
1976                         lnet_connect_console_error(rc, peer_ni->ksnp_id.nid,
1977                                                    route->ksnr_ipaddr,
1978                                                    route->ksnr_port);
1979                         goto failed;
1980                 }
1981
1982                 /* A +ve RC means I have to retry because I lost the connection
1983                  * race or I have to renegotiate protocol version */
1984                 retry_later = (rc != 0);
1985                 if (retry_later)
1986                         CDEBUG(D_NET, "peer_ni %s: conn race, retry later.\n",
1987                                libcfs_nid2str(peer_ni->ksnp_id.nid));
1988
1989                 write_lock_bh(&ksocknal_data.ksnd_global_lock);
1990         }
1991
1992         route->ksnr_scheduled = 0;
1993         route->ksnr_connecting = 0;
1994
1995         if (retry_later) {
1996                 /* re-queue for attention; this frees me up to handle
1997                  * the peer_ni's incoming connection request */
1998
1999                 if (rc == EALREADY ||
2000                     (rc == 0 && peer_ni->ksnp_accepting > 0)) {
2001                         /* We want to introduce a delay before next
2002                          * attempt to connect if we lost conn race,
2003                          * but the race is resolved quickly usually,
2004                          * so min_reconnectms should be good heuristic */
2005                         route->ksnr_retry_interval = *ksocknal_tunables.ksnd_min_reconnectms / 1000;
2006                         route->ksnr_timeout = ktime_get_seconds() +
2007                                               route->ksnr_retry_interval;
2008                 }
2009
2010                 ksocknal_launch_connection_locked(route);
2011         }
2012
2013         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
2014         return retry_later;
2015
2016  failed:
2017         write_lock_bh(&ksocknal_data.ksnd_global_lock);
2018
2019         route->ksnr_scheduled = 0;
2020         route->ksnr_connecting = 0;
2021
2022         /* This is a retry rather than a new connection */
2023         route->ksnr_retry_interval *= 2;
2024         route->ksnr_retry_interval =
2025                 max_t(time64_t, route->ksnr_retry_interval,
2026                       *ksocknal_tunables.ksnd_min_reconnectms / 1000);
2027         route->ksnr_retry_interval =
2028                 min_t(time64_t, route->ksnr_retry_interval,
2029                       *ksocknal_tunables.ksnd_max_reconnectms / 1000);
2030
2031         LASSERT(route->ksnr_retry_interval);
2032         route->ksnr_timeout = ktime_get_seconds() + route->ksnr_retry_interval;
2033
2034         if (!list_empty(&peer_ni->ksnp_tx_queue) &&
2035             peer_ni->ksnp_accepting == 0 &&
2036             ksocknal_find_connecting_route_locked(peer_ni) == NULL) {
2037                 struct ksock_conn *conn;
2038
2039                 /* ksnp_tx_queue is queued on a conn on successful
2040                  * connection for V1.x and V2.x */
2041                 if (!list_empty(&peer_ni->ksnp_conns)) {
2042                         conn = list_entry(peer_ni->ksnp_conns.next,
2043                                           struct ksock_conn, ksnc_list);
2044                         LASSERT (conn->ksnc_proto == &ksocknal_protocol_v3x);
2045                 }
2046
2047                 /* take all the blocked packets while I've got the lock and
2048                  * complete below... */
2049                 list_splice_init(&peer_ni->ksnp_tx_queue, &zombies);
2050         }
2051
2052         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
2053
2054         ksocknal_peer_failed(peer_ni);
2055         ksocknal_txlist_done(peer_ni->ksnp_ni, &zombies, rc);
2056         return 0;
2057 }
2058
2059 /*
2060  * check whether we need to create more connds.
2061  * It will try to create new thread if it's necessary, @timeout can
2062  * be updated if failed to create, so caller wouldn't keep try while
2063  * running out of resource.
2064  */
2065 static int
2066 ksocknal_connd_check_start(time64_t sec, long *timeout)
2067 {
2068         char name[16];
2069         int rc;
2070         int total = ksocknal_data.ksnd_connd_starting +
2071                     ksocknal_data.ksnd_connd_running;
2072
2073         if (unlikely(ksocknal_data.ksnd_init < SOCKNAL_INIT_ALL)) {
2074                 /* still in initializing */
2075                 return 0;
2076         }
2077
2078         if (total >= *ksocknal_tunables.ksnd_nconnds_max ||
2079             total > ksocknal_data.ksnd_connd_connecting + SOCKNAL_CONND_RESV) {
2080                 /* can't create more connd, or still have enough
2081                  * threads to handle more connecting */
2082                 return 0;
2083         }
2084
2085         if (list_empty(&ksocknal_data.ksnd_connd_routes)) {
2086                 /* no pending connecting request */
2087                 return 0;
2088         }
2089
2090         if (sec - ksocknal_data.ksnd_connd_failed_stamp <= 1) {
2091                 /* may run out of resource, retry later */
2092                 *timeout = cfs_time_seconds(1);
2093                 return 0;
2094         }
2095
2096         if (ksocknal_data.ksnd_connd_starting > 0) {
2097                 /* serialize starting to avoid flood */
2098                 return 0;
2099         }
2100
2101         ksocknal_data.ksnd_connd_starting_stamp = sec;
2102         ksocknal_data.ksnd_connd_starting++;
2103         spin_unlock_bh(&ksocknal_data.ksnd_connd_lock);
2104
2105         /* NB: total is the next id */
2106         snprintf(name, sizeof(name), "socknal_cd%02d", total);
2107         rc = ksocknal_thread_start(ksocknal_connd, NULL, name);
2108
2109         spin_lock_bh(&ksocknal_data.ksnd_connd_lock);
2110         if (rc == 0)
2111                 return 1;
2112
2113         /* we tried ... */
2114         LASSERT(ksocknal_data.ksnd_connd_starting > 0);
2115         ksocknal_data.ksnd_connd_starting--;
2116         ksocknal_data.ksnd_connd_failed_stamp = ktime_get_real_seconds();
2117
2118         return 1;
2119 }
2120
2121 /*
2122  * check whether current thread can exit, it will return 1 if there are too
2123  * many threads and no creating in past 120 seconds.
2124  * Also, this function may update @timeout to make caller come back
2125  * again to recheck these conditions.
2126  */
2127 static int
2128 ksocknal_connd_check_stop(time64_t sec, long *timeout)
2129 {
2130         int val;
2131
2132         if (unlikely(ksocknal_data.ksnd_init < SOCKNAL_INIT_ALL)) {
2133                 /* still in initializing */
2134                 return 0;
2135         }
2136
2137         if (ksocknal_data.ksnd_connd_starting > 0) {
2138                 /* in progress of starting new thread */
2139                 return 0;
2140         }
2141
2142         if (ksocknal_data.ksnd_connd_running <=
2143             *ksocknal_tunables.ksnd_nconnds) { /* can't shrink */
2144                 return 0;
2145         }
2146
2147         /* created thread in past 120 seconds? */
2148         val = (int)(ksocknal_data.ksnd_connd_starting_stamp +
2149                     SOCKNAL_CONND_TIMEOUT - sec);
2150
2151         *timeout = (val > 0) ? cfs_time_seconds(val) :
2152                                cfs_time_seconds(SOCKNAL_CONND_TIMEOUT);
2153         if (val > 0)
2154                 return 0;
2155
2156         /* no creating in past 120 seconds */
2157
2158         return ksocknal_data.ksnd_connd_running >
2159                ksocknal_data.ksnd_connd_connecting + SOCKNAL_CONND_RESV;
2160 }
2161
2162 /* Go through connd_routes queue looking for a route that we can process
2163  * right now, @timeout_p can be updated if we need to come back later */
2164 static struct ksock_route *
2165 ksocknal_connd_get_route_locked(signed long *timeout_p)
2166 {
2167         time64_t now = ktime_get_seconds();
2168         struct ksock_route *route;
2169
2170         /* connd_routes can contain both pending and ordinary routes */
2171         list_for_each_entry(route, &ksocknal_data.ksnd_connd_routes,
2172                                  ksnr_connd_list) {
2173
2174                 if (route->ksnr_retry_interval == 0 ||
2175                     now >= route->ksnr_timeout)
2176                         return route;
2177
2178                 if (*timeout_p == MAX_SCHEDULE_TIMEOUT ||
2179                     *timeout_p > cfs_time_seconds(route->ksnr_timeout - now))
2180                         *timeout_p = cfs_time_seconds(route->ksnr_timeout - now);
2181         }
2182
2183         return NULL;
2184 }
2185
2186 int
2187 ksocknal_connd(void *arg)
2188 {
2189         spinlock_t *connd_lock = &ksocknal_data.ksnd_connd_lock;
2190         struct ksock_connreq *cr;
2191         wait_queue_entry_t wait;
2192         int cons_retry = 0;
2193
2194         init_waitqueue_entry(&wait, current);
2195
2196         spin_lock_bh(connd_lock);
2197
2198         LASSERT(ksocknal_data.ksnd_connd_starting > 0);
2199         ksocknal_data.ksnd_connd_starting--;
2200         ksocknal_data.ksnd_connd_running++;
2201
2202         while (!ksocknal_data.ksnd_shuttingdown) {
2203                 struct ksock_route *route = NULL;
2204                 time64_t sec = ktime_get_real_seconds();
2205                 long timeout = MAX_SCHEDULE_TIMEOUT;
2206                 int  dropped_lock = 0;
2207
2208                 if (ksocknal_connd_check_stop(sec, &timeout)) {
2209                         /* wakeup another one to check stop */
2210                         wake_up(&ksocknal_data.ksnd_connd_waitq);
2211                         break;
2212                 }
2213
2214                 if (ksocknal_connd_check_start(sec, &timeout)) {
2215                         /* created new thread */
2216                         dropped_lock = 1;
2217                 }
2218
2219                 if (!list_empty(&ksocknal_data.ksnd_connd_connreqs)) {
2220                         /* Connection accepted by the listener */
2221                         cr = list_entry(ksocknal_data.ksnd_connd_connreqs.next,
2222                                         struct ksock_connreq, ksncr_list);
2223
2224                         list_del(&cr->ksncr_list);
2225                         spin_unlock_bh(connd_lock);
2226                         dropped_lock = 1;
2227
2228                         ksocknal_create_conn(cr->ksncr_ni, NULL,
2229                                              cr->ksncr_sock, SOCKLND_CONN_NONE);
2230                         lnet_ni_decref(cr->ksncr_ni);
2231                         LIBCFS_FREE(cr, sizeof(*cr));
2232
2233                         spin_lock_bh(connd_lock);
2234                 }
2235
2236                 /* Only handle an outgoing connection request if there
2237                  * is a thread left to handle incoming connections and
2238                  * create new connd */
2239                 if (ksocknal_data.ksnd_connd_connecting + SOCKNAL_CONND_RESV <
2240                     ksocknal_data.ksnd_connd_running) {
2241                         route = ksocknal_connd_get_route_locked(&timeout);
2242                 }
2243                 if (route != NULL) {
2244                         list_del(&route->ksnr_connd_list);
2245                         ksocknal_data.ksnd_connd_connecting++;
2246                         spin_unlock_bh(connd_lock);
2247                         dropped_lock = 1;
2248
2249                         if (ksocknal_connect(route)) {
2250                                 /* consecutive retry */
2251                                 if (cons_retry++ > SOCKNAL_INSANITY_RECONN) {
2252                                         CWARN("massive consecutive "
2253                                               "re-connecting to %pI4h\n",
2254                                               &route->ksnr_ipaddr);
2255                                         cons_retry = 0;
2256                                 }
2257                         } else {
2258                                 cons_retry = 0;
2259                         }
2260
2261                         ksocknal_route_decref(route);
2262
2263                         spin_lock_bh(connd_lock);
2264                         ksocknal_data.ksnd_connd_connecting--;
2265                 }
2266
2267                 if (dropped_lock) {
2268                         if (!need_resched())
2269                                 continue;
2270                         spin_unlock_bh(connd_lock);
2271                         cond_resched();
2272                         spin_lock_bh(connd_lock);
2273                         continue;
2274                 }
2275
2276                 /* Nothing to do for 'timeout'  */
2277                 set_current_state(TASK_INTERRUPTIBLE);
2278                 add_wait_queue_exclusive(&ksocknal_data.ksnd_connd_waitq, &wait);
2279                 spin_unlock_bh(connd_lock);
2280
2281                 schedule_timeout(timeout);
2282
2283                 remove_wait_queue(&ksocknal_data.ksnd_connd_waitq, &wait);
2284                 spin_lock_bh(connd_lock);
2285         }
2286         ksocknal_data.ksnd_connd_running--;
2287         spin_unlock_bh(connd_lock);
2288
2289         ksocknal_thread_fini();
2290         return 0;
2291 }
2292
2293 static struct ksock_conn *
2294 ksocknal_find_timed_out_conn(struct ksock_peer_ni *peer_ni)
2295 {
2296         /* We're called with a shared lock on ksnd_global_lock */
2297         struct ksock_conn *conn;
2298         struct list_head *ctmp;
2299         struct ksock_tx *tx;
2300
2301         list_for_each(ctmp, &peer_ni->ksnp_conns) {
2302                 int error;
2303
2304                 conn = list_entry(ctmp, struct ksock_conn, ksnc_list);
2305
2306                 /* Don't need the {get,put}connsock dance to deref ksnc_sock */
2307                 LASSERT (!conn->ksnc_closing);
2308
2309                 error = conn->ksnc_sock->sk->sk_err;
2310                 if (error != 0) {
2311                         ksocknal_conn_addref(conn);
2312
2313                         switch (error) {
2314                         case ECONNRESET:
2315                                 CNETERR("A connection with %s "
2316                                         "(%pI4h:%d) was reset; "
2317                                         "it may have rebooted.\n",
2318                                         libcfs_id2str(peer_ni->ksnp_id),
2319                                         &conn->ksnc_ipaddr,
2320                                         conn->ksnc_port);
2321                                 break;
2322                         case ETIMEDOUT:
2323                                 CNETERR("A connection with %s "
2324                                         "(%pI4h:%d) timed out; the "
2325                                         "network or node may be down.\n",
2326                                         libcfs_id2str(peer_ni->ksnp_id),
2327                                         &conn->ksnc_ipaddr,
2328                                         conn->ksnc_port);
2329                                 break;
2330                         default:
2331                                 CNETERR("An unexpected network error %d "
2332                                         "occurred with %s "
2333                                         "(%pI4h:%d\n", error,
2334                                         libcfs_id2str(peer_ni->ksnp_id),
2335                                         &conn->ksnc_ipaddr,
2336                                         conn->ksnc_port);
2337                                 break;
2338                         }
2339
2340                         return (conn);
2341                 }
2342
2343                 if (conn->ksnc_rx_started &&
2344                     ktime_get_seconds() >= conn->ksnc_rx_deadline) {
2345                         /* Timed out incomplete incoming message */
2346                         ksocknal_conn_addref(conn);
2347                         CNETERR("Timeout receiving from %s (%pI4h:%d), "
2348                                 "state %d wanted %d left %d\n",
2349                                 libcfs_id2str(peer_ni->ksnp_id),
2350                                 &conn->ksnc_ipaddr,
2351                                 conn->ksnc_port,
2352                                 conn->ksnc_rx_state,
2353                                 conn->ksnc_rx_nob_wanted,
2354                                 conn->ksnc_rx_nob_left);
2355                         return (conn);
2356                 }
2357
2358                 if ((!list_empty(&conn->ksnc_tx_queue) ||
2359                      conn->ksnc_sock->sk->sk_wmem_queued != 0) &&
2360                     ktime_get_seconds() >= conn->ksnc_tx_deadline) {
2361                         /* Timed out messages queued for sending or
2362                          * buffered in the socket's send buffer */
2363                         ksocknal_conn_addref(conn);
2364                         list_for_each_entry(tx, &conn->ksnc_tx_queue,
2365                                             tx_list)
2366                                 tx->tx_hstatus =
2367                                         LNET_MSG_STATUS_LOCAL_TIMEOUT;
2368                         CNETERR("Timeout sending data to %s (%pI4h:%d) "
2369                                 "the network or that node may be down.\n",
2370                                 libcfs_id2str(peer_ni->ksnp_id),
2371                                 &conn->ksnc_ipaddr, conn->ksnc_port);
2372                         return (conn);
2373                 }
2374         }
2375
2376         return (NULL);
2377 }
2378
2379 static inline void
2380 ksocknal_flush_stale_txs(struct ksock_peer_ni *peer_ni)
2381 {
2382         struct ksock_tx *tx;
2383         LIST_HEAD(stale_txs);
2384
2385         write_lock_bh(&ksocknal_data.ksnd_global_lock);
2386
2387         while (!list_empty(&peer_ni->ksnp_tx_queue)) {
2388                 tx = list_entry(peer_ni->ksnp_tx_queue.next,
2389                                 struct ksock_tx, tx_list);
2390
2391                 if (ktime_get_seconds() < tx->tx_deadline)
2392                         break;
2393
2394                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_TIMEOUT;
2395
2396                 list_move_tail(&tx->tx_list, &stale_txs);
2397         }
2398
2399         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
2400
2401         ksocknal_txlist_done(peer_ni->ksnp_ni, &stale_txs, -ETIMEDOUT);
2402 }
2403
2404 static int
2405 ksocknal_send_keepalive_locked(struct ksock_peer_ni *peer_ni)
2406 __must_hold(&ksocknal_data.ksnd_global_lock)
2407 {
2408         struct ksock_sched *sched;
2409         struct ksock_conn *conn;
2410         struct ksock_tx *tx;
2411
2412         /* last_alive will be updated by create_conn */
2413         if (list_empty(&peer_ni->ksnp_conns))
2414                 return 0;
2415
2416         if (peer_ni->ksnp_proto != &ksocknal_protocol_v3x)
2417                 return 0;
2418
2419         if (*ksocknal_tunables.ksnd_keepalive <= 0 ||
2420             ktime_get_seconds() < peer_ni->ksnp_last_alive +
2421                                   *ksocknal_tunables.ksnd_keepalive)
2422                 return 0;
2423
2424         if (ktime_get_seconds() < peer_ni->ksnp_send_keepalive)
2425                 return 0;
2426
2427         /* retry 10 secs later, so we wouldn't put pressure
2428          * on this peer_ni if we failed to send keepalive this time */
2429         peer_ni->ksnp_send_keepalive = ktime_get_seconds() + 10;
2430
2431         conn = ksocknal_find_conn_locked(peer_ni, NULL, 1);
2432         if (conn != NULL) {
2433                 sched = conn->ksnc_scheduler;
2434
2435                 spin_lock_bh(&sched->kss_lock);
2436                 if (!list_empty(&conn->ksnc_tx_queue)) {
2437                         spin_unlock_bh(&sched->kss_lock);
2438                         /* there is an queued ACK, don't need keepalive */
2439                         return 0;
2440                 }
2441
2442                 spin_unlock_bh(&sched->kss_lock);
2443         }
2444
2445         read_unlock(&ksocknal_data.ksnd_global_lock);
2446
2447         /* cookie = 1 is reserved for keepalive PING */
2448         tx = ksocknal_alloc_tx_noop(1, 1);
2449         if (tx == NULL) {
2450                 read_lock(&ksocknal_data.ksnd_global_lock);
2451                 return -ENOMEM;
2452         }
2453
2454         if (ksocknal_launch_packet(peer_ni->ksnp_ni, tx, peer_ni->ksnp_id) == 0) {
2455                 read_lock(&ksocknal_data.ksnd_global_lock);
2456                 return 1;
2457         }
2458
2459         ksocknal_free_tx(tx);
2460         read_lock(&ksocknal_data.ksnd_global_lock);
2461
2462         return -EIO;
2463 }
2464
2465
2466 static void
2467 ksocknal_check_peer_timeouts(int idx)
2468 {
2469         struct hlist_head *peers = &ksocknal_data.ksnd_peers[idx];
2470         struct ksock_peer_ni *peer_ni;
2471         struct ksock_conn *conn;
2472         struct ksock_tx *tx;
2473
2474  again:
2475         /* NB. We expect to have a look at all the peers and not find any
2476          * connections to time out, so we just use a shared lock while we
2477          * take a look...
2478          */
2479         read_lock(&ksocknal_data.ksnd_global_lock);
2480
2481         hlist_for_each_entry(peer_ni, peers, ksnp_list) {
2482                 struct ksock_tx *tx_stale;
2483                 time64_t deadline = 0;
2484                 int resid = 0;
2485                 int n = 0;
2486
2487                 if (ksocknal_send_keepalive_locked(peer_ni) != 0) {
2488                         read_unlock(&ksocknal_data.ksnd_global_lock);
2489                         goto again;
2490                 }
2491
2492                 conn = ksocknal_find_timed_out_conn(peer_ni);
2493
2494                 if (conn != NULL) {
2495                         read_unlock(&ksocknal_data.ksnd_global_lock);
2496
2497                         ksocknal_close_conn_and_siblings(conn, -ETIMEDOUT);
2498
2499                         /* NB we won't find this one again, but we can't
2500                          * just proceed with the next peer_ni, since we dropped
2501                          * ksnd_global_lock and it might be dead already!
2502                          */
2503                         ksocknal_conn_decref(conn);
2504                         goto again;
2505                 }
2506
2507                 /* we can't process stale txs right here because we're
2508                  * holding only shared lock
2509                  */
2510                 if (!list_empty(&peer_ni->ksnp_tx_queue)) {
2511                         struct ksock_tx *tx;
2512
2513                         tx = list_entry(peer_ni->ksnp_tx_queue.next,
2514                                         struct ksock_tx, tx_list);
2515                         if (ktime_get_seconds() >= tx->tx_deadline) {
2516                                 ksocknal_peer_addref(peer_ni);
2517                                 read_unlock(&ksocknal_data.ksnd_global_lock);
2518
2519                                 ksocknal_flush_stale_txs(peer_ni);
2520
2521                                 ksocknal_peer_decref(peer_ni);
2522                                 goto again;
2523                         }
2524                 }
2525
2526                 if (list_empty(&peer_ni->ksnp_zc_req_list))
2527                         continue;
2528
2529                 tx_stale = NULL;
2530                 spin_lock(&peer_ni->ksnp_lock);
2531                 list_for_each_entry(tx, &peer_ni->ksnp_zc_req_list, tx_zc_list) {
2532                         if (ktime_get_seconds() < tx->tx_deadline)
2533                                 break;
2534                         /* ignore the TX if connection is being closed */
2535                         if (tx->tx_conn->ksnc_closing)
2536                                 continue;
2537                         n++;
2538                         if (tx_stale == NULL)
2539                                 tx_stale = tx;
2540                 }
2541
2542                 if (tx_stale == NULL) {
2543                         spin_unlock(&peer_ni->ksnp_lock);
2544                         continue;
2545                 }
2546
2547                 deadline = tx_stale->tx_deadline;
2548                 resid    = tx_stale->tx_resid;
2549                 conn     = tx_stale->tx_conn;
2550                 ksocknal_conn_addref(conn);
2551
2552                 spin_unlock(&peer_ni->ksnp_lock);
2553                 read_unlock(&ksocknal_data.ksnd_global_lock);
2554
2555                 CERROR("Total %d stale ZC_REQs for peer_ni %s detected; the "
2556                        "oldest(%p) timed out %lld secs ago, "
2557                        "resid: %d, wmem: %d\n",
2558                        n, libcfs_nid2str(peer_ni->ksnp_id.nid), tx_stale,
2559                        ktime_get_seconds() - deadline,
2560                        resid, conn->ksnc_sock->sk->sk_wmem_queued);
2561
2562                 ksocknal_close_conn_and_siblings (conn, -ETIMEDOUT);
2563                 ksocknal_conn_decref(conn);
2564                 goto again;
2565         }
2566
2567         read_unlock(&ksocknal_data.ksnd_global_lock);
2568 }
2569
2570 int ksocknal_reaper(void *arg)
2571 {
2572         wait_queue_entry_t wait;
2573         struct ksock_conn *conn;
2574         struct ksock_sched *sched;
2575         LIST_HEAD(enomem_conns);
2576         int nenomem_conns;
2577         time64_t timeout;
2578         int i;
2579         int peer_index = 0;
2580         time64_t deadline = ktime_get_seconds();
2581
2582         init_waitqueue_entry(&wait, current);
2583
2584         spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
2585
2586         while (!ksocknal_data.ksnd_shuttingdown) {
2587                 if (!list_empty(&ksocknal_data.ksnd_deathrow_conns)) {
2588                         conn = list_entry(ksocknal_data.ksnd_deathrow_conns.next,
2589                                           struct ksock_conn, ksnc_list);
2590                         list_del(&conn->ksnc_list);
2591
2592                         spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
2593
2594                         ksocknal_terminate_conn(conn);
2595                         ksocknal_conn_decref(conn);
2596
2597                         spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
2598                         continue;
2599                 }
2600
2601                 if (!list_empty(&ksocknal_data.ksnd_zombie_conns)) {
2602                         conn = list_entry(ksocknal_data.ksnd_zombie_conns.next,
2603                                           struct ksock_conn, ksnc_list);
2604                         list_del(&conn->ksnc_list);
2605
2606                         spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
2607
2608                         ksocknal_destroy_conn(conn);
2609
2610                         spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
2611                         continue;
2612                 }
2613
2614                 list_splice_init(&ksocknal_data.ksnd_enomem_conns,
2615                                  &enomem_conns);
2616
2617                 spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
2618
2619                 /* reschedule all the connections that stalled with ENOMEM... */
2620                 nenomem_conns = 0;
2621                 while (!list_empty(&enomem_conns)) {
2622                         conn = list_entry(enomem_conns.next,
2623                                           struct ksock_conn, ksnc_tx_list);
2624                         list_del(&conn->ksnc_tx_list);
2625
2626                         sched = conn->ksnc_scheduler;
2627
2628                         spin_lock_bh(&sched->kss_lock);
2629
2630                         LASSERT(conn->ksnc_tx_scheduled);
2631                         conn->ksnc_tx_ready = 1;
2632                         list_add_tail(&conn->ksnc_tx_list,
2633                                           &sched->kss_tx_conns);
2634                         wake_up(&sched->kss_waitq);
2635
2636                         spin_unlock_bh(&sched->kss_lock);
2637                         nenomem_conns++;
2638                 }
2639
2640                 /* careful with the jiffy wrap... */
2641                 while ((timeout = deadline - ktime_get_seconds()) <= 0) {
2642                         const int n = 4;
2643                         const int p = 1;
2644                         int  chunk = HASH_SIZE(ksocknal_data.ksnd_peers);
2645                         unsigned int lnd_timeout;
2646
2647                         /* Time to check for timeouts on a few more peers: I
2648                          * do checks every 'p' seconds on a proportion of the
2649                          * peer_ni table and I need to check every connection
2650                          * 'n' times within a timeout interval, to ensure I
2651                          * detect a timeout on any connection within (n+1)/n
2652                          * times the timeout interval.
2653                          */
2654
2655                         lnd_timeout = ksocknal_timeout();
2656                         if (lnd_timeout > n * p)
2657                                 chunk = (chunk * n * p) / lnd_timeout;
2658                         if (chunk == 0)
2659                                 chunk = 1;
2660
2661                         for (i = 0; i < chunk; i++) {
2662                                 ksocknal_check_peer_timeouts(peer_index);
2663                                 peer_index = (peer_index + 1) %
2664                                         HASH_SIZE(ksocknal_data.ksnd_peers);
2665                         }
2666
2667                         deadline += p;
2668                 }
2669
2670                 if (nenomem_conns != 0) {
2671                         /* Reduce my timeout if I rescheduled ENOMEM conns.
2672                          * This also prevents me getting woken immediately
2673                          * if any go back on my enomem list. */
2674                         timeout = SOCKNAL_ENOMEM_RETRY;
2675                 }
2676                 ksocknal_data.ksnd_reaper_waketime = ktime_get_seconds() +
2677                                                      timeout;
2678
2679                 set_current_state(TASK_INTERRUPTIBLE);
2680                 add_wait_queue(&ksocknal_data.ksnd_reaper_waitq, &wait);
2681
2682                 if (!ksocknal_data.ksnd_shuttingdown &&
2683                     list_empty(&ksocknal_data.ksnd_deathrow_conns) &&
2684                     list_empty(&ksocknal_data.ksnd_zombie_conns))
2685                         schedule_timeout(cfs_time_seconds(timeout));
2686
2687                 set_current_state(TASK_RUNNING);
2688                 remove_wait_queue(&ksocknal_data.ksnd_reaper_waitq, &wait);
2689
2690                 spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
2691         }
2692
2693         spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
2694
2695         ksocknal_thread_fini();
2696         return 0;
2697 }