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