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