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