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