[POWERPC] Export copy_4K_page()
[wrt350n-kernel.git] / fs / ocfs2 / cluster / tcp.c
blobb650efa8c8bebd01991f43284287fdfaa49d1f41
1 /* -*- mode: c; c-basic-offset: 8; -*-
3 * vim: noexpandtab sw=8 ts=8 sts=0:
5 * Copyright (C) 2004 Oracle. All rights reserved.
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.
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.
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.
22 * ----
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.
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.
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.
41 * Any framing errors (bad magic, large payload lengths) close a connection.
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.
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.
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 <net/tcp.h>
63 #include <asm/uaccess.h>
65 #include "heartbeat.h"
66 #include "tcp.h"
67 #include "nodemanager.h"
68 #define MLOG_MASK_PREFIX ML_TCP
69 #include "masklog.h"
70 #include "quorum.h"
72 #include "tcp_internal.h"
74 /*
75 * The linux network stack isn't sparse endian clean.. It has macros like
76 * ntohs() which perform the endian checks and structs like sockaddr_in
77 * which aren't annotated. So __force is found here to get the build
78 * clean. When they emerge from the dark ages and annotate the code
79 * we can remove these.
82 #define SC_NODEF_FMT "node %s (num %u) at %u.%u.%u.%u:%u"
83 #define SC_NODEF_ARGS(sc) sc->sc_node->nd_name, sc->sc_node->nd_num, \
84 NIPQUAD(sc->sc_node->nd_ipv4_address), \
85 ntohs(sc->sc_node->nd_ipv4_port)
88 * In the following two log macros, the whitespace after the ',' just
89 * before ##args is intentional. Otherwise, gcc 2.95 will eat the
90 * previous token if args expands to nothing.
92 #define msglog(hdr, fmt, args...) do { \
93 typeof(hdr) __hdr = (hdr); \
94 mlog(ML_MSG, "[mag %u len %u typ %u stat %d sys_stat %d " \
95 "key %08x num %u] " fmt, \
96 be16_to_cpu(__hdr->magic), be16_to_cpu(__hdr->data_len), \
97 be16_to_cpu(__hdr->msg_type), be32_to_cpu(__hdr->status), \
98 be32_to_cpu(__hdr->sys_status), be32_to_cpu(__hdr->key), \
99 be32_to_cpu(__hdr->msg_num) , ##args); \
100 } while (0)
102 #define sclog(sc, fmt, args...) do { \
103 typeof(sc) __sc = (sc); \
104 mlog(ML_SOCKET, "[sc %p refs %d sock %p node %u page %p " \
105 "pg_off %zu] " fmt, __sc, \
106 atomic_read(&__sc->sc_kref.refcount), __sc->sc_sock, \
107 __sc->sc_node->nd_num, __sc->sc_page, __sc->sc_page_off , \
108 ##args); \
109 } while (0)
111 static DEFINE_RWLOCK(o2net_handler_lock);
112 static struct rb_root o2net_handler_tree = RB_ROOT;
114 static struct o2net_node o2net_nodes[O2NM_MAX_NODES];
116 /* XXX someday we'll need better accounting */
117 static struct socket *o2net_listen_sock = NULL;
120 * listen work is only queued by the listening socket callbacks on the
121 * o2net_wq. teardown detaches the callbacks before destroying the workqueue.
122 * quorum work is queued as sock containers are shutdown.. stop_listening
123 * tears down all the node's sock containers, preventing future shutdowns
124 * and queued quroum work, before canceling delayed quorum work and
125 * destroying the work queue.
127 static struct workqueue_struct *o2net_wq;
128 static struct work_struct o2net_listen_work;
130 static struct o2hb_callback_func o2net_hb_up, o2net_hb_down;
131 #define O2NET_HB_PRI 0x1
133 static struct o2net_handshake *o2net_hand;
134 static struct o2net_msg *o2net_keep_req, *o2net_keep_resp;
136 static int o2net_sys_err_translations[O2NET_ERR_MAX] =
137 {[O2NET_ERR_NONE] = 0,
138 [O2NET_ERR_NO_HNDLR] = -ENOPROTOOPT,
139 [O2NET_ERR_OVERFLOW] = -EOVERFLOW,
140 [O2NET_ERR_DIED] = -EHOSTDOWN,};
142 /* can't quite avoid *all* internal declarations :/ */
143 static void o2net_sc_connect_completed(void *arg);
144 static void o2net_rx_until_empty(void *arg);
145 static void o2net_shutdown_sc(void *arg);
146 static void o2net_listen_data_ready(struct sock *sk, int bytes);
147 static void o2net_sc_send_keep_req(void *arg);
148 static void o2net_idle_timer(unsigned long data);
149 static void o2net_sc_postpone_idle(struct o2net_sock_container *sc);
151 static inline int o2net_sys_err_to_errno(enum o2net_system_error err)
153 int trans;
154 BUG_ON(err >= O2NET_ERR_MAX);
155 trans = o2net_sys_err_translations[err];
157 /* Just in case we mess up the translation table above */
158 BUG_ON(err != O2NET_ERR_NONE && trans == 0);
159 return trans;
162 static struct o2net_node * o2net_nn_from_num(u8 node_num)
164 BUG_ON(node_num >= ARRAY_SIZE(o2net_nodes));
165 return &o2net_nodes[node_num];
168 static u8 o2net_num_from_nn(struct o2net_node *nn)
170 BUG_ON(nn == NULL);
171 return nn - o2net_nodes;
174 /* ------------------------------------------------------------ */
176 static int o2net_prep_nsw(struct o2net_node *nn, struct o2net_status_wait *nsw)
178 int ret = 0;
180 do {
181 if (!idr_pre_get(&nn->nn_status_idr, GFP_ATOMIC)) {
182 ret = -EAGAIN;
183 break;
185 spin_lock(&nn->nn_lock);
186 ret = idr_get_new(&nn->nn_status_idr, nsw, &nsw->ns_id);
187 if (ret == 0)
188 list_add_tail(&nsw->ns_node_item,
189 &nn->nn_status_list);
190 spin_unlock(&nn->nn_lock);
191 } while (ret == -EAGAIN);
193 if (ret == 0) {
194 init_waitqueue_head(&nsw->ns_wq);
195 nsw->ns_sys_status = O2NET_ERR_NONE;
196 nsw->ns_status = 0;
199 return ret;
202 static void o2net_complete_nsw_locked(struct o2net_node *nn,
203 struct o2net_status_wait *nsw,
204 enum o2net_system_error sys_status,
205 s32 status)
207 assert_spin_locked(&nn->nn_lock);
209 if (!list_empty(&nsw->ns_node_item)) {
210 list_del_init(&nsw->ns_node_item);
211 nsw->ns_sys_status = sys_status;
212 nsw->ns_status = status;
213 idr_remove(&nn->nn_status_idr, nsw->ns_id);
214 wake_up(&nsw->ns_wq);
218 static void o2net_complete_nsw(struct o2net_node *nn,
219 struct o2net_status_wait *nsw,
220 u64 id, enum o2net_system_error sys_status,
221 s32 status)
223 spin_lock(&nn->nn_lock);
224 if (nsw == NULL) {
225 if (id > INT_MAX)
226 goto out;
228 nsw = idr_find(&nn->nn_status_idr, id);
229 if (nsw == NULL)
230 goto out;
233 o2net_complete_nsw_locked(nn, nsw, sys_status, status);
235 out:
236 spin_unlock(&nn->nn_lock);
237 return;
240 static void o2net_complete_nodes_nsw(struct o2net_node *nn)
242 struct list_head *iter, *tmp;
243 unsigned int num_kills = 0;
244 struct o2net_status_wait *nsw;
246 assert_spin_locked(&nn->nn_lock);
248 list_for_each_safe(iter, tmp, &nn->nn_status_list) {
249 nsw = list_entry(iter, struct o2net_status_wait, ns_node_item);
250 o2net_complete_nsw_locked(nn, nsw, O2NET_ERR_DIED, 0);
251 num_kills++;
254 mlog(0, "completed %d messages for node %u\n", num_kills,
255 o2net_num_from_nn(nn));
258 static int o2net_nsw_completed(struct o2net_node *nn,
259 struct o2net_status_wait *nsw)
261 int completed;
262 spin_lock(&nn->nn_lock);
263 completed = list_empty(&nsw->ns_node_item);
264 spin_unlock(&nn->nn_lock);
265 return completed;
268 /* ------------------------------------------------------------ */
270 static void sc_kref_release(struct kref *kref)
272 struct o2net_sock_container *sc = container_of(kref,
273 struct o2net_sock_container, sc_kref);
274 sclog(sc, "releasing\n");
276 if (sc->sc_sock) {
277 sock_release(sc->sc_sock);
278 sc->sc_sock = NULL;
281 o2nm_node_put(sc->sc_node);
282 sc->sc_node = NULL;
284 kfree(sc);
287 static void sc_put(struct o2net_sock_container *sc)
289 sclog(sc, "put\n");
290 kref_put(&sc->sc_kref, sc_kref_release);
292 static void sc_get(struct o2net_sock_container *sc)
294 sclog(sc, "get\n");
295 kref_get(&sc->sc_kref);
297 static struct o2net_sock_container *sc_alloc(struct o2nm_node *node)
299 struct o2net_sock_container *sc, *ret = NULL;
300 struct page *page = NULL;
302 page = alloc_page(GFP_NOFS);
303 sc = kcalloc(1, sizeof(*sc), GFP_NOFS);
304 if (sc == NULL || page == NULL)
305 goto out;
307 kref_init(&sc->sc_kref);
308 o2nm_node_get(node);
309 sc->sc_node = node;
311 INIT_WORK(&sc->sc_connect_work, o2net_sc_connect_completed, sc);
312 INIT_WORK(&sc->sc_rx_work, o2net_rx_until_empty, sc);
313 INIT_WORK(&sc->sc_shutdown_work, o2net_shutdown_sc, sc);
314 INIT_WORK(&sc->sc_keepalive_work, o2net_sc_send_keep_req, sc);
316 init_timer(&sc->sc_idle_timeout);
317 sc->sc_idle_timeout.function = o2net_idle_timer;
318 sc->sc_idle_timeout.data = (unsigned long)sc;
320 sclog(sc, "alloced\n");
322 ret = sc;
323 sc->sc_page = page;
324 sc = NULL;
325 page = NULL;
327 out:
328 if (page)
329 __free_page(page);
330 kfree(sc);
332 return ret;
335 /* ------------------------------------------------------------ */
337 static void o2net_sc_queue_work(struct o2net_sock_container *sc,
338 struct work_struct *work)
340 sc_get(sc);
341 if (!queue_work(o2net_wq, work))
342 sc_put(sc);
344 static void o2net_sc_queue_delayed_work(struct o2net_sock_container *sc,
345 struct work_struct *work,
346 int delay)
348 sc_get(sc);
349 if (!queue_delayed_work(o2net_wq, work, delay))
350 sc_put(sc);
352 static void o2net_sc_cancel_delayed_work(struct o2net_sock_container *sc,
353 struct work_struct *work)
355 if (cancel_delayed_work(work))
356 sc_put(sc);
359 static void o2net_set_nn_state(struct o2net_node *nn,
360 struct o2net_sock_container *sc,
361 unsigned valid, int err)
363 int was_valid = nn->nn_sc_valid;
364 int was_err = nn->nn_persistent_error;
365 struct o2net_sock_container *old_sc = nn->nn_sc;
367 assert_spin_locked(&nn->nn_lock);
369 /* the node num comparison and single connect/accept path should stop
370 * an non-null sc from being overwritten with another */
371 BUG_ON(sc && nn->nn_sc && nn->nn_sc != sc);
372 mlog_bug_on_msg(err && valid, "err %d valid %u\n", err, valid);
373 mlog_bug_on_msg(valid && !sc, "valid %u sc %p\n", valid, sc);
375 /* we won't reconnect after our valid conn goes away for
376 * this hb iteration.. here so it shows up in the logs */
377 if (was_valid && !valid && err == 0)
378 err = -ENOTCONN;
380 mlog(ML_CONN, "node %u sc: %p -> %p, valid %u -> %u, err %d -> %d\n",
381 o2net_num_from_nn(nn), nn->nn_sc, sc, nn->nn_sc_valid, valid,
382 nn->nn_persistent_error, err);
384 nn->nn_sc = sc;
385 nn->nn_sc_valid = valid ? 1 : 0;
386 nn->nn_persistent_error = err;
388 /* mirrors o2net_tx_can_proceed() */
389 if (nn->nn_persistent_error || nn->nn_sc_valid)
390 wake_up(&nn->nn_sc_wq);
392 if (!was_err && nn->nn_persistent_error) {
393 o2quo_conn_err(o2net_num_from_nn(nn));
394 queue_delayed_work(o2net_wq, &nn->nn_still_up,
395 msecs_to_jiffies(O2NET_QUORUM_DELAY_MS));
398 if (was_valid && !valid) {
399 printk(KERN_INFO "o2net: no longer connected to "
400 SC_NODEF_FMT "\n", SC_NODEF_ARGS(old_sc));
401 o2net_complete_nodes_nsw(nn);
404 if (!was_valid && valid) {
405 o2quo_conn_up(o2net_num_from_nn(nn));
406 /* this is a bit of a hack. we only try reconnecting
407 * when heartbeating starts until we get a connection.
408 * if that connection then dies we don't try reconnecting.
409 * the only way to start connecting again is to down
410 * heartbeat and bring it back up. */
411 cancel_delayed_work(&nn->nn_connect_expired);
412 printk(KERN_INFO "o2net: %s " SC_NODEF_FMT "\n",
413 o2nm_this_node() > sc->sc_node->nd_num ?
414 "connected to" : "accepted connection from",
415 SC_NODEF_ARGS(sc));
418 /* trigger the connecting worker func as long as we're not valid,
419 * it will back off if it shouldn't connect. This can be called
420 * from node config teardown and so needs to be careful about
421 * the work queue actually being up. */
422 if (!valid && o2net_wq) {
423 unsigned long delay;
424 /* delay if we're withing a RECONNECT_DELAY of the
425 * last attempt */
426 delay = (nn->nn_last_connect_attempt +
427 msecs_to_jiffies(O2NET_RECONNECT_DELAY_MS))
428 - jiffies;
429 if (delay > msecs_to_jiffies(O2NET_RECONNECT_DELAY_MS))
430 delay = 0;
431 mlog(ML_CONN, "queueing conn attempt in %lu jiffies\n", delay);
432 queue_delayed_work(o2net_wq, &nn->nn_connect_work, delay);
435 /* keep track of the nn's sc ref for the caller */
436 if ((old_sc == NULL) && sc)
437 sc_get(sc);
438 if (old_sc && (old_sc != sc)) {
439 o2net_sc_queue_work(old_sc, &old_sc->sc_shutdown_work);
440 sc_put(old_sc);
444 /* see o2net_register_callbacks() */
445 static void o2net_data_ready(struct sock *sk, int bytes)
447 void (*ready)(struct sock *sk, int bytes);
449 read_lock(&sk->sk_callback_lock);
450 if (sk->sk_user_data) {
451 struct o2net_sock_container *sc = sk->sk_user_data;
452 sclog(sc, "data_ready hit\n");
453 do_gettimeofday(&sc->sc_tv_data_ready);
454 o2net_sc_queue_work(sc, &sc->sc_rx_work);
455 ready = sc->sc_data_ready;
456 } else {
457 ready = sk->sk_data_ready;
459 read_unlock(&sk->sk_callback_lock);
461 ready(sk, bytes);
464 /* see o2net_register_callbacks() */
465 static void o2net_state_change(struct sock *sk)
467 void (*state_change)(struct sock *sk);
468 struct o2net_sock_container *sc;
470 read_lock(&sk->sk_callback_lock);
471 sc = sk->sk_user_data;
472 if (sc == NULL) {
473 state_change = sk->sk_state_change;
474 goto out;
477 sclog(sc, "state_change to %d\n", sk->sk_state);
479 state_change = sc->sc_state_change;
481 switch(sk->sk_state) {
482 /* ignore connecting sockets as they make progress */
483 case TCP_SYN_SENT:
484 case TCP_SYN_RECV:
485 break;
486 case TCP_ESTABLISHED:
487 o2net_sc_queue_work(sc, &sc->sc_connect_work);
488 break;
489 default:
490 o2net_sc_queue_work(sc, &sc->sc_shutdown_work);
491 break;
493 out:
494 read_unlock(&sk->sk_callback_lock);
495 state_change(sk);
499 * we register callbacks so we can queue work on events before calling
500 * the original callbacks. our callbacks our careful to test user_data
501 * to discover when they've reaced with o2net_unregister_callbacks().
503 static void o2net_register_callbacks(struct sock *sk,
504 struct o2net_sock_container *sc)
506 write_lock_bh(&sk->sk_callback_lock);
508 /* accepted sockets inherit the old listen socket data ready */
509 if (sk->sk_data_ready == o2net_listen_data_ready) {
510 sk->sk_data_ready = sk->sk_user_data;
511 sk->sk_user_data = NULL;
514 BUG_ON(sk->sk_user_data != NULL);
515 sk->sk_user_data = sc;
516 sc_get(sc);
518 sc->sc_data_ready = sk->sk_data_ready;
519 sc->sc_state_change = sk->sk_state_change;
520 sk->sk_data_ready = o2net_data_ready;
521 sk->sk_state_change = o2net_state_change;
523 write_unlock_bh(&sk->sk_callback_lock);
526 static int o2net_unregister_callbacks(struct sock *sk,
527 struct o2net_sock_container *sc)
529 int ret = 0;
531 write_lock_bh(&sk->sk_callback_lock);
532 if (sk->sk_user_data == sc) {
533 ret = 1;
534 sk->sk_user_data = NULL;
535 sk->sk_data_ready = sc->sc_data_ready;
536 sk->sk_state_change = sc->sc_state_change;
538 write_unlock_bh(&sk->sk_callback_lock);
540 return ret;
544 * this is a little helper that is called by callers who have seen a problem
545 * with an sc and want to detach it from the nn if someone already hasn't beat
546 * them to it. if an error is given then the shutdown will be persistent
547 * and pending transmits will be canceled.
549 static void o2net_ensure_shutdown(struct o2net_node *nn,
550 struct o2net_sock_container *sc,
551 int err)
553 spin_lock(&nn->nn_lock);
554 if (nn->nn_sc == sc)
555 o2net_set_nn_state(nn, NULL, 0, err);
556 spin_unlock(&nn->nn_lock);
560 * This work queue function performs the blocking parts of socket shutdown. A
561 * few paths lead here. set_nn_state will trigger this callback if it sees an
562 * sc detached from the nn. state_change will also trigger this callback
563 * directly when it sees errors. In that case we need to call set_nn_state
564 * ourselves as state_change couldn't get the nn_lock and call set_nn_state
565 * itself.
567 static void o2net_shutdown_sc(void *arg)
569 struct o2net_sock_container *sc = arg;
570 struct o2net_node *nn = o2net_nn_from_num(sc->sc_node->nd_num);
572 sclog(sc, "shutting down\n");
574 /* drop the callbacks ref and call shutdown only once */
575 if (o2net_unregister_callbacks(sc->sc_sock->sk, sc)) {
576 /* we shouldn't flush as we're in the thread, the
577 * races with pending sc work structs are harmless */
578 del_timer_sync(&sc->sc_idle_timeout);
579 o2net_sc_cancel_delayed_work(sc, &sc->sc_keepalive_work);
580 sc_put(sc);
581 sc->sc_sock->ops->shutdown(sc->sc_sock,
582 RCV_SHUTDOWN|SEND_SHUTDOWN);
585 /* not fatal so failed connects before the other guy has our
586 * heartbeat can be retried */
587 o2net_ensure_shutdown(nn, sc, 0);
588 sc_put(sc);
591 /* ------------------------------------------------------------ */
593 static int o2net_handler_cmp(struct o2net_msg_handler *nmh, u32 msg_type,
594 u32 key)
596 int ret = memcmp(&nmh->nh_key, &key, sizeof(key));
598 if (ret == 0)
599 ret = memcmp(&nmh->nh_msg_type, &msg_type, sizeof(msg_type));
601 return ret;
604 static struct o2net_msg_handler *
605 o2net_handler_tree_lookup(u32 msg_type, u32 key, struct rb_node ***ret_p,
606 struct rb_node **ret_parent)
608 struct rb_node **p = &o2net_handler_tree.rb_node;
609 struct rb_node *parent = NULL;
610 struct o2net_msg_handler *nmh, *ret = NULL;
611 int cmp;
613 while (*p) {
614 parent = *p;
615 nmh = rb_entry(parent, struct o2net_msg_handler, nh_node);
616 cmp = o2net_handler_cmp(nmh, msg_type, key);
618 if (cmp < 0)
619 p = &(*p)->rb_left;
620 else if (cmp > 0)
621 p = &(*p)->rb_right;
622 else {
623 ret = nmh;
624 break;
628 if (ret_p != NULL)
629 *ret_p = p;
630 if (ret_parent != NULL)
631 *ret_parent = parent;
633 return ret;
636 static void o2net_handler_kref_release(struct kref *kref)
638 struct o2net_msg_handler *nmh;
639 nmh = container_of(kref, struct o2net_msg_handler, nh_kref);
641 kfree(nmh);
644 static void o2net_handler_put(struct o2net_msg_handler *nmh)
646 kref_put(&nmh->nh_kref, o2net_handler_kref_release);
649 /* max_len is protection for the handler func. incoming messages won't
650 * be given to the handler if their payload is longer than the max. */
651 int o2net_register_handler(u32 msg_type, u32 key, u32 max_len,
652 o2net_msg_handler_func *func, void *data,
653 struct list_head *unreg_list)
655 struct o2net_msg_handler *nmh = NULL;
656 struct rb_node **p, *parent;
657 int ret = 0;
659 if (max_len > O2NET_MAX_PAYLOAD_BYTES) {
660 mlog(0, "max_len for message handler out of range: %u\n",
661 max_len);
662 ret = -EINVAL;
663 goto out;
666 if (!msg_type) {
667 mlog(0, "no message type provided: %u, %p\n", msg_type, func);
668 ret = -EINVAL;
669 goto out;
672 if (!func) {
673 mlog(0, "no message handler provided: %u, %p\n",
674 msg_type, func);
675 ret = -EINVAL;
676 goto out;
679 nmh = kcalloc(1, sizeof(struct o2net_msg_handler), GFP_NOFS);
680 if (nmh == NULL) {
681 ret = -ENOMEM;
682 goto out;
685 nmh->nh_func = func;
686 nmh->nh_func_data = data;
687 nmh->nh_msg_type = msg_type;
688 nmh->nh_max_len = max_len;
689 nmh->nh_key = key;
690 /* the tree and list get this ref.. they're both removed in
691 * unregister when this ref is dropped */
692 kref_init(&nmh->nh_kref);
693 INIT_LIST_HEAD(&nmh->nh_unregister_item);
695 write_lock(&o2net_handler_lock);
696 if (o2net_handler_tree_lookup(msg_type, key, &p, &parent))
697 ret = -EEXIST;
698 else {
699 rb_link_node(&nmh->nh_node, parent, p);
700 rb_insert_color(&nmh->nh_node, &o2net_handler_tree);
701 list_add_tail(&nmh->nh_unregister_item, unreg_list);
703 mlog(ML_TCP, "registered handler func %p type %u key %08x\n",
704 func, msg_type, key);
705 /* we've had some trouble with handlers seemingly vanishing. */
706 mlog_bug_on_msg(o2net_handler_tree_lookup(msg_type, key, &p,
707 &parent) == NULL,
708 "couldn't find handler we *just* registerd "
709 "for type %u key %08x\n", msg_type, key);
711 write_unlock(&o2net_handler_lock);
712 if (ret)
713 goto out;
715 out:
716 if (ret)
717 kfree(nmh);
719 return ret;
721 EXPORT_SYMBOL_GPL(o2net_register_handler);
723 void o2net_unregister_handler_list(struct list_head *list)
725 struct list_head *pos, *n;
726 struct o2net_msg_handler *nmh;
728 write_lock(&o2net_handler_lock);
729 list_for_each_safe(pos, n, list) {
730 nmh = list_entry(pos, struct o2net_msg_handler,
731 nh_unregister_item);
732 mlog(ML_TCP, "unregistering handler func %p type %u key %08x\n",
733 nmh->nh_func, nmh->nh_msg_type, nmh->nh_key);
734 rb_erase(&nmh->nh_node, &o2net_handler_tree);
735 list_del_init(&nmh->nh_unregister_item);
736 kref_put(&nmh->nh_kref, o2net_handler_kref_release);
738 write_unlock(&o2net_handler_lock);
740 EXPORT_SYMBOL_GPL(o2net_unregister_handler_list);
742 static struct o2net_msg_handler *o2net_handler_get(u32 msg_type, u32 key)
744 struct o2net_msg_handler *nmh;
746 read_lock(&o2net_handler_lock);
747 nmh = o2net_handler_tree_lookup(msg_type, key, NULL, NULL);
748 if (nmh)
749 kref_get(&nmh->nh_kref);
750 read_unlock(&o2net_handler_lock);
752 return nmh;
755 /* ------------------------------------------------------------ */
757 static int o2net_recv_tcp_msg(struct socket *sock, void *data, size_t len)
759 int ret;
760 mm_segment_t oldfs;
761 struct kvec vec = {
762 .iov_len = len,
763 .iov_base = data,
765 struct msghdr msg = {
766 .msg_iovlen = 1,
767 .msg_iov = (struct iovec *)&vec,
768 .msg_flags = MSG_DONTWAIT,
771 oldfs = get_fs();
772 set_fs(get_ds());
773 ret = sock_recvmsg(sock, &msg, len, msg.msg_flags);
774 set_fs(oldfs);
776 return ret;
779 static int o2net_send_tcp_msg(struct socket *sock, struct kvec *vec,
780 size_t veclen, size_t total)
782 int ret;
783 mm_segment_t oldfs;
784 struct msghdr msg = {
785 .msg_iov = (struct iovec *)vec,
786 .msg_iovlen = veclen,
789 if (sock == NULL) {
790 ret = -EINVAL;
791 goto out;
794 oldfs = get_fs();
795 set_fs(get_ds());
796 ret = sock_sendmsg(sock, &msg, total);
797 set_fs(oldfs);
798 if (ret != total) {
799 mlog(ML_ERROR, "sendmsg returned %d instead of %zu\n", ret,
800 total);
801 if (ret >= 0)
802 ret = -EPIPE; /* should be smarter, I bet */
803 goto out;
806 ret = 0;
807 out:
808 if (ret < 0)
809 mlog(0, "returning error: %d\n", ret);
810 return ret;
813 static void o2net_sendpage(struct o2net_sock_container *sc,
814 void *kmalloced_virt,
815 size_t size)
817 struct o2net_node *nn = o2net_nn_from_num(sc->sc_node->nd_num);
818 ssize_t ret;
821 ret = sc->sc_sock->ops->sendpage(sc->sc_sock,
822 virt_to_page(kmalloced_virt),
823 (long)kmalloced_virt & ~PAGE_MASK,
824 size, MSG_DONTWAIT);
825 if (ret != size) {
826 mlog(ML_ERROR, "sendpage of size %zu to " SC_NODEF_FMT
827 " failed with %zd\n", size, SC_NODEF_ARGS(sc), ret);
828 o2net_ensure_shutdown(nn, sc, 0);
832 static void o2net_init_msg(struct o2net_msg *msg, u16 data_len, u16 msg_type, u32 key)
834 memset(msg, 0, sizeof(struct o2net_msg));
835 msg->magic = cpu_to_be16(O2NET_MSG_MAGIC);
836 msg->data_len = cpu_to_be16(data_len);
837 msg->msg_type = cpu_to_be16(msg_type);
838 msg->sys_status = cpu_to_be32(O2NET_ERR_NONE);
839 msg->status = 0;
840 msg->key = cpu_to_be32(key);
843 static int o2net_tx_can_proceed(struct o2net_node *nn,
844 struct o2net_sock_container **sc_ret,
845 int *error)
847 int ret = 0;
849 spin_lock(&nn->nn_lock);
850 if (nn->nn_persistent_error) {
851 ret = 1;
852 *sc_ret = NULL;
853 *error = nn->nn_persistent_error;
854 } else if (nn->nn_sc_valid) {
855 kref_get(&nn->nn_sc->sc_kref);
857 ret = 1;
858 *sc_ret = nn->nn_sc;
859 *error = 0;
861 spin_unlock(&nn->nn_lock);
863 return ret;
866 int o2net_send_message_vec(u32 msg_type, u32 key, struct kvec *caller_vec,
867 size_t caller_veclen, u8 target_node, int *status)
869 int ret, error = 0;
870 struct o2net_msg *msg = NULL;
871 size_t veclen, caller_bytes = 0;
872 struct kvec *vec = NULL;
873 struct o2net_sock_container *sc = NULL;
874 struct o2net_node *nn = o2net_nn_from_num(target_node);
875 struct o2net_status_wait nsw = {
876 .ns_node_item = LIST_HEAD_INIT(nsw.ns_node_item),
879 if (o2net_wq == NULL) {
880 mlog(0, "attempt to tx without o2netd running\n");
881 ret = -ESRCH;
882 goto out;
885 if (caller_veclen == 0) {
886 mlog(0, "bad kvec array length\n");
887 ret = -EINVAL;
888 goto out;
891 caller_bytes = iov_length((struct iovec *)caller_vec, caller_veclen);
892 if (caller_bytes > O2NET_MAX_PAYLOAD_BYTES) {
893 mlog(0, "total payload len %zu too large\n", caller_bytes);
894 ret = -EINVAL;
895 goto out;
898 if (target_node == o2nm_this_node()) {
899 ret = -ELOOP;
900 goto out;
903 ret = wait_event_interruptible(nn->nn_sc_wq,
904 o2net_tx_can_proceed(nn, &sc, &error));
905 if (!ret && error)
906 ret = error;
907 if (ret)
908 goto out;
910 veclen = caller_veclen + 1;
911 vec = kmalloc(sizeof(struct kvec) * veclen, GFP_ATOMIC);
912 if (vec == NULL) {
913 mlog(0, "failed to %zu element kvec!\n", veclen);
914 ret = -ENOMEM;
915 goto out;
918 msg = kmalloc(sizeof(struct o2net_msg), GFP_ATOMIC);
919 if (!msg) {
920 mlog(0, "failed to allocate a o2net_msg!\n");
921 ret = -ENOMEM;
922 goto out;
925 o2net_init_msg(msg, caller_bytes, msg_type, key);
927 vec[0].iov_len = sizeof(struct o2net_msg);
928 vec[0].iov_base = msg;
929 memcpy(&vec[1], caller_vec, caller_veclen * sizeof(struct kvec));
931 ret = o2net_prep_nsw(nn, &nsw);
932 if (ret)
933 goto out;
935 msg->msg_num = cpu_to_be32(nsw.ns_id);
937 /* finally, convert the message header to network byte-order
938 * and send */
939 ret = o2net_send_tcp_msg(sc->sc_sock, vec, veclen,
940 sizeof(struct o2net_msg) + caller_bytes);
941 msglog(msg, "sending returned %d\n", ret);
942 if (ret < 0) {
943 mlog(0, "error returned from o2net_send_tcp_msg=%d\n", ret);
944 goto out;
947 /* wait on other node's handler */
948 wait_event(nsw.ns_wq, o2net_nsw_completed(nn, &nsw));
950 /* Note that we avoid overwriting the callers status return
951 * variable if a system error was reported on the other
952 * side. Callers beware. */
953 ret = o2net_sys_err_to_errno(nsw.ns_sys_status);
954 if (status && !ret)
955 *status = nsw.ns_status;
957 mlog(0, "woken, returning system status %d, user status %d\n",
958 ret, nsw.ns_status);
959 out:
960 if (sc)
961 sc_put(sc);
962 if (vec)
963 kfree(vec);
964 if (msg)
965 kfree(msg);
966 o2net_complete_nsw(nn, &nsw, 0, 0, 0);
967 return ret;
969 EXPORT_SYMBOL_GPL(o2net_send_message_vec);
971 int o2net_send_message(u32 msg_type, u32 key, void *data, u32 len,
972 u8 target_node, int *status)
974 struct kvec vec = {
975 .iov_base = data,
976 .iov_len = len,
978 return o2net_send_message_vec(msg_type, key, &vec, 1,
979 target_node, status);
981 EXPORT_SYMBOL_GPL(o2net_send_message);
983 static int o2net_send_status_magic(struct socket *sock, struct o2net_msg *hdr,
984 enum o2net_system_error syserr, int err)
986 struct kvec vec = {
987 .iov_base = hdr,
988 .iov_len = sizeof(struct o2net_msg),
991 BUG_ON(syserr >= O2NET_ERR_MAX);
993 /* leave other fields intact from the incoming message, msg_num
994 * in particular */
995 hdr->sys_status = cpu_to_be32(syserr);
996 hdr->status = cpu_to_be32(err);
997 hdr->magic = cpu_to_be16(O2NET_MSG_STATUS_MAGIC); // twiddle the magic
998 hdr->data_len = 0;
1000 msglog(hdr, "about to send status magic %d\n", err);
1001 /* hdr has been in host byteorder this whole time */
1002 return o2net_send_tcp_msg(sock, &vec, 1, sizeof(struct o2net_msg));
1005 /* this returns -errno if the header was unknown or too large, etc.
1006 * after this is called the buffer us reused for the next message */
1007 static int o2net_process_message(struct o2net_sock_container *sc,
1008 struct o2net_msg *hdr)
1010 struct o2net_node *nn = o2net_nn_from_num(sc->sc_node->nd_num);
1011 int ret = 0, handler_status;
1012 enum o2net_system_error syserr;
1013 struct o2net_msg_handler *nmh = NULL;
1015 msglog(hdr, "processing message\n");
1017 o2net_sc_postpone_idle(sc);
1019 switch(be16_to_cpu(hdr->magic)) {
1020 case O2NET_MSG_STATUS_MAGIC:
1021 /* special type for returning message status */
1022 o2net_complete_nsw(nn, NULL,
1023 be32_to_cpu(hdr->msg_num),
1024 be32_to_cpu(hdr->sys_status),
1025 be32_to_cpu(hdr->status));
1026 goto out;
1027 case O2NET_MSG_KEEP_REQ_MAGIC:
1028 o2net_sendpage(sc, o2net_keep_resp,
1029 sizeof(*o2net_keep_resp));
1030 goto out;
1031 case O2NET_MSG_KEEP_RESP_MAGIC:
1032 goto out;
1033 case O2NET_MSG_MAGIC:
1034 break;
1035 default:
1036 msglog(hdr, "bad magic\n");
1037 ret = -EINVAL;
1038 goto out;
1039 break;
1042 /* find a handler for it */
1043 handler_status = 0;
1044 nmh = o2net_handler_get(be16_to_cpu(hdr->msg_type),
1045 be32_to_cpu(hdr->key));
1046 if (!nmh) {
1047 mlog(ML_TCP, "couldn't find handler for type %u key %08x\n",
1048 be16_to_cpu(hdr->msg_type), be32_to_cpu(hdr->key));
1049 syserr = O2NET_ERR_NO_HNDLR;
1050 goto out_respond;
1053 syserr = O2NET_ERR_NONE;
1055 if (be16_to_cpu(hdr->data_len) > nmh->nh_max_len)
1056 syserr = O2NET_ERR_OVERFLOW;
1058 if (syserr != O2NET_ERR_NONE)
1059 goto out_respond;
1061 do_gettimeofday(&sc->sc_tv_func_start);
1062 sc->sc_msg_key = be32_to_cpu(hdr->key);
1063 sc->sc_msg_type = be16_to_cpu(hdr->msg_type);
1064 handler_status = (nmh->nh_func)(hdr, sizeof(struct o2net_msg) +
1065 be16_to_cpu(hdr->data_len),
1066 nmh->nh_func_data);
1067 do_gettimeofday(&sc->sc_tv_func_stop);
1069 out_respond:
1070 /* this destroys the hdr, so don't use it after this */
1071 ret = o2net_send_status_magic(sc->sc_sock, hdr, syserr,
1072 handler_status);
1073 hdr = NULL;
1074 mlog(0, "sending handler status %d, syserr %d returned %d\n",
1075 handler_status, syserr, ret);
1077 out:
1078 if (nmh)
1079 o2net_handler_put(nmh);
1080 return ret;
1083 static int o2net_check_handshake(struct o2net_sock_container *sc)
1085 struct o2net_handshake *hand = page_address(sc->sc_page);
1086 struct o2net_node *nn = o2net_nn_from_num(sc->sc_node->nd_num);
1088 if (hand->protocol_version != cpu_to_be64(O2NET_PROTOCOL_VERSION)) {
1089 mlog(ML_NOTICE, SC_NODEF_FMT " advertised net protocol "
1090 "version %llu but %llu is required, disconnecting\n",
1091 SC_NODEF_ARGS(sc),
1092 (unsigned long long)be64_to_cpu(hand->protocol_version),
1093 O2NET_PROTOCOL_VERSION);
1095 /* don't bother reconnecting if its the wrong version. */
1096 o2net_ensure_shutdown(nn, sc, -ENOTCONN);
1097 return -1;
1100 sc->sc_handshake_ok = 1;
1102 spin_lock(&nn->nn_lock);
1103 /* set valid and queue the idle timers only if it hasn't been
1104 * shut down already */
1105 if (nn->nn_sc == sc) {
1106 o2net_sc_postpone_idle(sc);
1107 o2net_set_nn_state(nn, sc, 1, 0);
1109 spin_unlock(&nn->nn_lock);
1111 /* shift everything up as though it wasn't there */
1112 sc->sc_page_off -= sizeof(struct o2net_handshake);
1113 if (sc->sc_page_off)
1114 memmove(hand, hand + 1, sc->sc_page_off);
1116 return 0;
1119 /* this demuxes the queued rx bytes into header or payload bits and calls
1120 * handlers as each full message is read off the socket. it returns -error,
1121 * == 0 eof, or > 0 for progress made.*/
1122 static int o2net_advance_rx(struct o2net_sock_container *sc)
1124 struct o2net_msg *hdr;
1125 int ret = 0;
1126 void *data;
1127 size_t datalen;
1129 sclog(sc, "receiving\n");
1130 do_gettimeofday(&sc->sc_tv_advance_start);
1132 /* do we need more header? */
1133 if (sc->sc_page_off < sizeof(struct o2net_msg)) {
1134 data = page_address(sc->sc_page) + sc->sc_page_off;
1135 datalen = sizeof(struct o2net_msg) - sc->sc_page_off;
1136 ret = o2net_recv_tcp_msg(sc->sc_sock, data, datalen);
1137 if (ret > 0) {
1138 sc->sc_page_off += ret;
1140 /* this working relies on the handshake being
1141 * smaller than the normal message header */
1142 if (sc->sc_page_off >= sizeof(struct o2net_handshake)&&
1143 !sc->sc_handshake_ok && o2net_check_handshake(sc)) {
1144 ret = -EPROTO;
1145 goto out;
1148 /* only swab incoming here.. we can
1149 * only get here once as we cross from
1150 * being under to over */
1151 if (sc->sc_page_off == sizeof(struct o2net_msg)) {
1152 hdr = page_address(sc->sc_page);
1153 if (be16_to_cpu(hdr->data_len) >
1154 O2NET_MAX_PAYLOAD_BYTES)
1155 ret = -EOVERFLOW;
1158 if (ret <= 0)
1159 goto out;
1162 if (sc->sc_page_off < sizeof(struct o2net_msg)) {
1163 /* oof, still don't have a header */
1164 goto out;
1167 /* this was swabbed above when we first read it */
1168 hdr = page_address(sc->sc_page);
1170 msglog(hdr, "at page_off %zu\n", sc->sc_page_off);
1172 /* do we need more payload? */
1173 if (sc->sc_page_off - sizeof(struct o2net_msg) < be16_to_cpu(hdr->data_len)) {
1174 /* need more payload */
1175 data = page_address(sc->sc_page) + sc->sc_page_off;
1176 datalen = (sizeof(struct o2net_msg) + be16_to_cpu(hdr->data_len)) -
1177 sc->sc_page_off;
1178 ret = o2net_recv_tcp_msg(sc->sc_sock, data, datalen);
1179 if (ret > 0)
1180 sc->sc_page_off += ret;
1181 if (ret <= 0)
1182 goto out;
1185 if (sc->sc_page_off - sizeof(struct o2net_msg) == be16_to_cpu(hdr->data_len)) {
1186 /* we can only get here once, the first time we read
1187 * the payload.. so set ret to progress if the handler
1188 * works out. after calling this the message is toast */
1189 ret = o2net_process_message(sc, hdr);
1190 if (ret == 0)
1191 ret = 1;
1192 sc->sc_page_off = 0;
1195 out:
1196 sclog(sc, "ret = %d\n", ret);
1197 do_gettimeofday(&sc->sc_tv_advance_stop);
1198 return ret;
1201 /* this work func is triggerd by data ready. it reads until it can read no
1202 * more. it interprets 0, eof, as fatal. if data_ready hits while we're doing
1203 * our work the work struct will be marked and we'll be called again. */
1204 static void o2net_rx_until_empty(void *arg)
1206 struct o2net_sock_container *sc = arg;
1207 int ret;
1209 do {
1210 ret = o2net_advance_rx(sc);
1211 } while (ret > 0);
1213 if (ret <= 0 && ret != -EAGAIN) {
1214 struct o2net_node *nn = o2net_nn_from_num(sc->sc_node->nd_num);
1215 sclog(sc, "saw error %d, closing\n", ret);
1216 /* not permanent so read failed handshake can retry */
1217 o2net_ensure_shutdown(nn, sc, 0);
1220 sc_put(sc);
1223 static int o2net_set_nodelay(struct socket *sock)
1225 int ret, val = 1;
1226 mm_segment_t oldfs;
1228 oldfs = get_fs();
1229 set_fs(KERNEL_DS);
1232 * Dear unsuspecting programmer,
1234 * Don't use sock_setsockopt() for SOL_TCP. It doesn't check its level
1235 * argument and assumes SOL_SOCKET so, say, your TCP_NODELAY will
1236 * silently turn into SO_DEBUG.
1238 * Yours,
1239 * Keeper of hilariously fragile interfaces.
1241 ret = sock->ops->setsockopt(sock, SOL_TCP, TCP_NODELAY,
1242 (char __user *)&val, sizeof(val));
1244 set_fs(oldfs);
1245 return ret;
1248 /* ------------------------------------------------------------ */
1250 /* called when a connect completes and after a sock is accepted. the
1251 * rx path will see the response and mark the sc valid */
1252 static void o2net_sc_connect_completed(void *arg)
1254 struct o2net_sock_container *sc = arg;
1256 mlog(ML_MSG, "sc sending handshake with ver %llu id %llx\n",
1257 (unsigned long long)O2NET_PROTOCOL_VERSION,
1258 (unsigned long long)be64_to_cpu(o2net_hand->connector_id));
1260 o2net_sendpage(sc, o2net_hand, sizeof(*o2net_hand));
1261 sc_put(sc);
1264 /* this is called as a work_struct func. */
1265 static void o2net_sc_send_keep_req(void *arg)
1267 struct o2net_sock_container *sc = arg;
1269 o2net_sendpage(sc, o2net_keep_req, sizeof(*o2net_keep_req));
1270 sc_put(sc);
1273 /* socket shutdown does a del_timer_sync against this as it tears down.
1274 * we can't start this timer until we've got to the point in sc buildup
1275 * where shutdown is going to be involved */
1276 static void o2net_idle_timer(unsigned long data)
1278 struct o2net_sock_container *sc = (struct o2net_sock_container *)data;
1279 struct timeval now;
1281 do_gettimeofday(&now);
1283 printk(KERN_INFO "o2net: connection to " SC_NODEF_FMT " has been idle for 10 "
1284 "seconds, shutting it down.\n", SC_NODEF_ARGS(sc));
1285 mlog(ML_NOTICE, "here are some times that might help debug the "
1286 "situation: (tmr %ld.%ld now %ld.%ld dr %ld.%ld adv "
1287 "%ld.%ld:%ld.%ld func (%08x:%u) %ld.%ld:%ld.%ld)\n",
1288 sc->sc_tv_timer.tv_sec, (long) sc->sc_tv_timer.tv_usec,
1289 now.tv_sec, (long) now.tv_usec,
1290 sc->sc_tv_data_ready.tv_sec, (long) sc->sc_tv_data_ready.tv_usec,
1291 sc->sc_tv_advance_start.tv_sec,
1292 (long) sc->sc_tv_advance_start.tv_usec,
1293 sc->sc_tv_advance_stop.tv_sec,
1294 (long) sc->sc_tv_advance_stop.tv_usec,
1295 sc->sc_msg_key, sc->sc_msg_type,
1296 sc->sc_tv_func_start.tv_sec, (long) sc->sc_tv_func_start.tv_usec,
1297 sc->sc_tv_func_stop.tv_sec, (long) sc->sc_tv_func_stop.tv_usec);
1299 o2net_sc_queue_work(sc, &sc->sc_shutdown_work);
1302 static void o2net_sc_postpone_idle(struct o2net_sock_container *sc)
1304 o2net_sc_cancel_delayed_work(sc, &sc->sc_keepalive_work);
1305 o2net_sc_queue_delayed_work(sc, &sc->sc_keepalive_work,
1306 O2NET_KEEPALIVE_DELAY_SECS * HZ);
1307 do_gettimeofday(&sc->sc_tv_timer);
1308 mod_timer(&sc->sc_idle_timeout,
1309 jiffies + (O2NET_IDLE_TIMEOUT_SECS * HZ));
1312 /* this work func is kicked whenever a path sets the nn state which doesn't
1313 * have valid set. This includes seeing hb come up, losing a connection,
1314 * having a connect attempt fail, etc. This centralizes the logic which decides
1315 * if a connect attempt should be made or if we should give up and all future
1316 * transmit attempts should fail */
1317 static void o2net_start_connect(void *arg)
1319 struct o2net_node *nn = arg;
1320 struct o2net_sock_container *sc = NULL;
1321 struct o2nm_node *node = NULL, *mynode = NULL;
1322 struct socket *sock = NULL;
1323 struct sockaddr_in myaddr = {0, }, remoteaddr = {0, };
1324 int ret = 0;
1326 /* if we're greater we initiate tx, otherwise we accept */
1327 if (o2nm_this_node() <= o2net_num_from_nn(nn))
1328 goto out;
1330 /* watch for racing with tearing a node down */
1331 node = o2nm_get_node_by_num(o2net_num_from_nn(nn));
1332 if (node == NULL) {
1333 ret = 0;
1334 goto out;
1337 mynode = o2nm_get_node_by_num(o2nm_this_node());
1338 if (mynode == NULL) {
1339 ret = 0;
1340 goto out;
1343 spin_lock(&nn->nn_lock);
1344 /* see if we already have one pending or have given up */
1345 if (nn->nn_sc || nn->nn_persistent_error)
1346 arg = NULL;
1347 spin_unlock(&nn->nn_lock);
1348 if (arg == NULL) /* *shrug*, needed some indicator */
1349 goto out;
1351 nn->nn_last_connect_attempt = jiffies;
1353 sc = sc_alloc(node);
1354 if (sc == NULL) {
1355 mlog(0, "couldn't allocate sc\n");
1356 ret = -ENOMEM;
1357 goto out;
1360 ret = sock_create(PF_INET, SOCK_STREAM, IPPROTO_TCP, &sock);
1361 if (ret < 0) {
1362 mlog(0, "can't create socket: %d\n", ret);
1363 goto out;
1365 sc->sc_sock = sock; /* freed by sc_kref_release */
1367 sock->sk->sk_allocation = GFP_ATOMIC;
1369 myaddr.sin_family = AF_INET;
1370 myaddr.sin_addr.s_addr = (__force u32)mynode->nd_ipv4_address;
1371 myaddr.sin_port = (__force u16)htons(0); /* any port */
1373 ret = sock->ops->bind(sock, (struct sockaddr *)&myaddr,
1374 sizeof(myaddr));
1375 if (ret) {
1376 mlog(ML_ERROR, "bind failed with %d at address %u.%u.%u.%u\n",
1377 ret, NIPQUAD(mynode->nd_ipv4_address));
1378 goto out;
1381 ret = o2net_set_nodelay(sc->sc_sock);
1382 if (ret) {
1383 mlog(ML_ERROR, "setting TCP_NODELAY failed with %d\n", ret);
1384 goto out;
1387 o2net_register_callbacks(sc->sc_sock->sk, sc);
1389 spin_lock(&nn->nn_lock);
1390 /* handshake completion will set nn->nn_sc_valid */
1391 o2net_set_nn_state(nn, sc, 0, 0);
1392 spin_unlock(&nn->nn_lock);
1394 remoteaddr.sin_family = AF_INET;
1395 remoteaddr.sin_addr.s_addr = (__force u32)node->nd_ipv4_address;
1396 remoteaddr.sin_port = (__force u16)node->nd_ipv4_port;
1398 ret = sc->sc_sock->ops->connect(sc->sc_sock,
1399 (struct sockaddr *)&remoteaddr,
1400 sizeof(remoteaddr),
1401 O_NONBLOCK);
1402 if (ret == -EINPROGRESS)
1403 ret = 0;
1405 out:
1406 if (ret) {
1407 mlog(ML_NOTICE, "connect attempt to " SC_NODEF_FMT " failed "
1408 "with errno %d\n", SC_NODEF_ARGS(sc), ret);
1409 /* 0 err so that another will be queued and attempted
1410 * from set_nn_state */
1411 if (sc)
1412 o2net_ensure_shutdown(nn, sc, 0);
1414 if (sc)
1415 sc_put(sc);
1416 if (node)
1417 o2nm_node_put(node);
1418 if (mynode)
1419 o2nm_node_put(mynode);
1421 return;
1424 static void o2net_connect_expired(void *arg)
1426 struct o2net_node *nn = arg;
1428 spin_lock(&nn->nn_lock);
1429 if (!nn->nn_sc_valid) {
1430 mlog(ML_ERROR, "no connection established with node %u after "
1431 "%u seconds, giving up and returning errors.\n",
1432 o2net_num_from_nn(nn), O2NET_IDLE_TIMEOUT_SECS);
1434 o2net_set_nn_state(nn, NULL, 0, -ENOTCONN);
1436 spin_unlock(&nn->nn_lock);
1439 static void o2net_still_up(void *arg)
1441 struct o2net_node *nn = arg;
1443 o2quo_hb_still_up(o2net_num_from_nn(nn));
1446 /* ------------------------------------------------------------ */
1448 void o2net_disconnect_node(struct o2nm_node *node)
1450 struct o2net_node *nn = o2net_nn_from_num(node->nd_num);
1452 /* don't reconnect until it's heartbeating again */
1453 spin_lock(&nn->nn_lock);
1454 o2net_set_nn_state(nn, NULL, 0, -ENOTCONN);
1455 spin_unlock(&nn->nn_lock);
1457 if (o2net_wq) {
1458 cancel_delayed_work(&nn->nn_connect_expired);
1459 cancel_delayed_work(&nn->nn_connect_work);
1460 cancel_delayed_work(&nn->nn_still_up);
1461 flush_workqueue(o2net_wq);
1465 static void o2net_hb_node_down_cb(struct o2nm_node *node, int node_num,
1466 void *data)
1468 o2quo_hb_down(node_num);
1470 if (node_num != o2nm_this_node())
1471 o2net_disconnect_node(node);
1474 static void o2net_hb_node_up_cb(struct o2nm_node *node, int node_num,
1475 void *data)
1477 struct o2net_node *nn = o2net_nn_from_num(node_num);
1479 o2quo_hb_up(node_num);
1481 /* ensure an immediate connect attempt */
1482 nn->nn_last_connect_attempt = jiffies -
1483 (msecs_to_jiffies(O2NET_RECONNECT_DELAY_MS) + 1);
1485 if (node_num != o2nm_this_node()) {
1486 /* heartbeat doesn't work unless a local node number is
1487 * configured and doing so brings up the o2net_wq, so we can
1488 * use it.. */
1489 queue_delayed_work(o2net_wq, &nn->nn_connect_expired,
1490 O2NET_IDLE_TIMEOUT_SECS * HZ);
1492 /* believe it or not, accept and node hearbeating testing
1493 * can succeed for this node before we got here.. so
1494 * only use set_nn_state to clear the persistent error
1495 * if that hasn't already happened */
1496 spin_lock(&nn->nn_lock);
1497 if (nn->nn_persistent_error)
1498 o2net_set_nn_state(nn, NULL, 0, 0);
1499 spin_unlock(&nn->nn_lock);
1503 void o2net_unregister_hb_callbacks(void)
1505 int ret;
1507 ret = o2hb_unregister_callback(&o2net_hb_up);
1508 if (ret < 0)
1509 mlog(ML_ERROR, "Status return %d unregistering heartbeat up "
1510 "callback!\n", ret);
1512 ret = o2hb_unregister_callback(&o2net_hb_down);
1513 if (ret < 0)
1514 mlog(ML_ERROR, "Status return %d unregistering heartbeat down "
1515 "callback!\n", ret);
1518 int o2net_register_hb_callbacks(void)
1520 int ret;
1522 o2hb_setup_callback(&o2net_hb_down, O2HB_NODE_DOWN_CB,
1523 o2net_hb_node_down_cb, NULL, O2NET_HB_PRI);
1524 o2hb_setup_callback(&o2net_hb_up, O2HB_NODE_UP_CB,
1525 o2net_hb_node_up_cb, NULL, O2NET_HB_PRI);
1527 ret = o2hb_register_callback(&o2net_hb_up);
1528 if (ret == 0)
1529 ret = o2hb_register_callback(&o2net_hb_down);
1531 if (ret)
1532 o2net_unregister_hb_callbacks();
1534 return ret;
1537 /* ------------------------------------------------------------ */
1539 static int o2net_accept_one(struct socket *sock)
1541 int ret, slen;
1542 struct sockaddr_in sin;
1543 struct socket *new_sock = NULL;
1544 struct o2nm_node *node = NULL;
1545 struct o2net_sock_container *sc = NULL;
1546 struct o2net_node *nn;
1548 BUG_ON(sock == NULL);
1549 ret = sock_create_lite(sock->sk->sk_family, sock->sk->sk_type,
1550 sock->sk->sk_protocol, &new_sock);
1551 if (ret)
1552 goto out;
1554 new_sock->type = sock->type;
1555 new_sock->ops = sock->ops;
1556 ret = sock->ops->accept(sock, new_sock, O_NONBLOCK);
1557 if (ret < 0)
1558 goto out;
1560 new_sock->sk->sk_allocation = GFP_ATOMIC;
1562 ret = o2net_set_nodelay(new_sock);
1563 if (ret) {
1564 mlog(ML_ERROR, "setting TCP_NODELAY failed with %d\n", ret);
1565 goto out;
1568 slen = sizeof(sin);
1569 ret = new_sock->ops->getname(new_sock, (struct sockaddr *) &sin,
1570 &slen, 1);
1571 if (ret < 0)
1572 goto out;
1574 node = o2nm_get_node_by_ip((__force __be32)sin.sin_addr.s_addr);
1575 if (node == NULL) {
1576 mlog(ML_NOTICE, "attempt to connect from unknown node at "
1577 "%u.%u.%u.%u:%d\n", NIPQUAD(sin.sin_addr.s_addr),
1578 ntohs((__force __be16)sin.sin_port));
1579 ret = -EINVAL;
1580 goto out;
1583 if (o2nm_this_node() > node->nd_num) {
1584 mlog(ML_NOTICE, "unexpected connect attempted from a lower "
1585 "numbered node '%s' at " "%u.%u.%u.%u:%d with num %u\n",
1586 node->nd_name, NIPQUAD(sin.sin_addr.s_addr),
1587 ntohs((__force __be16)sin.sin_port), node->nd_num);
1588 ret = -EINVAL;
1589 goto out;
1592 /* this happens all the time when the other node sees our heartbeat
1593 * and tries to connect before we see their heartbeat */
1594 if (!o2hb_check_node_heartbeating_from_callback(node->nd_num)) {
1595 mlog(ML_CONN, "attempt to connect from node '%s' at "
1596 "%u.%u.%u.%u:%d but it isn't heartbeating\n",
1597 node->nd_name, NIPQUAD(sin.sin_addr.s_addr),
1598 ntohs((__force __be16)sin.sin_port));
1599 ret = -EINVAL;
1600 goto out;
1603 nn = o2net_nn_from_num(node->nd_num);
1605 spin_lock(&nn->nn_lock);
1606 if (nn->nn_sc)
1607 ret = -EBUSY;
1608 else
1609 ret = 0;
1610 spin_unlock(&nn->nn_lock);
1611 if (ret) {
1612 mlog(ML_NOTICE, "attempt to connect from node '%s' at "
1613 "%u.%u.%u.%u:%d but it already has an open connection\n",
1614 node->nd_name, NIPQUAD(sin.sin_addr.s_addr),
1615 ntohs((__force __be16)sin.sin_port));
1616 goto out;
1619 sc = sc_alloc(node);
1620 if (sc == NULL) {
1621 ret = -ENOMEM;
1622 goto out;
1625 sc->sc_sock = new_sock;
1626 new_sock = NULL;
1628 spin_lock(&nn->nn_lock);
1629 o2net_set_nn_state(nn, sc, 0, 0);
1630 spin_unlock(&nn->nn_lock);
1632 o2net_register_callbacks(sc->sc_sock->sk, sc);
1633 o2net_sc_queue_work(sc, &sc->sc_rx_work);
1635 o2net_sendpage(sc, o2net_hand, sizeof(*o2net_hand));
1637 out:
1638 if (new_sock)
1639 sock_release(new_sock);
1640 if (node)
1641 o2nm_node_put(node);
1642 if (sc)
1643 sc_put(sc);
1644 return ret;
1647 static void o2net_accept_many(void *arg)
1649 struct socket *sock = arg;
1650 while (o2net_accept_one(sock) == 0)
1651 cond_resched();
1654 static void o2net_listen_data_ready(struct sock *sk, int bytes)
1656 void (*ready)(struct sock *sk, int bytes);
1658 read_lock(&sk->sk_callback_lock);
1659 ready = sk->sk_user_data;
1660 if (ready == NULL) { /* check for teardown race */
1661 ready = sk->sk_data_ready;
1662 goto out;
1665 /* ->sk_data_ready is also called for a newly established child socket
1666 * before it has been accepted and the acceptor has set up their
1667 * data_ready.. we only want to queue listen work for our listening
1668 * socket */
1669 if (sk->sk_state == TCP_LISTEN) {
1670 mlog(ML_TCP, "bytes: %d\n", bytes);
1671 queue_work(o2net_wq, &o2net_listen_work);
1674 out:
1675 read_unlock(&sk->sk_callback_lock);
1676 ready(sk, bytes);
1679 static int o2net_open_listening_sock(__be16 port)
1681 struct socket *sock = NULL;
1682 int ret;
1683 struct sockaddr_in sin = {
1684 .sin_family = PF_INET,
1685 .sin_addr = { .s_addr = (__force u32)htonl(INADDR_ANY) },
1686 .sin_port = (__force u16)port,
1689 ret = sock_create(PF_INET, SOCK_STREAM, IPPROTO_TCP, &sock);
1690 if (ret < 0) {
1691 mlog(ML_ERROR, "unable to create socket, ret=%d\n", ret);
1692 goto out;
1695 sock->sk->sk_allocation = GFP_ATOMIC;
1697 write_lock_bh(&sock->sk->sk_callback_lock);
1698 sock->sk->sk_user_data = sock->sk->sk_data_ready;
1699 sock->sk->sk_data_ready = o2net_listen_data_ready;
1700 write_unlock_bh(&sock->sk->sk_callback_lock);
1702 o2net_listen_sock = sock;
1703 INIT_WORK(&o2net_listen_work, o2net_accept_many, sock);
1705 sock->sk->sk_reuse = 1;
1706 ret = sock->ops->bind(sock, (struct sockaddr *)&sin, sizeof(sin));
1707 if (ret < 0) {
1708 mlog(ML_ERROR, "unable to bind socket to port %d, ret=%d\n",
1709 ntohs(port), ret);
1710 goto out;
1713 ret = sock->ops->listen(sock, 64);
1714 if (ret < 0) {
1715 mlog(ML_ERROR, "unable to listen on port %d, ret=%d\n",
1716 ntohs(port), ret);
1719 out:
1720 if (ret) {
1721 o2net_listen_sock = NULL;
1722 if (sock)
1723 sock_release(sock);
1725 return ret;
1729 * called from node manager when we should bring up our network listening
1730 * socket. node manager handles all the serialization to only call this
1731 * once and to match it with o2net_stop_listening(). note,
1732 * o2nm_this_node() doesn't work yet as we're being called while it
1733 * is being set up.
1735 int o2net_start_listening(struct o2nm_node *node)
1737 int ret = 0;
1739 BUG_ON(o2net_wq != NULL);
1740 BUG_ON(o2net_listen_sock != NULL);
1742 mlog(ML_KTHREAD, "starting o2net thread...\n");
1743 o2net_wq = create_singlethread_workqueue("o2net");
1744 if (o2net_wq == NULL) {
1745 mlog(ML_ERROR, "unable to launch o2net thread\n");
1746 return -ENOMEM; /* ? */
1749 ret = o2net_open_listening_sock(node->nd_ipv4_port);
1750 if (ret) {
1751 destroy_workqueue(o2net_wq);
1752 o2net_wq = NULL;
1753 } else
1754 o2quo_conn_up(node->nd_num);
1756 return ret;
1759 /* again, o2nm_this_node() doesn't work here as we're involved in
1760 * tearing it down */
1761 void o2net_stop_listening(struct o2nm_node *node)
1763 struct socket *sock = o2net_listen_sock;
1764 size_t i;
1766 BUG_ON(o2net_wq == NULL);
1767 BUG_ON(o2net_listen_sock == NULL);
1769 /* stop the listening socket from generating work */
1770 write_lock_bh(&sock->sk->sk_callback_lock);
1771 sock->sk->sk_data_ready = sock->sk->sk_user_data;
1772 sock->sk->sk_user_data = NULL;
1773 write_unlock_bh(&sock->sk->sk_callback_lock);
1775 for (i = 0; i < ARRAY_SIZE(o2net_nodes); i++) {
1776 struct o2nm_node *node = o2nm_get_node_by_num(i);
1777 if (node) {
1778 o2net_disconnect_node(node);
1779 o2nm_node_put(node);
1783 /* finish all work and tear down the work queue */
1784 mlog(ML_KTHREAD, "waiting for o2net thread to exit....\n");
1785 destroy_workqueue(o2net_wq);
1786 o2net_wq = NULL;
1788 sock_release(o2net_listen_sock);
1789 o2net_listen_sock = NULL;
1791 o2quo_conn_err(node->nd_num);
1794 /* ------------------------------------------------------------ */
1796 int o2net_init(void)
1798 unsigned long i;
1800 o2quo_init();
1802 o2net_hand = kcalloc(1, sizeof(struct o2net_handshake), GFP_KERNEL);
1803 o2net_keep_req = kcalloc(1, sizeof(struct o2net_msg), GFP_KERNEL);
1804 o2net_keep_resp = kcalloc(1, sizeof(struct o2net_msg), GFP_KERNEL);
1805 if (!o2net_hand || !o2net_keep_req || !o2net_keep_resp) {
1806 kfree(o2net_hand);
1807 kfree(o2net_keep_req);
1808 kfree(o2net_keep_resp);
1809 return -ENOMEM;
1812 o2net_hand->protocol_version = cpu_to_be64(O2NET_PROTOCOL_VERSION);
1813 o2net_hand->connector_id = cpu_to_be64(1);
1815 o2net_keep_req->magic = cpu_to_be16(O2NET_MSG_KEEP_REQ_MAGIC);
1816 o2net_keep_resp->magic = cpu_to_be16(O2NET_MSG_KEEP_RESP_MAGIC);
1818 for (i = 0; i < ARRAY_SIZE(o2net_nodes); i++) {
1819 struct o2net_node *nn = o2net_nn_from_num(i);
1821 spin_lock_init(&nn->nn_lock);
1822 INIT_WORK(&nn->nn_connect_work, o2net_start_connect, nn);
1823 INIT_WORK(&nn->nn_connect_expired, o2net_connect_expired, nn);
1824 INIT_WORK(&nn->nn_still_up, o2net_still_up, nn);
1825 /* until we see hb from a node we'll return einval */
1826 nn->nn_persistent_error = -ENOTCONN;
1827 init_waitqueue_head(&nn->nn_sc_wq);
1828 idr_init(&nn->nn_status_idr);
1829 INIT_LIST_HEAD(&nn->nn_status_list);
1832 return 0;
1835 void o2net_exit(void)
1837 o2quo_exit();
1838 kfree(o2net_hand);
1839 kfree(o2net_keep_req);
1840 kfree(o2net_keep_resp);