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