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