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