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