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