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