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