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.
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
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
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 <linux/net.h>
62 #include <linux/export.h>
63 #include <linux/uaccess.h>
67 #include "heartbeat.h"
69 #include "nodemanager.h"
70 #define MLOG_MASK_PREFIX ML_TCP
73 #include "tcp_internal.h"
75 #define SC_NODEF_FMT "node %s (num %u) at %pI4:%u"
78 * In the following two log macros, the whitespace after the ',' just
79 * before ##args is intentional. Otherwise, gcc 2.95 will eat the
80 * previous token if args expands to nothing.
82 #define msglog(hdr, fmt, args...) do { \
83 typeof(hdr) __hdr = (hdr); \
84 mlog(ML_MSG, "[mag %u len %u typ %u stat %d sys_stat %d " \
85 "key %08x num %u] " fmt, \
86 be16_to_cpu(__hdr->magic), be16_to_cpu(__hdr->data_len), \
87 be16_to_cpu(__hdr->msg_type), be32_to_cpu(__hdr->status), \
88 be32_to_cpu(__hdr->sys_status), be32_to_cpu(__hdr->key), \
89 be32_to_cpu(__hdr->msg_num) , ##args); \
92 #define sclog(sc, fmt, args...) do { \
93 typeof(sc) __sc = (sc); \
94 mlog(ML_SOCKET, "[sc %p refs %d sock %p node %u page %p " \
95 "pg_off %zu] " fmt, __sc, \
96 atomic_read(&__sc->sc_kref.refcount), __sc->sc_sock, \
97 __sc->sc_node->nd_num, __sc->sc_page, __sc->sc_page_off , \
101 static DEFINE_RWLOCK(r2net_handler_lock);
102 static struct rb_root r2net_handler_tree = RB_ROOT;
104 static struct r2net_node r2net_nodes[R2NM_MAX_NODES];
106 /* XXX someday we'll need better accounting */
107 static struct socket *r2net_listen_sock;
110 * listen work is only queued by the listening socket callbacks on the
111 * r2net_wq. teardown detaches the callbacks before destroying the workqueue.
112 * quorum work is queued as sock containers are shutdown.. stop_listening
113 * tears down all the node's sock containers, preventing future shutdowns
114 * and queued quorum work, before canceling delayed quorum work and
115 * destroying the work queue.
117 static struct workqueue_struct *r2net_wq;
118 static struct work_struct r2net_listen_work;
120 static struct r2hb_callback_func r2net_hb_up, r2net_hb_down;
121 #define R2NET_HB_PRI 0x1
123 static struct r2net_handshake *r2net_hand;
124 static struct r2net_msg *r2net_keep_req, *r2net_keep_resp;
126 static int r2net_sys_err_translations[R2NET_ERR_MAX] = {
127 [R2NET_ERR_NONE] = 0,
128 [R2NET_ERR_NO_HNDLR] = -ENOPROTOOPT,
129 [R2NET_ERR_OVERFLOW] = -EOVERFLOW,
130 [R2NET_ERR_DIED] = -EHOSTDOWN,};
132 /* can't quite avoid *all* internal declarations :/ */
133 static void r2net_sc_connect_completed(struct work_struct *work);
134 static void r2net_rx_until_empty(struct work_struct *work);
135 static void r2net_shutdown_sc(struct work_struct *work);
136 static void r2net_listen_data_ready(struct sock *sk, int bytes);
137 static void r2net_sc_send_keep_req(struct work_struct *work);
138 static void r2net_idle_timer(unsigned long data);
139 static void r2net_sc_postpone_idle(struct r2net_sock_container *sc);
140 static void r2net_sc_reset_idle_timer(struct r2net_sock_container *sc);
142 #ifdef CONFIG_DEBUG_FS
143 static void r2net_init_nst(struct r2net_send_tracking *nst, u32 msgtype,
144 u32 msgkey, struct task_struct *task, u8 node)
146 INIT_LIST_HEAD(&nst->st_net_debug_item);
148 nst->st_msg_type = msgtype;
149 nst->st_msg_key = msgkey;
153 static inline void r2net_set_nst_sock_time(struct r2net_send_tracking *nst)
155 nst->st_sock_time = ktime_get();
158 static inline void r2net_set_nst_send_time(struct r2net_send_tracking *nst)
160 nst->st_send_time = ktime_get();
163 static inline void r2net_set_nst_status_time(struct r2net_send_tracking *nst)
165 nst->st_status_time = ktime_get();
168 static inline void r2net_set_nst_sock_container(struct r2net_send_tracking *nst,
169 struct r2net_sock_container *sc)
174 static inline void r2net_set_nst_msg_id(struct r2net_send_tracking *nst,
180 static inline void r2net_set_sock_timer(struct r2net_sock_container *sc)
182 sc->sc_tv_timer = ktime_get();
185 static inline void r2net_set_data_ready_time(struct r2net_sock_container *sc)
187 sc->sc_tv_data_ready = ktime_get();
190 static inline void r2net_set_advance_start_time(struct r2net_sock_container *sc)
192 sc->sc_tv_advance_start = ktime_get();
195 static inline void r2net_set_advance_stop_time(struct r2net_sock_container *sc)
197 sc->sc_tv_advance_stop = ktime_get();
200 static inline void r2net_set_func_start_time(struct r2net_sock_container *sc)
202 sc->sc_tv_func_start = ktime_get();
205 static inline void r2net_set_func_stop_time(struct r2net_sock_container *sc)
207 sc->sc_tv_func_stop = ktime_get();
210 #else /* CONFIG_DEBUG_FS */
211 # define r2net_init_nst(a, b, c, d, e)
212 # define r2net_set_nst_sock_time(a)
213 # define r2net_set_nst_send_time(a)
214 # define r2net_set_nst_status_time(a)
215 # define r2net_set_nst_sock_container(a, b)
216 # define r2net_set_nst_msg_id(a, b)
217 # define r2net_set_sock_timer(a)
218 # define r2net_set_data_ready_time(a)
219 # define r2net_set_advance_start_time(a)
220 # define r2net_set_advance_stop_time(a)
221 # define r2net_set_func_start_time(a)
222 # define r2net_set_func_stop_time(a)
223 #endif /* CONFIG_DEBUG_FS */
225 #ifdef CONFIG_RAMSTER_FS_STATS
226 static ktime_t r2net_get_func_run_time(struct r2net_sock_container *sc)
228 return ktime_sub(sc->sc_tv_func_stop, sc->sc_tv_func_start);
231 static void r2net_update_send_stats(struct r2net_send_tracking *nst,
232 struct r2net_sock_container *sc)
234 sc->sc_tv_status_total = ktime_add(sc->sc_tv_status_total,
235 ktime_sub(ktime_get(),
236 nst->st_status_time));
237 sc->sc_tv_send_total = ktime_add(sc->sc_tv_send_total,
238 ktime_sub(nst->st_status_time,
240 sc->sc_tv_acquiry_total = ktime_add(sc->sc_tv_acquiry_total,
241 ktime_sub(nst->st_send_time,
246 static void r2net_update_recv_stats(struct r2net_sock_container *sc)
248 sc->sc_tv_process_total = ktime_add(sc->sc_tv_process_total,
249 r2net_get_func_run_time(sc));
255 # define r2net_update_send_stats(a, b)
257 # define r2net_update_recv_stats(sc)
259 #endif /* CONFIG_RAMSTER_FS_STATS */
261 static inline int r2net_reconnect_delay(void)
263 return r2nm_single_cluster->cl_reconnect_delay_ms;
266 static inline int r2net_keepalive_delay(void)
268 return r2nm_single_cluster->cl_keepalive_delay_ms;
271 static inline int r2net_idle_timeout(void)
273 return r2nm_single_cluster->cl_idle_timeout_ms;
276 static inline int r2net_sys_err_to_errno(enum r2net_system_error err)
279 BUG_ON(err >= R2NET_ERR_MAX);
280 trans = r2net_sys_err_translations[err];
282 /* Just in case we mess up the translation table above */
283 BUG_ON(err != R2NET_ERR_NONE && trans == 0);
287 struct r2net_node *r2net_nn_from_num(u8 node_num)
289 BUG_ON(node_num >= ARRAY_SIZE(r2net_nodes));
290 return &r2net_nodes[node_num];
293 static u8 r2net_num_from_nn(struct r2net_node *nn)
296 return nn - r2net_nodes;
299 /* ------------------------------------------------------------ */
301 static int r2net_prep_nsw(struct r2net_node *nn, struct r2net_status_wait *nsw)
306 if (!idr_pre_get(&nn->nn_status_idr, GFP_ATOMIC)) {
310 spin_lock(&nn->nn_lock);
311 ret = idr_get_new(&nn->nn_status_idr, nsw, &nsw->ns_id);
313 list_add_tail(&nsw->ns_node_item,
314 &nn->nn_status_list);
315 spin_unlock(&nn->nn_lock);
316 } while (ret == -EAGAIN);
319 init_waitqueue_head(&nsw->ns_wq);
320 nsw->ns_sys_status = R2NET_ERR_NONE;
327 static void r2net_complete_nsw_locked(struct r2net_node *nn,
328 struct r2net_status_wait *nsw,
329 enum r2net_system_error sys_status,
332 assert_spin_locked(&nn->nn_lock);
334 if (!list_empty(&nsw->ns_node_item)) {
335 list_del_init(&nsw->ns_node_item);
336 nsw->ns_sys_status = sys_status;
337 nsw->ns_status = status;
338 idr_remove(&nn->nn_status_idr, nsw->ns_id);
339 wake_up(&nsw->ns_wq);
343 static void r2net_complete_nsw(struct r2net_node *nn,
344 struct r2net_status_wait *nsw,
345 u64 id, enum r2net_system_error sys_status,
348 spin_lock(&nn->nn_lock);
353 nsw = idr_find(&nn->nn_status_idr, id);
358 r2net_complete_nsw_locked(nn, nsw, sys_status, status);
361 spin_unlock(&nn->nn_lock);
365 static void r2net_complete_nodes_nsw(struct r2net_node *nn)
367 struct r2net_status_wait *nsw, *tmp;
368 unsigned int num_kills = 0;
370 assert_spin_locked(&nn->nn_lock);
372 list_for_each_entry_safe(nsw, tmp, &nn->nn_status_list, ns_node_item) {
373 r2net_complete_nsw_locked(nn, nsw, R2NET_ERR_DIED, 0);
377 mlog(0, "completed %d messages for node %u\n", num_kills,
378 r2net_num_from_nn(nn));
381 static int r2net_nsw_completed(struct r2net_node *nn,
382 struct r2net_status_wait *nsw)
385 spin_lock(&nn->nn_lock);
386 completed = list_empty(&nsw->ns_node_item);
387 spin_unlock(&nn->nn_lock);
391 /* ------------------------------------------------------------ */
393 static void sc_kref_release(struct kref *kref)
395 struct r2net_sock_container *sc = container_of(kref,
396 struct r2net_sock_container, sc_kref);
397 BUG_ON(timer_pending(&sc->sc_idle_timeout));
399 sclog(sc, "releasing\n");
402 sock_release(sc->sc_sock);
406 r2nm_undepend_item(&sc->sc_node->nd_item);
407 r2nm_node_put(sc->sc_node);
410 r2net_debug_del_sc(sc);
414 static void sc_put(struct r2net_sock_container *sc)
417 kref_put(&sc->sc_kref, sc_kref_release);
419 static void sc_get(struct r2net_sock_container *sc)
422 kref_get(&sc->sc_kref);
424 static struct r2net_sock_container *sc_alloc(struct r2nm_node *node)
426 struct r2net_sock_container *sc, *ret = NULL;
427 struct page *page = NULL;
430 page = alloc_page(GFP_NOFS);
431 sc = kzalloc(sizeof(*sc), GFP_NOFS);
432 if (sc == NULL || page == NULL)
435 kref_init(&sc->sc_kref);
439 /* pin the node item of the remote node */
440 status = r2nm_depend_item(&node->nd_item);
446 INIT_WORK(&sc->sc_connect_work, r2net_sc_connect_completed);
447 INIT_WORK(&sc->sc_rx_work, r2net_rx_until_empty);
448 INIT_WORK(&sc->sc_shutdown_work, r2net_shutdown_sc);
449 INIT_DELAYED_WORK(&sc->sc_keepalive_work, r2net_sc_send_keep_req);
451 init_timer(&sc->sc_idle_timeout);
452 sc->sc_idle_timeout.function = r2net_idle_timer;
453 sc->sc_idle_timeout.data = (unsigned long)sc;
455 sclog(sc, "alloced\n");
459 r2net_debug_add_sc(sc);
471 /* ------------------------------------------------------------ */
473 static void r2net_sc_queue_work(struct r2net_sock_container *sc,
474 struct work_struct *work)
477 if (!queue_work(r2net_wq, work))
480 static void r2net_sc_queue_delayed_work(struct r2net_sock_container *sc,
481 struct delayed_work *work,
485 if (!queue_delayed_work(r2net_wq, work, delay))
488 static void r2net_sc_cancel_delayed_work(struct r2net_sock_container *sc,
489 struct delayed_work *work)
491 if (cancel_delayed_work(work))
495 static atomic_t r2net_connected_peers = ATOMIC_INIT(0);
497 int r2net_num_connected_peers(void)
499 return atomic_read(&r2net_connected_peers);
502 static void r2net_set_nn_state(struct r2net_node *nn,
503 struct r2net_sock_container *sc,
504 unsigned valid, int err)
506 int was_valid = nn->nn_sc_valid;
507 int was_err = nn->nn_persistent_error;
508 struct r2net_sock_container *old_sc = nn->nn_sc;
510 assert_spin_locked(&nn->nn_lock);
513 atomic_dec(&r2net_connected_peers);
514 else if (!old_sc && sc)
515 atomic_inc(&r2net_connected_peers);
517 /* the node num comparison and single connect/accept path should stop
518 * an non-null sc from being overwritten with another */
519 BUG_ON(sc && nn->nn_sc && nn->nn_sc != sc);
520 mlog_bug_on_msg(err && valid, "err %d valid %u\n", err, valid);
521 mlog_bug_on_msg(valid && !sc, "valid %u sc %p\n", valid, sc);
523 if (was_valid && !valid && err == 0)
526 mlog(ML_CONN, "node %u sc: %p -> %p, valid %u -> %u, err %d -> %d\n",
527 r2net_num_from_nn(nn), nn->nn_sc, sc, nn->nn_sc_valid, valid,
528 nn->nn_persistent_error, err);
531 nn->nn_sc_valid = valid ? 1 : 0;
532 nn->nn_persistent_error = err;
534 /* mirrors r2net_tx_can_proceed() */
535 if (nn->nn_persistent_error || nn->nn_sc_valid)
536 wake_up(&nn->nn_sc_wq);
538 if (!was_err && nn->nn_persistent_error) {
539 queue_delayed_work(r2net_wq, &nn->nn_still_up,
540 msecs_to_jiffies(R2NET_QUORUM_DELAY_MS));
543 if (was_valid && !valid) {
544 pr_notice("ramster: No longer connected to " SC_NODEF_FMT "\n",
545 old_sc->sc_node->nd_name, old_sc->sc_node->nd_num,
546 &old_sc->sc_node->nd_ipv4_address,
547 ntohs(old_sc->sc_node->nd_ipv4_port));
548 r2net_complete_nodes_nsw(nn);
551 if (!was_valid && valid) {
552 cancel_delayed_work(&nn->nn_connect_expired);
553 pr_notice("ramster: %s " SC_NODEF_FMT "\n",
554 r2nm_this_node() > sc->sc_node->nd_num ?
555 "Connected to" : "Accepted connection from",
556 sc->sc_node->nd_name, sc->sc_node->nd_num,
557 &sc->sc_node->nd_ipv4_address,
558 ntohs(sc->sc_node->nd_ipv4_port));
561 /* trigger the connecting worker func as long as we're not valid,
562 * it will back off if it shouldn't connect. This can be called
563 * from node config teardown and so needs to be careful about
564 * the work queue actually being up. */
565 if (!valid && r2net_wq) {
567 /* delay if we're within a RECONNECT_DELAY of the
569 delay = (nn->nn_last_connect_attempt +
570 msecs_to_jiffies(r2net_reconnect_delay()))
572 if (delay > msecs_to_jiffies(r2net_reconnect_delay()))
574 mlog(ML_CONN, "queueing conn attempt in %lu jiffies\n", delay);
575 queue_delayed_work(r2net_wq, &nn->nn_connect_work, delay);
578 * Delay the expired work after idle timeout.
580 * We might have lots of failed connection attempts that run
581 * through here but we only cancel the connect_expired work when
582 * a connection attempt succeeds. So only the first enqueue of
583 * the connect_expired work will do anything. The rest will see
584 * that it's already queued and do nothing.
586 delay += msecs_to_jiffies(r2net_idle_timeout());
587 queue_delayed_work(r2net_wq, &nn->nn_connect_expired, delay);
590 /* keep track of the nn's sc ref for the caller */
591 if ((old_sc == NULL) && sc)
593 if (old_sc && (old_sc != sc)) {
594 r2net_sc_queue_work(old_sc, &old_sc->sc_shutdown_work);
599 /* see r2net_register_callbacks() */
600 static void r2net_data_ready(struct sock *sk, int bytes)
602 void (*ready)(struct sock *sk, int bytes);
604 read_lock(&sk->sk_callback_lock);
605 if (sk->sk_user_data) {
606 struct r2net_sock_container *sc = sk->sk_user_data;
607 sclog(sc, "data_ready hit\n");
608 r2net_set_data_ready_time(sc);
609 r2net_sc_queue_work(sc, &sc->sc_rx_work);
610 ready = sc->sc_data_ready;
612 ready = sk->sk_data_ready;
614 read_unlock(&sk->sk_callback_lock);
619 /* see r2net_register_callbacks() */
620 static void r2net_state_change(struct sock *sk)
622 void (*state_change)(struct sock *sk);
623 struct r2net_sock_container *sc;
625 read_lock(&sk->sk_callback_lock);
626 sc = sk->sk_user_data;
628 state_change = sk->sk_state_change;
632 sclog(sc, "state_change to %d\n", sk->sk_state);
634 state_change = sc->sc_state_change;
636 switch (sk->sk_state) {
638 /* ignore connecting sockets as they make progress */
642 case TCP_ESTABLISHED:
643 r2net_sc_queue_work(sc, &sc->sc_connect_work);
646 pr_info("ramster: Connection to "
647 SC_NODEF_FMT " shutdown, state %d\n",
648 sc->sc_node->nd_name, sc->sc_node->nd_num,
649 &sc->sc_node->nd_ipv4_address,
650 ntohs(sc->sc_node->nd_ipv4_port), sk->sk_state);
651 r2net_sc_queue_work(sc, &sc->sc_shutdown_work);
656 read_unlock(&sk->sk_callback_lock);
661 * we register callbacks so we can queue work on events before calling
662 * the original callbacks. our callbacks are careful to test user_data
663 * to discover when they've reaced with r2net_unregister_callbacks().
665 static void r2net_register_callbacks(struct sock *sk,
666 struct r2net_sock_container *sc)
668 write_lock_bh(&sk->sk_callback_lock);
670 /* accepted sockets inherit the old listen socket data ready */
671 if (sk->sk_data_ready == r2net_listen_data_ready) {
672 sk->sk_data_ready = sk->sk_user_data;
673 sk->sk_user_data = NULL;
676 BUG_ON(sk->sk_user_data != NULL);
677 sk->sk_user_data = sc;
680 sc->sc_data_ready = sk->sk_data_ready;
681 sc->sc_state_change = sk->sk_state_change;
682 sk->sk_data_ready = r2net_data_ready;
683 sk->sk_state_change = r2net_state_change;
685 mutex_init(&sc->sc_send_lock);
687 write_unlock_bh(&sk->sk_callback_lock);
690 static int r2net_unregister_callbacks(struct sock *sk,
691 struct r2net_sock_container *sc)
695 write_lock_bh(&sk->sk_callback_lock);
696 if (sk->sk_user_data == sc) {
698 sk->sk_user_data = NULL;
699 sk->sk_data_ready = sc->sc_data_ready;
700 sk->sk_state_change = sc->sc_state_change;
702 write_unlock_bh(&sk->sk_callback_lock);
708 * this is a little helper that is called by callers who have seen a problem
709 * with an sc and want to detach it from the nn if someone already hasn't beat
710 * them to it. if an error is given then the shutdown will be persistent
711 * and pending transmits will be canceled.
713 static void r2net_ensure_shutdown(struct r2net_node *nn,
714 struct r2net_sock_container *sc,
717 spin_lock(&nn->nn_lock);
719 r2net_set_nn_state(nn, NULL, 0, err);
720 spin_unlock(&nn->nn_lock);
724 * This work queue function performs the blocking parts of socket shutdown. A
725 * few paths lead here. set_nn_state will trigger this callback if it sees an
726 * sc detached from the nn. state_change will also trigger this callback
727 * directly when it sees errors. In that case we need to call set_nn_state
728 * ourselves as state_change couldn't get the nn_lock and call set_nn_state
731 static void r2net_shutdown_sc(struct work_struct *work)
733 struct r2net_sock_container *sc =
734 container_of(work, struct r2net_sock_container,
736 struct r2net_node *nn = r2net_nn_from_num(sc->sc_node->nd_num);
738 sclog(sc, "shutting down\n");
740 /* drop the callbacks ref and call shutdown only once */
741 if (r2net_unregister_callbacks(sc->sc_sock->sk, sc)) {
742 /* we shouldn't flush as we're in the thread, the
743 * races with pending sc work structs are harmless */
744 del_timer_sync(&sc->sc_idle_timeout);
745 r2net_sc_cancel_delayed_work(sc, &sc->sc_keepalive_work);
747 kernel_sock_shutdown(sc->sc_sock, SHUT_RDWR);
750 /* not fatal so failed connects before the other guy has our
751 * heartbeat can be retried */
752 r2net_ensure_shutdown(nn, sc, 0);
756 /* ------------------------------------------------------------ */
758 static int r2net_handler_cmp(struct r2net_msg_handler *nmh, u32 msg_type,
761 int ret = memcmp(&nmh->nh_key, &key, sizeof(key));
764 ret = memcmp(&nmh->nh_msg_type, &msg_type, sizeof(msg_type));
769 static struct r2net_msg_handler *
770 r2net_handler_tree_lookup(u32 msg_type, u32 key, struct rb_node ***ret_p,
771 struct rb_node **ret_parent)
773 struct rb_node **p = &r2net_handler_tree.rb_node;
774 struct rb_node *parent = NULL;
775 struct r2net_msg_handler *nmh, *ret = NULL;
780 nmh = rb_entry(parent, struct r2net_msg_handler, nh_node);
781 cmp = r2net_handler_cmp(nmh, msg_type, key);
795 if (ret_parent != NULL)
796 *ret_parent = parent;
801 static void r2net_handler_kref_release(struct kref *kref)
803 struct r2net_msg_handler *nmh;
804 nmh = container_of(kref, struct r2net_msg_handler, nh_kref);
809 static void r2net_handler_put(struct r2net_msg_handler *nmh)
811 kref_put(&nmh->nh_kref, r2net_handler_kref_release);
814 /* max_len is protection for the handler func. incoming messages won't
815 * be given to the handler if their payload is longer than the max. */
816 int r2net_register_handler(u32 msg_type, u32 key, u32 max_len,
817 r2net_msg_handler_func *func, void *data,
818 r2net_post_msg_handler_func *post_func,
819 struct list_head *unreg_list)
821 struct r2net_msg_handler *nmh = NULL;
822 struct rb_node **p, *parent;
825 if (max_len > R2NET_MAX_PAYLOAD_BYTES) {
826 mlog(0, "max_len for message handler out of range: %u\n",
833 mlog(0, "no message type provided: %u, %p\n", msg_type, func);
839 mlog(0, "no message handler provided: %u, %p\n",
845 nmh = kzalloc(sizeof(struct r2net_msg_handler), GFP_NOFS);
852 nmh->nh_func_data = data;
853 nmh->nh_post_func = post_func;
854 nmh->nh_msg_type = msg_type;
855 nmh->nh_max_len = max_len;
857 /* the tree and list get this ref.. they're both removed in
858 * unregister when this ref is dropped */
859 kref_init(&nmh->nh_kref);
860 INIT_LIST_HEAD(&nmh->nh_unregister_item);
862 write_lock(&r2net_handler_lock);
863 if (r2net_handler_tree_lookup(msg_type, key, &p, &parent))
866 rb_link_node(&nmh->nh_node, parent, p);
867 rb_insert_color(&nmh->nh_node, &r2net_handler_tree);
868 list_add_tail(&nmh->nh_unregister_item, unreg_list);
870 mlog(ML_TCP, "registered handler func %p type %u key %08x\n",
871 func, msg_type, key);
872 /* we've had some trouble with handlers seemingly vanishing. */
873 mlog_bug_on_msg(r2net_handler_tree_lookup(msg_type, key, &p,
875 "couldn't find handler we *just* registered "
876 "for type %u key %08x\n", msg_type, key);
878 write_unlock(&r2net_handler_lock);
888 EXPORT_SYMBOL_GPL(r2net_register_handler);
890 void r2net_unregister_handler_list(struct list_head *list)
892 struct r2net_msg_handler *nmh, *n;
894 write_lock(&r2net_handler_lock);
895 list_for_each_entry_safe(nmh, n, list, nh_unregister_item) {
896 mlog(ML_TCP, "unregistering handler func %p type %u key %08x\n",
897 nmh->nh_func, nmh->nh_msg_type, nmh->nh_key);
898 rb_erase(&nmh->nh_node, &r2net_handler_tree);
899 list_del_init(&nmh->nh_unregister_item);
900 kref_put(&nmh->nh_kref, r2net_handler_kref_release);
902 write_unlock(&r2net_handler_lock);
904 EXPORT_SYMBOL_GPL(r2net_unregister_handler_list);
906 static struct r2net_msg_handler *r2net_handler_get(u32 msg_type, u32 key)
908 struct r2net_msg_handler *nmh;
910 read_lock(&r2net_handler_lock);
911 nmh = r2net_handler_tree_lookup(msg_type, key, NULL, NULL);
913 kref_get(&nmh->nh_kref);
914 read_unlock(&r2net_handler_lock);
919 /* ------------------------------------------------------------ */
921 static int r2net_recv_tcp_msg(struct socket *sock, void *data, size_t len)
929 struct msghdr msg = {
931 .msg_iov = (struct iovec *)&vec,
932 .msg_flags = MSG_DONTWAIT,
937 ret = sock_recvmsg(sock, &msg, len, msg.msg_flags);
943 static int r2net_send_tcp_msg(struct socket *sock, struct kvec *vec,
944 size_t veclen, size_t total)
948 struct msghdr msg = {
949 .msg_iov = (struct iovec *)vec,
950 .msg_iovlen = veclen,
960 ret = sock_sendmsg(sock, &msg, total);
963 mlog(ML_ERROR, "sendmsg returned %d instead of %zu\n", ret,
966 ret = -EPIPE; /* should be smarter, I bet */
973 mlog(0, "returning error: %d\n", ret);
977 static void r2net_sendpage(struct r2net_sock_container *sc,
978 void *kmalloced_virt,
981 struct r2net_node *nn = r2net_nn_from_num(sc->sc_node->nd_num);
985 mutex_lock(&sc->sc_send_lock);
986 ret = sc->sc_sock->ops->sendpage(sc->sc_sock,
987 virt_to_page(kmalloced_virt),
988 (long)kmalloced_virt & ~PAGE_MASK,
990 mutex_unlock(&sc->sc_send_lock);
993 if (ret == (ssize_t)-EAGAIN) {
994 mlog(0, "sendpage of size %zu to " SC_NODEF_FMT
995 " returned EAGAIN\n", size, sc->sc_node->nd_name,
997 &sc->sc_node->nd_ipv4_address,
998 ntohs(sc->sc_node->nd_ipv4_port));
1002 mlog(ML_ERROR, "sendpage of size %zu to " SC_NODEF_FMT
1003 " failed with %zd\n", size, sc->sc_node->nd_name,
1004 sc->sc_node->nd_num, &sc->sc_node->nd_ipv4_address,
1005 ntohs(sc->sc_node->nd_ipv4_port), ret);
1006 r2net_ensure_shutdown(nn, sc, 0);
1011 static void r2net_init_msg(struct r2net_msg *msg, u16 data_len,
1012 u16 msg_type, u32 key)
1014 memset(msg, 0, sizeof(struct r2net_msg));
1015 msg->magic = cpu_to_be16(R2NET_MSG_MAGIC);
1016 msg->data_len = cpu_to_be16(data_len);
1017 msg->msg_type = cpu_to_be16(msg_type);
1018 msg->sys_status = cpu_to_be32(R2NET_ERR_NONE);
1020 msg->key = cpu_to_be32(key);
1023 static int r2net_tx_can_proceed(struct r2net_node *nn,
1024 struct r2net_sock_container **sc_ret,
1029 spin_lock(&nn->nn_lock);
1030 if (nn->nn_persistent_error) {
1033 *error = nn->nn_persistent_error;
1034 } else if (nn->nn_sc_valid) {
1035 kref_get(&nn->nn_sc->sc_kref);
1038 *sc_ret = nn->nn_sc;
1041 spin_unlock(&nn->nn_lock);
1046 /* Get a map of all nodes to which this node is currently connected to */
1047 void r2net_fill_node_map(unsigned long *map, unsigned bytes)
1049 struct r2net_sock_container *sc;
1052 BUG_ON(bytes < (BITS_TO_LONGS(R2NM_MAX_NODES) * sizeof(unsigned long)));
1054 memset(map, 0, bytes);
1055 for (node = 0; node < R2NM_MAX_NODES; ++node) {
1056 r2net_tx_can_proceed(r2net_nn_from_num(node), &sc, &ret);
1063 EXPORT_SYMBOL_GPL(r2net_fill_node_map);
1065 int r2net_send_message_vec(u32 msg_type, u32 key, struct kvec *caller_vec,
1066 size_t caller_veclen, u8 target_node, int *status)
1069 struct r2net_msg *msg = NULL;
1070 size_t veclen, caller_bytes = 0;
1071 struct kvec *vec = NULL;
1072 struct r2net_sock_container *sc = NULL;
1073 struct r2net_node *nn = r2net_nn_from_num(target_node);
1074 struct r2net_status_wait nsw = {
1075 .ns_node_item = LIST_HEAD_INIT(nsw.ns_node_item),
1077 struct r2net_send_tracking nst;
1079 /* this may be a general bug fix */
1080 init_waitqueue_head(&nsw.ns_wq);
1082 r2net_init_nst(&nst, msg_type, key, current, target_node);
1084 if (r2net_wq == NULL) {
1085 mlog(0, "attempt to tx without r2netd running\n");
1090 if (caller_veclen == 0) {
1091 mlog(0, "bad kvec array length\n");
1096 caller_bytes = iov_length((struct iovec *)caller_vec, caller_veclen);
1097 if (caller_bytes > R2NET_MAX_PAYLOAD_BYTES) {
1098 mlog(0, "total payload len %zu too large\n", caller_bytes);
1103 if (target_node == r2nm_this_node()) {
1108 r2net_debug_add_nst(&nst);
1110 r2net_set_nst_sock_time(&nst);
1112 wait_event(nn->nn_sc_wq, r2net_tx_can_proceed(nn, &sc, &ret));
1116 r2net_set_nst_sock_container(&nst, sc);
1118 veclen = caller_veclen + 1;
1119 vec = kmalloc(sizeof(struct kvec) * veclen, GFP_ATOMIC);
1121 mlog(0, "failed to %zu element kvec!\n", veclen);
1126 msg = kmalloc(sizeof(struct r2net_msg), GFP_ATOMIC);
1128 mlog(0, "failed to allocate a r2net_msg!\n");
1133 r2net_init_msg(msg, caller_bytes, msg_type, key);
1135 vec[0].iov_len = sizeof(struct r2net_msg);
1136 vec[0].iov_base = msg;
1137 memcpy(&vec[1], caller_vec, caller_veclen * sizeof(struct kvec));
1139 ret = r2net_prep_nsw(nn, &nsw);
1143 msg->msg_num = cpu_to_be32(nsw.ns_id);
1144 r2net_set_nst_msg_id(&nst, nsw.ns_id);
1146 r2net_set_nst_send_time(&nst);
1148 /* finally, convert the message header to network byte-order
1150 mutex_lock(&sc->sc_send_lock);
1151 ret = r2net_send_tcp_msg(sc->sc_sock, vec, veclen,
1152 sizeof(struct r2net_msg) + caller_bytes);
1153 mutex_unlock(&sc->sc_send_lock);
1154 msglog(msg, "sending returned %d\n", ret);
1156 mlog(0, "error returned from r2net_send_tcp_msg=%d\n", ret);
1160 /* wait on other node's handler */
1161 r2net_set_nst_status_time(&nst);
1162 wait_event(nsw.ns_wq, r2net_nsw_completed(nn, &nsw) ||
1163 nn->nn_persistent_error || !nn->nn_sc_valid);
1165 r2net_update_send_stats(&nst, sc);
1167 /* Note that we avoid overwriting the callers status return
1168 * variable if a system error was reported on the other
1169 * side. Callers beware. */
1170 ret = r2net_sys_err_to_errno(nsw.ns_sys_status);
1172 *status = nsw.ns_status;
1174 mlog(0, "woken, returning system status %d, user status %d\n",
1175 ret, nsw.ns_status);
1177 r2net_debug_del_nst(&nst); /* must be before dropping sc and node */
1182 r2net_complete_nsw(nn, &nsw, 0, 0, 0);
1185 EXPORT_SYMBOL_GPL(r2net_send_message_vec);
1187 int r2net_send_message(u32 msg_type, u32 key, void *data, u32 len,
1188 u8 target_node, int *status)
1194 return r2net_send_message_vec(msg_type, key, &vec, 1,
1195 target_node, status);
1197 EXPORT_SYMBOL_GPL(r2net_send_message);
1199 static int r2net_send_status_magic(struct socket *sock, struct r2net_msg *hdr,
1200 enum r2net_system_error syserr, int err)
1204 .iov_len = sizeof(struct r2net_msg),
1207 BUG_ON(syserr >= R2NET_ERR_MAX);
1209 /* leave other fields intact from the incoming message, msg_num
1211 hdr->sys_status = cpu_to_be32(syserr);
1212 hdr->status = cpu_to_be32(err);
1213 /* twiddle the magic */
1214 hdr->magic = cpu_to_be16(R2NET_MSG_STATUS_MAGIC);
1217 msglog(hdr, "about to send status magic %d\n", err);
1218 /* hdr has been in host byteorder this whole time */
1219 return r2net_send_tcp_msg(sock, &vec, 1, sizeof(struct r2net_msg));
1223 * "data magic" is a long version of "status magic" where the message
1224 * payload actually contains data to be passed in reply to certain messages
1226 static int r2net_send_data_magic(struct r2net_sock_container *sc,
1227 struct r2net_msg *hdr,
1228 void *data, size_t data_len,
1229 enum r2net_system_error syserr, int err)
1234 vec[0].iov_base = hdr;
1235 vec[0].iov_len = sizeof(struct r2net_msg);
1236 vec[1].iov_base = data;
1237 vec[1].iov_len = data_len;
1239 BUG_ON(syserr >= R2NET_ERR_MAX);
1241 /* leave other fields intact from the incoming message, msg_num
1243 hdr->sys_status = cpu_to_be32(syserr);
1244 hdr->status = cpu_to_be32(err);
1245 hdr->magic = cpu_to_be16(R2NET_MSG_DATA_MAGIC); /* twiddle magic */
1246 hdr->data_len = cpu_to_be16(data_len);
1248 msglog(hdr, "about to send data magic %d\n", err);
1249 /* hdr has been in host byteorder this whole time */
1250 ret = r2net_send_tcp_msg(sc->sc_sock, vec, 2,
1251 sizeof(struct r2net_msg) + data_len);
1256 * called by a message handler to convert an otherwise normal reply
1257 * message into a "data magic" message
1259 void r2net_force_data_magic(struct r2net_msg *hdr, u16 msgtype, u32 msgkey)
1261 hdr->magic = cpu_to_be16(R2NET_MSG_DATA_MAGIC);
1262 hdr->msg_type = cpu_to_be16(msgtype);
1263 hdr->key = cpu_to_be32(msgkey);
1266 /* this returns -errno if the header was unknown or too large, etc.
1267 * after this is called the buffer us reused for the next message */
1268 static int r2net_process_message(struct r2net_sock_container *sc,
1269 struct r2net_msg *hdr)
1271 struct r2net_node *nn = r2net_nn_from_num(sc->sc_node->nd_num);
1272 int ret = 0, handler_status;
1273 enum r2net_system_error syserr;
1274 struct r2net_msg_handler *nmh = NULL;
1275 void *ret_data = NULL;
1278 msglog(hdr, "processing message\n");
1280 r2net_sc_postpone_idle(sc);
1282 switch (be16_to_cpu(hdr->magic)) {
1284 case R2NET_MSG_STATUS_MAGIC:
1285 /* special type for returning message status */
1286 r2net_complete_nsw(nn, NULL, be32_to_cpu(hdr->msg_num),
1287 be32_to_cpu(hdr->sys_status),
1288 be32_to_cpu(hdr->status));
1290 case R2NET_MSG_KEEP_REQ_MAGIC:
1291 r2net_sendpage(sc, r2net_keep_resp, sizeof(*r2net_keep_resp));
1293 case R2NET_MSG_KEEP_RESP_MAGIC:
1295 case R2NET_MSG_MAGIC:
1297 case R2NET_MSG_DATA_MAGIC:
1299 * unlike a normal status magic, a data magic DOES
1300 * (MUST) have a handler, so the control flow is
1301 * a little funky here as a result
1306 msglog(hdr, "bad magic\n");
1312 /* find a handler for it */
1314 nmh = r2net_handler_get(be16_to_cpu(hdr->msg_type),
1315 be32_to_cpu(hdr->key));
1317 mlog(ML_TCP, "couldn't find handler for type %u key %08x\n",
1318 be16_to_cpu(hdr->msg_type), be32_to_cpu(hdr->key));
1319 syserr = R2NET_ERR_NO_HNDLR;
1323 syserr = R2NET_ERR_NONE;
1325 if (be16_to_cpu(hdr->data_len) > nmh->nh_max_len)
1326 syserr = R2NET_ERR_OVERFLOW;
1328 if (syserr != R2NET_ERR_NONE) {
1329 pr_err("ramster_r2net, message length problem\n");
1333 r2net_set_func_start_time(sc);
1334 sc->sc_msg_key = be32_to_cpu(hdr->key);
1335 sc->sc_msg_type = be16_to_cpu(hdr->msg_type);
1336 handler_status = (nmh->nh_func)(hdr, sizeof(struct r2net_msg) +
1337 be16_to_cpu(hdr->data_len),
1338 nmh->nh_func_data, &ret_data);
1341 * handler handled data sent in reply to request
1342 * so complete the transaction
1344 r2net_complete_nsw(nn, NULL, be32_to_cpu(hdr->msg_num),
1345 be32_to_cpu(hdr->sys_status), handler_status);
1349 * handler changed magic to DATA_MAGIC to reply to request for data,
1350 * implies ret_data points to data to return and handler_status
1351 * is the number of bytes of data
1353 if (be16_to_cpu(hdr->magic) == R2NET_MSG_DATA_MAGIC) {
1354 ret = r2net_send_data_magic(sc, hdr,
1355 ret_data, handler_status,
1358 mlog(0, "sending data reply %d, syserr %d returned %d\n",
1359 handler_status, syserr, ret);
1360 r2net_set_func_stop_time(sc);
1362 r2net_update_recv_stats(sc);
1365 r2net_set_func_stop_time(sc);
1367 r2net_update_recv_stats(sc);
1370 /* this destroys the hdr, so don't use it after this */
1371 mutex_lock(&sc->sc_send_lock);
1372 ret = r2net_send_status_magic(sc->sc_sock, hdr, syserr,
1374 mutex_unlock(&sc->sc_send_lock);
1376 mlog(0, "sending handler status %d, syserr %d returned %d\n",
1377 handler_status, syserr, ret);
1380 BUG_ON(ret_data != NULL && nmh->nh_post_func == NULL);
1381 if (nmh->nh_post_func)
1382 (nmh->nh_post_func)(handler_status, nmh->nh_func_data,
1388 r2net_handler_put(nmh);
1392 static int r2net_check_handshake(struct r2net_sock_container *sc)
1394 struct r2net_handshake *hand = page_address(sc->sc_page);
1395 struct r2net_node *nn = r2net_nn_from_num(sc->sc_node->nd_num);
1397 if (hand->protocol_version != cpu_to_be64(R2NET_PROTOCOL_VERSION)) {
1398 pr_notice("ramster: " SC_NODEF_FMT " Advertised net "
1399 "protocol version %llu but %llu is required. "
1400 "Disconnecting.\n", sc->sc_node->nd_name,
1401 sc->sc_node->nd_num, &sc->sc_node->nd_ipv4_address,
1402 ntohs(sc->sc_node->nd_ipv4_port),
1403 (unsigned long long)be64_to_cpu(hand->protocol_version),
1404 R2NET_PROTOCOL_VERSION);
1406 /* don't bother reconnecting if its the wrong version. */
1407 r2net_ensure_shutdown(nn, sc, -ENOTCONN);
1412 * Ensure timeouts are consistent with other nodes, otherwise
1413 * we can end up with one node thinking that the other must be down,
1414 * but isn't. This can ultimately cause corruption.
1416 if (be32_to_cpu(hand->r2net_idle_timeout_ms) !=
1417 r2net_idle_timeout()) {
1418 pr_notice("ramster: " SC_NODEF_FMT " uses a network "
1419 "idle timeout of %u ms, but we use %u ms locally. "
1420 "Disconnecting.\n", sc->sc_node->nd_name,
1421 sc->sc_node->nd_num, &sc->sc_node->nd_ipv4_address,
1422 ntohs(sc->sc_node->nd_ipv4_port),
1423 be32_to_cpu(hand->r2net_idle_timeout_ms),
1424 r2net_idle_timeout());
1425 r2net_ensure_shutdown(nn, sc, -ENOTCONN);
1429 if (be32_to_cpu(hand->r2net_keepalive_delay_ms) !=
1430 r2net_keepalive_delay()) {
1431 pr_notice("ramster: " SC_NODEF_FMT " uses a keepalive "
1432 "delay of %u ms, but we use %u ms locally. "
1433 "Disconnecting.\n", sc->sc_node->nd_name,
1434 sc->sc_node->nd_num, &sc->sc_node->nd_ipv4_address,
1435 ntohs(sc->sc_node->nd_ipv4_port),
1436 be32_to_cpu(hand->r2net_keepalive_delay_ms),
1437 r2net_keepalive_delay());
1438 r2net_ensure_shutdown(nn, sc, -ENOTCONN);
1442 if (be32_to_cpu(hand->r2hb_heartbeat_timeout_ms) !=
1443 R2HB_MAX_WRITE_TIMEOUT_MS) {
1444 pr_notice("ramster: " SC_NODEF_FMT " uses a heartbeat "
1445 "timeout of %u ms, but we use %u ms locally. "
1446 "Disconnecting.\n", sc->sc_node->nd_name,
1447 sc->sc_node->nd_num, &sc->sc_node->nd_ipv4_address,
1448 ntohs(sc->sc_node->nd_ipv4_port),
1449 be32_to_cpu(hand->r2hb_heartbeat_timeout_ms),
1450 R2HB_MAX_WRITE_TIMEOUT_MS);
1451 r2net_ensure_shutdown(nn, sc, -ENOTCONN);
1455 sc->sc_handshake_ok = 1;
1457 spin_lock(&nn->nn_lock);
1458 /* set valid and queue the idle timers only if it hasn't been
1459 * shut down already */
1460 if (nn->nn_sc == sc) {
1461 r2net_sc_reset_idle_timer(sc);
1462 atomic_set(&nn->nn_timeout, 0);
1463 r2net_set_nn_state(nn, sc, 1, 0);
1465 spin_unlock(&nn->nn_lock);
1467 /* shift everything up as though it wasn't there */
1468 sc->sc_page_off -= sizeof(struct r2net_handshake);
1469 if (sc->sc_page_off)
1470 memmove(hand, hand + 1, sc->sc_page_off);
1475 /* this demuxes the queued rx bytes into header or payload bits and calls
1476 * handlers as each full message is read off the socket. it returns -error,
1477 * == 0 eof, or > 0 for progress made.*/
1478 static int r2net_advance_rx(struct r2net_sock_container *sc)
1480 struct r2net_msg *hdr;
1485 sclog(sc, "receiving\n");
1486 r2net_set_advance_start_time(sc);
1488 if (unlikely(sc->sc_handshake_ok == 0)) {
1489 if (sc->sc_page_off < sizeof(struct r2net_handshake)) {
1490 data = page_address(sc->sc_page) + sc->sc_page_off;
1491 datalen = sizeof(struct r2net_handshake) -
1493 ret = r2net_recv_tcp_msg(sc->sc_sock, data, datalen);
1495 sc->sc_page_off += ret;
1498 if (sc->sc_page_off == sizeof(struct r2net_handshake)) {
1499 r2net_check_handshake(sc);
1500 if (unlikely(sc->sc_handshake_ok == 0))
1506 /* do we need more header? */
1507 if (sc->sc_page_off < sizeof(struct r2net_msg)) {
1508 data = page_address(sc->sc_page) + sc->sc_page_off;
1509 datalen = sizeof(struct r2net_msg) - sc->sc_page_off;
1510 ret = r2net_recv_tcp_msg(sc->sc_sock, data, datalen);
1512 sc->sc_page_off += ret;
1513 /* only swab incoming here.. we can
1514 * only get here once as we cross from
1515 * being under to over */
1516 if (sc->sc_page_off == sizeof(struct r2net_msg)) {
1517 hdr = page_address(sc->sc_page);
1518 if (be16_to_cpu(hdr->data_len) >
1519 R2NET_MAX_PAYLOAD_BYTES)
1521 WARN_ON_ONCE(ret == -EOVERFLOW);
1528 if (sc->sc_page_off < sizeof(struct r2net_msg)) {
1529 /* oof, still don't have a header */
1533 /* this was swabbed above when we first read it */
1534 hdr = page_address(sc->sc_page);
1536 msglog(hdr, "at page_off %zu\n", sc->sc_page_off);
1538 /* do we need more payload? */
1539 if (sc->sc_page_off - sizeof(struct r2net_msg) <
1540 be16_to_cpu(hdr->data_len)) {
1541 /* need more payload */
1542 data = page_address(sc->sc_page) + sc->sc_page_off;
1543 datalen = (sizeof(struct r2net_msg) +
1544 be16_to_cpu(hdr->data_len)) -
1546 ret = r2net_recv_tcp_msg(sc->sc_sock, data, datalen);
1548 sc->sc_page_off += ret;
1553 if (sc->sc_page_off - sizeof(struct r2net_msg) ==
1554 be16_to_cpu(hdr->data_len)) {
1555 /* we can only get here once, the first time we read
1556 * the payload.. so set ret to progress if the handler
1557 * works out. after calling this the message is toast */
1558 ret = r2net_process_message(sc, hdr);
1561 sc->sc_page_off = 0;
1565 sclog(sc, "ret = %d\n", ret);
1566 r2net_set_advance_stop_time(sc);
1570 /* this work func is triggerd by data ready. it reads until it can read no
1571 * more. it interprets 0, eof, as fatal. if data_ready hits while we're doing
1572 * our work the work struct will be marked and we'll be called again. */
1573 static void r2net_rx_until_empty(struct work_struct *work)
1575 struct r2net_sock_container *sc =
1576 container_of(work, struct r2net_sock_container, sc_rx_work);
1580 ret = r2net_advance_rx(sc);
1583 if (ret <= 0 && ret != -EAGAIN) {
1584 struct r2net_node *nn = r2net_nn_from_num(sc->sc_node->nd_num);
1585 sclog(sc, "saw error %d, closing\n", ret);
1586 /* not permanent so read failed handshake can retry */
1587 r2net_ensure_shutdown(nn, sc, 0);
1592 static int r2net_set_nodelay(struct socket *sock)
1601 * Dear unsuspecting programmer,
1603 * Don't use sock_setsockopt() for SOL_TCP. It doesn't check its level
1604 * argument and assumes SOL_SOCKET so, say, your TCP_NODELAY will
1605 * silently turn into SO_DEBUG.
1608 * Keeper of hilariously fragile interfaces.
1610 ret = sock->ops->setsockopt(sock, SOL_TCP, TCP_NODELAY,
1611 (char __user *)&val, sizeof(val));
1617 static void r2net_initialize_handshake(void)
1619 r2net_hand->r2hb_heartbeat_timeout_ms = cpu_to_be32(
1620 R2HB_MAX_WRITE_TIMEOUT_MS);
1621 r2net_hand->r2net_idle_timeout_ms = cpu_to_be32(r2net_idle_timeout());
1622 r2net_hand->r2net_keepalive_delay_ms = cpu_to_be32(
1623 r2net_keepalive_delay());
1624 r2net_hand->r2net_reconnect_delay_ms = cpu_to_be32(
1625 r2net_reconnect_delay());
1628 /* ------------------------------------------------------------ */
1630 /* called when a connect completes and after a sock is accepted. the
1631 * rx path will see the response and mark the sc valid */
1632 static void r2net_sc_connect_completed(struct work_struct *work)
1634 struct r2net_sock_container *sc =
1635 container_of(work, struct r2net_sock_container,
1638 mlog(ML_MSG, "sc sending handshake with ver %llu id %llx\n",
1639 (unsigned long long)R2NET_PROTOCOL_VERSION,
1640 (unsigned long long)be64_to_cpu(r2net_hand->connector_id));
1642 r2net_initialize_handshake();
1643 r2net_sendpage(sc, r2net_hand, sizeof(*r2net_hand));
1647 /* this is called as a work_struct func. */
1648 static void r2net_sc_send_keep_req(struct work_struct *work)
1650 struct r2net_sock_container *sc =
1651 container_of(work, struct r2net_sock_container,
1652 sc_keepalive_work.work);
1654 r2net_sendpage(sc, r2net_keep_req, sizeof(*r2net_keep_req));
1658 /* socket shutdown does a del_timer_sync against this as it tears down.
1659 * we can't start this timer until we've got to the point in sc buildup
1660 * where shutdown is going to be involved */
1661 static void r2net_idle_timer(unsigned long data)
1663 struct r2net_sock_container *sc = (struct r2net_sock_container *)data;
1664 struct r2net_node *nn = r2net_nn_from_num(sc->sc_node->nd_num);
1665 #ifdef CONFIG_DEBUG_FS
1666 unsigned long msecs = ktime_to_ms(ktime_get()) -
1667 ktime_to_ms(sc->sc_tv_timer);
1669 unsigned long msecs = r2net_idle_timeout();
1672 pr_notice("ramster: Connection to " SC_NODEF_FMT " has been "
1673 "idle for %lu.%lu secs, shutting it down.\n",
1674 sc->sc_node->nd_name, sc->sc_node->nd_num,
1675 &sc->sc_node->nd_ipv4_address, ntohs(sc->sc_node->nd_ipv4_port),
1676 msecs / 1000, msecs % 1000);
1679 * Initialize the nn_timeout so that the next connection attempt
1680 * will continue in r2net_start_connect.
1682 atomic_set(&nn->nn_timeout, 1);
1683 r2net_sc_queue_work(sc, &sc->sc_shutdown_work);
1686 static void r2net_sc_reset_idle_timer(struct r2net_sock_container *sc)
1688 r2net_sc_cancel_delayed_work(sc, &sc->sc_keepalive_work);
1689 r2net_sc_queue_delayed_work(sc, &sc->sc_keepalive_work,
1690 msecs_to_jiffies(r2net_keepalive_delay()));
1691 r2net_set_sock_timer(sc);
1692 mod_timer(&sc->sc_idle_timeout,
1693 jiffies + msecs_to_jiffies(r2net_idle_timeout()));
1696 static void r2net_sc_postpone_idle(struct r2net_sock_container *sc)
1698 /* Only push out an existing timer */
1699 if (timer_pending(&sc->sc_idle_timeout))
1700 r2net_sc_reset_idle_timer(sc);
1703 /* this work func is kicked whenever a path sets the nn state which doesn't
1704 * have valid set. This includes seeing hb come up, losing a connection,
1705 * having a connect attempt fail, etc. This centralizes the logic which decides
1706 * if a connect attempt should be made or if we should give up and all future
1707 * transmit attempts should fail */
1708 static void r2net_start_connect(struct work_struct *work)
1710 struct r2net_node *nn =
1711 container_of(work, struct r2net_node, nn_connect_work.work);
1712 struct r2net_sock_container *sc = NULL;
1713 struct r2nm_node *node = NULL, *mynode = NULL;
1714 struct socket *sock = NULL;
1715 struct sockaddr_in myaddr = {0, }, remoteaddr = {0, };
1717 unsigned int timeout;
1719 /* if we're greater we initiate tx, otherwise we accept */
1720 if (r2nm_this_node() <= r2net_num_from_nn(nn))
1723 /* watch for racing with tearing a node down */
1724 node = r2nm_get_node_by_num(r2net_num_from_nn(nn));
1730 mynode = r2nm_get_node_by_num(r2nm_this_node());
1731 if (mynode == NULL) {
1736 spin_lock(&nn->nn_lock);
1738 * see if we already have one pending or have given up.
1739 * For nn_timeout, it is set when we close the connection
1740 * because of the idle time out. So it means that we have
1741 * at least connected to that node successfully once,
1742 * now try to connect to it again.
1744 timeout = atomic_read(&nn->nn_timeout);
1745 stop = (nn->nn_sc ||
1746 (nn->nn_persistent_error &&
1747 (nn->nn_persistent_error != -ENOTCONN || timeout == 0)));
1748 spin_unlock(&nn->nn_lock);
1752 nn->nn_last_connect_attempt = jiffies;
1754 sc = sc_alloc(node);
1756 mlog(0, "couldn't allocate sc\n");
1761 ret = sock_create(PF_INET, SOCK_STREAM, IPPROTO_TCP, &sock);
1763 mlog(0, "can't create socket: %d\n", ret);
1766 sc->sc_sock = sock; /* freed by sc_kref_release */
1768 sock->sk->sk_allocation = GFP_ATOMIC;
1770 myaddr.sin_family = AF_INET;
1771 myaddr.sin_addr.s_addr = mynode->nd_ipv4_address;
1772 myaddr.sin_port = htons(0); /* any port */
1774 ret = sock->ops->bind(sock, (struct sockaddr *)&myaddr,
1777 mlog(ML_ERROR, "bind failed with %d at address %pI4\n",
1778 ret, &mynode->nd_ipv4_address);
1782 ret = r2net_set_nodelay(sc->sc_sock);
1784 mlog(ML_ERROR, "setting TCP_NODELAY failed with %d\n", ret);
1788 r2net_register_callbacks(sc->sc_sock->sk, sc);
1790 spin_lock(&nn->nn_lock);
1791 /* handshake completion will set nn->nn_sc_valid */
1792 r2net_set_nn_state(nn, sc, 0, 0);
1793 spin_unlock(&nn->nn_lock);
1795 remoteaddr.sin_family = AF_INET;
1796 remoteaddr.sin_addr.s_addr = node->nd_ipv4_address;
1797 remoteaddr.sin_port = node->nd_ipv4_port;
1799 ret = sc->sc_sock->ops->connect(sc->sc_sock,
1800 (struct sockaddr *)&remoteaddr,
1803 if (ret == -EINPROGRESS)
1808 pr_notice("ramster: Connect attempt to " SC_NODEF_FMT
1809 " failed with errno %d\n", sc->sc_node->nd_name,
1810 sc->sc_node->nd_num, &sc->sc_node->nd_ipv4_address,
1811 ntohs(sc->sc_node->nd_ipv4_port), ret);
1812 /* 0 err so that another will be queued and attempted
1813 * from set_nn_state */
1815 r2net_ensure_shutdown(nn, sc, 0);
1820 r2nm_node_put(node);
1822 r2nm_node_put(mynode);
1827 static void r2net_connect_expired(struct work_struct *work)
1829 struct r2net_node *nn =
1830 container_of(work, struct r2net_node, nn_connect_expired.work);
1832 spin_lock(&nn->nn_lock);
1833 if (!nn->nn_sc_valid) {
1834 pr_notice("ramster: No connection established with "
1835 "node %u after %u.%u seconds, giving up.\n",
1836 r2net_num_from_nn(nn),
1837 r2net_idle_timeout() / 1000,
1838 r2net_idle_timeout() % 1000);
1840 r2net_set_nn_state(nn, NULL, 0, -ENOTCONN);
1842 spin_unlock(&nn->nn_lock);
1845 static void r2net_still_up(struct work_struct *work)
1849 /* ------------------------------------------------------------ */
1851 void r2net_disconnect_node(struct r2nm_node *node)
1853 struct r2net_node *nn = r2net_nn_from_num(node->nd_num);
1855 /* don't reconnect until it's heartbeating again */
1856 spin_lock(&nn->nn_lock);
1857 atomic_set(&nn->nn_timeout, 0);
1858 r2net_set_nn_state(nn, NULL, 0, -ENOTCONN);
1859 spin_unlock(&nn->nn_lock);
1862 cancel_delayed_work(&nn->nn_connect_expired);
1863 cancel_delayed_work(&nn->nn_connect_work);
1864 cancel_delayed_work(&nn->nn_still_up);
1865 flush_workqueue(r2net_wq);
1869 static void r2net_hb_node_down_cb(struct r2nm_node *node, int node_num,
1875 if (node_num != r2nm_this_node())
1876 r2net_disconnect_node(node);
1878 BUG_ON(atomic_read(&r2net_connected_peers) < 0);
1881 static void r2net_hb_node_up_cb(struct r2nm_node *node, int node_num,
1884 struct r2net_node *nn = r2net_nn_from_num(node_num);
1888 /* ensure an immediate connect attempt */
1889 nn->nn_last_connect_attempt = jiffies -
1890 (msecs_to_jiffies(r2net_reconnect_delay()) + 1);
1892 if (node_num != r2nm_this_node()) {
1893 /* believe it or not, accept and node hearbeating testing
1894 * can succeed for this node before we got here.. so
1895 * only use set_nn_state to clear the persistent error
1896 * if that hasn't already happened */
1897 spin_lock(&nn->nn_lock);
1898 atomic_set(&nn->nn_timeout, 0);
1899 if (nn->nn_persistent_error)
1900 r2net_set_nn_state(nn, NULL, 0, 0);
1901 spin_unlock(&nn->nn_lock);
1905 void r2net_unregister_hb_callbacks(void)
1907 r2hb_unregister_callback(NULL, &r2net_hb_up);
1908 r2hb_unregister_callback(NULL, &r2net_hb_down);
1911 int r2net_register_hb_callbacks(void)
1915 r2hb_setup_callback(&r2net_hb_down, R2HB_NODE_DOWN_CB,
1916 r2net_hb_node_down_cb, NULL, R2NET_HB_PRI);
1917 r2hb_setup_callback(&r2net_hb_up, R2HB_NODE_UP_CB,
1918 r2net_hb_node_up_cb, NULL, R2NET_HB_PRI);
1920 ret = r2hb_register_callback(NULL, &r2net_hb_up);
1922 ret = r2hb_register_callback(NULL, &r2net_hb_down);
1925 r2net_unregister_hb_callbacks();
1930 /* ------------------------------------------------------------ */
1932 static int r2net_accept_one(struct socket *sock)
1935 struct sockaddr_in sin;
1936 struct socket *new_sock = NULL;
1937 struct r2nm_node *node = NULL;
1938 struct r2nm_node *local_node = NULL;
1939 struct r2net_sock_container *sc = NULL;
1940 struct r2net_node *nn;
1942 BUG_ON(sock == NULL);
1943 ret = sock_create_lite(sock->sk->sk_family, sock->sk->sk_type,
1944 sock->sk->sk_protocol, &new_sock);
1948 new_sock->type = sock->type;
1949 new_sock->ops = sock->ops;
1950 ret = sock->ops->accept(sock, new_sock, O_NONBLOCK);
1954 new_sock->sk->sk_allocation = GFP_ATOMIC;
1956 ret = r2net_set_nodelay(new_sock);
1958 mlog(ML_ERROR, "setting TCP_NODELAY failed with %d\n", ret);
1963 ret = new_sock->ops->getname(new_sock, (struct sockaddr *) &sin,
1968 node = r2nm_get_node_by_ip(sin.sin_addr.s_addr);
1970 pr_notice("ramster: Attempt to connect from unknown "
1971 "node at %pI4:%d\n", &sin.sin_addr.s_addr,
1972 ntohs(sin.sin_port));
1977 if (r2nm_this_node() >= node->nd_num) {
1978 local_node = r2nm_get_node_by_num(r2nm_this_node());
1979 pr_notice("ramster: Unexpected connect attempt seen "
1980 "at node '%s' (%u, %pI4:%d) from node '%s' (%u, "
1981 "%pI4:%d)\n", local_node->nd_name, local_node->nd_num,
1982 &(local_node->nd_ipv4_address),
1983 ntohs(local_node->nd_ipv4_port), node->nd_name,
1984 node->nd_num, &sin.sin_addr.s_addr, ntohs(sin.sin_port));
1989 /* this happens all the time when the other node sees our heartbeat
1990 * and tries to connect before we see their heartbeat */
1991 if (!r2hb_check_node_heartbeating_from_callback(node->nd_num)) {
1992 mlog(ML_CONN, "attempt to connect from node '%s' at "
1993 "%pI4:%d but it isn't heartbeating\n",
1994 node->nd_name, &sin.sin_addr.s_addr,
1995 ntohs(sin.sin_port));
2000 nn = r2net_nn_from_num(node->nd_num);
2002 spin_lock(&nn->nn_lock);
2007 spin_unlock(&nn->nn_lock);
2009 pr_notice("ramster: Attempt to connect from node '%s' "
2010 "at %pI4:%d but it already has an open connection\n",
2011 node->nd_name, &sin.sin_addr.s_addr,
2012 ntohs(sin.sin_port));
2016 sc = sc_alloc(node);
2022 sc->sc_sock = new_sock;
2025 spin_lock(&nn->nn_lock);
2026 atomic_set(&nn->nn_timeout, 0);
2027 r2net_set_nn_state(nn, sc, 0, 0);
2028 spin_unlock(&nn->nn_lock);
2030 r2net_register_callbacks(sc->sc_sock->sk, sc);
2031 r2net_sc_queue_work(sc, &sc->sc_rx_work);
2033 r2net_initialize_handshake();
2034 r2net_sendpage(sc, r2net_hand, sizeof(*r2net_hand));
2038 sock_release(new_sock);
2040 r2nm_node_put(node);
2042 r2nm_node_put(local_node);
2048 static void r2net_accept_many(struct work_struct *work)
2050 struct socket *sock = r2net_listen_sock;
2051 while (r2net_accept_one(sock) == 0)
2055 static void r2net_listen_data_ready(struct sock *sk, int bytes)
2057 void (*ready)(struct sock *sk, int bytes);
2059 read_lock(&sk->sk_callback_lock);
2060 ready = sk->sk_user_data;
2061 if (ready == NULL) { /* check for teardown race */
2062 ready = sk->sk_data_ready;
2066 /* ->sk_data_ready is also called for a newly established child socket
2067 * before it has been accepted and the acceptor has set up their
2068 * data_ready.. we only want to queue listen work for our listening
2070 if (sk->sk_state == TCP_LISTEN) {
2071 mlog(ML_TCP, "bytes: %d\n", bytes);
2072 queue_work(r2net_wq, &r2net_listen_work);
2076 read_unlock(&sk->sk_callback_lock);
2080 static int r2net_open_listening_sock(__be32 addr, __be16 port)
2082 struct socket *sock = NULL;
2084 struct sockaddr_in sin = {
2085 .sin_family = PF_INET,
2086 .sin_addr = { .s_addr = addr },
2090 ret = sock_create(PF_INET, SOCK_STREAM, IPPROTO_TCP, &sock);
2092 pr_err("ramster: Error %d while creating socket\n", ret);
2096 sock->sk->sk_allocation = GFP_ATOMIC;
2098 write_lock_bh(&sock->sk->sk_callback_lock);
2099 sock->sk->sk_user_data = sock->sk->sk_data_ready;
2100 sock->sk->sk_data_ready = r2net_listen_data_ready;
2101 write_unlock_bh(&sock->sk->sk_callback_lock);
2103 r2net_listen_sock = sock;
2104 INIT_WORK(&r2net_listen_work, r2net_accept_many);
2106 sock->sk->sk_reuse = /* SK_CAN_REUSE FIXME FOR 3.4 */ 1;
2107 ret = sock->ops->bind(sock, (struct sockaddr *)&sin, sizeof(sin));
2109 pr_err("ramster: Error %d while binding socket at %pI4:%u\n",
2110 ret, &addr, ntohs(port));
2114 ret = sock->ops->listen(sock, 64);
2116 pr_err("ramster: Error %d while listening on %pI4:%u\n",
2117 ret, &addr, ntohs(port));
2121 r2net_listen_sock = NULL;
2129 * called from node manager when we should bring up our network listening
2130 * socket. node manager handles all the serialization to only call this
2131 * once and to match it with r2net_stop_listening(). note,
2132 * r2nm_this_node() doesn't work yet as we're being called while it
2135 int r2net_start_listening(struct r2nm_node *node)
2139 BUG_ON(r2net_wq != NULL);
2140 BUG_ON(r2net_listen_sock != NULL);
2142 mlog(ML_KTHREAD, "starting r2net thread...\n");
2143 r2net_wq = create_singlethread_workqueue("r2net");
2144 if (r2net_wq == NULL) {
2145 mlog(ML_ERROR, "unable to launch r2net thread\n");
2146 return -ENOMEM; /* ? */
2149 ret = r2net_open_listening_sock(node->nd_ipv4_address,
2150 node->nd_ipv4_port);
2152 destroy_workqueue(r2net_wq);
2159 /* again, r2nm_this_node() doesn't work here as we're involved in
2160 * tearing it down */
2161 void r2net_stop_listening(struct r2nm_node *node)
2163 struct socket *sock = r2net_listen_sock;
2166 BUG_ON(r2net_wq == NULL);
2167 BUG_ON(r2net_listen_sock == NULL);
2169 /* stop the listening socket from generating work */
2170 write_lock_bh(&sock->sk->sk_callback_lock);
2171 sock->sk->sk_data_ready = sock->sk->sk_user_data;
2172 sock->sk->sk_user_data = NULL;
2173 write_unlock_bh(&sock->sk->sk_callback_lock);
2175 for (i = 0; i < ARRAY_SIZE(r2net_nodes); i++) {
2176 struct r2nm_node *node = r2nm_get_node_by_num(i);
2178 r2net_disconnect_node(node);
2179 r2nm_node_put(node);
2183 /* finish all work and tear down the work queue */
2184 mlog(ML_KTHREAD, "waiting for r2net thread to exit....\n");
2185 destroy_workqueue(r2net_wq);
2188 sock_release(r2net_listen_sock);
2189 r2net_listen_sock = NULL;
2192 void r2net_hb_node_up_manual(int node_num)
2194 struct r2nm_node dummy;
2195 if (r2nm_single_cluster == NULL)
2196 pr_err("ramster: cluster not alive, node_up_manual ignored\n");
2198 r2hb_manual_set_node_heartbeating(node_num);
2199 r2net_hb_node_up_cb(&dummy, node_num, NULL);
2203 /* ------------------------------------------------------------ */
2205 int r2net_init(void)
2209 if (r2net_debugfs_init())
2212 r2net_hand = kzalloc(sizeof(struct r2net_handshake), GFP_KERNEL);
2213 r2net_keep_req = kzalloc(sizeof(struct r2net_msg), GFP_KERNEL);
2214 r2net_keep_resp = kzalloc(sizeof(struct r2net_msg), GFP_KERNEL);
2215 if (!r2net_hand || !r2net_keep_req || !r2net_keep_resp) {
2217 kfree(r2net_keep_req);
2218 kfree(r2net_keep_resp);
2222 r2net_hand->protocol_version = cpu_to_be64(R2NET_PROTOCOL_VERSION);
2223 r2net_hand->connector_id = cpu_to_be64(1);
2225 r2net_keep_req->magic = cpu_to_be16(R2NET_MSG_KEEP_REQ_MAGIC);
2226 r2net_keep_resp->magic = cpu_to_be16(R2NET_MSG_KEEP_RESP_MAGIC);
2228 for (i = 0; i < ARRAY_SIZE(r2net_nodes); i++) {
2229 struct r2net_node *nn = r2net_nn_from_num(i);
2231 atomic_set(&nn->nn_timeout, 0);
2232 spin_lock_init(&nn->nn_lock);
2233 INIT_DELAYED_WORK(&nn->nn_connect_work, r2net_start_connect);
2234 INIT_DELAYED_WORK(&nn->nn_connect_expired,
2235 r2net_connect_expired);
2236 INIT_DELAYED_WORK(&nn->nn_still_up, r2net_still_up);
2237 /* until we see hb from a node we'll return einval */
2238 nn->nn_persistent_error = -ENOTCONN;
2239 init_waitqueue_head(&nn->nn_sc_wq);
2240 idr_init(&nn->nn_status_idr);
2241 INIT_LIST_HEAD(&nn->nn_status_list);
2247 void r2net_exit(void)
2250 kfree(r2net_keep_req);
2251 kfree(r2net_keep_resp);
2252 r2net_debugfs_exit();