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