Whamcloud - gitweb
Branch HEAD
[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  2008 Sun Microsystems, Inc. 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 < (int) iov->iov_len) {
133                         iov->iov_base = (void *)((char *)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 < (int)kiov->kiov_len) {
171                         kiov->kiov_offset += nob;
172                         kiov->kiov_len -= nob;
173                         return rc;
174                 }
175
176                 nob -= (int)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 < (int)iov->iov_len) {
281                         iov->iov_len -= nob;
282                         iov->iov_base = (void *)((char *)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 < (int) 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                         CDEBUG (D_NETERROR, "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                         CDEBUG (D_NETERROR, "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 ksock_conn_t *
606 ksocknal_find_conn_locked(ksock_peer_t *peer, ksock_tx_t *tx, int nonblk)
607 {
608         struct list_head *tmp;
609         ksock_conn_t     *conn;
610         ksock_conn_t     *typed = NULL;
611         ksock_conn_t     *fallback = NULL;
612         int               tnob     = 0;
613         int               fnob     = 0;
614
615         list_for_each (tmp, &peer->ksnp_conns) {
616                 ksock_conn_t *c   = list_entry(tmp, ksock_conn_t, ksnc_list);
617                 int           nob = cfs_atomic_read(&c->ksnc_tx_nob) +
618                                     libcfs_sock_wmem_queued(c->ksnc_sock);
619                 int           rc;
620
621                 LASSERT (!c->ksnc_closing);
622                 LASSERT (c->ksnc_proto != NULL &&
623                          c->ksnc_proto->pro_match_tx != NULL);
624
625                 rc = c->ksnc_proto->pro_match_tx(c, tx, nonblk);
626
627                 switch (rc) {
628                 default:
629                         LBUG();
630                 case SOCKNAL_MATCH_NO: /* protocol rejected the tx */
631                         continue;
632
633                 case SOCKNAL_MATCH_YES: /* typed connection */
634                         if (typed == NULL || tnob > nob ||
635                             (tnob == nob && *ksocknal_tunables.ksnd_round_robin &&
636                              cfs_time_after(typed->ksnc_tx_last_post, c->ksnc_tx_last_post))) {
637                                 typed = c;
638                                 tnob  = nob;
639                         }
640                         break;
641
642                 case SOCKNAL_MATCH_MAY: /* fallback connection */
643                         if (fallback == NULL || fnob > nob ||
644                             (fnob == nob && *ksocknal_tunables.ksnd_round_robin &&
645                              cfs_time_after(fallback->ksnc_tx_last_post, c->ksnc_tx_last_post))) {
646                                 fallback = c;
647                                 fnob     = nob;
648                         }
649                         break;
650                 }
651         }
652
653         /* prefer the typed selection */
654         conn = (typed != NULL) ? typed : fallback;
655
656         if (conn != NULL)
657                 conn->ksnc_tx_last_post = cfs_time_current();
658
659         return conn;
660 }
661
662 void
663 ksocknal_tx_prep(ksock_conn_t *conn, ksock_tx_t *tx)
664 {
665         conn->ksnc_proto->pro_pack(tx);
666
667         cfs_atomic_add (tx->tx_nob, &conn->ksnc_tx_nob);
668         ksocknal_conn_addref(conn); /* +1 ref for tx */
669         tx->tx_conn = conn;
670 }
671
672 void
673 ksocknal_queue_tx_locked (ksock_tx_t *tx, ksock_conn_t *conn)
674 {
675         ksock_sched_t *sched = conn->ksnc_scheduler;
676         ksock_msg_t   *msg = &tx->tx_msg;
677         ksock_tx_t    *ztx = NULL;
678         int            bufnob = 0;
679
680         /* called holding global lock (read or irq-write) and caller may
681          * not have dropped this lock between finding conn and calling me,
682          * so we don't need the {get,put}connsock dance to deref
683          * ksnc_sock... */
684         LASSERT(!conn->ksnc_closing);
685
686         CDEBUG (D_NET, "Sending to %s ip %d.%d.%d.%d:%d\n", 
687                 libcfs_id2str(conn->ksnc_peer->ksnp_id),
688                 HIPQUAD(conn->ksnc_ipaddr),
689                 conn->ksnc_port);
690
691         ksocknal_tx_prep(conn, tx);
692
693         /* Ensure the frags we've been given EXACTLY match the number of
694          * bytes we want to send.  Many TCP/IP stacks disregard any total
695          * size parameters passed to them and just look at the frags. 
696          *
697          * We always expect at least 1 mapped fragment containing the
698          * complete ksocknal message header. */
699         LASSERT (lnet_iov_nob (tx->tx_niov, tx->tx_iov) +
700                  lnet_kiov_nob(tx->tx_nkiov, tx->tx_kiov) ==
701                  (unsigned int)tx->tx_nob);
702         LASSERT (tx->tx_niov >= 1);
703         LASSERT (tx->tx_resid == tx->tx_nob);
704
705         CDEBUG (D_NET, "Packet %p type %d, nob %d niov %d nkiov %d\n",
706                 tx, (tx->tx_lnetmsg != NULL) ? tx->tx_lnetmsg->msg_hdr.type:
707                                                KSOCK_MSG_NOOP,
708                 tx->tx_nob, tx->tx_niov, tx->tx_nkiov);
709
710         /*
711          * FIXME: SOCK_WMEM_QUEUED and SOCK_ERROR could block in __DARWIN8__
712          * but they're used inside spinlocks a lot.
713          */
714         bufnob = libcfs_sock_wmem_queued(conn->ksnc_sock);
715         cfs_spin_lock_bh (&sched->kss_lock);
716
717         if (list_empty(&conn->ksnc_tx_queue) && bufnob == 0) {
718                 /* First packet starts the timeout */
719                 conn->ksnc_tx_deadline =
720                         cfs_time_shift(*ksocknal_tunables.ksnd_timeout);
721                 conn->ksnc_tx_bufnob = 0;
722                 cfs_mb(); /* order with adding to tx_queue */
723         }
724
725         if (msg->ksm_type == KSOCK_MSG_NOOP) {
726                 /* The packet is noop ZC ACK, try to piggyback the ack_cookie
727                  * on a normal packet so I don't need to send it */
728                 LASSERT (msg->ksm_zc_cookies[1] != 0);
729                 LASSERT (conn->ksnc_proto->pro_queue_tx_zcack != NULL);
730
731                 if (conn->ksnc_proto->pro_queue_tx_zcack(conn, tx, 0))
732                         ztx = tx; /* ZC ACK piggybacked on ztx release tx later */
733
734         } else {
735                 /* It's a normal packet - can it piggback a noop zc-ack that
736                  * has been queued already? */
737                 LASSERT (msg->ksm_zc_cookies[1] == 0);
738                 LASSERT (conn->ksnc_proto->pro_queue_tx_msg != NULL);
739
740                 ztx = conn->ksnc_proto->pro_queue_tx_msg(conn, tx);
741                 /* ztx will be released later */
742         }
743
744         if (ztx != NULL) {
745                 cfs_atomic_sub (ztx->tx_nob, &conn->ksnc_tx_nob);
746                 list_add_tail(&ztx->tx_list, &sched->kss_zombie_noop_txs);
747         }
748
749         if (conn->ksnc_tx_ready &&      /* able to send */
750             !conn->ksnc_tx_scheduled) { /* not scheduled to send */
751                 /* +1 ref for scheduler */
752                 ksocknal_conn_addref(conn);
753                 list_add_tail (&conn->ksnc_tx_list,
754                                &sched->kss_tx_conns);
755                 conn->ksnc_tx_scheduled = 1;
756                 cfs_waitq_signal (&sched->kss_waitq);
757         }
758
759         cfs_spin_unlock_bh (&sched->kss_lock);
760 }
761
762
763 ksock_route_t *
764 ksocknal_find_connectable_route_locked (ksock_peer_t *peer)
765 {
766         struct list_head  *tmp;
767         ksock_route_t     *route;
768
769         list_for_each (tmp, &peer->ksnp_routes) {
770                 route = list_entry (tmp, ksock_route_t, ksnr_list);
771
772                 LASSERT (!route->ksnr_connecting || route->ksnr_scheduled);
773
774                 if (route->ksnr_scheduled)      /* connections being established */
775                         continue;
776
777                 /* all route types connected ? */
778                 if ((ksocknal_route_mask() & ~route->ksnr_connected) == 0)
779                         continue;
780
781                 /* too soon to retry this guy? */
782                 if (!(route->ksnr_retry_interval == 0 || /* first attempt */
783                       cfs_time_aftereq (cfs_time_current(),
784                                         route->ksnr_timeout)))
785                         continue;
786
787                 return (route);
788         }
789
790         return (NULL);
791 }
792
793 ksock_route_t *
794 ksocknal_find_connecting_route_locked (ksock_peer_t *peer)
795 {
796         struct list_head  *tmp;
797         ksock_route_t     *route;
798
799         list_for_each (tmp, &peer->ksnp_routes) {
800                 route = list_entry (tmp, ksock_route_t, ksnr_list);
801
802                 LASSERT (!route->ksnr_connecting || route->ksnr_scheduled);
803
804                 if (route->ksnr_scheduled)
805                         return (route);
806         }
807
808         return (NULL);
809 }
810
811 int
812 ksocknal_launch_packet (lnet_ni_t *ni, ksock_tx_t *tx, lnet_process_id_t id)
813 {
814         ksock_peer_t     *peer;
815         ksock_conn_t     *conn;
816         ksock_route_t    *route;
817         cfs_rwlock_t     *g_lock;
818         int               retry;
819         int               rc;
820
821         LASSERT (tx->tx_conn == NULL);
822
823         g_lock = &ksocknal_data.ksnd_global_lock;
824
825         for (retry = 0;; retry = 1) {
826                 cfs_read_lock (g_lock);
827                 peer = ksocknal_find_peer_locked(ni, id);
828                 if (peer != NULL) {
829                         if (ksocknal_find_connectable_route_locked(peer) == NULL) {
830                                 conn = ksocknal_find_conn_locked(peer, tx, tx->tx_nonblk);
831                                 if (conn != NULL) {
832                                         /* I've got no routes that need to be
833                                          * connecting and I do have an actual
834                                          * connection... */
835                                         ksocknal_queue_tx_locked (tx, conn);
836                                         cfs_read_unlock (g_lock);
837                                         return (0);
838                                 }
839                         }
840                 }
841
842                 /* I'll need a write lock... */
843                 cfs_read_unlock (g_lock);
844
845                 cfs_write_lock_bh (g_lock);
846
847                 peer = ksocknal_find_peer_locked(ni, id);
848                 if (peer != NULL)
849                         break;
850
851                 cfs_write_unlock_bh (g_lock);
852
853                 if ((id.pid & LNET_PID_USERFLAG) != 0) {
854                         CERROR("Refusing to create a connection to "
855                                "userspace process %s\n", libcfs_id2str(id));
856                         return -EHOSTUNREACH;
857                 }
858
859                 if (retry) {
860                         CERROR("Can't find peer %s\n", libcfs_id2str(id));
861                         return -EHOSTUNREACH;
862                 }
863
864                 rc = ksocknal_add_peer(ni, id,
865                                        LNET_NIDADDR(id.nid),
866                                        lnet_acceptor_port());
867                 if (rc != 0) {
868                         CERROR("Can't add peer %s: %d\n",
869                                libcfs_id2str(id), rc);
870                         return rc;
871                 }
872         }
873
874         for (;;) {
875                 /* launch any/all connections that need it */
876                 route = ksocknal_find_connectable_route_locked (peer);
877                 if (route == NULL)
878                         break;
879
880                 ksocknal_launch_connection_locked (route);
881         }
882
883         conn = ksocknal_find_conn_locked(peer, tx, tx->tx_nonblk);
884         if (conn != NULL) {
885                 /* Connection exists; queue message on it */
886                 ksocknal_queue_tx_locked (tx, conn);
887                 cfs_write_unlock_bh (g_lock);
888                 return (0);
889         }
890
891         if (peer->ksnp_accepting > 0 ||
892             ksocknal_find_connecting_route_locked (peer) != NULL) {
893                 /* the message is going to be pinned to the peer */
894                 tx->tx_deadline =
895                         cfs_time_shift(*ksocknal_tunables.ksnd_timeout);
896
897                 /* Queue the message until a connection is established */
898                 list_add_tail (&tx->tx_list, &peer->ksnp_tx_queue);
899                 cfs_write_unlock_bh (g_lock);
900                 return 0;
901         }
902
903         cfs_write_unlock_bh (g_lock);
904
905         /* NB Routes may be ignored if connections to them failed recently */
906         CDEBUG(D_NETERROR, "No usable routes to %s\n", libcfs_id2str(id));
907         return (-EHOSTUNREACH);
908 }
909
910 int
911 ksocknal_send(lnet_ni_t *ni, void *private, lnet_msg_t *lntmsg)
912 {
913         int               type = lntmsg->msg_type;
914         lnet_process_id_t target = lntmsg->msg_target;
915         unsigned int      payload_niov = lntmsg->msg_niov;
916         struct iovec     *payload_iov = lntmsg->msg_iov;
917         lnet_kiov_t      *payload_kiov = lntmsg->msg_kiov;
918         unsigned int      payload_offset = lntmsg->msg_offset;
919         unsigned int      payload_nob = lntmsg->msg_len;
920         ksock_tx_t       *tx;
921         int               desc_size;
922         int               rc;
923
924         /* NB 'private' is different depending on what we're sending.
925          * Just ignore it... */
926
927         CDEBUG(D_NET, "sending %u bytes in %d frags to %s\n",
928                payload_nob, payload_niov, libcfs_id2str(target));
929
930         LASSERT (payload_nob == 0 || payload_niov > 0);
931         LASSERT (payload_niov <= LNET_MAX_IOV);
932         /* payload is either all vaddrs or all pages */
933         LASSERT (!(payload_kiov != NULL && payload_iov != NULL));
934         LASSERT (!cfs_in_interrupt ());
935
936         if (payload_iov != NULL)
937                 desc_size = offsetof(ksock_tx_t,
938                                      tx_frags.virt.iov[1 + payload_niov]);
939         else
940                 desc_size = offsetof(ksock_tx_t,
941                                      tx_frags.paged.kiov[payload_niov]);
942
943         tx = ksocknal_alloc_tx(KSOCK_MSG_LNET, desc_size);
944         if (tx == NULL) {
945                 CERROR("Can't allocate tx desc type %d size %d\n",
946                        type, desc_size);
947                 return (-ENOMEM);
948         }
949
950         tx->tx_conn = NULL;                     /* set when assigned a conn */
951         tx->tx_lnetmsg = lntmsg;
952
953         if (payload_iov != NULL) {
954                 tx->tx_kiov = NULL;
955                 tx->tx_nkiov = 0;
956                 tx->tx_iov = tx->tx_frags.virt.iov;
957                 tx->tx_niov = 1 +
958                               lnet_extract_iov(payload_niov, &tx->tx_iov[1],
959                                                payload_niov, payload_iov,
960                                                payload_offset, payload_nob);
961         } else {
962                 tx->tx_niov = 1;
963                 tx->tx_iov = &tx->tx_frags.paged.iov;
964                 tx->tx_kiov = tx->tx_frags.paged.kiov;
965                 tx->tx_nkiov = lnet_extract_kiov(payload_niov, tx->tx_kiov,
966                                                  payload_niov, payload_kiov,
967                                                  payload_offset, payload_nob);
968
969                 if (payload_nob >= *ksocknal_tunables.ksnd_zc_min_payload)
970                         tx->tx_zc_capable = 1;
971         }
972
973         socklnd_init_msg(&tx->tx_msg, KSOCK_MSG_LNET);
974
975         /* The first fragment will be set later in pro_pack */
976         rc = ksocknal_launch_packet(ni, tx, target);
977         if (rc == 0)
978                 return (0);
979
980         ksocknal_free_tx(tx);
981         return (-EIO);
982 }
983
984 int
985 ksocknal_thread_start (int (*fn)(void *arg), void *arg)
986 {
987         long          pid = cfs_kernel_thread (fn, arg, 0);
988
989         if (pid < 0)
990                 return ((int)pid);
991
992         cfs_write_lock_bh (&ksocknal_data.ksnd_global_lock);
993         ksocknal_data.ksnd_nthreads++;
994         cfs_write_unlock_bh (&ksocknal_data.ksnd_global_lock);
995         return (0);
996 }
997
998 void
999 ksocknal_thread_fini (void)
1000 {
1001         cfs_write_lock_bh (&ksocknal_data.ksnd_global_lock);
1002         ksocknal_data.ksnd_nthreads--;
1003         cfs_write_unlock_bh (&ksocknal_data.ksnd_global_lock);
1004 }
1005
1006 int
1007 ksocknal_new_packet (ksock_conn_t *conn, int nob_to_skip)
1008 {
1009         static char ksocknal_slop_buffer[4096];
1010
1011         int            nob;
1012         unsigned int   niov;
1013         int            skipped;
1014
1015         LASSERT(conn->ksnc_proto != NULL);
1016
1017         if ((*ksocknal_tunables.ksnd_eager_ack & conn->ksnc_type) != 0) {
1018                 /* Remind the socket to ack eagerly... */
1019                 ksocknal_lib_eager_ack(conn);
1020         }
1021
1022         if (nob_to_skip == 0) {         /* right at next packet boundary now */
1023                 conn->ksnc_rx_started = 0;
1024                 cfs_mb();                       /* racing with timeout thread */
1025
1026                 switch (conn->ksnc_proto->pro_version) {
1027                 case  KSOCK_PROTO_V2:
1028                 case  KSOCK_PROTO_V3:
1029                         conn->ksnc_rx_state = SOCKNAL_RX_KSM_HEADER;
1030                         conn->ksnc_rx_iov = (struct iovec *)&conn->ksnc_rx_iov_space;
1031                         conn->ksnc_rx_iov[0].iov_base = (char *)&conn->ksnc_msg;
1032
1033                         conn->ksnc_rx_nob_wanted = offsetof(ksock_msg_t, ksm_u);
1034                         conn->ksnc_rx_nob_left = offsetof(ksock_msg_t, ksm_u);
1035                         conn->ksnc_rx_iov[0].iov_len  = offsetof(ksock_msg_t, ksm_u);
1036                         break;
1037
1038                 case KSOCK_PROTO_V1:
1039                         /* Receiving bare lnet_hdr_t */
1040                         conn->ksnc_rx_state = SOCKNAL_RX_LNET_HEADER;
1041                         conn->ksnc_rx_nob_wanted = sizeof(lnet_hdr_t);
1042                         conn->ksnc_rx_nob_left = sizeof(lnet_hdr_t);
1043
1044                         conn->ksnc_rx_iov = (struct iovec *)&conn->ksnc_rx_iov_space;
1045                         conn->ksnc_rx_iov[0].iov_base = (char *)&conn->ksnc_msg.ksm_u.lnetmsg;
1046                         conn->ksnc_rx_iov[0].iov_len  = sizeof (lnet_hdr_t);
1047                         break;
1048
1049                 default:
1050                         LBUG ();
1051                 }
1052                 conn->ksnc_rx_niov = 1;
1053
1054                 conn->ksnc_rx_kiov = NULL;
1055                 conn->ksnc_rx_nkiov = 0;
1056                 conn->ksnc_rx_csum = ~0;
1057                 return (1);
1058         }
1059
1060         /* Set up to skip as much as possible now.  If there's more left
1061          * (ran out of iov entries) we'll get called again */
1062
1063         conn->ksnc_rx_state = SOCKNAL_RX_SLOP;
1064         conn->ksnc_rx_nob_left = nob_to_skip;
1065         conn->ksnc_rx_iov = (struct iovec *)&conn->ksnc_rx_iov_space;
1066         skipped = 0;
1067         niov = 0;
1068
1069         do {
1070                 nob = MIN (nob_to_skip, sizeof (ksocknal_slop_buffer));
1071
1072                 conn->ksnc_rx_iov[niov].iov_base = ksocknal_slop_buffer;
1073                 conn->ksnc_rx_iov[niov].iov_len  = nob;
1074                 niov++;
1075                 skipped += nob;
1076                 nob_to_skip -=nob;
1077
1078         } while (nob_to_skip != 0 &&    /* mustn't overflow conn's rx iov */
1079                  niov < sizeof(conn->ksnc_rx_iov_space) / sizeof (struct iovec));
1080
1081         conn->ksnc_rx_niov = niov;
1082         conn->ksnc_rx_kiov = NULL;
1083         conn->ksnc_rx_nkiov = 0;
1084         conn->ksnc_rx_nob_wanted = skipped;
1085         return (0);
1086 }
1087
1088 int
1089 ksocknal_process_receive (ksock_conn_t *conn)
1090 {
1091         lnet_hdr_t        *lhdr;
1092         lnet_process_id_t *id;
1093         int                rc;
1094
1095         LASSERT (cfs_atomic_read(&conn->ksnc_conn_refcount) > 0);
1096
1097         /* NB: sched lock NOT held */
1098         /* SOCKNAL_RX_LNET_HEADER is here for backward compatability */
1099         LASSERT (conn->ksnc_rx_state == SOCKNAL_RX_KSM_HEADER ||
1100                  conn->ksnc_rx_state == SOCKNAL_RX_LNET_PAYLOAD ||
1101                  conn->ksnc_rx_state == SOCKNAL_RX_LNET_HEADER ||
1102                  conn->ksnc_rx_state == SOCKNAL_RX_SLOP);
1103  again:
1104         if (conn->ksnc_rx_nob_wanted != 0) {
1105                 rc = ksocknal_receive(conn);
1106
1107                 if (rc <= 0) {
1108                         LASSERT (rc != -EAGAIN);
1109
1110                         if (rc == 0)
1111                                 CDEBUG (D_NET, "[%p] EOF from %s"
1112                                         " ip %d.%d.%d.%d:%d\n", conn,
1113                                         libcfs_id2str(conn->ksnc_peer->ksnp_id),
1114                                         HIPQUAD(conn->ksnc_ipaddr),
1115                                         conn->ksnc_port);
1116                         else if (!conn->ksnc_closing)
1117                                 CERROR ("[%p] Error %d on read from %s"
1118                                         " ip %d.%d.%d.%d:%d\n",
1119                                         conn, rc,
1120                                         libcfs_id2str(conn->ksnc_peer->ksnp_id),
1121                                         HIPQUAD(conn->ksnc_ipaddr),
1122                                         conn->ksnc_port);
1123
1124                         /* it's not an error if conn is being closed */
1125                         ksocknal_close_conn_and_siblings (conn,
1126                                                           (conn->ksnc_closing) ? 0 : rc);
1127                         return (rc == 0 ? -ESHUTDOWN : rc);
1128                 }
1129
1130                 if (conn->ksnc_rx_nob_wanted != 0) {
1131                         /* short read */
1132                         return (-EAGAIN);
1133                 }
1134         }
1135         switch (conn->ksnc_rx_state) {
1136         case SOCKNAL_RX_KSM_HEADER:
1137                 if (conn->ksnc_flip) {
1138                         __swab32s(&conn->ksnc_msg.ksm_type);
1139                         __swab32s(&conn->ksnc_msg.ksm_csum);
1140                         __swab64s(&conn->ksnc_msg.ksm_zc_cookies[0]);
1141                         __swab64s(&conn->ksnc_msg.ksm_zc_cookies[1]);
1142                 }
1143
1144                 if (conn->ksnc_msg.ksm_type != KSOCK_MSG_NOOP &&
1145                     conn->ksnc_msg.ksm_type != KSOCK_MSG_LNET) {
1146                         CERROR("%s: Unknown message type: %x\n",
1147                                libcfs_id2str(conn->ksnc_peer->ksnp_id),
1148                                conn->ksnc_msg.ksm_type);
1149                         ksocknal_new_packet(conn, 0);
1150                         ksocknal_close_conn_and_siblings(conn, -EPROTO);
1151                         return (-EPROTO);
1152                 }
1153
1154                 if (conn->ksnc_msg.ksm_type == KSOCK_MSG_NOOP &&
1155                     conn->ksnc_msg.ksm_csum != 0 &&     /* has checksum */
1156                     conn->ksnc_msg.ksm_csum != conn->ksnc_rx_csum) {
1157                         /* NOOP Checksum error */
1158                         CERROR("%s: Checksum error, wire:0x%08X data:0x%08X\n",
1159                                libcfs_id2str(conn->ksnc_peer->ksnp_id),
1160                                conn->ksnc_msg.ksm_csum, conn->ksnc_rx_csum);
1161                         ksocknal_new_packet(conn, 0);
1162                         ksocknal_close_conn_and_siblings(conn, -EPROTO);
1163                         return (-EIO);
1164                 }
1165
1166                 if (conn->ksnc_msg.ksm_zc_cookies[1] != 0) {
1167                         __u64 cookie = 0;
1168
1169                         LASSERT (conn->ksnc_proto != &ksocknal_protocol_v1x);
1170
1171                         if (conn->ksnc_msg.ksm_type == KSOCK_MSG_NOOP)
1172                                 cookie = conn->ksnc_msg.ksm_zc_cookies[0];
1173
1174                         rc = conn->ksnc_proto->pro_handle_zcack(conn, cookie,
1175                                                conn->ksnc_msg.ksm_zc_cookies[1]);
1176
1177                         if (rc != 0) {
1178                                 CERROR("%s: Unknown ZC-ACK cookie: "LPU64", "LPU64"\n",
1179                                        libcfs_id2str(conn->ksnc_peer->ksnp_id),
1180                                        cookie, conn->ksnc_msg.ksm_zc_cookies[1]);
1181                                 ksocknal_new_packet(conn, 0);
1182                                 ksocknal_close_conn_and_siblings(conn, -EPROTO);
1183                                 return (rc);
1184                         }
1185                 }
1186
1187                 if (conn->ksnc_msg.ksm_type == KSOCK_MSG_NOOP) {
1188                         ksocknal_new_packet (conn, 0);
1189                         return 0;       /* NOOP is done and just return */
1190                 }
1191
1192                 conn->ksnc_rx_state = SOCKNAL_RX_LNET_HEADER;
1193                 conn->ksnc_rx_nob_wanted = sizeof(ksock_lnet_msg_t);
1194                 conn->ksnc_rx_nob_left = sizeof(ksock_lnet_msg_t);
1195
1196                 conn->ksnc_rx_iov = (struct iovec *)&conn->ksnc_rx_iov_space;
1197                 conn->ksnc_rx_iov[0].iov_base = (char *)&conn->ksnc_msg.ksm_u.lnetmsg;
1198                 conn->ksnc_rx_iov[0].iov_len  = sizeof(ksock_lnet_msg_t);
1199
1200                 conn->ksnc_rx_niov = 1;
1201                 conn->ksnc_rx_kiov = NULL;
1202                 conn->ksnc_rx_nkiov = 0;
1203
1204                 goto again;     /* read lnet header now */
1205
1206         case SOCKNAL_RX_LNET_HEADER:
1207                 /* unpack message header */
1208                 conn->ksnc_proto->pro_unpack(&conn->ksnc_msg);
1209
1210                 if ((conn->ksnc_peer->ksnp_id.pid & LNET_PID_USERFLAG) != 0) {
1211                         /* Userspace peer */
1212                         lhdr = &conn->ksnc_msg.ksm_u.lnetmsg.ksnm_hdr;
1213                         id   = &conn->ksnc_peer->ksnp_id;
1214
1215                         /* Substitute process ID assigned at connection time */
1216                         lhdr->src_pid = cpu_to_le32(id->pid);
1217                         lhdr->src_nid = cpu_to_le64(id->nid);
1218                 }
1219
1220                 conn->ksnc_rx_state = SOCKNAL_RX_PARSE;
1221                 ksocknal_conn_addref(conn);     /* ++ref while parsing */
1222
1223                 rc = lnet_parse(conn->ksnc_peer->ksnp_ni,
1224                                 &conn->ksnc_msg.ksm_u.lnetmsg.ksnm_hdr,
1225                                 conn->ksnc_peer->ksnp_id.nid, conn, 0);
1226                 if (rc < 0) {
1227                         /* I just received garbage: give up on this conn */
1228                         ksocknal_new_packet(conn, 0);
1229                         ksocknal_close_conn_and_siblings (conn, rc);
1230                         ksocknal_conn_decref(conn);
1231                         return (-EPROTO);
1232                 }
1233
1234                 /* I'm racing with ksocknal_recv() */
1235                 LASSERT (conn->ksnc_rx_state == SOCKNAL_RX_PARSE ||
1236                          conn->ksnc_rx_state == SOCKNAL_RX_LNET_PAYLOAD);
1237
1238                 if (conn->ksnc_rx_state != SOCKNAL_RX_LNET_PAYLOAD)
1239                         return 0;
1240
1241                 /* ksocknal_recv() got called */
1242                 goto again;
1243
1244         case SOCKNAL_RX_LNET_PAYLOAD:
1245                 /* payload all received */
1246                 rc = 0;
1247
1248                 if (conn->ksnc_rx_nob_left == 0 &&   /* not truncating */
1249                     conn->ksnc_msg.ksm_csum != 0 &&  /* has checksum */
1250                     conn->ksnc_msg.ksm_csum != conn->ksnc_rx_csum) {
1251                         CERROR("%s: Checksum error, wire:0x%08X data:0x%08X\n",
1252                                libcfs_id2str(conn->ksnc_peer->ksnp_id),
1253                                conn->ksnc_msg.ksm_csum, conn->ksnc_rx_csum);
1254                         rc = -EIO;
1255                 }
1256
1257                 if (rc == 0 && conn->ksnc_msg.ksm_zc_cookies[0] != 0) {
1258                         LASSERT(conn->ksnc_proto != &ksocknal_protocol_v1x);
1259
1260                         lhdr = &conn->ksnc_msg.ksm_u.lnetmsg.ksnm_hdr;
1261                         id   = &conn->ksnc_peer->ksnp_id;
1262
1263                         rc = conn->ksnc_proto->pro_handle_zcreq(conn,
1264                                                conn->ksnc_msg.ksm_zc_cookies[0],
1265                                                le64_to_cpu(lhdr->src_nid) != id->nid);
1266                 }
1267
1268                 lnet_finalize(conn->ksnc_peer->ksnp_ni, conn->ksnc_cookie, rc);
1269
1270                 if (rc != 0) {
1271                         ksocknal_new_packet(conn, 0);
1272                         ksocknal_close_conn_and_siblings (conn, rc);
1273                         return (-EPROTO);
1274                 }
1275                 /* Fall through */
1276
1277         case SOCKNAL_RX_SLOP:
1278                 /* starting new packet? */
1279                 if (ksocknal_new_packet (conn, conn->ksnc_rx_nob_left))
1280                         return 0;       /* come back later */
1281                 goto again;             /* try to finish reading slop now */
1282
1283         default:
1284                 break;
1285         }
1286
1287         /* Not Reached */
1288         LBUG ();
1289         return (-EINVAL);                       /* keep gcc happy */
1290 }
1291
1292 int
1293 ksocknal_recv (lnet_ni_t *ni, void *private, lnet_msg_t *msg, int delayed,
1294                unsigned int niov, struct iovec *iov, lnet_kiov_t *kiov,
1295                unsigned int offset, unsigned int mlen, unsigned int rlen)
1296 {
1297         ksock_conn_t  *conn = (ksock_conn_t *)private;
1298         ksock_sched_t *sched = conn->ksnc_scheduler;
1299
1300         LASSERT (mlen <= rlen);
1301         LASSERT (niov <= LNET_MAX_IOV);
1302
1303         conn->ksnc_cookie = msg;
1304         conn->ksnc_rx_nob_wanted = mlen;
1305         conn->ksnc_rx_nob_left   = rlen;
1306
1307         if (mlen == 0 || iov != NULL) {
1308                 conn->ksnc_rx_nkiov = 0;
1309                 conn->ksnc_rx_kiov = NULL;
1310                 conn->ksnc_rx_iov = conn->ksnc_rx_iov_space.iov;
1311                 conn->ksnc_rx_niov =
1312                         lnet_extract_iov(LNET_MAX_IOV, conn->ksnc_rx_iov,
1313                                          niov, iov, offset, mlen);
1314         } else {
1315                 conn->ksnc_rx_niov = 0;
1316                 conn->ksnc_rx_iov  = NULL;
1317                 conn->ksnc_rx_kiov = conn->ksnc_rx_iov_space.kiov;
1318                 conn->ksnc_rx_nkiov =
1319                         lnet_extract_kiov(LNET_MAX_IOV, conn->ksnc_rx_kiov,
1320                                           niov, kiov, offset, mlen);
1321         }
1322
1323         LASSERT (mlen ==
1324                  lnet_iov_nob (conn->ksnc_rx_niov, conn->ksnc_rx_iov) +
1325                  lnet_kiov_nob (conn->ksnc_rx_nkiov, conn->ksnc_rx_kiov));
1326
1327         LASSERT (conn->ksnc_rx_scheduled);
1328
1329         cfs_spin_lock_bh (&sched->kss_lock);
1330
1331         switch (conn->ksnc_rx_state) {
1332         case SOCKNAL_RX_PARSE_WAIT:
1333                 list_add_tail(&conn->ksnc_rx_list, &sched->kss_rx_conns);
1334                 cfs_waitq_signal (&sched->kss_waitq);
1335                 LASSERT (conn->ksnc_rx_ready);
1336                 break;
1337
1338         case SOCKNAL_RX_PARSE:
1339                 /* scheduler hasn't noticed I'm parsing yet */
1340                 break;
1341         }
1342
1343         conn->ksnc_rx_state = SOCKNAL_RX_LNET_PAYLOAD;
1344
1345         cfs_spin_unlock_bh (&sched->kss_lock);
1346         ksocknal_conn_decref(conn);
1347         return (0);
1348 }
1349
1350 static inline int
1351 ksocknal_sched_cansleep(ksock_sched_t *sched)
1352 {
1353         int           rc;
1354
1355         cfs_spin_lock_bh (&sched->kss_lock);
1356
1357         rc = (!ksocknal_data.ksnd_shuttingdown &&
1358               list_empty(&sched->kss_rx_conns) &&
1359               list_empty(&sched->kss_tx_conns));
1360
1361         cfs_spin_unlock_bh (&sched->kss_lock);
1362         return (rc);
1363 }
1364
1365 int ksocknal_scheduler (void *arg)
1366 {
1367         ksock_sched_t     *sched = (ksock_sched_t *)arg;
1368         ksock_conn_t      *conn;
1369         ksock_tx_t        *tx;
1370         int                rc;
1371         int                nloops = 0;
1372         int                id = (int)(sched - ksocknal_data.ksnd_schedulers);
1373         char               name[16];
1374
1375         snprintf (name, sizeof (name),"socknal_sd%02d", id);
1376         cfs_daemonize (name);
1377         cfs_block_allsigs ();
1378
1379         if (ksocknal_lib_bind_thread_to_cpu(id))
1380                 CERROR ("Can't set CPU affinity for %s to %d\n", name, id);
1381
1382         cfs_spin_lock_bh (&sched->kss_lock);
1383
1384         while (!ksocknal_data.ksnd_shuttingdown) {
1385                 int did_something = 0;
1386
1387                 /* Ensure I progress everything semi-fairly */
1388
1389                 if (!list_empty (&sched->kss_rx_conns)) {
1390                         conn = list_entry(sched->kss_rx_conns.next,
1391                                           ksock_conn_t, ksnc_rx_list);
1392                         list_del(&conn->ksnc_rx_list);
1393
1394                         LASSERT(conn->ksnc_rx_scheduled);
1395                         LASSERT(conn->ksnc_rx_ready);
1396
1397                         /* clear rx_ready in case receive isn't complete.
1398                          * Do it BEFORE we call process_recv, since
1399                          * data_ready can set it any time after we release
1400                          * kss_lock. */
1401                         conn->ksnc_rx_ready = 0;
1402                         cfs_spin_unlock_bh (&sched->kss_lock);
1403
1404                         rc = ksocknal_process_receive(conn);
1405
1406                         cfs_spin_lock_bh (&sched->kss_lock);
1407
1408                         /* I'm the only one that can clear this flag */
1409                         LASSERT(conn->ksnc_rx_scheduled);
1410
1411                         /* Did process_receive get everything it wanted? */
1412                         if (rc == 0)
1413                                 conn->ksnc_rx_ready = 1;
1414
1415                         if (conn->ksnc_rx_state == SOCKNAL_RX_PARSE) {
1416                                 /* Conn blocked waiting for ksocknal_recv()
1417                                  * I change its state (under lock) to signal
1418                                  * it can be rescheduled */
1419                                 conn->ksnc_rx_state = SOCKNAL_RX_PARSE_WAIT;
1420                         } else if (conn->ksnc_rx_ready) {
1421                                 /* reschedule for rx */
1422                                 list_add_tail (&conn->ksnc_rx_list,
1423                                                &sched->kss_rx_conns);
1424                         } else {
1425                                 conn->ksnc_rx_scheduled = 0;
1426                                 /* drop my ref */
1427                                 ksocknal_conn_decref(conn);
1428                         }
1429
1430                         did_something = 1;
1431                 }
1432
1433                 if (!list_empty (&sched->kss_tx_conns)) {
1434                         CFS_LIST_HEAD    (zlist);
1435
1436                         if (!list_empty(&sched->kss_zombie_noop_txs)) {
1437                                 list_add(&zlist, &sched->kss_zombie_noop_txs);
1438                                 list_del_init(&sched->kss_zombie_noop_txs);
1439                         }
1440
1441                         conn = list_entry(sched->kss_tx_conns.next,
1442                                           ksock_conn_t, ksnc_tx_list);
1443                         list_del (&conn->ksnc_tx_list);
1444
1445                         LASSERT(conn->ksnc_tx_scheduled);
1446                         LASSERT(conn->ksnc_tx_ready);
1447                         LASSERT(!list_empty(&conn->ksnc_tx_queue));
1448
1449                         tx = list_entry(conn->ksnc_tx_queue.next,
1450                                         ksock_tx_t, tx_list);
1451
1452                         if (conn->ksnc_tx_carrier == tx)
1453                                 ksocknal_next_tx_carrier(conn);
1454
1455                         /* dequeue now so empty list => more to send */
1456                         list_del(&tx->tx_list);
1457
1458                         /* Clear tx_ready in case send isn't complete.  Do
1459                          * it BEFORE we call process_transmit, since
1460                          * write_space can set it any time after we release
1461                          * kss_lock. */
1462                         conn->ksnc_tx_ready = 0;
1463                         cfs_spin_unlock_bh (&sched->kss_lock);
1464
1465                         if (!list_empty(&zlist)) {
1466                                 /* free zombie noop txs, it's fast because 
1467                                  * noop txs are just put in freelist */
1468                                 ksocknal_txlist_done(NULL, &zlist, 0);
1469                         }
1470
1471                         rc = ksocknal_process_transmit(conn, tx);
1472
1473                         if (rc == -ENOMEM || rc == -EAGAIN) {
1474                                 /* Incomplete send: replace tx on HEAD of tx_queue */
1475                                 cfs_spin_lock_bh (&sched->kss_lock);
1476                                 list_add (&tx->tx_list, &conn->ksnc_tx_queue);
1477                         } else {
1478                                 /* Complete send; tx -ref */
1479                                 ksocknal_tx_decref (tx);
1480
1481                                 cfs_spin_lock_bh (&sched->kss_lock);
1482                                 /* assume space for more */
1483                                 conn->ksnc_tx_ready = 1;
1484                         }
1485
1486                         if (rc == -ENOMEM) {
1487                                 /* Do nothing; after a short timeout, this
1488                                  * conn will be reposted on kss_tx_conns. */
1489                         } else if (conn->ksnc_tx_ready &&
1490                                    !list_empty (&conn->ksnc_tx_queue)) {
1491                                 /* reschedule for tx */
1492                                 list_add_tail (&conn->ksnc_tx_list,
1493                                                &sched->kss_tx_conns);
1494                         } else {
1495                                 conn->ksnc_tx_scheduled = 0;
1496                                 /* drop my ref */
1497                                 ksocknal_conn_decref(conn);
1498                         }
1499
1500                         did_something = 1;
1501                 }
1502                 if (!did_something ||           /* nothing to do */
1503                     ++nloops == SOCKNAL_RESCHED) { /* hogging CPU? */
1504                         cfs_spin_unlock_bh (&sched->kss_lock);
1505
1506                         nloops = 0;
1507
1508                         if (!did_something) {   /* wait for something to do */
1509                                 cfs_wait_event_interruptible_exclusive(
1510                                         sched->kss_waitq,
1511                                         !ksocknal_sched_cansleep(sched), rc);
1512                                 LASSERT (rc == 0);
1513                         } else {
1514                                 our_cond_resched();
1515                         }
1516
1517                         cfs_spin_lock_bh (&sched->kss_lock);
1518                 }
1519         }
1520
1521         cfs_spin_unlock_bh (&sched->kss_lock);
1522         ksocknal_thread_fini ();
1523         return (0);
1524 }
1525
1526 /*
1527  * Add connection to kss_rx_conns of scheduler
1528  * and wakeup the scheduler.
1529  */
1530 void ksocknal_read_callback (ksock_conn_t *conn)
1531 {
1532         ksock_sched_t *sched;
1533         ENTRY;
1534
1535         sched = conn->ksnc_scheduler;
1536
1537         cfs_spin_lock_bh (&sched->kss_lock);
1538
1539         conn->ksnc_rx_ready = 1;
1540
1541         if (!conn->ksnc_rx_scheduled) {  /* not being progressed */
1542                 list_add_tail(&conn->ksnc_rx_list,
1543                               &sched->kss_rx_conns);
1544                 conn->ksnc_rx_scheduled = 1;
1545                 /* extra ref for scheduler */
1546                 ksocknal_conn_addref(conn);
1547
1548                 cfs_waitq_signal (&sched->kss_waitq);
1549         }
1550         cfs_spin_unlock_bh (&sched->kss_lock);
1551
1552         EXIT;
1553 }
1554
1555 /*
1556  * Add connection to kss_tx_conns of scheduler
1557  * and wakeup the scheduler.
1558  */
1559 void ksocknal_write_callback (ksock_conn_t *conn)
1560 {
1561         ksock_sched_t *sched;
1562         ENTRY;
1563
1564         sched = conn->ksnc_scheduler;
1565
1566         cfs_spin_lock_bh (&sched->kss_lock);
1567
1568         conn->ksnc_tx_ready = 1;
1569
1570         if (!conn->ksnc_tx_scheduled && // not being progressed 
1571             !list_empty(&conn->ksnc_tx_queue)){//packets to send 
1572                 list_add_tail (&conn->ksnc_tx_list,
1573                                &sched->kss_tx_conns);
1574                 conn->ksnc_tx_scheduled = 1;
1575                 /* extra ref for scheduler */
1576                 ksocknal_conn_addref(conn);
1577
1578                 cfs_waitq_signal (&sched->kss_waitq);
1579         }
1580
1581         cfs_spin_unlock_bh (&sched->kss_lock);
1582
1583         EXIT;
1584 }
1585
1586 ksock_proto_t *
1587 ksocknal_parse_proto_version (ksock_hello_msg_t *hello)
1588 {
1589         __u32   version = 0;
1590
1591         if (hello->kshm_magic == LNET_PROTO_MAGIC)
1592                 version = hello->kshm_version;
1593         else if (hello->kshm_magic == __swab32(LNET_PROTO_MAGIC))
1594                 version = __swab32(hello->kshm_version);
1595
1596         if (version != 0) {
1597 #if SOCKNAL_VERSION_DEBUG
1598                 if (*ksocknal_tunables.ksnd_protocol == 1)
1599                         return NULL;
1600
1601                 if (*ksocknal_tunables.ksnd_protocol == 2 &&
1602                     version == KSOCK_PROTO_V3)
1603                         return NULL;
1604 #endif
1605                 if (version == KSOCK_PROTO_V2)
1606                         return &ksocknal_protocol_v2x;
1607
1608                 if (version == KSOCK_PROTO_V3)
1609                         return &ksocknal_protocol_v3x;
1610
1611                 return NULL;
1612         }
1613
1614         if (hello->kshm_magic == le32_to_cpu(LNET_PROTO_TCP_MAGIC)) {
1615                 lnet_magicversion_t *hmv = (lnet_magicversion_t *)hello;
1616
1617                 CLASSERT (sizeof (lnet_magicversion_t) ==
1618                           offsetof (ksock_hello_msg_t, kshm_src_nid));
1619
1620                 if (hmv->version_major == cpu_to_le16 (KSOCK_PROTO_V1_MAJOR) &&
1621                     hmv->version_minor == cpu_to_le16 (KSOCK_PROTO_V1_MINOR))
1622                         return &ksocknal_protocol_v1x;
1623         }
1624
1625         return NULL;
1626 }
1627
1628 int
1629 ksocknal_send_hello (lnet_ni_t *ni, ksock_conn_t *conn,
1630                      lnet_nid_t peer_nid, ksock_hello_msg_t *hello)
1631 {
1632         /* CAVEAT EMPTOR: this byte flips 'ipaddrs' */
1633         ksock_net_t         *net = (ksock_net_t *)ni->ni_data;
1634
1635         LASSERT (hello->kshm_nips <= LNET_MAX_INTERFACES);
1636
1637         /* rely on caller to hold a ref on socket so it wouldn't disappear */
1638         LASSERT (conn->ksnc_proto != NULL);
1639
1640         hello->kshm_src_nid         = ni->ni_nid;
1641         hello->kshm_dst_nid         = peer_nid;
1642         hello->kshm_src_pid         = the_lnet.ln_pid;
1643
1644         hello->kshm_src_incarnation = net->ksnn_incarnation;
1645         hello->kshm_ctype           = conn->ksnc_type;
1646
1647         return conn->ksnc_proto->pro_send_hello(conn, hello);
1648 }
1649
1650 int
1651 ksocknal_invert_type(int type)
1652 {
1653         switch (type)
1654         {
1655         case SOCKLND_CONN_ANY:
1656         case SOCKLND_CONN_CONTROL:
1657                 return (type);
1658         case SOCKLND_CONN_BULK_IN:
1659                 return SOCKLND_CONN_BULK_OUT;
1660         case SOCKLND_CONN_BULK_OUT:
1661                 return SOCKLND_CONN_BULK_IN;
1662         default:
1663                 return (SOCKLND_CONN_NONE);
1664         }
1665 }
1666
1667 int
1668 ksocknal_recv_hello (lnet_ni_t *ni, ksock_conn_t *conn,
1669                      ksock_hello_msg_t *hello, lnet_process_id_t *peerid,
1670                      __u64 *incarnation)
1671 {
1672         /* Return < 0        fatal error
1673          *        0          success
1674          *        EALREADY   lost connection race
1675          *        EPROTO     protocol version mismatch
1676          */
1677         cfs_socket_t        *sock = conn->ksnc_sock;
1678         int                  active = (conn->ksnc_proto != NULL);
1679         int                  timeout;
1680         int                  proto_match;
1681         int                  rc;
1682         ksock_proto_t       *proto;
1683         lnet_process_id_t    recv_id;
1684
1685         /* socket type set on active connections - not set on passive */
1686         LASSERT (!active == !(conn->ksnc_type != SOCKLND_CONN_NONE));
1687
1688         timeout = active ? *ksocknal_tunables.ksnd_timeout :
1689                             lnet_acceptor_timeout();
1690
1691         rc = libcfs_sock_read(sock, &hello->kshm_magic, sizeof (hello->kshm_magic), timeout);
1692         if (rc != 0) {
1693                 CERROR ("Error %d reading HELLO from %u.%u.%u.%u\n",
1694                         rc, HIPQUAD(conn->ksnc_ipaddr));
1695                 LASSERT (rc < 0);
1696                 return rc;
1697         }
1698
1699         if (hello->kshm_magic != LNET_PROTO_MAGIC &&
1700             hello->kshm_magic != __swab32(LNET_PROTO_MAGIC) &&
1701             hello->kshm_magic != le32_to_cpu (LNET_PROTO_TCP_MAGIC)) {
1702                 /* Unexpected magic! */
1703                 CERROR ("Bad magic(1) %#08x (%#08x expected) from "
1704                         "%u.%u.%u.%u\n", __cpu_to_le32 (hello->kshm_magic),
1705                         LNET_PROTO_TCP_MAGIC,
1706                         HIPQUAD(conn->ksnc_ipaddr));
1707                 return -EPROTO;
1708         }
1709
1710         rc = libcfs_sock_read(sock, &hello->kshm_version,
1711                               sizeof(hello->kshm_version), 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         proto = ksocknal_parse_proto_version(hello);
1720         if (proto == NULL) {
1721                 if (!active) {
1722                         /* unknown protocol from peer, tell peer my protocol */
1723                         conn->ksnc_proto = &ksocknal_protocol_v3x;
1724 #if SOCKNAL_VERSION_DEBUG
1725                         if (*ksocknal_tunables.ksnd_protocol == 2)
1726                                 conn->ksnc_proto = &ksocknal_protocol_v2x;
1727                         else if (*ksocknal_tunables.ksnd_protocol == 1)
1728                                 conn->ksnc_proto = &ksocknal_protocol_v1x;
1729 #endif
1730                         hello->kshm_nips = 0;
1731                         ksocknal_send_hello(ni, conn, ni->ni_nid, hello);
1732                 }
1733
1734                 CERROR ("Unknown protocol version (%d.x expected)"
1735                         " from %u.%u.%u.%u\n",
1736                         conn->ksnc_proto->pro_version,
1737                         HIPQUAD(conn->ksnc_ipaddr));
1738
1739                 return -EPROTO;
1740         }
1741
1742         proto_match = (conn->ksnc_proto == proto);
1743         conn->ksnc_proto = proto;
1744
1745         /* receive the rest of hello message anyway */
1746         rc = conn->ksnc_proto->pro_recv_hello(conn, hello, timeout);
1747         if (rc != 0) {
1748                 CERROR("Error %d reading or checking hello from from %u.%u.%u.%u\n",
1749                        rc, HIPQUAD(conn->ksnc_ipaddr));
1750                 LASSERT (rc < 0);
1751                 return rc;
1752         }
1753
1754         *incarnation = hello->kshm_src_incarnation;
1755
1756         if (hello->kshm_src_nid == LNET_NID_ANY) {
1757                 CERROR("Expecting a HELLO hdr with a NID, but got LNET_NID_ANY"
1758                        "from %u.%u.%u.%u\n", HIPQUAD(conn->ksnc_ipaddr));
1759                 return -EPROTO;
1760         }
1761
1762         if (!active &&
1763             conn->ksnc_port > LNET_ACCEPTOR_MAX_RESERVED_PORT) {
1764                 /* Userspace NAL assigns peer process ID from socket */
1765                 recv_id.pid = conn->ksnc_port | LNET_PID_USERFLAG;
1766                 recv_id.nid = LNET_MKNID(LNET_NIDNET(ni->ni_nid), conn->ksnc_ipaddr);
1767         } else {
1768                 recv_id.nid = hello->kshm_src_nid;
1769                 recv_id.pid = hello->kshm_src_pid;
1770         }
1771
1772         if (!active) {
1773                 *peerid = recv_id;
1774
1775                 /* peer determines type */
1776                 conn->ksnc_type = ksocknal_invert_type(hello->kshm_ctype);
1777                 if (conn->ksnc_type == SOCKLND_CONN_NONE) {
1778                         CERROR ("Unexpected type %d from %s ip %u.%u.%u.%u\n",
1779                                 hello->kshm_ctype, libcfs_id2str(*peerid),
1780                                 HIPQUAD(conn->ksnc_ipaddr));
1781                         return -EPROTO;
1782                 }
1783
1784                 return 0;
1785         }
1786
1787         if (peerid->pid != recv_id.pid ||
1788             peerid->nid != recv_id.nid) {
1789                 LCONSOLE_ERROR_MSG(0x130, "Connected successfully to %s on host"
1790                                    " %u.%u.%u.%u, but they claimed they were "
1791                                    "%s; please check your Lustre "
1792                                    "configuration.\n",
1793                                    libcfs_id2str(*peerid),
1794                                    HIPQUAD(conn->ksnc_ipaddr),
1795                                    libcfs_id2str(recv_id));
1796                 return -EPROTO;
1797         }
1798
1799         if (hello->kshm_ctype == SOCKLND_CONN_NONE) {
1800                 /* Possible protocol mismatch or I lost the connection race */
1801                 return proto_match ? EALREADY : EPROTO;
1802         }
1803
1804         if (ksocknal_invert_type(hello->kshm_ctype) != conn->ksnc_type) {
1805                 CERROR ("Mismatched types: me %d, %s ip %u.%u.%u.%u %d\n",
1806                         conn->ksnc_type, libcfs_id2str(*peerid), 
1807                         HIPQUAD(conn->ksnc_ipaddr),
1808                         hello->kshm_ctype);
1809                 return -EPROTO;
1810         }
1811
1812         return 0;
1813 }
1814
1815 void
1816 ksocknal_connect (ksock_route_t *route)
1817 {
1818         CFS_LIST_HEAD    (zombies);
1819         ksock_peer_t     *peer = route->ksnr_peer;
1820         int               type;
1821         int               wanted;
1822         cfs_socket_t     *sock;
1823         cfs_time_t        deadline;
1824         int               retry_later = 0;
1825         int               rc = 0;
1826
1827         deadline = cfs_time_add(cfs_time_current(),
1828                                 cfs_time_seconds(*ksocknal_tunables.ksnd_timeout));
1829
1830         cfs_write_lock_bh (&ksocknal_data.ksnd_global_lock);
1831
1832         LASSERT (route->ksnr_scheduled);
1833         LASSERT (!route->ksnr_connecting);
1834
1835         route->ksnr_connecting = 1;
1836
1837         for (;;) {
1838                 wanted = ksocknal_route_mask() & ~route->ksnr_connected;
1839
1840                 /* stop connecting if peer/route got closed under me, or
1841                  * route got connected while queued */
1842                 if (peer->ksnp_closing || route->ksnr_deleted ||
1843                     wanted == 0) {
1844                         retry_later = 0;
1845                         break;
1846                 }
1847
1848                 /* reschedule if peer is connecting to me */
1849                 if (peer->ksnp_accepting > 0) {
1850                         CDEBUG(D_NET,
1851                                "peer %s(%d) already connecting to me, retry later.\n",
1852                                libcfs_nid2str(peer->ksnp_id.nid), peer->ksnp_accepting);
1853                         retry_later = 1;
1854                 }
1855
1856                 if (retry_later) /* needs reschedule */
1857                         break;
1858
1859                 if ((wanted & (1 << SOCKLND_CONN_ANY)) != 0) {
1860                         type = SOCKLND_CONN_ANY;
1861                 } else if ((wanted & (1 << SOCKLND_CONN_CONTROL)) != 0) {
1862                         type = SOCKLND_CONN_CONTROL;
1863                 } else if ((wanted & (1 << SOCKLND_CONN_BULK_IN)) != 0) {
1864                         type = SOCKLND_CONN_BULK_IN;
1865                 } else {
1866                         LASSERT ((wanted & (1 << SOCKLND_CONN_BULK_OUT)) != 0);
1867                         type = SOCKLND_CONN_BULK_OUT;
1868                 }
1869
1870                 cfs_write_unlock_bh (&ksocknal_data.ksnd_global_lock);
1871
1872                 if (cfs_time_aftereq(cfs_time_current(), deadline)) {
1873                         rc = -ETIMEDOUT;
1874                         lnet_connect_console_error(rc, peer->ksnp_id.nid,
1875                                                    route->ksnr_ipaddr,
1876                                                    route->ksnr_port);
1877                         goto failed;
1878                 }
1879
1880                 rc = lnet_connect(&sock, peer->ksnp_id.nid,
1881                                   route->ksnr_myipaddr,
1882                                   route->ksnr_ipaddr, route->ksnr_port);
1883                 if (rc != 0)
1884                         goto failed;
1885
1886                 rc = ksocknal_create_conn(peer->ksnp_ni, route, sock, type);
1887                 if (rc < 0) {
1888                         lnet_connect_console_error(rc, peer->ksnp_id.nid,
1889                                                    route->ksnr_ipaddr,
1890                                                    route->ksnr_port);
1891                         goto failed;
1892                 }
1893
1894                 /* A +ve RC means I have to retry because I lost the connection
1895                  * race or I have to renegotiate protocol version */
1896                 retry_later = (rc != 0);
1897                 if (retry_later)
1898                         CDEBUG(D_NET, "peer %s: conn race, retry later.\n",
1899                                libcfs_nid2str(peer->ksnp_id.nid));
1900
1901                 cfs_write_lock_bh (&ksocknal_data.ksnd_global_lock);
1902         }
1903
1904         route->ksnr_scheduled = 0;
1905         route->ksnr_connecting = 0;
1906
1907         if (retry_later) {
1908                 /* re-queue for attention; this frees me up to handle
1909                  * the peer's incoming connection request */
1910                 ksocknal_launch_connection_locked(route);
1911         }
1912
1913         cfs_write_unlock_bh (&ksocknal_data.ksnd_global_lock);
1914         return;
1915
1916  failed:
1917         cfs_write_lock_bh (&ksocknal_data.ksnd_global_lock);
1918
1919         route->ksnr_scheduled = 0;
1920         route->ksnr_connecting = 0;
1921
1922         /* This is a retry rather than a new connection */
1923         route->ksnr_retry_interval *= 2;
1924         route->ksnr_retry_interval =
1925                 MAX(route->ksnr_retry_interval,
1926                     cfs_time_seconds(*ksocknal_tunables.ksnd_min_reconnectms)/1000);
1927         route->ksnr_retry_interval =
1928                 MIN(route->ksnr_retry_interval,
1929                     cfs_time_seconds(*ksocknal_tunables.ksnd_max_reconnectms)/1000);
1930
1931         LASSERT (route->ksnr_retry_interval != 0);
1932         route->ksnr_timeout = cfs_time_add(cfs_time_current(),
1933                                            route->ksnr_retry_interval);
1934
1935         if (!list_empty(&peer->ksnp_tx_queue) &&
1936             peer->ksnp_accepting == 0 &&
1937             ksocknal_find_connecting_route_locked(peer) == NULL) {
1938                 ksock_conn_t *conn;
1939
1940                 /* ksnp_tx_queue is queued on a conn on successful
1941                  * connection for V1.x and V2.x */
1942                 if (!list_empty (&peer->ksnp_conns)) {
1943                         conn = list_entry(peer->ksnp_conns.next, ksock_conn_t, ksnc_list);
1944                         LASSERT (conn->ksnc_proto == &ksocknal_protocol_v3x);
1945                 }
1946
1947                 /* take all the blocked packets while I've got the lock and
1948                  * complete below... */
1949                 list_splice_init(&peer->ksnp_tx_queue, &zombies);
1950         }
1951
1952 #if 0           /* irrelevent with only eager routes */
1953         if (!route->ksnr_deleted) {
1954                 /* make this route least-favourite for re-selection */
1955                 list_del(&route->ksnr_list);
1956                 list_add_tail(&route->ksnr_list, &peer->ksnp_routes);
1957         }
1958 #endif
1959         cfs_write_unlock_bh (&ksocknal_data.ksnd_global_lock);
1960
1961         ksocknal_peer_failed(peer);
1962         ksocknal_txlist_done(peer->ksnp_ni, &zombies, 1);
1963 }
1964
1965 static inline int
1966 ksocknal_connd_connect_route_locked(void)
1967 {
1968         /* Only handle an outgoing connection request if there is someone left
1969          * to handle incoming connections */
1970         return !list_empty(&ksocknal_data.ksnd_connd_routes) &&
1971                 ((ksocknal_data.ksnd_connd_connecting + 1) <
1972                  *ksocknal_tunables.ksnd_nconnds);
1973 }
1974
1975 static inline int
1976 ksocknal_connd_ready(void)
1977 {
1978         int            rc;
1979
1980         cfs_spin_lock_bh (&ksocknal_data.ksnd_connd_lock);
1981
1982         rc = ksocknal_data.ksnd_shuttingdown ||
1983              !list_empty(&ksocknal_data.ksnd_connd_connreqs) ||
1984              ksocknal_connd_connect_route_locked();
1985
1986         cfs_spin_unlock_bh (&ksocknal_data.ksnd_connd_lock);
1987
1988         return rc;
1989 }
1990
1991 int
1992 ksocknal_connd (void *arg)
1993 {
1994         long               id = (long)(long_ptr_t)arg;
1995         char               name[16];
1996         ksock_connreq_t   *cr;
1997         ksock_route_t     *route;
1998         int                rc = 0;
1999
2000         snprintf (name, sizeof (name), "socknal_cd%02ld", id);
2001         cfs_daemonize (name);
2002         cfs_block_allsigs ();
2003
2004         cfs_spin_lock_bh (&ksocknal_data.ksnd_connd_lock);
2005
2006         while (!ksocknal_data.ksnd_shuttingdown) {
2007
2008                 if (!list_empty(&ksocknal_data.ksnd_connd_connreqs)) {
2009                         /* Connection accepted by the listener */
2010                         cr = list_entry(ksocknal_data.ksnd_connd_connreqs.next,
2011                                         ksock_connreq_t, ksncr_list);
2012
2013                         list_del(&cr->ksncr_list);
2014                         cfs_spin_unlock_bh (&ksocknal_data.ksnd_connd_lock);
2015
2016                         ksocknal_create_conn(cr->ksncr_ni, NULL,
2017                                              cr->ksncr_sock, SOCKLND_CONN_NONE);
2018                         lnet_ni_decref(cr->ksncr_ni);
2019                         LIBCFS_FREE(cr, sizeof(*cr));
2020
2021                         cfs_spin_lock_bh (&ksocknal_data.ksnd_connd_lock);
2022                 }
2023
2024                 if (ksocknal_connd_connect_route_locked()) {
2025                         /* Connection request */
2026                         route = list_entry (ksocknal_data.ksnd_connd_routes.next,
2027                                             ksock_route_t, ksnr_connd_list);
2028
2029                         list_del (&route->ksnr_connd_list);
2030                         ksocknal_data.ksnd_connd_connecting++;
2031                         cfs_spin_unlock_bh (&ksocknal_data.ksnd_connd_lock);
2032
2033                         ksocknal_connect (route);
2034                         ksocknal_route_decref(route);
2035
2036                         cfs_spin_lock_bh (&ksocknal_data.ksnd_connd_lock);
2037                         ksocknal_data.ksnd_connd_connecting--;
2038                 }
2039
2040                 cfs_spin_unlock_bh (&ksocknal_data.ksnd_connd_lock);
2041
2042                 cfs_wait_event_interruptible_exclusive(
2043                         ksocknal_data.ksnd_connd_waitq,
2044                         ksocknal_connd_ready(), rc);
2045
2046                 cfs_spin_lock_bh (&ksocknal_data.ksnd_connd_lock);
2047         }
2048
2049         cfs_spin_unlock_bh (&ksocknal_data.ksnd_connd_lock);
2050
2051         ksocknal_thread_fini ();
2052         return (0);
2053 }
2054
2055 ksock_conn_t *
2056 ksocknal_find_timed_out_conn (ksock_peer_t *peer)
2057 {
2058         /* We're called with a shared lock on ksnd_global_lock */
2059         ksock_conn_t      *conn;
2060         struct list_head  *ctmp;
2061
2062         list_for_each (ctmp, &peer->ksnp_conns) {
2063                 int     error;
2064                 conn = list_entry (ctmp, ksock_conn_t, ksnc_list);
2065
2066                 /* Don't need the {get,put}connsock dance to deref ksnc_sock */
2067                 LASSERT (!conn->ksnc_closing);
2068
2069                 /* SOCK_ERROR will reset error code of socket in
2070                  * some platform (like Darwin8.x) */
2071                 error = libcfs_sock_error(conn->ksnc_sock);
2072                 if (error != 0) {
2073                         ksocknal_conn_addref(conn);
2074
2075                         switch (error) {
2076                         case ECONNRESET:
2077                                 CDEBUG(D_NETERROR, "A connection with %s "
2078                                        "(%u.%u.%u.%u:%d) was reset; "
2079                                        "it may have rebooted.\n",
2080                                        libcfs_id2str(peer->ksnp_id),
2081                                        HIPQUAD(conn->ksnc_ipaddr),
2082                                        conn->ksnc_port);
2083                                 break;
2084                         case ETIMEDOUT:
2085                                 CDEBUG(D_NETERROR, "A connection with %s "
2086                                        "(%u.%u.%u.%u:%d) timed out; the "
2087                                        "network or node may be down.\n",
2088                                        libcfs_id2str(peer->ksnp_id),
2089                                        HIPQUAD(conn->ksnc_ipaddr),
2090                                        conn->ksnc_port);
2091                                 break;
2092                         default:
2093                                 CDEBUG(D_NETERROR, "An unexpected network error %d "
2094                                        "occurred with %s "
2095                                        "(%u.%u.%u.%u:%d\n", error,
2096                                        libcfs_id2str(peer->ksnp_id),
2097                                        HIPQUAD(conn->ksnc_ipaddr),
2098                                        conn->ksnc_port);
2099                                 break;
2100                         }
2101
2102                         return (conn);
2103                 }
2104
2105                 if (conn->ksnc_rx_started &&
2106                     cfs_time_aftereq(cfs_time_current(),
2107                                      conn->ksnc_rx_deadline)) {
2108                         /* Timed out incomplete incoming message */
2109                         ksocknal_conn_addref(conn);
2110                         CDEBUG(D_NETERROR, "Timeout receiving from %s "
2111                                "(%u.%u.%u.%u:%d), state %d wanted %d left %d\n",
2112                                libcfs_id2str(peer->ksnp_id),
2113                                HIPQUAD(conn->ksnc_ipaddr),
2114                                conn->ksnc_port,
2115                                conn->ksnc_rx_state,
2116                                conn->ksnc_rx_nob_wanted,
2117                                conn->ksnc_rx_nob_left);
2118                         return (conn);
2119                 }
2120
2121                 if ((!list_empty(&conn->ksnc_tx_queue) ||
2122                      libcfs_sock_wmem_queued(conn->ksnc_sock) != 0) &&
2123                     cfs_time_aftereq(cfs_time_current(),
2124                                      conn->ksnc_tx_deadline)) {
2125                         /* Timed out messages queued for sending or
2126                          * buffered in the socket's send buffer */
2127                         ksocknal_conn_addref(conn);
2128                         CDEBUG(D_NETERROR, "Timeout sending data to %s "
2129                                "(%u.%u.%u.%u:%d) the network or that "
2130                                "node may be down.\n",
2131                                libcfs_id2str(peer->ksnp_id),
2132                                HIPQUAD(conn->ksnc_ipaddr),
2133                                conn->ksnc_port);
2134                         return (conn);
2135                 }
2136         }
2137
2138         return (NULL);
2139 }
2140
2141 static inline void
2142 ksocknal_flush_stale_txs(ksock_peer_t *peer)
2143 {
2144         ksock_tx_t        *tx;
2145         CFS_LIST_HEAD      (stale_txs);
2146         
2147         cfs_write_lock_bh (&ksocknal_data.ksnd_global_lock);
2148
2149         while (!list_empty (&peer->ksnp_tx_queue)) {
2150                 tx = list_entry (peer->ksnp_tx_queue.next,
2151                                  ksock_tx_t, tx_list);
2152
2153                 if (!cfs_time_aftereq(cfs_time_current(),
2154                                       tx->tx_deadline))
2155                         break;
2156                 
2157                 list_del (&tx->tx_list);
2158                 list_add_tail (&tx->tx_list, &stale_txs);
2159         }
2160
2161         cfs_write_unlock_bh (&ksocknal_data.ksnd_global_lock);
2162
2163         ksocknal_txlist_done(peer->ksnp_ni, &stale_txs, 1);
2164 }
2165
2166 int
2167 ksocknal_send_keepalive_locked(ksock_peer_t *peer)
2168 {
2169         ksock_sched_t  *sched;
2170         ksock_conn_t   *conn;
2171         ksock_tx_t     *tx;
2172
2173         if (list_empty(&peer->ksnp_conns)) /* last_alive will be updated by create_conn */
2174                 return 0;
2175
2176         if (peer->ksnp_proto != &ksocknal_protocol_v3x)
2177                 return 0;
2178
2179         if (*ksocknal_tunables.ksnd_keepalive <= 0 ||
2180             cfs_time_before(cfs_time_current(),
2181                             cfs_time_add(peer->ksnp_last_alive,
2182                                          cfs_time_seconds(*ksocknal_tunables.ksnd_keepalive))))
2183                 return 0;
2184
2185         if (cfs_time_before(cfs_time_current(),
2186                             peer->ksnp_send_keepalive))
2187                 return 0;
2188
2189         /* retry 10 secs later, so we wouldn't put pressure
2190          * on this peer if we failed to send keepalive this time */
2191         peer->ksnp_send_keepalive = cfs_time_shift(10);
2192
2193         conn = ksocknal_find_conn_locked(peer, NULL, 1);
2194         if (conn != NULL) {
2195                 sched = conn->ksnc_scheduler;
2196
2197                 spin_lock_bh (&sched->kss_lock);
2198                 if (!list_empty(&conn->ksnc_tx_queue)) {
2199                         spin_unlock_bh(&sched->kss_lock);
2200                         /* there is an queued ACK, don't need keepalive */
2201                         return 0;
2202                 }
2203
2204                 spin_unlock_bh(&sched->kss_lock);
2205         }
2206
2207         read_unlock(&ksocknal_data.ksnd_global_lock);
2208
2209         /* cookie = 1 is reserved for keepalive PING */
2210         tx = ksocknal_alloc_tx_noop(1, 1);
2211         if (tx == NULL) {
2212                 read_lock(&ksocknal_data.ksnd_global_lock);
2213                 return -ENOMEM;
2214         }
2215
2216         if (ksocknal_launch_packet(peer->ksnp_ni, tx, peer->ksnp_id) == 0) {
2217                 read_lock(&ksocknal_data.ksnd_global_lock);
2218                 return 1;
2219         }
2220
2221         ksocknal_free_tx(tx);
2222         read_lock(&ksocknal_data.ksnd_global_lock);
2223
2224         return -EIO;
2225 }
2226
2227
2228 void
2229 ksocknal_check_peer_timeouts (int idx)
2230 {
2231         struct list_head *peers = &ksocknal_data.ksnd_peers[idx];
2232         struct list_head *ptmp;
2233         ksock_peer_t     *peer;
2234         ksock_conn_t     *conn;
2235
2236  again:
2237         /* NB. We expect to have a look at all the peers and not find any
2238          * connections to time out, so we just use a shared lock while we
2239          * take a look... */
2240         cfs_read_lock (&ksocknal_data.ksnd_global_lock);
2241
2242         list_for_each (ptmp, peers) {
2243                 peer = list_entry (ptmp, ksock_peer_t, ksnp_list);
2244                 if (ksocknal_send_keepalive_locked(peer) != 0) {
2245                         read_unlock (&ksocknal_data.ksnd_global_lock);
2246                         goto again;
2247                 }
2248
2249                 conn = ksocknal_find_timed_out_conn (peer);
2250
2251                 if (conn != NULL) {
2252                         cfs_read_unlock (&ksocknal_data.ksnd_global_lock);
2253
2254                         ksocknal_close_conn_and_siblings (conn, -ETIMEDOUT);
2255
2256                         /* NB we won't find this one again, but we can't
2257                          * just proceed with the next peer, since we dropped
2258                          * ksnd_global_lock and it might be dead already! */
2259                         ksocknal_conn_decref(conn);
2260                         goto again;
2261                 }
2262
2263                 /* we can't process stale txs right here because we're
2264                  * holding only shared lock */
2265                 if (!list_empty (&peer->ksnp_tx_queue)) {
2266                         ksock_tx_t *tx = list_entry (peer->ksnp_tx_queue.next,
2267                                                      ksock_tx_t, tx_list);
2268
2269                         if (cfs_time_aftereq(cfs_time_current(),
2270                                              tx->tx_deadline)) {
2271
2272                                 ksocknal_peer_addref(peer);
2273                                 cfs_read_unlock (&ksocknal_data.ksnd_global_lock);
2274                                 
2275                                 ksocknal_flush_stale_txs(peer);
2276
2277                                 ksocknal_peer_decref(peer);
2278                                 goto again;
2279                         }
2280                 }
2281         }
2282
2283         /* print out warnings about stale ZC_REQs */
2284         cfs_list_for_each_entry_typed(peer, peers, ksock_peer_t, ksnp_list) {
2285                 ksock_tx_t *tx;
2286                 int         n = 0;
2287                 
2288                 cfs_list_for_each_entry_typed(tx, &peer->ksnp_zc_req_list,
2289                                               ksock_tx_t, tx_zc_list) {
2290                         if (!cfs_time_aftereq(cfs_time_current(),
2291                                               tx->tx_deadline))
2292                                 break;
2293                         n++;
2294                 }
2295
2296                 if (n != 0) {
2297                         tx = list_entry (peer->ksnp_zc_req_list.next,
2298                                          ksock_tx_t, tx_zc_list);
2299                         CWARN("Stale ZC_REQs for peer %s detected: %d; the "
2300                               "oldest (%p) timed out %ld secs ago\n",
2301                               libcfs_nid2str(peer->ksnp_id.nid), n, tx,
2302                               cfs_duration_sec(cfs_time_current() -
2303                                                tx->tx_deadline));
2304                 }
2305         }
2306         
2307         cfs_read_unlock (&ksocknal_data.ksnd_global_lock);
2308 }
2309
2310 int
2311 ksocknal_reaper (void *arg)
2312 {
2313         cfs_waitlink_t     wait;
2314         ksock_conn_t      *conn;
2315         ksock_sched_t     *sched;
2316         struct list_head   enomem_conns;
2317         int                nenomem_conns;
2318         cfs_duration_t     timeout;
2319         int                i;
2320         int                peer_index = 0;
2321         cfs_time_t         deadline = cfs_time_current();
2322
2323         cfs_daemonize ("socknal_reaper");
2324         cfs_block_allsigs ();
2325
2326         CFS_INIT_LIST_HEAD(&enomem_conns);
2327         cfs_waitlink_init (&wait);
2328
2329         cfs_spin_lock_bh (&ksocknal_data.ksnd_reaper_lock);
2330
2331         while (!ksocknal_data.ksnd_shuttingdown) {
2332
2333                 if (!list_empty (&ksocknal_data.ksnd_deathrow_conns)) {
2334                         conn = list_entry (ksocknal_data.ksnd_deathrow_conns.next,
2335                                            ksock_conn_t, ksnc_list);
2336                         list_del (&conn->ksnc_list);
2337
2338                         cfs_spin_unlock_bh (&ksocknal_data.ksnd_reaper_lock);
2339
2340                         ksocknal_terminate_conn (conn);
2341                         ksocknal_conn_decref(conn);
2342
2343                         cfs_spin_lock_bh (&ksocknal_data.ksnd_reaper_lock);
2344                         continue;
2345                 }
2346
2347                 if (!list_empty (&ksocknal_data.ksnd_zombie_conns)) {
2348                         conn = list_entry (ksocknal_data.ksnd_zombie_conns.next,
2349                                            ksock_conn_t, ksnc_list);
2350                         list_del (&conn->ksnc_list);
2351
2352                         cfs_spin_unlock_bh (&ksocknal_data.ksnd_reaper_lock);
2353
2354                         ksocknal_destroy_conn (conn);
2355
2356                         cfs_spin_lock_bh (&ksocknal_data.ksnd_reaper_lock);
2357                         continue;
2358                 }
2359
2360                 if (!list_empty (&ksocknal_data.ksnd_enomem_conns)) {
2361                         list_add(&enomem_conns, &ksocknal_data.ksnd_enomem_conns);
2362                         list_del_init(&ksocknal_data.ksnd_enomem_conns);
2363                 }
2364
2365                 cfs_spin_unlock_bh (&ksocknal_data.ksnd_reaper_lock);
2366
2367                 /* reschedule all the connections that stalled with ENOMEM... */
2368                 nenomem_conns = 0;
2369                 while (!list_empty (&enomem_conns)) {
2370                         conn = list_entry (enomem_conns.next,
2371                                            ksock_conn_t, ksnc_tx_list);
2372                         list_del (&conn->ksnc_tx_list);
2373
2374                         sched = conn->ksnc_scheduler;
2375
2376                         cfs_spin_lock_bh (&sched->kss_lock);
2377
2378                         LASSERT (conn->ksnc_tx_scheduled);
2379                         conn->ksnc_tx_ready = 1;
2380                         list_add_tail(&conn->ksnc_tx_list, &sched->kss_tx_conns);
2381                         cfs_waitq_signal (&sched->kss_waitq);
2382
2383                         cfs_spin_unlock_bh (&sched->kss_lock);
2384                         nenomem_conns++;
2385                 }
2386
2387                 /* careful with the jiffy wrap... */
2388                 while ((timeout = cfs_time_sub(deadline,
2389                                                cfs_time_current())) <= 0) {
2390                         const int n = 4;
2391                         const int p = 1;
2392                         int       chunk = ksocknal_data.ksnd_peer_hash_size;
2393
2394                         /* Time to check for timeouts on a few more peers: I do
2395                          * checks every 'p' seconds on a proportion of the peer
2396                          * table and I need to check every connection 'n' times
2397                          * within a timeout interval, to ensure I detect a
2398                          * timeout on any connection within (n+1)/n times the
2399                          * timeout interval. */
2400
2401                         if (*ksocknal_tunables.ksnd_timeout > n * p)
2402                                 chunk = (chunk * n * p) /
2403                                         *ksocknal_tunables.ksnd_timeout;
2404                         if (chunk == 0)
2405                                 chunk = 1;
2406
2407                         for (i = 0; i < chunk; i++) {
2408                                 ksocknal_check_peer_timeouts (peer_index);
2409                                 peer_index = (peer_index + 1) %
2410                                              ksocknal_data.ksnd_peer_hash_size;
2411                         }
2412
2413                         deadline = cfs_time_add(deadline, cfs_time_seconds(p));
2414                 }
2415
2416                 if (nenomem_conns != 0) {
2417                         /* Reduce my timeout if I rescheduled ENOMEM conns.
2418                          * This also prevents me getting woken immediately
2419                          * if any go back on my enomem list. */
2420                         timeout = SOCKNAL_ENOMEM_RETRY;
2421                 }
2422                 ksocknal_data.ksnd_reaper_waketime =
2423                         cfs_time_add(cfs_time_current(), timeout);
2424
2425                 cfs_set_current_state (CFS_TASK_INTERRUPTIBLE);
2426                 cfs_waitq_add (&ksocknal_data.ksnd_reaper_waitq, &wait);
2427
2428                 if (!ksocknal_data.ksnd_shuttingdown &&
2429                     list_empty (&ksocknal_data.ksnd_deathrow_conns) &&
2430                     list_empty (&ksocknal_data.ksnd_zombie_conns))
2431                         cfs_waitq_timedwait (&wait, CFS_TASK_INTERRUPTIBLE, timeout);
2432
2433                 cfs_set_current_state (CFS_TASK_RUNNING);
2434                 cfs_waitq_del (&ksocknal_data.ksnd_reaper_waitq, &wait);
2435
2436                 cfs_spin_lock_bh (&ksocknal_data.ksnd_reaper_lock);
2437         }
2438
2439         cfs_spin_unlock_bh (&ksocknal_data.ksnd_reaper_lock);
2440
2441         ksocknal_thread_fini ();
2442         return (0);
2443 }