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