ARM: 7702/1: Set the page table freeing ceiling to TASK_SIZE
[cascardo/linux.git] / 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 = 0;
304
305         do {
306                 if (!idr_pre_get(&nn->nn_status_idr, GFP_ATOMIC)) {
307                         ret = -EAGAIN;
308                         break;
309                 }
310                 spin_lock(&nn->nn_lock);
311                 ret = idr_get_new(&nn->nn_status_idr, nsw, &nsw->ns_id);
312                 if (ret == 0)
313                         list_add_tail(&nsw->ns_node_item,
314                                       &nn->nn_status_list);
315                 spin_unlock(&nn->nn_lock);
316         } while (ret == -EAGAIN);
317
318         if (ret == 0)  {
319                 init_waitqueue_head(&nsw->ns_wq);
320                 nsw->ns_sys_status = R2NET_ERR_NONE;
321                 nsw->ns_status = 0;
322         }
323
324         return ret;
325 }
326
327 static void r2net_complete_nsw_locked(struct r2net_node *nn,
328                                       struct r2net_status_wait *nsw,
329                                       enum r2net_system_error sys_status,
330                                       s32 status)
331 {
332         assert_spin_locked(&nn->nn_lock);
333
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);
340         }
341 }
342
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,
346                                s32 status)
347 {
348         spin_lock(&nn->nn_lock);
349         if (nsw == NULL) {
350                 if (id > INT_MAX)
351                         goto out;
352
353                 nsw = idr_find(&nn->nn_status_idr, id);
354                 if (nsw == NULL)
355                         goto out;
356         }
357
358         r2net_complete_nsw_locked(nn, nsw, sys_status, status);
359
360 out:
361         spin_unlock(&nn->nn_lock);
362         return;
363 }
364
365 static void r2net_complete_nodes_nsw(struct r2net_node *nn)
366 {
367         struct r2net_status_wait *nsw, *tmp;
368         unsigned int num_kills = 0;
369
370         assert_spin_locked(&nn->nn_lock);
371
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);
374                 num_kills++;
375         }
376
377         mlog(0, "completed %d messages for node %u\n", num_kills,
378              r2net_num_from_nn(nn));
379 }
380
381 static int r2net_nsw_completed(struct r2net_node *nn,
382                                struct r2net_status_wait *nsw)
383 {
384         int completed;
385         spin_lock(&nn->nn_lock);
386         completed = list_empty(&nsw->ns_node_item);
387         spin_unlock(&nn->nn_lock);
388         return completed;
389 }
390
391 /* ------------------------------------------------------------ */
392
393 static void sc_kref_release(struct kref *kref)
394 {
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));
398
399         sclog(sc, "releasing\n");
400
401         if (sc->sc_sock) {
402                 sock_release(sc->sc_sock);
403                 sc->sc_sock = NULL;
404         }
405
406         r2nm_undepend_item(&sc->sc_node->nd_item);
407         r2nm_node_put(sc->sc_node);
408         sc->sc_node = NULL;
409
410         r2net_debug_del_sc(sc);
411         kfree(sc);
412 }
413
414 static void sc_put(struct r2net_sock_container *sc)
415 {
416         sclog(sc, "put\n");
417         kref_put(&sc->sc_kref, sc_kref_release);
418 }
419 static void sc_get(struct r2net_sock_container *sc)
420 {
421         sclog(sc, "get\n");
422         kref_get(&sc->sc_kref);
423 }
424 static struct r2net_sock_container *sc_alloc(struct r2nm_node *node)
425 {
426         struct r2net_sock_container *sc, *ret = NULL;
427         struct page *page = NULL;
428         int status = 0;
429
430         page = alloc_page(GFP_NOFS);
431         sc = kzalloc(sizeof(*sc), GFP_NOFS);
432         if (sc == NULL || page == NULL)
433                 goto out;
434
435         kref_init(&sc->sc_kref);
436         r2nm_node_get(node);
437         sc->sc_node = node;
438
439         /* pin the node item of the remote node */
440         status = r2nm_depend_item(&node->nd_item);
441         if (status) {
442                 mlog_errno(status);
443                 r2nm_node_put(node);
444                 goto out;
445         }
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);
450
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;
454
455         sclog(sc, "alloced\n");
456
457         ret = sc;
458         sc->sc_page = page;
459         r2net_debug_add_sc(sc);
460         sc = NULL;
461         page = NULL;
462
463 out:
464         if (page)
465                 __free_page(page);
466         kfree(sc);
467
468         return ret;
469 }
470
471 /* ------------------------------------------------------------ */
472
473 static void r2net_sc_queue_work(struct r2net_sock_container *sc,
474                                 struct work_struct *work)
475 {
476         sc_get(sc);
477         if (!queue_work(r2net_wq, work))
478                 sc_put(sc);
479 }
480 static void r2net_sc_queue_delayed_work(struct r2net_sock_container *sc,
481                                         struct delayed_work *work,
482                                         int delay)
483 {
484         sc_get(sc);
485         if (!queue_delayed_work(r2net_wq, work, delay))
486                 sc_put(sc);
487 }
488 static void r2net_sc_cancel_delayed_work(struct r2net_sock_container *sc,
489                                          struct delayed_work *work)
490 {
491         if (cancel_delayed_work(work))
492                 sc_put(sc);
493 }
494
495 static atomic_t r2net_connected_peers = ATOMIC_INIT(0);
496
497 int r2net_num_connected_peers(void)
498 {
499         return atomic_read(&r2net_connected_peers);
500 }
501
502 static void r2net_set_nn_state(struct r2net_node *nn,
503                                struct r2net_sock_container *sc,
504                                unsigned valid, int err)
505 {
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;
509
510         assert_spin_locked(&nn->nn_lock);
511
512         if (old_sc && !sc)
513                 atomic_dec(&r2net_connected_peers);
514         else if (!old_sc && sc)
515                 atomic_inc(&r2net_connected_peers);
516
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);
522
523         if (was_valid && !valid && err == 0)
524                 err = -ENOTCONN;
525
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);
529
530         nn->nn_sc = sc;
531         nn->nn_sc_valid = valid ? 1 : 0;
532         nn->nn_persistent_error = err;
533
534         /* mirrors r2net_tx_can_proceed() */
535         if (nn->nn_persistent_error || nn->nn_sc_valid)
536                 wake_up(&nn->nn_sc_wq);
537
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));
541         }
542
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);
549         }
550
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));
559         }
560
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) {
566                 unsigned long delay;
567                 /* delay if we're within a RECONNECT_DELAY of the
568                  * last attempt */
569                 delay = (nn->nn_last_connect_attempt +
570                          msecs_to_jiffies(r2net_reconnect_delay()))
571                         - jiffies;
572                 if (delay > msecs_to_jiffies(r2net_reconnect_delay()))
573                         delay = 0;
574                 mlog(ML_CONN, "queueing conn attempt in %lu jiffies\n", delay);
575                 queue_delayed_work(r2net_wq, &nn->nn_connect_work, delay);
576
577                 /*
578                  * Delay the expired work after idle timeout.
579                  *
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.
585                  */
586                 delay += msecs_to_jiffies(r2net_idle_timeout());
587                 queue_delayed_work(r2net_wq, &nn->nn_connect_expired, delay);
588         }
589
590         /* keep track of the nn's sc ref for the caller */
591         if ((old_sc == NULL) && sc)
592                 sc_get(sc);
593         if (old_sc && (old_sc != sc)) {
594                 r2net_sc_queue_work(old_sc, &old_sc->sc_shutdown_work);
595                 sc_put(old_sc);
596         }
597 }
598
599 /* see r2net_register_callbacks() */
600 static void r2net_data_ready(struct sock *sk, int bytes)
601 {
602         void (*ready)(struct sock *sk, int bytes);
603
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;
611         } else {
612                 ready = sk->sk_data_ready;
613         }
614         read_unlock(&sk->sk_callback_lock);
615
616         ready(sk, bytes);
617 }
618
619 /* see r2net_register_callbacks() */
620 static void r2net_state_change(struct sock *sk)
621 {
622         void (*state_change)(struct sock *sk);
623         struct r2net_sock_container *sc;
624
625         read_lock(&sk->sk_callback_lock);
626         sc = sk->sk_user_data;
627         if (sc == NULL) {
628                 state_change = sk->sk_state_change;
629                 goto out;
630         }
631
632         sclog(sc, "state_change to %d\n", sk->sk_state);
633
634         state_change = sc->sc_state_change;
635
636         switch (sk->sk_state) {
637
638         /* ignore connecting sockets as they make progress */
639         case TCP_SYN_SENT:
640         case TCP_SYN_RECV:
641                 break;
642         case TCP_ESTABLISHED:
643                 r2net_sc_queue_work(sc, &sc->sc_connect_work);
644                 break;
645         default:
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);
652                 break;
653
654         }
655 out:
656         read_unlock(&sk->sk_callback_lock);
657         state_change(sk);
658 }
659
660 /*
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().
664  */
665 static void r2net_register_callbacks(struct sock *sk,
666                                      struct r2net_sock_container *sc)
667 {
668         write_lock_bh(&sk->sk_callback_lock);
669
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;
674         }
675
676         BUG_ON(sk->sk_user_data != NULL);
677         sk->sk_user_data = sc;
678         sc_get(sc);
679
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;
684
685         mutex_init(&sc->sc_send_lock);
686
687         write_unlock_bh(&sk->sk_callback_lock);
688 }
689
690 static int r2net_unregister_callbacks(struct sock *sk,
691                                         struct r2net_sock_container *sc)
692 {
693         int ret = 0;
694
695         write_lock_bh(&sk->sk_callback_lock);
696         if (sk->sk_user_data == sc) {
697                 ret = 1;
698                 sk->sk_user_data = NULL;
699                 sk->sk_data_ready = sc->sc_data_ready;
700                 sk->sk_state_change = sc->sc_state_change;
701         }
702         write_unlock_bh(&sk->sk_callback_lock);
703
704         return ret;
705 }
706
707 /*
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.
712  */
713 static void r2net_ensure_shutdown(struct r2net_node *nn,
714                                         struct r2net_sock_container *sc,
715                                    int err)
716 {
717         spin_lock(&nn->nn_lock);
718         if (nn->nn_sc == sc)
719                 r2net_set_nn_state(nn, NULL, 0, err);
720         spin_unlock(&nn->nn_lock);
721 }
722
723 /*
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
729  * itself.
730  */
731 static void r2net_shutdown_sc(struct work_struct *work)
732 {
733         struct r2net_sock_container *sc =
734                 container_of(work, struct r2net_sock_container,
735                              sc_shutdown_work);
736         struct r2net_node *nn = r2net_nn_from_num(sc->sc_node->nd_num);
737
738         sclog(sc, "shutting down\n");
739
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);
746                 sc_put(sc);
747                 kernel_sock_shutdown(sc->sc_sock, SHUT_RDWR);
748         }
749
750         /* not fatal so failed connects before the other guy has our
751          * heartbeat can be retried */
752         r2net_ensure_shutdown(nn, sc, 0);
753         sc_put(sc);
754 }
755
756 /* ------------------------------------------------------------ */
757
758 static int r2net_handler_cmp(struct r2net_msg_handler *nmh, u32 msg_type,
759                              u32 key)
760 {
761         int ret = memcmp(&nmh->nh_key, &key, sizeof(key));
762
763         if (ret == 0)
764                 ret = memcmp(&nmh->nh_msg_type, &msg_type, sizeof(msg_type));
765
766         return ret;
767 }
768
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)
772 {
773         struct rb_node **p = &r2net_handler_tree.rb_node;
774         struct rb_node *parent = NULL;
775         struct r2net_msg_handler *nmh, *ret = NULL;
776         int cmp;
777
778         while (*p) {
779                 parent = *p;
780                 nmh = rb_entry(parent, struct r2net_msg_handler, nh_node);
781                 cmp = r2net_handler_cmp(nmh, msg_type, key);
782
783                 if (cmp < 0)
784                         p = &(*p)->rb_left;
785                 else if (cmp > 0)
786                         p = &(*p)->rb_right;
787                 else {
788                         ret = nmh;
789                         break;
790                 }
791         }
792
793         if (ret_p != NULL)
794                 *ret_p = p;
795         if (ret_parent != NULL)
796                 *ret_parent = parent;
797
798         return ret;
799 }
800
801 static void r2net_handler_kref_release(struct kref *kref)
802 {
803         struct r2net_msg_handler *nmh;
804         nmh = container_of(kref, struct r2net_msg_handler, nh_kref);
805
806         kfree(nmh);
807 }
808
809 static void r2net_handler_put(struct r2net_msg_handler *nmh)
810 {
811         kref_put(&nmh->nh_kref, r2net_handler_kref_release);
812 }
813
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)
820 {
821         struct r2net_msg_handler *nmh = NULL;
822         struct rb_node **p, *parent;
823         int ret = 0;
824
825         if (max_len > R2NET_MAX_PAYLOAD_BYTES) {
826                 mlog(0, "max_len for message handler out of range: %u\n",
827                         max_len);
828                 ret = -EINVAL;
829                 goto out;
830         }
831
832         if (!msg_type) {
833                 mlog(0, "no message type provided: %u, %p\n", msg_type, func);
834                 ret = -EINVAL;
835                 goto out;
836
837         }
838         if (!func) {
839                 mlog(0, "no message handler provided: %u, %p\n",
840                        msg_type, func);
841                 ret = -EINVAL;
842                 goto out;
843         }
844
845         nmh = kzalloc(sizeof(struct r2net_msg_handler), GFP_NOFS);
846         if (nmh == NULL) {
847                 ret = -ENOMEM;
848                 goto out;
849         }
850
851         nmh->nh_func = func;
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;
856         nmh->nh_key = key;
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);
861
862         write_lock(&r2net_handler_lock);
863         if (r2net_handler_tree_lookup(msg_type, key, &p, &parent))
864                 ret = -EEXIST;
865         else {
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);
869
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,
874                                                           &parent) == NULL,
875                                 "couldn't find handler we *just* registered "
876                                 "for type %u key %08x\n", msg_type, key);
877         }
878         write_unlock(&r2net_handler_lock);
879         if (ret)
880                 goto out;
881
882 out:
883         if (ret)
884                 kfree(nmh);
885
886         return ret;
887 }
888 EXPORT_SYMBOL_GPL(r2net_register_handler);
889
890 void r2net_unregister_handler_list(struct list_head *list)
891 {
892         struct r2net_msg_handler *nmh, *n;
893
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);
901         }
902         write_unlock(&r2net_handler_lock);
903 }
904 EXPORT_SYMBOL_GPL(r2net_unregister_handler_list);
905
906 static struct r2net_msg_handler *r2net_handler_get(u32 msg_type, u32 key)
907 {
908         struct r2net_msg_handler *nmh;
909
910         read_lock(&r2net_handler_lock);
911         nmh = r2net_handler_tree_lookup(msg_type, key, NULL, NULL);
912         if (nmh)
913                 kref_get(&nmh->nh_kref);
914         read_unlock(&r2net_handler_lock);
915
916         return nmh;
917 }
918
919 /* ------------------------------------------------------------ */
920
921 static int r2net_recv_tcp_msg(struct socket *sock, void *data, size_t len)
922 {
923         int ret;
924         mm_segment_t oldfs;
925         struct kvec vec = {
926                 .iov_len = len,
927                 .iov_base = data,
928         };
929         struct msghdr msg = {
930                 .msg_iovlen = 1,
931                 .msg_iov = (struct iovec *)&vec,
932                 .msg_flags = MSG_DONTWAIT,
933         };
934
935         oldfs = get_fs();
936         set_fs(get_ds());
937         ret = sock_recvmsg(sock, &msg, len, msg.msg_flags);
938         set_fs(oldfs);
939
940         return ret;
941 }
942
943 static int r2net_send_tcp_msg(struct socket *sock, struct kvec *vec,
944                               size_t veclen, size_t total)
945 {
946         int ret;
947         mm_segment_t oldfs;
948         struct msghdr msg = {
949                 .msg_iov = (struct iovec *)vec,
950                 .msg_iovlen = veclen,
951         };
952
953         if (sock == NULL) {
954                 ret = -EINVAL;
955                 goto out;
956         }
957
958         oldfs = get_fs();
959         set_fs(get_ds());
960         ret = sock_sendmsg(sock, &msg, total);
961         set_fs(oldfs);
962         if (ret != total) {
963                 mlog(ML_ERROR, "sendmsg returned %d instead of %zu\n", ret,
964                      total);
965                 if (ret >= 0)
966                         ret = -EPIPE; /* should be smarter, I bet */
967                 goto out;
968         }
969
970         ret = 0;
971 out:
972         if (ret < 0)
973                 mlog(0, "returning error: %d\n", ret);
974         return ret;
975 }
976
977 static void r2net_sendpage(struct r2net_sock_container *sc,
978                            void *kmalloced_virt,
979                            size_t size)
980 {
981         struct r2net_node *nn = r2net_nn_from_num(sc->sc_node->nd_num);
982         ssize_t ret;
983
984         while (1) {
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,
989                                         size, MSG_DONTWAIT);
990                 mutex_unlock(&sc->sc_send_lock);
991                 if (ret == size)
992                         break;
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,
996                                 sc->sc_node->nd_num,
997                                 &sc->sc_node->nd_ipv4_address,
998                                 ntohs(sc->sc_node->nd_ipv4_port));
999                         cond_resched();
1000                         continue;
1001                 }
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);
1007                 break;
1008         }
1009 }
1010
1011 static void r2net_init_msg(struct r2net_msg *msg, u16 data_len,
1012                                 u16 msg_type, u32 key)
1013 {
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);
1019         msg->status = 0;
1020         msg->key = cpu_to_be32(key);
1021 }
1022
1023 static int r2net_tx_can_proceed(struct r2net_node *nn,
1024                                 struct r2net_sock_container **sc_ret,
1025                                 int *error)
1026 {
1027         int ret = 0;
1028
1029         spin_lock(&nn->nn_lock);
1030         if (nn->nn_persistent_error) {
1031                 ret = 1;
1032                 *sc_ret = NULL;
1033                 *error = nn->nn_persistent_error;
1034         } else if (nn->nn_sc_valid) {
1035                 kref_get(&nn->nn_sc->sc_kref);
1036
1037                 ret = 1;
1038                 *sc_ret = nn->nn_sc;
1039                 *error = 0;
1040         }
1041         spin_unlock(&nn->nn_lock);
1042
1043         return ret;
1044 }
1045
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)
1048 {
1049         struct r2net_sock_container *sc;
1050         int node, ret;
1051
1052         BUG_ON(bytes < (BITS_TO_LONGS(R2NM_MAX_NODES) * sizeof(unsigned long)));
1053
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);
1057                 if (!ret) {
1058                         set_bit(node, map);
1059                         sc_put(sc);
1060                 }
1061         }
1062 }
1063 EXPORT_SYMBOL_GPL(r2net_fill_node_map);
1064
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)
1067 {
1068         int ret = 0;
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),
1076         };
1077         struct r2net_send_tracking nst;
1078
1079         /* this may be a general bug fix */
1080         init_waitqueue_head(&nsw.ns_wq);
1081
1082         r2net_init_nst(&nst, msg_type, key, current, target_node);
1083
1084         if (r2net_wq == NULL) {
1085                 mlog(0, "attempt to tx without r2netd running\n");
1086                 ret = -ESRCH;
1087                 goto out;
1088         }
1089
1090         if (caller_veclen == 0) {
1091                 mlog(0, "bad kvec array length\n");
1092                 ret = -EINVAL;
1093                 goto out;
1094         }
1095
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);
1099                 ret = -EINVAL;
1100                 goto out;
1101         }
1102
1103         if (target_node == r2nm_this_node()) {
1104                 ret = -ELOOP;
1105                 goto out;
1106         }
1107
1108         r2net_debug_add_nst(&nst);
1109
1110         r2net_set_nst_sock_time(&nst);
1111
1112         wait_event(nn->nn_sc_wq, r2net_tx_can_proceed(nn, &sc, &ret));
1113         if (ret)
1114                 goto out;
1115
1116         r2net_set_nst_sock_container(&nst, sc);
1117
1118         veclen = caller_veclen + 1;
1119         vec = kmalloc(sizeof(struct kvec) * veclen, GFP_ATOMIC);
1120         if (vec == NULL) {
1121                 mlog(0, "failed to %zu element kvec!\n", veclen);
1122                 ret = -ENOMEM;
1123                 goto out;
1124         }
1125
1126         msg = kmalloc(sizeof(struct r2net_msg), GFP_ATOMIC);
1127         if (!msg) {
1128                 mlog(0, "failed to allocate a r2net_msg!\n");
1129                 ret = -ENOMEM;
1130                 goto out;
1131         }
1132
1133         r2net_init_msg(msg, caller_bytes, msg_type, key);
1134
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));
1138
1139         ret = r2net_prep_nsw(nn, &nsw);
1140         if (ret)
1141                 goto out;
1142
1143         msg->msg_num = cpu_to_be32(nsw.ns_id);
1144         r2net_set_nst_msg_id(&nst, nsw.ns_id);
1145
1146         r2net_set_nst_send_time(&nst);
1147
1148         /* finally, convert the message header to network byte-order
1149          * and send */
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);
1155         if (ret < 0) {
1156                 mlog(0, "error returned from r2net_send_tcp_msg=%d\n", ret);
1157                 goto out;
1158         }
1159
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);
1164
1165         r2net_update_send_stats(&nst, sc);
1166
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);
1171         if (status && !ret)
1172                 *status = nsw.ns_status;
1173
1174         mlog(0, "woken, returning system status %d, user status %d\n",
1175              ret, nsw.ns_status);
1176 out:
1177         r2net_debug_del_nst(&nst); /* must be before dropping sc and node */
1178         if (sc)
1179                 sc_put(sc);
1180         kfree(vec);
1181         kfree(msg);
1182         r2net_complete_nsw(nn, &nsw, 0, 0, 0);
1183         return ret;
1184 }
1185 EXPORT_SYMBOL_GPL(r2net_send_message_vec);
1186
1187 int r2net_send_message(u32 msg_type, u32 key, void *data, u32 len,
1188                        u8 target_node, int *status)
1189 {
1190         struct kvec vec = {
1191                 .iov_base = data,
1192                 .iov_len = len,
1193         };
1194         return r2net_send_message_vec(msg_type, key, &vec, 1,
1195                                       target_node, status);
1196 }
1197 EXPORT_SYMBOL_GPL(r2net_send_message);
1198
1199 static int r2net_send_status_magic(struct socket *sock, struct r2net_msg *hdr,
1200                                    enum r2net_system_error syserr, int err)
1201 {
1202         struct kvec vec = {
1203                 .iov_base = hdr,
1204                 .iov_len = sizeof(struct r2net_msg),
1205         };
1206
1207         BUG_ON(syserr >= R2NET_ERR_MAX);
1208
1209         /* leave other fields intact from the incoming message, msg_num
1210          * in particular */
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);
1215         hdr->data_len = 0;
1216
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));
1220 }
1221
1222 /*
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
1225  */
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)
1230 {
1231         struct kvec vec[2];
1232         int ret;
1233
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;
1238
1239         BUG_ON(syserr >= R2NET_ERR_MAX);
1240
1241         /* leave other fields intact from the incoming message, msg_num
1242          * in particular */
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);
1247
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);
1252         return ret;
1253 }
1254
1255 /*
1256  * called by a message handler to convert an otherwise normal reply
1257  * message into a "data magic" message
1258  */
1259 void r2net_force_data_magic(struct r2net_msg *hdr, u16 msgtype, u32 msgkey)
1260 {
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);
1264 }
1265
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)
1270 {
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;
1276         int data_magic = 0;
1277
1278         msglog(hdr, "processing message\n");
1279
1280         r2net_sc_postpone_idle(sc);
1281
1282         switch (be16_to_cpu(hdr->magic)) {
1283
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));
1289                 goto out;
1290         case R2NET_MSG_KEEP_REQ_MAGIC:
1291                 r2net_sendpage(sc, r2net_keep_resp, sizeof(*r2net_keep_resp));
1292                 goto out;
1293         case R2NET_MSG_KEEP_RESP_MAGIC:
1294                 goto out;
1295         case R2NET_MSG_MAGIC:
1296                 break;
1297         case R2NET_MSG_DATA_MAGIC:
1298                 /*
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
1302                  */
1303                 data_magic = 1;
1304                 break;
1305         default:
1306                 msglog(hdr, "bad magic\n");
1307                 ret = -EINVAL;
1308                 goto out;
1309                 break;
1310         }
1311
1312         /* find a handler for it */
1313         handler_status = 0;
1314         nmh = r2net_handler_get(be16_to_cpu(hdr->msg_type),
1315                                 be32_to_cpu(hdr->key));
1316         if (!nmh) {
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;
1320                 goto out_respond;
1321         }
1322
1323         syserr = R2NET_ERR_NONE;
1324
1325         if (be16_to_cpu(hdr->data_len) > nmh->nh_max_len)
1326                 syserr = R2NET_ERR_OVERFLOW;
1327
1328         if (syserr != R2NET_ERR_NONE) {
1329                 pr_err("ramster_r2net, message length problem\n");
1330                 goto out_respond;
1331         }
1332
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);
1339         if (data_magic) {
1340                 /*
1341                  * handler handled data sent in reply to request
1342                  * so complete the transaction
1343                  */
1344                 r2net_complete_nsw(nn, NULL, be32_to_cpu(hdr->msg_num),
1345                         be32_to_cpu(hdr->sys_status), handler_status);
1346                 goto out;
1347         }
1348         /*
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
1352          */
1353         if (be16_to_cpu(hdr->magic) == R2NET_MSG_DATA_MAGIC) {
1354                 ret = r2net_send_data_magic(sc, hdr,
1355                                                 ret_data, handler_status,
1356                                                 syserr, 0);
1357                 hdr = NULL;
1358                 mlog(0, "sending data reply %d, syserr %d returned %d\n",
1359                         handler_status, syserr, ret);
1360                 r2net_set_func_stop_time(sc);
1361
1362                 r2net_update_recv_stats(sc);
1363                 goto out;
1364         }
1365         r2net_set_func_stop_time(sc);
1366
1367         r2net_update_recv_stats(sc);
1368
1369 out_respond:
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,
1373                                       handler_status);
1374         mutex_unlock(&sc->sc_send_lock);
1375         hdr = NULL;
1376         mlog(0, "sending handler status %d, syserr %d returned %d\n",
1377              handler_status, syserr, ret);
1378
1379         if (nmh) {
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,
1383                                             ret_data);
1384         }
1385
1386 out:
1387         if (nmh)
1388                 r2net_handler_put(nmh);
1389         return ret;
1390 }
1391
1392 static int r2net_check_handshake(struct r2net_sock_container *sc)
1393 {
1394         struct r2net_handshake *hand = page_address(sc->sc_page);
1395         struct r2net_node *nn = r2net_nn_from_num(sc->sc_node->nd_num);
1396
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);
1405
1406                 /* don't bother reconnecting if its the wrong version. */
1407                 r2net_ensure_shutdown(nn, sc, -ENOTCONN);
1408                 return -1;
1409         }
1410
1411         /*
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.
1415          */
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);
1426                 return -1;
1427         }
1428
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);
1439                 return -1;
1440         }
1441
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);
1452                 return -1;
1453         }
1454
1455         sc->sc_handshake_ok = 1;
1456
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);
1464         }
1465         spin_unlock(&nn->nn_lock);
1466
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);
1471
1472         return 0;
1473 }
1474
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)
1479 {
1480         struct r2net_msg *hdr;
1481         int ret = 0;
1482         void *data;
1483         size_t datalen;
1484
1485         sclog(sc, "receiving\n");
1486         r2net_set_advance_start_time(sc);
1487
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) -
1492                                                         sc->sc_page_off;
1493                         ret = r2net_recv_tcp_msg(sc->sc_sock, data, datalen);
1494                         if (ret > 0)
1495                                 sc->sc_page_off += ret;
1496                 }
1497
1498                 if (sc->sc_page_off == sizeof(struct r2net_handshake)) {
1499                         r2net_check_handshake(sc);
1500                         if (unlikely(sc->sc_handshake_ok == 0))
1501                                 ret = -EPROTO;
1502                 }
1503                 goto out;
1504         }
1505
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);
1511                 if (ret > 0) {
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)
1520                                         ret = -EOVERFLOW;
1521                                 WARN_ON_ONCE(ret == -EOVERFLOW);
1522                         }
1523                 }
1524                 if (ret <= 0)
1525                         goto out;
1526         }
1527
1528         if (sc->sc_page_off < sizeof(struct r2net_msg)) {
1529                 /* oof, still don't have a header */
1530                 goto out;
1531         }
1532
1533         /* this was swabbed above when we first read it */
1534         hdr = page_address(sc->sc_page);
1535
1536         msglog(hdr, "at page_off %zu\n", sc->sc_page_off);
1537
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)) -
1545                                 sc->sc_page_off;
1546                 ret = r2net_recv_tcp_msg(sc->sc_sock, data, datalen);
1547                 if (ret > 0)
1548                         sc->sc_page_off += ret;
1549                 if (ret <= 0)
1550                         goto out;
1551         }
1552
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);
1559                 if (ret == 0)
1560                         ret = 1;
1561                 sc->sc_page_off = 0;
1562         }
1563
1564 out:
1565         sclog(sc, "ret = %d\n", ret);
1566         r2net_set_advance_stop_time(sc);
1567         return ret;
1568 }
1569
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)
1574 {
1575         struct r2net_sock_container *sc =
1576                 container_of(work, struct r2net_sock_container, sc_rx_work);
1577         int ret;
1578
1579         do {
1580                 ret = r2net_advance_rx(sc);
1581         } while (ret > 0);
1582
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);
1588         }
1589         sc_put(sc);
1590 }
1591
1592 static int r2net_set_nodelay(struct socket *sock)
1593 {
1594         int ret, val = 1;
1595         mm_segment_t oldfs;
1596
1597         oldfs = get_fs();
1598         set_fs(KERNEL_DS);
1599
1600         /*
1601          * Dear unsuspecting programmer,
1602          *
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.
1606          *
1607          * Yours,
1608          * Keeper of hilariously fragile interfaces.
1609          */
1610         ret = sock->ops->setsockopt(sock, SOL_TCP, TCP_NODELAY,
1611                                     (char __user *)&val, sizeof(val));
1612
1613         set_fs(oldfs);
1614         return ret;
1615 }
1616
1617 static void r2net_initialize_handshake(void)
1618 {
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());
1626 }
1627
1628 /* ------------------------------------------------------------ */
1629
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)
1633 {
1634         struct r2net_sock_container *sc =
1635                         container_of(work, struct r2net_sock_container,
1636                              sc_connect_work);
1637
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));
1641
1642         r2net_initialize_handshake();
1643         r2net_sendpage(sc, r2net_hand, sizeof(*r2net_hand));
1644         sc_put(sc);
1645 }
1646
1647 /* this is called as a work_struct func. */
1648 static void r2net_sc_send_keep_req(struct work_struct *work)
1649 {
1650         struct r2net_sock_container *sc =
1651                 container_of(work, struct r2net_sock_container,
1652                              sc_keepalive_work.work);
1653
1654         r2net_sendpage(sc, r2net_keep_req, sizeof(*r2net_keep_req));
1655         sc_put(sc);
1656 }
1657
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)
1662 {
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);
1668 #else
1669         unsigned long msecs = r2net_idle_timeout();
1670 #endif
1671
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);
1677
1678         /*
1679          * Initialize the nn_timeout so that the next connection attempt
1680          * will continue in r2net_start_connect.
1681          */
1682         atomic_set(&nn->nn_timeout, 1);
1683         r2net_sc_queue_work(sc, &sc->sc_shutdown_work);
1684 }
1685
1686 static void r2net_sc_reset_idle_timer(struct r2net_sock_container *sc)
1687 {
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()));
1694 }
1695
1696 static void r2net_sc_postpone_idle(struct r2net_sock_container *sc)
1697 {
1698         /* Only push out an existing timer */
1699         if (timer_pending(&sc->sc_idle_timeout))
1700                 r2net_sc_reset_idle_timer(sc);
1701 }
1702
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)
1709 {
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, };
1716         int ret = 0, stop;
1717         unsigned int timeout;
1718
1719         /* if we're greater we initiate tx, otherwise we accept */
1720         if (r2nm_this_node() <= r2net_num_from_nn(nn))
1721                 goto out;
1722
1723         /* watch for racing with tearing a node down */
1724         node = r2nm_get_node_by_num(r2net_num_from_nn(nn));
1725         if (node == NULL) {
1726                 ret = 0;
1727                 goto out;
1728         }
1729
1730         mynode = r2nm_get_node_by_num(r2nm_this_node());
1731         if (mynode == NULL) {
1732                 ret = 0;
1733                 goto out;
1734         }
1735
1736         spin_lock(&nn->nn_lock);
1737         /*
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.
1743          */
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);
1749         if (stop)
1750                 goto out;
1751
1752         nn->nn_last_connect_attempt = jiffies;
1753
1754         sc = sc_alloc(node);
1755         if (sc == NULL) {
1756                 mlog(0, "couldn't allocate sc\n");
1757                 ret = -ENOMEM;
1758                 goto out;
1759         }
1760
1761         ret = sock_create(PF_INET, SOCK_STREAM, IPPROTO_TCP, &sock);
1762         if (ret < 0) {
1763                 mlog(0, "can't create socket: %d\n", ret);
1764                 goto out;
1765         }
1766         sc->sc_sock = sock; /* freed by sc_kref_release */
1767
1768         sock->sk->sk_allocation = GFP_ATOMIC;
1769
1770         myaddr.sin_family = AF_INET;
1771         myaddr.sin_addr.s_addr = mynode->nd_ipv4_address;
1772         myaddr.sin_port = htons(0); /* any port */
1773
1774         ret = sock->ops->bind(sock, (struct sockaddr *)&myaddr,
1775                               sizeof(myaddr));
1776         if (ret) {
1777                 mlog(ML_ERROR, "bind failed with %d at address %pI4\n",
1778                      ret, &mynode->nd_ipv4_address);
1779                 goto out;
1780         }
1781
1782         ret = r2net_set_nodelay(sc->sc_sock);
1783         if (ret) {
1784                 mlog(ML_ERROR, "setting TCP_NODELAY failed with %d\n", ret);
1785                 goto out;
1786         }
1787
1788         r2net_register_callbacks(sc->sc_sock->sk, sc);
1789
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);
1794
1795         remoteaddr.sin_family = AF_INET;
1796         remoteaddr.sin_addr.s_addr = node->nd_ipv4_address;
1797         remoteaddr.sin_port = node->nd_ipv4_port;
1798
1799         ret = sc->sc_sock->ops->connect(sc->sc_sock,
1800                                         (struct sockaddr *)&remoteaddr,
1801                                         sizeof(remoteaddr),
1802                                         O_NONBLOCK);
1803         if (ret == -EINPROGRESS)
1804                 ret = 0;
1805
1806 out:
1807         if (ret) {
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 */
1814                 if (sc)
1815                         r2net_ensure_shutdown(nn, sc, 0);
1816         }
1817         if (sc)
1818                 sc_put(sc);
1819         if (node)
1820                 r2nm_node_put(node);
1821         if (mynode)
1822                 r2nm_node_put(mynode);
1823
1824         return;
1825 }
1826
1827 static void r2net_connect_expired(struct work_struct *work)
1828 {
1829         struct r2net_node *nn =
1830                 container_of(work, struct r2net_node, nn_connect_expired.work);
1831
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);
1839
1840                 r2net_set_nn_state(nn, NULL, 0, -ENOTCONN);
1841         }
1842         spin_unlock(&nn->nn_lock);
1843 }
1844
1845 static void r2net_still_up(struct work_struct *work)
1846 {
1847 }
1848
1849 /* ------------------------------------------------------------ */
1850
1851 void r2net_disconnect_node(struct r2nm_node *node)
1852 {
1853         struct r2net_node *nn = r2net_nn_from_num(node->nd_num);
1854
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);
1860
1861         if (r2net_wq) {
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);
1866         }
1867 }
1868
1869 static void r2net_hb_node_down_cb(struct r2nm_node *node, int node_num,
1870                                   void *data)
1871 {
1872         if (!node)
1873                 return;
1874
1875         if (node_num != r2nm_this_node())
1876                 r2net_disconnect_node(node);
1877
1878         BUG_ON(atomic_read(&r2net_connected_peers) < 0);
1879 }
1880
1881 static void r2net_hb_node_up_cb(struct r2nm_node *node, int node_num,
1882                                 void *data)
1883 {
1884         struct r2net_node *nn = r2net_nn_from_num(node_num);
1885
1886         BUG_ON(!node);
1887
1888         /* ensure an immediate connect attempt */
1889         nn->nn_last_connect_attempt = jiffies -
1890                 (msecs_to_jiffies(r2net_reconnect_delay()) + 1);
1891
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);
1902         }
1903 }
1904
1905 void r2net_unregister_hb_callbacks(void)
1906 {
1907         r2hb_unregister_callback(NULL, &r2net_hb_up);
1908         r2hb_unregister_callback(NULL, &r2net_hb_down);
1909 }
1910
1911 int r2net_register_hb_callbacks(void)
1912 {
1913         int ret;
1914
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);
1919
1920         ret = r2hb_register_callback(NULL, &r2net_hb_up);
1921         if (ret == 0)
1922                 ret = r2hb_register_callback(NULL, &r2net_hb_down);
1923
1924         if (ret)
1925                 r2net_unregister_hb_callbacks();
1926
1927         return ret;
1928 }
1929
1930 /* ------------------------------------------------------------ */
1931
1932 static int r2net_accept_one(struct socket *sock)
1933 {
1934         int ret, slen;
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;
1941
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);
1945         if (ret)
1946                 goto out;
1947
1948         new_sock->type = sock->type;
1949         new_sock->ops = sock->ops;
1950         ret = sock->ops->accept(sock, new_sock, O_NONBLOCK);
1951         if (ret < 0)
1952                 goto out;
1953
1954         new_sock->sk->sk_allocation = GFP_ATOMIC;
1955
1956         ret = r2net_set_nodelay(new_sock);
1957         if (ret) {
1958                 mlog(ML_ERROR, "setting TCP_NODELAY failed with %d\n", ret);
1959                 goto out;
1960         }
1961
1962         slen = sizeof(sin);
1963         ret = new_sock->ops->getname(new_sock, (struct sockaddr *) &sin,
1964                                        &slen, 1);
1965         if (ret < 0)
1966                 goto out;
1967
1968         node = r2nm_get_node_by_ip(sin.sin_addr.s_addr);
1969         if (node == NULL) {
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));
1973                 ret = -EINVAL;
1974                 goto out;
1975         }
1976
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));
1985                 ret = -EINVAL;
1986                 goto out;
1987         }
1988
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));
1996                 ret = -EINVAL;
1997                 goto out;
1998         }
1999
2000         nn = r2net_nn_from_num(node->nd_num);
2001
2002         spin_lock(&nn->nn_lock);
2003         if (nn->nn_sc)
2004                 ret = -EBUSY;
2005         else
2006                 ret = 0;
2007         spin_unlock(&nn->nn_lock);
2008         if (ret) {
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));
2013                 goto out;
2014         }
2015
2016         sc = sc_alloc(node);
2017         if (sc == NULL) {
2018                 ret = -ENOMEM;
2019                 goto out;
2020         }
2021
2022         sc->sc_sock = new_sock;
2023         new_sock = NULL;
2024
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);
2029
2030         r2net_register_callbacks(sc->sc_sock->sk, sc);
2031         r2net_sc_queue_work(sc, &sc->sc_rx_work);
2032
2033         r2net_initialize_handshake();
2034         r2net_sendpage(sc, r2net_hand, sizeof(*r2net_hand));
2035
2036 out:
2037         if (new_sock)
2038                 sock_release(new_sock);
2039         if (node)
2040                 r2nm_node_put(node);
2041         if (local_node)
2042                 r2nm_node_put(local_node);
2043         if (sc)
2044                 sc_put(sc);
2045         return ret;
2046 }
2047
2048 static void r2net_accept_many(struct work_struct *work)
2049 {
2050         struct socket *sock = r2net_listen_sock;
2051         while (r2net_accept_one(sock) == 0)
2052                 cond_resched();
2053 }
2054
2055 static void r2net_listen_data_ready(struct sock *sk, int bytes)
2056 {
2057         void (*ready)(struct sock *sk, int bytes);
2058
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;
2063                 goto out;
2064         }
2065
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
2069          * socket */
2070         if (sk->sk_state == TCP_LISTEN) {
2071                 mlog(ML_TCP, "bytes: %d\n", bytes);
2072                 queue_work(r2net_wq, &r2net_listen_work);
2073         }
2074
2075 out:
2076         read_unlock(&sk->sk_callback_lock);
2077         ready(sk, bytes);
2078 }
2079
2080 static int r2net_open_listening_sock(__be32 addr, __be16 port)
2081 {
2082         struct socket *sock = NULL;
2083         int ret;
2084         struct sockaddr_in sin = {
2085                 .sin_family = PF_INET,
2086                 .sin_addr = { .s_addr = addr },
2087                 .sin_port = port,
2088         };
2089
2090         ret = sock_create(PF_INET, SOCK_STREAM, IPPROTO_TCP, &sock);
2091         if (ret < 0) {
2092                 pr_err("ramster: Error %d while creating socket\n", ret);
2093                 goto out;
2094         }
2095
2096         sock->sk->sk_allocation = GFP_ATOMIC;
2097
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);
2102
2103         r2net_listen_sock = sock;
2104         INIT_WORK(&r2net_listen_work, r2net_accept_many);
2105
2106         sock->sk->sk_reuse = /* SK_CAN_REUSE FIXME FOR 3.4 */ 1;
2107         ret = sock->ops->bind(sock, (struct sockaddr *)&sin, sizeof(sin));
2108         if (ret < 0) {
2109                 pr_err("ramster: Error %d while binding socket at %pI4:%u\n",
2110                         ret, &addr, ntohs(port));
2111                 goto out;
2112         }
2113
2114         ret = sock->ops->listen(sock, 64);
2115         if (ret < 0)
2116                 pr_err("ramster: Error %d while listening on %pI4:%u\n",
2117                        ret, &addr, ntohs(port));
2118
2119 out:
2120         if (ret) {
2121                 r2net_listen_sock = NULL;
2122                 if (sock)
2123                         sock_release(sock);
2124         }
2125         return ret;
2126 }
2127
2128 /*
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
2133  * is being set up.
2134  */
2135 int r2net_start_listening(struct r2nm_node *node)
2136 {
2137         int ret = 0;
2138
2139         BUG_ON(r2net_wq != NULL);
2140         BUG_ON(r2net_listen_sock != NULL);
2141
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; /* ? */
2147         }
2148
2149         ret = r2net_open_listening_sock(node->nd_ipv4_address,
2150                                         node->nd_ipv4_port);
2151         if (ret) {
2152                 destroy_workqueue(r2net_wq);
2153                 r2net_wq = NULL;
2154         }
2155
2156         return ret;
2157 }
2158
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)
2162 {
2163         struct socket *sock = r2net_listen_sock;
2164         size_t i;
2165
2166         BUG_ON(r2net_wq == NULL);
2167         BUG_ON(r2net_listen_sock == NULL);
2168
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);
2174
2175         for (i = 0; i < ARRAY_SIZE(r2net_nodes); i++) {
2176                 struct r2nm_node *node = r2nm_get_node_by_num(i);
2177                 if (node) {
2178                         r2net_disconnect_node(node);
2179                         r2nm_node_put(node);
2180                 }
2181         }
2182
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);
2186         r2net_wq = NULL;
2187
2188         sock_release(r2net_listen_sock);
2189         r2net_listen_sock = NULL;
2190 }
2191
2192 void r2net_hb_node_up_manual(int node_num)
2193 {
2194         struct r2nm_node dummy;
2195         if (r2nm_single_cluster == NULL)
2196                 pr_err("ramster: cluster not alive, node_up_manual ignored\n");
2197         else {
2198                 r2hb_manual_set_node_heartbeating(node_num);
2199                 r2net_hb_node_up_cb(&dummy, node_num, NULL);
2200         }
2201 }
2202
2203 /* ------------------------------------------------------------ */
2204
2205 int r2net_init(void)
2206 {
2207         unsigned long i;
2208
2209         if (r2net_debugfs_init())
2210                 return -ENOMEM;
2211
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) {
2216                 kfree(r2net_hand);
2217                 kfree(r2net_keep_req);
2218                 kfree(r2net_keep_resp);
2219                 return -ENOMEM;
2220         }
2221
2222         r2net_hand->protocol_version = cpu_to_be64(R2NET_PROTOCOL_VERSION);
2223         r2net_hand->connector_id = cpu_to_be64(1);
2224
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);
2227
2228         for (i = 0; i < ARRAY_SIZE(r2net_nodes); i++) {
2229                 struct r2net_node *nn = r2net_nn_from_num(i);
2230
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);
2242         }
2243
2244         return 0;
2245 }
2246
2247 void r2net_exit(void)
2248 {
2249         kfree(r2net_hand);
2250         kfree(r2net_keep_req);
2251         kfree(r2net_keep_resp);
2252         r2net_debugfs_exit();
2253 }