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