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