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