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