xref: /linux/net/netfilter/ipvs/ip_vs_sync.c (revision 1d1e8bc81f790a48cd643b1b1762de43334d4f14)
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_conn_options opts;
543 	struct ip_vs_sync_mesg_v0 *m;
544 	struct ip_vs_sync_conn_v0 *s;
545 	struct ip_vs_sync_buff *buff;
546 	struct ipvs_master_sync_state *ms;
547 	u32 flags, seq_mask;
548 	unsigned int len;
549 	int id;
550 
551 	if (unlikely(cp->af != AF_INET))
552 		return;
553 	flags = READ_ONCE(cp->flags);
554 	/* Do not sync ONE PACKET */
555 	if (flags & IP_VS_CONN_F_ONE_PACKET)
556 		return;
557 
558 	if (!ip_vs_sync_conn_needed(ipvs, cp, pkts))
559 		return;
560 
561 	if (flags & IP_VS_CONN_F_SEQ_MASK) {
562 		/* Take atomic snapshot of flags and seqs */
563 		spin_lock_bh(&cp->lock);
564 		flags = cp->flags;
565 		memcpy(&opts, &cp->sync_conn_opt, sizeof(opts));
566 		spin_unlock_bh(&cp->lock);
567 	}
568 
569 	spin_lock_bh(&ipvs->sync_buff_lock);
570 	if (!(ipvs->sync_state & IP_VS_STATE_MASTER)) {
571 		spin_unlock_bh(&ipvs->sync_buff_lock);
572 		return;
573 	}
574 
575 	id = select_master_thread_id(ipvs, cp);
576 	ms = &ipvs->ms[id];
577 	buff = ms->sync_buff;
578 	seq_mask = flags & IP_VS_CONN_F_SEQ_MASK;
579 	len = seq_mask ? FULL_CONN_SIZE : SIMPLE_CONN_SIZE;
580 	if (buff) {
581 		m = (struct ip_vs_sync_mesg_v0 *) buff->mesg;
582 		/* Send buffer if it is for v1 */
583 		if (buff->head + len > buff->end || !m->nr_conns) {
584 			sb_queue_tail(ipvs, ms);
585 			ms->sync_buff = NULL;
586 			buff = NULL;
587 		}
588 	}
589 	if (!buff) {
590 		buff = ip_vs_sync_buff_create_v0(ipvs, len);
591 		if (!buff) {
592 			spin_unlock_bh(&ipvs->sync_buff_lock);
593 			pr_err("ip_vs_sync_buff_create failed.\n");
594 			return;
595 		}
596 		ms->sync_buff = buff;
597 	}
598 
599 	m = (struct ip_vs_sync_mesg_v0 *) buff->mesg;
600 	s = (struct ip_vs_sync_conn_v0 *) buff->head;
601 
602 	/* copy members */
603 	s->reserved = 0;
604 	s->protocol = cp->protocol;
605 	s->cport = cp->cport;
606 	s->vport = cp->vport;
607 	s->dport = cp->dport;
608 	s->caddr = cp->caddr.ip;
609 	s->vaddr = cp->vaddr.ip;
610 	s->daddr = cp->daddr.ip;
611 	s->flags = htons(flags & ~IP_VS_CONN_F_HASHED);
612 	s->state = htons(cp->state);
613 	if (seq_mask) {
614 		struct ip_vs_sync_conn_options *opt =
615 			(struct ip_vs_sync_conn_options *)&s[1];
616 		memcpy(opt, &opts, sizeof(*opt));
617 	}
618 
619 	m->nr_conns++;
620 	m->size = htons(ntohs(m->size) + len);
621 	buff->head += len;
622 	spin_unlock_bh(&ipvs->sync_buff_lock);
623 
624 	/* synchronize its controller if it has */
625 	cp = cp->control;
626 	if (cp) {
627 		if (cp->flags & IP_VS_CONN_F_TEMPLATE)
628 			pkts = atomic_inc_return(&cp->in_pkts);
629 		else
630 			pkts = sysctl_sync_threshold(ipvs);
631 		ip_vs_sync_conn(ipvs, cp, pkts);
632 	}
633 }
634 
635 /*
636  *      Add an ip_vs_conn information into the current sync_buff.
637  *      Called by ip_vs_in.
638  *      Sending Version 1 messages
639  */
640 void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts)
641 {
642 	struct ip_vs_sync_conn_options opts;
643 	struct ip_vs_sync_mesg *m;
644 	union ip_vs_sync_conn *s;
645 	struct ip_vs_sync_buff *buff;
646 	struct ipvs_master_sync_state *ms;
647 	int id;
648 	__u8 *p;
649 	unsigned int len, pe_name_len, pad;
650 	u32 flags, seq_mask;
651 
652 	/* Handle old version of the protocol */
653 	if (sysctl_sync_ver(ipvs) == 0) {
654 		ip_vs_sync_conn_v0(ipvs, cp, pkts);
655 		return;
656 	}
657 	/* Do not sync ONE PACKET */
658 	if (cp->flags & IP_VS_CONN_F_ONE_PACKET)
659 		goto control;
660 sloop:
661 	if (!ip_vs_sync_conn_needed(ipvs, cp, pkts))
662 		goto control;
663 	flags = READ_ONCE(cp->flags);
664 	if (flags & IP_VS_CONN_F_SEQ_MASK) {
665 		/* Take atomic snapshot of flags and seqs */
666 		spin_lock_bh(&cp->lock);
667 		flags = cp->flags;
668 		memcpy(&opts, &cp->sync_conn_opt, sizeof(opts));
669 		spin_unlock_bh(&cp->lock);
670 	}
671 
672 	/* Sanity checks */
673 	pe_name_len = 0;
674 	if (cp->pe_data_len) {
675 		if (!cp->pe_data || !cp->dest) {
676 			IP_VS_ERR_RL("SYNC, connection pe_data invalid\n");
677 			return;
678 		}
679 		pe_name_len = strnlen(cp->pe->name, IP_VS_PENAME_MAXLEN);
680 	}
681 
682 	spin_lock_bh(&ipvs->sync_buff_lock);
683 	if (!(ipvs->sync_state & IP_VS_STATE_MASTER)) {
684 		spin_unlock_bh(&ipvs->sync_buff_lock);
685 		return;
686 	}
687 
688 	id = select_master_thread_id(ipvs, cp);
689 	ms = &ipvs->ms[id];
690 
691 #ifdef CONFIG_IP_VS_IPV6
692 	if (cp->af == AF_INET6)
693 		len = sizeof(struct ip_vs_sync_v6);
694 	else
695 #endif
696 		len = sizeof(struct ip_vs_sync_v4);
697 
698 	seq_mask = flags & IP_VS_CONN_F_SEQ_MASK;
699 	if (seq_mask)
700 		len += sizeof(struct ip_vs_sync_conn_options) + 2;
701 
702 	if (cp->pe_data_len)
703 		len += cp->pe_data_len + 2;	/* + Param hdr field */
704 	if (pe_name_len)
705 		len += pe_name_len + 2;
706 
707 	/* check if there is a space for this one  */
708 	pad = 0;
709 	buff = ms->sync_buff;
710 	if (buff) {
711 		m = buff->mesg;
712 		pad = (4 - (size_t) buff->head) & 3;
713 		/* Send buffer if it is for v0 */
714 		if (buff->head + len + pad > buff->end || m->reserved) {
715 			sb_queue_tail(ipvs, ms);
716 			ms->sync_buff = NULL;
717 			buff = NULL;
718 			pad = 0;
719 		}
720 	}
721 
722 	if (!buff) {
723 		buff = ip_vs_sync_buff_create(ipvs, len);
724 		if (!buff) {
725 			spin_unlock_bh(&ipvs->sync_buff_lock);
726 			pr_err("ip_vs_sync_buff_create failed.\n");
727 			return;
728 		}
729 		ms->sync_buff = buff;
730 		m = buff->mesg;
731 	}
732 
733 	p = buff->head;
734 	buff->head += pad + len;
735 	m->size = htons(ntohs(m->size) + pad + len);
736 	/* Add ev. padding from prev. sync_conn */
737 	while (pad--)
738 		*(p++) = 0;
739 
740 	s = (union ip_vs_sync_conn *)p;
741 
742 	/* Set message type  & copy members */
743 	s->v4.type = (cp->af == AF_INET6 ? STYPE_F_INET6 : 0);
744 	s->v4.ver_size = htons(len & SVER_MASK);	/* Version 0 */
745 	s->v4.flags = htonl(flags & ~IP_VS_CONN_F_HASHED);
746 	s->v4.state = htons(cp->state);
747 	s->v4.protocol = cp->protocol;
748 	s->v4.cport = cp->cport;
749 	s->v4.vport = cp->vport;
750 	s->v4.dport = cp->dport;
751 	s->v4.fwmark = htonl(cp->fwmark);
752 	s->v4.timeout = htonl(max(1UL, cp->timeout / HZ));
753 	m->nr_conns++;
754 
755 #ifdef CONFIG_IP_VS_IPV6
756 	if (cp->af == AF_INET6) {
757 		p += sizeof(struct ip_vs_sync_v6);
758 		s->v6.caddr = cp->caddr.in6;
759 		s->v6.vaddr = cp->vaddr.in6;
760 		s->v6.daddr = cp->daddr.in6;
761 	} else
762 #endif
763 	{
764 		p += sizeof(struct ip_vs_sync_v4);	/* options ptr */
765 		s->v4.caddr = cp->caddr.ip;
766 		s->v4.vaddr = cp->vaddr.ip;
767 		s->v4.daddr = cp->daddr.ip;
768 	}
769 	if (seq_mask) {
770 		*(p++) = IPVS_OPT_SEQ_DATA;
771 		*(p++) = sizeof(struct ip_vs_sync_conn_options);
772 		hton_seq(&opts.in_seq, (struct ip_vs_seq *)p);
773 		p += sizeof(struct ip_vs_seq);
774 		hton_seq(&opts.out_seq, (struct ip_vs_seq *)p);
775 		p += sizeof(struct ip_vs_seq);
776 	}
777 	/* Handle pe data */
778 	if (cp->pe_data_len && cp->pe_data) {
779 		*(p++) = IPVS_OPT_PE_DATA;
780 		*(p++) = cp->pe_data_len;
781 		memcpy(p, cp->pe_data, cp->pe_data_len);
782 		p += cp->pe_data_len;
783 		if (pe_name_len) {
784 			/* Add PE_NAME */
785 			*(p++) = IPVS_OPT_PE_NAME;
786 			*(p++) = pe_name_len;
787 			memcpy(p, cp->pe->name, pe_name_len);
788 			p += pe_name_len;
789 		}
790 	}
791 
792 	spin_unlock_bh(&ipvs->sync_buff_lock);
793 
794 control:
795 	/* synchronize its controller if it has */
796 	cp = cp->control;
797 	if (!cp)
798 		return;
799 	if (cp->flags & IP_VS_CONN_F_TEMPLATE)
800 		pkts = atomic_inc_return(&cp->in_pkts);
801 	else
802 		pkts = sysctl_sync_threshold(ipvs);
803 	goto sloop;
804 }
805 
806 /*
807  *  fill_param used by version 1
808  */
809 static inline int
810 ip_vs_conn_fill_param_sync(struct netns_ipvs *ipvs, int af, union ip_vs_sync_conn *sc,
811 			   struct ip_vs_conn_param *p,
812 			   __u8 *pe_data, unsigned int pe_data_len,
813 			   __u8 *pe_name, unsigned int pe_name_len)
814 {
815 #ifdef CONFIG_IP_VS_IPV6
816 	if (af == AF_INET6)
817 		ip_vs_conn_fill_param(ipvs, af, sc->v6.protocol,
818 				      (const union nf_inet_addr *)&sc->v6.caddr,
819 				      sc->v6.cport,
820 				      (const union nf_inet_addr *)&sc->v6.vaddr,
821 				      sc->v6.vport, p);
822 	else
823 #endif
824 		ip_vs_conn_fill_param(ipvs, af, sc->v4.protocol,
825 				      (const union nf_inet_addr *)&sc->v4.caddr,
826 				      sc->v4.cport,
827 				      (const union nf_inet_addr *)&sc->v4.vaddr,
828 				      sc->v4.vport, p);
829 	/* Handle pe data */
830 	if (pe_data_len) {
831 		if (pe_name_len) {
832 			char buff[IP_VS_PENAME_MAXLEN+1];
833 
834 			memcpy(buff, pe_name, pe_name_len);
835 			buff[pe_name_len]=0;
836 			p->pe = __ip_vs_pe_getbyname(buff);
837 			if (!p->pe) {
838 				IP_VS_DBG(3, "BACKUP, no %s engine found/loaded\n",
839 					     buff);
840 				return 1;
841 			}
842 		} else {
843 			IP_VS_ERR_RL("BACKUP, Invalid PE parameters\n");
844 			return 1;
845 		}
846 
847 		p->pe_data = kmemdup(pe_data, pe_data_len, GFP_ATOMIC);
848 		if (!p->pe_data) {
849 			module_put(p->pe->module);
850 			return -ENOMEM;
851 		}
852 		p->pe_data_len = pe_data_len;
853 	}
854 	return 0;
855 }
856 
857 /*
858  *  Connection Add / Update.
859  *  Common for version 0 and 1 reception of backup sync_conns.
860  *  Param: ...
861  *         timeout is in sec.
862  */
863 static void ip_vs_proc_conn(struct netns_ipvs *ipvs, struct ip_vs_conn_param *param,
864 			    unsigned int flags, unsigned int state,
865 			    unsigned int protocol, unsigned int type,
866 			    const union nf_inet_addr *daddr, __be16 dport,
867 			    unsigned long timeout, __u32 fwmark,
868 			    struct ip_vs_sync_conn_options *opt)
869 {
870 	struct ip_vs_conn *cp_new = NULL;
871 	struct ip_vs_dest *dest;
872 	struct ip_vs_conn *cp;
873 
874 	/* Templates require cport 0. Ordinary connections require
875 	 * NO_CPORT exactly when cport is 0.
876 	 */
877 	if (flags & IP_VS_CONN_F_TEMPLATE) {
878 		if (param->cport) {
879 			IP_VS_DBG(2, "BACKUP, template with cport dropped\n");
880 			kfree(param->pe_data);
881 			return;
882 		}
883 	} else if (!param->cport && !(flags & IP_VS_CONN_F_NO_CPORT)) {
884 		IP_VS_DBG(2, "BACKUP, conn without cport dropped\n");
885 		kfree(param->pe_data);
886 		return;
887 	} else if (param->cport && (flags & IP_VS_CONN_F_NO_CPORT)) {
888 		IP_VS_DBG(2, "BACKUP, conn with cport and NO_CPORT dropped\n");
889 		kfree(param->pe_data);
890 		return;
891 	}
892 
893 	if (!(flags & IP_VS_CONN_F_TEMPLATE)) {
894 		cp = ip_vs_conn_in_get(param);
895 		if (cp && ((cp->dport != dport) ||
896 			   !ip_vs_addr_equal(cp->daf, &cp->daddr, daddr))) {
897 			if (!(flags & IP_VS_CONN_F_INACTIVE)) {
898 				ip_vs_conn_expire_now(cp);
899 				__ip_vs_conn_put(cp);
900 				cp = NULL;
901 			} else {
902 				/* This is the expiration message for the
903 				 * connection that was already replaced, so we
904 				 * just ignore it.
905 				 */
906 				__ip_vs_conn_put(cp);
907 				kfree(param->pe_data);
908 				return;
909 			}
910 		}
911 	} else {
912 		cp = ip_vs_ct_in_get(param);
913 	}
914 
915 	if (cp) {
916 		/* Free pe_data */
917 		kfree(param->pe_data);
918 
919 		dest = cp->dest;
920 		spin_lock_bh(&cp->lock);
921 		if ((cp->flags ^ flags) & IP_VS_CONN_F_INACTIVE &&
922 		    !(flags & IP_VS_CONN_F_TEMPLATE) && dest) {
923 			if (flags & IP_VS_CONN_F_INACTIVE)
924 				atomic_dec(&dest->activeconns);
925 			else
926 				atomic_inc(&dest->activeconns);
927 		}
928 		flags &= IP_VS_CONN_F_BACKUP_UPD_MASK;
929 		flags |= cp->flags & ~IP_VS_CONN_F_BACKUP_UPD_MASK;
930 		cp->flags = flags;
931 	} else {
932 		/*
933 		 * Find the appropriate destination for the connection.
934 		 * If it is not found the connection will remain unbound
935 		 * but still handled.
936 		 */
937 		rcu_read_lock();
938 		/* This function is only invoked by the synchronization
939 		 * code. We do not currently support heterogeneous pools
940 		 * with synchronization, so we can make the assumption that
941 		 * the svc_af is the same as the dest_af
942 		 */
943 		dest = ip_vs_find_dest(ipvs, type, type, daddr, dport,
944 				       param->vaddr, param->vport, protocol,
945 				       fwmark, flags);
946 
947 		cp = ip_vs_conn_new(param, type, daddr, dport, flags, dest,
948 				    fwmark);
949 		rcu_read_unlock();
950 		if (!cp) {
951 			kfree(param->pe_data);
952 			IP_VS_DBG(2, "BACKUP, add new conn. failed\n");
953 			return;
954 		}
955 		if (!(flags & IP_VS_CONN_F_TEMPLATE))
956 			kfree(param->pe_data);
957 		cp_new = cp;
958 		spin_lock_bh(&cp->lock);
959 	}
960 
961 	if (opt) {
962 		cp->in_seq = opt->in_seq;
963 		cp->out_seq = opt->out_seq;
964 	}
965 	atomic_set(&cp->in_pkts, sysctl_sync_threshold(ipvs));
966 	cp->state = state;
967 	cp->old_state = cp->state;
968 	/*
969 	 * For Ver 0 messages style
970 	 *  - Not possible to recover the right timeout for templates
971 	 *  - can not find the right fwmark
972 	 *    virtual service. If needed, we can do it for
973 	 *    non-fwmark persistent services.
974 	 * Ver 1 messages style.
975 	 *  - No problem.
976 	 */
977 	if (timeout) {
978 		if (timeout > MAX_SCHEDULE_TIMEOUT / HZ)
979 			timeout = MAX_SCHEDULE_TIMEOUT / HZ;
980 		cp->timeout = timeout*HZ;
981 	} else {
982 		struct ip_vs_proto_data *pd;
983 
984 		pd = ip_vs_proto_data_get(ipvs, protocol);
985 		if (!(flags & IP_VS_CONN_F_TEMPLATE) && pd && pd->timeout_table)
986 			cp->timeout = pd->timeout_table[state];
987 		else
988 			cp->timeout = (3*60*HZ);
989 	}
990 	spin_unlock_bh(&cp->lock);
991 	if (!dest && !cp_new)
992 		ip_vs_try_bind_dest(cp);
993 	ip_vs_conn_put(cp);
994 }
995 
996 /* Check for incompatible flags */
997 static bool ip_vs_sync_validate_flags(u32 flags)
998 {
999 	/* We do not expect NO_CPORT, especially to allow lookups
1000 	 * to hit templates
1001 	 */
1002 	if (flags & IP_VS_CONN_F_NO_CPORT) {
1003 		if (flags & IP_VS_CONN_F_TEMPLATE)
1004 			return false;
1005 	}
1006 	if (flags & IP_VS_CONN_F_ONE_PACKET)
1007 		return false;
1008 	return true;
1009 }
1010 
1011 /*
1012  *  Process received multicast message for Version 0
1013  */
1014 static void ip_vs_process_message_v0(struct netns_ipvs *ipvs, const char *buffer,
1015 				     const size_t buflen)
1016 {
1017 	struct ip_vs_sync_mesg_v0 *m = (struct ip_vs_sync_mesg_v0 *)buffer;
1018 	struct ip_vs_sync_conn_v0 *s;
1019 	struct ip_vs_sync_conn_options *opt;
1020 	struct ip_vs_protocol *pp;
1021 	struct ip_vs_conn_param param;
1022 	char *p;
1023 	int i;
1024 
1025 	p = (char *)buffer + sizeof(struct ip_vs_sync_mesg_v0);
1026 	for (i=0; i<m->nr_conns; i++) {
1027 		unsigned int flags, state;
1028 
1029 		if (p + SIMPLE_CONN_SIZE > buffer+buflen) {
1030 			IP_VS_ERR_RL("BACKUP v0, bogus conn\n");
1031 			return;
1032 		}
1033 		s = (struct ip_vs_sync_conn_v0 *) p;
1034 		flags = ntohs(s->flags);
1035 		if (flags & IP_VS_CONN_F_SEQ_MASK) {
1036 			opt = (struct ip_vs_sync_conn_options *)&s[1];
1037 			p += FULL_CONN_SIZE;
1038 			if (p > buffer+buflen) {
1039 				IP_VS_ERR_RL("BACKUP v0, Dropping buffer bogus conn options\n");
1040 				return;
1041 			}
1042 		} else {
1043 			opt = NULL;
1044 			p += SIMPLE_CONN_SIZE;
1045 		}
1046 
1047 		if (!ip_vs_sync_validate_flags(flags)) {
1048 			IP_VS_DBG(2, "BACKUP v0, Invalid flags 0x%X\n", flags);
1049 			continue;
1050 		}
1051 		flags &= IP_VS_CONN_F_BACKUP_MASK;
1052 		flags |= IP_VS_CONN_F_SYNC;
1053 
1054 		state = ntohs(s->state);
1055 		if (!(flags & IP_VS_CONN_F_TEMPLATE)) {
1056 			pp = ip_vs_proto_get(s->protocol);
1057 			if (!pp) {
1058 				IP_VS_DBG(2, "BACKUP v0, Unsupported protocol %u\n",
1059 					s->protocol);
1060 				continue;
1061 			}
1062 			if (state >= pp->num_states) {
1063 				IP_VS_DBG(2, "BACKUP v0, Invalid %s state %u\n",
1064 					pp->name, state);
1065 				continue;
1066 			}
1067 		} else if (state >= IP_VS_CTPL_S_LAST) {
1068 			IP_VS_DBG(7, "BACKUP v0, Invalid tpl state %u\n",
1069 				  state);
1070 			continue;
1071 		}
1072 
1073 		ip_vs_conn_fill_param(ipvs, AF_INET, s->protocol,
1074 				      (const union nf_inet_addr *)&s->caddr,
1075 				      s->cport,
1076 				      (const union nf_inet_addr *)&s->vaddr,
1077 				      s->vport, &param);
1078 
1079 		/* Send timeout as Zero */
1080 		ip_vs_proc_conn(ipvs, &param, flags, state, s->protocol, AF_INET,
1081 				(union nf_inet_addr *)&s->daddr, s->dport,
1082 				0, 0, opt);
1083 	}
1084 }
1085 
1086 /*
1087  * Handle options
1088  */
1089 static inline int ip_vs_proc_seqopt(__u8 *p, unsigned int plen,
1090 				    __u32 *opt_flags,
1091 				    struct ip_vs_sync_conn_options *opt)
1092 {
1093 	struct ip_vs_sync_conn_options *topt;
1094 
1095 	topt = (struct ip_vs_sync_conn_options *)p;
1096 
1097 	if (plen != sizeof(struct ip_vs_sync_conn_options)) {
1098 		IP_VS_DBG(2, "BACKUP, bogus conn options length\n");
1099 		return -EINVAL;
1100 	}
1101 	if (*opt_flags & IPVS_OPT_F_SEQ_DATA) {
1102 		IP_VS_DBG(2, "BACKUP, conn options found twice\n");
1103 		return -EINVAL;
1104 	}
1105 	ntoh_seq(&topt->in_seq, &opt->in_seq);
1106 	ntoh_seq(&topt->out_seq, &opt->out_seq);
1107 	*opt_flags |= IPVS_OPT_F_SEQ_DATA;
1108 	return 0;
1109 }
1110 
1111 static int ip_vs_proc_str(__u8 *p, unsigned int plen, unsigned int *data_len,
1112 			  __u8 **data, unsigned int maxlen,
1113 			  __u32 *opt_flags, __u32 flag)
1114 {
1115 	if (plen > maxlen) {
1116 		IP_VS_DBG(2, "BACKUP, bogus par.data len > %d\n", maxlen);
1117 		return -EINVAL;
1118 	}
1119 	if (*opt_flags & flag) {
1120 		IP_VS_DBG(2, "BACKUP, Par.data found twice 0x%x\n", flag);
1121 		return -EINVAL;
1122 	}
1123 	*data_len = plen;
1124 	*data = p;
1125 	*opt_flags |= flag;
1126 	return 0;
1127 }
1128 /*
1129  *   Process a Version 1 sync. connection
1130  */
1131 static inline int ip_vs_proc_sync_conn(struct netns_ipvs *ipvs, __u8 *p, __u8 *msg_end)
1132 {
1133 	struct ip_vs_sync_conn_options opt;
1134 	union  ip_vs_sync_conn *s;
1135 	struct ip_vs_protocol *pp;
1136 	struct ip_vs_conn_param param;
1137 	__u32 flags;
1138 	unsigned int af, state, pe_data_len=0, pe_name_len=0;
1139 	__u8 *pe_data=NULL, *pe_name=NULL;
1140 	__u32 opt_flags=0;
1141 	int retc=0;
1142 
1143 	s = (union ip_vs_sync_conn *) p;
1144 
1145 	if (s->v6.type & STYPE_F_INET6) {
1146 #ifdef CONFIG_IP_VS_IPV6
1147 		af = AF_INET6;
1148 		p += sizeof(struct ip_vs_sync_v6);
1149 #else
1150 		IP_VS_DBG(3,"BACKUP, IPv6 msg received, and IPVS is not compiled for IPv6\n");
1151 		retc = 10;
1152 		goto out;
1153 #endif
1154 	} else if (!s->v4.type) {
1155 		af = AF_INET;
1156 		p += sizeof(struct ip_vs_sync_v4);
1157 	} else {
1158 		return -10;
1159 	}
1160 	if (p > msg_end)
1161 		return -20;
1162 
1163 	/* Process optional params check Type & Len. */
1164 	while (p < msg_end) {
1165 		int ptype;
1166 		int plen;
1167 
1168 		if (p+2 > msg_end)
1169 			return -30;
1170 		ptype = *(p++);
1171 		plen  = *(p++);
1172 
1173 		if (!plen || ((p + plen) > msg_end))
1174 			return -40;
1175 		/* Handle seq option  p = param data */
1176 		switch (ptype & ~IPVS_OPT_F_PARAM) {
1177 		case IPVS_OPT_SEQ_DATA:
1178 			if (ip_vs_proc_seqopt(p, plen, &opt_flags, &opt))
1179 				return -50;
1180 			break;
1181 
1182 		case IPVS_OPT_PE_DATA:
1183 			if (ip_vs_proc_str(p, plen, &pe_data_len, &pe_data,
1184 					   IP_VS_PEDATA_MAXLEN, &opt_flags,
1185 					   IPVS_OPT_F_PE_DATA))
1186 				return -60;
1187 			break;
1188 
1189 		case IPVS_OPT_PE_NAME:
1190 			if (ip_vs_proc_str(p, plen,&pe_name_len, &pe_name,
1191 					   IP_VS_PENAME_MAXLEN, &opt_flags,
1192 					   IPVS_OPT_F_PE_NAME))
1193 				return -70;
1194 			break;
1195 
1196 		default:
1197 			/* Param data mandatory ? */
1198 			if (!(ptype & IPVS_OPT_F_PARAM)) {
1199 				IP_VS_DBG(3, "BACKUP, Unknown mandatory param %d found\n",
1200 					  ptype & ~IPVS_OPT_F_PARAM);
1201 				retc = 20;
1202 				goto out;
1203 			}
1204 		}
1205 		p += plen;  /* Next option */
1206 	}
1207 
1208 	/* Get flags and Mask off unsupported */
1209 	flags = ntohl(s->v4.flags);
1210 	if (!ip_vs_sync_validate_flags(flags)) {
1211 		IP_VS_DBG(3, "BACKUP, Invalid flags 0x%X\n", flags);
1212 		retc = 25;
1213 		goto out;
1214 	}
1215 	flags &= IP_VS_CONN_F_BACKUP_MASK;
1216 	flags |= IP_VS_CONN_F_SYNC;
1217 	state = ntohs(s->v4.state);
1218 
1219 	if (!(flags & IP_VS_CONN_F_TEMPLATE)) {
1220 		pp = ip_vs_proto_get(s->v4.protocol);
1221 		if (!pp) {
1222 			IP_VS_DBG(3,"BACKUP, Unsupported protocol %u\n",
1223 				s->v4.protocol);
1224 			retc = 30;
1225 			goto out;
1226 		}
1227 		if (state >= pp->num_states) {
1228 			IP_VS_DBG(3, "BACKUP, Invalid %s state %u\n",
1229 				pp->name, state);
1230 			retc = 40;
1231 			goto out;
1232 		}
1233 	} else if (state >= IP_VS_CTPL_S_LAST) {
1234 		IP_VS_DBG(7, "BACKUP, Invalid tpl state %u\n", state);
1235 		retc = 40;
1236 		goto out;
1237 	}
1238 	if (ip_vs_conn_fill_param_sync(ipvs, af, s, &param, pe_data,
1239 				       pe_data_len, pe_name, pe_name_len)) {
1240 		retc = 50;
1241 		goto out;
1242 	}
1243 	/* If only IPv4, just silent skip IPv6 */
1244 	if (af == AF_INET)
1245 		ip_vs_proc_conn(ipvs, &param, flags, state, s->v4.protocol, af,
1246 				(union nf_inet_addr *)&s->v4.daddr, s->v4.dport,
1247 				ntohl(s->v4.timeout), ntohl(s->v4.fwmark),
1248 				(opt_flags & IPVS_OPT_F_SEQ_DATA ? &opt : NULL)
1249 				);
1250 #ifdef CONFIG_IP_VS_IPV6
1251 	else
1252 		ip_vs_proc_conn(ipvs, &param, flags, state, s->v6.protocol, af,
1253 				(union nf_inet_addr *)&s->v6.daddr, s->v6.dport,
1254 				ntohl(s->v6.timeout), ntohl(s->v6.fwmark),
1255 				(opt_flags & IPVS_OPT_F_SEQ_DATA ? &opt : NULL)
1256 				);
1257 #endif
1258 	ip_vs_pe_put(param.pe);
1259 	return 0;
1260 	/* Error exit */
1261 out:
1262 	IP_VS_DBG(2, "BACKUP, Single msg dropped err:%d\n", retc);
1263 	return retc;
1264 
1265 }
1266 /*
1267  *      Process received multicast message and create the corresponding
1268  *      ip_vs_conn entries.
1269  *      Handles Version 0 & 1
1270  */
1271 static void ip_vs_process_message(struct netns_ipvs *ipvs, __u8 *buffer,
1272 				  const size_t buflen)
1273 {
1274 	struct ip_vs_sync_mesg *m2 = (struct ip_vs_sync_mesg *)buffer;
1275 	__u8 *p, *msg_end;
1276 	int i, nr_conns;
1277 
1278 	if (buflen < sizeof(struct ip_vs_sync_mesg_v0)) {
1279 		IP_VS_DBG(2, "BACKUP, message header too short\n");
1280 		return;
1281 	}
1282 
1283 	if (buflen != ntohs(m2->size)) {
1284 		IP_VS_DBG(2, "BACKUP, bogus message size\n");
1285 		return;
1286 	}
1287 	/* SyncID sanity check */
1288 	if (ipvs->bcfg.syncid != 0 && m2->syncid != ipvs->bcfg.syncid) {
1289 		IP_VS_DBG(7, "BACKUP, Ignoring syncid = %d\n", m2->syncid);
1290 		return;
1291 	}
1292 	/* Handle version 1  message */
1293 	if ((m2->version == SYNC_PROTO_VER) && (m2->reserved == 0)
1294 	    && (m2->spare == 0)) {
1295 
1296 		msg_end = buffer + sizeof(struct ip_vs_sync_mesg);
1297 		nr_conns = m2->nr_conns;
1298 
1299 		for (i=0; i<nr_conns; i++) {
1300 			union ip_vs_sync_conn *s;
1301 			unsigned int size;
1302 			int retc;
1303 
1304 			p = msg_end;
1305 			if (p + sizeof(s->v4) > buffer+buflen) {
1306 				IP_VS_ERR_RL("BACKUP, Dropping buffer, too small\n");
1307 				return;
1308 			}
1309 			s = (union ip_vs_sync_conn *)p;
1310 			size = ntohs(s->v4.ver_size) & SVER_MASK;
1311 			msg_end = p + size;
1312 			/* Basic sanity checks */
1313 			if (msg_end  > buffer+buflen) {
1314 				IP_VS_ERR_RL("BACKUP, Dropping buffer, msg > buffer\n");
1315 				return;
1316 			}
1317 			if (ntohs(s->v4.ver_size) >> SVER_SHIFT) {
1318 				IP_VS_ERR_RL("BACKUP, Dropping buffer, Unknown version %d\n",
1319 					      ntohs(s->v4.ver_size) >> SVER_SHIFT);
1320 				return;
1321 			}
1322 			/* Process a single sync_conn */
1323 			retc = ip_vs_proc_sync_conn(ipvs, p, msg_end);
1324 			if (retc < 0) {
1325 				IP_VS_ERR_RL("BACKUP, Dropping buffer, Err: %d in decoding\n",
1326 					     retc);
1327 				return;
1328 			}
1329 			/* Make sure we have 32 bit alignment */
1330 			msg_end = p + ((size + 3) & ~3);
1331 		}
1332 	} else {
1333 		/* Old type of message */
1334 		ip_vs_process_message_v0(ipvs, buffer, buflen);
1335 		return;
1336 	}
1337 }
1338 
1339 
1340 /*
1341  *      Setup sndbuf (mode=1) or rcvbuf (mode=0)
1342  */
1343 static void set_sock_size(struct sock *sk, int mode, int val)
1344 {
1345 	/* setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &val, sizeof(val)); */
1346 	/* setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &val, sizeof(val)); */
1347 	lock_sock(sk);
1348 	if (mode) {
1349 		val = clamp_t(int, val, (SOCK_MIN_SNDBUF + 1) / 2,
1350 			      READ_ONCE(sysctl_wmem_max));
1351 		sk->sk_sndbuf = val * 2;
1352 		sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
1353 	} else {
1354 		val = clamp_t(int, val, (SOCK_MIN_RCVBUF + 1) / 2,
1355 			      READ_ONCE(sysctl_rmem_max));
1356 		sk->sk_rcvbuf = val * 2;
1357 		sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
1358 	}
1359 	release_sock(sk);
1360 }
1361 
1362 /*
1363  *      Setup loopback of outgoing multicasts on a sending socket
1364  */
1365 static void set_mcast_loop(struct sock *sk, u_char loop)
1366 {
1367 	/* setsockopt(sock, SOL_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)); */
1368 	inet_assign_bit(MC_LOOP, sk, loop);
1369 #ifdef CONFIG_IP_VS_IPV6
1370 	if (READ_ONCE(sk->sk_family) == AF_INET6) {
1371 		/* IPV6_MULTICAST_LOOP */
1372 		inet6_assign_bit(MC6_LOOP, sk, loop);
1373 	}
1374 #endif
1375 }
1376 
1377 /*
1378  *      Specify TTL for outgoing multicasts on a sending socket
1379  */
1380 static void set_mcast_ttl(struct sock *sk, u_char ttl)
1381 {
1382 	struct inet_sock *inet = inet_sk(sk);
1383 
1384 	/* setsockopt(sock, SOL_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)); */
1385 	lock_sock(sk);
1386 	WRITE_ONCE(inet->mc_ttl, ttl);
1387 #ifdef CONFIG_IP_VS_IPV6
1388 	if (sk->sk_family == AF_INET6) {
1389 		struct ipv6_pinfo *np = inet6_sk(sk);
1390 
1391 		/* IPV6_MULTICAST_HOPS */
1392 		WRITE_ONCE(np->mcast_hops, ttl);
1393 	}
1394 #endif
1395 	release_sock(sk);
1396 }
1397 
1398 /* Control fragmentation of messages */
1399 static void set_mcast_pmtudisc(struct sock *sk, int val)
1400 {
1401 	struct inet_sock *inet = inet_sk(sk);
1402 
1403 	/* setsockopt(sock, SOL_IP, IP_MTU_DISCOVER, &val, sizeof(val)); */
1404 	lock_sock(sk);
1405 	WRITE_ONCE(inet->pmtudisc, val);
1406 #ifdef CONFIG_IP_VS_IPV6
1407 	if (sk->sk_family == AF_INET6) {
1408 		struct ipv6_pinfo *np = inet6_sk(sk);
1409 
1410 		/* IPV6_MTU_DISCOVER */
1411 		WRITE_ONCE(np->pmtudisc, val);
1412 	}
1413 #endif
1414 	release_sock(sk);
1415 }
1416 
1417 /*
1418  *      Specify default interface for outgoing multicasts
1419  */
1420 static int set_mcast_if(struct sock *sk, struct net_device *dev)
1421 {
1422 	struct inet_sock *inet = inet_sk(sk);
1423 
1424 	if (sk->sk_bound_dev_if && dev->ifindex != sk->sk_bound_dev_if)
1425 		return -EINVAL;
1426 
1427 	lock_sock(sk);
1428 	inet->mc_index = dev->ifindex;
1429 	/*  inet->mc_addr  = 0; */
1430 #ifdef CONFIG_IP_VS_IPV6
1431 	if (sk->sk_family == AF_INET6) {
1432 		struct ipv6_pinfo *np = inet6_sk(sk);
1433 
1434 		/* IPV6_MULTICAST_IF */
1435 		WRITE_ONCE(np->mcast_oif, dev->ifindex);
1436 	}
1437 #endif
1438 	release_sock(sk);
1439 
1440 	return 0;
1441 }
1442 
1443 
1444 /*
1445  *      Join a multicast group.
1446  *      the group is specified by a class D multicast address 224.0.0.0/8
1447  *      in the in_addr structure passed in as a parameter.
1448  */
1449 static int
1450 join_mcast_group(struct sock *sk, struct in_addr *addr, struct net_device *dev)
1451 {
1452 	struct ip_mreqn mreq;
1453 	int ret;
1454 
1455 	memset(&mreq, 0, sizeof(mreq));
1456 	memcpy(&mreq.imr_multiaddr, addr, sizeof(struct in_addr));
1457 
1458 	if (sk->sk_bound_dev_if && dev->ifindex != sk->sk_bound_dev_if)
1459 		return -EINVAL;
1460 
1461 	mreq.imr_ifindex = dev->ifindex;
1462 
1463 	lock_sock(sk);
1464 	ret = ip_mc_join_group(sk, &mreq);
1465 	release_sock(sk);
1466 
1467 	return ret;
1468 }
1469 
1470 #ifdef CONFIG_IP_VS_IPV6
1471 static int join_mcast_group6(struct sock *sk, struct in6_addr *addr,
1472 			     struct net_device *dev)
1473 {
1474 	int ret;
1475 
1476 	if (sk->sk_bound_dev_if && dev->ifindex != sk->sk_bound_dev_if)
1477 		return -EINVAL;
1478 
1479 	lock_sock(sk);
1480 	ret = ipv6_sock_mc_join(sk, dev->ifindex, addr);
1481 	release_sock(sk);
1482 
1483 	return ret;
1484 }
1485 #endif
1486 
1487 static int bind_mcastif_addr(struct socket *sock, struct net_device *dev)
1488 {
1489 	__be32 addr;
1490 	struct sockaddr_in sin;
1491 
1492 	addr = inet_select_addr(dev, 0, RT_SCOPE_UNIVERSE);
1493 	if (!addr)
1494 		pr_err("You probably need to specify IP address on "
1495 		       "multicast interface.\n");
1496 
1497 	IP_VS_DBG(7, "binding socket with (%s) %pI4\n",
1498 		  dev->name, &addr);
1499 
1500 	/* Now bind the socket with the address of multicast interface */
1501 	sin.sin_family	     = AF_INET;
1502 	sin.sin_addr.s_addr  = addr;
1503 	sin.sin_port         = 0;
1504 
1505 	return kernel_bind(sock, (struct sockaddr_unsized *)&sin, sizeof(sin));
1506 }
1507 
1508 static void get_mcast_sockaddr(union ipvs_sockaddr *sa, int *salen,
1509 			       struct ipvs_sync_daemon_cfg *c, int id)
1510 {
1511 	if (AF_INET6 == c->mcast_af) {
1512 		sa->in6 = (struct sockaddr_in6) {
1513 			.sin6_family = AF_INET6,
1514 			.sin6_port = htons(c->mcast_port + id),
1515 		};
1516 		sa->in6.sin6_addr = c->mcast_group.in6;
1517 		*salen = sizeof(sa->in6);
1518 	} else {
1519 		sa->in = (struct sockaddr_in) {
1520 			.sin_family = AF_INET,
1521 			.sin_port = htons(c->mcast_port + id),
1522 		};
1523 		sa->in.sin_addr = c->mcast_group.in;
1524 		*salen = sizeof(sa->in);
1525 	}
1526 }
1527 
1528 /*
1529  *      Set up sending multicast socket over UDP
1530  */
1531 static int make_send_sock(struct netns_ipvs *ipvs, int id,
1532 			  struct net_device *dev, struct socket **sock_ret)
1533 {
1534 	/* multicast addr */
1535 	union ipvs_sockaddr mcast_addr;
1536 	struct socket *sock;
1537 	int result, salen;
1538 
1539 	/* First create a socket */
1540 	result = sock_create_kern(ipvs->net, ipvs->mcfg.mcast_af, SOCK_DGRAM,
1541 				  IPPROTO_UDP, &sock);
1542 	if (result < 0) {
1543 		pr_err("Error during creation of socket; terminating\n");
1544 		goto error;
1545 	}
1546 	*sock_ret = sock;
1547 	result = set_mcast_if(sock->sk, dev);
1548 	if (result < 0) {
1549 		pr_err("Error setting outbound mcast interface\n");
1550 		goto error;
1551 	}
1552 
1553 	set_mcast_loop(sock->sk, 0);
1554 	set_mcast_ttl(sock->sk, ipvs->mcfg.mcast_ttl);
1555 	/* Allow fragmentation if MTU changes */
1556 	set_mcast_pmtudisc(sock->sk, IP_PMTUDISC_DONT);
1557 	result = sysctl_sync_sock_size(ipvs);
1558 	if (result > 0)
1559 		set_sock_size(sock->sk, 1, result);
1560 
1561 	if (AF_INET == ipvs->mcfg.mcast_af)
1562 		result = bind_mcastif_addr(sock, dev);
1563 	else
1564 		result = 0;
1565 	if (result < 0) {
1566 		pr_err("Error binding address of the mcast interface\n");
1567 		goto error;
1568 	}
1569 
1570 	get_mcast_sockaddr(&mcast_addr, &salen, &ipvs->mcfg, id);
1571 	result = kernel_connect(sock, (struct sockaddr_unsized *)&mcast_addr,
1572 				salen, 0);
1573 	if (result < 0) {
1574 		pr_err("Error connecting to the multicast addr\n");
1575 		goto error;
1576 	}
1577 
1578 	return 0;
1579 
1580 error:
1581 	return result;
1582 }
1583 
1584 
1585 /*
1586  *      Set up receiving multicast socket over UDP
1587  */
1588 static int make_receive_sock(struct netns_ipvs *ipvs, int id,
1589 			     struct net_device *dev, struct socket **sock_ret)
1590 {
1591 	/* multicast addr */
1592 	union ipvs_sockaddr mcast_addr;
1593 	struct socket *sock;
1594 	int result, salen;
1595 
1596 	/* First create a socket */
1597 	result = sock_create_kern(ipvs->net, ipvs->bcfg.mcast_af, SOCK_DGRAM,
1598 				  IPPROTO_UDP, &sock);
1599 	if (result < 0) {
1600 		pr_err("Error during creation of socket; terminating\n");
1601 		goto error;
1602 	}
1603 	*sock_ret = sock;
1604 	/* it is equivalent to the REUSEADDR option in user-space */
1605 	sock->sk->sk_reuse = SK_CAN_REUSE;
1606 	result = sysctl_sync_sock_size(ipvs);
1607 	if (result > 0)
1608 		set_sock_size(sock->sk, 0, result);
1609 
1610 	get_mcast_sockaddr(&mcast_addr, &salen, &ipvs->bcfg, id);
1611 	sock->sk->sk_bound_dev_if = dev->ifindex;
1612 	result = kernel_bind(sock, (struct sockaddr_unsized *)&mcast_addr, salen);
1613 	if (result < 0) {
1614 		pr_err("Error binding to the multicast addr\n");
1615 		goto error;
1616 	}
1617 
1618 	/* join the multicast group */
1619 #ifdef CONFIG_IP_VS_IPV6
1620 	if (ipvs->bcfg.mcast_af == AF_INET6)
1621 		result = join_mcast_group6(sock->sk, &mcast_addr.in6.sin6_addr,
1622 					   dev);
1623 	else
1624 #endif
1625 		result = join_mcast_group(sock->sk, &mcast_addr.in.sin_addr,
1626 					  dev);
1627 	if (result < 0) {
1628 		pr_err("Error joining to the multicast group\n");
1629 		goto error;
1630 	}
1631 
1632 	return 0;
1633 
1634 error:
1635 	return result;
1636 }
1637 
1638 
1639 static int
1640 ip_vs_send_async(struct socket *sock, const char *buffer, const size_t length)
1641 {
1642 	struct msghdr	msg = {.msg_flags = MSG_DONTWAIT|MSG_NOSIGNAL};
1643 	struct kvec	iov;
1644 	int		len;
1645 
1646 	iov.iov_base     = (void *)buffer;
1647 	iov.iov_len      = length;
1648 
1649 	len = kernel_sendmsg(sock, &msg, &iov, 1, (size_t)(length));
1650 
1651 	return len;
1652 }
1653 
1654 static int
1655 ip_vs_send_sync_msg(struct socket *sock, struct ip_vs_sync_mesg *msg)
1656 {
1657 	int msize;
1658 	int ret;
1659 
1660 	msize = ntohs(msg->size);
1661 
1662 	ret = ip_vs_send_async(sock, (char *)msg, msize);
1663 	if (ret >= 0 || ret == -EAGAIN)
1664 		return ret;
1665 	pr_err("ip_vs_send_async error %d\n", ret);
1666 	return 0;
1667 }
1668 
1669 static int
1670 ip_vs_receive(struct socket *sock, char *buffer, const size_t buflen)
1671 {
1672 	struct msghdr		msg = {NULL,};
1673 	struct kvec		iov = {buffer, buflen};
1674 	int			len;
1675 
1676 	/* Receive a packet */
1677 	iov_iter_kvec(&msg.msg_iter, ITER_DEST, &iov, 1, buflen);
1678 	len = sock_recvmsg(sock, &msg, MSG_DONTWAIT);
1679 	if (len < 0)
1680 		return len;
1681 
1682 	return len;
1683 }
1684 
1685 /* Wakeup the master thread for sending */
1686 static void master_wakeup_work_handler(struct work_struct *work)
1687 {
1688 	struct ipvs_master_sync_state *ms =
1689 		container_of(work, struct ipvs_master_sync_state,
1690 			     master_wakeup_work.work);
1691 	struct netns_ipvs *ipvs = ms->ipvs;
1692 
1693 	spin_lock_bh(&ipvs->sync_lock);
1694 	if (ms->sync_queue_len &&
1695 	    ms->sync_queue_delay < IPVS_SYNC_WAKEUP_RATE) {
1696 		int id = (int)(ms - ipvs->ms);
1697 
1698 		ms->sync_queue_delay = IPVS_SYNC_WAKEUP_RATE;
1699 		wake_up_process(ipvs->master_tinfo[id].task);
1700 	}
1701 	spin_unlock_bh(&ipvs->sync_lock);
1702 }
1703 
1704 /* Get next buffer to send */
1705 static inline struct ip_vs_sync_buff *
1706 next_sync_buff(struct netns_ipvs *ipvs, struct ipvs_master_sync_state *ms)
1707 {
1708 	struct ip_vs_sync_buff *sb;
1709 
1710 	sb = sb_dequeue(ipvs, ms);
1711 	if (sb)
1712 		return sb;
1713 	/* Do not delay entries in buffer for more than 2 seconds */
1714 	return get_curr_sync_buff(ipvs, ms, IPVS_SYNC_FLUSH_TIME);
1715 }
1716 
1717 static int sync_thread_master(void *data)
1718 {
1719 	struct ip_vs_sync_thread_data *tinfo = data;
1720 	struct netns_ipvs *ipvs = tinfo->ipvs;
1721 	struct ipvs_master_sync_state *ms = &ipvs->ms[tinfo->id];
1722 	struct sock *sk = tinfo->sock->sk;
1723 	struct ip_vs_sync_buff *sb;
1724 
1725 	pr_info("sync thread started: state = MASTER, mcast_ifn = %s, "
1726 		"syncid = %d, id = %d\n",
1727 		ipvs->mcfg.mcast_ifn, ipvs->mcfg.syncid, tinfo->id);
1728 
1729 	for (;;) {
1730 		sb = next_sync_buff(ipvs, ms);
1731 		if (unlikely(kthread_should_stop()))
1732 			break;
1733 		if (!sb) {
1734 			schedule_timeout(IPVS_SYNC_CHECK_PERIOD);
1735 			continue;
1736 		}
1737 		while (ip_vs_send_sync_msg(tinfo->sock, sb->mesg) < 0) {
1738 			/* (Ab)use interruptible sleep to avoid increasing
1739 			 * the load avg.
1740 			 */
1741 			__wait_event_interruptible(*sk_sleep(sk),
1742 						   sock_writeable(sk) ||
1743 						   kthread_should_stop());
1744 			if (unlikely(kthread_should_stop()))
1745 				goto done;
1746 		}
1747 		ip_vs_sync_buff_release(sb);
1748 	}
1749 
1750 done:
1751 	__set_current_state(TASK_RUNNING);
1752 	if (sb)
1753 		ip_vs_sync_buff_release(sb);
1754 
1755 	/* clean up the sync_buff queue */
1756 	while ((sb = sb_dequeue(ipvs, ms)))
1757 		ip_vs_sync_buff_release(sb);
1758 	__set_current_state(TASK_RUNNING);
1759 
1760 	/* clean up the current sync_buff */
1761 	sb = get_curr_sync_buff(ipvs, ms, 0);
1762 	if (sb)
1763 		ip_vs_sync_buff_release(sb);
1764 
1765 	return 0;
1766 }
1767 
1768 
1769 static int sync_thread_backup(void *data)
1770 {
1771 	struct ip_vs_sync_thread_data *tinfo = data;
1772 	struct netns_ipvs *ipvs = tinfo->ipvs;
1773 	struct sock *sk = tinfo->sock->sk;
1774 	struct udp_sock *up = udp_sk(sk);
1775 	int len;
1776 
1777 	pr_info("sync thread started: state = BACKUP, mcast_ifn = %s, "
1778 		"syncid = %d, id = %d\n",
1779 		ipvs->bcfg.mcast_ifn, ipvs->bcfg.syncid, tinfo->id);
1780 
1781 	while (!kthread_should_stop()) {
1782 		wait_event_interruptible(*sk_sleep(sk),
1783 					 !skb_queue_empty_lockless(&sk->sk_receive_queue) ||
1784 					 !skb_queue_empty_lockless(&up->reader_queue) ||
1785 					 kthread_should_stop());
1786 
1787 		/* do we have data now? */
1788 		while (!skb_queue_empty_lockless(&sk->sk_receive_queue) ||
1789 		       !skb_queue_empty_lockless(&up->reader_queue)) {
1790 			len = ip_vs_receive(tinfo->sock, tinfo->buf,
1791 					ipvs->bcfg.sync_maxlen);
1792 			if (len <= 0) {
1793 				if (len != -EAGAIN)
1794 					pr_err("receiving message error\n");
1795 				break;
1796 			}
1797 
1798 			ip_vs_process_message(ipvs, tinfo->buf, len);
1799 		}
1800 	}
1801 
1802 	return 0;
1803 }
1804 
1805 
1806 int start_sync_thread(struct netns_ipvs *ipvs, struct ipvs_sync_daemon_cfg *c,
1807 		      int state)
1808 {
1809 	struct ip_vs_sync_thread_data *ti = NULL, *tinfo;
1810 	struct task_struct *task;
1811 	struct net_device *dev;
1812 	char *name;
1813 	int (*threadfn)(void *data);
1814 	int id = 0, count, hlen;
1815 	int result = -ENOMEM;
1816 	u16 mtu, min_mtu;
1817 
1818 	IP_VS_DBG(7, "%s(): pid %d\n", __func__, task_pid_nr(current));
1819 	IP_VS_DBG(7, "Each ip_vs_sync_conn entry needs %zd bytes\n",
1820 		  sizeof(struct ip_vs_sync_conn_v0));
1821 
1822 	/* increase the module use count */
1823 	if (!ip_vs_use_count_inc())
1824 		return -ENOPROTOOPT;
1825 
1826 	/* Backup server can be started without services just to sync conns,
1827 	 * make sure conn_tab is created even if ipvs->enable is 0.
1828 	 */
1829 	if (state == IP_VS_STATE_BACKUP) {
1830 		mutex_lock(&ipvs->service_mutex);
1831 		if (!rcu_dereference_protected(ipvs->conn_tab, 1)) {
1832 			int lfactor = sysctl_conn_lfactor(ipvs);
1833 			int new_size = ip_vs_conn_desired_size(ipvs, NULL,
1834 							       lfactor);
1835 			struct ip_vs_rht *tc_new;
1836 
1837 			tc_new = ip_vs_conn_tab_alloc(ipvs, new_size, lfactor);
1838 			if (!tc_new) {
1839 				mutex_unlock(&ipvs->service_mutex);
1840 				result = -ENOMEM;
1841 				goto out_module;
1842 			}
1843 			rcu_assign_pointer(ipvs->conn_tab, tc_new);
1844 		}
1845 		mutex_unlock(&ipvs->service_mutex);
1846 	}
1847 
1848 	/* Do not hold one mutex and then to block on another */
1849 	for (;;) {
1850 		rtnl_lock();
1851 		if (mutex_trylock(&ipvs->sync_mutex))
1852 			break;
1853 		rtnl_unlock();
1854 		mutex_lock(&ipvs->sync_mutex);
1855 		if (rtnl_trylock())
1856 			break;
1857 		mutex_unlock(&ipvs->sync_mutex);
1858 	}
1859 
1860 	if (!ipvs->sync_state) {
1861 		count = clamp(sysctl_sync_ports(ipvs), 1, IPVS_SYNC_PORTS_MAX);
1862 		ipvs->threads_mask = count - 1;
1863 	} else
1864 		count = ipvs->threads_mask + 1;
1865 
1866 	if (c->mcast_af == AF_UNSPEC) {
1867 		c->mcast_af = AF_INET;
1868 		c->mcast_group.ip = cpu_to_be32(IP_VS_SYNC_GROUP);
1869 	}
1870 	if (!c->mcast_port)
1871 		c->mcast_port = IP_VS_SYNC_PORT;
1872 	if (!c->mcast_ttl)
1873 		c->mcast_ttl = 1;
1874 
1875 	dev = __dev_get_by_name(ipvs->net, c->mcast_ifn);
1876 	if (!dev) {
1877 		pr_err("Unknown mcast interface: %s\n", c->mcast_ifn);
1878 		result = -ENODEV;
1879 		goto out_early;
1880 	}
1881 	hlen = (AF_INET6 == c->mcast_af) ?
1882 	       sizeof(struct ipv6hdr) + sizeof(struct udphdr) :
1883 	       sizeof(struct iphdr) + sizeof(struct udphdr);
1884 	mtu = (state == IP_VS_STATE_BACKUP) ?
1885 		  clamp(dev->mtu, 1500U, 65535U) : 1500U;
1886 	min_mtu = (state == IP_VS_STATE_BACKUP) ? 1024 : 1;
1887 
1888 	if (c->sync_maxlen)
1889 		c->sync_maxlen = clamp_t(unsigned int,
1890 					 c->sync_maxlen, min_mtu,
1891 					 65535 - hlen);
1892 	else
1893 		c->sync_maxlen = mtu - hlen;
1894 
1895 	if (state == IP_VS_STATE_MASTER) {
1896 		result = -EEXIST;
1897 		if (ipvs->ms)
1898 			goto out_early;
1899 
1900 		ipvs->mcfg = *c;
1901 		name = "ipvs-m:%d:%d";
1902 		threadfn = sync_thread_master;
1903 	} else if (state == IP_VS_STATE_BACKUP) {
1904 		result = -EEXIST;
1905 		if (ipvs->backup_tinfo)
1906 			goto out_early;
1907 
1908 		ipvs->bcfg = *c;
1909 		name = "ipvs-b:%d:%d";
1910 		threadfn = sync_thread_backup;
1911 	} else {
1912 		result = -EINVAL;
1913 		goto out_early;
1914 	}
1915 
1916 	if (state == IP_VS_STATE_MASTER) {
1917 		struct ipvs_master_sync_state *ms;
1918 
1919 		result = -ENOMEM;
1920 		ipvs->ms = kzalloc_objs(ipvs->ms[0], count);
1921 		if (!ipvs->ms)
1922 			goto out;
1923 		ms = ipvs->ms;
1924 		for (id = 0; id < count; id++, ms++) {
1925 			INIT_LIST_HEAD(&ms->sync_queue);
1926 			ms->sync_queue_len = 0;
1927 			ms->sync_queue_delay = 0;
1928 			INIT_DELAYED_WORK(&ms->master_wakeup_work,
1929 					  master_wakeup_work_handler);
1930 			ms->ipvs = ipvs;
1931 		}
1932 	}
1933 	result = -ENOMEM;
1934 	ti = kzalloc_objs(struct ip_vs_sync_thread_data, count);
1935 	if (!ti)
1936 		goto out;
1937 
1938 	for (id = 0; id < count; id++) {
1939 		tinfo = &ti[id];
1940 		tinfo->ipvs = ipvs;
1941 		if (state == IP_VS_STATE_BACKUP) {
1942 			result = -ENOMEM;
1943 			tinfo->buf = kmalloc(ipvs->bcfg.sync_maxlen,
1944 					     GFP_KERNEL);
1945 			if (!tinfo->buf)
1946 				goto out;
1947 		}
1948 		tinfo->id = id;
1949 		if (state == IP_VS_STATE_MASTER)
1950 			result = make_send_sock(ipvs, id, dev, &tinfo->sock);
1951 		else
1952 			result = make_receive_sock(ipvs, id, dev, &tinfo->sock);
1953 		if (result < 0)
1954 			goto out;
1955 
1956 		task = kthread_run(threadfn, tinfo, name, ipvs->gen, id);
1957 		if (IS_ERR(task)) {
1958 			result = PTR_ERR(task);
1959 			goto out;
1960 		}
1961 		tinfo->task = task;
1962 	}
1963 
1964 	/* mark as active */
1965 
1966 	if (state == IP_VS_STATE_MASTER)
1967 		ipvs->master_tinfo = ti;
1968 	else
1969 		ipvs->backup_tinfo = ti;
1970 	spin_lock_bh(&ipvs->sync_buff_lock);
1971 	ipvs->sync_state |= state;
1972 	spin_unlock_bh(&ipvs->sync_buff_lock);
1973 
1974 	mutex_unlock(&ipvs->sync_mutex);
1975 	rtnl_unlock();
1976 
1977 	return 0;
1978 
1979 out:
1980 	/* We do not need RTNL lock anymore, release it here so that
1981 	 * sock_release below can use rtnl_lock to leave the mcast group.
1982 	 */
1983 	rtnl_unlock();
1984 	id = min(id, count - 1);
1985 	if (ti) {
1986 		for (tinfo = ti + id; tinfo >= ti; tinfo--) {
1987 			if (tinfo->task)
1988 				kthread_stop(tinfo->task);
1989 		}
1990 	}
1991 	if (!(ipvs->sync_state & IP_VS_STATE_MASTER)) {
1992 		kfree(ipvs->ms);
1993 		ipvs->ms = NULL;
1994 	}
1995 	mutex_unlock(&ipvs->sync_mutex);
1996 
1997 	/* No more mutexes, release socks */
1998 	if (ti) {
1999 		for (tinfo = ti + id; tinfo >= ti; tinfo--) {
2000 			if (tinfo->sock)
2001 				sock_release(tinfo->sock);
2002 			kfree(tinfo->buf);
2003 		}
2004 		kfree(ti);
2005 	}
2006 
2007 	/* decrease the module use count */
2008 	ip_vs_use_count_dec();
2009 	return result;
2010 
2011 out_early:
2012 	mutex_unlock(&ipvs->sync_mutex);
2013 	rtnl_unlock();
2014 
2015 out_module:
2016 	/* decrease the module use count */
2017 	ip_vs_use_count_dec();
2018 	return result;
2019 }
2020 
2021 
2022 int stop_sync_thread(struct netns_ipvs *ipvs, int state)
2023 {
2024 	struct ip_vs_sync_thread_data *ti, *tinfo;
2025 	int id;
2026 	int retc = -EINVAL;
2027 
2028 	IP_VS_DBG(7, "%s(): pid %d\n", __func__, task_pid_nr(current));
2029 
2030 	mutex_lock(&ipvs->sync_mutex);
2031 	if (state == IP_VS_STATE_MASTER) {
2032 		retc = -ESRCH;
2033 		if (!ipvs->ms)
2034 			goto err;
2035 		ti = ipvs->master_tinfo;
2036 
2037 		/*
2038 		 * The lock synchronizes with sb_queue_tail(), so that we don't
2039 		 * add sync buffers to the queue, when we are already in
2040 		 * progress of stopping the master sync daemon.
2041 		 */
2042 
2043 		spin_lock_bh(&ipvs->sync_buff_lock);
2044 		spin_lock(&ipvs->sync_lock);
2045 		ipvs->sync_state &= ~IP_VS_STATE_MASTER;
2046 		spin_unlock(&ipvs->sync_lock);
2047 		spin_unlock_bh(&ipvs->sync_buff_lock);
2048 
2049 		retc = 0;
2050 		for (id = ipvs->threads_mask; id >= 0; id--) {
2051 			struct ipvs_master_sync_state *ms = &ipvs->ms[id];
2052 			int ret;
2053 
2054 			tinfo = &ti[id];
2055 			pr_info("stopping master sync thread %d ...\n",
2056 				task_pid_nr(tinfo->task));
2057 			cancel_delayed_work_sync(&ms->master_wakeup_work);
2058 			ret = kthread_stop(tinfo->task);
2059 			if (retc >= 0)
2060 				retc = ret;
2061 		}
2062 		kfree(ipvs->ms);
2063 		ipvs->ms = NULL;
2064 		ipvs->master_tinfo = NULL;
2065 	} else if (state == IP_VS_STATE_BACKUP) {
2066 		retc = -ESRCH;
2067 		if (!ipvs->backup_tinfo)
2068 			goto err;
2069 		ti = ipvs->backup_tinfo;
2070 
2071 		ipvs->sync_state &= ~IP_VS_STATE_BACKUP;
2072 		retc = 0;
2073 		for (id = ipvs->threads_mask; id >= 0; id--) {
2074 			int ret;
2075 
2076 			tinfo = &ti[id];
2077 			pr_info("stopping backup sync thread %d ...\n",
2078 				task_pid_nr(tinfo->task));
2079 			ret = kthread_stop(tinfo->task);
2080 			if (retc >= 0)
2081 				retc = ret;
2082 		}
2083 		ipvs->backup_tinfo = NULL;
2084 	} else {
2085 		goto err;
2086 	}
2087 	id = ipvs->threads_mask;
2088 	mutex_unlock(&ipvs->sync_mutex);
2089 
2090 	/* No more mutexes, release socks */
2091 	for (tinfo = ti + id; tinfo >= ti; tinfo--) {
2092 		if (tinfo->sock)
2093 			sock_release(tinfo->sock);
2094 		kfree(tinfo->buf);
2095 	}
2096 	kfree(ti);
2097 
2098 	/* decrease the module use count */
2099 	ip_vs_use_count_dec();
2100 	return retc;
2101 
2102 err:
2103 	mutex_unlock(&ipvs->sync_mutex);
2104 	return retc;
2105 }
2106 
2107 /*
2108  * Initialize data struct for each netns
2109  */
2110 int __net_init ip_vs_sync_net_init(struct netns_ipvs *ipvs)
2111 {
2112 	__mutex_init(&ipvs->sync_mutex, "ipvs->sync_mutex", &__ipvs_sync_key);
2113 	spin_lock_init(&ipvs->sync_lock);
2114 	spin_lock_init(&ipvs->sync_buff_lock);
2115 	return 0;
2116 }
2117 
2118 void ip_vs_sync_net_cleanup(struct netns_ipvs *ipvs)
2119 {
2120 	int retc;
2121 
2122 	retc = stop_sync_thread(ipvs, IP_VS_STATE_MASTER);
2123 	if (retc && retc != -ESRCH)
2124 		pr_err("Failed to stop Master Daemon\n");
2125 
2126 	retc = stop_sync_thread(ipvs, IP_VS_STATE_BACKUP);
2127 	if (retc && retc != -ESRCH)
2128 		pr_err("Failed to stop Backup Daemon\n");
2129 }
2130