xref: /linux/net/netfilter/ipvs/ip_vs_sync.c (revision f96e91748f6304668fe647e686d199d7207d36f1)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * IPVS         An implementation of the IP virtual server support for the
4  *              LINUX operating system.  IPVS is now implemented as a module
5  *              over the NetFilter framework. IPVS can be used to build a
6  *              high-performance and highly available server based on a
7  *              cluster of servers.
8  *
9  * Version 1,   is capable of handling both version 0 and 1 messages.
10  *              Version 0 is the plain old format.
11  *              Note Version 0 receivers will just drop Ver 1 messages.
12  *              Version 1 is capable of handle IPv6, Persistence data,
13  *              time-outs, and firewall marks.
14  *              In ver.1 "ip_vs_sync_conn_options" will be sent in netw. order.
15  *              Ver. 0 can be turned on by sysctl -w net.ipv4.vs.sync_version=0
16  *
17  * Definitions  Message: is a complete datagram
18  *              Sync_conn: is a part of a Message
19  *              Param Data is an option to a Sync_conn.
20  *
21  * Authors:     Wensong Zhang <wensong@linuxvirtualserver.org>
22  *
23  * ip_vs_sync:  sync connection info from master load balancer to backups
24  *              through multicast
25  *
26  * Changes:
27  *	Alexandre Cassen	:	Added master & backup support at a time.
28  *	Alexandre Cassen	:	Added SyncID support for incoming sync
29  *					messages filtering.
30  *	Justin Ossevoort	:	Fix endian problem on sync message size.
31  *	Hans Schillstrom	:	Added Version 1: i.e. IPv6,
32  *					Persistence support, fwmark and time-out.
33  */
34 
35 #define pr_fmt(fmt) "IPVS: " fmt
36 
37 #include <linux/module.h>
38 #include <linux/slab.h>
39 #include <linux/inetdevice.h>
40 #include <linux/net.h>
41 #include <linux/completion.h>
42 #include <linux/delay.h>
43 #include <linux/skbuff.h>
44 #include <linux/in.h>
45 #include <linux/igmp.h>                 /* for ip_mc_join_group */
46 #include <linux/udp.h>
47 #include <linux/err.h>
48 #include <linux/kthread.h>
49 #include <linux/wait.h>
50 #include <linux/kernel.h>
51 #include <linux/sched/signal.h>
52 
53 #include <linux/unaligned.h>		/* Used for ntoh_seq and hton_seq */
54 
55 #include <net/ip.h>
56 #include <net/sock.h>
57 
58 #include <net/ip_vs.h>
59 
60 #define IP_VS_SYNC_GROUP 0xe0000051    /* multicast addr - 224.0.0.81 */
61 #define IP_VS_SYNC_PORT  8848          /* multicast port */
62 
63 #define SYNC_PROTO_VER  1		/* Protocol version in header */
64 
65 static struct lock_class_key __ipvs_sync_key;
66 /*
67  *	IPVS sync connection entry
68  *	Version 0, i.e. original version.
69  */
70 struct ip_vs_sync_conn_v0 {
71 	__u8			reserved;
72 
73 	/* Protocol, addresses and port numbers */
74 	__u8			protocol;       /* Which protocol (TCP/UDP) */
75 	__be16			cport;
76 	__be16                  vport;
77 	__be16                  dport;
78 	__be32                  caddr;          /* client address */
79 	__be32                  vaddr;          /* virtual address */
80 	__be32                  daddr;          /* destination address */
81 
82 	/* Flags and state transition */
83 	__be16                  flags;          /* status flags */
84 	__be16                  state;          /* state info */
85 
86 	/* The sequence options start here */
87 };
88 
89 struct ip_vs_sync_conn_options {
90 	struct ip_vs_seq        in_seq;         /* incoming seq. struct */
91 	struct ip_vs_seq        out_seq;        /* outgoing seq. struct */
92 };
93 
94 /*
95      Sync Connection format (sync_conn)
96 
97        0                   1                   2                   3
98        0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
99       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
100       |    Type       |    Protocol   | Ver.  |        Size           |
101       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
102       |                             Flags                             |
103       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
104       |            State              |         cport                 |
105       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
106       |            vport              |         dport                 |
107       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
108       |                             fwmark                            |
109       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
110       |                             timeout  (in sec.)                |
111       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
112       |                              ...                              |
113       |                        IP-Addresses  (v4 or v6)               |
114       |                              ...                              |
115       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
116   Optional Parameters.
117       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
118       | Param. Type    | Param. Length |   Param. data                |
119       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+                               |
120       |                              ...                              |
121       |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
122       |                               | Param Type    | Param. Length |
123       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
124       |                           Param  data                         |
125       |         Last Param data should be padded for 32 bit alignment |
126       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
127 */
128 
129 /*
130  *  Type 0, IPv4 sync connection format
131  */
132 struct ip_vs_sync_v4 {
133 	__u8			type;
134 	__u8			protocol;	/* Which protocol (TCP/UDP) */
135 	__be16			ver_size;	/* Version msb 4 bits */
136 	/* Flags and state transition */
137 	__be32			flags;		/* status flags */
138 	__be16			state;		/* state info 	*/
139 	/* Protocol, addresses and port numbers */
140 	__be16			cport;
141 	__be16			vport;
142 	__be16			dport;
143 	__be32			fwmark;		/* Firewall mark from skb */
144 	__be32			timeout;	/* cp timeout */
145 	__be32			caddr;		/* client address */
146 	__be32			vaddr;		/* virtual address */
147 	__be32			daddr;		/* destination address */
148 	/* The sequence options start here */
149 	/* PE data padded to 32bit alignment after seq. options */
150 };
151 /*
152  * Type 2 messages IPv6
153  */
154 struct ip_vs_sync_v6 {
155 	__u8			type;
156 	__u8			protocol;	/* Which protocol (TCP/UDP) */
157 	__be16			ver_size;	/* Version msb 4 bits */
158 	/* Flags and state transition */
159 	__be32			flags;		/* status flags */
160 	__be16			state;		/* state info 	*/
161 	/* Protocol, addresses and port numbers */
162 	__be16			cport;
163 	__be16			vport;
164 	__be16			dport;
165 	__be32			fwmark;		/* Firewall mark from skb */
166 	__be32			timeout;	/* cp timeout */
167 	struct in6_addr		caddr;		/* client address */
168 	struct in6_addr		vaddr;		/* virtual address */
169 	struct in6_addr		daddr;		/* destination address */
170 	/* The sequence options start here */
171 	/* PE data padded to 32bit alignment after seq. options */
172 };
173 
174 union ip_vs_sync_conn {
175 	struct ip_vs_sync_v4	v4;
176 	struct ip_vs_sync_v6	v6;
177 };
178 
179 /* Bits in Type field in above */
180 #define STYPE_INET6		0
181 #define STYPE_F_INET6		(1 << STYPE_INET6)
182 
183 #define SVER_SHIFT		12		/* Shift to get version */
184 #define SVER_MASK		0x0fff		/* Mask to strip version */
185 
186 #define IPVS_OPT_SEQ_DATA	1
187 #define IPVS_OPT_PE_DATA	2
188 #define IPVS_OPT_PE_NAME	3
189 #define IPVS_OPT_PARAM		7
190 
191 #define IPVS_OPT_F_SEQ_DATA	(1 << (IPVS_OPT_SEQ_DATA-1))
192 #define IPVS_OPT_F_PE_DATA	(1 << (IPVS_OPT_PE_DATA-1))
193 #define IPVS_OPT_F_PE_NAME	(1 << (IPVS_OPT_PE_NAME-1))
194 #define IPVS_OPT_F_PARAM	(1 << (IPVS_OPT_PARAM-1))
195 
196 struct ip_vs_sync_thread_data {
197 	struct task_struct *task;
198 	struct netns_ipvs *ipvs;
199 	struct socket *sock;
200 	char *buf;
201 	int id;
202 };
203 
204 /* Version 0 definition of packet sizes */
205 #define SIMPLE_CONN_SIZE  (sizeof(struct ip_vs_sync_conn_v0))
206 #define FULL_CONN_SIZE  \
207 (sizeof(struct ip_vs_sync_conn_v0) + sizeof(struct ip_vs_sync_conn_options))
208 
209 
210 /*
211   The master mulitcasts messages (Datagrams) to the backup load balancers
212   in the following format.
213 
214  Version 1:
215   Note, first byte should be Zero, so ver 0 receivers will drop the packet.
216 
217        0                   1                   2                   3
218        0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
219       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
220       |      0        |    SyncID     |            Size               |
221       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
222       |  Count Conns  |    Version    |    Reserved, set to Zero      |
223       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
224       |                                                               |
225       |                    IPVS Sync Connection (1)                   |
226       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
227       |                            .                                  |
228       ~                            .                                  ~
229       |                            .                                  |
230       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
231       |                                                               |
232       |                    IPVS Sync Connection (n)                   |
233       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
234 
235  Version 0 Header
236        0                   1                   2                   3
237        0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
238       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
239       |  Count Conns  |    SyncID     |            Size               |
240       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
241       |                    IPVS Sync Connection (1)                   |
242 */
243 
244 /* Version 0 header */
245 struct ip_vs_sync_mesg_v0 {
246 	__u8                    nr_conns;
247 	__u8                    syncid;
248 	__be16                  size;
249 
250 	/* ip_vs_sync_conn entries start here */
251 };
252 
253 /* Version 1 header */
254 struct ip_vs_sync_mesg {
255 	__u8			reserved;	/* must be zero */
256 	__u8			syncid;
257 	__be16			size;
258 	__u8			nr_conns;
259 	__s8			version;	/* SYNC_PROTO_VER  */
260 	__u16			spare;
261 	/* ip_vs_sync_conn entries start here */
262 };
263 
264 union ipvs_sockaddr {
265 	struct sockaddr_in	in;
266 	struct sockaddr_in6	in6;
267 };
268 
269 struct ip_vs_sync_buff {
270 	struct list_head        list;
271 	unsigned long           firstuse;
272 
273 	/* pointers for the message data */
274 	struct ip_vs_sync_mesg  *mesg;
275 	unsigned char           *head;
276 	unsigned char           *end;
277 };
278 
279 /*
280  * Copy of struct ip_vs_seq
281  * From unaligned network order to aligned host order
282  */
283 static void ntoh_seq(struct ip_vs_seq *no, struct ip_vs_seq *ho)
284 {
285 	memset(ho, 0, sizeof(*ho));
286 	ho->init_seq       = get_unaligned_be32(&no->init_seq);
287 	ho->delta          = get_unaligned_be32(&no->delta);
288 	ho->previous_delta = get_unaligned_be32(&no->previous_delta);
289 }
290 
291 /*
292  * Copy of struct ip_vs_seq
293  * From Aligned host order to unaligned network order
294  */
295 static void hton_seq(struct ip_vs_seq *ho, struct ip_vs_seq *no)
296 {
297 	put_unaligned_be32(ho->init_seq, &no->init_seq);
298 	put_unaligned_be32(ho->delta, &no->delta);
299 	put_unaligned_be32(ho->previous_delta, &no->previous_delta);
300 }
301 
302 static inline struct ip_vs_sync_buff *
303 sb_dequeue(struct netns_ipvs *ipvs, struct ipvs_master_sync_state *ms)
304 {
305 	struct ip_vs_sync_buff *sb;
306 
307 	spin_lock_bh(&ipvs->sync_lock);
308 	if (list_empty(&ms->sync_queue)) {
309 		sb = NULL;
310 		__set_current_state(TASK_INTERRUPTIBLE);
311 	} else {
312 		sb = list_entry(ms->sync_queue.next, struct ip_vs_sync_buff,
313 				list);
314 		list_del(&sb->list);
315 		ms->sync_queue_len--;
316 		if (!ms->sync_queue_len)
317 			ms->sync_queue_delay = 0;
318 	}
319 	spin_unlock_bh(&ipvs->sync_lock);
320 
321 	return sb;
322 }
323 
324 /*
325  * Create a new sync buffer for Version 1 proto.
326  */
327 static inline struct ip_vs_sync_buff *
328 ip_vs_sync_buff_create(struct netns_ipvs *ipvs, unsigned int len)
329 {
330 	struct ip_vs_sync_buff *sb;
331 
332 	if (!(sb=kmalloc_obj(struct ip_vs_sync_buff, GFP_ATOMIC)))
333 		return NULL;
334 
335 	len = max_t(unsigned int, len + sizeof(struct ip_vs_sync_mesg),
336 		    ipvs->mcfg.sync_maxlen);
337 	sb->mesg = kmalloc(len, GFP_ATOMIC);
338 	if (!sb->mesg) {
339 		kfree(sb);
340 		return NULL;
341 	}
342 	sb->mesg->reserved = 0;  /* old nr_conns i.e. must be zero now */
343 	sb->mesg->version = SYNC_PROTO_VER;
344 	sb->mesg->syncid = ipvs->mcfg.syncid;
345 	sb->mesg->size = htons(sizeof(struct ip_vs_sync_mesg));
346 	sb->mesg->nr_conns = 0;
347 	sb->mesg->spare = 0;
348 	sb->head = (unsigned char *)sb->mesg + sizeof(struct ip_vs_sync_mesg);
349 	sb->end = (unsigned char *)sb->mesg + len;
350 
351 	sb->firstuse = jiffies;
352 	return sb;
353 }
354 
355 static inline void ip_vs_sync_buff_release(struct ip_vs_sync_buff *sb)
356 {
357 	kfree(sb->mesg);
358 	kfree(sb);
359 }
360 
361 static inline void sb_queue_tail(struct netns_ipvs *ipvs,
362 				 struct ipvs_master_sync_state *ms)
363 {
364 	struct ip_vs_sync_buff *sb = ms->sync_buff;
365 
366 	spin_lock(&ipvs->sync_lock);
367 	if (ipvs->sync_state & IP_VS_STATE_MASTER &&
368 	    ms->sync_queue_len < sysctl_sync_qlen_max(ipvs)) {
369 		if (!ms->sync_queue_len)
370 			schedule_delayed_work(&ms->master_wakeup_work,
371 					      max(IPVS_SYNC_SEND_DELAY, 1));
372 		ms->sync_queue_len++;
373 		list_add_tail(&sb->list, &ms->sync_queue);
374 		if ((++ms->sync_queue_delay) == IPVS_SYNC_WAKEUP_RATE) {
375 			int id = (int)(ms - ipvs->ms);
376 
377 			wake_up_process(ipvs->master_tinfo[id].task);
378 		}
379 	} else
380 		ip_vs_sync_buff_release(sb);
381 	spin_unlock(&ipvs->sync_lock);
382 }
383 
384 /*
385  *	Get the current sync buffer if it has been created for more
386  *	than the specified time or the specified time is zero.
387  */
388 static inline struct ip_vs_sync_buff *
389 get_curr_sync_buff(struct netns_ipvs *ipvs, struct ipvs_master_sync_state *ms,
390 		   unsigned long time)
391 {
392 	struct ip_vs_sync_buff *sb;
393 
394 	spin_lock_bh(&ipvs->sync_buff_lock);
395 	sb = ms->sync_buff;
396 	if (sb && time_after_eq(jiffies - sb->firstuse, time)) {
397 		ms->sync_buff = NULL;
398 		__set_current_state(TASK_RUNNING);
399 	} else
400 		sb = NULL;
401 	spin_unlock_bh(&ipvs->sync_buff_lock);
402 	return sb;
403 }
404 
405 static inline int
406 select_master_thread_id(struct netns_ipvs *ipvs, struct ip_vs_conn *cp)
407 {
408 	return ((long) cp >> (1 + ilog2(sizeof(*cp)))) & ipvs->threads_mask;
409 }
410 
411 /*
412  * Create a new sync buffer for Version 0 proto.
413  */
414 static inline struct ip_vs_sync_buff *
415 ip_vs_sync_buff_create_v0(struct netns_ipvs *ipvs, unsigned int len)
416 {
417 	struct ip_vs_sync_buff *sb;
418 	struct ip_vs_sync_mesg_v0 *mesg;
419 
420 	if (!(sb=kmalloc_obj(struct ip_vs_sync_buff, GFP_ATOMIC)))
421 		return NULL;
422 
423 	len = max_t(unsigned int, len + sizeof(struct ip_vs_sync_mesg_v0),
424 		    ipvs->mcfg.sync_maxlen);
425 	sb->mesg = kmalloc(len, GFP_ATOMIC);
426 	if (!sb->mesg) {
427 		kfree(sb);
428 		return NULL;
429 	}
430 	mesg = (struct ip_vs_sync_mesg_v0 *)sb->mesg;
431 	mesg->nr_conns = 0;
432 	mesg->syncid = ipvs->mcfg.syncid;
433 	mesg->size = htons(sizeof(struct ip_vs_sync_mesg_v0));
434 	sb->head = (unsigned char *)mesg + sizeof(struct ip_vs_sync_mesg_v0);
435 	sb->end = (unsigned char *)mesg + len;
436 	sb->firstuse = jiffies;
437 	return sb;
438 }
439 
440 /* Check if connection is controlled by persistence */
441 static inline bool in_persistence(struct ip_vs_conn *cp)
442 {
443 	for (cp = cp->control; cp; cp = cp->control) {
444 		if (cp->flags & IP_VS_CONN_F_TEMPLATE)
445 			return true;
446 	}
447 	return false;
448 }
449 
450 /* Check if conn should be synced.
451  * pkts: conn packets, use sysctl_sync_threshold to avoid packet check
452  * - (1) sync_refresh_period: reduce sync rate. Additionally, retry
453  *	sync_retries times with period of sync_refresh_period/8
454  * - (2) if both sync_refresh_period and sync_period are 0 send sync only
455  *	for state changes or only once when pkts matches sync_threshold
456  * - (3) templates: rate can be reduced only with sync_refresh_period or
457  *	with (2)
458  */
459 static int ip_vs_sync_conn_needed(struct netns_ipvs *ipvs,
460 				  struct ip_vs_conn *cp, int pkts)
461 {
462 	unsigned long orig = READ_ONCE(cp->sync_endtime);
463 	unsigned long now = jiffies;
464 	unsigned long n = (now + cp->timeout) & ~3UL;
465 	unsigned int sync_refresh_period;
466 	int sync_period;
467 	int force;
468 
469 	/* Check if we sync in current state */
470 	if (unlikely(cp->flags & IP_VS_CONN_F_TEMPLATE))
471 		force = 0;
472 	else if (unlikely(sysctl_sync_persist_mode(ipvs) && in_persistence(cp)))
473 		return 0;
474 	else if (likely(cp->protocol == IPPROTO_TCP)) {
475 		if (!((1 << cp->state) &
476 		      ((1 << IP_VS_TCP_S_ESTABLISHED) |
477 		       (1 << IP_VS_TCP_S_FIN_WAIT) |
478 		       (1 << IP_VS_TCP_S_CLOSE) |
479 		       (1 << IP_VS_TCP_S_CLOSE_WAIT) |
480 		       (1 << IP_VS_TCP_S_TIME_WAIT))))
481 			return 0;
482 		force = cp->state != cp->old_state;
483 		if (force && cp->state != IP_VS_TCP_S_ESTABLISHED)
484 			goto set;
485 	} else if (unlikely(cp->protocol == IPPROTO_SCTP)) {
486 		if (!((1 << cp->state) &
487 		      ((1 << IP_VS_SCTP_S_ESTABLISHED) |
488 		       (1 << IP_VS_SCTP_S_SHUTDOWN_SENT) |
489 		       (1 << IP_VS_SCTP_S_SHUTDOWN_RECEIVED) |
490 		       (1 << IP_VS_SCTP_S_SHUTDOWN_ACK_SENT) |
491 		       (1 << IP_VS_SCTP_S_CLOSED))))
492 			return 0;
493 		force = cp->state != cp->old_state;
494 		if (force && cp->state != IP_VS_SCTP_S_ESTABLISHED)
495 			goto set;
496 	} else {
497 		/* UDP or another protocol with single state */
498 		force = 0;
499 	}
500 
501 	sync_refresh_period = sysctl_sync_refresh_period(ipvs);
502 	if (sync_refresh_period > 0) {
503 		long diff = n - orig;
504 		long min_diff = max(cp->timeout >> 1, 10UL * HZ);
505 
506 		/* Avoid sync if difference is below sync_refresh_period
507 		 * and below the half timeout.
508 		 */
509 		if (abs(diff) < min_t(long, sync_refresh_period, min_diff)) {
510 			int retries = orig & 3;
511 
512 			if (retries >= sysctl_sync_retries(ipvs))
513 				return 0;
514 			if (time_before(now, orig - cp->timeout +
515 					(sync_refresh_period >> 3)))
516 				return 0;
517 			n |= retries + 1;
518 		}
519 	}
520 	sync_period = sysctl_sync_period(ipvs);
521 	if (sync_period > 0) {
522 		if (!(cp->flags & IP_VS_CONN_F_TEMPLATE) &&
523 		    pkts % sync_period != sysctl_sync_threshold(ipvs))
524 			return 0;
525 	} else if (!sync_refresh_period &&
526 		   pkts != sysctl_sync_threshold(ipvs))
527 		return 0;
528 
529 set:
530 	cp->old_state = cp->state;
531 	n = cmpxchg(&cp->sync_endtime, orig, n);
532 	return n == orig || force;
533 }
534 
535 /*
536  *      Version 0 , could be switched in by sys_ctl.
537  *      Add an ip_vs_conn information into the current sync_buff.
538  */
539 static void ip_vs_sync_conn_v0(struct netns_ipvs *ipvs, struct ip_vs_conn *cp,
540 			       int pkts)
541 {
542 	struct ip_vs_sync_mesg_v0 *m;
543 	struct ip_vs_sync_conn_v0 *s;
544 	struct ip_vs_sync_buff *buff;
545 	struct ipvs_master_sync_state *ms;
546 	int id;
547 	unsigned int len;
548 
549 	if (unlikely(cp->af != AF_INET))
550 		return;
551 	/* Do not sync ONE PACKET */
552 	if (cp->flags & IP_VS_CONN_F_ONE_PACKET)
553 		return;
554 
555 	if (!ip_vs_sync_conn_needed(ipvs, cp, pkts))
556 		return;
557 
558 	spin_lock_bh(&ipvs->sync_buff_lock);
559 	if (!(ipvs->sync_state & IP_VS_STATE_MASTER)) {
560 		spin_unlock_bh(&ipvs->sync_buff_lock);
561 		return;
562 	}
563 
564 	id = select_master_thread_id(ipvs, cp);
565 	ms = &ipvs->ms[id];
566 	buff = ms->sync_buff;
567 	len = (cp->flags & IP_VS_CONN_F_SEQ_MASK) ? FULL_CONN_SIZE :
568 		SIMPLE_CONN_SIZE;
569 	if (buff) {
570 		m = (struct ip_vs_sync_mesg_v0 *) buff->mesg;
571 		/* Send buffer if it is for v1 */
572 		if (buff->head + len > buff->end || !m->nr_conns) {
573 			sb_queue_tail(ipvs, ms);
574 			ms->sync_buff = NULL;
575 			buff = NULL;
576 		}
577 	}
578 	if (!buff) {
579 		buff = ip_vs_sync_buff_create_v0(ipvs, len);
580 		if (!buff) {
581 			spin_unlock_bh(&ipvs->sync_buff_lock);
582 			pr_err("ip_vs_sync_buff_create failed.\n");
583 			return;
584 		}
585 		ms->sync_buff = buff;
586 	}
587 
588 	m = (struct ip_vs_sync_mesg_v0 *) buff->mesg;
589 	s = (struct ip_vs_sync_conn_v0 *) buff->head;
590 
591 	/* copy members */
592 	s->reserved = 0;
593 	s->protocol = cp->protocol;
594 	s->cport = cp->cport;
595 	s->vport = cp->vport;
596 	s->dport = cp->dport;
597 	s->caddr = cp->caddr.ip;
598 	s->vaddr = cp->vaddr.ip;
599 	s->daddr = cp->daddr.ip;
600 	s->flags = htons(cp->flags & ~IP_VS_CONN_F_HASHED);
601 	s->state = htons(cp->state);
602 	if (cp->flags & IP_VS_CONN_F_SEQ_MASK) {
603 		struct ip_vs_sync_conn_options *opt =
604 			(struct ip_vs_sync_conn_options *)&s[1];
605 		memcpy(opt, &cp->sync_conn_opt, sizeof(*opt));
606 	}
607 
608 	m->nr_conns++;
609 	m->size = htons(ntohs(m->size) + len);
610 	buff->head += len;
611 	spin_unlock_bh(&ipvs->sync_buff_lock);
612 
613 	/* synchronize its controller if it has */
614 	cp = cp->control;
615 	if (cp) {
616 		if (cp->flags & IP_VS_CONN_F_TEMPLATE)
617 			pkts = atomic_inc_return(&cp->in_pkts);
618 		else
619 			pkts = sysctl_sync_threshold(ipvs);
620 		ip_vs_sync_conn(ipvs, cp, pkts);
621 	}
622 }
623 
624 /*
625  *      Add an ip_vs_conn information into the current sync_buff.
626  *      Called by ip_vs_in.
627  *      Sending Version 1 messages
628  */
629 void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts)
630 {
631 	struct ip_vs_sync_mesg *m;
632 	union ip_vs_sync_conn *s;
633 	struct ip_vs_sync_buff *buff;
634 	struct ipvs_master_sync_state *ms;
635 	int id;
636 	__u8 *p;
637 	unsigned int len, pe_name_len, pad;
638 
639 	/* Handle old version of the protocol */
640 	if (sysctl_sync_ver(ipvs) == 0) {
641 		ip_vs_sync_conn_v0(ipvs, cp, pkts);
642 		return;
643 	}
644 	/* Do not sync ONE PACKET */
645 	if (cp->flags & IP_VS_CONN_F_ONE_PACKET)
646 		goto control;
647 sloop:
648 	if (!ip_vs_sync_conn_needed(ipvs, cp, pkts))
649 		goto control;
650 
651 	/* Sanity checks */
652 	pe_name_len = 0;
653 	if (cp->pe_data_len) {
654 		if (!cp->pe_data || !cp->dest) {
655 			IP_VS_ERR_RL("SYNC, connection pe_data invalid\n");
656 			return;
657 		}
658 		pe_name_len = strnlen(cp->pe->name, IP_VS_PENAME_MAXLEN);
659 	}
660 
661 	spin_lock_bh(&ipvs->sync_buff_lock);
662 	if (!(ipvs->sync_state & IP_VS_STATE_MASTER)) {
663 		spin_unlock_bh(&ipvs->sync_buff_lock);
664 		return;
665 	}
666 
667 	id = select_master_thread_id(ipvs, cp);
668 	ms = &ipvs->ms[id];
669 
670 #ifdef CONFIG_IP_VS_IPV6
671 	if (cp->af == AF_INET6)
672 		len = sizeof(struct ip_vs_sync_v6);
673 	else
674 #endif
675 		len = sizeof(struct ip_vs_sync_v4);
676 
677 	if (cp->flags & IP_VS_CONN_F_SEQ_MASK)
678 		len += sizeof(struct ip_vs_sync_conn_options) + 2;
679 
680 	if (cp->pe_data_len)
681 		len += cp->pe_data_len + 2;	/* + Param hdr field */
682 	if (pe_name_len)
683 		len += pe_name_len + 2;
684 
685 	/* check if there is a space for this one  */
686 	pad = 0;
687 	buff = ms->sync_buff;
688 	if (buff) {
689 		m = buff->mesg;
690 		pad = (4 - (size_t) buff->head) & 3;
691 		/* Send buffer if it is for v0 */
692 		if (buff->head + len + pad > buff->end || m->reserved) {
693 			sb_queue_tail(ipvs, ms);
694 			ms->sync_buff = NULL;
695 			buff = NULL;
696 			pad = 0;
697 		}
698 	}
699 
700 	if (!buff) {
701 		buff = ip_vs_sync_buff_create(ipvs, len);
702 		if (!buff) {
703 			spin_unlock_bh(&ipvs->sync_buff_lock);
704 			pr_err("ip_vs_sync_buff_create failed.\n");
705 			return;
706 		}
707 		ms->sync_buff = buff;
708 		m = buff->mesg;
709 	}
710 
711 	p = buff->head;
712 	buff->head += pad + len;
713 	m->size = htons(ntohs(m->size) + pad + len);
714 	/* Add ev. padding from prev. sync_conn */
715 	while (pad--)
716 		*(p++) = 0;
717 
718 	s = (union ip_vs_sync_conn *)p;
719 
720 	/* Set message type  & copy members */
721 	s->v4.type = (cp->af == AF_INET6 ? STYPE_F_INET6 : 0);
722 	s->v4.ver_size = htons(len & SVER_MASK);	/* Version 0 */
723 	s->v4.flags = htonl(cp->flags & ~IP_VS_CONN_F_HASHED);
724 	s->v4.state = htons(cp->state);
725 	s->v4.protocol = cp->protocol;
726 	s->v4.cport = cp->cport;
727 	s->v4.vport = cp->vport;
728 	s->v4.dport = cp->dport;
729 	s->v4.fwmark = htonl(cp->fwmark);
730 	s->v4.timeout = htonl(cp->timeout / HZ);
731 	m->nr_conns++;
732 
733 #ifdef CONFIG_IP_VS_IPV6
734 	if (cp->af == AF_INET6) {
735 		p += sizeof(struct ip_vs_sync_v6);
736 		s->v6.caddr = cp->caddr.in6;
737 		s->v6.vaddr = cp->vaddr.in6;
738 		s->v6.daddr = cp->daddr.in6;
739 	} else
740 #endif
741 	{
742 		p += sizeof(struct ip_vs_sync_v4);	/* options ptr */
743 		s->v4.caddr = cp->caddr.ip;
744 		s->v4.vaddr = cp->vaddr.ip;
745 		s->v4.daddr = cp->daddr.ip;
746 	}
747 	if (cp->flags & IP_VS_CONN_F_SEQ_MASK) {
748 		*(p++) = IPVS_OPT_SEQ_DATA;
749 		*(p++) = sizeof(struct ip_vs_sync_conn_options);
750 		hton_seq(&cp->in_seq, (struct ip_vs_seq *)p);
751 		p += sizeof(struct ip_vs_seq);
752 		hton_seq(&cp->out_seq, (struct ip_vs_seq *)p);
753 		p += sizeof(struct ip_vs_seq);
754 	}
755 	/* Handle pe data */
756 	if (cp->pe_data_len && cp->pe_data) {
757 		*(p++) = IPVS_OPT_PE_DATA;
758 		*(p++) = cp->pe_data_len;
759 		memcpy(p, cp->pe_data, cp->pe_data_len);
760 		p += cp->pe_data_len;
761 		if (pe_name_len) {
762 			/* Add PE_NAME */
763 			*(p++) = IPVS_OPT_PE_NAME;
764 			*(p++) = pe_name_len;
765 			memcpy(p, cp->pe->name, pe_name_len);
766 			p += pe_name_len;
767 		}
768 	}
769 
770 	spin_unlock_bh(&ipvs->sync_buff_lock);
771 
772 control:
773 	/* synchronize its controller if it has */
774 	cp = cp->control;
775 	if (!cp)
776 		return;
777 	if (cp->flags & IP_VS_CONN_F_TEMPLATE)
778 		pkts = atomic_inc_return(&cp->in_pkts);
779 	else
780 		pkts = sysctl_sync_threshold(ipvs);
781 	goto sloop;
782 }
783 
784 /*
785  *  fill_param used by version 1
786  */
787 static inline int
788 ip_vs_conn_fill_param_sync(struct netns_ipvs *ipvs, int af, union ip_vs_sync_conn *sc,
789 			   struct ip_vs_conn_param *p,
790 			   __u8 *pe_data, unsigned int pe_data_len,
791 			   __u8 *pe_name, unsigned int pe_name_len)
792 {
793 #ifdef CONFIG_IP_VS_IPV6
794 	if (af == AF_INET6)
795 		ip_vs_conn_fill_param(ipvs, af, sc->v6.protocol,
796 				      (const union nf_inet_addr *)&sc->v6.caddr,
797 				      sc->v6.cport,
798 				      (const union nf_inet_addr *)&sc->v6.vaddr,
799 				      sc->v6.vport, p);
800 	else
801 #endif
802 		ip_vs_conn_fill_param(ipvs, af, sc->v4.protocol,
803 				      (const union nf_inet_addr *)&sc->v4.caddr,
804 				      sc->v4.cport,
805 				      (const union nf_inet_addr *)&sc->v4.vaddr,
806 				      sc->v4.vport, p);
807 	/* Handle pe data */
808 	if (pe_data_len) {
809 		if (pe_name_len) {
810 			char buff[IP_VS_PENAME_MAXLEN+1];
811 
812 			memcpy(buff, pe_name, pe_name_len);
813 			buff[pe_name_len]=0;
814 			p->pe = __ip_vs_pe_getbyname(buff);
815 			if (!p->pe) {
816 				IP_VS_DBG(3, "BACKUP, no %s engine found/loaded\n",
817 					     buff);
818 				return 1;
819 			}
820 		} else {
821 			IP_VS_ERR_RL("BACKUP, Invalid PE parameters\n");
822 			return 1;
823 		}
824 
825 		p->pe_data = kmemdup(pe_data, pe_data_len, GFP_ATOMIC);
826 		if (!p->pe_data) {
827 			module_put(p->pe->module);
828 			return -ENOMEM;
829 		}
830 		p->pe_data_len = pe_data_len;
831 	}
832 	return 0;
833 }
834 
835 /*
836  *  Connection Add / Update.
837  *  Common for version 0 and 1 reception of backup sync_conns.
838  *  Param: ...
839  *         timeout is in sec.
840  */
841 static void ip_vs_proc_conn(struct netns_ipvs *ipvs, struct ip_vs_conn_param *param,
842 			    unsigned int flags, unsigned int state,
843 			    unsigned int protocol, unsigned int type,
844 			    const union nf_inet_addr *daddr, __be16 dport,
845 			    unsigned long timeout, __u32 fwmark,
846 			    struct ip_vs_sync_conn_options *opt)
847 {
848 	struct ip_vs_dest *dest;
849 	struct ip_vs_conn *cp;
850 
851 	if (!(flags & IP_VS_CONN_F_TEMPLATE)) {
852 		cp = ip_vs_conn_in_get(param);
853 		if (cp && ((cp->dport != dport) ||
854 			   !ip_vs_addr_equal(cp->daf, &cp->daddr, daddr))) {
855 			if (!(flags & IP_VS_CONN_F_INACTIVE)) {
856 				ip_vs_conn_expire_now(cp);
857 				__ip_vs_conn_put(cp);
858 				cp = NULL;
859 			} else {
860 				/* This is the expiration message for the
861 				 * connection that was already replaced, so we
862 				 * just ignore it.
863 				 */
864 				__ip_vs_conn_put(cp);
865 				kfree(param->pe_data);
866 				return;
867 			}
868 		}
869 	} else {
870 		cp = ip_vs_ct_in_get(param);
871 	}
872 
873 	if (cp) {
874 		/* Free pe_data */
875 		kfree(param->pe_data);
876 
877 		dest = cp->dest;
878 		spin_lock_bh(&cp->lock);
879 		if ((cp->flags ^ flags) & IP_VS_CONN_F_INACTIVE &&
880 		    !(flags & IP_VS_CONN_F_TEMPLATE) && dest) {
881 			if (flags & IP_VS_CONN_F_INACTIVE)
882 				atomic_dec(&dest->activeconns);
883 			else
884 				atomic_inc(&dest->activeconns);
885 		}
886 		flags &= IP_VS_CONN_F_BACKUP_UPD_MASK;
887 		flags |= cp->flags & ~IP_VS_CONN_F_BACKUP_UPD_MASK;
888 		cp->flags = flags;
889 		spin_unlock_bh(&cp->lock);
890 		if (!dest)
891 			ip_vs_try_bind_dest(cp);
892 	} else {
893 		/*
894 		 * Find the appropriate destination for the connection.
895 		 * If it is not found the connection will remain unbound
896 		 * but still handled.
897 		 */
898 		rcu_read_lock();
899 		/* This function is only invoked by the synchronization
900 		 * code. We do not currently support heterogeneous pools
901 		 * with synchronization, so we can make the assumption that
902 		 * the svc_af is the same as the dest_af
903 		 */
904 		dest = ip_vs_find_dest(ipvs, type, type, daddr, dport,
905 				       param->vaddr, param->vport, protocol,
906 				       fwmark, flags);
907 
908 		cp = ip_vs_conn_new(param, type, daddr, dport, flags, dest,
909 				    fwmark);
910 		rcu_read_unlock();
911 		if (!cp) {
912 			kfree(param->pe_data);
913 			IP_VS_DBG(2, "BACKUP, add new conn. failed\n");
914 			return;
915 		}
916 		if (!(flags & IP_VS_CONN_F_TEMPLATE))
917 			kfree(param->pe_data);
918 	}
919 
920 	if (opt) {
921 		cp->in_seq = opt->in_seq;
922 		cp->out_seq = opt->out_seq;
923 	}
924 	atomic_set(&cp->in_pkts, sysctl_sync_threshold(ipvs));
925 	cp->state = state;
926 	cp->old_state = cp->state;
927 	/*
928 	 * For Ver 0 messages style
929 	 *  - Not possible to recover the right timeout for templates
930 	 *  - can not find the right fwmark
931 	 *    virtual service. If needed, we can do it for
932 	 *    non-fwmark persistent services.
933 	 * Ver 1 messages style.
934 	 *  - No problem.
935 	 */
936 	if (timeout) {
937 		if (timeout > MAX_SCHEDULE_TIMEOUT / HZ)
938 			timeout = MAX_SCHEDULE_TIMEOUT / HZ;
939 		cp->timeout = timeout*HZ;
940 	} else {
941 		struct ip_vs_proto_data *pd;
942 
943 		pd = ip_vs_proto_data_get(ipvs, protocol);
944 		if (!(flags & IP_VS_CONN_F_TEMPLATE) && pd && pd->timeout_table)
945 			cp->timeout = pd->timeout_table[state];
946 		else
947 			cp->timeout = (3*60*HZ);
948 	}
949 	ip_vs_conn_put(cp);
950 }
951 
952 /* Check for incompatible flags */
953 static bool ip_vs_sync_validate_flags(u32 flags)
954 {
955 	/* We do not expect NO_CPORT, especially to allow lookups
956 	 * to hit templates
957 	 */
958 	if (flags & IP_VS_CONN_F_NO_CPORT) {
959 		if (flags & IP_VS_CONN_F_TEMPLATE)
960 			return false;
961 	}
962 	if (flags & IP_VS_CONN_F_ONE_PACKET)
963 		return false;
964 	return true;
965 }
966 
967 /*
968  *  Process received multicast message for Version 0
969  */
970 static void ip_vs_process_message_v0(struct netns_ipvs *ipvs, const char *buffer,
971 				     const size_t buflen)
972 {
973 	struct ip_vs_sync_mesg_v0 *m = (struct ip_vs_sync_mesg_v0 *)buffer;
974 	struct ip_vs_sync_conn_v0 *s;
975 	struct ip_vs_sync_conn_options *opt;
976 	struct ip_vs_protocol *pp;
977 	struct ip_vs_conn_param param;
978 	char *p;
979 	int i;
980 
981 	p = (char *)buffer + sizeof(struct ip_vs_sync_mesg_v0);
982 	for (i=0; i<m->nr_conns; i++) {
983 		unsigned int flags, state;
984 
985 		if (p + SIMPLE_CONN_SIZE > buffer+buflen) {
986 			IP_VS_ERR_RL("BACKUP v0, bogus conn\n");
987 			return;
988 		}
989 		s = (struct ip_vs_sync_conn_v0 *) p;
990 		flags = ntohs(s->flags);
991 		if (flags & IP_VS_CONN_F_SEQ_MASK) {
992 			opt = (struct ip_vs_sync_conn_options *)&s[1];
993 			p += FULL_CONN_SIZE;
994 			if (p > buffer+buflen) {
995 				IP_VS_ERR_RL("BACKUP v0, Dropping buffer bogus conn options\n");
996 				return;
997 			}
998 		} else {
999 			opt = NULL;
1000 			p += SIMPLE_CONN_SIZE;
1001 		}
1002 
1003 		if (!ip_vs_sync_validate_flags(flags)) {
1004 			IP_VS_DBG(2, "BACKUP v0, Invalid flags 0x%X\n", flags);
1005 			continue;
1006 		}
1007 		flags &= IP_VS_CONN_F_BACKUP_MASK;
1008 		flags |= IP_VS_CONN_F_SYNC;
1009 
1010 		state = ntohs(s->state);
1011 		if (!(flags & IP_VS_CONN_F_TEMPLATE)) {
1012 			pp = ip_vs_proto_get(s->protocol);
1013 			if (!pp) {
1014 				IP_VS_DBG(2, "BACKUP v0, Unsupported protocol %u\n",
1015 					s->protocol);
1016 				continue;
1017 			}
1018 			if (state >= pp->num_states) {
1019 				IP_VS_DBG(2, "BACKUP v0, Invalid %s state %u\n",
1020 					pp->name, state);
1021 				continue;
1022 			}
1023 		} else if (state >= IP_VS_CTPL_S_LAST) {
1024 			IP_VS_DBG(7, "BACKUP v0, Invalid tpl state %u\n",
1025 				  state);
1026 			continue;
1027 		}
1028 
1029 		ip_vs_conn_fill_param(ipvs, AF_INET, s->protocol,
1030 				      (const union nf_inet_addr *)&s->caddr,
1031 				      s->cport,
1032 				      (const union nf_inet_addr *)&s->vaddr,
1033 				      s->vport, &param);
1034 
1035 		/* Send timeout as Zero */
1036 		ip_vs_proc_conn(ipvs, &param, flags, state, s->protocol, AF_INET,
1037 				(union nf_inet_addr *)&s->daddr, s->dport,
1038 				0, 0, opt);
1039 	}
1040 }
1041 
1042 /*
1043  * Handle options
1044  */
1045 static inline int ip_vs_proc_seqopt(__u8 *p, unsigned int plen,
1046 				    __u32 *opt_flags,
1047 				    struct ip_vs_sync_conn_options *opt)
1048 {
1049 	struct ip_vs_sync_conn_options *topt;
1050 
1051 	topt = (struct ip_vs_sync_conn_options *)p;
1052 
1053 	if (plen != sizeof(struct ip_vs_sync_conn_options)) {
1054 		IP_VS_DBG(2, "BACKUP, bogus conn options length\n");
1055 		return -EINVAL;
1056 	}
1057 	if (*opt_flags & IPVS_OPT_F_SEQ_DATA) {
1058 		IP_VS_DBG(2, "BACKUP, conn options found twice\n");
1059 		return -EINVAL;
1060 	}
1061 	ntoh_seq(&topt->in_seq, &opt->in_seq);
1062 	ntoh_seq(&topt->out_seq, &opt->out_seq);
1063 	*opt_flags |= IPVS_OPT_F_SEQ_DATA;
1064 	return 0;
1065 }
1066 
1067 static int ip_vs_proc_str(__u8 *p, unsigned int plen, unsigned int *data_len,
1068 			  __u8 **data, unsigned int maxlen,
1069 			  __u32 *opt_flags, __u32 flag)
1070 {
1071 	if (plen > maxlen) {
1072 		IP_VS_DBG(2, "BACKUP, bogus par.data len > %d\n", maxlen);
1073 		return -EINVAL;
1074 	}
1075 	if (*opt_flags & flag) {
1076 		IP_VS_DBG(2, "BACKUP, Par.data found twice 0x%x\n", flag);
1077 		return -EINVAL;
1078 	}
1079 	*data_len = plen;
1080 	*data = p;
1081 	*opt_flags |= flag;
1082 	return 0;
1083 }
1084 /*
1085  *   Process a Version 1 sync. connection
1086  */
1087 static inline int ip_vs_proc_sync_conn(struct netns_ipvs *ipvs, __u8 *p, __u8 *msg_end)
1088 {
1089 	struct ip_vs_sync_conn_options opt;
1090 	union  ip_vs_sync_conn *s;
1091 	struct ip_vs_protocol *pp;
1092 	struct ip_vs_conn_param param;
1093 	__u32 flags;
1094 	unsigned int af, state, pe_data_len=0, pe_name_len=0;
1095 	__u8 *pe_data=NULL, *pe_name=NULL;
1096 	__u32 opt_flags=0;
1097 	int retc=0;
1098 
1099 	s = (union ip_vs_sync_conn *) p;
1100 
1101 	if (s->v6.type & STYPE_F_INET6) {
1102 #ifdef CONFIG_IP_VS_IPV6
1103 		af = AF_INET6;
1104 		p += sizeof(struct ip_vs_sync_v6);
1105 #else
1106 		IP_VS_DBG(3,"BACKUP, IPv6 msg received, and IPVS is not compiled for IPv6\n");
1107 		retc = 10;
1108 		goto out;
1109 #endif
1110 	} else if (!s->v4.type) {
1111 		af = AF_INET;
1112 		p += sizeof(struct ip_vs_sync_v4);
1113 	} else {
1114 		return -10;
1115 	}
1116 	if (p > msg_end)
1117 		return -20;
1118 
1119 	/* Process optional params check Type & Len. */
1120 	while (p < msg_end) {
1121 		int ptype;
1122 		int plen;
1123 
1124 		if (p+2 > msg_end)
1125 			return -30;
1126 		ptype = *(p++);
1127 		plen  = *(p++);
1128 
1129 		if (!plen || ((p + plen) > msg_end))
1130 			return -40;
1131 		/* Handle seq option  p = param data */
1132 		switch (ptype & ~IPVS_OPT_F_PARAM) {
1133 		case IPVS_OPT_SEQ_DATA:
1134 			if (ip_vs_proc_seqopt(p, plen, &opt_flags, &opt))
1135 				return -50;
1136 			break;
1137 
1138 		case IPVS_OPT_PE_DATA:
1139 			if (ip_vs_proc_str(p, plen, &pe_data_len, &pe_data,
1140 					   IP_VS_PEDATA_MAXLEN, &opt_flags,
1141 					   IPVS_OPT_F_PE_DATA))
1142 				return -60;
1143 			break;
1144 
1145 		case IPVS_OPT_PE_NAME:
1146 			if (ip_vs_proc_str(p, plen,&pe_name_len, &pe_name,
1147 					   IP_VS_PENAME_MAXLEN, &opt_flags,
1148 					   IPVS_OPT_F_PE_NAME))
1149 				return -70;
1150 			break;
1151 
1152 		default:
1153 			/* Param data mandatory ? */
1154 			if (!(ptype & IPVS_OPT_F_PARAM)) {
1155 				IP_VS_DBG(3, "BACKUP, Unknown mandatory param %d found\n",
1156 					  ptype & ~IPVS_OPT_F_PARAM);
1157 				retc = 20;
1158 				goto out;
1159 			}
1160 		}
1161 		p += plen;  /* Next option */
1162 	}
1163 
1164 	/* Get flags and Mask off unsupported */
1165 	flags = ntohl(s->v4.flags);
1166 	if (!ip_vs_sync_validate_flags(flags)) {
1167 		IP_VS_DBG(3, "BACKUP, Invalid flags 0x%X\n", flags);
1168 		retc = 25;
1169 		goto out;
1170 	}
1171 	flags &= IP_VS_CONN_F_BACKUP_MASK;
1172 	flags |= IP_VS_CONN_F_SYNC;
1173 	state = ntohs(s->v4.state);
1174 
1175 	if (!(flags & IP_VS_CONN_F_TEMPLATE)) {
1176 		pp = ip_vs_proto_get(s->v4.protocol);
1177 		if (!pp) {
1178 			IP_VS_DBG(3,"BACKUP, Unsupported protocol %u\n",
1179 				s->v4.protocol);
1180 			retc = 30;
1181 			goto out;
1182 		}
1183 		if (state >= pp->num_states) {
1184 			IP_VS_DBG(3, "BACKUP, Invalid %s state %u\n",
1185 				pp->name, state);
1186 			retc = 40;
1187 			goto out;
1188 		}
1189 	} else if (state >= IP_VS_CTPL_S_LAST) {
1190 		IP_VS_DBG(7, "BACKUP, Invalid tpl state %u\n", state);
1191 		retc = 40;
1192 		goto out;
1193 	}
1194 	if (ip_vs_conn_fill_param_sync(ipvs, af, s, &param, pe_data,
1195 				       pe_data_len, pe_name, pe_name_len)) {
1196 		retc = 50;
1197 		goto out;
1198 	}
1199 	/* If only IPv4, just silent skip IPv6 */
1200 	if (af == AF_INET)
1201 		ip_vs_proc_conn(ipvs, &param, flags, state, s->v4.protocol, af,
1202 				(union nf_inet_addr *)&s->v4.daddr, s->v4.dport,
1203 				ntohl(s->v4.timeout), ntohl(s->v4.fwmark),
1204 				(opt_flags & IPVS_OPT_F_SEQ_DATA ? &opt : NULL)
1205 				);
1206 #ifdef CONFIG_IP_VS_IPV6
1207 	else
1208 		ip_vs_proc_conn(ipvs, &param, flags, state, s->v6.protocol, af,
1209 				(union nf_inet_addr *)&s->v6.daddr, s->v6.dport,
1210 				ntohl(s->v6.timeout), ntohl(s->v6.fwmark),
1211 				(opt_flags & IPVS_OPT_F_SEQ_DATA ? &opt : NULL)
1212 				);
1213 #endif
1214 	ip_vs_pe_put(param.pe);
1215 	return 0;
1216 	/* Error exit */
1217 out:
1218 	IP_VS_DBG(2, "BACKUP, Single msg dropped err:%d\n", retc);
1219 	return retc;
1220 
1221 }
1222 /*
1223  *      Process received multicast message and create the corresponding
1224  *      ip_vs_conn entries.
1225  *      Handles Version 0 & 1
1226  */
1227 static void ip_vs_process_message(struct netns_ipvs *ipvs, __u8 *buffer,
1228 				  const size_t buflen)
1229 {
1230 	struct ip_vs_sync_mesg *m2 = (struct ip_vs_sync_mesg *)buffer;
1231 	__u8 *p, *msg_end;
1232 	int i, nr_conns;
1233 
1234 	if (buflen < sizeof(struct ip_vs_sync_mesg_v0)) {
1235 		IP_VS_DBG(2, "BACKUP, message header too short\n");
1236 		return;
1237 	}
1238 
1239 	if (buflen != ntohs(m2->size)) {
1240 		IP_VS_DBG(2, "BACKUP, bogus message size\n");
1241 		return;
1242 	}
1243 	/* SyncID sanity check */
1244 	if (ipvs->bcfg.syncid != 0 && m2->syncid != ipvs->bcfg.syncid) {
1245 		IP_VS_DBG(7, "BACKUP, Ignoring syncid = %d\n", m2->syncid);
1246 		return;
1247 	}
1248 	/* Handle version 1  message */
1249 	if ((m2->version == SYNC_PROTO_VER) && (m2->reserved == 0)
1250 	    && (m2->spare == 0)) {
1251 
1252 		msg_end = buffer + sizeof(struct ip_vs_sync_mesg);
1253 		nr_conns = m2->nr_conns;
1254 
1255 		for (i=0; i<nr_conns; i++) {
1256 			union ip_vs_sync_conn *s;
1257 			unsigned int size;
1258 			int retc;
1259 
1260 			p = msg_end;
1261 			if (p + sizeof(s->v4) > buffer+buflen) {
1262 				IP_VS_ERR_RL("BACKUP, Dropping buffer, too small\n");
1263 				return;
1264 			}
1265 			s = (union ip_vs_sync_conn *)p;
1266 			size = ntohs(s->v4.ver_size) & SVER_MASK;
1267 			msg_end = p + size;
1268 			/* Basic sanity checks */
1269 			if (msg_end  > buffer+buflen) {
1270 				IP_VS_ERR_RL("BACKUP, Dropping buffer, msg > buffer\n");
1271 				return;
1272 			}
1273 			if (ntohs(s->v4.ver_size) >> SVER_SHIFT) {
1274 				IP_VS_ERR_RL("BACKUP, Dropping buffer, Unknown version %d\n",
1275 					      ntohs(s->v4.ver_size) >> SVER_SHIFT);
1276 				return;
1277 			}
1278 			/* Process a single sync_conn */
1279 			retc = ip_vs_proc_sync_conn(ipvs, p, msg_end);
1280 			if (retc < 0) {
1281 				IP_VS_ERR_RL("BACKUP, Dropping buffer, Err: %d in decoding\n",
1282 					     retc);
1283 				return;
1284 			}
1285 			/* Make sure we have 32 bit alignment */
1286 			msg_end = p + ((size + 3) & ~3);
1287 		}
1288 	} else {
1289 		/* Old type of message */
1290 		ip_vs_process_message_v0(ipvs, buffer, buflen);
1291 		return;
1292 	}
1293 }
1294 
1295 
1296 /*
1297  *      Setup sndbuf (mode=1) or rcvbuf (mode=0)
1298  */
1299 static void set_sock_size(struct sock *sk, int mode, int val)
1300 {
1301 	/* setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &val, sizeof(val)); */
1302 	/* setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &val, sizeof(val)); */
1303 	lock_sock(sk);
1304 	if (mode) {
1305 		val = clamp_t(int, val, (SOCK_MIN_SNDBUF + 1) / 2,
1306 			      READ_ONCE(sysctl_wmem_max));
1307 		sk->sk_sndbuf = val * 2;
1308 		sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
1309 	} else {
1310 		val = clamp_t(int, val, (SOCK_MIN_RCVBUF + 1) / 2,
1311 			      READ_ONCE(sysctl_rmem_max));
1312 		sk->sk_rcvbuf = val * 2;
1313 		sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
1314 	}
1315 	release_sock(sk);
1316 }
1317 
1318 /*
1319  *      Setup loopback of outgoing multicasts on a sending socket
1320  */
1321 static void set_mcast_loop(struct sock *sk, u_char loop)
1322 {
1323 	/* setsockopt(sock, SOL_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)); */
1324 	inet_assign_bit(MC_LOOP, sk, loop);
1325 #ifdef CONFIG_IP_VS_IPV6
1326 	if (READ_ONCE(sk->sk_family) == AF_INET6) {
1327 		/* IPV6_MULTICAST_LOOP */
1328 		inet6_assign_bit(MC6_LOOP, sk, loop);
1329 	}
1330 #endif
1331 }
1332 
1333 /*
1334  *      Specify TTL for outgoing multicasts on a sending socket
1335  */
1336 static void set_mcast_ttl(struct sock *sk, u_char ttl)
1337 {
1338 	struct inet_sock *inet = inet_sk(sk);
1339 
1340 	/* setsockopt(sock, SOL_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)); */
1341 	lock_sock(sk);
1342 	WRITE_ONCE(inet->mc_ttl, ttl);
1343 #ifdef CONFIG_IP_VS_IPV6
1344 	if (sk->sk_family == AF_INET6) {
1345 		struct ipv6_pinfo *np = inet6_sk(sk);
1346 
1347 		/* IPV6_MULTICAST_HOPS */
1348 		WRITE_ONCE(np->mcast_hops, ttl);
1349 	}
1350 #endif
1351 	release_sock(sk);
1352 }
1353 
1354 /* Control fragmentation of messages */
1355 static void set_mcast_pmtudisc(struct sock *sk, int val)
1356 {
1357 	struct inet_sock *inet = inet_sk(sk);
1358 
1359 	/* setsockopt(sock, SOL_IP, IP_MTU_DISCOVER, &val, sizeof(val)); */
1360 	lock_sock(sk);
1361 	WRITE_ONCE(inet->pmtudisc, val);
1362 #ifdef CONFIG_IP_VS_IPV6
1363 	if (sk->sk_family == AF_INET6) {
1364 		struct ipv6_pinfo *np = inet6_sk(sk);
1365 
1366 		/* IPV6_MTU_DISCOVER */
1367 		WRITE_ONCE(np->pmtudisc, val);
1368 	}
1369 #endif
1370 	release_sock(sk);
1371 }
1372 
1373 /*
1374  *      Specifiy default interface for outgoing multicasts
1375  */
1376 static int set_mcast_if(struct sock *sk, struct net_device *dev)
1377 {
1378 	struct inet_sock *inet = inet_sk(sk);
1379 
1380 	if (sk->sk_bound_dev_if && dev->ifindex != sk->sk_bound_dev_if)
1381 		return -EINVAL;
1382 
1383 	lock_sock(sk);
1384 	inet->mc_index = dev->ifindex;
1385 	/*  inet->mc_addr  = 0; */
1386 #ifdef CONFIG_IP_VS_IPV6
1387 	if (sk->sk_family == AF_INET6) {
1388 		struct ipv6_pinfo *np = inet6_sk(sk);
1389 
1390 		/* IPV6_MULTICAST_IF */
1391 		WRITE_ONCE(np->mcast_oif, dev->ifindex);
1392 	}
1393 #endif
1394 	release_sock(sk);
1395 
1396 	return 0;
1397 }
1398 
1399 
1400 /*
1401  *      Join a multicast group.
1402  *      the group is specified by a class D multicast address 224.0.0.0/8
1403  *      in the in_addr structure passed in as a parameter.
1404  */
1405 static int
1406 join_mcast_group(struct sock *sk, struct in_addr *addr, struct net_device *dev)
1407 {
1408 	struct ip_mreqn mreq;
1409 	int ret;
1410 
1411 	memset(&mreq, 0, sizeof(mreq));
1412 	memcpy(&mreq.imr_multiaddr, addr, sizeof(struct in_addr));
1413 
1414 	if (sk->sk_bound_dev_if && dev->ifindex != sk->sk_bound_dev_if)
1415 		return -EINVAL;
1416 
1417 	mreq.imr_ifindex = dev->ifindex;
1418 
1419 	lock_sock(sk);
1420 	ret = ip_mc_join_group(sk, &mreq);
1421 	release_sock(sk);
1422 
1423 	return ret;
1424 }
1425 
1426 #ifdef CONFIG_IP_VS_IPV6
1427 static int join_mcast_group6(struct sock *sk, struct in6_addr *addr,
1428 			     struct net_device *dev)
1429 {
1430 	int ret;
1431 
1432 	if (sk->sk_bound_dev_if && dev->ifindex != sk->sk_bound_dev_if)
1433 		return -EINVAL;
1434 
1435 	lock_sock(sk);
1436 	ret = ipv6_sock_mc_join(sk, dev->ifindex, addr);
1437 	release_sock(sk);
1438 
1439 	return ret;
1440 }
1441 #endif
1442 
1443 static int bind_mcastif_addr(struct socket *sock, struct net_device *dev)
1444 {
1445 	__be32 addr;
1446 	struct sockaddr_in sin;
1447 
1448 	addr = inet_select_addr(dev, 0, RT_SCOPE_UNIVERSE);
1449 	if (!addr)
1450 		pr_err("You probably need to specify IP address on "
1451 		       "multicast interface.\n");
1452 
1453 	IP_VS_DBG(7, "binding socket with (%s) %pI4\n",
1454 		  dev->name, &addr);
1455 
1456 	/* Now bind the socket with the address of multicast interface */
1457 	sin.sin_family	     = AF_INET;
1458 	sin.sin_addr.s_addr  = addr;
1459 	sin.sin_port         = 0;
1460 
1461 	return kernel_bind(sock, (struct sockaddr_unsized *)&sin, sizeof(sin));
1462 }
1463 
1464 static void get_mcast_sockaddr(union ipvs_sockaddr *sa, int *salen,
1465 			       struct ipvs_sync_daemon_cfg *c, int id)
1466 {
1467 	if (AF_INET6 == c->mcast_af) {
1468 		sa->in6 = (struct sockaddr_in6) {
1469 			.sin6_family = AF_INET6,
1470 			.sin6_port = htons(c->mcast_port + id),
1471 		};
1472 		sa->in6.sin6_addr = c->mcast_group.in6;
1473 		*salen = sizeof(sa->in6);
1474 	} else {
1475 		sa->in = (struct sockaddr_in) {
1476 			.sin_family = AF_INET,
1477 			.sin_port = htons(c->mcast_port + id),
1478 		};
1479 		sa->in.sin_addr = c->mcast_group.in;
1480 		*salen = sizeof(sa->in);
1481 	}
1482 }
1483 
1484 /*
1485  *      Set up sending multicast socket over UDP
1486  */
1487 static int make_send_sock(struct netns_ipvs *ipvs, int id,
1488 			  struct net_device *dev, struct socket **sock_ret)
1489 {
1490 	/* multicast addr */
1491 	union ipvs_sockaddr mcast_addr;
1492 	struct socket *sock;
1493 	int result, salen;
1494 
1495 	/* First create a socket */
1496 	result = sock_create_kern(ipvs->net, ipvs->mcfg.mcast_af, SOCK_DGRAM,
1497 				  IPPROTO_UDP, &sock);
1498 	if (result < 0) {
1499 		pr_err("Error during creation of socket; terminating\n");
1500 		goto error;
1501 	}
1502 	*sock_ret = sock;
1503 	result = set_mcast_if(sock->sk, dev);
1504 	if (result < 0) {
1505 		pr_err("Error setting outbound mcast interface\n");
1506 		goto error;
1507 	}
1508 
1509 	set_mcast_loop(sock->sk, 0);
1510 	set_mcast_ttl(sock->sk, ipvs->mcfg.mcast_ttl);
1511 	/* Allow fragmentation if MTU changes */
1512 	set_mcast_pmtudisc(sock->sk, IP_PMTUDISC_DONT);
1513 	result = sysctl_sync_sock_size(ipvs);
1514 	if (result > 0)
1515 		set_sock_size(sock->sk, 1, result);
1516 
1517 	if (AF_INET == ipvs->mcfg.mcast_af)
1518 		result = bind_mcastif_addr(sock, dev);
1519 	else
1520 		result = 0;
1521 	if (result < 0) {
1522 		pr_err("Error binding address of the mcast interface\n");
1523 		goto error;
1524 	}
1525 
1526 	get_mcast_sockaddr(&mcast_addr, &salen, &ipvs->mcfg, id);
1527 	result = kernel_connect(sock, (struct sockaddr_unsized *)&mcast_addr,
1528 				salen, 0);
1529 	if (result < 0) {
1530 		pr_err("Error connecting to the multicast addr\n");
1531 		goto error;
1532 	}
1533 
1534 	return 0;
1535 
1536 error:
1537 	return result;
1538 }
1539 
1540 
1541 /*
1542  *      Set up receiving multicast socket over UDP
1543  */
1544 static int make_receive_sock(struct netns_ipvs *ipvs, int id,
1545 			     struct net_device *dev, struct socket **sock_ret)
1546 {
1547 	/* multicast addr */
1548 	union ipvs_sockaddr mcast_addr;
1549 	struct socket *sock;
1550 	int result, salen;
1551 
1552 	/* First create a socket */
1553 	result = sock_create_kern(ipvs->net, ipvs->bcfg.mcast_af, SOCK_DGRAM,
1554 				  IPPROTO_UDP, &sock);
1555 	if (result < 0) {
1556 		pr_err("Error during creation of socket; terminating\n");
1557 		goto error;
1558 	}
1559 	*sock_ret = sock;
1560 	/* it is equivalent to the REUSEADDR option in user-space */
1561 	sock->sk->sk_reuse = SK_CAN_REUSE;
1562 	result = sysctl_sync_sock_size(ipvs);
1563 	if (result > 0)
1564 		set_sock_size(sock->sk, 0, result);
1565 
1566 	get_mcast_sockaddr(&mcast_addr, &salen, &ipvs->bcfg, id);
1567 	sock->sk->sk_bound_dev_if = dev->ifindex;
1568 	result = kernel_bind(sock, (struct sockaddr_unsized *)&mcast_addr, salen);
1569 	if (result < 0) {
1570 		pr_err("Error binding to the multicast addr\n");
1571 		goto error;
1572 	}
1573 
1574 	/* join the multicast group */
1575 #ifdef CONFIG_IP_VS_IPV6
1576 	if (ipvs->bcfg.mcast_af == AF_INET6)
1577 		result = join_mcast_group6(sock->sk, &mcast_addr.in6.sin6_addr,
1578 					   dev);
1579 	else
1580 #endif
1581 		result = join_mcast_group(sock->sk, &mcast_addr.in.sin_addr,
1582 					  dev);
1583 	if (result < 0) {
1584 		pr_err("Error joining to the multicast group\n");
1585 		goto error;
1586 	}
1587 
1588 	return 0;
1589 
1590 error:
1591 	return result;
1592 }
1593 
1594 
1595 static int
1596 ip_vs_send_async(struct socket *sock, const char *buffer, const size_t length)
1597 {
1598 	struct msghdr	msg = {.msg_flags = MSG_DONTWAIT|MSG_NOSIGNAL};
1599 	struct kvec	iov;
1600 	int		len;
1601 
1602 	iov.iov_base     = (void *)buffer;
1603 	iov.iov_len      = length;
1604 
1605 	len = kernel_sendmsg(sock, &msg, &iov, 1, (size_t)(length));
1606 
1607 	return len;
1608 }
1609 
1610 static int
1611 ip_vs_send_sync_msg(struct socket *sock, struct ip_vs_sync_mesg *msg)
1612 {
1613 	int msize;
1614 	int ret;
1615 
1616 	msize = ntohs(msg->size);
1617 
1618 	ret = ip_vs_send_async(sock, (char *)msg, msize);
1619 	if (ret >= 0 || ret == -EAGAIN)
1620 		return ret;
1621 	pr_err("ip_vs_send_async error %d\n", ret);
1622 	return 0;
1623 }
1624 
1625 static int
1626 ip_vs_receive(struct socket *sock, char *buffer, const size_t buflen)
1627 {
1628 	struct msghdr		msg = {NULL,};
1629 	struct kvec		iov = {buffer, buflen};
1630 	int			len;
1631 
1632 	/* Receive a packet */
1633 	iov_iter_kvec(&msg.msg_iter, ITER_DEST, &iov, 1, buflen);
1634 	len = sock_recvmsg(sock, &msg, MSG_DONTWAIT);
1635 	if (len < 0)
1636 		return len;
1637 
1638 	return len;
1639 }
1640 
1641 /* Wakeup the master thread for sending */
1642 static void master_wakeup_work_handler(struct work_struct *work)
1643 {
1644 	struct ipvs_master_sync_state *ms =
1645 		container_of(work, struct ipvs_master_sync_state,
1646 			     master_wakeup_work.work);
1647 	struct netns_ipvs *ipvs = ms->ipvs;
1648 
1649 	spin_lock_bh(&ipvs->sync_lock);
1650 	if (ms->sync_queue_len &&
1651 	    ms->sync_queue_delay < IPVS_SYNC_WAKEUP_RATE) {
1652 		int id = (int)(ms - ipvs->ms);
1653 
1654 		ms->sync_queue_delay = IPVS_SYNC_WAKEUP_RATE;
1655 		wake_up_process(ipvs->master_tinfo[id].task);
1656 	}
1657 	spin_unlock_bh(&ipvs->sync_lock);
1658 }
1659 
1660 /* Get next buffer to send */
1661 static inline struct ip_vs_sync_buff *
1662 next_sync_buff(struct netns_ipvs *ipvs, struct ipvs_master_sync_state *ms)
1663 {
1664 	struct ip_vs_sync_buff *sb;
1665 
1666 	sb = sb_dequeue(ipvs, ms);
1667 	if (sb)
1668 		return sb;
1669 	/* Do not delay entries in buffer for more than 2 seconds */
1670 	return get_curr_sync_buff(ipvs, ms, IPVS_SYNC_FLUSH_TIME);
1671 }
1672 
1673 static int sync_thread_master(void *data)
1674 {
1675 	struct ip_vs_sync_thread_data *tinfo = data;
1676 	struct netns_ipvs *ipvs = tinfo->ipvs;
1677 	struct ipvs_master_sync_state *ms = &ipvs->ms[tinfo->id];
1678 	struct sock *sk = tinfo->sock->sk;
1679 	struct ip_vs_sync_buff *sb;
1680 
1681 	pr_info("sync thread started: state = MASTER, mcast_ifn = %s, "
1682 		"syncid = %d, id = %d\n",
1683 		ipvs->mcfg.mcast_ifn, ipvs->mcfg.syncid, tinfo->id);
1684 
1685 	for (;;) {
1686 		sb = next_sync_buff(ipvs, ms);
1687 		if (unlikely(kthread_should_stop()))
1688 			break;
1689 		if (!sb) {
1690 			schedule_timeout(IPVS_SYNC_CHECK_PERIOD);
1691 			continue;
1692 		}
1693 		while (ip_vs_send_sync_msg(tinfo->sock, sb->mesg) < 0) {
1694 			/* (Ab)use interruptible sleep to avoid increasing
1695 			 * the load avg.
1696 			 */
1697 			__wait_event_interruptible(*sk_sleep(sk),
1698 						   sock_writeable(sk) ||
1699 						   kthread_should_stop());
1700 			if (unlikely(kthread_should_stop()))
1701 				goto done;
1702 		}
1703 		ip_vs_sync_buff_release(sb);
1704 	}
1705 
1706 done:
1707 	__set_current_state(TASK_RUNNING);
1708 	if (sb)
1709 		ip_vs_sync_buff_release(sb);
1710 
1711 	/* clean up the sync_buff queue */
1712 	while ((sb = sb_dequeue(ipvs, ms)))
1713 		ip_vs_sync_buff_release(sb);
1714 	__set_current_state(TASK_RUNNING);
1715 
1716 	/* clean up the current sync_buff */
1717 	sb = get_curr_sync_buff(ipvs, ms, 0);
1718 	if (sb)
1719 		ip_vs_sync_buff_release(sb);
1720 
1721 	return 0;
1722 }
1723 
1724 
1725 static int sync_thread_backup(void *data)
1726 {
1727 	struct ip_vs_sync_thread_data *tinfo = data;
1728 	struct netns_ipvs *ipvs = tinfo->ipvs;
1729 	struct sock *sk = tinfo->sock->sk;
1730 	struct udp_sock *up = udp_sk(sk);
1731 	int len;
1732 
1733 	pr_info("sync thread started: state = BACKUP, mcast_ifn = %s, "
1734 		"syncid = %d, id = %d\n",
1735 		ipvs->bcfg.mcast_ifn, ipvs->bcfg.syncid, tinfo->id);
1736 
1737 	while (!kthread_should_stop()) {
1738 		wait_event_interruptible(*sk_sleep(sk),
1739 					 !skb_queue_empty_lockless(&sk->sk_receive_queue) ||
1740 					 !skb_queue_empty_lockless(&up->reader_queue) ||
1741 					 kthread_should_stop());
1742 
1743 		/* do we have data now? */
1744 		while (!skb_queue_empty_lockless(&sk->sk_receive_queue) ||
1745 		       !skb_queue_empty_lockless(&up->reader_queue)) {
1746 			len = ip_vs_receive(tinfo->sock, tinfo->buf,
1747 					ipvs->bcfg.sync_maxlen);
1748 			if (len <= 0) {
1749 				if (len != -EAGAIN)
1750 					pr_err("receiving message error\n");
1751 				break;
1752 			}
1753 
1754 			ip_vs_process_message(ipvs, tinfo->buf, len);
1755 		}
1756 	}
1757 
1758 	return 0;
1759 }
1760 
1761 
1762 int start_sync_thread(struct netns_ipvs *ipvs, struct ipvs_sync_daemon_cfg *c,
1763 		      int state)
1764 {
1765 	struct ip_vs_sync_thread_data *ti = NULL, *tinfo;
1766 	struct task_struct *task;
1767 	struct net_device *dev;
1768 	char *name;
1769 	int (*threadfn)(void *data);
1770 	int id = 0, count, hlen;
1771 	int result = -ENOMEM;
1772 	u16 mtu, min_mtu;
1773 
1774 	IP_VS_DBG(7, "%s(): pid %d\n", __func__, task_pid_nr(current));
1775 	IP_VS_DBG(7, "Each ip_vs_sync_conn entry needs %zd bytes\n",
1776 		  sizeof(struct ip_vs_sync_conn_v0));
1777 
1778 	/* increase the module use count */
1779 	if (!ip_vs_use_count_inc())
1780 		return -ENOPROTOOPT;
1781 
1782 	/* Backup server can be started without services just to sync conns,
1783 	 * make sure conn_tab is created even if ipvs->enable is 0.
1784 	 */
1785 	if (state == IP_VS_STATE_BACKUP) {
1786 		mutex_lock(&ipvs->service_mutex);
1787 		if (!rcu_dereference_protected(ipvs->conn_tab, 1)) {
1788 			int lfactor = sysctl_conn_lfactor(ipvs);
1789 			int new_size = ip_vs_conn_desired_size(ipvs, NULL,
1790 							       lfactor);
1791 			struct ip_vs_rht *tc_new;
1792 
1793 			tc_new = ip_vs_conn_tab_alloc(ipvs, new_size, lfactor);
1794 			if (!tc_new) {
1795 				mutex_unlock(&ipvs->service_mutex);
1796 				result = -ENOMEM;
1797 				goto out_module;
1798 			}
1799 			rcu_assign_pointer(ipvs->conn_tab, tc_new);
1800 		}
1801 		mutex_unlock(&ipvs->service_mutex);
1802 	}
1803 
1804 	/* Do not hold one mutex and then to block on another */
1805 	for (;;) {
1806 		rtnl_lock();
1807 		if (mutex_trylock(&ipvs->sync_mutex))
1808 			break;
1809 		rtnl_unlock();
1810 		mutex_lock(&ipvs->sync_mutex);
1811 		if (rtnl_trylock())
1812 			break;
1813 		mutex_unlock(&ipvs->sync_mutex);
1814 	}
1815 
1816 	if (!ipvs->sync_state) {
1817 		count = clamp(sysctl_sync_ports(ipvs), 1, IPVS_SYNC_PORTS_MAX);
1818 		ipvs->threads_mask = count - 1;
1819 	} else
1820 		count = ipvs->threads_mask + 1;
1821 
1822 	if (c->mcast_af == AF_UNSPEC) {
1823 		c->mcast_af = AF_INET;
1824 		c->mcast_group.ip = cpu_to_be32(IP_VS_SYNC_GROUP);
1825 	}
1826 	if (!c->mcast_port)
1827 		c->mcast_port = IP_VS_SYNC_PORT;
1828 	if (!c->mcast_ttl)
1829 		c->mcast_ttl = 1;
1830 
1831 	dev = __dev_get_by_name(ipvs->net, c->mcast_ifn);
1832 	if (!dev) {
1833 		pr_err("Unknown mcast interface: %s\n", c->mcast_ifn);
1834 		result = -ENODEV;
1835 		goto out_early;
1836 	}
1837 	hlen = (AF_INET6 == c->mcast_af) ?
1838 	       sizeof(struct ipv6hdr) + sizeof(struct udphdr) :
1839 	       sizeof(struct iphdr) + sizeof(struct udphdr);
1840 	mtu = (state == IP_VS_STATE_BACKUP) ?
1841 		  clamp(dev->mtu, 1500U, 65535U) : 1500U;
1842 	min_mtu = (state == IP_VS_STATE_BACKUP) ? 1024 : 1;
1843 
1844 	if (c->sync_maxlen)
1845 		c->sync_maxlen = clamp_t(unsigned int,
1846 					 c->sync_maxlen, min_mtu,
1847 					 65535 - hlen);
1848 	else
1849 		c->sync_maxlen = mtu - hlen;
1850 
1851 	if (state == IP_VS_STATE_MASTER) {
1852 		result = -EEXIST;
1853 		if (ipvs->ms)
1854 			goto out_early;
1855 
1856 		ipvs->mcfg = *c;
1857 		name = "ipvs-m:%d:%d";
1858 		threadfn = sync_thread_master;
1859 	} else if (state == IP_VS_STATE_BACKUP) {
1860 		result = -EEXIST;
1861 		if (ipvs->backup_tinfo)
1862 			goto out_early;
1863 
1864 		ipvs->bcfg = *c;
1865 		name = "ipvs-b:%d:%d";
1866 		threadfn = sync_thread_backup;
1867 	} else {
1868 		result = -EINVAL;
1869 		goto out_early;
1870 	}
1871 
1872 	if (state == IP_VS_STATE_MASTER) {
1873 		struct ipvs_master_sync_state *ms;
1874 
1875 		result = -ENOMEM;
1876 		ipvs->ms = kzalloc_objs(ipvs->ms[0], count);
1877 		if (!ipvs->ms)
1878 			goto out;
1879 		ms = ipvs->ms;
1880 		for (id = 0; id < count; id++, ms++) {
1881 			INIT_LIST_HEAD(&ms->sync_queue);
1882 			ms->sync_queue_len = 0;
1883 			ms->sync_queue_delay = 0;
1884 			INIT_DELAYED_WORK(&ms->master_wakeup_work,
1885 					  master_wakeup_work_handler);
1886 			ms->ipvs = ipvs;
1887 		}
1888 	}
1889 	result = -ENOMEM;
1890 	ti = kzalloc_objs(struct ip_vs_sync_thread_data, count);
1891 	if (!ti)
1892 		goto out;
1893 
1894 	for (id = 0; id < count; id++) {
1895 		tinfo = &ti[id];
1896 		tinfo->ipvs = ipvs;
1897 		if (state == IP_VS_STATE_BACKUP) {
1898 			result = -ENOMEM;
1899 			tinfo->buf = kmalloc(ipvs->bcfg.sync_maxlen,
1900 					     GFP_KERNEL);
1901 			if (!tinfo->buf)
1902 				goto out;
1903 		}
1904 		tinfo->id = id;
1905 		if (state == IP_VS_STATE_MASTER)
1906 			result = make_send_sock(ipvs, id, dev, &tinfo->sock);
1907 		else
1908 			result = make_receive_sock(ipvs, id, dev, &tinfo->sock);
1909 		if (result < 0)
1910 			goto out;
1911 
1912 		task = kthread_run(threadfn, tinfo, name, ipvs->gen, id);
1913 		if (IS_ERR(task)) {
1914 			result = PTR_ERR(task);
1915 			goto out;
1916 		}
1917 		tinfo->task = task;
1918 	}
1919 
1920 	/* mark as active */
1921 
1922 	if (state == IP_VS_STATE_MASTER)
1923 		ipvs->master_tinfo = ti;
1924 	else
1925 		ipvs->backup_tinfo = ti;
1926 	spin_lock_bh(&ipvs->sync_buff_lock);
1927 	ipvs->sync_state |= state;
1928 	spin_unlock_bh(&ipvs->sync_buff_lock);
1929 
1930 	mutex_unlock(&ipvs->sync_mutex);
1931 	rtnl_unlock();
1932 
1933 	return 0;
1934 
1935 out:
1936 	/* We do not need RTNL lock anymore, release it here so that
1937 	 * sock_release below can use rtnl_lock to leave the mcast group.
1938 	 */
1939 	rtnl_unlock();
1940 	id = min(id, count - 1);
1941 	if (ti) {
1942 		for (tinfo = ti + id; tinfo >= ti; tinfo--) {
1943 			if (tinfo->task)
1944 				kthread_stop(tinfo->task);
1945 		}
1946 	}
1947 	if (!(ipvs->sync_state & IP_VS_STATE_MASTER)) {
1948 		kfree(ipvs->ms);
1949 		ipvs->ms = NULL;
1950 	}
1951 	mutex_unlock(&ipvs->sync_mutex);
1952 
1953 	/* No more mutexes, release socks */
1954 	if (ti) {
1955 		for (tinfo = ti + id; tinfo >= ti; tinfo--) {
1956 			if (tinfo->sock)
1957 				sock_release(tinfo->sock);
1958 			kfree(tinfo->buf);
1959 		}
1960 		kfree(ti);
1961 	}
1962 
1963 	/* decrease the module use count */
1964 	ip_vs_use_count_dec();
1965 	return result;
1966 
1967 out_early:
1968 	mutex_unlock(&ipvs->sync_mutex);
1969 	rtnl_unlock();
1970 
1971 out_module:
1972 	/* decrease the module use count */
1973 	ip_vs_use_count_dec();
1974 	return result;
1975 }
1976 
1977 
1978 int stop_sync_thread(struct netns_ipvs *ipvs, int state)
1979 {
1980 	struct ip_vs_sync_thread_data *ti, *tinfo;
1981 	int id;
1982 	int retc = -EINVAL;
1983 
1984 	IP_VS_DBG(7, "%s(): pid %d\n", __func__, task_pid_nr(current));
1985 
1986 	mutex_lock(&ipvs->sync_mutex);
1987 	if (state == IP_VS_STATE_MASTER) {
1988 		retc = -ESRCH;
1989 		if (!ipvs->ms)
1990 			goto err;
1991 		ti = ipvs->master_tinfo;
1992 
1993 		/*
1994 		 * The lock synchronizes with sb_queue_tail(), so that we don't
1995 		 * add sync buffers to the queue, when we are already in
1996 		 * progress of stopping the master sync daemon.
1997 		 */
1998 
1999 		spin_lock_bh(&ipvs->sync_buff_lock);
2000 		spin_lock(&ipvs->sync_lock);
2001 		ipvs->sync_state &= ~IP_VS_STATE_MASTER;
2002 		spin_unlock(&ipvs->sync_lock);
2003 		spin_unlock_bh(&ipvs->sync_buff_lock);
2004 
2005 		retc = 0;
2006 		for (id = ipvs->threads_mask; id >= 0; id--) {
2007 			struct ipvs_master_sync_state *ms = &ipvs->ms[id];
2008 			int ret;
2009 
2010 			tinfo = &ti[id];
2011 			pr_info("stopping master sync thread %d ...\n",
2012 				task_pid_nr(tinfo->task));
2013 			cancel_delayed_work_sync(&ms->master_wakeup_work);
2014 			ret = kthread_stop(tinfo->task);
2015 			if (retc >= 0)
2016 				retc = ret;
2017 		}
2018 		kfree(ipvs->ms);
2019 		ipvs->ms = NULL;
2020 		ipvs->master_tinfo = NULL;
2021 	} else if (state == IP_VS_STATE_BACKUP) {
2022 		retc = -ESRCH;
2023 		if (!ipvs->backup_tinfo)
2024 			goto err;
2025 		ti = ipvs->backup_tinfo;
2026 
2027 		ipvs->sync_state &= ~IP_VS_STATE_BACKUP;
2028 		retc = 0;
2029 		for (id = ipvs->threads_mask; id >= 0; id--) {
2030 			int ret;
2031 
2032 			tinfo = &ti[id];
2033 			pr_info("stopping backup sync thread %d ...\n",
2034 				task_pid_nr(tinfo->task));
2035 			ret = kthread_stop(tinfo->task);
2036 			if (retc >= 0)
2037 				retc = ret;
2038 		}
2039 		ipvs->backup_tinfo = NULL;
2040 	} else {
2041 		goto err;
2042 	}
2043 	id = ipvs->threads_mask;
2044 	mutex_unlock(&ipvs->sync_mutex);
2045 
2046 	/* No more mutexes, release socks */
2047 	for (tinfo = ti + id; tinfo >= ti; tinfo--) {
2048 		if (tinfo->sock)
2049 			sock_release(tinfo->sock);
2050 		kfree(tinfo->buf);
2051 	}
2052 	kfree(ti);
2053 
2054 	/* decrease the module use count */
2055 	ip_vs_use_count_dec();
2056 	return retc;
2057 
2058 err:
2059 	mutex_unlock(&ipvs->sync_mutex);
2060 	return retc;
2061 }
2062 
2063 /*
2064  * Initialize data struct for each netns
2065  */
2066 int __net_init ip_vs_sync_net_init(struct netns_ipvs *ipvs)
2067 {
2068 	__mutex_init(&ipvs->sync_mutex, "ipvs->sync_mutex", &__ipvs_sync_key);
2069 	spin_lock_init(&ipvs->sync_lock);
2070 	spin_lock_init(&ipvs->sync_buff_lock);
2071 	return 0;
2072 }
2073 
2074 void ip_vs_sync_net_cleanup(struct netns_ipvs *ipvs)
2075 {
2076 	int retc;
2077 
2078 	retc = stop_sync_thread(ipvs, IP_VS_STATE_MASTER);
2079 	if (retc && retc != -ESRCH)
2080 		pr_err("Failed to stop Master Daemon\n");
2081 
2082 	retc = stop_sync_thread(ipvs, IP_VS_STATE_BACKUP);
2083 	if (retc && retc != -ESRCH)
2084 		pr_err("Failed to stop Backup Daemon\n");
2085 }
2086