Whamcloud - gitweb
LU-12678 lnet: socklnd: mark all ksock_proto struct 'const'.
[fs/lustre-release.git] / lnet / klnds / socklnd / socklnd_cb.c
1 /*
2  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
3  *
4  * Copyright (c) 2011, 2017, Intel Corporation.
5  *
6  *   Author: Zach Brown <zab@zabbo.net>
7  *   Author: Peter J. Braam <braam@clusterfs.com>
8  *   Author: Phil Schwan <phil@clusterfs.com>
9  *   Author: Eric Barton <eric@bartonsoftware.com>
10  *
11  *   This file is part of Lustre, https://wiki.whamcloud.com/
12  *
13  *   Portals is free software; you can redistribute it and/or
14  *   modify it under the terms of version 2 of the GNU General Public
15  *   License as published by the Free Software Foundation.
16  *
17  *   Portals is distributed in the hope that it will be useful,
18  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
19  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  *   GNU General Public License for more details.
21  *
22  *   You should have received a copy of the GNU General Public License
23  *   along with Portals; if not, write to the Free Software
24  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25  */
26
27 #include "socklnd.h"
28
29 struct ksock_tx *
30 ksocknal_alloc_tx(int type, int size)
31 {
32         struct ksock_tx *tx = NULL;
33
34         if (type == KSOCK_MSG_NOOP) {
35                 LASSERT(size == KSOCK_NOOP_TX_SIZE);
36
37                 /* searching for a noop tx in free list */
38                 spin_lock(&ksocknal_data.ksnd_tx_lock);
39
40                 if (!list_empty(&ksocknal_data.ksnd_idle_noop_txs)) {
41                         tx = list_entry(ksocknal_data.ksnd_idle_noop_txs.next,
42                                         struct ksock_tx, tx_list);
43                         LASSERT(tx->tx_desc_size == size);
44                         list_del(&tx->tx_list);
45                 }
46
47                 spin_unlock(&ksocknal_data.ksnd_tx_lock);
48         }
49
50         if (tx == NULL)
51                 LIBCFS_ALLOC(tx, size);
52
53         if (tx == NULL)
54                 return NULL;
55
56         atomic_set(&tx->tx_refcount, 1);
57         tx->tx_zc_aborted = 0;
58         tx->tx_zc_capable = 0;
59         tx->tx_zc_checked = 0;
60         tx->tx_hstatus = LNET_MSG_STATUS_OK;
61         tx->tx_desc_size  = size;
62
63         atomic_inc(&ksocknal_data.ksnd_nactive_txs);
64
65         return tx;
66 }
67
68 struct ksock_tx *
69 ksocknal_alloc_tx_noop(__u64 cookie, int nonblk)
70 {
71         struct ksock_tx *tx;
72
73         tx = ksocknal_alloc_tx(KSOCK_MSG_NOOP, KSOCK_NOOP_TX_SIZE);
74         if (tx == NULL) {
75                 CERROR("Can't allocate noop tx desc\n");
76                 return NULL;
77         }
78
79         tx->tx_conn     = NULL;
80         tx->tx_lnetmsg  = NULL;
81         tx->tx_kiov     = NULL;
82         tx->tx_nkiov    = 0;
83         tx->tx_iov      = tx->tx_frags.virt.iov;
84         tx->tx_niov     = 1;
85         tx->tx_nonblk   = nonblk;
86
87         tx->tx_msg.ksm_csum = 0;
88         tx->tx_msg.ksm_type = KSOCK_MSG_NOOP;
89         tx->tx_msg.ksm_zc_cookies[0] = 0;
90         tx->tx_msg.ksm_zc_cookies[1] = cookie;
91
92         return tx;
93 }
94
95
96 void
97 ksocknal_free_tx(struct ksock_tx *tx)
98 {
99         atomic_dec(&ksocknal_data.ksnd_nactive_txs);
100
101         if (tx->tx_lnetmsg == NULL && tx->tx_desc_size == KSOCK_NOOP_TX_SIZE) {
102                 /* it's a noop tx */
103                 spin_lock(&ksocknal_data.ksnd_tx_lock);
104
105                 list_add(&tx->tx_list, &ksocknal_data.ksnd_idle_noop_txs);
106
107                 spin_unlock(&ksocknal_data.ksnd_tx_lock);
108         } else {
109                 LIBCFS_FREE(tx, tx->tx_desc_size);
110         }
111 }
112
113 static int
114 ksocknal_send_iov(struct ksock_conn *conn, struct ksock_tx *tx,
115                   struct kvec *scratch_iov)
116 {
117         struct kvec *iov = tx->tx_iov;
118         int    nob;
119         int    rc;
120
121         LASSERT(tx->tx_niov > 0);
122
123         /* Never touch tx->tx_iov inside ksocknal_lib_send_iov() */
124         rc = ksocknal_lib_send_iov(conn, tx, scratch_iov);
125
126         if (rc <= 0)                            /* sent nothing? */
127                 return rc;
128
129         nob = rc;
130         LASSERT(nob <= tx->tx_resid);
131         tx->tx_resid -= nob;
132
133         /* "consume" iov */
134         do {
135                 LASSERT(tx->tx_niov > 0);
136
137                 if (nob < (int) iov->iov_len) {
138                         iov->iov_base += nob;
139                         iov->iov_len -= nob;
140                         return rc;
141                 }
142
143                 nob -= iov->iov_len;
144                 tx->tx_iov = ++iov;
145                 tx->tx_niov--;
146         } while (nob != 0);
147
148         return rc;
149 }
150
151 static int
152 ksocknal_send_kiov(struct ksock_conn *conn, struct ksock_tx *tx,
153                    struct kvec *scratch_iov)
154 {
155         lnet_kiov_t *kiov = tx->tx_kiov;
156         int nob;
157         int rc;
158
159         LASSERT(tx->tx_niov == 0);
160         LASSERT(tx->tx_nkiov > 0);
161
162         /* Never touch tx->tx_kiov inside ksocknal_lib_send_kiov() */
163         rc = ksocknal_lib_send_kiov(conn, tx, scratch_iov);
164
165         if (rc <= 0)                            /* sent nothing? */
166                 return rc;
167
168         nob = rc;
169         LASSERT(nob <= tx->tx_resid);
170         tx->tx_resid -= nob;
171
172         /* "consume" kiov */
173         do {
174                 LASSERT(tx->tx_nkiov > 0);
175
176                 if (nob < (int)kiov->kiov_len) {
177                         kiov->kiov_offset += nob;
178                         kiov->kiov_len -= nob;
179                         return rc;
180                 }
181
182                 nob -= (int)kiov->kiov_len;
183                 tx->tx_kiov = ++kiov;
184                 tx->tx_nkiov--;
185         } while (nob != 0);
186
187         return rc;
188 }
189
190 static int
191 ksocknal_transmit(struct ksock_conn *conn, struct ksock_tx *tx,
192                   struct kvec *scratch_iov)
193 {
194         int     rc;
195         int     bufnob;
196
197         if (ksocknal_data.ksnd_stall_tx != 0)
198                 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         lnet_kiov_t *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->kiov_len) {
333                         kiov->kiov_offset += nob;
334                         kiov->kiov_len -= nob;
335                         return -EAGAIN;
336                 }
337
338                 nob -= kiov->kiov_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 kvec *payload_iov = lntmsg->msg_iov;
990         lnet_kiov_t      *payload_kiov = lntmsg->msg_kiov;
991         unsigned int      payload_offset = lntmsg->msg_offset;
992         unsigned int      payload_nob = lntmsg->msg_len;
993         struct ksock_tx *tx;
994         int               desc_size;
995         int               rc;
996
997         /* NB 'private' is different depending on what we're sending.
998          * Just ignore it... */
999
1000         CDEBUG(D_NET, "sending %u bytes in %d frags to %s\n",
1001                payload_nob, payload_niov, libcfs_id2str(target));
1002
1003         LASSERT (payload_nob == 0 || payload_niov > 0);
1004         LASSERT (payload_niov <= LNET_MAX_IOV);
1005         /* payload is either all vaddrs or all pages */
1006         LASSERT (!(payload_kiov != NULL && payload_iov != NULL));
1007         LASSERT (!in_interrupt ());
1008
1009         if (payload_iov != NULL)
1010                 desc_size = offsetof(struct ksock_tx,
1011                                      tx_frags.virt.iov[1 + payload_niov]);
1012         else
1013                 desc_size = offsetof(struct ksock_tx,
1014                                      tx_frags.paged.kiov[payload_niov]);
1015
1016         if (lntmsg->msg_vmflush)
1017                 mpflag = cfs_memory_pressure_get_and_set();
1018         tx = ksocknal_alloc_tx(KSOCK_MSG_LNET, desc_size);
1019         if (tx == NULL) {
1020                 CERROR("Can't allocate tx desc type %d size %d\n",
1021                        type, desc_size);
1022                 if (lntmsg->msg_vmflush)
1023                         cfs_memory_pressure_restore(mpflag);
1024                 return (-ENOMEM);
1025         }
1026
1027         tx->tx_conn = NULL;                     /* set when assigned a conn */
1028         tx->tx_lnetmsg = lntmsg;
1029
1030         if (payload_iov != NULL) {
1031                 tx->tx_kiov = NULL;
1032                 tx->tx_nkiov = 0;
1033                 tx->tx_iov = tx->tx_frags.virt.iov;
1034                 tx->tx_niov = 1 +
1035                               lnet_extract_iov(payload_niov, &tx->tx_iov[1],
1036                                                payload_niov, payload_iov,
1037                                                payload_offset, payload_nob);
1038         } else {
1039                 tx->tx_niov = 1;
1040                 tx->tx_iov = &tx->tx_frags.paged.iov;
1041                 tx->tx_kiov = tx->tx_frags.paged.kiov;
1042                 tx->tx_nkiov = lnet_extract_kiov(payload_niov, tx->tx_kiov,
1043                                                  payload_niov, payload_kiov,
1044                                                  payload_offset, payload_nob);
1045
1046                 if (payload_nob >= *ksocknal_tunables.ksnd_zc_min_payload)
1047                         tx->tx_zc_capable = 1;
1048         }
1049
1050         tx->tx_msg.ksm_csum = 0;
1051         tx->tx_msg.ksm_type = KSOCK_MSG_LNET;
1052         tx->tx_msg.ksm_zc_cookies[0] = 0;
1053         tx->tx_msg.ksm_zc_cookies[1] = 0;
1054
1055         /* The first fragment will be set later in pro_pack */
1056         rc = ksocknal_launch_packet(ni, tx, target);
1057         if (!mpflag)
1058                 cfs_memory_pressure_restore(mpflag);
1059
1060         if (rc == 0)
1061                 return (0);
1062
1063         lntmsg->msg_health_status = tx->tx_hstatus;
1064         ksocknal_free_tx(tx);
1065         return (-EIO);
1066 }
1067
1068 int
1069 ksocknal_thread_start(int (*fn)(void *arg), void *arg, char *name)
1070 {
1071         struct task_struct *task = kthread_run(fn, arg, name);
1072
1073         if (IS_ERR(task))
1074                 return PTR_ERR(task);
1075
1076         write_lock_bh(&ksocknal_data.ksnd_global_lock);
1077         ksocknal_data.ksnd_nthreads++;
1078         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
1079         return 0;
1080 }
1081
1082 void
1083 ksocknal_thread_fini (void)
1084 {
1085         write_lock_bh(&ksocknal_data.ksnd_global_lock);
1086         ksocknal_data.ksnd_nthreads--;
1087         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
1088 }
1089
1090 int
1091 ksocknal_new_packet(struct ksock_conn *conn, int nob_to_skip)
1092 {
1093         static char ksocknal_slop_buffer[4096];
1094         int nob;
1095         unsigned int niov;
1096         int skipped;
1097
1098         LASSERT(conn->ksnc_proto != NULL);
1099
1100         if ((*ksocknal_tunables.ksnd_eager_ack & conn->ksnc_type) != 0) {
1101                 /* Remind the socket to ack eagerly... */
1102                 ksocknal_lib_eager_ack(conn);
1103         }
1104
1105         if (nob_to_skip == 0) {         /* right at next packet boundary now */
1106                 conn->ksnc_rx_started = 0;
1107                 smp_mb();                       /* racing with timeout thread */
1108
1109                 switch (conn->ksnc_proto->pro_version) {
1110                 case  KSOCK_PROTO_V2:
1111                 case  KSOCK_PROTO_V3:
1112                         conn->ksnc_rx_state = SOCKNAL_RX_KSM_HEADER;
1113                         conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
1114                         conn->ksnc_rx_iov[0].iov_base = (char *)&conn->ksnc_msg;
1115
1116                         conn->ksnc_rx_nob_wanted = offsetof(struct ksock_msg, ksm_u);
1117                         conn->ksnc_rx_nob_left = offsetof(struct ksock_msg, ksm_u);
1118                         conn->ksnc_rx_iov[0].iov_len  = offsetof(struct ksock_msg, ksm_u);
1119                         break;
1120
1121                 case KSOCK_PROTO_V1:
1122                         /* Receiving bare struct lnet_hdr */
1123                         conn->ksnc_rx_state = SOCKNAL_RX_LNET_HEADER;
1124                         conn->ksnc_rx_nob_wanted = sizeof(struct lnet_hdr);
1125                         conn->ksnc_rx_nob_left = sizeof(struct lnet_hdr);
1126
1127                         conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
1128                         conn->ksnc_rx_iov[0].iov_base = (char *)&conn->ksnc_msg.ksm_u.lnetmsg;
1129                         conn->ksnc_rx_iov[0].iov_len = sizeof(struct lnet_hdr);
1130                         break;
1131
1132                 default:
1133                         LBUG ();
1134                 }
1135                 conn->ksnc_rx_niov = 1;
1136
1137                 conn->ksnc_rx_kiov = NULL;
1138                 conn->ksnc_rx_nkiov = 0;
1139                 conn->ksnc_rx_csum = ~0;
1140                 return (1);
1141         }
1142
1143         /* Set up to skip as much as possible now.  If there's more left
1144          * (ran out of iov entries) we'll get called again */
1145
1146         conn->ksnc_rx_state = SOCKNAL_RX_SLOP;
1147         conn->ksnc_rx_nob_left = nob_to_skip;
1148         conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
1149         skipped = 0;
1150         niov = 0;
1151
1152         do {
1153                 nob = min_t(int, nob_to_skip, sizeof(ksocknal_slop_buffer));
1154
1155                 conn->ksnc_rx_iov[niov].iov_base = ksocknal_slop_buffer;
1156                 conn->ksnc_rx_iov[niov].iov_len  = nob;
1157                 niov++;
1158                 skipped += nob;
1159                 nob_to_skip -= nob;
1160
1161         } while (nob_to_skip != 0 &&    /* mustn't overflow conn's rx iov */
1162                  niov < sizeof(conn->ksnc_rx_iov_space) / sizeof(struct kvec));
1163
1164         conn->ksnc_rx_niov = niov;
1165         conn->ksnc_rx_kiov = NULL;
1166         conn->ksnc_rx_nkiov = 0;
1167         conn->ksnc_rx_nob_wanted = skipped;
1168         return (0);
1169 }
1170
1171 static int
1172 ksocknal_process_receive(struct ksock_conn *conn,
1173                          struct page **rx_scratch_pgs,
1174                          struct kvec *scratch_iov)
1175 {
1176         struct lnet_hdr *lhdr;
1177         struct lnet_process_id *id;
1178         int rc;
1179
1180         LASSERT (atomic_read(&conn->ksnc_conn_refcount) > 0);
1181
1182         /* NB: sched lock NOT held */
1183         /* SOCKNAL_RX_LNET_HEADER is here for backward compatibility */
1184         LASSERT(conn->ksnc_rx_state == SOCKNAL_RX_KSM_HEADER ||
1185                 conn->ksnc_rx_state == SOCKNAL_RX_LNET_PAYLOAD ||
1186                 conn->ksnc_rx_state == SOCKNAL_RX_LNET_HEADER ||
1187                 conn->ksnc_rx_state == SOCKNAL_RX_SLOP);
1188  again:
1189         if (conn->ksnc_rx_nob_wanted != 0) {
1190                 rc = ksocknal_receive(conn, rx_scratch_pgs,
1191                                       scratch_iov);
1192
1193                 if (rc <= 0) {
1194                         struct lnet_process_id ksnp_id;
1195
1196                         ksnp_id = conn->ksnc_peer->ksnp_id;
1197
1198                         LASSERT(rc != -EAGAIN);
1199                         if (rc == 0)
1200                                 CDEBUG(D_NET, "[%p] EOF from %s "
1201                                        "ip %pI4h:%d\n", conn,
1202                                         libcfs_id2str(ksnp_id),
1203                                         &conn->ksnc_ipaddr,
1204                                         conn->ksnc_port);
1205                         else if (!conn->ksnc_closing)
1206                                 CERROR("[%p] Error %d on read from %s "
1207                                        "ip %pI4h:%d\n", conn, rc,
1208                                        libcfs_id2str(ksnp_id),
1209                                        &conn->ksnc_ipaddr,
1210                                        conn->ksnc_port);
1211
1212                         /* it's not an error if conn is being closed */
1213                         ksocknal_close_conn_and_siblings (conn,
1214                                                           (conn->ksnc_closing) ? 0 : rc);
1215                         return (rc == 0 ? -ESHUTDOWN : rc);
1216                 }
1217
1218                 if (conn->ksnc_rx_nob_wanted != 0) {
1219                         /* short read */
1220                         return (-EAGAIN);
1221                 }
1222         }
1223         switch (conn->ksnc_rx_state) {
1224         case SOCKNAL_RX_KSM_HEADER:
1225                 if (conn->ksnc_flip) {
1226                         __swab32s(&conn->ksnc_msg.ksm_type);
1227                         __swab32s(&conn->ksnc_msg.ksm_csum);
1228                         __swab64s(&conn->ksnc_msg.ksm_zc_cookies[0]);
1229                         __swab64s(&conn->ksnc_msg.ksm_zc_cookies[1]);
1230                 }
1231
1232                 if (conn->ksnc_msg.ksm_type != KSOCK_MSG_NOOP &&
1233                     conn->ksnc_msg.ksm_type != KSOCK_MSG_LNET) {
1234                         CERROR("%s: Unknown message type: %x\n",
1235                                libcfs_id2str(conn->ksnc_peer->ksnp_id),
1236                                conn->ksnc_msg.ksm_type);
1237                         ksocknal_new_packet(conn, 0);
1238                         ksocknal_close_conn_and_siblings(conn, -EPROTO);
1239                         return (-EPROTO);
1240                 }
1241
1242                 if (conn->ksnc_msg.ksm_type == KSOCK_MSG_NOOP &&
1243                     conn->ksnc_msg.ksm_csum != 0 &&     /* has checksum */
1244                     conn->ksnc_msg.ksm_csum != conn->ksnc_rx_csum) {
1245                         /* NOOP Checksum error */
1246                         CERROR("%s: Checksum error, wire:0x%08X data:0x%08X\n",
1247                                libcfs_id2str(conn->ksnc_peer->ksnp_id),
1248                                conn->ksnc_msg.ksm_csum, conn->ksnc_rx_csum);
1249                         ksocknal_new_packet(conn, 0);
1250                         ksocknal_close_conn_and_siblings(conn, -EPROTO);
1251                         return (-EIO);
1252                 }
1253
1254                 if (conn->ksnc_msg.ksm_zc_cookies[1] != 0) {
1255                         __u64 cookie = 0;
1256
1257                         LASSERT (conn->ksnc_proto != &ksocknal_protocol_v1x);
1258
1259                         if (conn->ksnc_msg.ksm_type == KSOCK_MSG_NOOP)
1260                                 cookie = conn->ksnc_msg.ksm_zc_cookies[0];
1261
1262                         rc = conn->ksnc_proto->pro_handle_zcack(conn, cookie,
1263                                                conn->ksnc_msg.ksm_zc_cookies[1]);
1264
1265                         if (rc != 0) {
1266                                 CERROR("%s: Unknown ZC-ACK cookie: %llu, %llu\n",
1267                                        libcfs_id2str(conn->ksnc_peer->ksnp_id),
1268                                        cookie, conn->ksnc_msg.ksm_zc_cookies[1]);
1269                                 ksocknal_new_packet(conn, 0);
1270                                 ksocknal_close_conn_and_siblings(conn, -EPROTO);
1271                                 return (rc);
1272                         }
1273                 }
1274
1275                 if (conn->ksnc_msg.ksm_type == KSOCK_MSG_NOOP) {
1276                         ksocknal_new_packet (conn, 0);
1277                         return 0;       /* NOOP is done and just return */
1278                 }
1279
1280                 conn->ksnc_rx_state = SOCKNAL_RX_LNET_HEADER;
1281                 conn->ksnc_rx_nob_wanted = sizeof(struct ksock_lnet_msg);
1282                 conn->ksnc_rx_nob_left = sizeof(struct ksock_lnet_msg);
1283
1284                 conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
1285                 conn->ksnc_rx_iov[0].iov_base = (char *)&conn->ksnc_msg.ksm_u.lnetmsg;
1286                 conn->ksnc_rx_iov[0].iov_len  = sizeof(struct ksock_lnet_msg);
1287
1288                 conn->ksnc_rx_niov = 1;
1289                 conn->ksnc_rx_kiov = NULL;
1290                 conn->ksnc_rx_nkiov = 0;
1291
1292                 goto again;     /* read lnet header now */
1293
1294         case SOCKNAL_RX_LNET_HEADER:
1295                 /* unpack message header */
1296                 conn->ksnc_proto->pro_unpack(&conn->ksnc_msg);
1297
1298                 if ((conn->ksnc_peer->ksnp_id.pid & LNET_PID_USERFLAG) != 0) {
1299                         /* Userspace peer_ni */
1300                         lhdr = &conn->ksnc_msg.ksm_u.lnetmsg.ksnm_hdr;
1301                         id   = &conn->ksnc_peer->ksnp_id;
1302
1303                         /* Substitute process ID assigned at connection time */
1304                         lhdr->src_pid = cpu_to_le32(id->pid);
1305                         lhdr->src_nid = cpu_to_le64(id->nid);
1306                 }
1307
1308                 conn->ksnc_rx_state = SOCKNAL_RX_PARSE;
1309                 ksocknal_conn_addref(conn);     /* ++ref while parsing */
1310
1311                 rc = lnet_parse(conn->ksnc_peer->ksnp_ni,
1312                                 &conn->ksnc_msg.ksm_u.lnetmsg.ksnm_hdr,
1313                                 conn->ksnc_peer->ksnp_id.nid, conn, 0);
1314                 if (rc < 0) {
1315                         /* I just received garbage: give up on this conn */
1316                         ksocknal_new_packet(conn, 0);
1317                         ksocknal_close_conn_and_siblings (conn, rc);
1318                         ksocknal_conn_decref(conn);
1319                         return (-EPROTO);
1320                 }
1321
1322                 /* I'm racing with ksocknal_recv() */
1323                 LASSERT (conn->ksnc_rx_state == SOCKNAL_RX_PARSE ||
1324                          conn->ksnc_rx_state == SOCKNAL_RX_LNET_PAYLOAD);
1325
1326                 if (conn->ksnc_rx_state != SOCKNAL_RX_LNET_PAYLOAD)
1327                         return 0;
1328
1329                 /* ksocknal_recv() got called */
1330                 goto again;
1331
1332         case SOCKNAL_RX_LNET_PAYLOAD:
1333                 /* payload all received */
1334                 rc = 0;
1335
1336                 if (conn->ksnc_rx_nob_left == 0 &&   /* not truncating */
1337                     conn->ksnc_msg.ksm_csum != 0 &&  /* has checksum */
1338                     conn->ksnc_msg.ksm_csum != conn->ksnc_rx_csum) {
1339                         CERROR("%s: Checksum error, wire:0x%08X data:0x%08X\n",
1340                                libcfs_id2str(conn->ksnc_peer->ksnp_id),
1341                                conn->ksnc_msg.ksm_csum, conn->ksnc_rx_csum);
1342                         rc = -EIO;
1343                 }
1344
1345                 if (rc == 0 && conn->ksnc_msg.ksm_zc_cookies[0] != 0) {
1346                         LASSERT(conn->ksnc_proto != &ksocknal_protocol_v1x);
1347
1348                         lhdr = &conn->ksnc_msg.ksm_u.lnetmsg.ksnm_hdr;
1349                         id   = &conn->ksnc_peer->ksnp_id;
1350
1351                         rc = conn->ksnc_proto->pro_handle_zcreq(conn,
1352                                         conn->ksnc_msg.ksm_zc_cookies[0],
1353                                         *ksocknal_tunables.ksnd_nonblk_zcack ||
1354                                         le64_to_cpu(lhdr->src_nid) != id->nid);
1355                 }
1356
1357                 if (rc && conn->ksnc_lnet_msg)
1358                         conn->ksnc_lnet_msg->msg_health_status =
1359                                 LNET_MSG_STATUS_REMOTE_ERROR;
1360                 lnet_finalize(conn->ksnc_lnet_msg, rc);
1361
1362                 if (rc != 0) {
1363                         ksocknal_new_packet(conn, 0);
1364                         ksocknal_close_conn_and_siblings (conn, rc);
1365                         return (-EPROTO);
1366                 }
1367                 /* Fall through */
1368
1369         case SOCKNAL_RX_SLOP:
1370                 /* starting new packet? */
1371                 if (ksocknal_new_packet (conn, conn->ksnc_rx_nob_left))
1372                         return 0;       /* come back later */
1373                 goto again;             /* try to finish reading slop now */
1374
1375         default:
1376                 break;
1377         }
1378
1379         /* Not Reached */
1380         LBUG ();
1381         return (-EINVAL);                       /* keep gcc happy */
1382 }
1383
1384 int
1385 ksocknal_recv(struct lnet_ni *ni, void *private, struct lnet_msg *msg,
1386               int delayed, unsigned int niov, struct kvec *iov,
1387               lnet_kiov_t *kiov, unsigned int offset, unsigned int mlen,
1388               unsigned int rlen)
1389 {
1390         struct ksock_conn *conn = private;
1391         struct ksock_sched *sched = conn->ksnc_scheduler;
1392
1393         LASSERT (mlen <= rlen);
1394         LASSERT (niov <= LNET_MAX_IOV);
1395
1396         conn->ksnc_lnet_msg = msg;
1397         conn->ksnc_rx_nob_wanted = mlen;
1398         conn->ksnc_rx_nob_left   = rlen;
1399
1400         if (mlen == 0 || iov != NULL) {
1401                 conn->ksnc_rx_nkiov = 0;
1402                 conn->ksnc_rx_kiov = NULL;
1403                 conn->ksnc_rx_iov = conn->ksnc_rx_iov_space.iov;
1404                 conn->ksnc_rx_niov =
1405                         lnet_extract_iov(LNET_MAX_IOV, conn->ksnc_rx_iov,
1406                                          niov, iov, offset, mlen);
1407         } else {
1408                 conn->ksnc_rx_niov = 0;
1409                 conn->ksnc_rx_iov  = NULL;
1410                 conn->ksnc_rx_kiov = conn->ksnc_rx_iov_space.kiov;
1411                 conn->ksnc_rx_nkiov =
1412                         lnet_extract_kiov(LNET_MAX_IOV, conn->ksnc_rx_kiov,
1413                                           niov, kiov, offset, mlen);
1414         }
1415
1416         LASSERT (mlen ==
1417                  lnet_iov_nob (conn->ksnc_rx_niov, conn->ksnc_rx_iov) +
1418                  lnet_kiov_nob (conn->ksnc_rx_nkiov, conn->ksnc_rx_kiov));
1419
1420         LASSERT (conn->ksnc_rx_scheduled);
1421
1422         spin_lock_bh(&sched->kss_lock);
1423
1424         switch (conn->ksnc_rx_state) {
1425         case SOCKNAL_RX_PARSE_WAIT:
1426                 list_add_tail(&conn->ksnc_rx_list, &sched->kss_rx_conns);
1427                 wake_up(&sched->kss_waitq);
1428                 LASSERT(conn->ksnc_rx_ready);
1429                 break;
1430
1431         case SOCKNAL_RX_PARSE:
1432                 /* scheduler hasn't noticed I'm parsing yet */
1433                 break;
1434         }
1435
1436         conn->ksnc_rx_state = SOCKNAL_RX_LNET_PAYLOAD;
1437
1438         spin_unlock_bh(&sched->kss_lock);
1439         ksocknal_conn_decref(conn);
1440         return 0;
1441 }
1442
1443 static inline int
1444 ksocknal_sched_cansleep(struct ksock_sched *sched)
1445 {
1446         int           rc;
1447
1448         spin_lock_bh(&sched->kss_lock);
1449
1450         rc = (!ksocknal_data.ksnd_shuttingdown &&
1451               list_empty(&sched->kss_rx_conns) &&
1452               list_empty(&sched->kss_tx_conns));
1453
1454         spin_unlock_bh(&sched->kss_lock);
1455         return rc;
1456 }
1457
1458 int ksocknal_scheduler(void *arg)
1459 {
1460         struct ksock_sched *sched;
1461         struct ksock_conn *conn;
1462         struct ksock_tx *tx;
1463         int rc;
1464         int nloops = 0;
1465         long id = (long)arg;
1466         struct page **rx_scratch_pgs;
1467         struct kvec *scratch_iov;
1468
1469         sched = ksocknal_data.ksnd_schedulers[KSOCK_THREAD_CPT(id)];
1470
1471         LIBCFS_CPT_ALLOC(rx_scratch_pgs, lnet_cpt_table(), sched->kss_cpt,
1472                          sizeof(*rx_scratch_pgs) * LNET_MAX_IOV);
1473         if (!rx_scratch_pgs) {
1474                 CERROR("Unable to allocate scratch pages\n");
1475                 return -ENOMEM;
1476         }
1477
1478         LIBCFS_CPT_ALLOC(scratch_iov, lnet_cpt_table(), sched->kss_cpt,
1479                          sizeof(*scratch_iov) * LNET_MAX_IOV);
1480         if (!scratch_iov) {
1481                 CERROR("Unable to allocate scratch iov\n");
1482                 return -ENOMEM;
1483         }
1484
1485         cfs_block_allsigs();
1486
1487         rc = cfs_cpt_bind(lnet_cpt_table(), sched->kss_cpt);
1488         if (rc != 0) {
1489                 CWARN("Can't set CPU partition affinity to %d: %d\n",
1490                         sched->kss_cpt, rc);
1491         }
1492
1493         spin_lock_bh(&sched->kss_lock);
1494
1495         while (!ksocknal_data.ksnd_shuttingdown) {
1496                 int did_something = 0;
1497
1498                 /* Ensure I progress everything semi-fairly */
1499
1500                 if (!list_empty(&sched->kss_rx_conns)) {
1501                         conn = list_entry(sched->kss_rx_conns.next,
1502                                           struct ksock_conn, ksnc_rx_list);
1503                         list_del(&conn->ksnc_rx_list);
1504
1505                         LASSERT(conn->ksnc_rx_scheduled);
1506                         LASSERT(conn->ksnc_rx_ready);
1507
1508                         /* clear rx_ready in case receive isn't complete.
1509                          * Do it BEFORE we call process_recv, since
1510                          * data_ready can set it any time after we release
1511                          * kss_lock. */
1512                         conn->ksnc_rx_ready = 0;
1513                         spin_unlock_bh(&sched->kss_lock);
1514
1515                         rc = ksocknal_process_receive(conn, rx_scratch_pgs,
1516                                                       scratch_iov);
1517
1518                         spin_lock_bh(&sched->kss_lock);
1519
1520                         /* I'm the only one that can clear this flag */
1521                         LASSERT(conn->ksnc_rx_scheduled);
1522
1523                         /* Did process_receive get everything it wanted? */
1524                         if (rc == 0)
1525                                 conn->ksnc_rx_ready = 1;
1526
1527                         if (conn->ksnc_rx_state == SOCKNAL_RX_PARSE) {
1528                                 /* Conn blocked waiting for ksocknal_recv()
1529                                  * I change its state (under lock) to signal
1530                                  * it can be rescheduled */
1531                                 conn->ksnc_rx_state = SOCKNAL_RX_PARSE_WAIT;
1532                         } else if (conn->ksnc_rx_ready) {
1533                                 /* reschedule for rx */
1534                                 list_add_tail(&conn->ksnc_rx_list,
1535                                                    &sched->kss_rx_conns);
1536                         } else {
1537                                 conn->ksnc_rx_scheduled = 0;
1538                                 /* drop my ref */
1539                                 ksocknal_conn_decref(conn);
1540                         }
1541
1542                         did_something = 1;
1543                 }
1544
1545                 if (!list_empty(&sched->kss_tx_conns)) {
1546                         LIST_HEAD(zlist);
1547
1548                         if (!list_empty(&sched->kss_zombie_noop_txs)) {
1549                                 list_add(&zlist,
1550                                          &sched->kss_zombie_noop_txs);
1551                                 list_del_init(&sched->kss_zombie_noop_txs);
1552                         }
1553
1554                         conn = list_entry(sched->kss_tx_conns.next,
1555                                           struct ksock_conn, ksnc_tx_list);
1556                         list_del(&conn->ksnc_tx_list);
1557
1558                         LASSERT(conn->ksnc_tx_scheduled);
1559                         LASSERT(conn->ksnc_tx_ready);
1560                         LASSERT(!list_empty(&conn->ksnc_tx_queue));
1561
1562                         tx = list_entry(conn->ksnc_tx_queue.next,
1563                                         struct ksock_tx, tx_list);
1564
1565                         if (conn->ksnc_tx_carrier == tx)
1566                                 ksocknal_next_tx_carrier(conn);
1567
1568                         /* dequeue now so empty list => more to send */
1569                         list_del(&tx->tx_list);
1570
1571                         /* Clear tx_ready in case send isn't complete.  Do
1572                          * it BEFORE we call process_transmit, since
1573                          * write_space can set it any time after we release
1574                          * kss_lock. */
1575                         conn->ksnc_tx_ready = 0;
1576                         spin_unlock_bh(&sched->kss_lock);
1577
1578                         if (!list_empty(&zlist)) {
1579                                 /* free zombie noop txs, it's fast because
1580                                  * noop txs are just put in freelist */
1581                                 ksocknal_txlist_done(NULL, &zlist, 0);
1582                         }
1583
1584                         rc = ksocknal_process_transmit(conn, tx, scratch_iov);
1585
1586                         if (rc == -ENOMEM || rc == -EAGAIN) {
1587                                 /* Incomplete send: replace tx on HEAD of tx_queue */
1588                                 spin_lock_bh(&sched->kss_lock);
1589                                 list_add(&tx->tx_list,
1590                                          &conn->ksnc_tx_queue);
1591                         } else {
1592                                 /* Complete send; tx -ref */
1593                                 ksocknal_tx_decref(tx);
1594
1595                                 spin_lock_bh(&sched->kss_lock);
1596                                 /* assume space for more */
1597                                 conn->ksnc_tx_ready = 1;
1598                         }
1599
1600                         if (rc == -ENOMEM) {
1601                                 /* Do nothing; after a short timeout, this
1602                                  * conn will be reposted on kss_tx_conns. */
1603                         } else if (conn->ksnc_tx_ready &&
1604                                    !list_empty(&conn->ksnc_tx_queue)) {
1605                                 /* reschedule for tx */
1606                                 list_add_tail(&conn->ksnc_tx_list,
1607                                               &sched->kss_tx_conns);
1608                         } else {
1609                                 conn->ksnc_tx_scheduled = 0;
1610                                 /* drop my ref */
1611                                 ksocknal_conn_decref(conn);
1612                         }
1613
1614                         did_something = 1;
1615                 }
1616                 if (!did_something ||           /* nothing to do */
1617                     ++nloops == SOCKNAL_RESCHED) { /* hogging CPU? */
1618                         spin_unlock_bh(&sched->kss_lock);
1619
1620                         nloops = 0;
1621
1622                         if (!did_something) {   /* wait for something to do */
1623                                 rc = wait_event_interruptible_exclusive(
1624                                         sched->kss_waitq,
1625                                         !ksocknal_sched_cansleep(sched));
1626                                 LASSERT (rc == 0);
1627                         } else {
1628                                 cond_resched();
1629                         }
1630
1631                         spin_lock_bh(&sched->kss_lock);
1632                 }
1633         }
1634
1635         spin_unlock_bh(&sched->kss_lock);
1636         LIBCFS_FREE(rx_scratch_pgs, sizeof(*rx_scratch_pgs) *
1637                     LNET_MAX_IOV);
1638         LIBCFS_FREE(scratch_iov, sizeof(*scratch_iov) *
1639                     LNET_MAX_IOV);
1640         ksocknal_thread_fini();
1641         return 0;
1642 }
1643
1644 /*
1645  * Add connection to kss_rx_conns of scheduler
1646  * and wakeup the scheduler.
1647  */
1648 void ksocknal_read_callback(struct ksock_conn *conn)
1649 {
1650         struct ksock_sched *sched;
1651         ENTRY;
1652
1653         sched = conn->ksnc_scheduler;
1654
1655         spin_lock_bh(&sched->kss_lock);
1656
1657         conn->ksnc_rx_ready = 1;
1658
1659         if (!conn->ksnc_rx_scheduled) {  /* not being progressed */
1660                 list_add_tail(&conn->ksnc_rx_list,
1661                                   &sched->kss_rx_conns);
1662                 conn->ksnc_rx_scheduled = 1;
1663                 /* extra ref for scheduler */
1664                 ksocknal_conn_addref(conn);
1665
1666                 wake_up (&sched->kss_waitq);
1667         }
1668         spin_unlock_bh(&sched->kss_lock);
1669
1670         EXIT;
1671 }
1672
1673 /*
1674  * Add connection to kss_tx_conns of scheduler
1675  * and wakeup the scheduler.
1676  */
1677 void ksocknal_write_callback(struct ksock_conn *conn)
1678 {
1679         struct ksock_sched *sched;
1680         ENTRY;
1681
1682         sched = conn->ksnc_scheduler;
1683
1684         spin_lock_bh(&sched->kss_lock);
1685
1686         conn->ksnc_tx_ready = 1;
1687
1688         if (!conn->ksnc_tx_scheduled && /* not being progressed */
1689             !list_empty(&conn->ksnc_tx_queue)) { /* packets to send */
1690                 list_add_tail(&conn->ksnc_tx_list, &sched->kss_tx_conns);
1691                 conn->ksnc_tx_scheduled = 1;
1692                 /* extra ref for scheduler */
1693                 ksocknal_conn_addref(conn);
1694
1695                 wake_up(&sched->kss_waitq);
1696         }
1697
1698         spin_unlock_bh(&sched->kss_lock);
1699
1700         EXIT;
1701 }
1702
1703 static const struct ksock_proto *
1704 ksocknal_parse_proto_version(struct ksock_hello_msg *hello)
1705 {
1706         __u32   version = 0;
1707
1708         if (hello->kshm_magic == LNET_PROTO_MAGIC)
1709                 version = hello->kshm_version;
1710         else if (hello->kshm_magic == __swab32(LNET_PROTO_MAGIC))
1711                 version = __swab32(hello->kshm_version);
1712
1713         if (version != 0) {
1714 #if SOCKNAL_VERSION_DEBUG
1715                 if (*ksocknal_tunables.ksnd_protocol == 1)
1716                         return NULL;
1717
1718                 if (*ksocknal_tunables.ksnd_protocol == 2 &&
1719                     version == KSOCK_PROTO_V3)
1720                         return NULL;
1721 #endif
1722                 if (version == KSOCK_PROTO_V2)
1723                         return &ksocknal_protocol_v2x;
1724
1725                 if (version == KSOCK_PROTO_V3)
1726                         return &ksocknal_protocol_v3x;
1727
1728                 return NULL;
1729         }
1730
1731         if (hello->kshm_magic == le32_to_cpu(LNET_PROTO_TCP_MAGIC)) {
1732                 struct lnet_magicversion *hmv;
1733
1734                 BUILD_BUG_ON(sizeof(struct lnet_magicversion) !=
1735                          offsetof(struct ksock_hello_msg, kshm_src_nid));
1736
1737                 hmv = (struct lnet_magicversion *)hello;
1738
1739                 if (hmv->version_major == cpu_to_le16 (KSOCK_PROTO_V1_MAJOR) &&
1740                     hmv->version_minor == cpu_to_le16 (KSOCK_PROTO_V1_MINOR))
1741                         return &ksocknal_protocol_v1x;
1742         }
1743
1744         return NULL;
1745 }
1746
1747 int
1748 ksocknal_send_hello(struct lnet_ni *ni, struct ksock_conn *conn,
1749                     lnet_nid_t peer_nid, struct ksock_hello_msg *hello)
1750 {
1751         /* CAVEAT EMPTOR: this byte flips 'ipaddrs' */
1752         struct ksock_net *net = (struct ksock_net *)ni->ni_data;
1753
1754         LASSERT(hello->kshm_nips <= LNET_INTERFACES_NUM);
1755
1756         /* rely on caller to hold a ref on socket so it wouldn't disappear */
1757         LASSERT(conn->ksnc_proto != NULL);
1758
1759         hello->kshm_src_nid         = ni->ni_nid;
1760         hello->kshm_dst_nid         = peer_nid;
1761         hello->kshm_src_pid         = the_lnet.ln_pid;
1762
1763         hello->kshm_src_incarnation = net->ksnn_incarnation;
1764         hello->kshm_ctype           = conn->ksnc_type;
1765
1766         return conn->ksnc_proto->pro_send_hello(conn, hello);
1767 }
1768
1769 static int
1770 ksocknal_invert_type(int type)
1771 {
1772         switch (type)
1773         {
1774         case SOCKLND_CONN_ANY:
1775         case SOCKLND_CONN_CONTROL:
1776                 return (type);
1777         case SOCKLND_CONN_BULK_IN:
1778                 return SOCKLND_CONN_BULK_OUT;
1779         case SOCKLND_CONN_BULK_OUT:
1780                 return SOCKLND_CONN_BULK_IN;
1781         default:
1782                 return (SOCKLND_CONN_NONE);
1783         }
1784 }
1785
1786 int
1787 ksocknal_recv_hello(struct lnet_ni *ni, struct ksock_conn *conn,
1788                     struct ksock_hello_msg *hello,
1789                     struct lnet_process_id *peerid,
1790                     __u64 *incarnation)
1791 {
1792         /* Return < 0        fatal error
1793          *        0          success
1794          *        EALREADY   lost connection race
1795          *        EPROTO     protocol version mismatch
1796          */
1797         struct socket        *sock = conn->ksnc_sock;
1798         int                  active = (conn->ksnc_proto != NULL);
1799         int                  timeout;
1800         int                  proto_match;
1801         int                  rc;
1802         const struct ksock_proto *proto;
1803         struct lnet_process_id recv_id;
1804
1805         /* socket type set on active connections - not set on passive */
1806         LASSERT(!active == !(conn->ksnc_type != SOCKLND_CONN_NONE));
1807
1808         timeout = active ? lnet_get_lnd_timeout() :
1809                             lnet_acceptor_timeout();
1810
1811         rc = lnet_sock_read(sock, &hello->kshm_magic,
1812                             sizeof(hello->kshm_magic), timeout);
1813         if (rc != 0) {
1814                 CERROR("Error %d reading HELLO from %pI4h\n",
1815                        rc, &conn->ksnc_ipaddr);
1816                 LASSERT (rc < 0);
1817                 return rc;
1818         }
1819
1820         if (hello->kshm_magic != LNET_PROTO_MAGIC &&
1821             hello->kshm_magic != __swab32(LNET_PROTO_MAGIC) &&
1822             hello->kshm_magic != le32_to_cpu (LNET_PROTO_TCP_MAGIC)) {
1823                 /* Unexpected magic! */
1824                 CERROR ("Bad magic(1) %#08x (%#08x expected) from "
1825                         "%pI4h\n", __cpu_to_le32 (hello->kshm_magic),
1826                         LNET_PROTO_TCP_MAGIC, &conn->ksnc_ipaddr);
1827                 return -EPROTO;
1828         }
1829
1830         rc = lnet_sock_read(sock, &hello->kshm_version,
1831                             sizeof(hello->kshm_version), timeout);
1832         if (rc != 0) {
1833                 CERROR("Error %d reading HELLO from %pI4h\n",
1834                        rc, &conn->ksnc_ipaddr);
1835                 LASSERT(rc < 0);
1836                 return rc;
1837         }
1838
1839         proto = ksocknal_parse_proto_version(hello);
1840         if (proto == NULL) {
1841                 if (!active) {
1842                         /* unknown protocol from peer_ni, tell peer_ni my protocol */
1843                         conn->ksnc_proto = &ksocknal_protocol_v3x;
1844 #if SOCKNAL_VERSION_DEBUG
1845                         if (*ksocknal_tunables.ksnd_protocol == 2)
1846                                 conn->ksnc_proto = &ksocknal_protocol_v2x;
1847                         else if (*ksocknal_tunables.ksnd_protocol == 1)
1848                                 conn->ksnc_proto = &ksocknal_protocol_v1x;
1849 #endif
1850                         hello->kshm_nips = 0;
1851                         ksocknal_send_hello(ni, conn, ni->ni_nid, hello);
1852                 }
1853
1854                 CERROR("Unknown protocol version (%d.x expected) from %pI4h\n",
1855                        conn->ksnc_proto->pro_version, &conn->ksnc_ipaddr);
1856
1857                 return -EPROTO;
1858         }
1859
1860         proto_match = (conn->ksnc_proto == proto);
1861         conn->ksnc_proto = proto;
1862
1863         /* receive the rest of hello message anyway */
1864         rc = conn->ksnc_proto->pro_recv_hello(conn, hello, timeout);
1865         if (rc != 0) {
1866                 CERROR("Error %d reading or checking hello from from %pI4h\n",
1867                        rc, &conn->ksnc_ipaddr);
1868                 LASSERT (rc < 0);
1869                 return rc;
1870         }
1871
1872         *incarnation = hello->kshm_src_incarnation;
1873
1874         if (hello->kshm_src_nid == LNET_NID_ANY) {
1875                 CERROR("Expecting a HELLO hdr with a NID, but got LNET_NID_ANY from %pI4h\n",
1876                        &conn->ksnc_ipaddr);
1877                 return -EPROTO;
1878         }
1879
1880         if (!active &&
1881             conn->ksnc_port > LNET_ACCEPTOR_MAX_RESERVED_PORT) {
1882                 /* Userspace NAL assigns peer_ni process ID from socket */
1883                 recv_id.pid = conn->ksnc_port | LNET_PID_USERFLAG;
1884                 recv_id.nid = LNET_MKNID(LNET_NIDNET(ni->ni_nid), conn->ksnc_ipaddr);
1885         } else {
1886                 recv_id.nid = hello->kshm_src_nid;
1887                 recv_id.pid = hello->kshm_src_pid;
1888         }
1889
1890         if (!active) {
1891                 *peerid = recv_id;
1892
1893                 /* peer_ni determines type */
1894                 conn->ksnc_type = ksocknal_invert_type(hello->kshm_ctype);
1895                 if (conn->ksnc_type == SOCKLND_CONN_NONE) {
1896                         CERROR("Unexpected type %d from %s ip %pI4h\n",
1897                                hello->kshm_ctype, libcfs_id2str(*peerid),
1898                                &conn->ksnc_ipaddr);
1899                         return -EPROTO;
1900                 }
1901                 return 0;
1902         }
1903
1904         if (peerid->pid != recv_id.pid ||
1905             peerid->nid != recv_id.nid) {
1906                 LCONSOLE_ERROR_MSG(0x130, "Connected successfully to %s on host"
1907                                    " %pI4h, but they claimed they were "
1908                                    "%s; please check your Lustre "
1909                                    "configuration.\n",
1910                                    libcfs_id2str(*peerid),
1911                                    &conn->ksnc_ipaddr,
1912                                    libcfs_id2str(recv_id));
1913                 return -EPROTO;
1914         }
1915
1916         if (hello->kshm_ctype == SOCKLND_CONN_NONE) {
1917                 /* Possible protocol mismatch or I lost the connection race */
1918                 return proto_match ? EALREADY : EPROTO;
1919         }
1920
1921         if (ksocknal_invert_type(hello->kshm_ctype) != conn->ksnc_type) {
1922                 CERROR("Mismatched types: me %d, %s ip %pI4h %d\n",
1923                        conn->ksnc_type, libcfs_id2str(*peerid),
1924                        &conn->ksnc_ipaddr,
1925                        hello->kshm_ctype);
1926                 return -EPROTO;
1927         }
1928         return 0;
1929 }
1930
1931 static int
1932 ksocknal_connect(struct ksock_route *route)
1933 {
1934         LIST_HEAD(zombies);
1935         struct ksock_peer_ni *peer_ni = route->ksnr_peer;
1936         int               type;
1937         int               wanted;
1938         struct socket     *sock;
1939         time64_t deadline;
1940         int               retry_later = 0;
1941         int               rc = 0;
1942
1943         deadline = ktime_get_seconds() + lnet_get_lnd_timeout();
1944
1945         write_lock_bh(&ksocknal_data.ksnd_global_lock);
1946
1947         LASSERT (route->ksnr_scheduled);
1948         LASSERT (!route->ksnr_connecting);
1949
1950         route->ksnr_connecting = 1;
1951
1952         for (;;) {
1953                 wanted = ksocknal_route_mask() & ~route->ksnr_connected;
1954
1955                 /* stop connecting if peer_ni/route got closed under me, or
1956                  * route got connected while queued */
1957                 if (peer_ni->ksnp_closing || route->ksnr_deleted ||
1958                     wanted == 0) {
1959                         retry_later = 0;
1960                         break;
1961                 }
1962
1963                 /* reschedule if peer_ni is connecting to me */
1964                 if (peer_ni->ksnp_accepting > 0) {
1965                         CDEBUG(D_NET,
1966                                "peer_ni %s(%d) already connecting to me, retry later.\n",
1967                                libcfs_nid2str(peer_ni->ksnp_id.nid), peer_ni->ksnp_accepting);
1968                         retry_later = 1;
1969                 }
1970
1971                 if (retry_later) /* needs reschedule */
1972                         break;
1973
1974                 if ((wanted & (1 << SOCKLND_CONN_ANY)) != 0) {
1975                         type = SOCKLND_CONN_ANY;
1976                 } else if ((wanted & (1 << SOCKLND_CONN_CONTROL)) != 0) {
1977                         type = SOCKLND_CONN_CONTROL;
1978                 } else if ((wanted & (1 << SOCKLND_CONN_BULK_IN)) != 0) {
1979                         type = SOCKLND_CONN_BULK_IN;
1980                 } else {
1981                         LASSERT ((wanted & (1 << SOCKLND_CONN_BULK_OUT)) != 0);
1982                         type = SOCKLND_CONN_BULK_OUT;
1983                 }
1984
1985                 write_unlock_bh(&ksocknal_data.ksnd_global_lock);
1986
1987                 if (ktime_get_seconds() >= deadline) {
1988                         rc = -ETIMEDOUT;
1989                         lnet_connect_console_error(rc, peer_ni->ksnp_id.nid,
1990                                                    route->ksnr_ipaddr,
1991                                                    route->ksnr_port);
1992                         goto failed;
1993                 }
1994
1995                 rc = lnet_connect(&sock, peer_ni->ksnp_id.nid,
1996                                   route->ksnr_myipaddr,
1997                                   route->ksnr_ipaddr, route->ksnr_port,
1998                                   peer_ni->ksnp_ni->ni_net_ns);
1999                 if (rc != 0)
2000                         goto failed;
2001
2002                 rc = ksocknal_create_conn(peer_ni->ksnp_ni, route, sock, type);
2003                 if (rc < 0) {
2004                         lnet_connect_console_error(rc, peer_ni->ksnp_id.nid,
2005                                                    route->ksnr_ipaddr,
2006                                                    route->ksnr_port);
2007                         goto failed;
2008                 }
2009
2010                 /* A +ve RC means I have to retry because I lost the connection
2011                  * race or I have to renegotiate protocol version */
2012                 retry_later = (rc != 0);
2013                 if (retry_later)
2014                         CDEBUG(D_NET, "peer_ni %s: conn race, retry later.\n",
2015                                libcfs_nid2str(peer_ni->ksnp_id.nid));
2016
2017                 write_lock_bh(&ksocknal_data.ksnd_global_lock);
2018         }
2019
2020         route->ksnr_scheduled = 0;
2021         route->ksnr_connecting = 0;
2022
2023         if (retry_later) {
2024                 /* re-queue for attention; this frees me up to handle
2025                  * the peer_ni's incoming connection request */
2026
2027                 if (rc == EALREADY ||
2028                     (rc == 0 && peer_ni->ksnp_accepting > 0)) {
2029                         /* We want to introduce a delay before next
2030                          * attempt to connect if we lost conn race,
2031                          * but the race is resolved quickly usually,
2032                          * so min_reconnectms should be good heuristic */
2033                         route->ksnr_retry_interval = *ksocknal_tunables.ksnd_min_reconnectms / 1000;
2034                         route->ksnr_timeout = ktime_get_seconds() +
2035                                               route->ksnr_retry_interval;
2036                 }
2037
2038                 ksocknal_launch_connection_locked(route);
2039         }
2040
2041         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
2042         return retry_later;
2043
2044  failed:
2045         write_lock_bh(&ksocknal_data.ksnd_global_lock);
2046
2047         route->ksnr_scheduled = 0;
2048         route->ksnr_connecting = 0;
2049
2050         /* This is a retry rather than a new connection */
2051         route->ksnr_retry_interval *= 2;
2052         route->ksnr_retry_interval =
2053                 max_t(time64_t, route->ksnr_retry_interval,
2054                       *ksocknal_tunables.ksnd_min_reconnectms / 1000);
2055         route->ksnr_retry_interval =
2056                 min_t(time64_t, route->ksnr_retry_interval,
2057                       *ksocknal_tunables.ksnd_max_reconnectms / 1000);
2058
2059         LASSERT(route->ksnr_retry_interval);
2060         route->ksnr_timeout = ktime_get_seconds() + route->ksnr_retry_interval;
2061
2062         if (!list_empty(&peer_ni->ksnp_tx_queue) &&
2063             peer_ni->ksnp_accepting == 0 &&
2064             ksocknal_find_connecting_route_locked(peer_ni) == NULL) {
2065                 struct ksock_conn *conn;
2066
2067                 /* ksnp_tx_queue is queued on a conn on successful
2068                  * connection for V1.x and V2.x */
2069                 if (!list_empty(&peer_ni->ksnp_conns)) {
2070                         conn = list_entry(peer_ni->ksnp_conns.next,
2071                                           struct ksock_conn, ksnc_list);
2072                         LASSERT (conn->ksnc_proto == &ksocknal_protocol_v3x);
2073                 }
2074
2075                 /* take all the blocked packets while I've got the lock and
2076                  * complete below... */
2077                 list_splice_init(&peer_ni->ksnp_tx_queue, &zombies);
2078         }
2079
2080         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
2081
2082         ksocknal_peer_failed(peer_ni);
2083         ksocknal_txlist_done(peer_ni->ksnp_ni, &zombies, rc);
2084         return 0;
2085 }
2086
2087 /*
2088  * check whether we need to create more connds.
2089  * It will try to create new thread if it's necessary, @timeout can
2090  * be updated if failed to create, so caller wouldn't keep try while
2091  * running out of resource.
2092  */
2093 static int
2094 ksocknal_connd_check_start(time64_t sec, long *timeout)
2095 {
2096         char name[16];
2097         int rc;
2098         int total = ksocknal_data.ksnd_connd_starting +
2099                     ksocknal_data.ksnd_connd_running;
2100
2101         if (unlikely(ksocknal_data.ksnd_init < SOCKNAL_INIT_ALL)) {
2102                 /* still in initializing */
2103                 return 0;
2104         }
2105
2106         if (total >= *ksocknal_tunables.ksnd_nconnds_max ||
2107             total > ksocknal_data.ksnd_connd_connecting + SOCKNAL_CONND_RESV) {
2108                 /* can't create more connd, or still have enough
2109                  * threads to handle more connecting */
2110                 return 0;
2111         }
2112
2113         if (list_empty(&ksocknal_data.ksnd_connd_routes)) {
2114                 /* no pending connecting request */
2115                 return 0;
2116         }
2117
2118         if (sec - ksocknal_data.ksnd_connd_failed_stamp <= 1) {
2119                 /* may run out of resource, retry later */
2120                 *timeout = cfs_time_seconds(1);
2121                 return 0;
2122         }
2123
2124         if (ksocknal_data.ksnd_connd_starting > 0) {
2125                 /* serialize starting to avoid flood */
2126                 return 0;
2127         }
2128
2129         ksocknal_data.ksnd_connd_starting_stamp = sec;
2130         ksocknal_data.ksnd_connd_starting++;
2131         spin_unlock_bh(&ksocknal_data.ksnd_connd_lock);
2132
2133         /* NB: total is the next id */
2134         snprintf(name, sizeof(name), "socknal_cd%02d", total);
2135         rc = ksocknal_thread_start(ksocknal_connd, NULL, name);
2136
2137         spin_lock_bh(&ksocknal_data.ksnd_connd_lock);
2138         if (rc == 0)
2139                 return 1;
2140
2141         /* we tried ... */
2142         LASSERT(ksocknal_data.ksnd_connd_starting > 0);
2143         ksocknal_data.ksnd_connd_starting--;
2144         ksocknal_data.ksnd_connd_failed_stamp = ktime_get_real_seconds();
2145
2146         return 1;
2147 }
2148
2149 /*
2150  * check whether current thread can exit, it will return 1 if there are too
2151  * many threads and no creating in past 120 seconds.
2152  * Also, this function may update @timeout to make caller come back
2153  * again to recheck these conditions.
2154  */
2155 static int
2156 ksocknal_connd_check_stop(time64_t sec, long *timeout)
2157 {
2158         int val;
2159
2160         if (unlikely(ksocknal_data.ksnd_init < SOCKNAL_INIT_ALL)) {
2161                 /* still in initializing */
2162                 return 0;
2163         }
2164
2165         if (ksocknal_data.ksnd_connd_starting > 0) {
2166                 /* in progress of starting new thread */
2167                 return 0;
2168         }
2169
2170         if (ksocknal_data.ksnd_connd_running <=
2171             *ksocknal_tunables.ksnd_nconnds) { /* can't shrink */
2172                 return 0;
2173         }
2174
2175         /* created thread in past 120 seconds? */
2176         val = (int)(ksocknal_data.ksnd_connd_starting_stamp +
2177                     SOCKNAL_CONND_TIMEOUT - sec);
2178
2179         *timeout = (val > 0) ? cfs_time_seconds(val) :
2180                                cfs_time_seconds(SOCKNAL_CONND_TIMEOUT);
2181         if (val > 0)
2182                 return 0;
2183
2184         /* no creating in past 120 seconds */
2185
2186         return ksocknal_data.ksnd_connd_running >
2187                ksocknal_data.ksnd_connd_connecting + SOCKNAL_CONND_RESV;
2188 }
2189
2190 /* Go through connd_routes queue looking for a route that we can process
2191  * right now, @timeout_p can be updated if we need to come back later */
2192 static struct ksock_route *
2193 ksocknal_connd_get_route_locked(signed long *timeout_p)
2194 {
2195         time64_t now = ktime_get_seconds();
2196         struct ksock_route *route;
2197
2198         /* connd_routes can contain both pending and ordinary routes */
2199         list_for_each_entry(route, &ksocknal_data.ksnd_connd_routes,
2200                                  ksnr_connd_list) {
2201
2202                 if (route->ksnr_retry_interval == 0 ||
2203                     now >= route->ksnr_timeout)
2204                         return route;
2205
2206                 if (*timeout_p == MAX_SCHEDULE_TIMEOUT ||
2207                     *timeout_p > cfs_time_seconds(route->ksnr_timeout - now))
2208                         *timeout_p = cfs_time_seconds(route->ksnr_timeout - now);
2209         }
2210
2211         return NULL;
2212 }
2213
2214 int
2215 ksocknal_connd(void *arg)
2216 {
2217         spinlock_t *connd_lock = &ksocknal_data.ksnd_connd_lock;
2218         struct ksock_connreq *cr;
2219         wait_queue_entry_t wait;
2220         int nloops = 0;
2221         int cons_retry = 0;
2222
2223         cfs_block_allsigs();
2224
2225         init_waitqueue_entry(&wait, current);
2226
2227         spin_lock_bh(connd_lock);
2228
2229         LASSERT(ksocknal_data.ksnd_connd_starting > 0);
2230         ksocknal_data.ksnd_connd_starting--;
2231         ksocknal_data.ksnd_connd_running++;
2232
2233         while (!ksocknal_data.ksnd_shuttingdown) {
2234                 struct ksock_route *route = NULL;
2235                 time64_t sec = ktime_get_real_seconds();
2236                 long timeout = MAX_SCHEDULE_TIMEOUT;
2237                 int  dropped_lock = 0;
2238
2239                 if (ksocknal_connd_check_stop(sec, &timeout)) {
2240                         /* wakeup another one to check stop */
2241                         wake_up(&ksocknal_data.ksnd_connd_waitq);
2242                         break;
2243                 }
2244
2245                 if (ksocknal_connd_check_start(sec, &timeout)) {
2246                         /* created new thread */
2247                         dropped_lock = 1;
2248                 }
2249
2250                 if (!list_empty(&ksocknal_data.ksnd_connd_connreqs)) {
2251                         /* Connection accepted by the listener */
2252                         cr = list_entry(ksocknal_data.ksnd_connd_connreqs.next,
2253                                         struct ksock_connreq, ksncr_list);
2254
2255                         list_del(&cr->ksncr_list);
2256                         spin_unlock_bh(connd_lock);
2257                         dropped_lock = 1;
2258
2259                         ksocknal_create_conn(cr->ksncr_ni, NULL,
2260                                              cr->ksncr_sock, SOCKLND_CONN_NONE);
2261                         lnet_ni_decref(cr->ksncr_ni);
2262                         LIBCFS_FREE(cr, sizeof(*cr));
2263
2264                         spin_lock_bh(connd_lock);
2265                 }
2266
2267                 /* Only handle an outgoing connection request if there
2268                  * is a thread left to handle incoming connections and
2269                  * create new connd */
2270                 if (ksocknal_data.ksnd_connd_connecting + SOCKNAL_CONND_RESV <
2271                     ksocknal_data.ksnd_connd_running) {
2272                         route = ksocknal_connd_get_route_locked(&timeout);
2273                 }
2274                 if (route != NULL) {
2275                         list_del(&route->ksnr_connd_list);
2276                         ksocknal_data.ksnd_connd_connecting++;
2277                         spin_unlock_bh(connd_lock);
2278                         dropped_lock = 1;
2279
2280                         if (ksocknal_connect(route)) {
2281                                 /* consecutive retry */
2282                                 if (cons_retry++ > SOCKNAL_INSANITY_RECONN) {
2283                                         CWARN("massive consecutive "
2284                                               "re-connecting to %pI4h\n",
2285                                               &route->ksnr_ipaddr);
2286                                         cons_retry = 0;
2287                                 }
2288                         } else {
2289                                 cons_retry = 0;
2290                         }
2291
2292                         ksocknal_route_decref(route);
2293
2294                         spin_lock_bh(connd_lock);
2295                         ksocknal_data.ksnd_connd_connecting--;
2296                 }
2297
2298                 if (dropped_lock) {
2299                         if (++nloops < SOCKNAL_RESCHED)
2300                                 continue;
2301                         spin_unlock_bh(connd_lock);
2302                         nloops = 0;
2303                         cond_resched();
2304                         spin_lock_bh(connd_lock);
2305                         continue;
2306                 }
2307
2308                 /* Nothing to do for 'timeout'  */
2309                 set_current_state(TASK_INTERRUPTIBLE);
2310                 add_wait_queue_exclusive(&ksocknal_data.ksnd_connd_waitq, &wait);
2311                 spin_unlock_bh(connd_lock);
2312
2313                 nloops = 0;
2314                 schedule_timeout(timeout);
2315
2316                 remove_wait_queue(&ksocknal_data.ksnd_connd_waitq, &wait);
2317                 spin_lock_bh(connd_lock);
2318         }
2319         ksocknal_data.ksnd_connd_running--;
2320         spin_unlock_bh(connd_lock);
2321
2322         ksocknal_thread_fini();
2323         return 0;
2324 }
2325
2326 static struct ksock_conn *
2327 ksocknal_find_timed_out_conn(struct ksock_peer_ni *peer_ni)
2328 {
2329         /* We're called with a shared lock on ksnd_global_lock */
2330         struct ksock_conn *conn;
2331         struct list_head *ctmp;
2332         struct ksock_tx *tx;
2333
2334         list_for_each(ctmp, &peer_ni->ksnp_conns) {
2335                 int error;
2336
2337                 conn = list_entry(ctmp, struct ksock_conn, ksnc_list);
2338
2339                 /* Don't need the {get,put}connsock dance to deref ksnc_sock */
2340                 LASSERT (!conn->ksnc_closing);
2341
2342                 error = conn->ksnc_sock->sk->sk_err;
2343                 if (error != 0) {
2344                         ksocknal_conn_addref(conn);
2345
2346                         switch (error) {
2347                         case ECONNRESET:
2348                                 CNETERR("A connection with %s "
2349                                         "(%pI4h:%d) was reset; "
2350                                         "it may have rebooted.\n",
2351                                         libcfs_id2str(peer_ni->ksnp_id),
2352                                         &conn->ksnc_ipaddr,
2353                                         conn->ksnc_port);
2354                                 break;
2355                         case ETIMEDOUT:
2356                                 CNETERR("A connection with %s "
2357                                         "(%pI4h:%d) timed out; the "
2358                                         "network or node may be down.\n",
2359                                         libcfs_id2str(peer_ni->ksnp_id),
2360                                         &conn->ksnc_ipaddr,
2361                                         conn->ksnc_port);
2362                                 break;
2363                         default:
2364                                 CNETERR("An unexpected network error %d "
2365                                         "occurred with %s "
2366                                         "(%pI4h:%d\n", error,
2367                                         libcfs_id2str(peer_ni->ksnp_id),
2368                                         &conn->ksnc_ipaddr,
2369                                         conn->ksnc_port);
2370                                 break;
2371                         }
2372
2373                         return (conn);
2374                 }
2375
2376                 if (conn->ksnc_rx_started &&
2377                     ktime_get_seconds() >= conn->ksnc_rx_deadline) {
2378                         /* Timed out incomplete incoming message */
2379                         ksocknal_conn_addref(conn);
2380                         CNETERR("Timeout receiving from %s (%pI4h:%d), "
2381                                 "state %d wanted %d left %d\n",
2382                                 libcfs_id2str(peer_ni->ksnp_id),
2383                                 &conn->ksnc_ipaddr,
2384                                 conn->ksnc_port,
2385                                 conn->ksnc_rx_state,
2386                                 conn->ksnc_rx_nob_wanted,
2387                                 conn->ksnc_rx_nob_left);
2388                         return (conn);
2389                 }
2390
2391                 if ((!list_empty(&conn->ksnc_tx_queue) ||
2392                      conn->ksnc_sock->sk->sk_wmem_queued != 0) &&
2393                     ktime_get_seconds() >= conn->ksnc_tx_deadline) {
2394                         /* Timed out messages queued for sending or
2395                          * buffered in the socket's send buffer */
2396                         ksocknal_conn_addref(conn);
2397                         list_for_each_entry(tx, &conn->ksnc_tx_queue,
2398                                             tx_list)
2399                                 tx->tx_hstatus =
2400                                         LNET_MSG_STATUS_LOCAL_TIMEOUT;
2401                         CNETERR("Timeout sending data to %s (%pI4h:%d) "
2402                                 "the network or that node may be down.\n",
2403                                 libcfs_id2str(peer_ni->ksnp_id),
2404                                 &conn->ksnc_ipaddr, conn->ksnc_port);
2405                         return (conn);
2406                 }
2407         }
2408
2409         return (NULL);
2410 }
2411
2412 static inline void
2413 ksocknal_flush_stale_txs(struct ksock_peer_ni *peer_ni)
2414 {
2415         struct ksock_tx *tx;
2416         LIST_HEAD(stale_txs);
2417
2418         write_lock_bh(&ksocknal_data.ksnd_global_lock);
2419
2420         while (!list_empty(&peer_ni->ksnp_tx_queue)) {
2421                 tx = list_entry(peer_ni->ksnp_tx_queue.next,
2422                                 struct ksock_tx, tx_list);
2423
2424                 if (ktime_get_seconds() < tx->tx_deadline)
2425                         break;
2426
2427                 tx->tx_hstatus = LNET_MSG_STATUS_LOCAL_TIMEOUT;
2428
2429                 list_move_tail(&tx->tx_list, &stale_txs);
2430         }
2431
2432         write_unlock_bh(&ksocknal_data.ksnd_global_lock);
2433
2434         ksocknal_txlist_done(peer_ni->ksnp_ni, &stale_txs, -ETIMEDOUT);
2435 }
2436
2437 static int
2438 ksocknal_send_keepalive_locked(struct ksock_peer_ni *peer_ni)
2439 __must_hold(&ksocknal_data.ksnd_global_lock)
2440 {
2441         struct ksock_sched *sched;
2442         struct ksock_conn *conn;
2443         struct ksock_tx *tx;
2444
2445         /* last_alive will be updated by create_conn */
2446         if (list_empty(&peer_ni->ksnp_conns))
2447                 return 0;
2448
2449         if (peer_ni->ksnp_proto != &ksocknal_protocol_v3x)
2450                 return 0;
2451
2452         if (*ksocknal_tunables.ksnd_keepalive <= 0 ||
2453             ktime_get_seconds() < peer_ni->ksnp_last_alive +
2454                                   *ksocknal_tunables.ksnd_keepalive)
2455                 return 0;
2456
2457         if (ktime_get_seconds() < peer_ni->ksnp_send_keepalive)
2458                 return 0;
2459
2460         /* retry 10 secs later, so we wouldn't put pressure
2461          * on this peer_ni if we failed to send keepalive this time */
2462         peer_ni->ksnp_send_keepalive = ktime_get_seconds() + 10;
2463
2464         conn = ksocknal_find_conn_locked(peer_ni, NULL, 1);
2465         if (conn != NULL) {
2466                 sched = conn->ksnc_scheduler;
2467
2468                 spin_lock_bh(&sched->kss_lock);
2469                 if (!list_empty(&conn->ksnc_tx_queue)) {
2470                         spin_unlock_bh(&sched->kss_lock);
2471                         /* there is an queued ACK, don't need keepalive */
2472                         return 0;
2473                 }
2474
2475                 spin_unlock_bh(&sched->kss_lock);
2476         }
2477
2478         read_unlock(&ksocknal_data.ksnd_global_lock);
2479
2480         /* cookie = 1 is reserved for keepalive PING */
2481         tx = ksocknal_alloc_tx_noop(1, 1);
2482         if (tx == NULL) {
2483                 read_lock(&ksocknal_data.ksnd_global_lock);
2484                 return -ENOMEM;
2485         }
2486
2487         if (ksocknal_launch_packet(peer_ni->ksnp_ni, tx, peer_ni->ksnp_id) == 0) {
2488                 read_lock(&ksocknal_data.ksnd_global_lock);
2489                 return 1;
2490         }
2491
2492         ksocknal_free_tx(tx);
2493         read_lock(&ksocknal_data.ksnd_global_lock);
2494
2495         return -EIO;
2496 }
2497
2498
2499 static void
2500 ksocknal_check_peer_timeouts(int idx)
2501 {
2502         struct hlist_head *peers = &ksocknal_data.ksnd_peers[idx];
2503         struct ksock_peer_ni *peer_ni;
2504         struct ksock_conn *conn;
2505         struct ksock_tx *tx;
2506
2507  again:
2508         /* NB. We expect to have a look at all the peers and not find any
2509          * connections to time out, so we just use a shared lock while we
2510          * take a look...
2511          */
2512         read_lock(&ksocknal_data.ksnd_global_lock);
2513
2514         hlist_for_each_entry(peer_ni, peers, ksnp_list) {
2515                 struct ksock_tx *tx_stale;
2516                 time64_t deadline = 0;
2517                 int resid = 0;
2518                 int n = 0;
2519
2520                 if (ksocknal_send_keepalive_locked(peer_ni) != 0) {
2521                         read_unlock(&ksocknal_data.ksnd_global_lock);
2522                         goto again;
2523                 }
2524
2525                 conn = ksocknal_find_timed_out_conn(peer_ni);
2526
2527                 if (conn != NULL) {
2528                         read_unlock(&ksocknal_data.ksnd_global_lock);
2529
2530                         ksocknal_close_conn_and_siblings(conn, -ETIMEDOUT);
2531
2532                         /* NB we won't find this one again, but we can't
2533                          * just proceed with the next peer_ni, since we dropped
2534                          * ksnd_global_lock and it might be dead already!
2535                          */
2536                         ksocknal_conn_decref(conn);
2537                         goto again;
2538                 }
2539
2540                 /* we can't process stale txs right here because we're
2541                  * holding only shared lock
2542                  */
2543                 if (!list_empty(&peer_ni->ksnp_tx_queue)) {
2544                         struct ksock_tx *tx;
2545
2546                         tx = list_entry(peer_ni->ksnp_tx_queue.next,
2547                                         struct ksock_tx, tx_list);
2548                         if (ktime_get_seconds() >= tx->tx_deadline) {
2549                                 ksocknal_peer_addref(peer_ni);
2550                                 read_unlock(&ksocknal_data.ksnd_global_lock);
2551
2552                                 ksocknal_flush_stale_txs(peer_ni);
2553
2554                                 ksocknal_peer_decref(peer_ni);
2555                                 goto again;
2556                         }
2557                 }
2558
2559                 if (list_empty(&peer_ni->ksnp_zc_req_list))
2560                         continue;
2561
2562                 tx_stale = NULL;
2563                 spin_lock(&peer_ni->ksnp_lock);
2564                 list_for_each_entry(tx, &peer_ni->ksnp_zc_req_list, tx_zc_list) {
2565                         if (ktime_get_seconds() < tx->tx_deadline)
2566                                 break;
2567                         /* ignore the TX if connection is being closed */
2568                         if (tx->tx_conn->ksnc_closing)
2569                                 continue;
2570                         n++;
2571                         if (tx_stale == NULL)
2572                                 tx_stale = tx;
2573                 }
2574
2575                 if (tx_stale == NULL) {
2576                         spin_unlock(&peer_ni->ksnp_lock);
2577                         continue;
2578                 }
2579
2580                 deadline = tx_stale->tx_deadline;
2581                 resid    = tx_stale->tx_resid;
2582                 conn     = tx_stale->tx_conn;
2583                 ksocknal_conn_addref(conn);
2584
2585                 spin_unlock(&peer_ni->ksnp_lock);
2586                 read_unlock(&ksocknal_data.ksnd_global_lock);
2587
2588                 CERROR("Total %d stale ZC_REQs for peer_ni %s detected; the "
2589                        "oldest(%p) timed out %lld secs ago, "
2590                        "resid: %d, wmem: %d\n",
2591                        n, libcfs_nid2str(peer_ni->ksnp_id.nid), tx_stale,
2592                        ktime_get_seconds() - deadline,
2593                        resid, conn->ksnc_sock->sk->sk_wmem_queued);
2594
2595                 ksocknal_close_conn_and_siblings (conn, -ETIMEDOUT);
2596                 ksocknal_conn_decref(conn);
2597                 goto again;
2598         }
2599
2600         read_unlock(&ksocknal_data.ksnd_global_lock);
2601 }
2602
2603 int ksocknal_reaper(void *arg)
2604 {
2605         wait_queue_entry_t wait;
2606         struct ksock_conn *conn;
2607         struct ksock_sched *sched;
2608         LIST_HEAD(enomem_conns);
2609         int nenomem_conns;
2610         time64_t timeout;
2611         int i;
2612         int peer_index = 0;
2613         time64_t deadline = ktime_get_seconds();
2614
2615         cfs_block_allsigs ();
2616
2617         init_waitqueue_entry(&wait, current);
2618
2619         spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
2620
2621         while (!ksocknal_data.ksnd_shuttingdown) {
2622                 if (!list_empty(&ksocknal_data.ksnd_deathrow_conns)) {
2623                         conn = list_entry(ksocknal_data.ksnd_deathrow_conns.next,
2624                                           struct ksock_conn, ksnc_list);
2625                         list_del(&conn->ksnc_list);
2626
2627                         spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
2628
2629                         ksocknal_terminate_conn(conn);
2630                         ksocknal_conn_decref(conn);
2631
2632                         spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
2633                         continue;
2634                 }
2635
2636                 if (!list_empty(&ksocknal_data.ksnd_zombie_conns)) {
2637                         conn = list_entry(ksocknal_data.ksnd_zombie_conns.next,
2638                                           struct ksock_conn, ksnc_list);
2639                         list_del(&conn->ksnc_list);
2640
2641                         spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
2642
2643                         ksocknal_destroy_conn(conn);
2644
2645                         spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
2646                         continue;
2647                 }
2648
2649                 if (!list_empty(&ksocknal_data.ksnd_enomem_conns)) {
2650                         list_add(&enomem_conns,
2651                                      &ksocknal_data.ksnd_enomem_conns);
2652                         list_del_init(&ksocknal_data.ksnd_enomem_conns);
2653                 }
2654
2655                 spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
2656
2657                 /* reschedule all the connections that stalled with ENOMEM... */
2658                 nenomem_conns = 0;
2659                 while (!list_empty(&enomem_conns)) {
2660                         conn = list_entry(enomem_conns.next,
2661                                           struct ksock_conn, ksnc_tx_list);
2662                         list_del(&conn->ksnc_tx_list);
2663
2664                         sched = conn->ksnc_scheduler;
2665
2666                         spin_lock_bh(&sched->kss_lock);
2667
2668                         LASSERT(conn->ksnc_tx_scheduled);
2669                         conn->ksnc_tx_ready = 1;
2670                         list_add_tail(&conn->ksnc_tx_list,
2671                                           &sched->kss_tx_conns);
2672                         wake_up(&sched->kss_waitq);
2673
2674                         spin_unlock_bh(&sched->kss_lock);
2675                         nenomem_conns++;
2676                 }
2677
2678                 /* careful with the jiffy wrap... */
2679                 while ((timeout = deadline - ktime_get_seconds()) <= 0) {
2680                         const int n = 4;
2681                         const int p = 1;
2682                         int  chunk = HASH_SIZE(ksocknal_data.ksnd_peers);
2683                         unsigned int lnd_timeout;
2684
2685                         /* Time to check for timeouts on a few more peers: I
2686                          * do checks every 'p' seconds on a proportion of the
2687                          * peer_ni table and I need to check every connection
2688                          * 'n' times within a timeout interval, to ensure I
2689                          * detect a timeout on any connection within (n+1)/n
2690                          * times the timeout interval.
2691                          */
2692
2693                         lnd_timeout = lnet_get_lnd_timeout();
2694                         if (lnd_timeout > n * p)
2695                                 chunk = (chunk * n * p) / lnd_timeout;
2696                         if (chunk == 0)
2697                                 chunk = 1;
2698
2699                         for (i = 0; i < chunk; i++) {
2700                                 ksocknal_check_peer_timeouts(peer_index);
2701                                 peer_index = (peer_index + 1) %
2702                                         HASH_SIZE(ksocknal_data.ksnd_peers);
2703                         }
2704
2705                         deadline += p;
2706                 }
2707
2708                 if (nenomem_conns != 0) {
2709                         /* Reduce my timeout if I rescheduled ENOMEM conns.
2710                          * This also prevents me getting woken immediately
2711                          * if any go back on my enomem list. */
2712                         timeout = SOCKNAL_ENOMEM_RETRY;
2713                 }
2714                 ksocknal_data.ksnd_reaper_waketime = ktime_get_seconds() +
2715                                                      timeout;
2716
2717                 set_current_state(TASK_INTERRUPTIBLE);
2718                 add_wait_queue(&ksocknal_data.ksnd_reaper_waitq, &wait);
2719
2720                 if (!ksocknal_data.ksnd_shuttingdown &&
2721                     list_empty(&ksocknal_data.ksnd_deathrow_conns) &&
2722                     list_empty(&ksocknal_data.ksnd_zombie_conns))
2723                         schedule_timeout(cfs_time_seconds(timeout));
2724
2725                 set_current_state(TASK_RUNNING);
2726                 remove_wait_queue(&ksocknal_data.ksnd_reaper_waitq, &wait);
2727
2728                 spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
2729         }
2730
2731         spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
2732
2733         ksocknal_thread_fini();
2734         return 0;
2735 }