ocfs2/cluster: Track send message timing stats for each socket
[linux-2.6.git] / fs / ocfs2 / cluster / tcp.c
1 /* -*- mode: c; c-basic-offset: 8; -*-
2  *
3  * vim: noexpandtab sw=8 ts=8 sts=0:
4  *
5  * Copyright (C) 2004 Oracle.  All rights reserved.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public
18  * License along with this program; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 021110-1307, USA.
21  *
22  * ----
23  *
24  * Callers for this were originally written against a very simple synchronus
25  * API.  This implementation reflects those simple callers.  Some day I'm sure
26  * we'll need to move to a more robust posting/callback mechanism.
27  *
28  * Transmit calls pass in kernel virtual addresses and block copying this into
29  * the socket's tx buffers via a usual blocking sendmsg.  They'll block waiting
30  * for a failed socket to timeout.  TX callers can also pass in a poniter to an
31  * 'int' which gets filled with an errno off the wire in response to the
32  * message they send.
33  *
34  * Handlers for unsolicited messages are registered.  Each socket has a page
35  * that incoming data is copied into.  First the header, then the data.
36  * Handlers are called from only one thread with a reference to this per-socket
37  * page.  This page is destroyed after the handler call, so it can't be
38  * referenced beyond the call.  Handlers may block but are discouraged from
39  * doing so.
40  *
41  * Any framing errors (bad magic, large payload lengths) close a connection.
42  *
43  * Our sock_container holds the state we associate with a socket.  It's current
44  * framing state is held there as well as the refcounting we do around when it
45  * is safe to tear down the socket.  The socket is only finally torn down from
46  * the container when the container loses all of its references -- so as long
47  * as you hold a ref on the container you can trust that the socket is valid
48  * for use with kernel socket APIs.
49  *
50  * Connections are initiated between a pair of nodes when the node with the
51  * higher node number gets a heartbeat callback which indicates that the lower
52  * numbered node has started heartbeating.  The lower numbered node is passive
53  * and only accepts the connection if the higher numbered node is heartbeating.
54  */
55
56 #include <linux/kernel.h>
57 #include <linux/jiffies.h>
58 #include <linux/slab.h>
59 #include <linux/idr.h>
60 #include <linux/kref.h>
61 #include <linux/net.h>
62 #include <net/tcp.h>
63
64 #include <asm/uaccess.h>
65
66 #include "heartbeat.h"
67 #include "tcp.h"
68 #include "nodemanager.h"
69 #define MLOG_MASK_PREFIX ML_TCP
70 #include "masklog.h"
71 #include "quorum.h"
72
73 #include "tcp_internal.h"
74
75 #define SC_NODEF_FMT "node %s (num %u) at %pI4:%u"
76 #define SC_NODEF_ARGS(sc) sc->sc_node->nd_name, sc->sc_node->nd_num,    \
77                           &sc->sc_node->nd_ipv4_address,                \
78                           ntohs(sc->sc_node->nd_ipv4_port)
79
80 /*
81  * In the following two log macros, the whitespace after the ',' just
82  * before ##args is intentional. Otherwise, gcc 2.95 will eat the
83  * previous token if args expands to nothing.
84  */
85 #define msglog(hdr, fmt, args...) do {                                  \
86         typeof(hdr) __hdr = (hdr);                                      \
87         mlog(ML_MSG, "[mag %u len %u typ %u stat %d sys_stat %d "       \
88              "key %08x num %u] " fmt,                                   \
89              be16_to_cpu(__hdr->magic), be16_to_cpu(__hdr->data_len),   \
90              be16_to_cpu(__hdr->msg_type), be32_to_cpu(__hdr->status),  \
91              be32_to_cpu(__hdr->sys_status), be32_to_cpu(__hdr->key),   \
92              be32_to_cpu(__hdr->msg_num) ,  ##args);                    \
93 } while (0)
94
95 #define sclog(sc, fmt, args...) do {                                    \
96         typeof(sc) __sc = (sc);                                         \
97         mlog(ML_SOCKET, "[sc %p refs %d sock %p node %u page %p "       \
98              "pg_off %zu] " fmt, __sc,                                  \
99              atomic_read(&__sc->sc_kref.refcount), __sc->sc_sock,       \
100             __sc->sc_node->nd_num, __sc->sc_page, __sc->sc_page_off ,   \
101             ##args);                                                    \
102 } while (0)
103
104 static DEFINE_RWLOCK(o2net_handler_lock);
105 static struct rb_root o2net_handler_tree = RB_ROOT;
106
107 static struct o2net_node o2net_nodes[O2NM_MAX_NODES];
108
109 /* XXX someday we'll need better accounting */
110 static struct socket *o2net_listen_sock = NULL;
111
112 /*
113  * listen work is only queued by the listening socket callbacks on the
114  * o2net_wq.  teardown detaches the callbacks before destroying the workqueue.
115  * quorum work is queued as sock containers are shutdown.. stop_listening
116  * tears down all the node's sock containers, preventing future shutdowns
117  * and queued quroum work, before canceling delayed quorum work and
118  * destroying the work queue.
119  */
120 static struct workqueue_struct *o2net_wq;
121 static struct work_struct o2net_listen_work;
122
123 static struct o2hb_callback_func o2net_hb_up, o2net_hb_down;
124 #define O2NET_HB_PRI 0x1
125
126 static struct o2net_handshake *o2net_hand;
127 static struct o2net_msg *o2net_keep_req, *o2net_keep_resp;
128
129 static int o2net_sys_err_translations[O2NET_ERR_MAX] =
130                 {[O2NET_ERR_NONE]       = 0,
131                  [O2NET_ERR_NO_HNDLR]   = -ENOPROTOOPT,
132                  [O2NET_ERR_OVERFLOW]   = -EOVERFLOW,
133                  [O2NET_ERR_DIED]       = -EHOSTDOWN,};
134
135 /* can't quite avoid *all* internal declarations :/ */
136 static void o2net_sc_connect_completed(struct work_struct *work);
137 static void o2net_rx_until_empty(struct work_struct *work);
138 static void o2net_shutdown_sc(struct work_struct *work);
139 static void o2net_listen_data_ready(struct sock *sk, int bytes);
140 static void o2net_sc_send_keep_req(struct work_struct *work);
141 static void o2net_idle_timer(unsigned long data);
142 static void o2net_sc_postpone_idle(struct o2net_sock_container *sc);
143 static void o2net_sc_reset_idle_timer(struct o2net_sock_container *sc);
144
145 #ifdef CONFIG_DEBUG_FS
146 static void o2net_init_nst(struct o2net_send_tracking *nst, u32 msgtype,
147                            u32 msgkey, struct task_struct *task, u8 node)
148 {
149         INIT_LIST_HEAD(&nst->st_net_debug_item);
150         nst->st_task = task;
151         nst->st_msg_type = msgtype;
152         nst->st_msg_key = msgkey;
153         nst->st_node = node;
154 }
155
156 static inline void o2net_set_nst_sock_time(struct o2net_send_tracking *nst)
157 {
158         nst->st_sock_time = ktime_get();
159 }
160
161 static inline void o2net_set_nst_send_time(struct o2net_send_tracking *nst)
162 {
163         nst->st_send_time = ktime_get();
164 }
165
166 static inline void o2net_set_nst_status_time(struct o2net_send_tracking *nst)
167 {
168         nst->st_status_time = ktime_get();
169 }
170
171 static inline void o2net_set_nst_sock_container(struct o2net_send_tracking *nst,
172                                                 struct o2net_sock_container *sc)
173 {
174         nst->st_sc = sc;
175 }
176
177 static inline void o2net_set_nst_msg_id(struct o2net_send_tracking *nst,
178                                         u32 msg_id)
179 {
180         nst->st_id = msg_id;
181 }
182
183 static inline void o2net_set_sock_timer(struct o2net_sock_container *sc)
184 {
185         sc->sc_tv_timer = ktime_get();
186 }
187
188 static inline void o2net_set_data_ready_time(struct o2net_sock_container *sc)
189 {
190         sc->sc_tv_data_ready = ktime_get();
191 }
192
193 static inline void o2net_set_advance_start_time(struct o2net_sock_container *sc)
194 {
195         sc->sc_tv_advance_start = ktime_get();
196 }
197
198 static inline void o2net_set_advance_stop_time(struct o2net_sock_container *sc)
199 {
200         sc->sc_tv_advance_stop = ktime_get();
201 }
202
203 static inline void o2net_set_func_start_time(struct o2net_sock_container *sc)
204 {
205         sc->sc_tv_func_start = ktime_get();
206 }
207
208 static inline void o2net_set_func_stop_time(struct o2net_sock_container *sc)
209 {
210         sc->sc_tv_func_stop = ktime_get();
211 }
212 #else  /* CONFIG_DEBUG_FS */
213 # define o2net_init_nst(a, b, c, d, e)
214 # define o2net_set_nst_sock_time(a)
215 # define o2net_set_nst_send_time(a)
216 # define o2net_set_nst_status_time(a)
217 # define o2net_set_nst_sock_container(a, b)
218 # define o2net_set_nst_msg_id(a, b)
219 # define o2net_set_sock_timer(a)
220 # define o2net_set_data_ready_time(a)
221 # define o2net_set_advance_start_time(a)
222 # define o2net_set_advance_stop_time(a)
223 # define o2net_set_func_start_time(a)
224 # define o2net_set_func_stop_time(a)
225 #endif /* CONFIG_DEBUG_FS */
226
227 #ifdef CONFIG_OCFS2_FS_STATS
228 static void o2net_update_send_stats(struct o2net_send_tracking *nst,
229                                     struct o2net_sock_container *sc)
230 {
231         sc->sc_tv_status_total = ktime_add(sc->sc_tv_status_total,
232                                            ktime_sub(ktime_get(),
233                                                      nst->st_status_time));
234         sc->sc_tv_send_total = ktime_add(sc->sc_tv_send_total,
235                                          ktime_sub(nst->st_status_time,
236                                                    nst->st_send_time));
237         sc->sc_tv_acquiry_total = ktime_add(sc->sc_tv_acquiry_total,
238                                             ktime_sub(nst->st_send_time,
239                                                       nst->st_sock_time));
240         sc->sc_send_count++;
241 }
242
243 #else
244
245 # define o2net_update_send_stats(a, b)
246
247 #endif /* CONFIG_OCFS2_FS_STATS */
248
249 static inline int o2net_reconnect_delay(void)
250 {
251         return o2nm_single_cluster->cl_reconnect_delay_ms;
252 }
253
254 static inline int o2net_keepalive_delay(void)
255 {
256         return o2nm_single_cluster->cl_keepalive_delay_ms;
257 }
258
259 static inline int o2net_idle_timeout(void)
260 {
261         return o2nm_single_cluster->cl_idle_timeout_ms;
262 }
263
264 static inline int o2net_sys_err_to_errno(enum o2net_system_error err)
265 {
266         int trans;
267         BUG_ON(err >= O2NET_ERR_MAX);
268         trans = o2net_sys_err_translations[err];
269
270         /* Just in case we mess up the translation table above */
271         BUG_ON(err != O2NET_ERR_NONE && trans == 0);
272         return trans;
273 }
274
275 static struct o2net_node * o2net_nn_from_num(u8 node_num)
276 {
277         BUG_ON(node_num >= ARRAY_SIZE(o2net_nodes));
278         return &o2net_nodes[node_num];
279 }
280
281 static u8 o2net_num_from_nn(struct o2net_node *nn)
282 {
283         BUG_ON(nn == NULL);
284         return nn - o2net_nodes;
285 }
286
287 /* ------------------------------------------------------------ */
288
289 static int o2net_prep_nsw(struct o2net_node *nn, struct o2net_status_wait *nsw)
290 {
291         int ret = 0;
292
293         do {
294                 if (!idr_pre_get(&nn->nn_status_idr, GFP_ATOMIC)) {
295                         ret = -EAGAIN;
296                         break;
297                 }
298                 spin_lock(&nn->nn_lock);
299                 ret = idr_get_new(&nn->nn_status_idr, nsw, &nsw->ns_id);
300                 if (ret == 0)
301                         list_add_tail(&nsw->ns_node_item,
302                                       &nn->nn_status_list);
303                 spin_unlock(&nn->nn_lock);
304         } while (ret == -EAGAIN);
305
306         if (ret == 0)  {
307                 init_waitqueue_head(&nsw->ns_wq);
308                 nsw->ns_sys_status = O2NET_ERR_NONE;
309                 nsw->ns_status = 0;
310         }
311
312         return ret;
313 }
314
315 static void o2net_complete_nsw_locked(struct o2net_node *nn,
316                                       struct o2net_status_wait *nsw,
317                                       enum o2net_system_error sys_status,
318                                       s32 status)
319 {
320         assert_spin_locked(&nn->nn_lock);
321
322         if (!list_empty(&nsw->ns_node_item)) {
323                 list_del_init(&nsw->ns_node_item);
324                 nsw->ns_sys_status = sys_status;
325                 nsw->ns_status = status;
326                 idr_remove(&nn->nn_status_idr, nsw->ns_id);
327                 wake_up(&nsw->ns_wq);
328         }
329 }
330
331 static void o2net_complete_nsw(struct o2net_node *nn,
332                                struct o2net_status_wait *nsw,
333                                u64 id, enum o2net_system_error sys_status,
334                                s32 status)
335 {
336         spin_lock(&nn->nn_lock);
337         if (nsw == NULL) {
338                 if (id > INT_MAX)
339                         goto out;
340
341                 nsw = idr_find(&nn->nn_status_idr, id);
342                 if (nsw == NULL)
343                         goto out;
344         }
345
346         o2net_complete_nsw_locked(nn, nsw, sys_status, status);
347
348 out:
349         spin_unlock(&nn->nn_lock);
350         return;
351 }
352
353 static void o2net_complete_nodes_nsw(struct o2net_node *nn)
354 {
355         struct o2net_status_wait *nsw, *tmp;
356         unsigned int num_kills = 0;
357
358         assert_spin_locked(&nn->nn_lock);
359
360         list_for_each_entry_safe(nsw, tmp, &nn->nn_status_list, ns_node_item) {
361                 o2net_complete_nsw_locked(nn, nsw, O2NET_ERR_DIED, 0);
362                 num_kills++;
363         }
364
365         mlog(0, "completed %d messages for node %u\n", num_kills,
366              o2net_num_from_nn(nn));
367 }
368
369 static int o2net_nsw_completed(struct o2net_node *nn,
370                                struct o2net_status_wait *nsw)
371 {
372         int completed;
373         spin_lock(&nn->nn_lock);
374         completed = list_empty(&nsw->ns_node_item);
375         spin_unlock(&nn->nn_lock);
376         return completed;
377 }
378
379 /* ------------------------------------------------------------ */
380
381 static void sc_kref_release(struct kref *kref)
382 {
383         struct o2net_sock_container *sc = container_of(kref,
384                                         struct o2net_sock_container, sc_kref);
385         BUG_ON(timer_pending(&sc->sc_idle_timeout));
386
387         sclog(sc, "releasing\n");
388
389         if (sc->sc_sock) {
390                 sock_release(sc->sc_sock);
391                 sc->sc_sock = NULL;
392         }
393
394         o2nm_undepend_item(&sc->sc_node->nd_item);
395         o2nm_node_put(sc->sc_node);
396         sc->sc_node = NULL;
397
398         o2net_debug_del_sc(sc);
399         kfree(sc);
400 }
401
402 static void sc_put(struct o2net_sock_container *sc)
403 {
404         sclog(sc, "put\n");
405         kref_put(&sc->sc_kref, sc_kref_release);
406 }
407 static void sc_get(struct o2net_sock_container *sc)
408 {
409         sclog(sc, "get\n");
410         kref_get(&sc->sc_kref);
411 }
412 static struct o2net_sock_container *sc_alloc(struct o2nm_node *node)
413 {
414         struct o2net_sock_container *sc, *ret = NULL;
415         struct page *page = NULL;
416         int status = 0;
417
418         page = alloc_page(GFP_NOFS);
419         sc = kzalloc(sizeof(*sc), GFP_NOFS);
420         if (sc == NULL || page == NULL)
421                 goto out;
422
423         kref_init(&sc->sc_kref);
424         o2nm_node_get(node);
425         sc->sc_node = node;
426
427         /* pin the node item of the remote node */
428         status = o2nm_depend_item(&node->nd_item);
429         if (status) {
430                 mlog_errno(status);
431                 o2nm_node_put(node);
432                 goto out;
433         }
434         INIT_WORK(&sc->sc_connect_work, o2net_sc_connect_completed);
435         INIT_WORK(&sc->sc_rx_work, o2net_rx_until_empty);
436         INIT_WORK(&sc->sc_shutdown_work, o2net_shutdown_sc);
437         INIT_DELAYED_WORK(&sc->sc_keepalive_work, o2net_sc_send_keep_req);
438
439         init_timer(&sc->sc_idle_timeout);
440         sc->sc_idle_timeout.function = o2net_idle_timer;
441         sc->sc_idle_timeout.data = (unsigned long)sc;
442
443         sclog(sc, "alloced\n");
444
445         ret = sc;
446         sc->sc_page = page;
447         o2net_debug_add_sc(sc);
448         sc = NULL;
449         page = NULL;
450
451 out:
452         if (page)
453                 __free_page(page);
454         kfree(sc);
455
456         return ret;
457 }
458
459 /* ------------------------------------------------------------ */
460
461 static void o2net_sc_queue_work(struct o2net_sock_container *sc,
462                                 struct work_struct *work)
463 {
464         sc_get(sc);
465         if (!queue_work(o2net_wq, work))
466                 sc_put(sc);
467 }
468 static void o2net_sc_queue_delayed_work(struct o2net_sock_container *sc,
469                                         struct delayed_work *work,
470                                         int delay)
471 {
472         sc_get(sc);
473         if (!queue_delayed_work(o2net_wq, work, delay))
474                 sc_put(sc);
475 }
476 static void o2net_sc_cancel_delayed_work(struct o2net_sock_container *sc,
477                                          struct delayed_work *work)
478 {
479         if (cancel_delayed_work(work))
480                 sc_put(sc);
481 }
482
483 static atomic_t o2net_connected_peers = ATOMIC_INIT(0);
484
485 int o2net_num_connected_peers(void)
486 {
487         return atomic_read(&o2net_connected_peers);
488 }
489
490 static void o2net_set_nn_state(struct o2net_node *nn,
491                                struct o2net_sock_container *sc,
492                                unsigned valid, int err)
493 {
494         int was_valid = nn->nn_sc_valid;
495         int was_err = nn->nn_persistent_error;
496         struct o2net_sock_container *old_sc = nn->nn_sc;
497
498         assert_spin_locked(&nn->nn_lock);
499
500         if (old_sc && !sc)
501                 atomic_dec(&o2net_connected_peers);
502         else if (!old_sc && sc)
503                 atomic_inc(&o2net_connected_peers);
504
505         /* the node num comparison and single connect/accept path should stop
506          * an non-null sc from being overwritten with another */
507         BUG_ON(sc && nn->nn_sc && nn->nn_sc != sc);
508         mlog_bug_on_msg(err && valid, "err %d valid %u\n", err, valid);
509         mlog_bug_on_msg(valid && !sc, "valid %u sc %p\n", valid, sc);
510
511         if (was_valid && !valid && err == 0)
512                 err = -ENOTCONN;
513
514         mlog(ML_CONN, "node %u sc: %p -> %p, valid %u -> %u, err %d -> %d\n",
515              o2net_num_from_nn(nn), nn->nn_sc, sc, nn->nn_sc_valid, valid,
516              nn->nn_persistent_error, err);
517
518         nn->nn_sc = sc;
519         nn->nn_sc_valid = valid ? 1 : 0;
520         nn->nn_persistent_error = err;
521
522         /* mirrors o2net_tx_can_proceed() */
523         if (nn->nn_persistent_error || nn->nn_sc_valid)
524                 wake_up(&nn->nn_sc_wq);
525
526         if (!was_err && nn->nn_persistent_error) {
527                 o2quo_conn_err(o2net_num_from_nn(nn));
528                 queue_delayed_work(o2net_wq, &nn->nn_still_up,
529                                    msecs_to_jiffies(O2NET_QUORUM_DELAY_MS));
530         }
531
532         if (was_valid && !valid) {
533                 printk(KERN_NOTICE "o2net: no longer connected to "
534                        SC_NODEF_FMT "\n", SC_NODEF_ARGS(old_sc));
535                 o2net_complete_nodes_nsw(nn);
536         }
537
538         if (!was_valid && valid) {
539                 o2quo_conn_up(o2net_num_from_nn(nn));
540                 cancel_delayed_work(&nn->nn_connect_expired);
541                 printk(KERN_NOTICE "o2net: %s " SC_NODEF_FMT "\n",
542                        o2nm_this_node() > sc->sc_node->nd_num ?
543                                 "connected to" : "accepted connection from",
544                        SC_NODEF_ARGS(sc));
545         }
546
547         /* trigger the connecting worker func as long as we're not valid,
548          * it will back off if it shouldn't connect.  This can be called
549          * from node config teardown and so needs to be careful about
550          * the work queue actually being up. */
551         if (!valid && o2net_wq) {
552                 unsigned long delay;
553                 /* delay if we're withing a RECONNECT_DELAY of the
554                  * last attempt */
555                 delay = (nn->nn_last_connect_attempt +
556                          msecs_to_jiffies(o2net_reconnect_delay()))
557                         - jiffies;
558                 if (delay > msecs_to_jiffies(o2net_reconnect_delay()))
559                         delay = 0;
560                 mlog(ML_CONN, "queueing conn attempt in %lu jiffies\n", delay);
561                 queue_delayed_work(o2net_wq, &nn->nn_connect_work, delay);
562
563                 /*
564                  * Delay the expired work after idle timeout.
565                  *
566                  * We might have lots of failed connection attempts that run
567                  * through here but we only cancel the connect_expired work when
568                  * a connection attempt succeeds.  So only the first enqueue of
569                  * the connect_expired work will do anything.  The rest will see
570                  * that it's already queued and do nothing.
571                  */
572                 delay += msecs_to_jiffies(o2net_idle_timeout());
573                 queue_delayed_work(o2net_wq, &nn->nn_connect_expired, delay);
574         }
575
576         /* keep track of the nn's sc ref for the caller */
577         if ((old_sc == NULL) && sc)
578                 sc_get(sc);
579         if (old_sc && (old_sc != sc)) {
580                 o2net_sc_queue_work(old_sc, &old_sc->sc_shutdown_work);
581                 sc_put(old_sc);
582         }
583 }
584
585 /* see o2net_register_callbacks() */
586 static void o2net_data_ready(struct sock *sk, int bytes)
587 {
588         void (*ready)(struct sock *sk, int bytes);
589
590         read_lock(&sk->sk_callback_lock);
591         if (sk->sk_user_data) {
592                 struct o2net_sock_container *sc = sk->sk_user_data;
593                 sclog(sc, "data_ready hit\n");
594                 o2net_set_data_ready_time(sc);
595                 o2net_sc_queue_work(sc, &sc->sc_rx_work);
596                 ready = sc->sc_data_ready;
597         } else {
598                 ready = sk->sk_data_ready;
599         }
600         read_unlock(&sk->sk_callback_lock);
601
602         ready(sk, bytes);
603 }
604
605 /* see o2net_register_callbacks() */
606 static void o2net_state_change(struct sock *sk)
607 {
608         void (*state_change)(struct sock *sk);
609         struct o2net_sock_container *sc;
610
611         read_lock(&sk->sk_callback_lock);
612         sc = sk->sk_user_data;
613         if (sc == NULL) {
614                 state_change = sk->sk_state_change;
615                 goto out;
616         }
617
618         sclog(sc, "state_change to %d\n", sk->sk_state);
619
620         state_change = sc->sc_state_change;
621
622         switch(sk->sk_state) {
623                 /* ignore connecting sockets as they make progress */
624                 case TCP_SYN_SENT:
625                 case TCP_SYN_RECV:
626                         break;
627                 case TCP_ESTABLISHED:
628                         o2net_sc_queue_work(sc, &sc->sc_connect_work);
629                         break;
630                 default:
631                         printk(KERN_INFO "o2net: connection to " SC_NODEF_FMT
632                               " shutdown, state %d\n",
633                               SC_NODEF_ARGS(sc), sk->sk_state);
634                         o2net_sc_queue_work(sc, &sc->sc_shutdown_work);
635                         break;
636         }
637 out:
638         read_unlock(&sk->sk_callback_lock);
639         state_change(sk);
640 }
641
642 /*
643  * we register callbacks so we can queue work on events before calling
644  * the original callbacks.  our callbacks our careful to test user_data
645  * to discover when they've reaced with o2net_unregister_callbacks().
646  */
647 static void o2net_register_callbacks(struct sock *sk,
648                                      struct o2net_sock_container *sc)
649 {
650         write_lock_bh(&sk->sk_callback_lock);
651
652         /* accepted sockets inherit the old listen socket data ready */
653         if (sk->sk_data_ready == o2net_listen_data_ready) {
654                 sk->sk_data_ready = sk->sk_user_data;
655                 sk->sk_user_data = NULL;
656         }
657
658         BUG_ON(sk->sk_user_data != NULL);
659         sk->sk_user_data = sc;
660         sc_get(sc);
661
662         sc->sc_data_ready = sk->sk_data_ready;
663         sc->sc_state_change = sk->sk_state_change;
664         sk->sk_data_ready = o2net_data_ready;
665         sk->sk_state_change = o2net_state_change;
666
667         mutex_init(&sc->sc_send_lock);
668
669         write_unlock_bh(&sk->sk_callback_lock);
670 }
671
672 static int o2net_unregister_callbacks(struct sock *sk,
673                                    struct o2net_sock_container *sc)
674 {
675         int ret = 0;
676
677         write_lock_bh(&sk->sk_callback_lock);
678         if (sk->sk_user_data == sc) {
679                 ret = 1;
680                 sk->sk_user_data = NULL;
681                 sk->sk_data_ready = sc->sc_data_ready;
682                 sk->sk_state_change = sc->sc_state_change;
683         }
684         write_unlock_bh(&sk->sk_callback_lock);
685
686         return ret;
687 }
688
689 /*
690  * this is a little helper that is called by callers who have seen a problem
691  * with an sc and want to detach it from the nn if someone already hasn't beat
692  * them to it.  if an error is given then the shutdown will be persistent
693  * and pending transmits will be canceled.
694  */
695 static void o2net_ensure_shutdown(struct o2net_node *nn,
696                                    struct o2net_sock_container *sc,
697                                    int err)
698 {
699         spin_lock(&nn->nn_lock);
700         if (nn->nn_sc == sc)
701                 o2net_set_nn_state(nn, NULL, 0, err);
702         spin_unlock(&nn->nn_lock);
703 }
704
705 /*
706  * This work queue function performs the blocking parts of socket shutdown.  A
707  * few paths lead here.  set_nn_state will trigger this callback if it sees an
708  * sc detached from the nn.  state_change will also trigger this callback
709  * directly when it sees errors.  In that case we need to call set_nn_state
710  * ourselves as state_change couldn't get the nn_lock and call set_nn_state
711  * itself.
712  */
713 static void o2net_shutdown_sc(struct work_struct *work)
714 {
715         struct o2net_sock_container *sc =
716                 container_of(work, struct o2net_sock_container,
717                              sc_shutdown_work);
718         struct o2net_node *nn = o2net_nn_from_num(sc->sc_node->nd_num);
719
720         sclog(sc, "shutting down\n");
721
722         /* drop the callbacks ref and call shutdown only once */
723         if (o2net_unregister_callbacks(sc->sc_sock->sk, sc)) {
724                 /* we shouldn't flush as we're in the thread, the
725                  * races with pending sc work structs are harmless */
726                 del_timer_sync(&sc->sc_idle_timeout);
727                 o2net_sc_cancel_delayed_work(sc, &sc->sc_keepalive_work);
728                 sc_put(sc);
729                 kernel_sock_shutdown(sc->sc_sock, SHUT_RDWR);
730         }
731
732         /* not fatal so failed connects before the other guy has our
733          * heartbeat can be retried */
734         o2net_ensure_shutdown(nn, sc, 0);
735         sc_put(sc);
736 }
737
738 /* ------------------------------------------------------------ */
739
740 static int o2net_handler_cmp(struct o2net_msg_handler *nmh, u32 msg_type,
741                              u32 key)
742 {
743         int ret = memcmp(&nmh->nh_key, &key, sizeof(key));
744
745         if (ret == 0)
746                 ret = memcmp(&nmh->nh_msg_type, &msg_type, sizeof(msg_type));
747
748         return ret;
749 }
750
751 static struct o2net_msg_handler *
752 o2net_handler_tree_lookup(u32 msg_type, u32 key, struct rb_node ***ret_p,
753                           struct rb_node **ret_parent)
754 {
755         struct rb_node **p = &o2net_handler_tree.rb_node;
756         struct rb_node *parent = NULL;
757         struct o2net_msg_handler *nmh, *ret = NULL;
758         int cmp;
759
760         while (*p) {
761                 parent = *p;
762                 nmh = rb_entry(parent, struct o2net_msg_handler, nh_node);
763                 cmp = o2net_handler_cmp(nmh, msg_type, key);
764
765                 if (cmp < 0)
766                         p = &(*p)->rb_left;
767                 else if (cmp > 0)
768                         p = &(*p)->rb_right;
769                 else {
770                         ret = nmh;
771                         break;
772                 }
773         }
774
775         if (ret_p != NULL)
776                 *ret_p = p;
777         if (ret_parent != NULL)
778                 *ret_parent = parent;
779
780         return ret;
781 }
782
783 static void o2net_handler_kref_release(struct kref *kref)
784 {
785         struct o2net_msg_handler *nmh;
786         nmh = container_of(kref, struct o2net_msg_handler, nh_kref);
787
788         kfree(nmh);
789 }
790
791 static void o2net_handler_put(struct o2net_msg_handler *nmh)
792 {
793         kref_put(&nmh->nh_kref, o2net_handler_kref_release);
794 }
795
796 /* max_len is protection for the handler func.  incoming messages won't
797  * be given to the handler if their payload is longer than the max. */
798 int o2net_register_handler(u32 msg_type, u32 key, u32 max_len,
799                            o2net_msg_handler_func *func, void *data,
800                            o2net_post_msg_handler_func *post_func,
801                            struct list_head *unreg_list)
802 {
803         struct o2net_msg_handler *nmh = NULL;
804         struct rb_node **p, *parent;
805         int ret = 0;
806
807         if (max_len > O2NET_MAX_PAYLOAD_BYTES) {
808                 mlog(0, "max_len for message handler out of range: %u\n",
809                         max_len);
810                 ret = -EINVAL;
811                 goto out;
812         }
813
814         if (!msg_type) {
815                 mlog(0, "no message type provided: %u, %p\n", msg_type, func);
816                 ret = -EINVAL;
817                 goto out;
818
819         }
820         if (!func) {
821                 mlog(0, "no message handler provided: %u, %p\n",
822                        msg_type, func);
823                 ret = -EINVAL;
824                 goto out;
825         }
826
827         nmh = kzalloc(sizeof(struct o2net_msg_handler), GFP_NOFS);
828         if (nmh == NULL) {
829                 ret = -ENOMEM;
830                 goto out;
831         }
832
833         nmh->nh_func = func;
834         nmh->nh_func_data = data;
835         nmh->nh_post_func = post_func;
836         nmh->nh_msg_type = msg_type;
837         nmh->nh_max_len = max_len;
838         nmh->nh_key = key;
839         /* the tree and list get this ref.. they're both removed in
840          * unregister when this ref is dropped */
841         kref_init(&nmh->nh_kref);
842         INIT_LIST_HEAD(&nmh->nh_unregister_item);
843
844         write_lock(&o2net_handler_lock);
845         if (o2net_handler_tree_lookup(msg_type, key, &p, &parent))
846                 ret = -EEXIST;
847         else {
848                 rb_link_node(&nmh->nh_node, parent, p);
849                 rb_insert_color(&nmh->nh_node, &o2net_handler_tree);
850                 list_add_tail(&nmh->nh_unregister_item, unreg_list);
851
852                 mlog(ML_TCP, "registered handler func %p type %u key %08x\n",
853                      func, msg_type, key);
854                 /* we've had some trouble with handlers seemingly vanishing. */
855                 mlog_bug_on_msg(o2net_handler_tree_lookup(msg_type, key, &p,
856                                                           &parent) == NULL,
857                                 "couldn't find handler we *just* registerd "
858                                 "for type %u key %08x\n", msg_type, key);
859         }
860         write_unlock(&o2net_handler_lock);
861         if (ret)
862                 goto out;
863
864 out:
865         if (ret)
866                 kfree(nmh);
867
868         return ret;
869 }
870 EXPORT_SYMBOL_GPL(o2net_register_handler);
871
872 void o2net_unregister_handler_list(struct list_head *list)
873 {
874         struct o2net_msg_handler *nmh, *n;
875
876         write_lock(&o2net_handler_lock);
877         list_for_each_entry_safe(nmh, n, list, nh_unregister_item) {
878                 mlog(ML_TCP, "unregistering handler func %p type %u key %08x\n",
879                      nmh->nh_func, nmh->nh_msg_type, nmh->nh_key);
880                 rb_erase(&nmh->nh_node, &o2net_handler_tree);
881                 list_del_init(&nmh->nh_unregister_item);
882                 kref_put(&nmh->nh_kref, o2net_handler_kref_release);
883         }
884         write_unlock(&o2net_handler_lock);
885 }
886 EXPORT_SYMBOL_GPL(o2net_unregister_handler_list);
887
888 static struct o2net_msg_handler *o2net_handler_get(u32 msg_type, u32 key)
889 {
890         struct o2net_msg_handler *nmh;
891
892         read_lock(&o2net_handler_lock);
893         nmh = o2net_handler_tree_lookup(msg_type, key, NULL, NULL);
894         if (nmh)
895                 kref_get(&nmh->nh_kref);
896         read_unlock(&o2net_handler_lock);
897
898         return nmh;
899 }
900
901 /* ------------------------------------------------------------ */
902
903 static int o2net_recv_tcp_msg(struct socket *sock, void *data, size_t len)
904 {
905         int ret;
906         mm_segment_t oldfs;
907         struct kvec vec = {
908                 .iov_len = len,
909                 .iov_base = data,
910         };
911         struct msghdr msg = {
912                 .msg_iovlen = 1,
913                 .msg_iov = (struct iovec *)&vec,
914                 .msg_flags = MSG_DONTWAIT,
915         };
916
917         oldfs = get_fs();
918         set_fs(get_ds());
919         ret = sock_recvmsg(sock, &msg, len, msg.msg_flags);
920         set_fs(oldfs);
921
922         return ret;
923 }
924
925 static int o2net_send_tcp_msg(struct socket *sock, struct kvec *vec,
926                               size_t veclen, size_t total)
927 {
928         int ret;
929         mm_segment_t oldfs;
930         struct msghdr msg = {
931                 .msg_iov = (struct iovec *)vec,
932                 .msg_iovlen = veclen,
933         };
934
935         if (sock == NULL) {
936                 ret = -EINVAL;
937                 goto out;
938         }
939
940         oldfs = get_fs();
941         set_fs(get_ds());
942         ret = sock_sendmsg(sock, &msg, total);
943         set_fs(oldfs);
944         if (ret != total) {
945                 mlog(ML_ERROR, "sendmsg returned %d instead of %zu\n", ret,
946                      total);
947                 if (ret >= 0)
948                         ret = -EPIPE; /* should be smarter, I bet */
949                 goto out;
950         }
951
952         ret = 0;
953 out:
954         if (ret < 0)
955                 mlog(0, "returning error: %d\n", ret);
956         return ret;
957 }
958
959 static void o2net_sendpage(struct o2net_sock_container *sc,
960                            void *kmalloced_virt,
961                            size_t size)
962 {
963         struct o2net_node *nn = o2net_nn_from_num(sc->sc_node->nd_num);
964         ssize_t ret;
965
966         while (1) {
967                 mutex_lock(&sc->sc_send_lock);
968                 ret = sc->sc_sock->ops->sendpage(sc->sc_sock,
969                                                  virt_to_page(kmalloced_virt),
970                                                  (long)kmalloced_virt & ~PAGE_MASK,
971                                                  size, MSG_DONTWAIT);
972                 mutex_unlock(&sc->sc_send_lock);
973                 if (ret == size)
974                         break;
975                 if (ret == (ssize_t)-EAGAIN) {
976                         mlog(0, "sendpage of size %zu to " SC_NODEF_FMT
977                              " returned EAGAIN\n", size, SC_NODEF_ARGS(sc));
978                         cond_resched();
979                         continue;
980                 }
981                 mlog(ML_ERROR, "sendpage of size %zu to " SC_NODEF_FMT
982                      " failed with %zd\n", size, SC_NODEF_ARGS(sc), ret);
983                 o2net_ensure_shutdown(nn, sc, 0);
984                 break;
985         }
986 }
987
988 static void o2net_init_msg(struct o2net_msg *msg, u16 data_len, u16 msg_type, u32 key)
989 {
990         memset(msg, 0, sizeof(struct o2net_msg));
991         msg->magic = cpu_to_be16(O2NET_MSG_MAGIC);
992         msg->data_len = cpu_to_be16(data_len);
993         msg->msg_type = cpu_to_be16(msg_type);
994         msg->sys_status = cpu_to_be32(O2NET_ERR_NONE);
995         msg->status = 0;
996         msg->key = cpu_to_be32(key);
997 }
998
999 static int o2net_tx_can_proceed(struct o2net_node *nn,
1000                                 struct o2net_sock_container **sc_ret,
1001                                 int *error)
1002 {
1003         int ret = 0;
1004
1005         spin_lock(&nn->nn_lock);
1006         if (nn->nn_persistent_error) {
1007                 ret = 1;
1008                 *sc_ret = NULL;
1009                 *error = nn->nn_persistent_error;
1010         } else if (nn->nn_sc_valid) {
1011                 kref_get(&nn->nn_sc->sc_kref);
1012
1013                 ret = 1;
1014                 *sc_ret = nn->nn_sc;
1015                 *error = 0;
1016         }
1017         spin_unlock(&nn->nn_lock);
1018
1019         return ret;
1020 }
1021
1022 int o2net_send_message_vec(u32 msg_type, u32 key, struct kvec *caller_vec,
1023                            size_t caller_veclen, u8 target_node, int *status)
1024 {
1025         int ret = 0;
1026         struct o2net_msg *msg = NULL;
1027         size_t veclen, caller_bytes = 0;
1028         struct kvec *vec = NULL;
1029         struct o2net_sock_container *sc = NULL;
1030         struct o2net_node *nn = o2net_nn_from_num(target_node);
1031         struct o2net_status_wait nsw = {
1032                 .ns_node_item = LIST_HEAD_INIT(nsw.ns_node_item),
1033         };
1034         struct o2net_send_tracking nst;
1035
1036         o2net_init_nst(&nst, msg_type, key, current, target_node);
1037
1038         if (o2net_wq == NULL) {
1039                 mlog(0, "attempt to tx without o2netd running\n");
1040                 ret = -ESRCH;
1041                 goto out;
1042         }
1043
1044         if (caller_veclen == 0) {
1045                 mlog(0, "bad kvec array length\n");
1046                 ret = -EINVAL;
1047                 goto out;
1048         }
1049
1050         caller_bytes = iov_length((struct iovec *)caller_vec, caller_veclen);
1051         if (caller_bytes > O2NET_MAX_PAYLOAD_BYTES) {
1052                 mlog(0, "total payload len %zu too large\n", caller_bytes);
1053                 ret = -EINVAL;
1054                 goto out;
1055         }
1056
1057         if (target_node == o2nm_this_node()) {
1058                 ret = -ELOOP;
1059                 goto out;
1060         }
1061
1062         o2net_debug_add_nst(&nst);
1063
1064         o2net_set_nst_sock_time(&nst);
1065
1066         wait_event(nn->nn_sc_wq, o2net_tx_can_proceed(nn, &sc, &ret));
1067         if (ret)
1068                 goto out;
1069
1070         o2net_set_nst_sock_container(&nst, sc);
1071
1072         veclen = caller_veclen + 1;
1073         vec = kmalloc(sizeof(struct kvec) * veclen, GFP_ATOMIC);
1074         if (vec == NULL) {
1075                 mlog(0, "failed to %zu element kvec!\n", veclen);
1076                 ret = -ENOMEM;
1077                 goto out;
1078         }
1079
1080         msg = kmalloc(sizeof(struct o2net_msg), GFP_ATOMIC);
1081         if (!msg) {
1082                 mlog(0, "failed to allocate a o2net_msg!\n");
1083                 ret = -ENOMEM;
1084                 goto out;
1085         }
1086
1087         o2net_init_msg(msg, caller_bytes, msg_type, key);
1088
1089         vec[0].iov_len = sizeof(struct o2net_msg);
1090         vec[0].iov_base = msg;
1091         memcpy(&vec[1], caller_vec, caller_veclen * sizeof(struct kvec));
1092
1093         ret = o2net_prep_nsw(nn, &nsw);
1094         if (ret)
1095                 goto out;
1096
1097         msg->msg_num = cpu_to_be32(nsw.ns_id);
1098         o2net_set_nst_msg_id(&nst, nsw.ns_id);
1099
1100         o2net_set_nst_send_time(&nst);
1101
1102         /* finally, convert the message header to network byte-order
1103          * and send */
1104         mutex_lock(&sc->sc_send_lock);
1105         ret = o2net_send_tcp_msg(sc->sc_sock, vec, veclen,
1106                                  sizeof(struct o2net_msg) + caller_bytes);
1107         mutex_unlock(&sc->sc_send_lock);
1108         msglog(msg, "sending returned %d\n", ret);
1109         if (ret < 0) {
1110                 mlog(0, "error returned from o2net_send_tcp_msg=%d\n", ret);
1111                 goto out;
1112         }
1113
1114         /* wait on other node's handler */
1115         o2net_set_nst_status_time(&nst);
1116         wait_event(nsw.ns_wq, o2net_nsw_completed(nn, &nsw));
1117
1118         o2net_update_send_stats(&nst, sc);
1119
1120         /* Note that we avoid overwriting the callers status return
1121          * variable if a system error was reported on the other
1122          * side. Callers beware. */
1123         ret = o2net_sys_err_to_errno(nsw.ns_sys_status);
1124         if (status && !ret)
1125                 *status = nsw.ns_status;
1126
1127         mlog(0, "woken, returning system status %d, user status %d\n",
1128              ret, nsw.ns_status);
1129 out:
1130         o2net_debug_del_nst(&nst); /* must be before dropping sc and node */
1131         if (sc)
1132                 sc_put(sc);
1133         if (vec)
1134                 kfree(vec);
1135         if (msg)
1136                 kfree(msg);
1137         o2net_complete_nsw(nn, &nsw, 0, 0, 0);
1138         return ret;
1139 }
1140 EXPORT_SYMBOL_GPL(o2net_send_message_vec);
1141
1142 int o2net_send_message(u32 msg_type, u32 key, void *data, u32 len,
1143                        u8 target_node, int *status)
1144 {
1145         struct kvec vec = {
1146                 .iov_base = data,
1147                 .iov_len = len,
1148         };
1149         return o2net_send_message_vec(msg_type, key, &vec, 1,
1150                                       target_node, status);
1151 }
1152 EXPORT_SYMBOL_GPL(o2net_send_message);
1153
1154 static int o2net_send_status_magic(struct socket *sock, struct o2net_msg *hdr,
1155                                    enum o2net_system_error syserr, int err)
1156 {
1157         struct kvec vec = {
1158                 .iov_base = hdr,
1159                 .iov_len = sizeof(struct o2net_msg),
1160         };
1161
1162         BUG_ON(syserr >= O2NET_ERR_MAX);
1163
1164         /* leave other fields intact from the incoming message, msg_num
1165          * in particular */
1166         hdr->sys_status = cpu_to_be32(syserr);
1167         hdr->status = cpu_to_be32(err);
1168         hdr->magic = cpu_to_be16(O2NET_MSG_STATUS_MAGIC);  // twiddle the magic
1169         hdr->data_len = 0;
1170
1171         msglog(hdr, "about to send status magic %d\n", err);
1172         /* hdr has been in host byteorder this whole time */
1173         return o2net_send_tcp_msg(sock, &vec, 1, sizeof(struct o2net_msg));
1174 }
1175
1176 /* this returns -errno if the header was unknown or too large, etc.
1177  * after this is called the buffer us reused for the next message */
1178 static int o2net_process_message(struct o2net_sock_container *sc,
1179                                  struct o2net_msg *hdr)
1180 {
1181         struct o2net_node *nn = o2net_nn_from_num(sc->sc_node->nd_num);
1182         int ret = 0, handler_status;
1183         enum  o2net_system_error syserr;
1184         struct o2net_msg_handler *nmh = NULL;
1185         void *ret_data = NULL;
1186
1187         msglog(hdr, "processing message\n");
1188
1189         o2net_sc_postpone_idle(sc);
1190
1191         switch(be16_to_cpu(hdr->magic)) {
1192                 case O2NET_MSG_STATUS_MAGIC:
1193                         /* special type for returning message status */
1194                         o2net_complete_nsw(nn, NULL,
1195                                            be32_to_cpu(hdr->msg_num),
1196                                            be32_to_cpu(hdr->sys_status),
1197                                            be32_to_cpu(hdr->status));
1198                         goto out;
1199                 case O2NET_MSG_KEEP_REQ_MAGIC:
1200                         o2net_sendpage(sc, o2net_keep_resp,
1201                                        sizeof(*o2net_keep_resp));
1202                         goto out;
1203                 case O2NET_MSG_KEEP_RESP_MAGIC:
1204                         goto out;
1205                 case O2NET_MSG_MAGIC:
1206                         break;
1207                 default:
1208                         msglog(hdr, "bad magic\n");
1209                         ret = -EINVAL;
1210                         goto out;
1211                         break;
1212         }
1213
1214         /* find a handler for it */
1215         handler_status = 0;
1216         nmh = o2net_handler_get(be16_to_cpu(hdr->msg_type),
1217                                 be32_to_cpu(hdr->key));
1218         if (!nmh) {
1219                 mlog(ML_TCP, "couldn't find handler for type %u key %08x\n",
1220                      be16_to_cpu(hdr->msg_type), be32_to_cpu(hdr->key));
1221                 syserr = O2NET_ERR_NO_HNDLR;
1222                 goto out_respond;
1223         }
1224
1225         syserr = O2NET_ERR_NONE;
1226
1227         if (be16_to_cpu(hdr->data_len) > nmh->nh_max_len)
1228                 syserr = O2NET_ERR_OVERFLOW;
1229
1230         if (syserr != O2NET_ERR_NONE)
1231                 goto out_respond;
1232
1233         o2net_set_func_start_time(sc);
1234         sc->sc_msg_key = be32_to_cpu(hdr->key);
1235         sc->sc_msg_type = be16_to_cpu(hdr->msg_type);
1236         handler_status = (nmh->nh_func)(hdr, sizeof(struct o2net_msg) +
1237                                              be16_to_cpu(hdr->data_len),
1238                                         nmh->nh_func_data, &ret_data);
1239         o2net_set_func_stop_time(sc);
1240
1241 out_respond:
1242         /* this destroys the hdr, so don't use it after this */
1243         mutex_lock(&sc->sc_send_lock);
1244         ret = o2net_send_status_magic(sc->sc_sock, hdr, syserr,
1245                                       handler_status);
1246         mutex_unlock(&sc->sc_send_lock);
1247         hdr = NULL;
1248         mlog(0, "sending handler status %d, syserr %d returned %d\n",
1249              handler_status, syserr, ret);
1250
1251         if (nmh) {
1252                 BUG_ON(ret_data != NULL && nmh->nh_post_func == NULL);
1253                 if (nmh->nh_post_func)
1254                         (nmh->nh_post_func)(handler_status, nmh->nh_func_data,
1255                                             ret_data);
1256         }
1257
1258 out:
1259         if (nmh)
1260                 o2net_handler_put(nmh);
1261         return ret;
1262 }
1263
1264 static int o2net_check_handshake(struct o2net_sock_container *sc)
1265 {
1266         struct o2net_handshake *hand = page_address(sc->sc_page);
1267         struct o2net_node *nn = o2net_nn_from_num(sc->sc_node->nd_num);
1268
1269         if (hand->protocol_version != cpu_to_be64(O2NET_PROTOCOL_VERSION)) {
1270                 mlog(ML_NOTICE, SC_NODEF_FMT " advertised net protocol "
1271                      "version %llu but %llu is required, disconnecting\n",
1272                      SC_NODEF_ARGS(sc),
1273                      (unsigned long long)be64_to_cpu(hand->protocol_version),
1274                      O2NET_PROTOCOL_VERSION);
1275
1276                 /* don't bother reconnecting if its the wrong version. */
1277                 o2net_ensure_shutdown(nn, sc, -ENOTCONN);
1278                 return -1;
1279         }
1280
1281         /*
1282          * Ensure timeouts are consistent with other nodes, otherwise
1283          * we can end up with one node thinking that the other must be down,
1284          * but isn't. This can ultimately cause corruption.
1285          */
1286         if (be32_to_cpu(hand->o2net_idle_timeout_ms) !=
1287                                 o2net_idle_timeout()) {
1288                 mlog(ML_NOTICE, SC_NODEF_FMT " uses a network idle timeout of "
1289                      "%u ms, but we use %u ms locally.  disconnecting\n",
1290                      SC_NODEF_ARGS(sc),
1291                      be32_to_cpu(hand->o2net_idle_timeout_ms),
1292                      o2net_idle_timeout());
1293                 o2net_ensure_shutdown(nn, sc, -ENOTCONN);
1294                 return -1;
1295         }
1296
1297         if (be32_to_cpu(hand->o2net_keepalive_delay_ms) !=
1298                         o2net_keepalive_delay()) {
1299                 mlog(ML_NOTICE, SC_NODEF_FMT " uses a keepalive delay of "
1300                      "%u ms, but we use %u ms locally.  disconnecting\n",
1301                      SC_NODEF_ARGS(sc),
1302                      be32_to_cpu(hand->o2net_keepalive_delay_ms),
1303                      o2net_keepalive_delay());
1304                 o2net_ensure_shutdown(nn, sc, -ENOTCONN);
1305                 return -1;
1306         }
1307
1308         if (be32_to_cpu(hand->o2hb_heartbeat_timeout_ms) !=
1309                         O2HB_MAX_WRITE_TIMEOUT_MS) {
1310                 mlog(ML_NOTICE, SC_NODEF_FMT " uses a heartbeat timeout of "
1311                      "%u ms, but we use %u ms locally.  disconnecting\n",
1312                      SC_NODEF_ARGS(sc),
1313                      be32_to_cpu(hand->o2hb_heartbeat_timeout_ms),
1314                      O2HB_MAX_WRITE_TIMEOUT_MS);
1315                 o2net_ensure_shutdown(nn, sc, -ENOTCONN);
1316                 return -1;
1317         }
1318
1319         sc->sc_handshake_ok = 1;
1320
1321         spin_lock(&nn->nn_lock);
1322         /* set valid and queue the idle timers only if it hasn't been
1323          * shut down already */
1324         if (nn->nn_sc == sc) {
1325                 o2net_sc_reset_idle_timer(sc);
1326                 atomic_set(&nn->nn_timeout, 0);
1327                 o2net_set_nn_state(nn, sc, 1, 0);
1328         }
1329         spin_unlock(&nn->nn_lock);
1330
1331         /* shift everything up as though it wasn't there */
1332         sc->sc_page_off -= sizeof(struct o2net_handshake);
1333         if (sc->sc_page_off)
1334                 memmove(hand, hand + 1, sc->sc_page_off);
1335
1336         return 0;
1337 }
1338
1339 /* this demuxes the queued rx bytes into header or payload bits and calls
1340  * handlers as each full message is read off the socket.  it returns -error,
1341  * == 0 eof, or > 0 for progress made.*/
1342 static int o2net_advance_rx(struct o2net_sock_container *sc)
1343 {
1344         struct o2net_msg *hdr;
1345         int ret = 0;
1346         void *data;
1347         size_t datalen;
1348
1349         sclog(sc, "receiving\n");
1350         o2net_set_advance_start_time(sc);
1351
1352         if (unlikely(sc->sc_handshake_ok == 0)) {
1353                 if(sc->sc_page_off < sizeof(struct o2net_handshake)) {
1354                         data = page_address(sc->sc_page) + sc->sc_page_off;
1355                         datalen = sizeof(struct o2net_handshake) - sc->sc_page_off;
1356                         ret = o2net_recv_tcp_msg(sc->sc_sock, data, datalen);
1357                         if (ret > 0)
1358                                 sc->sc_page_off += ret;
1359                 }
1360
1361                 if (sc->sc_page_off == sizeof(struct o2net_handshake)) {
1362                         o2net_check_handshake(sc);
1363                         if (unlikely(sc->sc_handshake_ok == 0))
1364                                 ret = -EPROTO;
1365                 }
1366                 goto out;
1367         }
1368
1369         /* do we need more header? */
1370         if (sc->sc_page_off < sizeof(struct o2net_msg)) {
1371                 data = page_address(sc->sc_page) + sc->sc_page_off;
1372                 datalen = sizeof(struct o2net_msg) - sc->sc_page_off;
1373                 ret = o2net_recv_tcp_msg(sc->sc_sock, data, datalen);
1374                 if (ret > 0) {
1375                         sc->sc_page_off += ret;
1376                         /* only swab incoming here.. we can
1377                          * only get here once as we cross from
1378                          * being under to over */
1379                         if (sc->sc_page_off == sizeof(struct o2net_msg)) {
1380                                 hdr = page_address(sc->sc_page);
1381                                 if (be16_to_cpu(hdr->data_len) >
1382                                     O2NET_MAX_PAYLOAD_BYTES)
1383                                         ret = -EOVERFLOW;
1384                         }
1385                 }
1386                 if (ret <= 0)
1387                         goto out;
1388         }
1389
1390         if (sc->sc_page_off < sizeof(struct o2net_msg)) {
1391                 /* oof, still don't have a header */
1392                 goto out;
1393         }
1394
1395         /* this was swabbed above when we first read it */
1396         hdr = page_address(sc->sc_page);
1397
1398         msglog(hdr, "at page_off %zu\n", sc->sc_page_off);
1399
1400         /* do we need more payload? */
1401         if (sc->sc_page_off - sizeof(struct o2net_msg) < be16_to_cpu(hdr->data_len)) {
1402                 /* need more payload */
1403                 data = page_address(sc->sc_page) + sc->sc_page_off;
1404                 datalen = (sizeof(struct o2net_msg) + be16_to_cpu(hdr->data_len)) -
1405                           sc->sc_page_off;
1406                 ret = o2net_recv_tcp_msg(sc->sc_sock, data, datalen);
1407                 if (ret > 0)
1408                         sc->sc_page_off += ret;
1409                 if (ret <= 0)
1410                         goto out;
1411         }
1412
1413         if (sc->sc_page_off - sizeof(struct o2net_msg) == be16_to_cpu(hdr->data_len)) {
1414                 /* we can only get here once, the first time we read
1415                  * the payload.. so set ret to progress if the handler
1416                  * works out. after calling this the message is toast */
1417                 ret = o2net_process_message(sc, hdr);
1418                 if (ret == 0)
1419                         ret = 1;
1420                 sc->sc_page_off = 0;
1421         }
1422
1423 out:
1424         sclog(sc, "ret = %d\n", ret);
1425         o2net_set_advance_stop_time(sc);
1426         return ret;
1427 }
1428
1429 /* this work func is triggerd by data ready.  it reads until it can read no
1430  * more.  it interprets 0, eof, as fatal.  if data_ready hits while we're doing
1431  * our work the work struct will be marked and we'll be called again. */
1432 static void o2net_rx_until_empty(struct work_struct *work)
1433 {
1434         struct o2net_sock_container *sc =
1435                 container_of(work, struct o2net_sock_container, sc_rx_work);
1436         int ret;
1437
1438         do {
1439                 ret = o2net_advance_rx(sc);
1440         } while (ret > 0);
1441
1442         if (ret <= 0 && ret != -EAGAIN) {
1443                 struct o2net_node *nn = o2net_nn_from_num(sc->sc_node->nd_num);
1444                 sclog(sc, "saw error %d, closing\n", ret);
1445                 /* not permanent so read failed handshake can retry */
1446                 o2net_ensure_shutdown(nn, sc, 0);
1447         }
1448
1449         sc_put(sc);
1450 }
1451
1452 static int o2net_set_nodelay(struct socket *sock)
1453 {
1454         int ret, val = 1;
1455         mm_segment_t oldfs;
1456
1457         oldfs = get_fs();
1458         set_fs(KERNEL_DS);
1459
1460         /*
1461          * Dear unsuspecting programmer,
1462          *
1463          * Don't use sock_setsockopt() for SOL_TCP.  It doesn't check its level
1464          * argument and assumes SOL_SOCKET so, say, your TCP_NODELAY will
1465          * silently turn into SO_DEBUG.
1466          *
1467          * Yours,
1468          * Keeper of hilariously fragile interfaces.
1469          */
1470         ret = sock->ops->setsockopt(sock, SOL_TCP, TCP_NODELAY,
1471                                     (char __user *)&val, sizeof(val));
1472
1473         set_fs(oldfs);
1474         return ret;
1475 }
1476
1477 static void o2net_initialize_handshake(void)
1478 {
1479         o2net_hand->o2hb_heartbeat_timeout_ms = cpu_to_be32(
1480                 O2HB_MAX_WRITE_TIMEOUT_MS);
1481         o2net_hand->o2net_idle_timeout_ms = cpu_to_be32(o2net_idle_timeout());
1482         o2net_hand->o2net_keepalive_delay_ms = cpu_to_be32(
1483                 o2net_keepalive_delay());
1484         o2net_hand->o2net_reconnect_delay_ms = cpu_to_be32(
1485                 o2net_reconnect_delay());
1486 }
1487
1488 /* ------------------------------------------------------------ */
1489
1490 /* called when a connect completes and after a sock is accepted.  the
1491  * rx path will see the response and mark the sc valid */
1492 static void o2net_sc_connect_completed(struct work_struct *work)
1493 {
1494         struct o2net_sock_container *sc =
1495                 container_of(work, struct o2net_sock_container,
1496                              sc_connect_work);
1497
1498         mlog(ML_MSG, "sc sending handshake with ver %llu id %llx\n",
1499               (unsigned long long)O2NET_PROTOCOL_VERSION,
1500               (unsigned long long)be64_to_cpu(o2net_hand->connector_id));
1501
1502         o2net_initialize_handshake();
1503         o2net_sendpage(sc, o2net_hand, sizeof(*o2net_hand));
1504         sc_put(sc);
1505 }
1506
1507 /* this is called as a work_struct func. */
1508 static void o2net_sc_send_keep_req(struct work_struct *work)
1509 {
1510         struct o2net_sock_container *sc =
1511                 container_of(work, struct o2net_sock_container,
1512                              sc_keepalive_work.work);
1513
1514         o2net_sendpage(sc, o2net_keep_req, sizeof(*o2net_keep_req));
1515         sc_put(sc);
1516 }
1517
1518 /* socket shutdown does a del_timer_sync against this as it tears down.
1519  * we can't start this timer until we've got to the point in sc buildup
1520  * where shutdown is going to be involved */
1521 static void o2net_idle_timer(unsigned long data)
1522 {
1523         struct o2net_sock_container *sc = (struct o2net_sock_container *)data;
1524         struct o2net_node *nn = o2net_nn_from_num(sc->sc_node->nd_num);
1525
1526 #ifdef CONFIG_DEBUG_FS
1527         ktime_t now = ktime_get();
1528 #endif
1529
1530         printk(KERN_NOTICE "o2net: connection to " SC_NODEF_FMT " has been idle for %u.%u "
1531              "seconds, shutting it down.\n", SC_NODEF_ARGS(sc),
1532                      o2net_idle_timeout() / 1000,
1533                      o2net_idle_timeout() % 1000);
1534
1535 #ifdef CONFIG_DEBUG_FS
1536         mlog(ML_NOTICE, "Here are some times that might help debug the "
1537              "situation: (Timer: %lld, Now %lld, DataReady %lld, Advance %lld-%lld, "
1538              "Key 0x%08x, Func %u, FuncTime %lld-%lld)\n",
1539              (long long)ktime_to_us(sc->sc_tv_timer), (long long)ktime_to_us(now),
1540              (long long)ktime_to_us(sc->sc_tv_data_ready),
1541              (long long)ktime_to_us(sc->sc_tv_advance_start),
1542              (long long)ktime_to_us(sc->sc_tv_advance_stop),
1543              sc->sc_msg_key, sc->sc_msg_type,
1544              (long long)ktime_to_us(sc->sc_tv_func_start),
1545              (long long)ktime_to_us(sc->sc_tv_func_stop));
1546 #endif
1547
1548         /*
1549          * Initialize the nn_timeout so that the next connection attempt
1550          * will continue in o2net_start_connect.
1551          */
1552         atomic_set(&nn->nn_timeout, 1);
1553
1554         o2net_sc_queue_work(sc, &sc->sc_shutdown_work);
1555 }
1556
1557 static void o2net_sc_reset_idle_timer(struct o2net_sock_container *sc)
1558 {
1559         o2net_sc_cancel_delayed_work(sc, &sc->sc_keepalive_work);
1560         o2net_sc_queue_delayed_work(sc, &sc->sc_keepalive_work,
1561                       msecs_to_jiffies(o2net_keepalive_delay()));
1562         o2net_set_sock_timer(sc);
1563         mod_timer(&sc->sc_idle_timeout,
1564                jiffies + msecs_to_jiffies(o2net_idle_timeout()));
1565 }
1566
1567 static void o2net_sc_postpone_idle(struct o2net_sock_container *sc)
1568 {
1569         /* Only push out an existing timer */
1570         if (timer_pending(&sc->sc_idle_timeout))
1571                 o2net_sc_reset_idle_timer(sc);
1572 }
1573
1574 /* this work func is kicked whenever a path sets the nn state which doesn't
1575  * have valid set.  This includes seeing hb come up, losing a connection,
1576  * having a connect attempt fail, etc. This centralizes the logic which decides
1577  * if a connect attempt should be made or if we should give up and all future
1578  * transmit attempts should fail */
1579 static void o2net_start_connect(struct work_struct *work)
1580 {
1581         struct o2net_node *nn =
1582                 container_of(work, struct o2net_node, nn_connect_work.work);
1583         struct o2net_sock_container *sc = NULL;
1584         struct o2nm_node *node = NULL, *mynode = NULL;
1585         struct socket *sock = NULL;
1586         struct sockaddr_in myaddr = {0, }, remoteaddr = {0, };
1587         int ret = 0, stop;
1588         unsigned int timeout;
1589
1590         /* if we're greater we initiate tx, otherwise we accept */
1591         if (o2nm_this_node() <= o2net_num_from_nn(nn))
1592                 goto out;
1593
1594         /* watch for racing with tearing a node down */
1595         node = o2nm_get_node_by_num(o2net_num_from_nn(nn));
1596         if (node == NULL) {
1597                 ret = 0;
1598                 goto out;
1599         }
1600
1601         mynode = o2nm_get_node_by_num(o2nm_this_node());
1602         if (mynode == NULL) {
1603                 ret = 0;
1604                 goto out;
1605         }
1606
1607         spin_lock(&nn->nn_lock);
1608         /*
1609          * see if we already have one pending or have given up.
1610          * For nn_timeout, it is set when we close the connection
1611          * because of the idle time out. So it means that we have
1612          * at least connected to that node successfully once,
1613          * now try to connect to it again.
1614          */
1615         timeout = atomic_read(&nn->nn_timeout);
1616         stop = (nn->nn_sc ||
1617                 (nn->nn_persistent_error &&
1618                 (nn->nn_persistent_error != -ENOTCONN || timeout == 0)));
1619         spin_unlock(&nn->nn_lock);
1620         if (stop)
1621                 goto out;
1622
1623         nn->nn_last_connect_attempt = jiffies;
1624
1625         sc = sc_alloc(node);
1626         if (sc == NULL) {
1627                 mlog(0, "couldn't allocate sc\n");
1628                 ret = -ENOMEM;
1629                 goto out;
1630         }
1631
1632         ret = sock_create(PF_INET, SOCK_STREAM, IPPROTO_TCP, &sock);
1633         if (ret < 0) {
1634                 mlog(0, "can't create socket: %d\n", ret);
1635                 goto out;
1636         }
1637         sc->sc_sock = sock; /* freed by sc_kref_release */
1638
1639         sock->sk->sk_allocation = GFP_ATOMIC;
1640
1641         myaddr.sin_family = AF_INET;
1642         myaddr.sin_addr.s_addr = mynode->nd_ipv4_address;
1643         myaddr.sin_port = htons(0); /* any port */
1644
1645         ret = sock->ops->bind(sock, (struct sockaddr *)&myaddr,
1646                               sizeof(myaddr));
1647         if (ret) {
1648                 mlog(ML_ERROR, "bind failed with %d at address %pI4\n",
1649                      ret, &mynode->nd_ipv4_address);
1650                 goto out;
1651         }
1652
1653         ret = o2net_set_nodelay(sc->sc_sock);
1654         if (ret) {
1655                 mlog(ML_ERROR, "setting TCP_NODELAY failed with %d\n", ret);
1656                 goto out;
1657         }
1658
1659         o2net_register_callbacks(sc->sc_sock->sk, sc);
1660
1661         spin_lock(&nn->nn_lock);
1662         /* handshake completion will set nn->nn_sc_valid */
1663         o2net_set_nn_state(nn, sc, 0, 0);
1664         spin_unlock(&nn->nn_lock);
1665
1666         remoteaddr.sin_family = AF_INET;
1667         remoteaddr.sin_addr.s_addr = node->nd_ipv4_address;
1668         remoteaddr.sin_port = node->nd_ipv4_port;
1669
1670         ret = sc->sc_sock->ops->connect(sc->sc_sock,
1671                                         (struct sockaddr *)&remoteaddr,
1672                                         sizeof(remoteaddr),
1673                                         O_NONBLOCK);
1674         if (ret == -EINPROGRESS)
1675                 ret = 0;
1676
1677 out:
1678         if (ret) {
1679                 mlog(ML_NOTICE, "connect attempt to " SC_NODEF_FMT " failed "
1680                      "with errno %d\n", SC_NODEF_ARGS(sc), ret);
1681                 /* 0 err so that another will be queued and attempted
1682                  * from set_nn_state */
1683                 if (sc)
1684                         o2net_ensure_shutdown(nn, sc, 0);
1685         }
1686         if (sc)
1687                 sc_put(sc);
1688         if (node)
1689                 o2nm_node_put(node);
1690         if (mynode)
1691                 o2nm_node_put(mynode);
1692
1693         return;
1694 }
1695
1696 static void o2net_connect_expired(struct work_struct *work)
1697 {
1698         struct o2net_node *nn =
1699                 container_of(work, struct o2net_node, nn_connect_expired.work);
1700
1701         spin_lock(&nn->nn_lock);
1702         if (!nn->nn_sc_valid) {
1703                 mlog(ML_ERROR, "no connection established with node %u after "
1704                      "%u.%u seconds, giving up and returning errors.\n",
1705                      o2net_num_from_nn(nn),
1706                      o2net_idle_timeout() / 1000,
1707                      o2net_idle_timeout() % 1000);
1708
1709                 o2net_set_nn_state(nn, NULL, 0, -ENOTCONN);
1710         }
1711         spin_unlock(&nn->nn_lock);
1712 }
1713
1714 static void o2net_still_up(struct work_struct *work)
1715 {
1716         struct o2net_node *nn =
1717                 container_of(work, struct o2net_node, nn_still_up.work);
1718
1719         o2quo_hb_still_up(o2net_num_from_nn(nn));
1720 }
1721
1722 /* ------------------------------------------------------------ */
1723
1724 void o2net_disconnect_node(struct o2nm_node *node)
1725 {
1726         struct o2net_node *nn = o2net_nn_from_num(node->nd_num);
1727
1728         /* don't reconnect until it's heartbeating again */
1729         spin_lock(&nn->nn_lock);
1730         atomic_set(&nn->nn_timeout, 0);
1731         o2net_set_nn_state(nn, NULL, 0, -ENOTCONN);
1732         spin_unlock(&nn->nn_lock);
1733
1734         if (o2net_wq) {
1735                 cancel_delayed_work(&nn->nn_connect_expired);
1736                 cancel_delayed_work(&nn->nn_connect_work);
1737                 cancel_delayed_work(&nn->nn_still_up);
1738                 flush_workqueue(o2net_wq);
1739         }
1740 }
1741
1742 static void o2net_hb_node_down_cb(struct o2nm_node *node, int node_num,
1743                                   void *data)
1744 {
1745         o2quo_hb_down(node_num);
1746
1747         if (!node)
1748                 return;
1749
1750         if (node_num != o2nm_this_node())
1751                 o2net_disconnect_node(node);
1752
1753         BUG_ON(atomic_read(&o2net_connected_peers) < 0);
1754 }
1755
1756 static void o2net_hb_node_up_cb(struct o2nm_node *node, int node_num,
1757                                 void *data)
1758 {
1759         struct o2net_node *nn = o2net_nn_from_num(node_num);
1760
1761         o2quo_hb_up(node_num);
1762
1763         BUG_ON(!node);
1764
1765         /* ensure an immediate connect attempt */
1766         nn->nn_last_connect_attempt = jiffies -
1767                 (msecs_to_jiffies(o2net_reconnect_delay()) + 1);
1768
1769         if (node_num != o2nm_this_node()) {
1770                 /* believe it or not, accept and node hearbeating testing
1771                  * can succeed for this node before we got here.. so
1772                  * only use set_nn_state to clear the persistent error
1773                  * if that hasn't already happened */
1774                 spin_lock(&nn->nn_lock);
1775                 atomic_set(&nn->nn_timeout, 0);
1776                 if (nn->nn_persistent_error)
1777                         o2net_set_nn_state(nn, NULL, 0, 0);
1778                 spin_unlock(&nn->nn_lock);
1779         }
1780 }
1781
1782 void o2net_unregister_hb_callbacks(void)
1783 {
1784         o2hb_unregister_callback(NULL, &o2net_hb_up);
1785         o2hb_unregister_callback(NULL, &o2net_hb_down);
1786 }
1787
1788 int o2net_register_hb_callbacks(void)
1789 {
1790         int ret;
1791
1792         o2hb_setup_callback(&o2net_hb_down, O2HB_NODE_DOWN_CB,
1793                             o2net_hb_node_down_cb, NULL, O2NET_HB_PRI);
1794         o2hb_setup_callback(&o2net_hb_up, O2HB_NODE_UP_CB,
1795                             o2net_hb_node_up_cb, NULL, O2NET_HB_PRI);
1796
1797         ret = o2hb_register_callback(NULL, &o2net_hb_up);
1798         if (ret == 0)
1799                 ret = o2hb_register_callback(NULL, &o2net_hb_down);
1800
1801         if (ret)
1802                 o2net_unregister_hb_callbacks();
1803
1804         return ret;
1805 }
1806
1807 /* ------------------------------------------------------------ */
1808
1809 static int o2net_accept_one(struct socket *sock)
1810 {
1811         int ret, slen;
1812         struct sockaddr_in sin;
1813         struct socket *new_sock = NULL;
1814         struct o2nm_node *node = NULL;
1815         struct o2nm_node *local_node = NULL;
1816         struct o2net_sock_container *sc = NULL;
1817         struct o2net_node *nn;
1818
1819         BUG_ON(sock == NULL);
1820         ret = sock_create_lite(sock->sk->sk_family, sock->sk->sk_type,
1821                                sock->sk->sk_protocol, &new_sock);
1822         if (ret)
1823                 goto out;
1824
1825         new_sock->type = sock->type;
1826         new_sock->ops = sock->ops;
1827         ret = sock->ops->accept(sock, new_sock, O_NONBLOCK);
1828         if (ret < 0)
1829                 goto out;
1830
1831         new_sock->sk->sk_allocation = GFP_ATOMIC;
1832
1833         ret = o2net_set_nodelay(new_sock);
1834         if (ret) {
1835                 mlog(ML_ERROR, "setting TCP_NODELAY failed with %d\n", ret);
1836                 goto out;
1837         }
1838
1839         slen = sizeof(sin);
1840         ret = new_sock->ops->getname(new_sock, (struct sockaddr *) &sin,
1841                                        &slen, 1);
1842         if (ret < 0)
1843                 goto out;
1844
1845         node = o2nm_get_node_by_ip(sin.sin_addr.s_addr);
1846         if (node == NULL) {
1847                 mlog(ML_NOTICE, "attempt to connect from unknown node at %pI4:%d\n",
1848                      &sin.sin_addr.s_addr, ntohs(sin.sin_port));
1849                 ret = -EINVAL;
1850                 goto out;
1851         }
1852
1853         if (o2nm_this_node() >= node->nd_num) {
1854                 local_node = o2nm_get_node_by_num(o2nm_this_node());
1855                 mlog(ML_NOTICE, "unexpected connect attempt seen at node '%s' ("
1856                      "%u, %pI4:%d) from node '%s' (%u, %pI4:%d)\n",
1857                      local_node->nd_name, local_node->nd_num,
1858                      &(local_node->nd_ipv4_address),
1859                      ntohs(local_node->nd_ipv4_port),
1860                      node->nd_name, node->nd_num, &sin.sin_addr.s_addr,
1861                      ntohs(sin.sin_port));
1862                 ret = -EINVAL;
1863                 goto out;
1864         }
1865
1866         /* this happens all the time when the other node sees our heartbeat
1867          * and tries to connect before we see their heartbeat */
1868         if (!o2hb_check_node_heartbeating_from_callback(node->nd_num)) {
1869                 mlog(ML_CONN, "attempt to connect from node '%s' at "
1870                      "%pI4:%d but it isn't heartbeating\n",
1871                      node->nd_name, &sin.sin_addr.s_addr,
1872                      ntohs(sin.sin_port));
1873                 ret = -EINVAL;
1874                 goto out;
1875         }
1876
1877         nn = o2net_nn_from_num(node->nd_num);
1878
1879         spin_lock(&nn->nn_lock);
1880         if (nn->nn_sc)
1881                 ret = -EBUSY;
1882         else
1883                 ret = 0;
1884         spin_unlock(&nn->nn_lock);
1885         if (ret) {
1886                 mlog(ML_NOTICE, "attempt to connect from node '%s' at "
1887                      "%pI4:%d but it already has an open connection\n",
1888                      node->nd_name, &sin.sin_addr.s_addr,
1889                      ntohs(sin.sin_port));
1890                 goto out;
1891         }
1892
1893         sc = sc_alloc(node);
1894         if (sc == NULL) {
1895                 ret = -ENOMEM;
1896                 goto out;
1897         }
1898
1899         sc->sc_sock = new_sock;
1900         new_sock = NULL;
1901
1902         spin_lock(&nn->nn_lock);
1903         atomic_set(&nn->nn_timeout, 0);
1904         o2net_set_nn_state(nn, sc, 0, 0);
1905         spin_unlock(&nn->nn_lock);
1906
1907         o2net_register_callbacks(sc->sc_sock->sk, sc);
1908         o2net_sc_queue_work(sc, &sc->sc_rx_work);
1909
1910         o2net_initialize_handshake();
1911         o2net_sendpage(sc, o2net_hand, sizeof(*o2net_hand));
1912
1913 out:
1914         if (new_sock)
1915                 sock_release(new_sock);
1916         if (node)
1917                 o2nm_node_put(node);
1918         if (local_node)
1919                 o2nm_node_put(local_node);
1920         if (sc)
1921                 sc_put(sc);
1922         return ret;
1923 }
1924
1925 static void o2net_accept_many(struct work_struct *work)
1926 {
1927         struct socket *sock = o2net_listen_sock;
1928         while (o2net_accept_one(sock) == 0)
1929                 cond_resched();
1930 }
1931
1932 static void o2net_listen_data_ready(struct sock *sk, int bytes)
1933 {
1934         void (*ready)(struct sock *sk, int bytes);
1935
1936         read_lock(&sk->sk_callback_lock);
1937         ready = sk->sk_user_data;
1938         if (ready == NULL) { /* check for teardown race */
1939                 ready = sk->sk_data_ready;
1940                 goto out;
1941         }
1942
1943         /* ->sk_data_ready is also called for a newly established child socket
1944          * before it has been accepted and the acceptor has set up their
1945          * data_ready.. we only want to queue listen work for our listening
1946          * socket */
1947         if (sk->sk_state == TCP_LISTEN) {
1948                 mlog(ML_TCP, "bytes: %d\n", bytes);
1949                 queue_work(o2net_wq, &o2net_listen_work);
1950         }
1951
1952 out:
1953         read_unlock(&sk->sk_callback_lock);
1954         ready(sk, bytes);
1955 }
1956
1957 static int o2net_open_listening_sock(__be32 addr, __be16 port)
1958 {
1959         struct socket *sock = NULL;
1960         int ret;
1961         struct sockaddr_in sin = {
1962                 .sin_family = PF_INET,
1963                 .sin_addr = { .s_addr = addr },
1964                 .sin_port = port,
1965         };
1966
1967         ret = sock_create(PF_INET, SOCK_STREAM, IPPROTO_TCP, &sock);
1968         if (ret < 0) {
1969                 mlog(ML_ERROR, "unable to create socket, ret=%d\n", ret);
1970                 goto out;
1971         }
1972
1973         sock->sk->sk_allocation = GFP_ATOMIC;
1974
1975         write_lock_bh(&sock->sk->sk_callback_lock);
1976         sock->sk->sk_user_data = sock->sk->sk_data_ready;
1977         sock->sk->sk_data_ready = o2net_listen_data_ready;
1978         write_unlock_bh(&sock->sk->sk_callback_lock);
1979
1980         o2net_listen_sock = sock;
1981         INIT_WORK(&o2net_listen_work, o2net_accept_many);
1982
1983         sock->sk->sk_reuse = 1;
1984         ret = sock->ops->bind(sock, (struct sockaddr *)&sin, sizeof(sin));
1985         if (ret < 0) {
1986                 mlog(ML_ERROR, "unable to bind socket at %pI4:%u, "
1987                      "ret=%d\n", &addr, ntohs(port), ret);
1988                 goto out;
1989         }
1990
1991         ret = sock->ops->listen(sock, 64);
1992         if (ret < 0) {
1993                 mlog(ML_ERROR, "unable to listen on %pI4:%u, ret=%d\n",
1994                      &addr, ntohs(port), ret);
1995         }
1996
1997 out:
1998         if (ret) {
1999                 o2net_listen_sock = NULL;
2000                 if (sock)
2001                         sock_release(sock);
2002         }
2003         return ret;
2004 }
2005
2006 /*
2007  * called from node manager when we should bring up our network listening
2008  * socket.  node manager handles all the serialization to only call this
2009  * once and to match it with o2net_stop_listening().  note,
2010  * o2nm_this_node() doesn't work yet as we're being called while it
2011  * is being set up.
2012  */
2013 int o2net_start_listening(struct o2nm_node *node)
2014 {
2015         int ret = 0;
2016
2017         BUG_ON(o2net_wq != NULL);
2018         BUG_ON(o2net_listen_sock != NULL);
2019
2020         mlog(ML_KTHREAD, "starting o2net thread...\n");
2021         o2net_wq = create_singlethread_workqueue("o2net");
2022         if (o2net_wq == NULL) {
2023                 mlog(ML_ERROR, "unable to launch o2net thread\n");
2024                 return -ENOMEM; /* ? */
2025         }
2026
2027         ret = o2net_open_listening_sock(node->nd_ipv4_address,
2028                                         node->nd_ipv4_port);
2029         if (ret) {
2030                 destroy_workqueue(o2net_wq);
2031                 o2net_wq = NULL;
2032         } else
2033                 o2quo_conn_up(node->nd_num);
2034
2035         return ret;
2036 }
2037
2038 /* again, o2nm_this_node() doesn't work here as we're involved in
2039  * tearing it down */
2040 void o2net_stop_listening(struct o2nm_node *node)
2041 {
2042         struct socket *sock = o2net_listen_sock;
2043         size_t i;
2044
2045         BUG_ON(o2net_wq == NULL);
2046         BUG_ON(o2net_listen_sock == NULL);
2047
2048         /* stop the listening socket from generating work */
2049         write_lock_bh(&sock->sk->sk_callback_lock);
2050         sock->sk->sk_data_ready = sock->sk->sk_user_data;
2051         sock->sk->sk_user_data = NULL;
2052         write_unlock_bh(&sock->sk->sk_callback_lock);
2053
2054         for (i = 0; i < ARRAY_SIZE(o2net_nodes); i++) {
2055                 struct o2nm_node *node = o2nm_get_node_by_num(i);
2056                 if (node) {
2057                         o2net_disconnect_node(node);
2058                         o2nm_node_put(node);
2059                 }
2060         }
2061
2062         /* finish all work and tear down the work queue */
2063         mlog(ML_KTHREAD, "waiting for o2net thread to exit....\n");
2064         destroy_workqueue(o2net_wq);
2065         o2net_wq = NULL;
2066
2067         sock_release(o2net_listen_sock);
2068         o2net_listen_sock = NULL;
2069
2070         o2quo_conn_err(node->nd_num);
2071 }
2072
2073 /* ------------------------------------------------------------ */
2074
2075 int o2net_init(void)
2076 {
2077         unsigned long i;
2078
2079         o2quo_init();
2080
2081         if (o2net_debugfs_init())
2082                 return -ENOMEM;
2083
2084         o2net_hand = kzalloc(sizeof(struct o2net_handshake), GFP_KERNEL);
2085         o2net_keep_req = kzalloc(sizeof(struct o2net_msg), GFP_KERNEL);
2086         o2net_keep_resp = kzalloc(sizeof(struct o2net_msg), GFP_KERNEL);
2087         if (!o2net_hand || !o2net_keep_req || !o2net_keep_resp) {
2088                 kfree(o2net_hand);
2089                 kfree(o2net_keep_req);
2090                 kfree(o2net_keep_resp);
2091                 return -ENOMEM;
2092         }
2093
2094         o2net_hand->protocol_version = cpu_to_be64(O2NET_PROTOCOL_VERSION);
2095         o2net_hand->connector_id = cpu_to_be64(1);
2096
2097         o2net_keep_req->magic = cpu_to_be16(O2NET_MSG_KEEP_REQ_MAGIC);
2098         o2net_keep_resp->magic = cpu_to_be16(O2NET_MSG_KEEP_RESP_MAGIC);
2099
2100         for (i = 0; i < ARRAY_SIZE(o2net_nodes); i++) {
2101                 struct o2net_node *nn = o2net_nn_from_num(i);
2102
2103                 atomic_set(&nn->nn_timeout, 0);
2104                 spin_lock_init(&nn->nn_lock);
2105                 INIT_DELAYED_WORK(&nn->nn_connect_work, o2net_start_connect);
2106                 INIT_DELAYED_WORK(&nn->nn_connect_expired,
2107                                   o2net_connect_expired);
2108                 INIT_DELAYED_WORK(&nn->nn_still_up, o2net_still_up);
2109                 /* until we see hb from a node we'll return einval */
2110                 nn->nn_persistent_error = -ENOTCONN;
2111                 init_waitqueue_head(&nn->nn_sc_wq);
2112                 idr_init(&nn->nn_status_idr);
2113                 INIT_LIST_HEAD(&nn->nn_status_list);
2114         }
2115
2116         return 0;
2117 }
2118
2119 void o2net_exit(void)
2120 {
2121         o2quo_exit();
2122         kfree(o2net_hand);
2123         kfree(o2net_keep_req);
2124         kfree(o2net_keep_resp);
2125         o2net_debugfs_exit();
2126 }