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