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