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