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