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