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