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