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