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