fs: dlm: move free writequeue into con free
[linux-2.6-microblaze.git] / fs / dlm / lowcomms.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /******************************************************************************
3 *******************************************************************************
4 **
5 **  Copyright (C) Sistina Software, Inc.  1997-2003  All rights reserved.
6 **  Copyright (C) 2004-2009 Red Hat, Inc.  All rights reserved.
7 **
8 **
9 *******************************************************************************
10 ******************************************************************************/
11
12 /*
13  * lowcomms.c
14  *
15  * This is the "low-level" comms layer.
16  *
17  * It is responsible for sending/receiving messages
18  * from other nodes in the cluster.
19  *
20  * Cluster nodes are referred to by their nodeids. nodeids are
21  * simply 32 bit numbers to the locking module - if they need to
22  * be expanded for the cluster infrastructure then that is its
23  * responsibility. It is this layer's
24  * responsibility to resolve these into IP address or
25  * whatever it needs for inter-node communication.
26  *
27  * The comms level is two kernel threads that deal mainly with
28  * the receiving of messages from other nodes and passing them
29  * up to the mid-level comms layer (which understands the
30  * message format) for execution by the locking core, and
31  * a send thread which does all the setting up of connections
32  * to remote nodes and the sending of data. Threads are not allowed
33  * to send their own data because it may cause them to wait in times
34  * of high load. Also, this way, the sending thread can collect together
35  * messages bound for one node and send them in one block.
36  *
37  * lowcomms will choose to use either TCP or SCTP as its transport layer
38  * depending on the configuration variable 'protocol'. This should be set
39  * to 0 (default) for TCP or 1 for SCTP. It should be configured using a
40  * cluster-wide mechanism as it must be the same on all nodes of the cluster
41  * for the DLM to function.
42  *
43  */
44
45 #include <asm/ioctls.h>
46 #include <net/sock.h>
47 #include <net/tcp.h>
48 #include <linux/pagemap.h>
49 #include <linux/file.h>
50 #include <linux/mutex.h>
51 #include <linux/sctp.h>
52 #include <linux/slab.h>
53 #include <net/sctp/sctp.h>
54 #include <net/ipv6.h>
55
56 #include "dlm_internal.h"
57 #include "lowcomms.h"
58 #include "midcomms.h"
59 #include "config.h"
60
61 #define NEEDED_RMEM (4*1024*1024)
62 #define CONN_HASH_SIZE 32
63
64 /* Number of messages to send before rescheduling */
65 #define MAX_SEND_MSG_COUNT 25
66 #define DLM_SHUTDOWN_WAIT_TIMEOUT msecs_to_jiffies(10000)
67
68 struct cbuf {
69         unsigned int base;
70         unsigned int len;
71         unsigned int mask;
72 };
73
74 static void cbuf_add(struct cbuf *cb, int n)
75 {
76         cb->len += n;
77 }
78
79 static int cbuf_data(struct cbuf *cb)
80 {
81         return ((cb->base + cb->len) & cb->mask);
82 }
83
84 static void cbuf_init(struct cbuf *cb, int size)
85 {
86         cb->base = cb->len = 0;
87         cb->mask = size-1;
88 }
89
90 static void cbuf_eat(struct cbuf *cb, int n)
91 {
92         cb->len  -= n;
93         cb->base += n;
94         cb->base &= cb->mask;
95 }
96
97 static bool cbuf_empty(struct cbuf *cb)
98 {
99         return cb->len == 0;
100 }
101
102 struct connection {
103         struct socket *sock;    /* NULL if not connected */
104         uint32_t nodeid;        /* So we know who we are in the list */
105         struct mutex sock_mutex;
106         unsigned long flags;
107 #define CF_READ_PENDING 1
108 #define CF_WRITE_PENDING 2
109 #define CF_INIT_PENDING 4
110 #define CF_IS_OTHERCON 5
111 #define CF_CLOSE 6
112 #define CF_APP_LIMITED 7
113 #define CF_CLOSING 8
114 #define CF_SHUTDOWN 9
115         struct list_head writequeue;  /* List of outgoing writequeue_entries */
116         spinlock_t writequeue_lock;
117         int (*rx_action) (struct connection *); /* What to do when active */
118         void (*connect_action) (struct connection *);   /* What to do to connect */
119         void (*shutdown_action)(struct connection *con); /* What to do to shutdown */
120         struct page *rx_page;
121         struct cbuf cb;
122         int retries;
123 #define MAX_CONNECT_RETRIES 3
124         struct hlist_node list;
125         struct connection *othercon;
126         struct work_struct rwork; /* Receive workqueue */
127         struct work_struct swork; /* Send workqueue */
128         wait_queue_head_t shutdown_wait; /* wait for graceful shutdown */
129         struct rcu_head rcu;
130 };
131 #define sock2con(x) ((struct connection *)(x)->sk_user_data)
132
133 /* An entry waiting to be sent */
134 struct writequeue_entry {
135         struct list_head list;
136         struct page *page;
137         int offset;
138         int len;
139         int end;
140         int users;
141         struct connection *con;
142 };
143
144 struct dlm_node_addr {
145         struct list_head list;
146         int nodeid;
147         int addr_count;
148         int curr_addr_index;
149         struct sockaddr_storage *addr[DLM_MAX_ADDR_COUNT];
150 };
151
152 static struct listen_sock_callbacks {
153         void (*sk_error_report)(struct sock *);
154         void (*sk_data_ready)(struct sock *);
155         void (*sk_state_change)(struct sock *);
156         void (*sk_write_space)(struct sock *);
157 } listen_sock;
158
159 static LIST_HEAD(dlm_node_addrs);
160 static DEFINE_SPINLOCK(dlm_node_addrs_spin);
161
162 static struct sockaddr_storage *dlm_local_addr[DLM_MAX_ADDR_COUNT];
163 static int dlm_local_count;
164 static int dlm_allow_conn;
165
166 /* Work queues */
167 static struct workqueue_struct *recv_workqueue;
168 static struct workqueue_struct *send_workqueue;
169
170 static struct hlist_head connection_hash[CONN_HASH_SIZE];
171 static DEFINE_SPINLOCK(connections_lock);
172 DEFINE_STATIC_SRCU(connections_srcu);
173
174 static void process_recv_sockets(struct work_struct *work);
175 static void process_send_sockets(struct work_struct *work);
176
177
178 /* This is deliberately very simple because most clusters have simple
179    sequential nodeids, so we should be able to go straight to a connection
180    struct in the array */
181 static inline int nodeid_hash(int nodeid)
182 {
183         return nodeid & (CONN_HASH_SIZE-1);
184 }
185
186 static struct connection *__find_con(int nodeid)
187 {
188         int r, idx;
189         struct connection *con;
190
191         r = nodeid_hash(nodeid);
192
193         idx = srcu_read_lock(&connections_srcu);
194         hlist_for_each_entry_rcu(con, &connection_hash[r], list) {
195                 if (con->nodeid == nodeid) {
196                         srcu_read_unlock(&connections_srcu, idx);
197                         return con;
198                 }
199         }
200         srcu_read_unlock(&connections_srcu, idx);
201
202         return NULL;
203 }
204
205 /*
206  * If 'allocation' is zero then we don't attempt to create a new
207  * connection structure for this node.
208  */
209 static struct connection *nodeid2con(int nodeid, gfp_t alloc)
210 {
211         struct connection *con = NULL;
212         int r;
213
214         con = __find_con(nodeid);
215         if (con || !alloc)
216                 return con;
217
218         con = kzalloc(sizeof(*con), alloc);
219         if (!con)
220                 return NULL;
221
222         con->nodeid = nodeid;
223         mutex_init(&con->sock_mutex);
224         INIT_LIST_HEAD(&con->writequeue);
225         spin_lock_init(&con->writequeue_lock);
226         INIT_WORK(&con->swork, process_send_sockets);
227         INIT_WORK(&con->rwork, process_recv_sockets);
228         init_waitqueue_head(&con->shutdown_wait);
229
230         /* Setup action pointers for child sockets */
231         if (con->nodeid) {
232                 struct connection *zerocon = __find_con(0);
233
234                 con->connect_action = zerocon->connect_action;
235                 if (!con->rx_action)
236                         con->rx_action = zerocon->rx_action;
237         }
238
239         r = nodeid_hash(nodeid);
240
241         spin_lock(&connections_lock);
242         hlist_add_head_rcu(&con->list, &connection_hash[r]);
243         spin_unlock(&connections_lock);
244
245         return con;
246 }
247
248 /* Loop round all connections */
249 static void foreach_conn(void (*conn_func)(struct connection *c))
250 {
251         int i, idx;
252         struct connection *con;
253
254         idx = srcu_read_lock(&connections_srcu);
255         for (i = 0; i < CONN_HASH_SIZE; i++) {
256                 hlist_for_each_entry_rcu(con, &connection_hash[i], list)
257                         conn_func(con);
258         }
259         srcu_read_unlock(&connections_srcu, idx);
260 }
261
262 static struct dlm_node_addr *find_node_addr(int nodeid)
263 {
264         struct dlm_node_addr *na;
265
266         list_for_each_entry(na, &dlm_node_addrs, list) {
267                 if (na->nodeid == nodeid)
268                         return na;
269         }
270         return NULL;
271 }
272
273 static int addr_compare(struct sockaddr_storage *x, struct sockaddr_storage *y)
274 {
275         switch (x->ss_family) {
276         case AF_INET: {
277                 struct sockaddr_in *sinx = (struct sockaddr_in *)x;
278                 struct sockaddr_in *siny = (struct sockaddr_in *)y;
279                 if (sinx->sin_addr.s_addr != siny->sin_addr.s_addr)
280                         return 0;
281                 if (sinx->sin_port != siny->sin_port)
282                         return 0;
283                 break;
284         }
285         case AF_INET6: {
286                 struct sockaddr_in6 *sinx = (struct sockaddr_in6 *)x;
287                 struct sockaddr_in6 *siny = (struct sockaddr_in6 *)y;
288                 if (!ipv6_addr_equal(&sinx->sin6_addr, &siny->sin6_addr))
289                         return 0;
290                 if (sinx->sin6_port != siny->sin6_port)
291                         return 0;
292                 break;
293         }
294         default:
295                 return 0;
296         }
297         return 1;
298 }
299
300 static int nodeid_to_addr(int nodeid, struct sockaddr_storage *sas_out,
301                           struct sockaddr *sa_out, bool try_new_addr)
302 {
303         struct sockaddr_storage sas;
304         struct dlm_node_addr *na;
305
306         if (!dlm_local_count)
307                 return -1;
308
309         spin_lock(&dlm_node_addrs_spin);
310         na = find_node_addr(nodeid);
311         if (na && na->addr_count) {
312                 memcpy(&sas, na->addr[na->curr_addr_index],
313                        sizeof(struct sockaddr_storage));
314
315                 if (try_new_addr) {
316                         na->curr_addr_index++;
317                         if (na->curr_addr_index == na->addr_count)
318                                 na->curr_addr_index = 0;
319                 }
320         }
321         spin_unlock(&dlm_node_addrs_spin);
322
323         if (!na)
324                 return -EEXIST;
325
326         if (!na->addr_count)
327                 return -ENOENT;
328
329         if (sas_out)
330                 memcpy(sas_out, &sas, sizeof(struct sockaddr_storage));
331
332         if (!sa_out)
333                 return 0;
334
335         if (dlm_local_addr[0]->ss_family == AF_INET) {
336                 struct sockaddr_in *in4  = (struct sockaddr_in *) &sas;
337                 struct sockaddr_in *ret4 = (struct sockaddr_in *) sa_out;
338                 ret4->sin_addr.s_addr = in4->sin_addr.s_addr;
339         } else {
340                 struct sockaddr_in6 *in6  = (struct sockaddr_in6 *) &sas;
341                 struct sockaddr_in6 *ret6 = (struct sockaddr_in6 *) sa_out;
342                 ret6->sin6_addr = in6->sin6_addr;
343         }
344
345         return 0;
346 }
347
348 static int addr_to_nodeid(struct sockaddr_storage *addr, int *nodeid)
349 {
350         struct dlm_node_addr *na;
351         int rv = -EEXIST;
352         int addr_i;
353
354         spin_lock(&dlm_node_addrs_spin);
355         list_for_each_entry(na, &dlm_node_addrs, list) {
356                 if (!na->addr_count)
357                         continue;
358
359                 for (addr_i = 0; addr_i < na->addr_count; addr_i++) {
360                         if (addr_compare(na->addr[addr_i], addr)) {
361                                 *nodeid = na->nodeid;
362                                 rv = 0;
363                                 goto unlock;
364                         }
365                 }
366         }
367 unlock:
368         spin_unlock(&dlm_node_addrs_spin);
369         return rv;
370 }
371
372 int dlm_lowcomms_addr(int nodeid, struct sockaddr_storage *addr, int len)
373 {
374         struct sockaddr_storage *new_addr;
375         struct dlm_node_addr *new_node, *na;
376
377         new_node = kzalloc(sizeof(struct dlm_node_addr), GFP_NOFS);
378         if (!new_node)
379                 return -ENOMEM;
380
381         new_addr = kzalloc(sizeof(struct sockaddr_storage), GFP_NOFS);
382         if (!new_addr) {
383                 kfree(new_node);
384                 return -ENOMEM;
385         }
386
387         memcpy(new_addr, addr, len);
388
389         spin_lock(&dlm_node_addrs_spin);
390         na = find_node_addr(nodeid);
391         if (!na) {
392                 new_node->nodeid = nodeid;
393                 new_node->addr[0] = new_addr;
394                 new_node->addr_count = 1;
395                 list_add(&new_node->list, &dlm_node_addrs);
396                 spin_unlock(&dlm_node_addrs_spin);
397                 return 0;
398         }
399
400         if (na->addr_count >= DLM_MAX_ADDR_COUNT) {
401                 spin_unlock(&dlm_node_addrs_spin);
402                 kfree(new_addr);
403                 kfree(new_node);
404                 return -ENOSPC;
405         }
406
407         na->addr[na->addr_count++] = new_addr;
408         spin_unlock(&dlm_node_addrs_spin);
409         kfree(new_node);
410         return 0;
411 }
412
413 /* Data available on socket or listen socket received a connect */
414 static void lowcomms_data_ready(struct sock *sk)
415 {
416         struct connection *con;
417
418         read_lock_bh(&sk->sk_callback_lock);
419         con = sock2con(sk);
420         if (con && !test_and_set_bit(CF_READ_PENDING, &con->flags))
421                 queue_work(recv_workqueue, &con->rwork);
422         read_unlock_bh(&sk->sk_callback_lock);
423 }
424
425 static void lowcomms_write_space(struct sock *sk)
426 {
427         struct connection *con;
428
429         read_lock_bh(&sk->sk_callback_lock);
430         con = sock2con(sk);
431         if (!con)
432                 goto out;
433
434         clear_bit(SOCK_NOSPACE, &con->sock->flags);
435
436         if (test_and_clear_bit(CF_APP_LIMITED, &con->flags)) {
437                 con->sock->sk->sk_write_pending--;
438                 clear_bit(SOCKWQ_ASYNC_NOSPACE, &con->sock->flags);
439         }
440
441         queue_work(send_workqueue, &con->swork);
442 out:
443         read_unlock_bh(&sk->sk_callback_lock);
444 }
445
446 static inline void lowcomms_connect_sock(struct connection *con)
447 {
448         if (test_bit(CF_CLOSE, &con->flags))
449                 return;
450         queue_work(send_workqueue, &con->swork);
451         cond_resched();
452 }
453
454 static void lowcomms_state_change(struct sock *sk)
455 {
456         /* SCTP layer is not calling sk_data_ready when the connection
457          * is done, so we catch the signal through here. Also, it
458          * doesn't switch socket state when entering shutdown, so we
459          * skip the write in that case.
460          */
461         if (sk->sk_shutdown) {
462                 if (sk->sk_shutdown == RCV_SHUTDOWN)
463                         lowcomms_data_ready(sk);
464         } else if (sk->sk_state == TCP_ESTABLISHED) {
465                 lowcomms_write_space(sk);
466         }
467 }
468
469 int dlm_lowcomms_connect_node(int nodeid)
470 {
471         struct connection *con;
472
473         if (nodeid == dlm_our_nodeid())
474                 return 0;
475
476         con = nodeid2con(nodeid, GFP_NOFS);
477         if (!con)
478                 return -ENOMEM;
479         lowcomms_connect_sock(con);
480         return 0;
481 }
482
483 static void lowcomms_error_report(struct sock *sk)
484 {
485         struct connection *con;
486         struct sockaddr_storage saddr;
487         void (*orig_report)(struct sock *) = NULL;
488
489         read_lock_bh(&sk->sk_callback_lock);
490         con = sock2con(sk);
491         if (con == NULL)
492                 goto out;
493
494         orig_report = listen_sock.sk_error_report;
495         if (con->sock == NULL ||
496             kernel_getpeername(con->sock, (struct sockaddr *)&saddr) < 0) {
497                 printk_ratelimited(KERN_ERR "dlm: node %d: socket error "
498                                    "sending to node %d, port %d, "
499                                    "sk_err=%d/%d\n", dlm_our_nodeid(),
500                                    con->nodeid, dlm_config.ci_tcp_port,
501                                    sk->sk_err, sk->sk_err_soft);
502         } else if (saddr.ss_family == AF_INET) {
503                 struct sockaddr_in *sin4 = (struct sockaddr_in *)&saddr;
504
505                 printk_ratelimited(KERN_ERR "dlm: node %d: socket error "
506                                    "sending to node %d at %pI4, port %d, "
507                                    "sk_err=%d/%d\n", dlm_our_nodeid(),
508                                    con->nodeid, &sin4->sin_addr.s_addr,
509                                    dlm_config.ci_tcp_port, sk->sk_err,
510                                    sk->sk_err_soft);
511         } else {
512                 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&saddr;
513
514                 printk_ratelimited(KERN_ERR "dlm: node %d: socket error "
515                                    "sending to node %d at %u.%u.%u.%u, "
516                                    "port %d, sk_err=%d/%d\n", dlm_our_nodeid(),
517                                    con->nodeid, sin6->sin6_addr.s6_addr32[0],
518                                    sin6->sin6_addr.s6_addr32[1],
519                                    sin6->sin6_addr.s6_addr32[2],
520                                    sin6->sin6_addr.s6_addr32[3],
521                                    dlm_config.ci_tcp_port, sk->sk_err,
522                                    sk->sk_err_soft);
523         }
524 out:
525         read_unlock_bh(&sk->sk_callback_lock);
526         if (orig_report)
527                 orig_report(sk);
528 }
529
530 /* Note: sk_callback_lock must be locked before calling this function. */
531 static void save_listen_callbacks(struct socket *sock)
532 {
533         struct sock *sk = sock->sk;
534
535         listen_sock.sk_data_ready = sk->sk_data_ready;
536         listen_sock.sk_state_change = sk->sk_state_change;
537         listen_sock.sk_write_space = sk->sk_write_space;
538         listen_sock.sk_error_report = sk->sk_error_report;
539 }
540
541 static void restore_callbacks(struct socket *sock)
542 {
543         struct sock *sk = sock->sk;
544
545         write_lock_bh(&sk->sk_callback_lock);
546         sk->sk_user_data = NULL;
547         sk->sk_data_ready = listen_sock.sk_data_ready;
548         sk->sk_state_change = listen_sock.sk_state_change;
549         sk->sk_write_space = listen_sock.sk_write_space;
550         sk->sk_error_report = listen_sock.sk_error_report;
551         write_unlock_bh(&sk->sk_callback_lock);
552 }
553
554 /* Make a socket active */
555 static void add_sock(struct socket *sock, struct connection *con)
556 {
557         struct sock *sk = sock->sk;
558
559         write_lock_bh(&sk->sk_callback_lock);
560         con->sock = sock;
561
562         sk->sk_user_data = con;
563         /* Install a data_ready callback */
564         sk->sk_data_ready = lowcomms_data_ready;
565         sk->sk_write_space = lowcomms_write_space;
566         sk->sk_state_change = lowcomms_state_change;
567         sk->sk_allocation = GFP_NOFS;
568         sk->sk_error_report = lowcomms_error_report;
569         write_unlock_bh(&sk->sk_callback_lock);
570 }
571
572 /* Add the port number to an IPv6 or 4 sockaddr and return the address
573    length */
574 static void make_sockaddr(struct sockaddr_storage *saddr, uint16_t port,
575                           int *addr_len)
576 {
577         saddr->ss_family =  dlm_local_addr[0]->ss_family;
578         if (saddr->ss_family == AF_INET) {
579                 struct sockaddr_in *in4_addr = (struct sockaddr_in *)saddr;
580                 in4_addr->sin_port = cpu_to_be16(port);
581                 *addr_len = sizeof(struct sockaddr_in);
582                 memset(&in4_addr->sin_zero, 0, sizeof(in4_addr->sin_zero));
583         } else {
584                 struct sockaddr_in6 *in6_addr = (struct sockaddr_in6 *)saddr;
585                 in6_addr->sin6_port = cpu_to_be16(port);
586                 *addr_len = sizeof(struct sockaddr_in6);
587         }
588         memset((char *)saddr + *addr_len, 0, sizeof(struct sockaddr_storage) - *addr_len);
589 }
590
591 /* Close a remote connection and tidy up */
592 static void close_connection(struct connection *con, bool and_other,
593                              bool tx, bool rx)
594 {
595         bool closing = test_and_set_bit(CF_CLOSING, &con->flags);
596
597         if (tx && !closing && cancel_work_sync(&con->swork)) {
598                 log_print("canceled swork for node %d", con->nodeid);
599                 clear_bit(CF_WRITE_PENDING, &con->flags);
600         }
601         if (rx && !closing && cancel_work_sync(&con->rwork)) {
602                 log_print("canceled rwork for node %d", con->nodeid);
603                 clear_bit(CF_READ_PENDING, &con->flags);
604         }
605
606         mutex_lock(&con->sock_mutex);
607         if (con->sock) {
608                 restore_callbacks(con->sock);
609                 sock_release(con->sock);
610                 con->sock = NULL;
611         }
612         if (con->othercon && and_other) {
613                 /* Will only re-enter once. */
614                 close_connection(con->othercon, false, true, true);
615         }
616         if (con->rx_page) {
617                 __free_page(con->rx_page);
618                 con->rx_page = NULL;
619         }
620
621         con->retries = 0;
622         mutex_unlock(&con->sock_mutex);
623         clear_bit(CF_CLOSING, &con->flags);
624 }
625
626 static void shutdown_connection(struct connection *con)
627 {
628         int ret;
629
630         if (cancel_work_sync(&con->swork)) {
631                 log_print("canceled swork for node %d", con->nodeid);
632                 clear_bit(CF_WRITE_PENDING, &con->flags);
633         }
634
635         mutex_lock(&con->sock_mutex);
636         /* nothing to shutdown */
637         if (!con->sock) {
638                 mutex_unlock(&con->sock_mutex);
639                 return;
640         }
641
642         set_bit(CF_SHUTDOWN, &con->flags);
643         ret = kernel_sock_shutdown(con->sock, SHUT_WR);
644         mutex_unlock(&con->sock_mutex);
645         if (ret) {
646                 log_print("Connection %p failed to shutdown: %d will force close",
647                           con, ret);
648                 goto force_close;
649         } else {
650                 ret = wait_event_timeout(con->shutdown_wait,
651                                          !test_bit(CF_SHUTDOWN, &con->flags),
652                                          DLM_SHUTDOWN_WAIT_TIMEOUT);
653                 if (ret == 0) {
654                         log_print("Connection %p shutdown timed out, will force close",
655                                   con);
656                         goto force_close;
657                 }
658         }
659
660         return;
661
662 force_close:
663         clear_bit(CF_SHUTDOWN, &con->flags);
664         close_connection(con, false, true, true);
665 }
666
667 static void dlm_tcp_shutdown(struct connection *con)
668 {
669         if (con->othercon)
670                 shutdown_connection(con->othercon);
671         shutdown_connection(con);
672 }
673
674 /* Data received from remote end */
675 static int receive_from_sock(struct connection *con)
676 {
677         int ret = 0;
678         struct msghdr msg = {};
679         struct kvec iov[2];
680         unsigned len;
681         int r;
682         int call_again_soon = 0;
683         int nvec;
684
685         mutex_lock(&con->sock_mutex);
686
687         if (con->sock == NULL) {
688                 ret = -EAGAIN;
689                 goto out_close;
690         }
691         if (con->nodeid == 0) {
692                 ret = -EINVAL;
693                 goto out_close;
694         }
695
696         if (con->rx_page == NULL) {
697                 /*
698                  * This doesn't need to be atomic, but I think it should
699                  * improve performance if it is.
700                  */
701                 con->rx_page = alloc_page(GFP_ATOMIC);
702                 if (con->rx_page == NULL)
703                         goto out_resched;
704                 cbuf_init(&con->cb, PAGE_SIZE);
705         }
706
707         /*
708          * iov[0] is the bit of the circular buffer between the current end
709          * point (cb.base + cb.len) and the end of the buffer.
710          */
711         iov[0].iov_len = con->cb.base - cbuf_data(&con->cb);
712         iov[0].iov_base = page_address(con->rx_page) + cbuf_data(&con->cb);
713         iov[1].iov_len = 0;
714         nvec = 1;
715
716         /*
717          * iov[1] is the bit of the circular buffer between the start of the
718          * buffer and the start of the currently used section (cb.base)
719          */
720         if (cbuf_data(&con->cb) >= con->cb.base) {
721                 iov[0].iov_len = PAGE_SIZE - cbuf_data(&con->cb);
722                 iov[1].iov_len = con->cb.base;
723                 iov[1].iov_base = page_address(con->rx_page);
724                 nvec = 2;
725         }
726         len = iov[0].iov_len + iov[1].iov_len;
727         iov_iter_kvec(&msg.msg_iter, READ, iov, nvec, len);
728
729         r = ret = sock_recvmsg(con->sock, &msg, MSG_DONTWAIT | MSG_NOSIGNAL);
730         if (ret <= 0)
731                 goto out_close;
732         else if (ret == len)
733                 call_again_soon = 1;
734
735         cbuf_add(&con->cb, ret);
736         ret = dlm_process_incoming_buffer(con->nodeid,
737                                           page_address(con->rx_page),
738                                           con->cb.base, con->cb.len,
739                                           PAGE_SIZE);
740         if (ret < 0) {
741                 log_print("lowcomms err %d: addr=%p, base=%u, len=%u, read=%d",
742                           ret, page_address(con->rx_page), con->cb.base,
743                           con->cb.len, r);
744                 cbuf_eat(&con->cb, r);
745         } else {
746                 cbuf_eat(&con->cb, ret);
747         }
748
749         if (cbuf_empty(&con->cb) && !call_again_soon) {
750                 __free_page(con->rx_page);
751                 con->rx_page = NULL;
752         }
753
754         if (call_again_soon)
755                 goto out_resched;
756         mutex_unlock(&con->sock_mutex);
757         return 0;
758
759 out_resched:
760         if (!test_and_set_bit(CF_READ_PENDING, &con->flags))
761                 queue_work(recv_workqueue, &con->rwork);
762         mutex_unlock(&con->sock_mutex);
763         return -EAGAIN;
764
765 out_close:
766         mutex_unlock(&con->sock_mutex);
767         if (ret != -EAGAIN) {
768                 /* Reconnect when there is something to send */
769                 close_connection(con, false, true, false);
770                 if (ret == 0) {
771                         log_print("connection %p got EOF from %d",
772                                   con, con->nodeid);
773                         /* handling for tcp shutdown */
774                         clear_bit(CF_SHUTDOWN, &con->flags);
775                         wake_up(&con->shutdown_wait);
776                         /* signal to breaking receive worker */
777                         ret = -1;
778                 }
779         }
780         return ret;
781 }
782
783 /* Listening socket is busy, accept a connection */
784 static int accept_from_sock(struct connection *con)
785 {
786         int result;
787         struct sockaddr_storage peeraddr;
788         struct socket *newsock;
789         int len;
790         int nodeid;
791         struct connection *newcon;
792         struct connection *addcon;
793
794         if (!dlm_allow_conn) {
795                 return -1;
796         }
797
798         mutex_lock_nested(&con->sock_mutex, 0);
799
800         if (!con->sock) {
801                 mutex_unlock(&con->sock_mutex);
802                 return -ENOTCONN;
803         }
804
805         result = kernel_accept(con->sock, &newsock, O_NONBLOCK);
806         if (result < 0)
807                 goto accept_err;
808
809         /* Get the connected socket's peer */
810         memset(&peeraddr, 0, sizeof(peeraddr));
811         len = newsock->ops->getname(newsock, (struct sockaddr *)&peeraddr, 2);
812         if (len < 0) {
813                 result = -ECONNABORTED;
814                 goto accept_err;
815         }
816
817         /* Get the new node's NODEID */
818         make_sockaddr(&peeraddr, 0, &len);
819         if (addr_to_nodeid(&peeraddr, &nodeid)) {
820                 unsigned char *b=(unsigned char *)&peeraddr;
821                 log_print("connect from non cluster node");
822                 print_hex_dump_bytes("ss: ", DUMP_PREFIX_NONE, 
823                                      b, sizeof(struct sockaddr_storage));
824                 sock_release(newsock);
825                 mutex_unlock(&con->sock_mutex);
826                 return -1;
827         }
828
829         log_print("got connection from %d", nodeid);
830
831         /*  Check to see if we already have a connection to this node. This
832          *  could happen if the two nodes initiate a connection at roughly
833          *  the same time and the connections cross on the wire.
834          *  In this case we store the incoming one in "othercon"
835          */
836         newcon = nodeid2con(nodeid, GFP_NOFS);
837         if (!newcon) {
838                 result = -ENOMEM;
839                 goto accept_err;
840         }
841         mutex_lock_nested(&newcon->sock_mutex, 1);
842         if (newcon->sock) {
843                 struct connection *othercon = newcon->othercon;
844
845                 if (!othercon) {
846                         othercon = kzalloc(sizeof(*othercon), GFP_NOFS);
847                         if (!othercon) {
848                                 log_print("failed to allocate incoming socket");
849                                 mutex_unlock(&newcon->sock_mutex);
850                                 result = -ENOMEM;
851                                 goto accept_err;
852                         }
853                         othercon->nodeid = nodeid;
854                         othercon->rx_action = receive_from_sock;
855                         mutex_init(&othercon->sock_mutex);
856                         INIT_LIST_HEAD(&othercon->writequeue);
857                         spin_lock_init(&othercon->writequeue_lock);
858                         INIT_WORK(&othercon->swork, process_send_sockets);
859                         INIT_WORK(&othercon->rwork, process_recv_sockets);
860                         init_waitqueue_head(&othercon->shutdown_wait);
861                         set_bit(CF_IS_OTHERCON, &othercon->flags);
862                 } else {
863                         /* close other sock con if we have something new */
864                         close_connection(othercon, false, true, false);
865                 }
866
867                 mutex_lock_nested(&othercon->sock_mutex, 2);
868                 newcon->othercon = othercon;
869                 add_sock(newsock, othercon);
870                 addcon = othercon;
871                 mutex_unlock(&othercon->sock_mutex);
872         }
873         else {
874                 newcon->rx_action = receive_from_sock;
875                 /* accept copies the sk after we've saved the callbacks, so we
876                    don't want to save them a second time or comm errors will
877                    result in calling sk_error_report recursively. */
878                 add_sock(newsock, newcon);
879                 addcon = newcon;
880         }
881
882         mutex_unlock(&newcon->sock_mutex);
883
884         /*
885          * Add it to the active queue in case we got data
886          * between processing the accept adding the socket
887          * to the read_sockets list
888          */
889         if (!test_and_set_bit(CF_READ_PENDING, &addcon->flags))
890                 queue_work(recv_workqueue, &addcon->rwork);
891         mutex_unlock(&con->sock_mutex);
892
893         return 0;
894
895 accept_err:
896         mutex_unlock(&con->sock_mutex);
897         if (newsock)
898                 sock_release(newsock);
899
900         if (result != -EAGAIN)
901                 log_print("error accepting connection from node: %d", result);
902         return result;
903 }
904
905 static void free_entry(struct writequeue_entry *e)
906 {
907         __free_page(e->page);
908         kfree(e);
909 }
910
911 /*
912  * writequeue_entry_complete - try to delete and free write queue entry
913  * @e: write queue entry to try to delete
914  * @completed: bytes completed
915  *
916  * writequeue_lock must be held.
917  */
918 static void writequeue_entry_complete(struct writequeue_entry *e, int completed)
919 {
920         e->offset += completed;
921         e->len -= completed;
922
923         if (e->len == 0 && e->users == 0) {
924                 list_del(&e->list);
925                 free_entry(e);
926         }
927 }
928
929 /*
930  * sctp_bind_addrs - bind a SCTP socket to all our addresses
931  */
932 static int sctp_bind_addrs(struct connection *con, uint16_t port)
933 {
934         struct sockaddr_storage localaddr;
935         struct sockaddr *addr = (struct sockaddr *)&localaddr;
936         int i, addr_len, result = 0;
937
938         for (i = 0; i < dlm_local_count; i++) {
939                 memcpy(&localaddr, dlm_local_addr[i], sizeof(localaddr));
940                 make_sockaddr(&localaddr, port, &addr_len);
941
942                 if (!i)
943                         result = kernel_bind(con->sock, addr, addr_len);
944                 else
945                         result = sock_bind_add(con->sock->sk, addr, addr_len);
946
947                 if (result < 0) {
948                         log_print("Can't bind to %d addr number %d, %d.\n",
949                                   port, i + 1, result);
950                         break;
951                 }
952         }
953         return result;
954 }
955
956 /* Initiate an SCTP association.
957    This is a special case of send_to_sock() in that we don't yet have a
958    peeled-off socket for this association, so we use the listening socket
959    and add the primary IP address of the remote node.
960  */
961 static void sctp_connect_to_sock(struct connection *con)
962 {
963         struct sockaddr_storage daddr;
964         int result;
965         int addr_len;
966         struct socket *sock;
967         unsigned int mark;
968
969         if (con->nodeid == 0) {
970                 log_print("attempt to connect sock 0 foiled");
971                 return;
972         }
973
974         mutex_lock(&con->sock_mutex);
975
976         /* Some odd races can cause double-connects, ignore them */
977         if (con->retries++ > MAX_CONNECT_RETRIES)
978                 goto out;
979
980         if (con->sock) {
981                 log_print("node %d already connected.", con->nodeid);
982                 goto out;
983         }
984
985         memset(&daddr, 0, sizeof(daddr));
986         result = nodeid_to_addr(con->nodeid, &daddr, NULL, true);
987         if (result < 0) {
988                 log_print("no address for nodeid %d", con->nodeid);
989                 goto out;
990         }
991
992         /* Create a socket to communicate with */
993         result = sock_create_kern(&init_net, dlm_local_addr[0]->ss_family,
994                                   SOCK_STREAM, IPPROTO_SCTP, &sock);
995         if (result < 0)
996                 goto socket_err;
997
998         /* set skb mark */
999         result = dlm_comm_mark(con->nodeid, &mark);
1000         if (result < 0)
1001                 goto bind_err;
1002
1003         sock_set_mark(sock->sk, mark);
1004
1005         con->rx_action = receive_from_sock;
1006         con->connect_action = sctp_connect_to_sock;
1007         add_sock(sock, con);
1008
1009         /* Bind to all addresses. */
1010         if (sctp_bind_addrs(con, 0))
1011                 goto bind_err;
1012
1013         make_sockaddr(&daddr, dlm_config.ci_tcp_port, &addr_len);
1014
1015         log_print("connecting to %d", con->nodeid);
1016
1017         /* Turn off Nagle's algorithm */
1018         sctp_sock_set_nodelay(sock->sk);
1019
1020         /*
1021          * Make sock->ops->connect() function return in specified time,
1022          * since O_NONBLOCK argument in connect() function does not work here,
1023          * then, we should restore the default value of this attribute.
1024          */
1025         sock_set_sndtimeo(sock->sk, 5);
1026         result = sock->ops->connect(sock, (struct sockaddr *)&daddr, addr_len,
1027                                    0);
1028         sock_set_sndtimeo(sock->sk, 0);
1029
1030         if (result == -EINPROGRESS)
1031                 result = 0;
1032         if (result == 0)
1033                 goto out;
1034
1035 bind_err:
1036         con->sock = NULL;
1037         sock_release(sock);
1038
1039 socket_err:
1040         /*
1041          * Some errors are fatal and this list might need adjusting. For other
1042          * errors we try again until the max number of retries is reached.
1043          */
1044         if (result != -EHOSTUNREACH &&
1045             result != -ENETUNREACH &&
1046             result != -ENETDOWN &&
1047             result != -EINVAL &&
1048             result != -EPROTONOSUPPORT) {
1049                 log_print("connect %d try %d error %d", con->nodeid,
1050                           con->retries, result);
1051                 mutex_unlock(&con->sock_mutex);
1052                 msleep(1000);
1053                 lowcomms_connect_sock(con);
1054                 return;
1055         }
1056
1057 out:
1058         mutex_unlock(&con->sock_mutex);
1059 }
1060
1061 /* Connect a new socket to its peer */
1062 static void tcp_connect_to_sock(struct connection *con)
1063 {
1064         struct sockaddr_storage saddr, src_addr;
1065         int addr_len;
1066         struct socket *sock = NULL;
1067         unsigned int mark;
1068         int result;
1069
1070         if (con->nodeid == 0) {
1071                 log_print("attempt to connect sock 0 foiled");
1072                 return;
1073         }
1074
1075         mutex_lock(&con->sock_mutex);
1076         if (con->retries++ > MAX_CONNECT_RETRIES)
1077                 goto out;
1078
1079         /* Some odd races can cause double-connects, ignore them */
1080         if (con->sock)
1081                 goto out;
1082
1083         /* Create a socket to communicate with */
1084         result = sock_create_kern(&init_net, dlm_local_addr[0]->ss_family,
1085                                   SOCK_STREAM, IPPROTO_TCP, &sock);
1086         if (result < 0)
1087                 goto out_err;
1088
1089         /* set skb mark */
1090         result = dlm_comm_mark(con->nodeid, &mark);
1091         if (result < 0)
1092                 goto out_err;
1093
1094         sock_set_mark(sock->sk, mark);
1095
1096         memset(&saddr, 0, sizeof(saddr));
1097         result = nodeid_to_addr(con->nodeid, &saddr, NULL, false);
1098         if (result < 0) {
1099                 log_print("no address for nodeid %d", con->nodeid);
1100                 goto out_err;
1101         }
1102
1103         con->rx_action = receive_from_sock;
1104         con->connect_action = tcp_connect_to_sock;
1105         con->shutdown_action = dlm_tcp_shutdown;
1106         add_sock(sock, con);
1107
1108         /* Bind to our cluster-known address connecting to avoid
1109            routing problems */
1110         memcpy(&src_addr, dlm_local_addr[0], sizeof(src_addr));
1111         make_sockaddr(&src_addr, 0, &addr_len);
1112         result = sock->ops->bind(sock, (struct sockaddr *) &src_addr,
1113                                  addr_len);
1114         if (result < 0) {
1115                 log_print("could not bind for connect: %d", result);
1116                 /* This *may* not indicate a critical error */
1117         }
1118
1119         make_sockaddr(&saddr, dlm_config.ci_tcp_port, &addr_len);
1120
1121         log_print("connecting to %d", con->nodeid);
1122
1123         /* Turn off Nagle's algorithm */
1124         tcp_sock_set_nodelay(sock->sk);
1125
1126         result = sock->ops->connect(sock, (struct sockaddr *)&saddr, addr_len,
1127                                    O_NONBLOCK);
1128         if (result == -EINPROGRESS)
1129                 result = 0;
1130         if (result == 0)
1131                 goto out;
1132
1133 out_err:
1134         if (con->sock) {
1135                 sock_release(con->sock);
1136                 con->sock = NULL;
1137         } else if (sock) {
1138                 sock_release(sock);
1139         }
1140         /*
1141          * Some errors are fatal and this list might need adjusting. For other
1142          * errors we try again until the max number of retries is reached.
1143          */
1144         if (result != -EHOSTUNREACH &&
1145             result != -ENETUNREACH &&
1146             result != -ENETDOWN && 
1147             result != -EINVAL &&
1148             result != -EPROTONOSUPPORT) {
1149                 log_print("connect %d try %d error %d", con->nodeid,
1150                           con->retries, result);
1151                 mutex_unlock(&con->sock_mutex);
1152                 msleep(1000);
1153                 lowcomms_connect_sock(con);
1154                 return;
1155         }
1156 out:
1157         mutex_unlock(&con->sock_mutex);
1158         return;
1159 }
1160
1161 static struct socket *tcp_create_listen_sock(struct connection *con,
1162                                              struct sockaddr_storage *saddr)
1163 {
1164         struct socket *sock = NULL;
1165         int result = 0;
1166         int addr_len;
1167
1168         if (dlm_local_addr[0]->ss_family == AF_INET)
1169                 addr_len = sizeof(struct sockaddr_in);
1170         else
1171                 addr_len = sizeof(struct sockaddr_in6);
1172
1173         /* Create a socket to communicate with */
1174         result = sock_create_kern(&init_net, dlm_local_addr[0]->ss_family,
1175                                   SOCK_STREAM, IPPROTO_TCP, &sock);
1176         if (result < 0) {
1177                 log_print("Can't create listening comms socket");
1178                 goto create_out;
1179         }
1180
1181         sock_set_mark(sock->sk, dlm_config.ci_mark);
1182
1183         /* Turn off Nagle's algorithm */
1184         tcp_sock_set_nodelay(sock->sk);
1185
1186         sock_set_reuseaddr(sock->sk);
1187
1188         write_lock_bh(&sock->sk->sk_callback_lock);
1189         sock->sk->sk_user_data = con;
1190         save_listen_callbacks(sock);
1191         con->rx_action = accept_from_sock;
1192         con->connect_action = tcp_connect_to_sock;
1193         write_unlock_bh(&sock->sk->sk_callback_lock);
1194
1195         /* Bind to our port */
1196         make_sockaddr(saddr, dlm_config.ci_tcp_port, &addr_len);
1197         result = sock->ops->bind(sock, (struct sockaddr *) saddr, addr_len);
1198         if (result < 0) {
1199                 log_print("Can't bind to port %d", dlm_config.ci_tcp_port);
1200                 sock_release(sock);
1201                 sock = NULL;
1202                 con->sock = NULL;
1203                 goto create_out;
1204         }
1205         sock_set_keepalive(sock->sk);
1206
1207         result = sock->ops->listen(sock, 5);
1208         if (result < 0) {
1209                 log_print("Can't listen on port %d", dlm_config.ci_tcp_port);
1210                 sock_release(sock);
1211                 sock = NULL;
1212                 goto create_out;
1213         }
1214
1215 create_out:
1216         return sock;
1217 }
1218
1219 /* Get local addresses */
1220 static void init_local(void)
1221 {
1222         struct sockaddr_storage sas, *addr;
1223         int i;
1224
1225         dlm_local_count = 0;
1226         for (i = 0; i < DLM_MAX_ADDR_COUNT; i++) {
1227                 if (dlm_our_addr(&sas, i))
1228                         break;
1229
1230                 addr = kmemdup(&sas, sizeof(*addr), GFP_NOFS);
1231                 if (!addr)
1232                         break;
1233                 dlm_local_addr[dlm_local_count++] = addr;
1234         }
1235 }
1236
1237 static void deinit_local(void)
1238 {
1239         int i;
1240
1241         for (i = 0; i < dlm_local_count; i++)
1242                 kfree(dlm_local_addr[i]);
1243 }
1244
1245 /* Initialise SCTP socket and bind to all interfaces */
1246 static int sctp_listen_for_all(void)
1247 {
1248         struct socket *sock = NULL;
1249         int result = -EINVAL;
1250         struct connection *con = nodeid2con(0, GFP_NOFS);
1251
1252         if (!con)
1253                 return -ENOMEM;
1254
1255         log_print("Using SCTP for communications");
1256
1257         result = sock_create_kern(&init_net, dlm_local_addr[0]->ss_family,
1258                                   SOCK_STREAM, IPPROTO_SCTP, &sock);
1259         if (result < 0) {
1260                 log_print("Can't create comms socket, check SCTP is loaded");
1261                 goto out;
1262         }
1263
1264         sock_set_rcvbuf(sock->sk, NEEDED_RMEM);
1265         sock_set_mark(sock->sk, dlm_config.ci_mark);
1266         sctp_sock_set_nodelay(sock->sk);
1267
1268         write_lock_bh(&sock->sk->sk_callback_lock);
1269         /* Init con struct */
1270         sock->sk->sk_user_data = con;
1271         save_listen_callbacks(sock);
1272         con->sock = sock;
1273         con->sock->sk->sk_data_ready = lowcomms_data_ready;
1274         con->rx_action = accept_from_sock;
1275         con->connect_action = sctp_connect_to_sock;
1276
1277         write_unlock_bh(&sock->sk->sk_callback_lock);
1278
1279         /* Bind to all addresses. */
1280         if (sctp_bind_addrs(con, dlm_config.ci_tcp_port))
1281                 goto create_delsock;
1282
1283         result = sock->ops->listen(sock, 5);
1284         if (result < 0) {
1285                 log_print("Can't set socket listening");
1286                 goto create_delsock;
1287         }
1288
1289         return 0;
1290
1291 create_delsock:
1292         sock_release(sock);
1293         con->sock = NULL;
1294 out:
1295         return result;
1296 }
1297
1298 static int tcp_listen_for_all(void)
1299 {
1300         struct socket *sock = NULL;
1301         struct connection *con = nodeid2con(0, GFP_NOFS);
1302         int result = -EINVAL;
1303
1304         if (!con)
1305                 return -ENOMEM;
1306
1307         /* We don't support multi-homed hosts */
1308         if (dlm_local_addr[1] != NULL) {
1309                 log_print("TCP protocol can't handle multi-homed hosts, "
1310                           "try SCTP");
1311                 return -EINVAL;
1312         }
1313
1314         log_print("Using TCP for communications");
1315
1316         sock = tcp_create_listen_sock(con, dlm_local_addr[0]);
1317         if (sock) {
1318                 add_sock(sock, con);
1319                 result = 0;
1320         }
1321         else {
1322                 result = -EADDRINUSE;
1323         }
1324
1325         return result;
1326 }
1327
1328
1329
1330 static struct writequeue_entry *new_writequeue_entry(struct connection *con,
1331                                                      gfp_t allocation)
1332 {
1333         struct writequeue_entry *entry;
1334
1335         entry = kmalloc(sizeof(struct writequeue_entry), allocation);
1336         if (!entry)
1337                 return NULL;
1338
1339         entry->page = alloc_page(allocation);
1340         if (!entry->page) {
1341                 kfree(entry);
1342                 return NULL;
1343         }
1344
1345         entry->offset = 0;
1346         entry->len = 0;
1347         entry->end = 0;
1348         entry->users = 0;
1349         entry->con = con;
1350
1351         return entry;
1352 }
1353
1354 void *dlm_lowcomms_get_buffer(int nodeid, int len, gfp_t allocation, char **ppc)
1355 {
1356         struct connection *con;
1357         struct writequeue_entry *e;
1358         int offset = 0;
1359
1360         con = nodeid2con(nodeid, allocation);
1361         if (!con)
1362                 return NULL;
1363
1364         spin_lock(&con->writequeue_lock);
1365         e = list_entry(con->writequeue.prev, struct writequeue_entry, list);
1366         if ((&e->list == &con->writequeue) ||
1367             (PAGE_SIZE - e->end < len)) {
1368                 e = NULL;
1369         } else {
1370                 offset = e->end;
1371                 e->end += len;
1372                 e->users++;
1373         }
1374         spin_unlock(&con->writequeue_lock);
1375
1376         if (e) {
1377         got_one:
1378                 *ppc = page_address(e->page) + offset;
1379                 return e;
1380         }
1381
1382         e = new_writequeue_entry(con, allocation);
1383         if (e) {
1384                 spin_lock(&con->writequeue_lock);
1385                 offset = e->end;
1386                 e->end += len;
1387                 e->users++;
1388                 list_add_tail(&e->list, &con->writequeue);
1389                 spin_unlock(&con->writequeue_lock);
1390                 goto got_one;
1391         }
1392         return NULL;
1393 }
1394
1395 void dlm_lowcomms_commit_buffer(void *mh)
1396 {
1397         struct writequeue_entry *e = (struct writequeue_entry *)mh;
1398         struct connection *con = e->con;
1399         int users;
1400
1401         spin_lock(&con->writequeue_lock);
1402         users = --e->users;
1403         if (users)
1404                 goto out;
1405         e->len = e->end - e->offset;
1406         spin_unlock(&con->writequeue_lock);
1407
1408         queue_work(send_workqueue, &con->swork);
1409         return;
1410
1411 out:
1412         spin_unlock(&con->writequeue_lock);
1413         return;
1414 }
1415
1416 /* Send a message */
1417 static void send_to_sock(struct connection *con)
1418 {
1419         int ret = 0;
1420         const int msg_flags = MSG_DONTWAIT | MSG_NOSIGNAL;
1421         struct writequeue_entry *e;
1422         int len, offset;
1423         int count = 0;
1424
1425         mutex_lock(&con->sock_mutex);
1426         if (con->sock == NULL)
1427                 goto out_connect;
1428
1429         spin_lock(&con->writequeue_lock);
1430         for (;;) {
1431                 e = list_entry(con->writequeue.next, struct writequeue_entry,
1432                                list);
1433                 if ((struct list_head *) e == &con->writequeue)
1434                         break;
1435
1436                 len = e->len;
1437                 offset = e->offset;
1438                 BUG_ON(len == 0 && e->users == 0);
1439                 spin_unlock(&con->writequeue_lock);
1440
1441                 ret = 0;
1442                 if (len) {
1443                         ret = kernel_sendpage(con->sock, e->page, offset, len,
1444                                               msg_flags);
1445                         if (ret == -EAGAIN || ret == 0) {
1446                                 if (ret == -EAGAIN &&
1447                                     test_bit(SOCKWQ_ASYNC_NOSPACE, &con->sock->flags) &&
1448                                     !test_and_set_bit(CF_APP_LIMITED, &con->flags)) {
1449                                         /* Notify TCP that we're limited by the
1450                                          * application window size.
1451                                          */
1452                                         set_bit(SOCK_NOSPACE, &con->sock->flags);
1453                                         con->sock->sk->sk_write_pending++;
1454                                 }
1455                                 cond_resched();
1456                                 goto out;
1457                         } else if (ret < 0)
1458                                 goto send_error;
1459                 }
1460
1461                 /* Don't starve people filling buffers */
1462                 if (++count >= MAX_SEND_MSG_COUNT) {
1463                         cond_resched();
1464                         count = 0;
1465                 }
1466
1467                 spin_lock(&con->writequeue_lock);
1468                 writequeue_entry_complete(e, ret);
1469         }
1470         spin_unlock(&con->writequeue_lock);
1471 out:
1472         mutex_unlock(&con->sock_mutex);
1473         return;
1474
1475 send_error:
1476         mutex_unlock(&con->sock_mutex);
1477         close_connection(con, false, false, true);
1478         /* Requeue the send work. When the work daemon runs again, it will try
1479            a new connection, then call this function again. */
1480         queue_work(send_workqueue, &con->swork);
1481         return;
1482
1483 out_connect:
1484         mutex_unlock(&con->sock_mutex);
1485         queue_work(send_workqueue, &con->swork);
1486         cond_resched();
1487 }
1488
1489 static void clean_one_writequeue(struct connection *con)
1490 {
1491         struct writequeue_entry *e, *safe;
1492
1493         spin_lock(&con->writequeue_lock);
1494         list_for_each_entry_safe(e, safe, &con->writequeue, list) {
1495                 list_del(&e->list);
1496                 free_entry(e);
1497         }
1498         spin_unlock(&con->writequeue_lock);
1499 }
1500
1501 /* Called from recovery when it knows that a node has
1502    left the cluster */
1503 int dlm_lowcomms_close(int nodeid)
1504 {
1505         struct connection *con;
1506         struct dlm_node_addr *na;
1507
1508         log_print("closing connection to node %d", nodeid);
1509         con = nodeid2con(nodeid, 0);
1510         if (con) {
1511                 set_bit(CF_CLOSE, &con->flags);
1512                 close_connection(con, true, true, true);
1513                 clean_one_writequeue(con);
1514         }
1515
1516         spin_lock(&dlm_node_addrs_spin);
1517         na = find_node_addr(nodeid);
1518         if (na) {
1519                 list_del(&na->list);
1520                 while (na->addr_count--)
1521                         kfree(na->addr[na->addr_count]);
1522                 kfree(na);
1523         }
1524         spin_unlock(&dlm_node_addrs_spin);
1525
1526         return 0;
1527 }
1528
1529 /* Receive workqueue function */
1530 static void process_recv_sockets(struct work_struct *work)
1531 {
1532         struct connection *con = container_of(work, struct connection, rwork);
1533         int err;
1534
1535         clear_bit(CF_READ_PENDING, &con->flags);
1536         do {
1537                 err = con->rx_action(con);
1538         } while (!err);
1539 }
1540
1541 /* Send workqueue function */
1542 static void process_send_sockets(struct work_struct *work)
1543 {
1544         struct connection *con = container_of(work, struct connection, swork);
1545
1546         clear_bit(CF_WRITE_PENDING, &con->flags);
1547         if (con->sock == NULL) /* not mutex protected so check it inside too */
1548                 con->connect_action(con);
1549         if (!list_empty(&con->writequeue))
1550                 send_to_sock(con);
1551 }
1552
1553 static void work_stop(void)
1554 {
1555         if (recv_workqueue)
1556                 destroy_workqueue(recv_workqueue);
1557         if (send_workqueue)
1558                 destroy_workqueue(send_workqueue);
1559 }
1560
1561 static int work_start(void)
1562 {
1563         recv_workqueue = alloc_workqueue("dlm_recv",
1564                                          WQ_UNBOUND | WQ_MEM_RECLAIM, 1);
1565         if (!recv_workqueue) {
1566                 log_print("can't start dlm_recv");
1567                 return -ENOMEM;
1568         }
1569
1570         send_workqueue = alloc_workqueue("dlm_send",
1571                                          WQ_UNBOUND | WQ_MEM_RECLAIM, 1);
1572         if (!send_workqueue) {
1573                 log_print("can't start dlm_send");
1574                 destroy_workqueue(recv_workqueue);
1575                 return -ENOMEM;
1576         }
1577
1578         return 0;
1579 }
1580
1581 static void _stop_conn(struct connection *con, bool and_other)
1582 {
1583         mutex_lock(&con->sock_mutex);
1584         set_bit(CF_CLOSE, &con->flags);
1585         set_bit(CF_READ_PENDING, &con->flags);
1586         set_bit(CF_WRITE_PENDING, &con->flags);
1587         if (con->sock && con->sock->sk) {
1588                 write_lock_bh(&con->sock->sk->sk_callback_lock);
1589                 con->sock->sk->sk_user_data = NULL;
1590                 write_unlock_bh(&con->sock->sk->sk_callback_lock);
1591         }
1592         if (con->othercon && and_other)
1593                 _stop_conn(con->othercon, false);
1594         mutex_unlock(&con->sock_mutex);
1595 }
1596
1597 static void stop_conn(struct connection *con)
1598 {
1599         _stop_conn(con, true);
1600 }
1601
1602 static void shutdown_conn(struct connection *con)
1603 {
1604         if (con->shutdown_action)
1605                 con->shutdown_action(con);
1606 }
1607
1608 static void free_conn(struct connection *con)
1609 {
1610         close_connection(con, true, true, true);
1611         if (con->othercon)
1612                 kfree_rcu(con->othercon, rcu);
1613         spin_lock(&connections_lock);
1614         hlist_del_rcu(&con->list);
1615         spin_unlock(&connections_lock);
1616         clean_one_writequeue(con);
1617         kfree_rcu(con, rcu);
1618 }
1619
1620 static void work_flush(void)
1621 {
1622         int ok, idx;
1623         int i;
1624         struct connection *con;
1625
1626         do {
1627                 ok = 1;
1628                 foreach_conn(stop_conn);
1629                 if (recv_workqueue)
1630                         flush_workqueue(recv_workqueue);
1631                 if (send_workqueue)
1632                         flush_workqueue(send_workqueue);
1633                 idx = srcu_read_lock(&connections_srcu);
1634                 for (i = 0; i < CONN_HASH_SIZE && ok; i++) {
1635                         hlist_for_each_entry_rcu(con, &connection_hash[i],
1636                                                  list) {
1637                                 ok &= test_bit(CF_READ_PENDING, &con->flags);
1638                                 ok &= test_bit(CF_WRITE_PENDING, &con->flags);
1639                                 if (con->othercon) {
1640                                         ok &= test_bit(CF_READ_PENDING,
1641                                                        &con->othercon->flags);
1642                                         ok &= test_bit(CF_WRITE_PENDING,
1643                                                        &con->othercon->flags);
1644                                 }
1645                         }
1646                 }
1647                 srcu_read_unlock(&connections_srcu, idx);
1648         } while (!ok);
1649 }
1650
1651 void dlm_lowcomms_stop(void)
1652 {
1653         /* Set all the flags to prevent any
1654            socket activity.
1655         */
1656         dlm_allow_conn = 0;
1657
1658         if (recv_workqueue)
1659                 flush_workqueue(recv_workqueue);
1660         if (send_workqueue)
1661                 flush_workqueue(send_workqueue);
1662
1663         foreach_conn(shutdown_conn);
1664         work_flush();
1665         foreach_conn(free_conn);
1666         work_stop();
1667         deinit_local();
1668 }
1669
1670 int dlm_lowcomms_start(void)
1671 {
1672         int error = -EINVAL;
1673         struct connection *con;
1674         int i;
1675
1676         for (i = 0; i < CONN_HASH_SIZE; i++)
1677                 INIT_HLIST_HEAD(&connection_hash[i]);
1678
1679         init_local();
1680         if (!dlm_local_count) {
1681                 error = -ENOTCONN;
1682                 log_print("no local IP address has been set");
1683                 goto fail;
1684         }
1685
1686         error = work_start();
1687         if (error)
1688                 goto fail;
1689
1690         dlm_allow_conn = 1;
1691
1692         /* Start listening */
1693         if (dlm_config.ci_protocol == 0)
1694                 error = tcp_listen_for_all();
1695         else
1696                 error = sctp_listen_for_all();
1697         if (error)
1698                 goto fail_unlisten;
1699
1700         return 0;
1701
1702 fail_unlisten:
1703         dlm_allow_conn = 0;
1704         con = nodeid2con(0,0);
1705         if (con) {
1706                 close_connection(con, false, true, true);
1707                 kfree_rcu(con, rcu);
1708         }
1709 fail:
1710         return error;
1711 }
1712
1713 void dlm_lowcomms_exit(void)
1714 {
1715         struct dlm_node_addr *na, *safe;
1716
1717         spin_lock(&dlm_node_addrs_spin);
1718         list_for_each_entry_safe(na, safe, &dlm_node_addrs, list) {
1719                 list_del(&na->list);
1720                 while (na->addr_count--)
1721                         kfree(na->addr[na->addr_count]);
1722                 kfree(na);
1723         }
1724         spin_unlock(&dlm_node_addrs_spin);
1725 }