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