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