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