Whamcloud - gitweb
LU-9120 lnet: health error simulation
[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.hpdd.intel.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                 if (rc)
413                         CERROR("tx failure rc = %d, hstatus = %d\n", rc,
414                                hstatus);
415                 lnetmsg->msg_health_status = hstatus;
416                 lnet_finalize(lnetmsg, rc);
417         }
418
419         EXIT;
420 }
421
422 void
423 ksocknal_txlist_done(struct lnet_ni *ni, struct list_head *txlist, int error)
424 {
425         struct ksock_tx *tx;
426
427         while (!list_empty(txlist)) {
428                 tx = list_entry(txlist->next, struct ksock_tx, tx_list);
429
430                 if (error && tx->tx_lnetmsg != NULL) {
431                         CNETERR("Deleting packet type %d len %d %s->%s\n",
432                                 le32_to_cpu(tx->tx_lnetmsg->msg_hdr.type),
433                                 le32_to_cpu(tx->tx_lnetmsg->msg_hdr.payload_length),
434                                 libcfs_nid2str(le64_to_cpu(tx->tx_lnetmsg->msg_hdr.src_nid)),
435                                 libcfs_nid2str(le64_to_cpu(tx->tx_lnetmsg->msg_hdr.dest_nid)));
436                 } else if (error) {
437                         CNETERR("Deleting noop packet\n");
438                 }
439
440                 list_del(&tx->tx_list);
441
442                 if (tx->tx_hstatus == LNET_MSG_STATUS_OK) {
443                         if (error == -ETIMEDOUT)
444                                 tx->tx_hstatus =
445                                   LNET_MSG_STATUS_LOCAL_TIMEOUT;
446                         else if (error == -ENETDOWN ||
447                                  error == -EHOSTUNREACH ||
448                                  error == -ENETUNREACH)
449                                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_DROPPED;
450                         /*
451                          * for all other errors we don't want to
452                          * retransmit
453                          */
454                         else if (error)
455                                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
456                 }
457
458                 LASSERT(atomic_read(&tx->tx_refcount) == 1);
459                 ksocknal_tx_done(ni, tx, error);
460         }
461 }
462
463 static void
464 ksocknal_check_zc_req(struct ksock_tx *tx)
465 {
466         struct ksock_conn *conn = tx->tx_conn;
467         struct ksock_peer_ni *peer_ni = conn->ksnc_peer;
468
469         /* Set tx_msg.ksm_zc_cookies[0] to a unique non-zero cookie and add tx
470          * to ksnp_zc_req_list if some fragment of this message should be sent
471          * zero-copy.  Our peer_ni will send an ACK containing this cookie when
472          * she has received this message to tell us we can signal completion.
473          * tx_msg.ksm_zc_cookies[0] remains non-zero while tx is on
474          * ksnp_zc_req_list. */
475         LASSERT (tx->tx_msg.ksm_type != KSOCK_MSG_NOOP);
476         LASSERT (tx->tx_zc_capable);
477
478         tx->tx_zc_checked = 1;
479
480         if (conn->ksnc_proto == &ksocknal_protocol_v1x ||
481             !conn->ksnc_zc_capable)
482                 return;
483
484         /* assign cookie and queue tx to pending list, it will be released when
485          * a matching ack is received. See ksocknal_handle_zcack() */
486
487         ksocknal_tx_addref(tx);
488
489         spin_lock(&peer_ni->ksnp_lock);
490
491         /* ZC_REQ is going to be pinned to the peer_ni */
492         tx->tx_deadline = ktime_get_seconds() +
493                           lnet_get_lnd_timeout();
494
495         LASSERT (tx->tx_msg.ksm_zc_cookies[0] == 0);
496
497         tx->tx_msg.ksm_zc_cookies[0] = peer_ni->ksnp_zc_next_cookie++;
498
499         if (peer_ni->ksnp_zc_next_cookie == 0)
500                 peer_ni->ksnp_zc_next_cookie = SOCKNAL_KEEPALIVE_PING + 1;
501
502         list_add_tail(&tx->tx_zc_list, &peer_ni->ksnp_zc_req_list);
503
504         spin_unlock(&peer_ni->ksnp_lock);
505 }
506
507 static void
508 ksocknal_uncheck_zc_req(struct ksock_tx *tx)
509 {
510         struct ksock_peer_ni *peer_ni = tx->tx_conn->ksnc_peer;
511
512         LASSERT(tx->tx_msg.ksm_type != KSOCK_MSG_NOOP);
513         LASSERT(tx->tx_zc_capable);
514
515         tx->tx_zc_checked = 0;
516
517         spin_lock(&peer_ni->ksnp_lock);
518
519         if (tx->tx_msg.ksm_zc_cookies[0] == 0) {
520                 /* Not waiting for an ACK */
521                 spin_unlock(&peer_ni->ksnp_lock);
522                 return;
523         }
524
525         tx->tx_msg.ksm_zc_cookies[0] = 0;
526         list_del(&tx->tx_zc_list);
527
528         spin_unlock(&peer_ni->ksnp_lock);
529
530         ksocknal_tx_decref(tx);
531 }
532
533 static int
534 ksocknal_process_transmit(struct ksock_conn *conn, struct ksock_tx *tx)
535 {
536         int rc;
537         bool error_sim = false;
538
539         if (lnet_send_error_simulation(tx->tx_lnetmsg, &tx->tx_hstatus)) {
540                 error_sim = true;
541                 rc = -EINVAL;
542                 goto simulate_error;
543         }
544
545         if (tx->tx_zc_capable && !tx->tx_zc_checked)
546                 ksocknal_check_zc_req(tx);
547
548         rc = ksocknal_transmit (conn, tx);
549
550         CDEBUG (D_NET, "send(%d) %d\n", tx->tx_resid, rc);
551
552         if (tx->tx_resid == 0) {
553                 /* Sent everything OK */
554                 LASSERT (rc == 0);
555
556                 return (0);
557         }
558
559         if (rc == -EAGAIN)
560                 return (rc);
561
562         if (rc == -ENOMEM) {
563                 static int counter;
564
565                 counter++;   /* exponential backoff warnings */
566                 if ((counter & (-counter)) == counter)
567                         CWARN("%u ENOMEM tx %p (%u allocated)\n",
568                               counter, conn, atomic_read(&libcfs_kmemory));
569
570                 /* Queue on ksnd_enomem_conns for retry after a timeout */
571                 spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
572
573                 /* enomem list takes over scheduler's ref... */
574                 LASSERT (conn->ksnc_tx_scheduled);
575                 list_add_tail(&conn->ksnc_tx_list,
576                                   &ksocknal_data.ksnd_enomem_conns);
577                 if (ktime_get_seconds() + SOCKNAL_ENOMEM_RETRY <
578                     ksocknal_data.ksnd_reaper_waketime)
579                         wake_up(&ksocknal_data.ksnd_reaper_waitq);
580
581                 spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
582
583                 /*
584                  * set the health status of the message which determines
585                  * whether we should retry the transmit
586                  */
587                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
588                 return (rc);
589         }
590
591 simulate_error:
592
593         /* Actual error */
594         LASSERT(rc < 0);
595
596         if (!error_sim) {
597                 /*
598                 * set the health status of the message which determines
599                 * whether we should retry the transmit
600                 */
601                 if (rc == -ETIMEDOUT)
602                         tx->tx_hstatus = LNET_MSG_STATUS_REMOTE_TIMEOUT;
603                 else
604                         tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_ERROR;
605         }
606
607         if (!conn->ksnc_closing) {
608                 switch (rc) {
609                 case -ECONNRESET:
610                         LCONSOLE_WARN("Host %pI4h reset our connection "
611                                       "while we were sending data; it may have "
612                                       "rebooted.\n",
613                                       &conn->ksnc_ipaddr);
614                         break;
615                 default:
616                         LCONSOLE_WARN("There was an unexpected network error "
617                                       "while writing to %pI4h: %d.\n",
618                                       &conn->ksnc_ipaddr, rc);
619                         break;
620                 }
621                 CDEBUG(D_NET, "[%p] Error %d on write to %s ip %pI4h:%d\n",
622                        conn, rc, libcfs_id2str(conn->ksnc_peer->ksnp_id),
623                        &conn->ksnc_ipaddr, conn->ksnc_port);
624         }
625
626         if (tx->tx_zc_checked)
627                 ksocknal_uncheck_zc_req(tx);
628
629         /* it's not an error if conn is being closed */
630         ksocknal_close_conn_and_siblings(conn,
631                                           (conn->ksnc_closing) ? 0 : rc);
632
633         return rc;
634 }
635
636 static void
637 ksocknal_launch_connection_locked(struct ksock_route *route)
638 {
639
640         /* called holding write lock on ksnd_global_lock */
641
642         LASSERT (!route->ksnr_scheduled);
643         LASSERT (!route->ksnr_connecting);
644         LASSERT ((ksocknal_route_mask() & ~route->ksnr_connected) != 0);
645
646         route->ksnr_scheduled = 1;              /* scheduling conn for connd */
647         ksocknal_route_addref(route);           /* extra ref for connd */
648
649         spin_lock_bh(&ksocknal_data.ksnd_connd_lock);
650
651         list_add_tail(&route->ksnr_connd_list,
652                           &ksocknal_data.ksnd_connd_routes);
653         wake_up(&ksocknal_data.ksnd_connd_waitq);
654
655         spin_unlock_bh(&ksocknal_data.ksnd_connd_lock);
656 }
657
658 void
659 ksocknal_launch_all_connections_locked(struct ksock_peer_ni *peer_ni)
660 {
661         struct ksock_route *route;
662
663         /* called holding write lock on ksnd_global_lock */
664         for (;;) {
665                 /* launch any/all connections that need it */
666                 route = ksocknal_find_connectable_route_locked(peer_ni);
667                 if (route == NULL)
668                         return;
669
670                 ksocknal_launch_connection_locked(route);
671         }
672 }
673
674 struct ksock_conn *
675 ksocknal_find_conn_locked(struct ksock_peer_ni *peer_ni, struct ksock_tx *tx, int nonblk)
676 {
677         struct list_head *tmp;
678         struct ksock_conn *conn;
679         struct ksock_conn *typed = NULL;
680         struct ksock_conn *fallback = NULL;
681         int tnob = 0;
682         int fnob = 0;
683
684         list_for_each(tmp, &peer_ni->ksnp_conns) {
685                 struct ksock_conn *c = list_entry(tmp, struct ksock_conn,
686                                                   ksnc_list);
687                 int nob = atomic_read(&c->ksnc_tx_nob) +
688                           c->ksnc_sock->sk->sk_wmem_queued;
689                 int rc;
690
691                 LASSERT (!c->ksnc_closing);
692                 LASSERT (c->ksnc_proto != NULL &&
693                          c->ksnc_proto->pro_match_tx != NULL);
694
695                 rc = c->ksnc_proto->pro_match_tx(c, tx, nonblk);
696
697                 switch (rc) {
698                 default:
699                         LBUG();
700                 case SOCKNAL_MATCH_NO: /* protocol rejected the tx */
701                         continue;
702
703                 case SOCKNAL_MATCH_YES: /* typed connection */
704                         if (typed == NULL || tnob > nob ||
705                             (tnob == nob && *ksocknal_tunables.ksnd_round_robin &&
706                              typed->ksnc_tx_last_post > c->ksnc_tx_last_post)) {
707                                 typed = c;
708                                 tnob  = nob;
709                         }
710                         break;
711
712                 case SOCKNAL_MATCH_MAY: /* fallback connection */
713                         if (fallback == NULL || fnob > nob ||
714                             (fnob == nob && *ksocknal_tunables.ksnd_round_robin &&
715                              fallback->ksnc_tx_last_post > c->ksnc_tx_last_post)) {
716                                 fallback = c;
717                                 fnob     = nob;
718                         }
719                         break;
720                 }
721         }
722
723         /* prefer the typed selection */
724         conn = (typed != NULL) ? typed : fallback;
725
726         if (conn != NULL)
727                 conn->ksnc_tx_last_post = ktime_get_seconds();
728
729         return conn;
730 }
731
732 void
733 ksocknal_tx_prep(struct ksock_conn *conn, struct ksock_tx *tx)
734 {
735         conn->ksnc_proto->pro_pack(tx);
736
737         atomic_add (tx->tx_nob, &conn->ksnc_tx_nob);
738         ksocknal_conn_addref(conn); /* +1 ref for tx */
739         tx->tx_conn = conn;
740 }
741
742 void
743 ksocknal_queue_tx_locked(struct ksock_tx *tx, struct ksock_conn *conn)
744 {
745         struct ksock_sched *sched = conn->ksnc_scheduler;
746         struct ksock_msg *msg = &tx->tx_msg;
747         struct ksock_tx *ztx = NULL;
748         int bufnob = 0;
749
750         /* called holding global lock (read or irq-write) and caller may
751          * not have dropped this lock between finding conn and calling me,
752          * so we don't need the {get,put}connsock dance to deref
753          * ksnc_sock... */
754         LASSERT(!conn->ksnc_closing);
755
756         CDEBUG(D_NET, "Sending to %s ip %pI4h:%d\n",
757                libcfs_id2str(conn->ksnc_peer->ksnp_id),
758                &conn->ksnc_ipaddr, conn->ksnc_port);
759
760         ksocknal_tx_prep(conn, tx);
761
762         /* Ensure the frags we've been given EXACTLY match the number of
763          * bytes we want to send.  Many TCP/IP stacks disregard any total
764          * size parameters passed to them and just look at the frags.
765          *
766          * We always expect at least 1 mapped fragment containing the
767          * complete ksocknal message header. */
768         LASSERT (lnet_iov_nob (tx->tx_niov, tx->tx_iov) +
769                  lnet_kiov_nob(tx->tx_nkiov, tx->tx_kiov) ==
770                  (unsigned int)tx->tx_nob);
771         LASSERT (tx->tx_niov >= 1);
772         LASSERT (tx->tx_resid == tx->tx_nob);
773
774         CDEBUG (D_NET, "Packet %p type %d, nob %d niov %d nkiov %d\n",
775                 tx, (tx->tx_lnetmsg != NULL) ? tx->tx_lnetmsg->msg_hdr.type:
776                                                KSOCK_MSG_NOOP,
777                 tx->tx_nob, tx->tx_niov, tx->tx_nkiov);
778
779         bufnob = conn->ksnc_sock->sk->sk_wmem_queued;
780         spin_lock_bh(&sched->kss_lock);
781
782         if (list_empty(&conn->ksnc_tx_queue) && bufnob == 0) {
783                 /* First packet starts the timeout */
784                 conn->ksnc_tx_deadline = ktime_get_seconds() +
785                                          lnet_get_lnd_timeout();
786                 if (conn->ksnc_tx_bufnob > 0) /* something got ACKed */
787                         conn->ksnc_peer->ksnp_last_alive = ktime_get_seconds();
788                 conn->ksnc_tx_bufnob = 0;
789                 smp_mb(); /* order with adding to tx_queue */
790         }
791
792         if (msg->ksm_type == KSOCK_MSG_NOOP) {
793                 /* The packet is noop ZC ACK, try to piggyback the ack_cookie
794                  * on a normal packet so I don't need to send it */
795                 LASSERT (msg->ksm_zc_cookies[1] != 0);
796                 LASSERT (conn->ksnc_proto->pro_queue_tx_zcack != NULL);
797
798                 if (conn->ksnc_proto->pro_queue_tx_zcack(conn, tx, 0))
799                         ztx = tx; /* ZC ACK piggybacked on ztx release tx later */
800
801         } else {
802                 /* It's a normal packet - can it piggback a noop zc-ack that
803                  * has been queued already? */
804                 LASSERT (msg->ksm_zc_cookies[1] == 0);
805                 LASSERT (conn->ksnc_proto->pro_queue_tx_msg != NULL);
806
807                 ztx = conn->ksnc_proto->pro_queue_tx_msg(conn, tx);
808                 /* ztx will be released later */
809         }
810
811         if (ztx != NULL) {
812                 atomic_sub (ztx->tx_nob, &conn->ksnc_tx_nob);
813                 list_add_tail(&ztx->tx_list, &sched->kss_zombie_noop_txs);
814         }
815
816         if (conn->ksnc_tx_ready &&      /* able to send */
817             !conn->ksnc_tx_scheduled) { /* not scheduled to send */
818                 /* +1 ref for scheduler */
819                 ksocknal_conn_addref(conn);
820                 list_add_tail(&conn->ksnc_tx_list,
821                                    &sched->kss_tx_conns);
822                 conn->ksnc_tx_scheduled = 1;
823                 wake_up(&sched->kss_waitq);
824         }
825
826         spin_unlock_bh(&sched->kss_lock);
827 }
828
829
830 struct ksock_route *
831 ksocknal_find_connectable_route_locked(struct ksock_peer_ni *peer_ni)
832 {
833         time64_t now = ktime_get_seconds();
834         struct list_head *tmp;
835         struct ksock_route *route;
836
837         list_for_each(tmp, &peer_ni->ksnp_routes) {
838                 route = list_entry(tmp, struct ksock_route, ksnr_list);
839
840                 LASSERT (!route->ksnr_connecting || route->ksnr_scheduled);
841
842                 if (route->ksnr_scheduled)      /* connections being established */
843                         continue;
844
845                 /* all route types connected ? */
846                 if ((ksocknal_route_mask() & ~route->ksnr_connected) == 0)
847                         continue;
848
849                 if (!(route->ksnr_retry_interval == 0 || /* first attempt */
850                       now >= route->ksnr_timeout)) {
851                         CDEBUG(D_NET,
852                                "Too soon to retry route %pI4h "
853                                "(cnted %d, interval %lld, %lld secs later)\n",
854                                &route->ksnr_ipaddr,
855                                route->ksnr_connected,
856                                route->ksnr_retry_interval,
857                                route->ksnr_timeout - now);
858                         continue;
859                 }
860
861                 return (route);
862         }
863
864         return (NULL);
865 }
866
867 struct ksock_route *
868 ksocknal_find_connecting_route_locked(struct ksock_peer_ni *peer_ni)
869 {
870         struct list_head *tmp;
871         struct ksock_route *route;
872
873         list_for_each(tmp, &peer_ni->ksnp_routes) {
874                 route = list_entry(tmp, struct ksock_route, ksnr_list);
875
876                 LASSERT (!route->ksnr_connecting || route->ksnr_scheduled);
877
878                 if (route->ksnr_scheduled)
879                         return (route);
880         }
881
882         return (NULL);
883 }
884
885 int
886 ksocknal_launch_packet(struct lnet_ni *ni, struct ksock_tx *tx,
887                        struct lnet_process_id id)
888 {
889         struct ksock_peer_ni *peer_ni;
890         struct ksock_conn *conn;
891         rwlock_t *g_lock;
892         int retry;
893         int rc;
894
895         LASSERT (tx->tx_conn == NULL);
896
897         g_lock = &ksocknal_data.ksnd_global_lock;
898
899         for (retry = 0;; retry = 1) {
900                 read_lock(g_lock);
901                 peer_ni = ksocknal_find_peer_locked(ni, id);
902                 if (peer_ni != NULL) {
903                         if (ksocknal_find_connectable_route_locked(peer_ni) == NULL) {
904                                 conn = ksocknal_find_conn_locked(peer_ni, tx, tx->tx_nonblk);
905                                 if (conn != NULL) {
906                                         /* I've got no routes that need to be
907                                          * connecting and I do have an actual
908                                          * connection... */
909                                         ksocknal_queue_tx_locked (tx, conn);
910                                         read_unlock(g_lock);
911                                         return (0);
912                                 }
913                         }
914                 }
915
916                 /* I'll need a write lock... */
917                 read_unlock(g_lock);
918
919                 write_lock_bh(g_lock);
920
921                 peer_ni = ksocknal_find_peer_locked(ni, id);
922                 if (peer_ni != NULL)
923                         break;
924
925                 write_unlock_bh(g_lock);
926
927                 if ((id.pid & LNET_PID_USERFLAG) != 0) {
928                         CERROR("Refusing to create a connection to "
929                                "userspace process %s\n", libcfs_id2str(id));
930                         return -EHOSTUNREACH;
931                 }
932
933                 if (retry) {
934                         CERROR("Can't find peer_ni %s\n", libcfs_id2str(id));
935                         return -EHOSTUNREACH;
936                 }
937
938                 rc = ksocknal_add_peer(ni, id,
939                                        LNET_NIDADDR(id.nid),
940                                        lnet_acceptor_port());
941                 if (rc != 0) {
942                         CERROR("Can't add peer_ni %s: %d\n",
943                                libcfs_id2str(id), rc);
944                         return rc;
945                 }
946         }
947
948         ksocknal_launch_all_connections_locked(peer_ni);
949
950         conn = ksocknal_find_conn_locked(peer_ni, tx, tx->tx_nonblk);
951         if (conn != NULL) {
952                 /* Connection exists; queue message on it */
953                 ksocknal_queue_tx_locked (tx, conn);
954                 write_unlock_bh(g_lock);
955                 return (0);
956         }
957
958         if (peer_ni->ksnp_accepting > 0 ||
959             ksocknal_find_connecting_route_locked (peer_ni) != NULL) {
960                 /* the message is going to be pinned to the peer_ni */
961                 tx->tx_deadline = ktime_get_seconds() +
962                                   lnet_get_lnd_timeout();
963
964                 /* Queue the message until a connection is established */
965                 list_add_tail(&tx->tx_list, &peer_ni->ksnp_tx_queue);
966                 write_unlock_bh(g_lock);
967                 return 0;
968         }
969
970         write_unlock_bh(g_lock);
971
972         /* NB Routes may be ignored if connections to them failed recently */
973         CNETERR("No usable routes to %s\n", libcfs_id2str(id));
974         return (-EHOSTUNREACH);
975 }
976
977 int
978 ksocknal_send(struct lnet_ni *ni, void *private, struct lnet_msg *lntmsg)
979 {
980         int mpflag = 1;
981         int type = lntmsg->msg_type;
982         struct lnet_process_id target = lntmsg->msg_target;
983         unsigned int      payload_niov = lntmsg->msg_niov;
984         struct kvec *payload_iov = lntmsg->msg_iov;
985         lnet_kiov_t      *payload_kiov = lntmsg->msg_kiov;
986         unsigned int      payload_offset = lntmsg->msg_offset;
987         unsigned int      payload_nob = lntmsg->msg_len;
988         struct ksock_tx *tx;
989         int               desc_size;
990         int               rc;
991
992         /* NB 'private' is different depending on what we're sending.
993          * Just ignore it... */
994
995         CDEBUG(D_NET, "sending %u bytes in %d frags to %s\n",
996                payload_nob, payload_niov, libcfs_id2str(target));
997
998         LASSERT (payload_nob == 0 || payload_niov > 0);
999         LASSERT (payload_niov <= LNET_MAX_IOV);
1000         /* payload is either all vaddrs or all pages */
1001         LASSERT (!(payload_kiov != NULL && payload_iov != NULL));
1002         LASSERT (!in_interrupt ());
1003
1004         if (payload_iov != NULL)
1005                 desc_size = offsetof(struct ksock_tx,
1006                                      tx_frags.virt.iov[1 + payload_niov]);
1007         else
1008                 desc_size = offsetof(struct ksock_tx,
1009                                      tx_frags.paged.kiov[payload_niov]);
1010
1011         if (lntmsg->msg_vmflush)
1012                 mpflag = cfs_memory_pressure_get_and_set();
1013         tx = ksocknal_alloc_tx(KSOCK_MSG_LNET, desc_size);
1014         if (tx == NULL) {
1015                 CERROR("Can't allocate tx desc type %d size %d\n",
1016                        type, desc_size);
1017                 if (lntmsg->msg_vmflush)
1018                         cfs_memory_pressure_restore(mpflag);
1019                 return (-ENOMEM);
1020         }
1021
1022         tx->tx_conn = NULL;                     /* set when assigned a conn */
1023         tx->tx_lnetmsg = lntmsg;
1024
1025         if (payload_iov != NULL) {
1026                 tx->tx_kiov = NULL;
1027                 tx->tx_nkiov = 0;
1028                 tx->tx_iov = tx->tx_frags.virt.iov;
1029                 tx->tx_niov = 1 +
1030                               lnet_extract_iov(payload_niov, &tx->tx_iov[1],
1031                                                payload_niov, payload_iov,
1032                                                payload_offset, payload_nob);
1033         } else {
1034                 tx->tx_niov = 1;
1035                 tx->tx_iov = &tx->tx_frags.paged.iov;
1036                 tx->tx_kiov = tx->tx_frags.paged.kiov;
1037                 tx->tx_nkiov = lnet_extract_kiov(payload_niov, tx->tx_kiov,
1038                                                  payload_niov, payload_kiov,
1039                                                  payload_offset, payload_nob);
1040
1041                 if (payload_nob >= *ksocknal_tunables.ksnd_zc_min_payload)
1042                         tx->tx_zc_capable = 1;
1043         }
1044
1045         tx->tx_msg.ksm_csum = 0;
1046         tx->tx_msg.ksm_type = KSOCK_MSG_LNET;
1047         tx->tx_msg.ksm_zc_cookies[0] = 0;
1048         tx->tx_msg.ksm_zc_cookies[1] = 0;
1049
1050         /* The first fragment will be set later in pro_pack */
1051         rc = ksocknal_launch_packet(ni, tx, target);
1052         if (!mpflag)
1053                 cfs_memory_pressure_restore(mpflag);
1054
1055         if (rc == 0)
1056                 return (0);
1057
1058         ksocknal_free_tx(tx);
1059         return (-EIO);
1060 }
1061
1062 int
1063 ksocknal_thread_start(int (*fn)(void *arg), void *arg, char *name)
1064 {
1065         struct task_struct *task = kthread_run(fn, arg, name);
1066
1067         if (IS_ERR(task))
1068                 return PTR_ERR(task);
1069
1070         write_lock_bh(&ksocknal_data.ksnd_global_lock);
1071         ksocknal_data.ksnd_nthreads++;
1072         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
1073         return 0;
1074 }
1075
1076 void
1077 ksocknal_thread_fini (void)
1078 {
1079         write_lock_bh(&ksocknal_data.ksnd_global_lock);
1080         ksocknal_data.ksnd_nthreads--;
1081         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
1082 }
1083
1084 int
1085 ksocknal_new_packet(struct ksock_conn *conn, int nob_to_skip)
1086 {
1087         static char ksocknal_slop_buffer[4096];
1088         int nob;
1089         unsigned int niov;
1090         int skipped;
1091
1092         LASSERT(conn->ksnc_proto != NULL);
1093
1094         if ((*ksocknal_tunables.ksnd_eager_ack & conn->ksnc_type) != 0) {
1095                 /* Remind the socket to ack eagerly... */
1096                 ksocknal_lib_eager_ack(conn);
1097         }
1098
1099         if (nob_to_skip == 0) {         /* right at next packet boundary now */
1100                 conn->ksnc_rx_started = 0;
1101                 smp_mb();                       /* racing with timeout thread */
1102
1103                 switch (conn->ksnc_proto->pro_version) {
1104                 case  KSOCK_PROTO_V2:
1105                 case  KSOCK_PROTO_V3:
1106                         conn->ksnc_rx_state = SOCKNAL_RX_KSM_HEADER;
1107                         conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
1108                         conn->ksnc_rx_iov[0].iov_base = (char *)&conn->ksnc_msg;
1109
1110                         conn->ksnc_rx_nob_wanted = offsetof(struct ksock_msg, ksm_u);
1111                         conn->ksnc_rx_nob_left = offsetof(struct ksock_msg, ksm_u);
1112                         conn->ksnc_rx_iov[0].iov_len  = offsetof(struct ksock_msg, ksm_u);
1113                         break;
1114
1115                 case KSOCK_PROTO_V1:
1116                         /* Receiving bare struct lnet_hdr */
1117                         conn->ksnc_rx_state = SOCKNAL_RX_LNET_HEADER;
1118                         conn->ksnc_rx_nob_wanted = sizeof(struct lnet_hdr);
1119                         conn->ksnc_rx_nob_left = sizeof(struct lnet_hdr);
1120
1121                         conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
1122                         conn->ksnc_rx_iov[0].iov_base = (char *)&conn->ksnc_msg.ksm_u.lnetmsg;
1123                         conn->ksnc_rx_iov[0].iov_len = sizeof(struct lnet_hdr);
1124                         break;
1125
1126                 default:
1127                         LBUG ();
1128                 }
1129                 conn->ksnc_rx_niov = 1;
1130
1131                 conn->ksnc_rx_kiov = NULL;
1132                 conn->ksnc_rx_nkiov = 0;
1133                 conn->ksnc_rx_csum = ~0;
1134                 return (1);
1135         }
1136
1137         /* Set up to skip as much as possible now.  If there's more left
1138          * (ran out of iov entries) we'll get called again */
1139
1140         conn->ksnc_rx_state = SOCKNAL_RX_SLOP;
1141         conn->ksnc_rx_nob_left = nob_to_skip;
1142         conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
1143         skipped = 0;
1144         niov = 0;
1145
1146         do {
1147                 nob = MIN (nob_to_skip, sizeof (ksocknal_slop_buffer));
1148
1149                 conn->ksnc_rx_iov[niov].iov_base = ksocknal_slop_buffer;
1150                 conn->ksnc_rx_iov[niov].iov_len  = nob;
1151                 niov++;
1152                 skipped += nob;
1153                 nob_to_skip -=nob;
1154
1155         } while (nob_to_skip != 0 &&    /* mustn't overflow conn's rx iov */
1156                  niov < sizeof(conn->ksnc_rx_iov_space) / sizeof(struct kvec));
1157
1158         conn->ksnc_rx_niov = niov;
1159         conn->ksnc_rx_kiov = NULL;
1160         conn->ksnc_rx_nkiov = 0;
1161         conn->ksnc_rx_nob_wanted = skipped;
1162         return (0);
1163 }
1164
1165 static int
1166 ksocknal_process_receive(struct ksock_conn *conn)
1167 {
1168         struct lnet_hdr *lhdr;
1169         struct lnet_process_id *id;
1170         int rc;
1171
1172         LASSERT (atomic_read(&conn->ksnc_conn_refcount) > 0);
1173
1174         /* NB: sched lock NOT held */
1175         /* SOCKNAL_RX_LNET_HEADER is here for backward compatibility */
1176         LASSERT (conn->ksnc_rx_state == SOCKNAL_RX_KSM_HEADER ||
1177                  conn->ksnc_rx_state == SOCKNAL_RX_LNET_PAYLOAD ||
1178                  conn->ksnc_rx_state == SOCKNAL_RX_LNET_HEADER ||
1179                  conn->ksnc_rx_state == SOCKNAL_RX_SLOP);
1180  again:
1181         if (conn->ksnc_rx_nob_wanted != 0) {
1182                 rc = ksocknal_receive(conn);
1183
1184                 if (rc <= 0) {
1185                         struct lnet_process_id ksnp_id;
1186
1187                         ksnp_id = conn->ksnc_peer->ksnp_id;
1188
1189                         LASSERT(rc != -EAGAIN);
1190                         if (rc == 0)
1191                                 CDEBUG(D_NET, "[%p] EOF from %s "
1192                                        "ip %pI4h:%d\n", conn,
1193                                         libcfs_id2str(ksnp_id),
1194                                         &conn->ksnc_ipaddr,
1195                                         conn->ksnc_port);
1196                         else if (!conn->ksnc_closing)
1197                                 CERROR("[%p] Error %d on read from %s "
1198                                        "ip %pI4h:%d\n", conn, rc,
1199                                        libcfs_id2str(ksnp_id),
1200                                        &conn->ksnc_ipaddr,
1201                                        conn->ksnc_port);
1202
1203                         /* it's not an error if conn is being closed */
1204                         ksocknal_close_conn_and_siblings (conn,
1205                                                           (conn->ksnc_closing) ? 0 : rc);
1206                         return (rc == 0 ? -ESHUTDOWN : rc);
1207                 }
1208
1209                 if (conn->ksnc_rx_nob_wanted != 0) {
1210                         /* short read */
1211                         return (-EAGAIN);
1212                 }
1213         }
1214         switch (conn->ksnc_rx_state) {
1215         case SOCKNAL_RX_KSM_HEADER:
1216                 if (conn->ksnc_flip) {
1217                         __swab32s(&conn->ksnc_msg.ksm_type);
1218                         __swab32s(&conn->ksnc_msg.ksm_csum);
1219                         __swab64s(&conn->ksnc_msg.ksm_zc_cookies[0]);
1220                         __swab64s(&conn->ksnc_msg.ksm_zc_cookies[1]);
1221                 }
1222
1223                 if (conn->ksnc_msg.ksm_type != KSOCK_MSG_NOOP &&
1224                     conn->ksnc_msg.ksm_type != KSOCK_MSG_LNET) {
1225                         CERROR("%s: Unknown message type: %x\n",
1226                                libcfs_id2str(conn->ksnc_peer->ksnp_id),
1227                                conn->ksnc_msg.ksm_type);
1228                         ksocknal_new_packet(conn, 0);
1229                         ksocknal_close_conn_and_siblings(conn, -EPROTO);
1230                         return (-EPROTO);
1231                 }
1232
1233                 if (conn->ksnc_msg.ksm_type == KSOCK_MSG_NOOP &&
1234                     conn->ksnc_msg.ksm_csum != 0 &&     /* has checksum */
1235                     conn->ksnc_msg.ksm_csum != conn->ksnc_rx_csum) {
1236                         /* NOOP Checksum error */
1237                         CERROR("%s: Checksum error, wire:0x%08X data:0x%08X\n",
1238                                libcfs_id2str(conn->ksnc_peer->ksnp_id),
1239                                conn->ksnc_msg.ksm_csum, conn->ksnc_rx_csum);
1240                         ksocknal_new_packet(conn, 0);
1241                         ksocknal_close_conn_and_siblings(conn, -EPROTO);
1242                         return (-EIO);
1243                 }
1244
1245                 if (conn->ksnc_msg.ksm_zc_cookies[1] != 0) {
1246                         __u64 cookie = 0;
1247
1248                         LASSERT (conn->ksnc_proto != &ksocknal_protocol_v1x);
1249
1250                         if (conn->ksnc_msg.ksm_type == KSOCK_MSG_NOOP)
1251                                 cookie = conn->ksnc_msg.ksm_zc_cookies[0];
1252
1253                         rc = conn->ksnc_proto->pro_handle_zcack(conn, cookie,
1254                                                conn->ksnc_msg.ksm_zc_cookies[1]);
1255
1256                         if (rc != 0) {
1257                                 CERROR("%s: Unknown ZC-ACK cookie: %llu, %llu\n",
1258                                        libcfs_id2str(conn->ksnc_peer->ksnp_id),
1259                                        cookie, conn->ksnc_msg.ksm_zc_cookies[1]);
1260                                 ksocknal_new_packet(conn, 0);
1261                                 ksocknal_close_conn_and_siblings(conn, -EPROTO);
1262                                 return (rc);
1263                         }
1264                 }
1265
1266                 if (conn->ksnc_msg.ksm_type == KSOCK_MSG_NOOP) {
1267                         ksocknal_new_packet (conn, 0);
1268                         return 0;       /* NOOP is done and just return */
1269                 }
1270
1271                 conn->ksnc_rx_state = SOCKNAL_RX_LNET_HEADER;
1272                 conn->ksnc_rx_nob_wanted = sizeof(struct ksock_lnet_msg);
1273                 conn->ksnc_rx_nob_left = sizeof(struct ksock_lnet_msg);
1274
1275                 conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
1276                 conn->ksnc_rx_iov[0].iov_base = (char *)&conn->ksnc_msg.ksm_u.lnetmsg;
1277                 conn->ksnc_rx_iov[0].iov_len  = sizeof(struct ksock_lnet_msg);
1278
1279                 conn->ksnc_rx_niov = 1;
1280                 conn->ksnc_rx_kiov = NULL;
1281                 conn->ksnc_rx_nkiov = 0;
1282
1283                 goto again;     /* read lnet header now */
1284
1285         case SOCKNAL_RX_LNET_HEADER:
1286                 /* unpack message header */
1287                 conn->ksnc_proto->pro_unpack(&conn->ksnc_msg);
1288
1289                 if ((conn->ksnc_peer->ksnp_id.pid & LNET_PID_USERFLAG) != 0) {
1290                         /* Userspace peer_ni */
1291                         lhdr = &conn->ksnc_msg.ksm_u.lnetmsg.ksnm_hdr;
1292                         id   = &conn->ksnc_peer->ksnp_id;
1293
1294                         /* Substitute process ID assigned at connection time */
1295                         lhdr->src_pid = cpu_to_le32(id->pid);
1296                         lhdr->src_nid = cpu_to_le64(id->nid);
1297                 }
1298
1299                 conn->ksnc_rx_state = SOCKNAL_RX_PARSE;
1300                 ksocknal_conn_addref(conn);     /* ++ref while parsing */
1301
1302                 rc = lnet_parse(conn->ksnc_peer->ksnp_ni,
1303                                 &conn->ksnc_msg.ksm_u.lnetmsg.ksnm_hdr,
1304                                 conn->ksnc_peer->ksnp_id.nid, conn, 0);
1305                 if (rc < 0) {
1306                         /* I just received garbage: give up on this conn */
1307                         ksocknal_new_packet(conn, 0);
1308                         ksocknal_close_conn_and_siblings (conn, rc);
1309                         ksocknal_conn_decref(conn);
1310                         return (-EPROTO);
1311                 }
1312
1313                 /* I'm racing with ksocknal_recv() */
1314                 LASSERT (conn->ksnc_rx_state == SOCKNAL_RX_PARSE ||
1315                          conn->ksnc_rx_state == SOCKNAL_RX_LNET_PAYLOAD);
1316
1317                 if (conn->ksnc_rx_state != SOCKNAL_RX_LNET_PAYLOAD)
1318                         return 0;
1319
1320                 /* ksocknal_recv() got called */
1321                 goto again;
1322
1323         case SOCKNAL_RX_LNET_PAYLOAD:
1324                 /* payload all received */
1325                 rc = 0;
1326
1327                 if (conn->ksnc_rx_nob_left == 0 &&   /* not truncating */
1328                     conn->ksnc_msg.ksm_csum != 0 &&  /* has checksum */
1329                     conn->ksnc_msg.ksm_csum != conn->ksnc_rx_csum) {
1330                         CERROR("%s: Checksum error, wire:0x%08X data:0x%08X\n",
1331                                libcfs_id2str(conn->ksnc_peer->ksnp_id),
1332                                conn->ksnc_msg.ksm_csum, conn->ksnc_rx_csum);
1333                         rc = -EIO;
1334                 }
1335
1336                 if (rc == 0 && conn->ksnc_msg.ksm_zc_cookies[0] != 0) {
1337                         LASSERT(conn->ksnc_proto != &ksocknal_protocol_v1x);
1338
1339                         lhdr = &conn->ksnc_msg.ksm_u.lnetmsg.ksnm_hdr;
1340                         id   = &conn->ksnc_peer->ksnp_id;
1341
1342                         rc = conn->ksnc_proto->pro_handle_zcreq(conn,
1343                                         conn->ksnc_msg.ksm_zc_cookies[0],
1344                                         *ksocknal_tunables.ksnd_nonblk_zcack ||
1345                                         le64_to_cpu(lhdr->src_nid) != id->nid);
1346                 }
1347
1348                 lnet_finalize(conn->ksnc_cookie, 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_cookie = 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 }