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