netfilter: ipt_CLUSTERIP: fix sleep-in-atomic bug in clusterip_config_entry_put()
[platform/kernel/linux-starfive.git] / net / ipv4 / netfilter / ipt_CLUSTERIP.c
1 /* Cluster IP hashmark target
2  * (C) 2003-2004 by Harald Welte <laforge@netfilter.org>
3  * based on ideas of Fabio Olive Leite <olive@unixforge.org>
4  *
5  * Development of this code funded by SuSE Linux AG, http://www.suse.com/
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  *
11  */
12 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
13 #include <linux/module.h>
14 #include <linux/proc_fs.h>
15 #include <linux/jhash.h>
16 #include <linux/bitops.h>
17 #include <linux/skbuff.h>
18 #include <linux/slab.h>
19 #include <linux/ip.h>
20 #include <linux/tcp.h>
21 #include <linux/udp.h>
22 #include <linux/icmp.h>
23 #include <linux/if_arp.h>
24 #include <linux/seq_file.h>
25 #include <linux/refcount.h>
26 #include <linux/netfilter_arp.h>
27 #include <linux/netfilter/x_tables.h>
28 #include <linux/netfilter_ipv4/ip_tables.h>
29 #include <linux/netfilter_ipv4/ipt_CLUSTERIP.h>
30 #include <net/netfilter/nf_conntrack.h>
31 #include <net/net_namespace.h>
32 #include <net/netns/generic.h>
33 #include <net/checksum.h>
34 #include <net/ip.h>
35
36 #define CLUSTERIP_VERSION "0.8"
37
38 MODULE_LICENSE("GPL");
39 MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
40 MODULE_DESCRIPTION("Xtables: CLUSTERIP target");
41
42 struct clusterip_config {
43         struct list_head list;                  /* list of all configs */
44         refcount_t refcount;                    /* reference count */
45         refcount_t entries;                     /* number of entries/rules
46                                                  * referencing us */
47
48         __be32 clusterip;                       /* the IP address */
49         u_int8_t clustermac[ETH_ALEN];          /* the MAC address */
50         int ifindex;                            /* device ifindex */
51         u_int16_t num_total_nodes;              /* total number of nodes */
52         unsigned long local_nodes;              /* node number array */
53
54 #ifdef CONFIG_PROC_FS
55         struct proc_dir_entry *pde;             /* proc dir entry */
56 #endif
57         enum clusterip_hashmode hash_mode;      /* which hashing mode */
58         u_int32_t hash_initval;                 /* hash initialization */
59         struct rcu_head rcu;                    /* for call_rcu_bh */
60         struct net *net;                        /* netns for pernet list */
61         char ifname[IFNAMSIZ];                  /* device ifname */
62 };
63
64 #ifdef CONFIG_PROC_FS
65 static const struct file_operations clusterip_proc_fops;
66 #endif
67
68 struct clusterip_net {
69         struct list_head configs;
70         /* lock protects the configs list */
71         spinlock_t lock;
72
73 #ifdef CONFIG_PROC_FS
74         struct proc_dir_entry *procdir;
75         /* mutex protects the config->pde*/
76         struct mutex mutex;
77 #endif
78 };
79
80 static unsigned int clusterip_net_id __read_mostly;
81 static inline struct clusterip_net *clusterip_pernet(struct net *net)
82 {
83         return net_generic(net, clusterip_net_id);
84 }
85
86 static inline void
87 clusterip_config_get(struct clusterip_config *c)
88 {
89         refcount_inc(&c->refcount);
90 }
91
92 static void clusterip_config_rcu_free(struct rcu_head *head)
93 {
94         struct clusterip_config *config;
95         struct net_device *dev;
96
97         config = container_of(head, struct clusterip_config, rcu);
98         dev = dev_get_by_name(config->net, config->ifname);
99         if (dev) {
100                 dev_mc_del(dev, config->clustermac);
101                 dev_put(dev);
102         }
103         kfree(config);
104 }
105
106 static inline void
107 clusterip_config_put(struct clusterip_config *c)
108 {
109         if (refcount_dec_and_test(&c->refcount))
110                 call_rcu(&c->rcu, clusterip_config_rcu_free);
111 }
112
113 /* decrease the count of entries using/referencing this config.  If last
114  * entry(rule) is removed, remove the config from lists, but don't free it
115  * yet, since proc-files could still be holding references */
116 static inline void
117 clusterip_config_entry_put(struct clusterip_config *c)
118 {
119         struct clusterip_net *cn = clusterip_pernet(c->net);
120
121         local_bh_disable();
122         if (refcount_dec_and_lock(&c->entries, &cn->lock)) {
123                 list_del_rcu(&c->list);
124                 spin_unlock(&cn->lock);
125                 local_bh_enable();
126                 /* In case anyone still accesses the file, the open/close
127                  * functions are also incrementing the refcount on their own,
128                  * so it's safe to remove the entry even if it's in use. */
129 #ifdef CONFIG_PROC_FS
130                 mutex_lock(&cn->mutex);
131                 if (cn->procdir)
132                         proc_remove(c->pde);
133                 mutex_unlock(&cn->mutex);
134 #endif
135                 return;
136         }
137         local_bh_enable();
138 }
139
140 static struct clusterip_config *
141 __clusterip_config_find(struct net *net, __be32 clusterip)
142 {
143         struct clusterip_config *c;
144         struct clusterip_net *cn = clusterip_pernet(net);
145
146         list_for_each_entry_rcu(c, &cn->configs, list) {
147                 if (c->clusterip == clusterip)
148                         return c;
149         }
150
151         return NULL;
152 }
153
154 static inline struct clusterip_config *
155 clusterip_config_find_get(struct net *net, __be32 clusterip, int entry)
156 {
157         struct clusterip_config *c;
158
159         rcu_read_lock_bh();
160         c = __clusterip_config_find(net, clusterip);
161         if (c) {
162 #ifdef CONFIG_PROC_FS
163                 if (!c->pde)
164                         c = NULL;
165                 else
166 #endif
167                 if (unlikely(!refcount_inc_not_zero(&c->refcount)))
168                         c = NULL;
169                 else if (entry) {
170                         if (unlikely(!refcount_inc_not_zero(&c->entries))) {
171                                 clusterip_config_put(c);
172                                 c = NULL;
173                         }
174                 }
175         }
176         rcu_read_unlock_bh();
177
178         return c;
179 }
180
181 static void
182 clusterip_config_init_nodelist(struct clusterip_config *c,
183                                const struct ipt_clusterip_tgt_info *i)
184 {
185         int n;
186
187         for (n = 0; n < i->num_local_nodes; n++)
188                 set_bit(i->local_nodes[n] - 1, &c->local_nodes);
189 }
190
191 static int
192 clusterip_netdev_event(struct notifier_block *this, unsigned long event,
193                        void *ptr)
194 {
195         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
196         struct net *net = dev_net(dev);
197         struct clusterip_net *cn = clusterip_pernet(net);
198         struct clusterip_config *c;
199
200         spin_lock_bh(&cn->lock);
201         list_for_each_entry_rcu(c, &cn->configs, list) {
202                 switch (event) {
203                 case NETDEV_REGISTER:
204                         if (!strcmp(dev->name, c->ifname)) {
205                                 c->ifindex = dev->ifindex;
206                                 dev_mc_add(dev, c->clustermac);
207                         }
208                         break;
209                 case NETDEV_UNREGISTER:
210                         if (dev->ifindex == c->ifindex) {
211                                 dev_mc_del(dev, c->clustermac);
212                                 c->ifindex = -1;
213                         }
214                         break;
215                 case NETDEV_CHANGENAME:
216                         if (!strcmp(dev->name, c->ifname)) {
217                                 c->ifindex = dev->ifindex;
218                                 dev_mc_add(dev, c->clustermac);
219                         } else if (dev->ifindex == c->ifindex) {
220                                 dev_mc_del(dev, c->clustermac);
221                                 c->ifindex = -1;
222                         }
223                         break;
224                 }
225         }
226         spin_unlock_bh(&cn->lock);
227
228         return NOTIFY_DONE;
229 }
230
231 static struct clusterip_config *
232 clusterip_config_init(struct net *net, const struct ipt_clusterip_tgt_info *i,
233                       __be32 ip, const char *iniface)
234 {
235         struct clusterip_net *cn = clusterip_pernet(net);
236         struct clusterip_config *c;
237         struct net_device *dev;
238         int err;
239
240         if (iniface[0] == '\0') {
241                 pr_info("Please specify an interface name\n");
242                 return ERR_PTR(-EINVAL);
243         }
244
245         c = kzalloc(sizeof(*c), GFP_ATOMIC);
246         if (!c)
247                 return ERR_PTR(-ENOMEM);
248
249         dev = dev_get_by_name(net, iniface);
250         if (!dev) {
251                 pr_info("no such interface %s\n", iniface);
252                 kfree(c);
253                 return ERR_PTR(-ENOENT);
254         }
255         c->ifindex = dev->ifindex;
256         strcpy(c->ifname, dev->name);
257         memcpy(&c->clustermac, &i->clustermac, ETH_ALEN);
258         dev_mc_add(dev, c->clustermac);
259         dev_put(dev);
260
261         c->clusterip = ip;
262         c->num_total_nodes = i->num_total_nodes;
263         clusterip_config_init_nodelist(c, i);
264         c->hash_mode = i->hash_mode;
265         c->hash_initval = i->hash_initval;
266         c->net = net;
267         refcount_set(&c->refcount, 1);
268
269         spin_lock_bh(&cn->lock);
270         if (__clusterip_config_find(net, ip)) {
271                 err = -EBUSY;
272                 goto out_config_put;
273         }
274
275         list_add_rcu(&c->list, &cn->configs);
276         spin_unlock_bh(&cn->lock);
277
278 #ifdef CONFIG_PROC_FS
279         {
280                 char buffer[16];
281
282                 /* create proc dir entry */
283                 sprintf(buffer, "%pI4", &ip);
284                 mutex_lock(&cn->mutex);
285                 c->pde = proc_create_data(buffer, 0600,
286                                           cn->procdir,
287                                           &clusterip_proc_fops, c);
288                 mutex_unlock(&cn->mutex);
289                 if (!c->pde) {
290                         err = -ENOMEM;
291                         goto err;
292                 }
293         }
294 #endif
295
296         refcount_set(&c->entries, 1);
297         return c;
298
299 #ifdef CONFIG_PROC_FS
300 err:
301 #endif
302         spin_lock_bh(&cn->lock);
303         list_del_rcu(&c->list);
304 out_config_put:
305         spin_unlock_bh(&cn->lock);
306         clusterip_config_put(c);
307         return ERR_PTR(err);
308 }
309
310 #ifdef CONFIG_PROC_FS
311 static int
312 clusterip_add_node(struct clusterip_config *c, u_int16_t nodenum)
313 {
314
315         if (nodenum == 0 ||
316             nodenum > c->num_total_nodes)
317                 return 1;
318
319         /* check if we already have this number in our bitfield */
320         if (test_and_set_bit(nodenum - 1, &c->local_nodes))
321                 return 1;
322
323         return 0;
324 }
325
326 static bool
327 clusterip_del_node(struct clusterip_config *c, u_int16_t nodenum)
328 {
329         if (nodenum == 0 ||
330             nodenum > c->num_total_nodes)
331                 return true;
332
333         if (test_and_clear_bit(nodenum - 1, &c->local_nodes))
334                 return false;
335
336         return true;
337 }
338 #endif
339
340 static inline u_int32_t
341 clusterip_hashfn(const struct sk_buff *skb,
342                  const struct clusterip_config *config)
343 {
344         const struct iphdr *iph = ip_hdr(skb);
345         unsigned long hashval;
346         u_int16_t sport = 0, dport = 0;
347         int poff;
348
349         poff = proto_ports_offset(iph->protocol);
350         if (poff >= 0) {
351                 const u_int16_t *ports;
352                 u16 _ports[2];
353
354                 ports = skb_header_pointer(skb, iph->ihl * 4 + poff, 4, _ports);
355                 if (ports) {
356                         sport = ports[0];
357                         dport = ports[1];
358                 }
359         } else {
360                 net_info_ratelimited("unknown protocol %u\n", iph->protocol);
361         }
362
363         switch (config->hash_mode) {
364         case CLUSTERIP_HASHMODE_SIP:
365                 hashval = jhash_1word(ntohl(iph->saddr),
366                                       config->hash_initval);
367                 break;
368         case CLUSTERIP_HASHMODE_SIP_SPT:
369                 hashval = jhash_2words(ntohl(iph->saddr), sport,
370                                        config->hash_initval);
371                 break;
372         case CLUSTERIP_HASHMODE_SIP_SPT_DPT:
373                 hashval = jhash_3words(ntohl(iph->saddr), sport, dport,
374                                        config->hash_initval);
375                 break;
376         default:
377                 /* to make gcc happy */
378                 hashval = 0;
379                 /* This cannot happen, unless the check function wasn't called
380                  * at rule load time */
381                 pr_info("unknown mode %u\n", config->hash_mode);
382                 BUG();
383                 break;
384         }
385
386         /* node numbers are 1..n, not 0..n */
387         return reciprocal_scale(hashval, config->num_total_nodes) + 1;
388 }
389
390 static inline int
391 clusterip_responsible(const struct clusterip_config *config, u_int32_t hash)
392 {
393         return test_bit(hash - 1, &config->local_nodes);
394 }
395
396 /***********************************************************************
397  * IPTABLES TARGET
398  ***********************************************************************/
399
400 static unsigned int
401 clusterip_tg(struct sk_buff *skb, const struct xt_action_param *par)
402 {
403         const struct ipt_clusterip_tgt_info *cipinfo = par->targinfo;
404         struct nf_conn *ct;
405         enum ip_conntrack_info ctinfo;
406         u_int32_t hash;
407
408         /* don't need to clusterip_config_get() here, since refcount
409          * is only decremented by destroy() - and ip_tables guarantees
410          * that the ->target() function isn't called after ->destroy() */
411
412         ct = nf_ct_get(skb, &ctinfo);
413         if (ct == NULL)
414                 return NF_DROP;
415
416         /* special case: ICMP error handling. conntrack distinguishes between
417          * error messages (RELATED) and information requests (see below) */
418         if (ip_hdr(skb)->protocol == IPPROTO_ICMP &&
419             (ctinfo == IP_CT_RELATED ||
420              ctinfo == IP_CT_RELATED_REPLY))
421                 return XT_CONTINUE;
422
423         /* ip_conntrack_icmp guarantees us that we only have ICMP_ECHO,
424          * TIMESTAMP, INFO_REQUEST or ADDRESS type icmp packets from here
425          * on, which all have an ID field [relevant for hashing]. */
426
427         hash = clusterip_hashfn(skb, cipinfo->config);
428
429         switch (ctinfo) {
430         case IP_CT_NEW:
431                 ct->mark = hash;
432                 break;
433         case IP_CT_RELATED:
434         case IP_CT_RELATED_REPLY:
435                 /* FIXME: we don't handle expectations at the moment.
436                  * They can arrive on a different node than
437                  * the master connection (e.g. FTP passive mode) */
438         case IP_CT_ESTABLISHED:
439         case IP_CT_ESTABLISHED_REPLY:
440                 break;
441         default:                        /* Prevent gcc warnings */
442                 break;
443         }
444
445 #ifdef DEBUG
446         nf_ct_dump_tuple_ip(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
447 #endif
448         pr_debug("hash=%u ct_hash=%u ", hash, ct->mark);
449         if (!clusterip_responsible(cipinfo->config, hash)) {
450                 pr_debug("not responsible\n");
451                 return NF_DROP;
452         }
453         pr_debug("responsible\n");
454
455         /* despite being received via linklayer multicast, this is
456          * actually a unicast IP packet. TCP doesn't like PACKET_MULTICAST */
457         skb->pkt_type = PACKET_HOST;
458
459         return XT_CONTINUE;
460 }
461
462 static int clusterip_tg_check(const struct xt_tgchk_param *par)
463 {
464         struct ipt_clusterip_tgt_info *cipinfo = par->targinfo;
465         const struct ipt_entry *e = par->entryinfo;
466         struct clusterip_config *config;
467         int ret, i;
468
469         if (par->nft_compat) {
470                 pr_err("cannot use CLUSTERIP target from nftables compat\n");
471                 return -EOPNOTSUPP;
472         }
473
474         if (cipinfo->hash_mode != CLUSTERIP_HASHMODE_SIP &&
475             cipinfo->hash_mode != CLUSTERIP_HASHMODE_SIP_SPT &&
476             cipinfo->hash_mode != CLUSTERIP_HASHMODE_SIP_SPT_DPT) {
477                 pr_info("unknown mode %u\n", cipinfo->hash_mode);
478                 return -EINVAL;
479
480         }
481         if (e->ip.dmsk.s_addr != htonl(0xffffffff) ||
482             e->ip.dst.s_addr == 0) {
483                 pr_info("Please specify destination IP\n");
484                 return -EINVAL;
485         }
486         if (cipinfo->num_local_nodes > ARRAY_SIZE(cipinfo->local_nodes)) {
487                 pr_info("bad num_local_nodes %u\n", cipinfo->num_local_nodes);
488                 return -EINVAL;
489         }
490         for (i = 0; i < cipinfo->num_local_nodes; i++) {
491                 if (cipinfo->local_nodes[i] - 1 >=
492                     sizeof(config->local_nodes) * 8) {
493                         pr_info("bad local_nodes[%d] %u\n",
494                                 i, cipinfo->local_nodes[i]);
495                         return -EINVAL;
496                 }
497         }
498
499         config = clusterip_config_find_get(par->net, e->ip.dst.s_addr, 1);
500         if (!config) {
501                 if (!(cipinfo->flags & CLUSTERIP_FLAG_NEW)) {
502                         pr_info("no config found for %pI4, need 'new'\n",
503                                 &e->ip.dst.s_addr);
504                         return -EINVAL;
505                 } else {
506                         config = clusterip_config_init(par->net, cipinfo,
507                                                        e->ip.dst.s_addr,
508                                                        e->ip.iniface);
509                         if (IS_ERR(config))
510                                 return PTR_ERR(config);
511                 }
512         }
513
514         ret = nf_ct_netns_get(par->net, par->family);
515         if (ret < 0) {
516                 pr_info("cannot load conntrack support for proto=%u\n",
517                         par->family);
518                 clusterip_config_entry_put(config);
519                 clusterip_config_put(config);
520                 return ret;
521         }
522
523         if (!par->net->xt.clusterip_deprecated_warning) {
524                 pr_info("ipt_CLUSTERIP is deprecated and it will removed soon, "
525                         "use xt_cluster instead\n");
526                 par->net->xt.clusterip_deprecated_warning = true;
527         }
528
529         cipinfo->config = config;
530         return ret;
531 }
532
533 /* drop reference count of cluster config when rule is deleted */
534 static void clusterip_tg_destroy(const struct xt_tgdtor_param *par)
535 {
536         const struct ipt_clusterip_tgt_info *cipinfo = par->targinfo;
537
538         /* if no more entries are referencing the config, remove it
539          * from the list and destroy the proc entry */
540         clusterip_config_entry_put(cipinfo->config);
541
542         clusterip_config_put(cipinfo->config);
543
544         nf_ct_netns_put(par->net, par->family);
545 }
546
547 #ifdef CONFIG_COMPAT
548 struct compat_ipt_clusterip_tgt_info
549 {
550         u_int32_t       flags;
551         u_int8_t        clustermac[6];
552         u_int16_t       num_total_nodes;
553         u_int16_t       num_local_nodes;
554         u_int16_t       local_nodes[CLUSTERIP_MAX_NODES];
555         u_int32_t       hash_mode;
556         u_int32_t       hash_initval;
557         compat_uptr_t   config;
558 };
559 #endif /* CONFIG_COMPAT */
560
561 static struct xt_target clusterip_tg_reg __read_mostly = {
562         .name           = "CLUSTERIP",
563         .family         = NFPROTO_IPV4,
564         .target         = clusterip_tg,
565         .checkentry     = clusterip_tg_check,
566         .destroy        = clusterip_tg_destroy,
567         .targetsize     = sizeof(struct ipt_clusterip_tgt_info),
568         .usersize       = offsetof(struct ipt_clusterip_tgt_info, config),
569 #ifdef CONFIG_COMPAT
570         .compatsize     = sizeof(struct compat_ipt_clusterip_tgt_info),
571 #endif /* CONFIG_COMPAT */
572         .me             = THIS_MODULE
573 };
574
575
576 /***********************************************************************
577  * ARP MANGLING CODE
578  ***********************************************************************/
579
580 /* hardcoded for 48bit ethernet and 32bit ipv4 addresses */
581 struct arp_payload {
582         u_int8_t src_hw[ETH_ALEN];
583         __be32 src_ip;
584         u_int8_t dst_hw[ETH_ALEN];
585         __be32 dst_ip;
586 } __packed;
587
588 #ifdef DEBUG
589 static void arp_print(struct arp_payload *payload)
590 {
591 #define HBUFFERLEN 30
592         char hbuffer[HBUFFERLEN];
593         int j, k;
594
595         for (k = 0, j = 0; k < HBUFFERLEN - 3 && j < ETH_ALEN; j++) {
596                 hbuffer[k++] = hex_asc_hi(payload->src_hw[j]);
597                 hbuffer[k++] = hex_asc_lo(payload->src_hw[j]);
598                 hbuffer[k++] = ':';
599         }
600         hbuffer[--k] = '\0';
601
602         pr_debug("src %pI4@%s, dst %pI4\n",
603                  &payload->src_ip, hbuffer, &payload->dst_ip);
604 }
605 #endif
606
607 static unsigned int
608 arp_mangle(void *priv,
609            struct sk_buff *skb,
610            const struct nf_hook_state *state)
611 {
612         struct arphdr *arp = arp_hdr(skb);
613         struct arp_payload *payload;
614         struct clusterip_config *c;
615         struct net *net = state->net;
616
617         /* we don't care about non-ethernet and non-ipv4 ARP */
618         if (arp->ar_hrd != htons(ARPHRD_ETHER) ||
619             arp->ar_pro != htons(ETH_P_IP) ||
620             arp->ar_pln != 4 || arp->ar_hln != ETH_ALEN)
621                 return NF_ACCEPT;
622
623         /* we only want to mangle arp requests and replies */
624         if (arp->ar_op != htons(ARPOP_REPLY) &&
625             arp->ar_op != htons(ARPOP_REQUEST))
626                 return NF_ACCEPT;
627
628         payload = (void *)(arp+1);
629
630         /* if there is no clusterip configuration for the arp reply's
631          * source ip, we don't want to mangle it */
632         c = clusterip_config_find_get(net, payload->src_ip, 0);
633         if (!c)
634                 return NF_ACCEPT;
635
636         /* normally the linux kernel always replies to arp queries of
637          * addresses on different interfacs.  However, in the CLUSTERIP case
638          * this wouldn't work, since we didn't subscribe the mcast group on
639          * other interfaces */
640         if (c->ifindex != state->out->ifindex) {
641                 pr_debug("not mangling arp reply on different interface: cip'%d'-skb'%d'\n",
642                          c->ifindex, state->out->ifindex);
643                 clusterip_config_put(c);
644                 return NF_ACCEPT;
645         }
646
647         /* mangle reply hardware address */
648         memcpy(payload->src_hw, c->clustermac, arp->ar_hln);
649
650 #ifdef DEBUG
651         pr_debug("mangled arp reply: ");
652         arp_print(payload);
653 #endif
654
655         clusterip_config_put(c);
656
657         return NF_ACCEPT;
658 }
659
660 static const struct nf_hook_ops cip_arp_ops = {
661         .hook = arp_mangle,
662         .pf = NFPROTO_ARP,
663         .hooknum = NF_ARP_OUT,
664         .priority = -1
665 };
666
667 /***********************************************************************
668  * PROC DIR HANDLING
669  ***********************************************************************/
670
671 #ifdef CONFIG_PROC_FS
672
673 struct clusterip_seq_position {
674         unsigned int pos;       /* position */
675         unsigned int weight;    /* number of bits set == size */
676         unsigned int bit;       /* current bit */
677         unsigned long val;      /* current value */
678 };
679
680 static void *clusterip_seq_start(struct seq_file *s, loff_t *pos)
681 {
682         struct clusterip_config *c = s->private;
683         unsigned int weight;
684         u_int32_t local_nodes;
685         struct clusterip_seq_position *idx;
686
687         /* FIXME: possible race */
688         local_nodes = c->local_nodes;
689         weight = hweight32(local_nodes);
690         if (*pos >= weight)
691                 return NULL;
692
693         idx = kmalloc(sizeof(struct clusterip_seq_position), GFP_KERNEL);
694         if (!idx)
695                 return ERR_PTR(-ENOMEM);
696
697         idx->pos = *pos;
698         idx->weight = weight;
699         idx->bit = ffs(local_nodes);
700         idx->val = local_nodes;
701         clear_bit(idx->bit - 1, &idx->val);
702
703         return idx;
704 }
705
706 static void *clusterip_seq_next(struct seq_file *s, void *v, loff_t *pos)
707 {
708         struct clusterip_seq_position *idx = v;
709
710         *pos = ++idx->pos;
711         if (*pos >= idx->weight) {
712                 kfree(v);
713                 return NULL;
714         }
715         idx->bit = ffs(idx->val);
716         clear_bit(idx->bit - 1, &idx->val);
717         return idx;
718 }
719
720 static void clusterip_seq_stop(struct seq_file *s, void *v)
721 {
722         if (!IS_ERR(v))
723                 kfree(v);
724 }
725
726 static int clusterip_seq_show(struct seq_file *s, void *v)
727 {
728         struct clusterip_seq_position *idx = v;
729
730         if (idx->pos != 0)
731                 seq_putc(s, ',');
732
733         seq_printf(s, "%u", idx->bit);
734
735         if (idx->pos == idx->weight - 1)
736                 seq_putc(s, '\n');
737
738         return 0;
739 }
740
741 static const struct seq_operations clusterip_seq_ops = {
742         .start  = clusterip_seq_start,
743         .next   = clusterip_seq_next,
744         .stop   = clusterip_seq_stop,
745         .show   = clusterip_seq_show,
746 };
747
748 static int clusterip_proc_open(struct inode *inode, struct file *file)
749 {
750         int ret = seq_open(file, &clusterip_seq_ops);
751
752         if (!ret) {
753                 struct seq_file *sf = file->private_data;
754                 struct clusterip_config *c = PDE_DATA(inode);
755
756                 sf->private = c;
757
758                 clusterip_config_get(c);
759         }
760
761         return ret;
762 }
763
764 static int clusterip_proc_release(struct inode *inode, struct file *file)
765 {
766         struct clusterip_config *c = PDE_DATA(inode);
767         int ret;
768
769         ret = seq_release(inode, file);
770
771         if (!ret)
772                 clusterip_config_put(c);
773
774         return ret;
775 }
776
777 static ssize_t clusterip_proc_write(struct file *file, const char __user *input,
778                                 size_t size, loff_t *ofs)
779 {
780         struct clusterip_config *c = PDE_DATA(file_inode(file));
781 #define PROC_WRITELEN   10
782         char buffer[PROC_WRITELEN+1];
783         unsigned long nodenum;
784         int rc;
785
786         if (size > PROC_WRITELEN)
787                 return -EIO;
788         if (copy_from_user(buffer, input, size))
789                 return -EFAULT;
790         buffer[size] = 0;
791
792         if (*buffer == '+') {
793                 rc = kstrtoul(buffer+1, 10, &nodenum);
794                 if (rc)
795                         return rc;
796                 if (clusterip_add_node(c, nodenum))
797                         return -ENOMEM;
798         } else if (*buffer == '-') {
799                 rc = kstrtoul(buffer+1, 10, &nodenum);
800                 if (rc)
801                         return rc;
802                 if (clusterip_del_node(c, nodenum))
803                         return -ENOENT;
804         } else
805                 return -EIO;
806
807         return size;
808 }
809
810 static const struct file_operations clusterip_proc_fops = {
811         .open    = clusterip_proc_open,
812         .read    = seq_read,
813         .write   = clusterip_proc_write,
814         .llseek  = seq_lseek,
815         .release = clusterip_proc_release,
816 };
817
818 #endif /* CONFIG_PROC_FS */
819
820 static int clusterip_net_init(struct net *net)
821 {
822         struct clusterip_net *cn = clusterip_pernet(net);
823         int ret;
824
825         INIT_LIST_HEAD(&cn->configs);
826
827         spin_lock_init(&cn->lock);
828
829         ret = nf_register_net_hook(net, &cip_arp_ops);
830         if (ret < 0)
831                 return ret;
832
833 #ifdef CONFIG_PROC_FS
834         cn->procdir = proc_mkdir("ipt_CLUSTERIP", net->proc_net);
835         if (!cn->procdir) {
836                 nf_unregister_net_hook(net, &cip_arp_ops);
837                 pr_err("Unable to proc dir entry\n");
838                 return -ENOMEM;
839         }
840         mutex_init(&cn->mutex);
841 #endif /* CONFIG_PROC_FS */
842
843         return 0;
844 }
845
846 static void clusterip_net_exit(struct net *net)
847 {
848         struct clusterip_net *cn = clusterip_pernet(net);
849
850 #ifdef CONFIG_PROC_FS
851         mutex_lock(&cn->mutex);
852         proc_remove(cn->procdir);
853         cn->procdir = NULL;
854         mutex_unlock(&cn->mutex);
855 #endif
856         nf_unregister_net_hook(net, &cip_arp_ops);
857 }
858
859 static struct pernet_operations clusterip_net_ops = {
860         .init = clusterip_net_init,
861         .exit = clusterip_net_exit,
862         .id   = &clusterip_net_id,
863         .size = sizeof(struct clusterip_net),
864 };
865
866 struct notifier_block cip_netdev_notifier = {
867         .notifier_call = clusterip_netdev_event
868 };
869
870 static int __init clusterip_tg_init(void)
871 {
872         int ret;
873
874         ret = register_pernet_subsys(&clusterip_net_ops);
875         if (ret < 0)
876                 return ret;
877
878         ret = xt_register_target(&clusterip_tg_reg);
879         if (ret < 0)
880                 goto cleanup_subsys;
881
882         ret = register_netdevice_notifier(&cip_netdev_notifier);
883         if (ret < 0)
884                 goto unregister_target;
885
886         pr_info("ClusterIP Version %s loaded successfully\n",
887                 CLUSTERIP_VERSION);
888
889         return 0;
890
891 unregister_target:
892         xt_unregister_target(&clusterip_tg_reg);
893 cleanup_subsys:
894         unregister_pernet_subsys(&clusterip_net_ops);
895         return ret;
896 }
897
898 static void __exit clusterip_tg_exit(void)
899 {
900         pr_info("ClusterIP Version %s unloading\n", CLUSTERIP_VERSION);
901
902         unregister_netdevice_notifier(&cip_netdev_notifier);
903         xt_unregister_target(&clusterip_tg_reg);
904         unregister_pernet_subsys(&clusterip_net_ops);
905
906         /* Wait for completion of call_rcu()'s (clusterip_config_rcu_free) */
907         rcu_barrier();
908 }
909
910 module_init(clusterip_tg_init);
911 module_exit(clusterip_tg_exit);