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