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