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