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