linux/net/netfilter/ipvs/ip_vs_ctl.c
<<
>>
Prefs
   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 * Authors:     Wensong Zhang <wensong@linuxvirtualserver.org>
   9 *              Peter Kese <peter.kese@ijs.si>
  10 *              Julian Anastasov <ja@ssi.bg>
  11 *
  12 *              This program is free software; you can redistribute it and/or
  13 *              modify it under the terms of the GNU General Public License
  14 *              as published by the Free Software Foundation; either version
  15 *              2 of the License, or (at your option) any later version.
  16 *
  17 * Changes:
  18 *
  19 */
  20
  21#define KMSG_COMPONENT "IPVS"
  22#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
  23
  24#include <linux/module.h>
  25#include <linux/init.h>
  26#include <linux/types.h>
  27#include <linux/capability.h>
  28#include <linux/fs.h>
  29#include <linux/sysctl.h>
  30#include <linux/proc_fs.h>
  31#include <linux/workqueue.h>
  32#include <linux/swap.h>
  33#include <linux/seq_file.h>
  34#include <linux/slab.h>
  35
  36#include <linux/netfilter.h>
  37#include <linux/netfilter_ipv4.h>
  38#include <linux/mutex.h>
  39
  40#include <net/net_namespace.h>
  41#include <linux/nsproxy.h>
  42#include <net/ip.h>
  43#ifdef CONFIG_IP_VS_IPV6
  44#include <net/ipv6.h>
  45#include <net/ip6_route.h>
  46#endif
  47#include <net/route.h>
  48#include <net/sock.h>
  49#include <net/genetlink.h>
  50
  51#include <asm/uaccess.h>
  52
  53#include <net/ip_vs.h>
  54
  55/* semaphore for IPVS sockopts. And, [gs]etsockopt may sleep. */
  56static DEFINE_MUTEX(__ip_vs_mutex);
  57
  58/* sysctl variables */
  59
  60#ifdef CONFIG_IP_VS_DEBUG
  61static int sysctl_ip_vs_debug_level = 0;
  62
  63int ip_vs_get_debug_level(void)
  64{
  65        return sysctl_ip_vs_debug_level;
  66}
  67#endif
  68
  69
  70/*  Protos */
  71static void __ip_vs_del_service(struct ip_vs_service *svc, bool cleanup);
  72
  73
  74#ifdef CONFIG_IP_VS_IPV6
  75/* Taken from rt6_fill_node() in net/ipv6/route.c, is there a better way? */
  76static bool __ip_vs_addr_is_local_v6(struct net *net,
  77                                     const struct in6_addr *addr)
  78{
  79        struct flowi6 fl6 = {
  80                .daddr = *addr,
  81        };
  82        struct dst_entry *dst = ip6_route_output(net, NULL, &fl6);
  83        bool is_local;
  84
  85        is_local = !dst->error && dst->dev && (dst->dev->flags & IFF_LOOPBACK);
  86
  87        dst_release(dst);
  88        return is_local;
  89}
  90#endif
  91
  92#ifdef CONFIG_SYSCTL
  93/*
  94 *      update_defense_level is called from keventd and from sysctl,
  95 *      so it needs to protect itself from softirqs
  96 */
  97static void update_defense_level(struct netns_ipvs *ipvs)
  98{
  99        struct sysinfo i;
 100        static int old_secure_tcp = 0;
 101        int availmem;
 102        int nomem;
 103        int to_change = -1;
 104
 105        /* we only count free and buffered memory (in pages) */
 106        si_meminfo(&i);
 107        availmem = i.freeram + i.bufferram;
 108        /* however in linux 2.5 the i.bufferram is total page cache size,
 109           we need adjust it */
 110        /* si_swapinfo(&i); */
 111        /* availmem = availmem - (i.totalswap - i.freeswap); */
 112
 113        nomem = (availmem < ipvs->sysctl_amemthresh);
 114
 115        local_bh_disable();
 116
 117        /* drop_entry */
 118        spin_lock(&ipvs->dropentry_lock);
 119        switch (ipvs->sysctl_drop_entry) {
 120        case 0:
 121                atomic_set(&ipvs->dropentry, 0);
 122                break;
 123        case 1:
 124                if (nomem) {
 125                        atomic_set(&ipvs->dropentry, 1);
 126                        ipvs->sysctl_drop_entry = 2;
 127                } else {
 128                        atomic_set(&ipvs->dropentry, 0);
 129                }
 130                break;
 131        case 2:
 132                if (nomem) {
 133                        atomic_set(&ipvs->dropentry, 1);
 134                } else {
 135                        atomic_set(&ipvs->dropentry, 0);
 136                        ipvs->sysctl_drop_entry = 1;
 137                };
 138                break;
 139        case 3:
 140                atomic_set(&ipvs->dropentry, 1);
 141                break;
 142        }
 143        spin_unlock(&ipvs->dropentry_lock);
 144
 145        /* drop_packet */
 146        spin_lock(&ipvs->droppacket_lock);
 147        switch (ipvs->sysctl_drop_packet) {
 148        case 0:
 149                ipvs->drop_rate = 0;
 150                break;
 151        case 1:
 152                if (nomem) {
 153                        ipvs->drop_rate = ipvs->drop_counter
 154                                = ipvs->sysctl_amemthresh /
 155                                (ipvs->sysctl_amemthresh-availmem);
 156                        ipvs->sysctl_drop_packet = 2;
 157                } else {
 158                        ipvs->drop_rate = 0;
 159                }
 160                break;
 161        case 2:
 162                if (nomem) {
 163                        ipvs->drop_rate = ipvs->drop_counter
 164                                = ipvs->sysctl_amemthresh /
 165                                (ipvs->sysctl_amemthresh-availmem);
 166                } else {
 167                        ipvs->drop_rate = 0;
 168                        ipvs->sysctl_drop_packet = 1;
 169                }
 170                break;
 171        case 3:
 172                ipvs->drop_rate = ipvs->sysctl_am_droprate;
 173                break;
 174        }
 175        spin_unlock(&ipvs->droppacket_lock);
 176
 177        /* secure_tcp */
 178        spin_lock(&ipvs->securetcp_lock);
 179        switch (ipvs->sysctl_secure_tcp) {
 180        case 0:
 181                if (old_secure_tcp >= 2)
 182                        to_change = 0;
 183                break;
 184        case 1:
 185                if (nomem) {
 186                        if (old_secure_tcp < 2)
 187                                to_change = 1;
 188                        ipvs->sysctl_secure_tcp = 2;
 189                } else {
 190                        if (old_secure_tcp >= 2)
 191                                to_change = 0;
 192                }
 193                break;
 194        case 2:
 195                if (nomem) {
 196                        if (old_secure_tcp < 2)
 197                                to_change = 1;
 198                } else {
 199                        if (old_secure_tcp >= 2)
 200                                to_change = 0;
 201                        ipvs->sysctl_secure_tcp = 1;
 202                }
 203                break;
 204        case 3:
 205                if (old_secure_tcp < 2)
 206                        to_change = 1;
 207                break;
 208        }
 209        old_secure_tcp = ipvs->sysctl_secure_tcp;
 210        if (to_change >= 0)
 211                ip_vs_protocol_timeout_change(ipvs,
 212                                              ipvs->sysctl_secure_tcp > 1);
 213        spin_unlock(&ipvs->securetcp_lock);
 214
 215        local_bh_enable();
 216}
 217
 218
 219/*
 220 *      Timer for checking the defense
 221 */
 222#define DEFENSE_TIMER_PERIOD    1*HZ
 223
 224static void defense_work_handler(struct work_struct *work)
 225{
 226        struct netns_ipvs *ipvs =
 227                container_of(work, struct netns_ipvs, defense_work.work);
 228
 229        update_defense_level(ipvs);
 230        if (atomic_read(&ipvs->dropentry))
 231                ip_vs_random_dropentry(ipvs->net);
 232        schedule_delayed_work(&ipvs->defense_work, DEFENSE_TIMER_PERIOD);
 233}
 234#endif
 235
 236int
 237ip_vs_use_count_inc(void)
 238{
 239        return try_module_get(THIS_MODULE);
 240}
 241
 242void
 243ip_vs_use_count_dec(void)
 244{
 245        module_put(THIS_MODULE);
 246}
 247
 248
 249/*
 250 *      Hash table: for virtual service lookups
 251 */
 252#define IP_VS_SVC_TAB_BITS 8
 253#define IP_VS_SVC_TAB_SIZE (1 << IP_VS_SVC_TAB_BITS)
 254#define IP_VS_SVC_TAB_MASK (IP_VS_SVC_TAB_SIZE - 1)
 255
 256/* the service table hashed by <protocol, addr, port> */
 257static struct hlist_head ip_vs_svc_table[IP_VS_SVC_TAB_SIZE];
 258/* the service table hashed by fwmark */
 259static struct hlist_head ip_vs_svc_fwm_table[IP_VS_SVC_TAB_SIZE];
 260
 261
 262/*
 263 *      Returns hash value for virtual service
 264 */
 265static inline unsigned int
 266ip_vs_svc_hashkey(struct net *net, int af, unsigned int proto,
 267                  const union nf_inet_addr *addr, __be16 port)
 268{
 269        register unsigned int porth = ntohs(port);
 270        __be32 addr_fold = addr->ip;
 271        __u32 ahash;
 272
 273#ifdef CONFIG_IP_VS_IPV6
 274        if (af == AF_INET6)
 275                addr_fold = addr->ip6[0]^addr->ip6[1]^
 276                            addr->ip6[2]^addr->ip6[3];
 277#endif
 278        ahash = ntohl(addr_fold);
 279        ahash ^= ((size_t) net >> 8);
 280
 281        return (proto ^ ahash ^ (porth >> IP_VS_SVC_TAB_BITS) ^ porth) &
 282               IP_VS_SVC_TAB_MASK;
 283}
 284
 285/*
 286 *      Returns hash value of fwmark for virtual service lookup
 287 */
 288static inline unsigned int ip_vs_svc_fwm_hashkey(struct net *net, __u32 fwmark)
 289{
 290        return (((size_t)net>>8) ^ fwmark) & IP_VS_SVC_TAB_MASK;
 291}
 292
 293/*
 294 *      Hashes a service in the ip_vs_svc_table by <netns,proto,addr,port>
 295 *      or in the ip_vs_svc_fwm_table by fwmark.
 296 *      Should be called with locked tables.
 297 */
 298static int ip_vs_svc_hash(struct ip_vs_service *svc)
 299{
 300        unsigned int hash;
 301
 302        if (svc->flags & IP_VS_SVC_F_HASHED) {
 303                pr_err("%s(): request for already hashed, called from %pF\n",
 304                       __func__, __builtin_return_address(0));
 305                return 0;
 306        }
 307
 308        if (svc->fwmark == 0) {
 309                /*
 310                 *  Hash it by <netns,protocol,addr,port> in ip_vs_svc_table
 311                 */
 312                hash = ip_vs_svc_hashkey(svc->net, svc->af, svc->protocol,
 313                                         &svc->addr, svc->port);
 314                hlist_add_head_rcu(&svc->s_list, &ip_vs_svc_table[hash]);
 315        } else {
 316                /*
 317                 *  Hash it by fwmark in svc_fwm_table
 318                 */
 319                hash = ip_vs_svc_fwm_hashkey(svc->net, svc->fwmark);
 320                hlist_add_head_rcu(&svc->f_list, &ip_vs_svc_fwm_table[hash]);
 321        }
 322
 323        svc->flags |= IP_VS_SVC_F_HASHED;
 324        /* increase its refcnt because it is referenced by the svc table */
 325        atomic_inc(&svc->refcnt);
 326        return 1;
 327}
 328
 329
 330/*
 331 *      Unhashes a service from svc_table / svc_fwm_table.
 332 *      Should be called with locked tables.
 333 */
 334static int ip_vs_svc_unhash(struct ip_vs_service *svc)
 335{
 336        if (!(svc->flags & IP_VS_SVC_F_HASHED)) {
 337                pr_err("%s(): request for unhash flagged, called from %pF\n",
 338                       __func__, __builtin_return_address(0));
 339                return 0;
 340        }
 341
 342        if (svc->fwmark == 0) {
 343                /* Remove it from the svc_table table */
 344                hlist_del_rcu(&svc->s_list);
 345        } else {
 346                /* Remove it from the svc_fwm_table table */
 347                hlist_del_rcu(&svc->f_list);
 348        }
 349
 350        svc->flags &= ~IP_VS_SVC_F_HASHED;
 351        atomic_dec(&svc->refcnt);
 352        return 1;
 353}
 354
 355
 356/*
 357 *      Get service by {netns, proto,addr,port} in the service table.
 358 */
 359static inline struct ip_vs_service *
 360__ip_vs_service_find(struct net *net, int af, __u16 protocol,
 361                     const union nf_inet_addr *vaddr, __be16 vport)
 362{
 363        unsigned int hash;
 364        struct ip_vs_service *svc;
 365
 366        /* Check for "full" addressed entries */
 367        hash = ip_vs_svc_hashkey(net, af, protocol, vaddr, vport);
 368
 369        hlist_for_each_entry_rcu(svc, &ip_vs_svc_table[hash], s_list) {
 370                if ((svc->af == af)
 371                    && ip_vs_addr_equal(af, &svc->addr, vaddr)
 372                    && (svc->port == vport)
 373                    && (svc->protocol == protocol)
 374                    && net_eq(svc->net, net)) {
 375                        /* HIT */
 376                        return svc;
 377                }
 378        }
 379
 380        return NULL;
 381}
 382
 383
 384/*
 385 *      Get service by {fwmark} in the service table.
 386 */
 387static inline struct ip_vs_service *
 388__ip_vs_svc_fwm_find(struct net *net, int af, __u32 fwmark)
 389{
 390        unsigned int hash;
 391        struct ip_vs_service *svc;
 392
 393        /* Check for fwmark addressed entries */
 394        hash = ip_vs_svc_fwm_hashkey(net, fwmark);
 395
 396        hlist_for_each_entry_rcu(svc, &ip_vs_svc_fwm_table[hash], f_list) {
 397                if (svc->fwmark == fwmark && svc->af == af
 398                    && net_eq(svc->net, net)) {
 399                        /* HIT */
 400                        return svc;
 401                }
 402        }
 403
 404        return NULL;
 405}
 406
 407/* Find service, called under RCU lock */
 408struct ip_vs_service *
 409ip_vs_service_find(struct net *net, int af, __u32 fwmark, __u16 protocol,
 410                   const union nf_inet_addr *vaddr, __be16 vport)
 411{
 412        struct ip_vs_service *svc;
 413        struct netns_ipvs *ipvs = net_ipvs(net);
 414
 415        /*
 416         *      Check the table hashed by fwmark first
 417         */
 418        if (fwmark) {
 419                svc = __ip_vs_svc_fwm_find(net, af, fwmark);
 420                if (svc)
 421                        goto out;
 422        }
 423
 424        /*
 425         *      Check the table hashed by <protocol,addr,port>
 426         *      for "full" addressed entries
 427         */
 428        svc = __ip_vs_service_find(net, af, protocol, vaddr, vport);
 429
 430        if (svc == NULL
 431            && protocol == IPPROTO_TCP
 432            && atomic_read(&ipvs->ftpsvc_counter)
 433            && (vport == FTPDATA || ntohs(vport) >= PROT_SOCK)) {
 434                /*
 435                 * Check if ftp service entry exists, the packet
 436                 * might belong to FTP data connections.
 437                 */
 438                svc = __ip_vs_service_find(net, af, protocol, vaddr, FTPPORT);
 439        }
 440
 441        if (svc == NULL
 442            && atomic_read(&ipvs->nullsvc_counter)) {
 443                /*
 444                 * Check if the catch-all port (port zero) exists
 445                 */
 446                svc = __ip_vs_service_find(net, af, protocol, vaddr, 0);
 447        }
 448
 449  out:
 450        IP_VS_DBG_BUF(9, "lookup service: fwm %u %s %s:%u %s\n",
 451                      fwmark, ip_vs_proto_name(protocol),
 452                      IP_VS_DBG_ADDR(af, vaddr), ntohs(vport),
 453                      svc ? "hit" : "not hit");
 454
 455        return svc;
 456}
 457
 458
 459static inline void
 460__ip_vs_bind_svc(struct ip_vs_dest *dest, struct ip_vs_service *svc)
 461{
 462        atomic_inc(&svc->refcnt);
 463        dest->svc = svc;
 464}
 465
 466static void ip_vs_service_free(struct ip_vs_service *svc)
 467{
 468        free_percpu(svc->stats.cpustats);
 469        kfree(svc);
 470}
 471
 472static void
 473__ip_vs_unbind_svc(struct ip_vs_dest *dest)
 474{
 475        struct ip_vs_service *svc = dest->svc;
 476
 477        dest->svc = NULL;
 478        if (atomic_dec_and_test(&svc->refcnt)) {
 479                IP_VS_DBG_BUF(3, "Removing service %u/%s:%u\n",
 480                              svc->fwmark,
 481                              IP_VS_DBG_ADDR(svc->af, &svc->addr),
 482                              ntohs(svc->port));
 483                ip_vs_service_free(svc);
 484        }
 485}
 486
 487
 488/*
 489 *      Returns hash value for real service
 490 */
 491static inline unsigned int ip_vs_rs_hashkey(int af,
 492                                            const union nf_inet_addr *addr,
 493                                            __be16 port)
 494{
 495        register unsigned int porth = ntohs(port);
 496        __be32 addr_fold = addr->ip;
 497
 498#ifdef CONFIG_IP_VS_IPV6
 499        if (af == AF_INET6)
 500                addr_fold = addr->ip6[0]^addr->ip6[1]^
 501                            addr->ip6[2]^addr->ip6[3];
 502#endif
 503
 504        return (ntohl(addr_fold)^(porth>>IP_VS_RTAB_BITS)^porth)
 505                & IP_VS_RTAB_MASK;
 506}
 507
 508/* Hash ip_vs_dest in rs_table by <proto,addr,port>. */
 509static void ip_vs_rs_hash(struct netns_ipvs *ipvs, struct ip_vs_dest *dest)
 510{
 511        unsigned int hash;
 512
 513        if (dest->in_rs_table)
 514                return;
 515
 516        /*
 517         *      Hash by proto,addr,port,
 518         *      which are the parameters of the real service.
 519         */
 520        hash = ip_vs_rs_hashkey(dest->af, &dest->addr, dest->port);
 521
 522        hlist_add_head_rcu(&dest->d_list, &ipvs->rs_table[hash]);
 523        dest->in_rs_table = 1;
 524}
 525
 526/* Unhash ip_vs_dest from rs_table. */
 527static void ip_vs_rs_unhash(struct ip_vs_dest *dest)
 528{
 529        /*
 530         * Remove it from the rs_table table.
 531         */
 532        if (dest->in_rs_table) {
 533                hlist_del_rcu(&dest->d_list);
 534                dest->in_rs_table = 0;
 535        }
 536}
 537
 538/* Check if real service by <proto,addr,port> is present */
 539bool ip_vs_has_real_service(struct net *net, int af, __u16 protocol,
 540                            const union nf_inet_addr *daddr, __be16 dport)
 541{
 542        struct netns_ipvs *ipvs = net_ipvs(net);
 543        unsigned int hash;
 544        struct ip_vs_dest *dest;
 545
 546        /* Check for "full" addressed entries */
 547        hash = ip_vs_rs_hashkey(af, daddr, dport);
 548
 549        rcu_read_lock();
 550        hlist_for_each_entry_rcu(dest, &ipvs->rs_table[hash], d_list) {
 551                if (dest->port == dport &&
 552                    dest->af == af &&
 553                    ip_vs_addr_equal(af, &dest->addr, daddr) &&
 554                    (dest->protocol == protocol || dest->vfwmark)) {
 555                        /* HIT */
 556                        rcu_read_unlock();
 557                        return true;
 558                }
 559        }
 560        rcu_read_unlock();
 561
 562        return false;
 563}
 564
 565/* Find real service record by <proto,addr,port>.
 566 * In case of multiple records with the same <proto,addr,port>, only
 567 * the first found record is returned.
 568 *
 569 * To be called under RCU lock.
 570 */
 571struct ip_vs_dest *ip_vs_find_real_service(struct netns_ipvs *ipvs, int af,
 572                                           __u16 protocol,
 573                                           const union nf_inet_addr *daddr,
 574                                           __be16 dport)
 575{
 576        unsigned int hash;
 577        struct ip_vs_dest *dest;
 578
 579        /* Check for "full" addressed entries */
 580        hash = ip_vs_rs_hashkey(af, daddr, dport);
 581
 582        hlist_for_each_entry_rcu(dest, &ipvs->rs_table[hash], d_list) {
 583                if (dest->port == dport &&
 584                    dest->af == af &&
 585                    ip_vs_addr_equal(af, &dest->addr, daddr) &&
 586                        (dest->protocol == protocol || dest->vfwmark)) {
 587                        /* HIT */
 588                        return dest;
 589                }
 590        }
 591
 592        return NULL;
 593}
 594
 595/* Lookup destination by {addr,port} in the given service
 596 * Called under RCU lock.
 597 */
 598static struct ip_vs_dest *
 599ip_vs_lookup_dest(struct ip_vs_service *svc, const union nf_inet_addr *daddr,
 600                  __be16 dport)
 601{
 602        struct ip_vs_dest *dest;
 603
 604        /*
 605         * Find the destination for the given service
 606         */
 607        list_for_each_entry_rcu(dest, &svc->destinations, n_list) {
 608                if ((dest->af == svc->af)
 609                    && ip_vs_addr_equal(svc->af, &dest->addr, daddr)
 610                    && (dest->port == dport)) {
 611                        /* HIT */
 612                        return dest;
 613                }
 614        }
 615
 616        return NULL;
 617}
 618
 619/*
 620 * Find destination by {daddr,dport,vaddr,protocol}
 621 * Created to be used in ip_vs_process_message() in
 622 * the backup synchronization daemon. It finds the
 623 * destination to be bound to the received connection
 624 * on the backup.
 625 * Called under RCU lock, no refcnt is returned.
 626 */
 627struct ip_vs_dest *ip_vs_find_dest(struct net  *net, int af,
 628                                   const union nf_inet_addr *daddr,
 629                                   __be16 dport,
 630                                   const union nf_inet_addr *vaddr,
 631                                   __be16 vport, __u16 protocol, __u32 fwmark,
 632                                   __u32 flags)
 633{
 634        struct ip_vs_dest *dest;
 635        struct ip_vs_service *svc;
 636        __be16 port = dport;
 637
 638        svc = ip_vs_service_find(net, af, fwmark, protocol, vaddr, vport);
 639        if (!svc)
 640                return NULL;
 641        if (fwmark && (flags & IP_VS_CONN_F_FWD_MASK) != IP_VS_CONN_F_MASQ)
 642                port = 0;
 643        dest = ip_vs_lookup_dest(svc, daddr, port);
 644        if (!dest)
 645                dest = ip_vs_lookup_dest(svc, daddr, port ^ dport);
 646        return dest;
 647}
 648
 649void ip_vs_dest_dst_rcu_free(struct rcu_head *head)
 650{
 651        struct ip_vs_dest_dst *dest_dst = container_of(head,
 652                                                       struct ip_vs_dest_dst,
 653                                                       rcu_head);
 654
 655        dst_release(dest_dst->dst_cache);
 656        kfree(dest_dst);
 657}
 658
 659/* Release dest_dst and dst_cache for dest in user context */
 660static void __ip_vs_dst_cache_reset(struct ip_vs_dest *dest)
 661{
 662        struct ip_vs_dest_dst *old;
 663
 664        old = rcu_dereference_protected(dest->dest_dst, 1);
 665        if (old) {
 666                RCU_INIT_POINTER(dest->dest_dst, NULL);
 667                call_rcu(&old->rcu_head, ip_vs_dest_dst_rcu_free);
 668        }
 669}
 670
 671/*
 672 *  Lookup dest by {svc,addr,port} in the destination trash.
 673 *  The destination trash is used to hold the destinations that are removed
 674 *  from the service table but are still referenced by some conn entries.
 675 *  The reason to add the destination trash is when the dest is temporary
 676 *  down (either by administrator or by monitor program), the dest can be
 677 *  picked back from the trash, the remaining connections to the dest can
 678 *  continue, and the counting information of the dest is also useful for
 679 *  scheduling.
 680 */
 681static struct ip_vs_dest *
 682ip_vs_trash_get_dest(struct ip_vs_service *svc, const union nf_inet_addr *daddr,
 683                     __be16 dport)
 684{
 685        struct ip_vs_dest *dest;
 686        struct netns_ipvs *ipvs = net_ipvs(svc->net);
 687
 688        /*
 689         * Find the destination in trash
 690         */
 691        spin_lock_bh(&ipvs->dest_trash_lock);
 692        list_for_each_entry(dest, &ipvs->dest_trash, t_list) {
 693                IP_VS_DBG_BUF(3, "Destination %u/%s:%u still in trash, "
 694                              "dest->refcnt=%d\n",
 695                              dest->vfwmark,
 696                              IP_VS_DBG_ADDR(svc->af, &dest->addr),
 697                              ntohs(dest->port),
 698                              atomic_read(&dest->refcnt));
 699                /* We can not reuse dest while in grace period
 700                 * because conns still can use dest->svc
 701                 */
 702                if (test_bit(IP_VS_DEST_STATE_REMOVING, &dest->state))
 703                        continue;
 704                if (dest->af == svc->af &&
 705                    ip_vs_addr_equal(svc->af, &dest->addr, daddr) &&
 706                    dest->port == dport &&
 707                    dest->vfwmark == svc->fwmark &&
 708                    dest->protocol == svc->protocol &&
 709                    (svc->fwmark ||
 710                     (ip_vs_addr_equal(svc->af, &dest->vaddr, &svc->addr) &&
 711                      dest->vport == svc->port))) {
 712                        /* HIT */
 713                        list_del(&dest->t_list);
 714                        ip_vs_dest_hold(dest);
 715                        goto out;
 716                }
 717        }
 718
 719        dest = NULL;
 720
 721out:
 722        spin_unlock_bh(&ipvs->dest_trash_lock);
 723
 724        return dest;
 725}
 726
 727static void ip_vs_dest_free(struct ip_vs_dest *dest)
 728{
 729        __ip_vs_dst_cache_reset(dest);
 730        __ip_vs_unbind_svc(dest);
 731        free_percpu(dest->stats.cpustats);
 732        kfree(dest);
 733}
 734
 735/*
 736 *  Clean up all the destinations in the trash
 737 *  Called by the ip_vs_control_cleanup()
 738 *
 739 *  When the ip_vs_control_clearup is activated by ipvs module exit,
 740 *  the service tables must have been flushed and all the connections
 741 *  are expired, and the refcnt of each destination in the trash must
 742 *  be 0, so we simply release them here.
 743 */
 744static void ip_vs_trash_cleanup(struct net *net)
 745{
 746        struct ip_vs_dest *dest, *nxt;
 747        struct netns_ipvs *ipvs = net_ipvs(net);
 748
 749        del_timer_sync(&ipvs->dest_trash_timer);
 750        /* No need to use dest_trash_lock */
 751        list_for_each_entry_safe(dest, nxt, &ipvs->dest_trash, t_list) {
 752                list_del(&dest->t_list);
 753                ip_vs_dest_free(dest);
 754        }
 755}
 756
 757static void
 758ip_vs_copy_stats(struct ip_vs_stats_user *dst, struct ip_vs_stats *src)
 759{
 760#define IP_VS_SHOW_STATS_COUNTER(c) dst->c = src->ustats.c - src->ustats0.c
 761
 762        spin_lock_bh(&src->lock);
 763
 764        IP_VS_SHOW_STATS_COUNTER(conns);
 765        IP_VS_SHOW_STATS_COUNTER(inpkts);
 766        IP_VS_SHOW_STATS_COUNTER(outpkts);
 767        IP_VS_SHOW_STATS_COUNTER(inbytes);
 768        IP_VS_SHOW_STATS_COUNTER(outbytes);
 769
 770        ip_vs_read_estimator(dst, src);
 771
 772        spin_unlock_bh(&src->lock);
 773}
 774
 775static void
 776ip_vs_zero_stats(struct ip_vs_stats *stats)
 777{
 778        spin_lock_bh(&stats->lock);
 779
 780        /* get current counters as zero point, rates are zeroed */
 781
 782#define IP_VS_ZERO_STATS_COUNTER(c) stats->ustats0.c = stats->ustats.c
 783
 784        IP_VS_ZERO_STATS_COUNTER(conns);
 785        IP_VS_ZERO_STATS_COUNTER(inpkts);
 786        IP_VS_ZERO_STATS_COUNTER(outpkts);
 787        IP_VS_ZERO_STATS_COUNTER(inbytes);
 788        IP_VS_ZERO_STATS_COUNTER(outbytes);
 789
 790        ip_vs_zero_estimator(stats);
 791
 792        spin_unlock_bh(&stats->lock);
 793}
 794
 795/*
 796 *      Update a destination in the given service
 797 */
 798static void
 799__ip_vs_update_dest(struct ip_vs_service *svc, struct ip_vs_dest *dest,
 800                    struct ip_vs_dest_user_kern *udest, int add)
 801{
 802        struct netns_ipvs *ipvs = net_ipvs(svc->net);
 803        struct ip_vs_scheduler *sched;
 804        int conn_flags;
 805
 806        /* set the weight and the flags */
 807        atomic_set(&dest->weight, udest->weight);
 808        conn_flags = udest->conn_flags & IP_VS_CONN_F_DEST_MASK;
 809        conn_flags |= IP_VS_CONN_F_INACTIVE;
 810
 811        /* set the IP_VS_CONN_F_NOOUTPUT flag if not masquerading/NAT */
 812        if ((conn_flags & IP_VS_CONN_F_FWD_MASK) != IP_VS_CONN_F_MASQ) {
 813                conn_flags |= IP_VS_CONN_F_NOOUTPUT;
 814        } else {
 815                /*
 816                 *    Put the real service in rs_table if not present.
 817                 *    For now only for NAT!
 818                 */
 819                ip_vs_rs_hash(ipvs, dest);
 820        }
 821        atomic_set(&dest->conn_flags, conn_flags);
 822
 823        /* bind the service */
 824        if (!dest->svc) {
 825                __ip_vs_bind_svc(dest, svc);
 826        } else {
 827                if (dest->svc != svc) {
 828                        __ip_vs_unbind_svc(dest);
 829                        ip_vs_zero_stats(&dest->stats);
 830                        __ip_vs_bind_svc(dest, svc);
 831                }
 832        }
 833
 834        /* set the dest status flags */
 835        dest->flags |= IP_VS_DEST_F_AVAILABLE;
 836
 837        if (udest->u_threshold == 0 || udest->u_threshold > dest->u_threshold)
 838                dest->flags &= ~IP_VS_DEST_F_OVERLOAD;
 839        dest->u_threshold = udest->u_threshold;
 840        dest->l_threshold = udest->l_threshold;
 841
 842        spin_lock_bh(&dest->dst_lock);
 843        __ip_vs_dst_cache_reset(dest);
 844        spin_unlock_bh(&dest->dst_lock);
 845
 846        if (add) {
 847                ip_vs_start_estimator(svc->net, &dest->stats);
 848                list_add_rcu(&dest->n_list, &svc->destinations);
 849                svc->num_dests++;
 850                sched = rcu_dereference_protected(svc->scheduler, 1);
 851                if (sched && sched->add_dest)
 852                        sched->add_dest(svc, dest);
 853        } else {
 854                sched = rcu_dereference_protected(svc->scheduler, 1);
 855                if (sched && sched->upd_dest)
 856                        sched->upd_dest(svc, dest);
 857        }
 858}
 859
 860
 861/*
 862 *      Create a destination for the given service
 863 */
 864static int
 865ip_vs_new_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest,
 866               struct ip_vs_dest **dest_p)
 867{
 868        struct ip_vs_dest *dest;
 869        unsigned int atype;
 870
 871        EnterFunction(2);
 872
 873#ifdef CONFIG_IP_VS_IPV6
 874        if (svc->af == AF_INET6) {
 875                atype = ipv6_addr_type(&udest->addr.in6);
 876                if ((!(atype & IPV6_ADDR_UNICAST) ||
 877                        atype & IPV6_ADDR_LINKLOCAL) &&
 878                        !__ip_vs_addr_is_local_v6(svc->net, &udest->addr.in6))
 879                        return -EINVAL;
 880        } else
 881#endif
 882        {
 883                atype = inet_addr_type(svc->net, udest->addr.ip);
 884                if (atype != RTN_LOCAL && atype != RTN_UNICAST)
 885                        return -EINVAL;
 886        }
 887
 888        dest = kzalloc(sizeof(struct ip_vs_dest), GFP_KERNEL);
 889        if (dest == NULL)
 890                return -ENOMEM;
 891
 892        dest->stats.cpustats = alloc_percpu(struct ip_vs_cpu_stats);
 893        if (!dest->stats.cpustats)
 894                goto err_alloc;
 895
 896        dest->af = svc->af;
 897        dest->protocol = svc->protocol;
 898        dest->vaddr = svc->addr;
 899        dest->vport = svc->port;
 900        dest->vfwmark = svc->fwmark;
 901        ip_vs_addr_copy(svc->af, &dest->addr, &udest->addr);
 902        dest->port = udest->port;
 903
 904        atomic_set(&dest->activeconns, 0);
 905        atomic_set(&dest->inactconns, 0);
 906        atomic_set(&dest->persistconns, 0);
 907        atomic_set(&dest->refcnt, 1);
 908
 909        INIT_HLIST_NODE(&dest->d_list);
 910        spin_lock_init(&dest->dst_lock);
 911        spin_lock_init(&dest->stats.lock);
 912        __ip_vs_update_dest(svc, dest, udest, 1);
 913
 914        *dest_p = dest;
 915
 916        LeaveFunction(2);
 917        return 0;
 918
 919err_alloc:
 920        kfree(dest);
 921        return -ENOMEM;
 922}
 923
 924
 925/*
 926 *      Add a destination into an existing service
 927 */
 928static int
 929ip_vs_add_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest)
 930{
 931        struct ip_vs_dest *dest;
 932        union nf_inet_addr daddr;
 933        __be16 dport = udest->port;
 934        int ret;
 935
 936        EnterFunction(2);
 937
 938        if (udest->weight < 0) {
 939                pr_err("%s(): server weight less than zero\n", __func__);
 940                return -ERANGE;
 941        }
 942
 943        if (udest->l_threshold > udest->u_threshold) {
 944                pr_err("%s(): lower threshold is higher than upper threshold\n",
 945                        __func__);
 946                return -ERANGE;
 947        }
 948
 949        ip_vs_addr_copy(svc->af, &daddr, &udest->addr);
 950
 951        /* We use function that requires RCU lock */
 952        rcu_read_lock();
 953        dest = ip_vs_lookup_dest(svc, &daddr, dport);
 954        rcu_read_unlock();
 955
 956        if (dest != NULL) {
 957                IP_VS_DBG(1, "%s(): dest already exists\n", __func__);
 958                return -EEXIST;
 959        }
 960
 961        /*
 962         * Check if the dest already exists in the trash and
 963         * is from the same service
 964         */
 965        dest = ip_vs_trash_get_dest(svc, &daddr, dport);
 966
 967        if (dest != NULL) {
 968                IP_VS_DBG_BUF(3, "Get destination %s:%u from trash, "
 969                              "dest->refcnt=%d, service %u/%s:%u\n",
 970                              IP_VS_DBG_ADDR(svc->af, &daddr), ntohs(dport),
 971                              atomic_read(&dest->refcnt),
 972                              dest->vfwmark,
 973                              IP_VS_DBG_ADDR(svc->af, &dest->vaddr),
 974                              ntohs(dest->vport));
 975
 976                __ip_vs_update_dest(svc, dest, udest, 1);
 977                ret = 0;
 978        } else {
 979                /*
 980                 * Allocate and initialize the dest structure
 981                 */
 982                ret = ip_vs_new_dest(svc, udest, &dest);
 983        }
 984        LeaveFunction(2);
 985
 986        return ret;
 987}
 988
 989
 990/*
 991 *      Edit a destination in the given service
 992 */
 993static int
 994ip_vs_edit_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest)
 995{
 996        struct ip_vs_dest *dest;
 997        union nf_inet_addr daddr;
 998        __be16 dport = udest->port;
 999
1000        EnterFunction(2);
1001
1002        if (udest->weight < 0) {
1003                pr_err("%s(): server weight less than zero\n", __func__);
1004                return -ERANGE;
1005        }
1006
1007        if (udest->l_threshold > udest->u_threshold) {
1008                pr_err("%s(): lower threshold is higher than upper threshold\n",
1009                        __func__);
1010                return -ERANGE;
1011        }
1012
1013        ip_vs_addr_copy(svc->af, &daddr, &udest->addr);
1014
1015        /* We use function that requires RCU lock */
1016        rcu_read_lock();
1017        dest = ip_vs_lookup_dest(svc, &daddr, dport);
1018        rcu_read_unlock();
1019
1020        if (dest == NULL) {
1021                IP_VS_DBG(1, "%s(): dest doesn't exist\n", __func__);
1022                return -ENOENT;
1023        }
1024
1025        __ip_vs_update_dest(svc, dest, udest, 0);
1026        LeaveFunction(2);
1027
1028        return 0;
1029}
1030
1031static void ip_vs_dest_wait_readers(struct rcu_head *head)
1032{
1033        struct ip_vs_dest *dest = container_of(head, struct ip_vs_dest,
1034                                               rcu_head);
1035
1036        /* End of grace period after unlinking */
1037        clear_bit(IP_VS_DEST_STATE_REMOVING, &dest->state);
1038}
1039
1040
1041/*
1042 *      Delete a destination (must be already unlinked from the service)
1043 */
1044static void __ip_vs_del_dest(struct net *net, struct ip_vs_dest *dest,
1045                             bool cleanup)
1046{
1047        struct netns_ipvs *ipvs = net_ipvs(net);
1048
1049        ip_vs_stop_estimator(net, &dest->stats);
1050
1051        /*
1052         *  Remove it from the d-linked list with the real services.
1053         */
1054        ip_vs_rs_unhash(dest);
1055
1056        if (!cleanup) {
1057                set_bit(IP_VS_DEST_STATE_REMOVING, &dest->state);
1058                call_rcu(&dest->rcu_head, ip_vs_dest_wait_readers);
1059        }
1060
1061        spin_lock_bh(&ipvs->dest_trash_lock);
1062        IP_VS_DBG_BUF(3, "Moving dest %s:%u into trash, dest->refcnt=%d\n",
1063                      IP_VS_DBG_ADDR(dest->af, &dest->addr), ntohs(dest->port),
1064                      atomic_read(&dest->refcnt));
1065        if (list_empty(&ipvs->dest_trash) && !cleanup)
1066                mod_timer(&ipvs->dest_trash_timer,
1067                          jiffies + IP_VS_DEST_TRASH_PERIOD);
1068        /* dest lives in trash without reference */
1069        list_add(&dest->t_list, &ipvs->dest_trash);
1070        spin_unlock_bh(&ipvs->dest_trash_lock);
1071        ip_vs_dest_put(dest);
1072}
1073
1074
1075/*
1076 *      Unlink a destination from the given service
1077 */
1078static void __ip_vs_unlink_dest(struct ip_vs_service *svc,
1079                                struct ip_vs_dest *dest,
1080                                int svcupd)
1081{
1082        dest->flags &= ~IP_VS_DEST_F_AVAILABLE;
1083
1084        /*
1085         *  Remove it from the d-linked destination list.
1086         */
1087        list_del_rcu(&dest->n_list);
1088        svc->num_dests--;
1089
1090        if (svcupd) {
1091                struct ip_vs_scheduler *sched;
1092
1093                sched = rcu_dereference_protected(svc->scheduler, 1);
1094                if (sched && sched->del_dest)
1095                        sched->del_dest(svc, dest);
1096        }
1097}
1098
1099
1100/*
1101 *      Delete a destination server in the given service
1102 */
1103static int
1104ip_vs_del_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest)
1105{
1106        struct ip_vs_dest *dest;
1107        __be16 dport = udest->port;
1108
1109        EnterFunction(2);
1110
1111        /* We use function that requires RCU lock */
1112        rcu_read_lock();
1113        dest = ip_vs_lookup_dest(svc, &udest->addr, dport);
1114        rcu_read_unlock();
1115
1116        if (dest == NULL) {
1117                IP_VS_DBG(1, "%s(): destination not found!\n", __func__);
1118                return -ENOENT;
1119        }
1120
1121        /*
1122         *      Unlink dest from the service
1123         */
1124        __ip_vs_unlink_dest(svc, dest, 1);
1125
1126        /*
1127         *      Delete the destination
1128         */
1129        __ip_vs_del_dest(svc->net, dest, false);
1130
1131        LeaveFunction(2);
1132
1133        return 0;
1134}
1135
1136static void ip_vs_dest_trash_expire(unsigned long data)
1137{
1138        struct net *net = (struct net *) data;
1139        struct netns_ipvs *ipvs = net_ipvs(net);
1140        struct ip_vs_dest *dest, *next;
1141
1142        spin_lock(&ipvs->dest_trash_lock);
1143        list_for_each_entry_safe(dest, next, &ipvs->dest_trash, t_list) {
1144                /* Skip if dest is in grace period */
1145                if (test_bit(IP_VS_DEST_STATE_REMOVING, &dest->state))
1146                        continue;
1147                if (atomic_read(&dest->refcnt) > 0)
1148                        continue;
1149                IP_VS_DBG_BUF(3, "Removing destination %u/%s:%u from trash\n",
1150                              dest->vfwmark,
1151                              IP_VS_DBG_ADDR(dest->svc->af, &dest->addr),
1152                              ntohs(dest->port));
1153                list_del(&dest->t_list);
1154                ip_vs_dest_free(dest);
1155        }
1156        if (!list_empty(&ipvs->dest_trash))
1157                mod_timer(&ipvs->dest_trash_timer,
1158                          jiffies + IP_VS_DEST_TRASH_PERIOD);
1159        spin_unlock(&ipvs->dest_trash_lock);
1160}
1161
1162/*
1163 *      Add a service into the service hash table
1164 */
1165static int
1166ip_vs_add_service(struct net *net, struct ip_vs_service_user_kern *u,
1167                  struct ip_vs_service **svc_p)
1168{
1169        int ret = 0;
1170        struct ip_vs_scheduler *sched = NULL;
1171        struct ip_vs_pe *pe = NULL;
1172        struct ip_vs_service *svc = NULL;
1173        struct netns_ipvs *ipvs = net_ipvs(net);
1174
1175        /* increase the module use count */
1176        ip_vs_use_count_inc();
1177
1178        /* Lookup the scheduler by 'u->sched_name' */
1179        if (strcmp(u->sched_name, "none")) {
1180                sched = ip_vs_scheduler_get(u->sched_name);
1181                if (!sched) {
1182                        pr_info("Scheduler module ip_vs_%s not found\n",
1183                                u->sched_name);
1184                        ret = -ENOENT;
1185                        goto out_err;
1186                }
1187        }
1188
1189        if (u->pe_name && *u->pe_name) {
1190                pe = ip_vs_pe_getbyname(u->pe_name);
1191                if (pe == NULL) {
1192                        pr_info("persistence engine module ip_vs_pe_%s "
1193                                "not found\n", u->pe_name);
1194                        ret = -ENOENT;
1195                        goto out_err;
1196                }
1197        }
1198
1199#ifdef CONFIG_IP_VS_IPV6
1200        if (u->af == AF_INET6) {
1201                __u32 plen = (__force __u32) u->netmask;
1202
1203                if (plen < 1 || plen > 128) {
1204                        ret = -EINVAL;
1205                        goto out_err;
1206                }
1207        }
1208#endif
1209
1210        svc = kzalloc(sizeof(struct ip_vs_service), GFP_KERNEL);
1211        if (svc == NULL) {
1212                IP_VS_DBG(1, "%s(): no memory\n", __func__);
1213                ret = -ENOMEM;
1214                goto out_err;
1215        }
1216        svc->stats.cpustats = alloc_percpu(struct ip_vs_cpu_stats);
1217        if (!svc->stats.cpustats) {
1218                ret = -ENOMEM;
1219                goto out_err;
1220        }
1221
1222        /* I'm the first user of the service */
1223        atomic_set(&svc->refcnt, 0);
1224
1225        svc->af = u->af;
1226        svc->protocol = u->protocol;
1227        ip_vs_addr_copy(svc->af, &svc->addr, &u->addr);
1228        svc->port = u->port;
1229        svc->fwmark = u->fwmark;
1230        svc->flags = u->flags;
1231        svc->timeout = u->timeout * HZ;
1232        svc->netmask = u->netmask;
1233        svc->net = net;
1234
1235        INIT_LIST_HEAD(&svc->destinations);
1236        spin_lock_init(&svc->sched_lock);
1237        spin_lock_init(&svc->stats.lock);
1238
1239        /* Bind the scheduler */
1240        if (sched) {
1241                ret = ip_vs_bind_scheduler(svc, sched);
1242                if (ret)
1243                        goto out_err;
1244                sched = NULL;
1245        }
1246
1247        /* Bind the ct retriever */
1248        RCU_INIT_POINTER(svc->pe, pe);
1249        pe = NULL;
1250
1251        /* Update the virtual service counters */
1252        if (svc->port == FTPPORT)
1253                atomic_inc(&ipvs->ftpsvc_counter);
1254        else if (svc->port == 0)
1255                atomic_inc(&ipvs->nullsvc_counter);
1256        if (svc->pe && svc->pe->conn_out)
1257                atomic_inc(&ipvs->conn_out_counter);
1258
1259        ip_vs_start_estimator(net, &svc->stats);
1260
1261        /* Count only IPv4 services for old get/setsockopt interface */
1262        if (svc->af == AF_INET)
1263                ipvs->num_services++;
1264
1265        /* Hash the service into the service table */
1266        ip_vs_svc_hash(svc);
1267
1268        *svc_p = svc;
1269        /* Now there is a service - full throttle */
1270        ipvs->enable = 1;
1271        return 0;
1272
1273
1274 out_err:
1275        if (svc != NULL) {
1276                ip_vs_unbind_scheduler(svc, sched);
1277                ip_vs_service_free(svc);
1278        }
1279        ip_vs_scheduler_put(sched);
1280        ip_vs_pe_put(pe);
1281
1282        /* decrease the module use count */
1283        ip_vs_use_count_dec();
1284
1285        return ret;
1286}
1287
1288
1289/*
1290 *      Edit a service and bind it with a new scheduler
1291 */
1292static int
1293ip_vs_edit_service(struct ip_vs_service *svc, struct ip_vs_service_user_kern *u)
1294{
1295        struct ip_vs_scheduler *sched = NULL, *old_sched;
1296        struct ip_vs_pe *pe = NULL, *old_pe = NULL;
1297        int ret = 0;
1298        bool new_pe_conn_out, old_pe_conn_out;
1299
1300        /*
1301         * Lookup the scheduler, by 'u->sched_name'
1302         */
1303        if (strcmp(u->sched_name, "none")) {
1304                sched = ip_vs_scheduler_get(u->sched_name);
1305                if (!sched) {
1306                        pr_info("Scheduler module ip_vs_%s not found\n",
1307                                u->sched_name);
1308                        return -ENOENT;
1309                }
1310        }
1311        old_sched = sched;
1312
1313        if (u->pe_name && *u->pe_name) {
1314                pe = ip_vs_pe_getbyname(u->pe_name);
1315                if (pe == NULL) {
1316                        pr_info("persistence engine module ip_vs_pe_%s "
1317                                "not found\n", u->pe_name);
1318                        ret = -ENOENT;
1319                        goto out;
1320                }
1321                old_pe = pe;
1322        }
1323
1324#ifdef CONFIG_IP_VS_IPV6
1325        if (u->af == AF_INET6) {
1326                __u32 plen = (__force __u32) u->netmask;
1327
1328                if (plen < 1 || plen > 128) {
1329                        ret = -EINVAL;
1330                        goto out;
1331                }
1332        }
1333#endif
1334
1335        old_sched = rcu_dereference_protected(svc->scheduler, 1);
1336        if (sched != old_sched) {
1337                if (old_sched) {
1338                        ip_vs_unbind_scheduler(svc, old_sched);
1339                        RCU_INIT_POINTER(svc->scheduler, NULL);
1340                        /* Wait all svc->sched_data users */
1341                        synchronize_rcu();
1342                }
1343                /* Bind the new scheduler */
1344                if (sched) {
1345                        ret = ip_vs_bind_scheduler(svc, sched);
1346                        if (ret) {
1347                                ip_vs_scheduler_put(sched);
1348                                goto out;
1349                        }
1350                }
1351        }
1352
1353        /*
1354         * Set the flags and timeout value
1355         */
1356        svc->flags = u->flags | IP_VS_SVC_F_HASHED;
1357        svc->timeout = u->timeout * HZ;
1358        svc->netmask = u->netmask;
1359
1360        old_pe = rcu_dereference_protected(svc->pe, 1);
1361        if (pe != old_pe) {
1362                rcu_assign_pointer(svc->pe, pe);
1363                /* check for optional methods in new pe */
1364                new_pe_conn_out = (pe && pe->conn_out) ? true : false;
1365                old_pe_conn_out = (old_pe && old_pe->conn_out) ? true : false;
1366                if (new_pe_conn_out && !old_pe_conn_out)
1367                        atomic_inc(&net_ipvs(svc->net)->conn_out_counter);
1368                if (old_pe_conn_out && !new_pe_conn_out)
1369                        atomic_dec(&net_ipvs(svc->net)->conn_out_counter);
1370        }
1371
1372out:
1373        ip_vs_scheduler_put(old_sched);
1374        ip_vs_pe_put(old_pe);
1375        return ret;
1376}
1377
1378static void ip_vs_service_rcu_free(struct rcu_head *head)
1379{
1380        struct ip_vs_service *svc;
1381
1382        svc = container_of(head, struct ip_vs_service, rcu_head);
1383        ip_vs_service_free(svc);
1384}
1385
1386/*
1387 *      Delete a service from the service list
1388 *      - The service must be unlinked, unlocked and not referenced!
1389 *      - We are called under _bh lock
1390 */
1391static void __ip_vs_del_service(struct ip_vs_service *svc, bool cleanup)
1392{
1393        struct ip_vs_dest *dest, *nxt;
1394        struct ip_vs_scheduler *old_sched;
1395        struct ip_vs_pe *old_pe;
1396        struct netns_ipvs *ipvs = net_ipvs(svc->net);
1397
1398        /* Count only IPv4 services for old get/setsockopt interface */
1399        if (svc->af == AF_INET)
1400                ipvs->num_services--;
1401
1402        ip_vs_stop_estimator(svc->net, &svc->stats);
1403
1404        /* Unbind scheduler */
1405        old_sched = rcu_dereference_protected(svc->scheduler, 1);
1406        ip_vs_unbind_scheduler(svc, old_sched);
1407        ip_vs_scheduler_put(old_sched);
1408
1409        /* Unbind persistence engine, keep svc->pe */
1410        old_pe = rcu_dereference_protected(svc->pe, 1);
1411        if (old_pe && old_pe->conn_out)
1412                atomic_dec(&ipvs->conn_out_counter);
1413        ip_vs_pe_put(old_pe);
1414
1415        /*
1416         *    Unlink the whole destination list
1417         */
1418        list_for_each_entry_safe(dest, nxt, &svc->destinations, n_list) {
1419                __ip_vs_unlink_dest(svc, dest, 0);
1420                __ip_vs_del_dest(svc->net, dest, cleanup);
1421        }
1422
1423        /*
1424         *    Update the virtual service counters
1425         */
1426        if (svc->port == FTPPORT)
1427                atomic_dec(&ipvs->ftpsvc_counter);
1428        else if (svc->port == 0)
1429                atomic_dec(&ipvs->nullsvc_counter);
1430
1431        /*
1432         *    Free the service if nobody refers to it
1433         */
1434        if (atomic_dec_and_test(&svc->refcnt)) {
1435                IP_VS_DBG_BUF(3, "Removing service %u/%s:%u\n",
1436                              svc->fwmark,
1437                              IP_VS_DBG_ADDR(svc->af, &svc->addr),
1438                              ntohs(svc->port));
1439                call_rcu(&svc->rcu_head, ip_vs_service_rcu_free);
1440        }
1441
1442        /* decrease the module use count */
1443        ip_vs_use_count_dec();
1444}
1445
1446/*
1447 * Unlink a service from list and try to delete it if its refcnt reached 0
1448 */
1449static void ip_vs_unlink_service(struct ip_vs_service *svc, bool cleanup)
1450{
1451        /* Hold svc to avoid double release from dest_trash */
1452        atomic_inc(&svc->refcnt);
1453        /*
1454         * Unhash it from the service table
1455         */
1456        ip_vs_svc_unhash(svc);
1457
1458        __ip_vs_del_service(svc, cleanup);
1459}
1460
1461/*
1462 *      Delete a service from the service list
1463 */
1464static int ip_vs_del_service(struct ip_vs_service *svc)
1465{
1466        if (svc == NULL)
1467                return -EEXIST;
1468        ip_vs_unlink_service(svc, false);
1469
1470        return 0;
1471}
1472
1473
1474/*
1475 *      Flush all the virtual services
1476 */
1477static int ip_vs_flush(struct net *net, bool cleanup)
1478{
1479        int idx;
1480        struct ip_vs_service *svc;
1481        struct hlist_node *n;
1482
1483        /*
1484         * Flush the service table hashed by <netns,protocol,addr,port>
1485         */
1486        for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1487                hlist_for_each_entry_safe(svc, n, &ip_vs_svc_table[idx],
1488                                          s_list) {
1489                        if (net_eq(svc->net, net))
1490                                ip_vs_unlink_service(svc, cleanup);
1491                }
1492        }
1493
1494        /*
1495         * Flush the service table hashed by fwmark
1496         */
1497        for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1498                hlist_for_each_entry_safe(svc, n, &ip_vs_svc_fwm_table[idx],
1499                                          f_list) {
1500                        if (net_eq(svc->net, net))
1501                                ip_vs_unlink_service(svc, cleanup);
1502                }
1503        }
1504
1505        return 0;
1506}
1507
1508/*
1509 *      Delete service by {netns} in the service table.
1510 *      Called by __ip_vs_cleanup()
1511 */
1512void ip_vs_service_net_cleanup(struct net *net)
1513{
1514        EnterFunction(2);
1515        /* Check for "full" addressed entries */
1516        mutex_lock(&__ip_vs_mutex);
1517        ip_vs_flush(net, true);
1518        mutex_unlock(&__ip_vs_mutex);
1519        LeaveFunction(2);
1520}
1521
1522/* Put all references for device (dst_cache) */
1523static inline void
1524ip_vs_forget_dev(struct ip_vs_dest *dest, struct net_device *dev)
1525{
1526        struct ip_vs_dest_dst *dest_dst;
1527
1528        spin_lock_bh(&dest->dst_lock);
1529        dest_dst = rcu_dereference_protected(dest->dest_dst, 1);
1530        if (dest_dst && dest_dst->dst_cache->dev == dev) {
1531                IP_VS_DBG_BUF(3, "Reset dev:%s dest %s:%u ,dest->refcnt=%d\n",
1532                              dev->name,
1533                              IP_VS_DBG_ADDR(dest->af, &dest->addr),
1534                              ntohs(dest->port),
1535                              atomic_read(&dest->refcnt));
1536                __ip_vs_dst_cache_reset(dest);
1537        }
1538        spin_unlock_bh(&dest->dst_lock);
1539
1540}
1541/* Netdev event receiver
1542 * Currently only NETDEV_DOWN is handled to release refs to cached dsts
1543 */
1544static int ip_vs_dst_event(struct notifier_block *this, unsigned long event,
1545                           void *ptr)
1546{
1547        struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1548        struct net *net = dev_net(dev);
1549        struct netns_ipvs *ipvs = net_ipvs(net);
1550        struct ip_vs_service *svc;
1551        struct ip_vs_dest *dest;
1552        unsigned int idx;
1553
1554        if (event != NETDEV_DOWN || !ipvs)
1555                return NOTIFY_DONE;
1556        IP_VS_DBG(3, "%s() dev=%s\n", __func__, dev->name);
1557        EnterFunction(2);
1558        mutex_lock(&__ip_vs_mutex);
1559        for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1560                hlist_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) {
1561                        if (net_eq(svc->net, net)) {
1562                                list_for_each_entry(dest, &svc->destinations,
1563                                                    n_list) {
1564                                        ip_vs_forget_dev(dest, dev);
1565                                }
1566                        }
1567                }
1568
1569                hlist_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) {
1570                        if (net_eq(svc->net, net)) {
1571                                list_for_each_entry(dest, &svc->destinations,
1572                                                    n_list) {
1573                                        ip_vs_forget_dev(dest, dev);
1574                                }
1575                        }
1576
1577                }
1578        }
1579
1580        spin_lock_bh(&ipvs->dest_trash_lock);
1581        list_for_each_entry(dest, &ipvs->dest_trash, t_list) {
1582                ip_vs_forget_dev(dest, dev);
1583        }
1584        spin_unlock_bh(&ipvs->dest_trash_lock);
1585        mutex_unlock(&__ip_vs_mutex);
1586        LeaveFunction(2);
1587        return NOTIFY_DONE;
1588}
1589
1590/*
1591 *      Zero counters in a service or all services
1592 */
1593static int ip_vs_zero_service(struct ip_vs_service *svc)
1594{
1595        struct ip_vs_dest *dest;
1596
1597        list_for_each_entry(dest, &svc->destinations, n_list) {
1598                ip_vs_zero_stats(&dest->stats);
1599        }
1600        ip_vs_zero_stats(&svc->stats);
1601        return 0;
1602}
1603
1604static int ip_vs_zero_all(struct net *net)
1605{
1606        int idx;
1607        struct ip_vs_service *svc;
1608
1609        for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1610                hlist_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) {
1611                        if (net_eq(svc->net, net))
1612                                ip_vs_zero_service(svc);
1613                }
1614        }
1615
1616        for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1617                hlist_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) {
1618                        if (net_eq(svc->net, net))
1619                                ip_vs_zero_service(svc);
1620                }
1621        }
1622
1623        ip_vs_zero_stats(&net_ipvs(net)->tot_stats);
1624        return 0;
1625}
1626
1627#ifdef CONFIG_SYSCTL
1628
1629static int zero;
1630static int three = 3;
1631
1632static int
1633proc_do_defense_mode(struct ctl_table *table, int write,
1634                     void __user *buffer, size_t *lenp, loff_t *ppos)
1635{
1636        struct net *net = current->nsproxy->net_ns;
1637        int *valp = table->data;
1638        int val = *valp;
1639        int rc;
1640
1641        rc = proc_dointvec(table, write, buffer, lenp, ppos);
1642        if (write && (*valp != val)) {
1643                if ((*valp < 0) || (*valp > 3)) {
1644                        /* Restore the correct value */
1645                        *valp = val;
1646                } else {
1647                        update_defense_level(net_ipvs(net));
1648                }
1649        }
1650        return rc;
1651}
1652
1653static int
1654proc_do_sync_threshold(struct ctl_table *table, int write,
1655                       void __user *buffer, size_t *lenp, loff_t *ppos)
1656{
1657        int *valp = table->data;
1658        int val[2];
1659        int rc;
1660
1661        /* backup the value first */
1662        memcpy(val, valp, sizeof(val));
1663
1664        rc = proc_dointvec(table, write, buffer, lenp, ppos);
1665        if (write && (valp[0] < 0 || valp[1] < 0 ||
1666            (valp[0] >= valp[1] && valp[1]))) {
1667                /* Restore the correct value */
1668                memcpy(valp, val, sizeof(val));
1669        }
1670        return rc;
1671}
1672
1673static int
1674proc_do_sync_mode(struct ctl_table *table, int write,
1675                     void __user *buffer, size_t *lenp, loff_t *ppos)
1676{
1677        int *valp = table->data;
1678        int val = *valp;
1679        int rc;
1680
1681        rc = proc_dointvec(table, write, buffer, lenp, ppos);
1682        if (write && (*valp != val)) {
1683                if ((*valp < 0) || (*valp > 1)) {
1684                        /* Restore the correct value */
1685                        *valp = val;
1686                }
1687        }
1688        return rc;
1689}
1690
1691static int
1692proc_do_sync_ports(struct ctl_table *table, int write,
1693                   void __user *buffer, size_t *lenp, loff_t *ppos)
1694{
1695        int *valp = table->data;
1696        int val = *valp;
1697        int rc;
1698
1699        rc = proc_dointvec(table, write, buffer, lenp, ppos);
1700        if (write && (*valp != val)) {
1701                if (*valp < 1 || !is_power_of_2(*valp)) {
1702                        /* Restore the correct value */
1703                        *valp = val;
1704                }
1705        }
1706        return rc;
1707}
1708
1709/*
1710 *      IPVS sysctl table (under the /proc/sys/net/ipv4/vs/)
1711 *      Do not change order or insert new entries without
1712 *      align with netns init in ip_vs_control_net_init()
1713 */
1714
1715static struct ctl_table vs_vars[] = {
1716        {
1717                .procname       = "amemthresh",
1718                .maxlen         = sizeof(int),
1719                .mode           = 0644,
1720                .proc_handler   = proc_dointvec,
1721        },
1722        {
1723                .procname       = "am_droprate",
1724                .maxlen         = sizeof(int),
1725                .mode           = 0644,
1726                .proc_handler   = proc_dointvec,
1727        },
1728        {
1729                .procname       = "drop_entry",
1730                .maxlen         = sizeof(int),
1731                .mode           = 0644,
1732                .proc_handler   = proc_do_defense_mode,
1733        },
1734        {
1735                .procname       = "drop_packet",
1736                .maxlen         = sizeof(int),
1737                .mode           = 0644,
1738                .proc_handler   = proc_do_defense_mode,
1739        },
1740#ifdef CONFIG_IP_VS_NFCT
1741        {
1742                .procname       = "conntrack",
1743                .maxlen         = sizeof(int),
1744                .mode           = 0644,
1745                .proc_handler   = &proc_dointvec,
1746        },
1747#endif
1748        {
1749                .procname       = "secure_tcp",
1750                .maxlen         = sizeof(int),
1751                .mode           = 0644,
1752                .proc_handler   = proc_do_defense_mode,
1753        },
1754        {
1755                .procname       = "snat_reroute",
1756                .maxlen         = sizeof(int),
1757                .mode           = 0644,
1758                .proc_handler   = &proc_dointvec,
1759        },
1760        {
1761                .procname       = "sync_version",
1762                .maxlen         = sizeof(int),
1763                .mode           = 0644,
1764                .proc_handler   = &proc_do_sync_mode,
1765        },
1766        {
1767                .procname       = "sync_ports",
1768                .maxlen         = sizeof(int),
1769                .mode           = 0644,
1770                .proc_handler   = &proc_do_sync_ports,
1771        },
1772        {
1773                .procname       = "sync_qlen_max",
1774                .maxlen         = sizeof(int),
1775                .mode           = 0644,
1776                .proc_handler   = proc_dointvec,
1777        },
1778        {
1779                .procname       = "sync_sock_size",
1780                .maxlen         = sizeof(int),
1781                .mode           = 0644,
1782                .proc_handler   = proc_dointvec,
1783        },
1784        {
1785                .procname       = "cache_bypass",
1786                .maxlen         = sizeof(int),
1787                .mode           = 0644,
1788                .proc_handler   = proc_dointvec,
1789        },
1790        {
1791                .procname       = "expire_nodest_conn",
1792                .maxlen         = sizeof(int),
1793                .mode           = 0644,
1794                .proc_handler   = proc_dointvec,
1795        },
1796        {
1797                .procname       = "expire_quiescent_template",
1798                .maxlen         = sizeof(int),
1799                .mode           = 0644,
1800                .proc_handler   = proc_dointvec,
1801        },
1802        {
1803                .procname       = "sync_threshold",
1804                .maxlen         =
1805                        sizeof(((struct netns_ipvs *)0)->sysctl_sync_threshold),
1806                .mode           = 0644,
1807                .proc_handler   = proc_do_sync_threshold,
1808        },
1809        {
1810                .procname       = "sync_refresh_period",
1811                .maxlen         = sizeof(int),
1812                .mode           = 0644,
1813                .proc_handler   = proc_dointvec_jiffies,
1814        },
1815        {
1816                .procname       = "sync_retries",
1817                .maxlen         = sizeof(int),
1818                .mode           = 0644,
1819                .proc_handler   = proc_dointvec_minmax,
1820                .extra1         = &zero,
1821                .extra2         = &three,
1822        },
1823        {
1824                .procname       = "nat_icmp_send",
1825                .maxlen         = sizeof(int),
1826                .mode           = 0644,
1827                .proc_handler   = proc_dointvec,
1828        },
1829        {
1830                .procname       = "pmtu_disc",
1831                .maxlen         = sizeof(int),
1832                .mode           = 0644,
1833                .proc_handler   = proc_dointvec,
1834        },
1835        {
1836                .procname       = "backup_only",
1837                .maxlen         = sizeof(int),
1838                .mode           = 0644,
1839                .proc_handler   = proc_dointvec,
1840        },
1841        {
1842                .procname       = "conn_reuse_mode",
1843                .maxlen         = sizeof(int),
1844                .mode           = 0644,
1845                .proc_handler   = proc_dointvec,
1846        },
1847#ifdef CONFIG_IP_VS_DEBUG
1848        {
1849                .procname       = "debug_level",
1850                .data           = &sysctl_ip_vs_debug_level,
1851                .maxlen         = sizeof(int),
1852                .mode           = 0644,
1853                .proc_handler   = proc_dointvec,
1854        },
1855#endif
1856#if 0
1857        {
1858                .procname       = "timeout_established",
1859                .data   = &vs_timeout_table_dos.timeout[IP_VS_S_ESTABLISHED],
1860                .maxlen         = sizeof(int),
1861                .mode           = 0644,
1862                .proc_handler   = proc_dointvec_jiffies,
1863        },
1864        {
1865                .procname       = "timeout_synsent",
1866                .data   = &vs_timeout_table_dos.timeout[IP_VS_S_SYN_SENT],
1867                .maxlen         = sizeof(int),
1868                .mode           = 0644,
1869                .proc_handler   = proc_dointvec_jiffies,
1870        },
1871        {
1872                .procname       = "timeout_synrecv",
1873                .data   = &vs_timeout_table_dos.timeout[IP_VS_S_SYN_RECV],
1874                .maxlen         = sizeof(int),
1875                .mode           = 0644,
1876                .proc_handler   = proc_dointvec_jiffies,
1877        },
1878        {
1879                .procname       = "timeout_finwait",
1880                .data   = &vs_timeout_table_dos.timeout[IP_VS_S_FIN_WAIT],
1881                .maxlen         = sizeof(int),
1882                .mode           = 0644,
1883                .proc_handler   = proc_dointvec_jiffies,
1884        },
1885        {
1886                .procname       = "timeout_timewait",
1887                .data   = &vs_timeout_table_dos.timeout[IP_VS_S_TIME_WAIT],
1888                .maxlen         = sizeof(int),
1889                .mode           = 0644,
1890                .proc_handler   = proc_dointvec_jiffies,
1891        },
1892        {
1893                .procname       = "timeout_close",
1894                .data   = &vs_timeout_table_dos.timeout[IP_VS_S_CLOSE],
1895                .maxlen         = sizeof(int),
1896                .mode           = 0644,
1897                .proc_handler   = proc_dointvec_jiffies,
1898        },
1899        {
1900                .procname       = "timeout_closewait",
1901                .data   = &vs_timeout_table_dos.timeout[IP_VS_S_CLOSE_WAIT],
1902                .maxlen         = sizeof(int),
1903                .mode           = 0644,
1904                .proc_handler   = proc_dointvec_jiffies,
1905        },
1906        {
1907                .procname       = "timeout_lastack",
1908                .data   = &vs_timeout_table_dos.timeout[IP_VS_S_LAST_ACK],
1909                .maxlen         = sizeof(int),
1910                .mode           = 0644,
1911                .proc_handler   = proc_dointvec_jiffies,
1912        },
1913        {
1914                .procname       = "timeout_listen",
1915                .data   = &vs_timeout_table_dos.timeout[IP_VS_S_LISTEN],
1916                .maxlen         = sizeof(int),
1917                .mode           = 0644,
1918                .proc_handler   = proc_dointvec_jiffies,
1919        },
1920        {
1921                .procname       = "timeout_synack",
1922                .data   = &vs_timeout_table_dos.timeout[IP_VS_S_SYNACK],
1923                .maxlen         = sizeof(int),
1924                .mode           = 0644,
1925                .proc_handler   = proc_dointvec_jiffies,
1926        },
1927        {
1928                .procname       = "timeout_udp",
1929                .data   = &vs_timeout_table_dos.timeout[IP_VS_S_UDP],
1930                .maxlen         = sizeof(int),
1931                .mode           = 0644,
1932                .proc_handler   = proc_dointvec_jiffies,
1933        },
1934        {
1935                .procname       = "timeout_icmp",
1936                .data   = &vs_timeout_table_dos.timeout[IP_VS_S_ICMP],
1937                .maxlen         = sizeof(int),
1938                .mode           = 0644,
1939                .proc_handler   = proc_dointvec_jiffies,
1940        },
1941#endif
1942        { }
1943};
1944
1945#endif
1946
1947#ifdef CONFIG_PROC_FS
1948
1949struct ip_vs_iter {
1950        struct seq_net_private p;  /* Do not move this, netns depends upon it*/
1951        struct hlist_head *table;
1952        int bucket;
1953};
1954
1955/*
1956 *      Write the contents of the VS rule table to a PROCfs file.
1957 *      (It is kept just for backward compatibility)
1958 */
1959static inline const char *ip_vs_fwd_name(unsigned int flags)
1960{
1961        switch (flags & IP_VS_CONN_F_FWD_MASK) {
1962        case IP_VS_CONN_F_LOCALNODE:
1963                return "Local";
1964        case IP_VS_CONN_F_TUNNEL:
1965                return "Tunnel";
1966        case IP_VS_CONN_F_DROUTE:
1967                return "Route";
1968        default:
1969                return "Masq";
1970        }
1971}
1972
1973
1974/* Get the Nth entry in the two lists */
1975static struct ip_vs_service *ip_vs_info_array(struct seq_file *seq, loff_t pos)
1976{
1977        struct net *net = seq_file_net(seq);
1978        struct ip_vs_iter *iter = seq->private;
1979        int idx;
1980        struct ip_vs_service *svc;
1981
1982        /* look in hash by protocol */
1983        for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1984                hlist_for_each_entry_rcu(svc, &ip_vs_svc_table[idx], s_list) {
1985                        if (net_eq(svc->net, net) && pos-- == 0) {
1986                                iter->table = ip_vs_svc_table;
1987                                iter->bucket = idx;
1988                                return svc;
1989                        }
1990                }
1991        }
1992
1993        /* keep looking in fwmark */
1994        for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1995                hlist_for_each_entry_rcu(svc, &ip_vs_svc_fwm_table[idx],
1996                                         f_list) {
1997                        if (net_eq(svc->net, net) && pos-- == 0) {
1998                                iter->table = ip_vs_svc_fwm_table;
1999                                iter->bucket = idx;
2000                                return svc;
2001                        }
2002                }
2003        }
2004
2005        return NULL;
2006}
2007
2008static void *ip_vs_info_seq_start(struct seq_file *seq, loff_t *pos)
2009        __acquires(RCU)
2010{
2011        rcu_read_lock();
2012        return *pos ? ip_vs_info_array(seq, *pos - 1) : SEQ_START_TOKEN;
2013}
2014
2015
2016static void *ip_vs_info_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2017{
2018        struct hlist_node *e;
2019        struct ip_vs_iter *iter;
2020        struct ip_vs_service *svc;
2021
2022        ++*pos;
2023        if (v == SEQ_START_TOKEN)
2024                return ip_vs_info_array(seq,0);
2025
2026        svc = v;
2027        iter = seq->private;
2028
2029        if (iter->table == ip_vs_svc_table) {
2030                /* next service in table hashed by protocol */
2031                e = rcu_dereference(hlist_next_rcu(&svc->s_list));
2032                if (e)
2033                        return hlist_entry(e, struct ip_vs_service, s_list);
2034
2035                while (++iter->bucket < IP_VS_SVC_TAB_SIZE) {
2036                        hlist_for_each_entry_rcu(svc,
2037                                                 &ip_vs_svc_table[iter->bucket],
2038                                                 s_list) {
2039                                return svc;
2040                        }
2041                }
2042
2043                iter->table = ip_vs_svc_fwm_table;
2044                iter->bucket = -1;
2045                goto scan_fwmark;
2046        }
2047
2048        /* next service in hashed by fwmark */
2049        e = rcu_dereference(hlist_next_rcu(&svc->f_list));
2050        if (e)
2051                return hlist_entry(e, struct ip_vs_service, f_list);
2052
2053 scan_fwmark:
2054        while (++iter->bucket < IP_VS_SVC_TAB_SIZE) {
2055                hlist_for_each_entry_rcu(svc,
2056                                         &ip_vs_svc_fwm_table[iter->bucket],
2057                                         f_list)
2058                        return svc;
2059        }
2060
2061        return NULL;
2062}
2063
2064static void ip_vs_info_seq_stop(struct seq_file *seq, void *v)
2065        __releases(RCU)
2066{
2067        rcu_read_unlock();
2068}
2069
2070
2071static int ip_vs_info_seq_show(struct seq_file *seq, void *v)
2072{
2073        if (v == SEQ_START_TOKEN) {
2074                seq_printf(seq,
2075                        "IP Virtual Server version %d.%d.%d (size=%d)\n",
2076                        NVERSION(IP_VS_VERSION_CODE), ip_vs_conn_tab_size);
2077                seq_puts(seq,
2078                         "Prot LocalAddress:Port Scheduler Flags\n");
2079                seq_puts(seq,
2080                         "  -> RemoteAddress:Port Forward Weight ActiveConn InActConn\n");
2081        } else {
2082                const struct ip_vs_service *svc = v;
2083                const struct ip_vs_iter *iter = seq->private;
2084                const struct ip_vs_dest *dest;
2085                struct ip_vs_scheduler *sched = rcu_dereference(svc->scheduler);
2086                char *sched_name = sched ? sched->name : "none";
2087
2088                if (iter->table == ip_vs_svc_table) {
2089#ifdef CONFIG_IP_VS_IPV6
2090                        if (svc->af == AF_INET6)
2091                                seq_printf(seq, "%s  [%pI6]:%04X %s ",
2092                                           ip_vs_proto_name(svc->protocol),
2093                                           &svc->addr.in6,
2094                                           ntohs(svc->port),
2095                                           sched_name);
2096                        else
2097#endif
2098                                seq_printf(seq, "%s  %08X:%04X %s %s ",
2099                                           ip_vs_proto_name(svc->protocol),
2100                                           ntohl(svc->addr.ip),
2101                                           ntohs(svc->port),
2102                                           sched_name,
2103                                           (svc->flags & IP_VS_SVC_F_ONEPACKET)?"ops ":"");
2104                } else {
2105                        seq_printf(seq, "FWM  %08X %s %s",
2106                                   svc->fwmark, sched_name,
2107                                   (svc->flags & IP_VS_SVC_F_ONEPACKET)?"ops ":"");
2108                }
2109
2110                if (svc->flags & IP_VS_SVC_F_PERSISTENT)
2111                        seq_printf(seq, "persistent %d %08X\n",
2112                                svc->timeout,
2113                                ntohl(svc->netmask));
2114                else
2115                        seq_putc(seq, '\n');
2116
2117                list_for_each_entry_rcu(dest, &svc->destinations, n_list) {
2118#ifdef CONFIG_IP_VS_IPV6
2119                        if (dest->af == AF_INET6)
2120                                seq_printf(seq,
2121                                           "  -> [%pI6]:%04X"
2122                                           "      %-7s %-6d %-10d %-10d\n",
2123                                           &dest->addr.in6,
2124                                           ntohs(dest->port),
2125                                           ip_vs_fwd_name(atomic_read(&dest->conn_flags)),
2126                                           atomic_read(&dest->weight),
2127                                           atomic_read(&dest->activeconns),
2128                                           atomic_read(&dest->inactconns));
2129                        else
2130#endif
2131                                seq_printf(seq,
2132                                           "  -> %08X:%04X      "
2133                                           "%-7s %-6d %-10d %-10d\n",
2134                                           ntohl(dest->addr.ip),
2135                                           ntohs(dest->port),
2136                                           ip_vs_fwd_name(atomic_read(&dest->conn_flags)),
2137                                           atomic_read(&dest->weight),
2138                                           atomic_read(&dest->activeconns),
2139                                           atomic_read(&dest->inactconns));
2140
2141                }
2142        }
2143        return 0;
2144}
2145
2146static const struct seq_operations ip_vs_info_seq_ops = {
2147        .start = ip_vs_info_seq_start,
2148        .next  = ip_vs_info_seq_next,
2149        .stop  = ip_vs_info_seq_stop,
2150        .show  = ip_vs_info_seq_show,
2151};
2152
2153static int ip_vs_info_open(struct inode *inode, struct file *file)
2154{
2155        return seq_open_net(inode, file, &ip_vs_info_seq_ops,
2156                        sizeof(struct ip_vs_iter));
2157}
2158
2159static const struct file_operations ip_vs_info_fops = {
2160        .owner   = THIS_MODULE,
2161        .open    = ip_vs_info_open,
2162        .read    = seq_read,
2163        .llseek  = seq_lseek,
2164        .release = seq_release_net,
2165};
2166
2167static int ip_vs_stats_show(struct seq_file *seq, void *v)
2168{
2169        struct net *net = seq_file_single_net(seq);
2170        struct ip_vs_stats_user show;
2171
2172/*               01234567 01234567 01234567 0123456701234567 0123456701234567 */
2173        seq_puts(seq,
2174                 "   Total Incoming Outgoing         Incoming         Outgoing\n");
2175        seq_printf(seq,
2176                   "   Conns  Packets  Packets            Bytes            Bytes\n");
2177
2178        ip_vs_copy_stats(&show, &net_ipvs(net)->tot_stats);
2179        seq_printf(seq, "%8X %8X %8X %16LX %16LX\n\n", show.conns,
2180                   show.inpkts, show.outpkts,
2181                   (unsigned long long) show.inbytes,
2182                   (unsigned long long) show.outbytes);
2183
2184/*                 01234567 01234567 01234567 0123456701234567 0123456701234567 */
2185        seq_puts(seq,
2186                   " Conns/s   Pkts/s   Pkts/s          Bytes/s          Bytes/s\n");
2187        seq_printf(seq, "%8X %8X %8X %16X %16X\n",
2188                        show.cps, show.inpps, show.outpps,
2189                        show.inbps, show.outbps);
2190
2191        return 0;
2192}
2193
2194static int ip_vs_stats_seq_open(struct inode *inode, struct file *file)
2195{
2196        return single_open_net(inode, file, ip_vs_stats_show);
2197}
2198
2199static const struct file_operations ip_vs_stats_fops = {
2200        .owner = THIS_MODULE,
2201        .open = ip_vs_stats_seq_open,
2202        .read = seq_read,
2203        .llseek = seq_lseek,
2204        .release = single_release_net,
2205};
2206
2207static int ip_vs_stats_percpu_show(struct seq_file *seq, void *v)
2208{
2209        struct net *net = seq_file_single_net(seq);
2210        struct ip_vs_stats *tot_stats = &net_ipvs(net)->tot_stats;
2211        struct ip_vs_cpu_stats __percpu *cpustats = tot_stats->cpustats;
2212        struct ip_vs_stats_user rates;
2213        int i;
2214
2215/*               01234567 01234567 01234567 0123456701234567 0123456701234567 */
2216        seq_puts(seq,
2217                 "       Total Incoming Outgoing         Incoming         Outgoing\n");
2218        seq_printf(seq,
2219                   "CPU    Conns  Packets  Packets            Bytes            Bytes\n");
2220
2221        for_each_possible_cpu(i) {
2222                struct ip_vs_cpu_stats *u = per_cpu_ptr(cpustats, i);
2223                unsigned int start;
2224                __u64 inbytes, outbytes;
2225
2226                do {
2227                        start = u64_stats_fetch_begin_irq(&u->syncp);
2228                        inbytes = u->ustats.inbytes;
2229                        outbytes = u->ustats.outbytes;
2230                } while (u64_stats_fetch_retry_irq(&u->syncp, start));
2231
2232                seq_printf(seq, "%3X %8X %8X %8X %16LX %16LX\n",
2233                           i, u->ustats.conns, u->ustats.inpkts,
2234                           u->ustats.outpkts, (__u64)inbytes,
2235                           (__u64)outbytes);
2236        }
2237
2238        spin_lock_bh(&tot_stats->lock);
2239
2240        seq_printf(seq, "  ~ %8X %8X %8X %16LX %16LX\n\n",
2241                   tot_stats->ustats.conns, tot_stats->ustats.inpkts,
2242                   tot_stats->ustats.outpkts,
2243                   (unsigned long long) tot_stats->ustats.inbytes,
2244                   (unsigned long long) tot_stats->ustats.outbytes);
2245
2246        ip_vs_read_estimator(&rates, tot_stats);
2247
2248        spin_unlock_bh(&tot_stats->lock);
2249
2250/*                 01234567 01234567 01234567 0123456701234567 0123456701234567 */
2251        seq_puts(seq,
2252                   "     Conns/s   Pkts/s   Pkts/s          Bytes/s          Bytes/s\n");
2253        seq_printf(seq, "    %8X %8X %8X %16X %16X\n",
2254                        rates.cps,
2255                        rates.inpps,
2256                        rates.outpps,
2257                        rates.inbps,
2258                        rates.outbps);
2259
2260        return 0;
2261}
2262
2263static int ip_vs_stats_percpu_seq_open(struct inode *inode, struct file *file)
2264{
2265        return single_open_net(inode, file, ip_vs_stats_percpu_show);
2266}
2267
2268static const struct file_operations ip_vs_stats_percpu_fops = {
2269        .owner = THIS_MODULE,
2270        .open = ip_vs_stats_percpu_seq_open,
2271        .read = seq_read,
2272        .llseek = seq_lseek,
2273        .release = single_release_net,
2274};
2275#endif
2276
2277/*
2278 *      Set timeout values for tcp tcpfin udp in the timeout_table.
2279 */
2280static int ip_vs_set_timeout(struct net *net, struct ip_vs_timeout_user *u)
2281{
2282#if defined(CONFIG_IP_VS_PROTO_TCP) || defined(CONFIG_IP_VS_PROTO_UDP)
2283        struct ip_vs_proto_data *pd;
2284#endif
2285
2286        IP_VS_DBG(2, "Setting timeout tcp:%d tcpfin:%d udp:%d\n",
2287                  u->tcp_timeout,
2288                  u->tcp_fin_timeout,
2289                  u->udp_timeout);
2290
2291#ifdef CONFIG_IP_VS_PROTO_TCP
2292        if (u->tcp_timeout) {
2293                pd = ip_vs_proto_data_get(net, IPPROTO_TCP);
2294                pd->timeout_table[IP_VS_TCP_S_ESTABLISHED]
2295                        = u->tcp_timeout * HZ;
2296        }
2297
2298        if (u->tcp_fin_timeout) {
2299                pd = ip_vs_proto_data_get(net, IPPROTO_TCP);
2300                pd->timeout_table[IP_VS_TCP_S_FIN_WAIT]
2301                        = u->tcp_fin_timeout * HZ;
2302        }
2303#endif
2304
2305#ifdef CONFIG_IP_VS_PROTO_UDP
2306        if (u->udp_timeout) {
2307                pd = ip_vs_proto_data_get(net, IPPROTO_UDP);
2308                pd->timeout_table[IP_VS_UDP_S_NORMAL]
2309                        = u->udp_timeout * HZ;
2310        }
2311#endif
2312        return 0;
2313}
2314
2315
2316#define SET_CMDID(cmd)          (cmd - IP_VS_BASE_CTL)
2317#define SERVICE_ARG_LEN         (sizeof(struct ip_vs_service_user))
2318#define SVCDEST_ARG_LEN         (sizeof(struct ip_vs_service_user) +    \
2319                                 sizeof(struct ip_vs_dest_user))
2320#define TIMEOUT_ARG_LEN         (sizeof(struct ip_vs_timeout_user))
2321#define DAEMON_ARG_LEN          (sizeof(struct ip_vs_daemon_user))
2322#define MAX_ARG_LEN             SVCDEST_ARG_LEN
2323
2324static const unsigned char set_arglen[SET_CMDID(IP_VS_SO_SET_MAX)+1] = {
2325        [SET_CMDID(IP_VS_SO_SET_ADD)]           = SERVICE_ARG_LEN,
2326        [SET_CMDID(IP_VS_SO_SET_EDIT)]          = SERVICE_ARG_LEN,
2327        [SET_CMDID(IP_VS_SO_SET_DEL)]           = SERVICE_ARG_LEN,
2328        [SET_CMDID(IP_VS_SO_SET_FLUSH)]         = 0,
2329        [SET_CMDID(IP_VS_SO_SET_ADDDEST)]       = SVCDEST_ARG_LEN,
2330        [SET_CMDID(IP_VS_SO_SET_DELDEST)]       = SVCDEST_ARG_LEN,
2331        [SET_CMDID(IP_VS_SO_SET_EDITDEST)]      = SVCDEST_ARG_LEN,
2332        [SET_CMDID(IP_VS_SO_SET_TIMEOUT)]       = TIMEOUT_ARG_LEN,
2333        [SET_CMDID(IP_VS_SO_SET_STARTDAEMON)]   = DAEMON_ARG_LEN,
2334        [SET_CMDID(IP_VS_SO_SET_STOPDAEMON)]    = DAEMON_ARG_LEN,
2335        [SET_CMDID(IP_VS_SO_SET_ZERO)]          = SERVICE_ARG_LEN,
2336};
2337
2338static void ip_vs_copy_usvc_compat(struct ip_vs_service_user_kern *usvc,
2339                                  struct ip_vs_service_user *usvc_compat)
2340{
2341        memset(usvc, 0, sizeof(*usvc));
2342
2343        usvc->af                = AF_INET;
2344        usvc->protocol          = usvc_compat->protocol;
2345        usvc->addr.ip           = usvc_compat->addr;
2346        usvc->port              = usvc_compat->port;
2347        usvc->fwmark            = usvc_compat->fwmark;
2348
2349        /* Deep copy of sched_name is not needed here */
2350        usvc->sched_name        = usvc_compat->sched_name;
2351
2352        usvc->flags             = usvc_compat->flags;
2353        usvc->timeout           = usvc_compat->timeout;
2354        usvc->netmask           = usvc_compat->netmask;
2355}
2356
2357static void ip_vs_copy_udest_compat(struct ip_vs_dest_user_kern *udest,
2358                                   struct ip_vs_dest_user *udest_compat)
2359{
2360        memset(udest, 0, sizeof(*udest));
2361
2362        udest->addr.ip          = udest_compat->addr;
2363        udest->port             = udest_compat->port;
2364        udest->conn_flags       = udest_compat->conn_flags;
2365        udest->weight           = udest_compat->weight;
2366        udest->u_threshold      = udest_compat->u_threshold;
2367        udest->l_threshold      = udest_compat->l_threshold;
2368}
2369
2370static int
2371do_ip_vs_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len)
2372{
2373        struct net *net = sock_net(sk);
2374        int ret;
2375        unsigned char arg[MAX_ARG_LEN];
2376        struct ip_vs_service_user *usvc_compat;
2377        struct ip_vs_service_user_kern usvc;
2378        struct ip_vs_service *svc;
2379        struct ip_vs_dest_user *udest_compat;
2380        struct ip_vs_dest_user_kern udest;
2381        struct netns_ipvs *ipvs = net_ipvs(net);
2382
2383        if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
2384                return -EPERM;
2385
2386        if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_SET_MAX)
2387                return -EINVAL;
2388        if (len < 0 || len >  MAX_ARG_LEN)
2389                return -EINVAL;
2390        if (len != set_arglen[SET_CMDID(cmd)]) {
2391                pr_err("set_ctl: len %u != %u\n",
2392                       len, set_arglen[SET_CMDID(cmd)]);
2393                return -EINVAL;
2394        }
2395
2396        if (copy_from_user(arg, user, len) != 0)
2397                return -EFAULT;
2398
2399        /* increase the module use count */
2400        ip_vs_use_count_inc();
2401
2402        /* Handle daemons since they have another lock */
2403        if (cmd == IP_VS_SO_SET_STARTDAEMON ||
2404            cmd == IP_VS_SO_SET_STOPDAEMON) {
2405                struct ip_vs_daemon_user *dm = (struct ip_vs_daemon_user *)arg;
2406
2407                if (cmd == IP_VS_SO_SET_STARTDAEMON) {
2408                        struct ipvs_sync_daemon_cfg cfg;
2409
2410                        memset(&cfg, 0, sizeof(cfg));
2411                        ret = -EINVAL;
2412                        if (strscpy(cfg.mcast_ifn, dm->mcast_ifn,
2413                                    sizeof(cfg.mcast_ifn)) <= 0)
2414                                goto out_dec;
2415                        cfg.syncid = dm->syncid;
2416                        ret = start_sync_thread(ipvs, &cfg, dm->state);
2417                } else {
2418                        mutex_lock(&ipvs->sync_mutex);
2419                        ret = stop_sync_thread(net, dm->state);
2420                        mutex_unlock(&ipvs->sync_mutex);
2421                }
2422                goto out_dec;
2423        }
2424
2425        mutex_lock(&__ip_vs_mutex);
2426        if (cmd == IP_VS_SO_SET_FLUSH) {
2427                /* Flush the virtual service */
2428                ret = ip_vs_flush(net, false);
2429                goto out_unlock;
2430        } else if (cmd == IP_VS_SO_SET_TIMEOUT) {
2431                /* Set timeout values for (tcp tcpfin udp) */
2432                ret = ip_vs_set_timeout(net, (struct ip_vs_timeout_user *)arg);
2433                goto out_unlock;
2434        }
2435
2436        usvc_compat = (struct ip_vs_service_user *)arg;
2437        udest_compat = (struct ip_vs_dest_user *)(usvc_compat + 1);
2438
2439        /* We only use the new structs internally, so copy userspace compat
2440         * structs to extended internal versions */
2441        ip_vs_copy_usvc_compat(&usvc, usvc_compat);
2442        ip_vs_copy_udest_compat(&udest, udest_compat);
2443
2444        if (cmd == IP_VS_SO_SET_ZERO) {
2445                /* if no service address is set, zero counters in all */
2446                if (!usvc.fwmark && !usvc.addr.ip && !usvc.port) {
2447                        ret = ip_vs_zero_all(net);
2448                        goto out_unlock;
2449                }
2450        }
2451
2452        if ((cmd == IP_VS_SO_SET_ADD || cmd == IP_VS_SO_SET_EDIT) &&
2453            strnlen(usvc.sched_name, IP_VS_SCHEDNAME_MAXLEN) ==
2454            IP_VS_SCHEDNAME_MAXLEN) {
2455                ret = -EINVAL;
2456                goto out_unlock;
2457        }
2458
2459        /* Check for valid protocol: TCP or UDP or SCTP, even for fwmark!=0 */
2460        if (usvc.protocol != IPPROTO_TCP && usvc.protocol != IPPROTO_UDP &&
2461            usvc.protocol != IPPROTO_SCTP) {
2462                pr_err("set_ctl: invalid protocol: %d %pI4:%d\n",
2463                       usvc.protocol, &usvc.addr.ip,
2464                       ntohs(usvc.port));
2465                ret = -EFAULT;
2466                goto out_unlock;
2467        }
2468
2469        /* Lookup the exact service by <protocol, addr, port> or fwmark */
2470        rcu_read_lock();
2471        if (usvc.fwmark == 0)
2472                svc = __ip_vs_service_find(net, usvc.af, usvc.protocol,
2473                                           &usvc.addr, usvc.port);
2474        else
2475                svc = __ip_vs_svc_fwm_find(net, usvc.af, usvc.fwmark);
2476        rcu_read_unlock();
2477
2478        if (cmd != IP_VS_SO_SET_ADD
2479            && (svc == NULL || svc->protocol != usvc.protocol)) {
2480                ret = -ESRCH;
2481                goto out_unlock;
2482        }
2483
2484        switch (cmd) {
2485        case IP_VS_SO_SET_ADD:
2486                if (svc != NULL)
2487                        ret = -EEXIST;
2488                else
2489                        ret = ip_vs_add_service(net, &usvc, &svc);
2490                break;
2491        case IP_VS_SO_SET_EDIT:
2492                ret = ip_vs_edit_service(svc, &usvc);
2493                break;
2494        case IP_VS_SO_SET_DEL:
2495                ret = ip_vs_del_service(svc);
2496                if (!ret)
2497                        goto out_unlock;
2498                break;
2499        case IP_VS_SO_SET_ZERO:
2500                ret = ip_vs_zero_service(svc);
2501                break;
2502        case IP_VS_SO_SET_ADDDEST:
2503                ret = ip_vs_add_dest(svc, &udest);
2504                break;
2505        case IP_VS_SO_SET_EDITDEST:
2506                ret = ip_vs_edit_dest(svc, &udest);
2507                break;
2508        case IP_VS_SO_SET_DELDEST:
2509                ret = ip_vs_del_dest(svc, &udest);
2510                break;
2511        default:
2512                ret = -EINVAL;
2513        }
2514
2515  out_unlock:
2516        mutex_unlock(&__ip_vs_mutex);
2517  out_dec:
2518        /* decrease the module use count */
2519        ip_vs_use_count_dec();
2520
2521        return ret;
2522}
2523
2524
2525static void
2526ip_vs_copy_service(struct ip_vs_service_entry *dst, struct ip_vs_service *src)
2527{
2528        struct ip_vs_scheduler *sched;
2529        char *sched_name;
2530
2531        sched = rcu_dereference_protected(src->scheduler, 1);
2532        sched_name = sched ? sched->name : "none";
2533        dst->protocol = src->protocol;
2534        dst->addr = src->addr.ip;
2535        dst->port = src->port;
2536        dst->fwmark = src->fwmark;
2537        strlcpy(dst->sched_name, sched_name, sizeof(dst->sched_name));
2538        dst->flags = src->flags;
2539        dst->timeout = src->timeout / HZ;
2540        dst->netmask = src->netmask;
2541        dst->num_dests = src->num_dests;
2542        ip_vs_copy_stats(&dst->stats, &src->stats);
2543}
2544
2545static inline int
2546__ip_vs_get_service_entries(struct net *net,
2547                            const struct ip_vs_get_services *get,
2548                            struct ip_vs_get_services __user *uptr)
2549{
2550        int idx, count=0;
2551        struct ip_vs_service *svc;
2552        struct ip_vs_service_entry entry;
2553        int ret = 0;
2554
2555        for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
2556                hlist_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) {
2557                        /* Only expose IPv4 entries to old interface */
2558                        if (svc->af != AF_INET || !net_eq(svc->net, net))
2559                                continue;
2560
2561                        if (count >= get->num_services)
2562                                goto out;
2563                        memset(&entry, 0, sizeof(entry));
2564                        ip_vs_copy_service(&entry, svc);
2565                        if (copy_to_user(&uptr->entrytable[count],
2566                                         &entry, sizeof(entry))) {
2567                                ret = -EFAULT;
2568                                goto out;
2569                        }
2570                        count++;
2571                }
2572        }
2573
2574        for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
2575                hlist_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) {
2576                        /* Only expose IPv4 entries to old interface */
2577                        if (svc->af != AF_INET || !net_eq(svc->net, net))
2578                                continue;
2579
2580                        if (count >= get->num_services)
2581                                goto out;
2582                        memset(&entry, 0, sizeof(entry));
2583                        ip_vs_copy_service(&entry, svc);
2584                        if (copy_to_user(&uptr->entrytable[count],
2585                                         &entry, sizeof(entry))) {
2586                                ret = -EFAULT;
2587                                goto out;
2588                        }
2589                        count++;
2590                }
2591        }
2592out:
2593        return ret;
2594}
2595
2596static inline int
2597__ip_vs_get_dest_entries(struct net *net, const struct ip_vs_get_dests *get,
2598                         struct ip_vs_get_dests __user *uptr)
2599{
2600        struct ip_vs_service *svc;
2601        union nf_inet_addr addr = { .ip = get->addr };
2602        int ret = 0;
2603
2604        rcu_read_lock();
2605        if (get->fwmark)
2606                svc = __ip_vs_svc_fwm_find(net, AF_INET, get->fwmark);
2607        else
2608                svc = __ip_vs_service_find(net, AF_INET, get->protocol, &addr,
2609                                           get->port);
2610        rcu_read_unlock();
2611
2612        if (svc) {
2613                int count = 0;
2614                struct ip_vs_dest *dest;
2615                struct ip_vs_dest_entry entry;
2616
2617                memset(&entry, 0, sizeof(entry));
2618                list_for_each_entry(dest, &svc->destinations, n_list) {
2619                        if (count >= get->num_dests)
2620                                break;
2621
2622                        entry.addr = dest->addr.ip;
2623                        entry.port = dest->port;
2624                        entry.conn_flags = atomic_read(&dest->conn_flags);
2625                        entry.weight = atomic_read(&dest->weight);
2626                        entry.u_threshold = dest->u_threshold;
2627                        entry.l_threshold = dest->l_threshold;
2628                        entry.activeconns = atomic_read(&dest->activeconns);
2629                        entry.inactconns = atomic_read(&dest->inactconns);
2630                        entry.persistconns = atomic_read(&dest->persistconns);
2631                        ip_vs_copy_stats(&entry.stats, &dest->stats);
2632                        if (copy_to_user(&uptr->entrytable[count],
2633                                         &entry, sizeof(entry))) {
2634                                ret = -EFAULT;
2635                                break;
2636                        }
2637                        count++;
2638                }
2639        } else
2640                ret = -ESRCH;
2641        return ret;
2642}
2643
2644static inline void
2645__ip_vs_get_timeouts(struct net *net, struct ip_vs_timeout_user *u)
2646{
2647#if defined(CONFIG_IP_VS_PROTO_TCP) || defined(CONFIG_IP_VS_PROTO_UDP)
2648        struct ip_vs_proto_data *pd;
2649#endif
2650
2651        memset(u, 0, sizeof (*u));
2652
2653#ifdef CONFIG_IP_VS_PROTO_TCP
2654        pd = ip_vs_proto_data_get(net, IPPROTO_TCP);
2655        u->tcp_timeout = pd->timeout_table[IP_VS_TCP_S_ESTABLISHED] / HZ;
2656        u->tcp_fin_timeout = pd->timeout_table[IP_VS_TCP_S_FIN_WAIT] / HZ;
2657#endif
2658#ifdef CONFIG_IP_VS_PROTO_UDP
2659        pd = ip_vs_proto_data_get(net, IPPROTO_UDP);
2660        u->udp_timeout =
2661                        pd->timeout_table[IP_VS_UDP_S_NORMAL] / HZ;
2662#endif
2663}
2664
2665
2666#define GET_CMDID(cmd)          (cmd - IP_VS_BASE_CTL)
2667#define GET_INFO_ARG_LEN        (sizeof(struct ip_vs_getinfo))
2668#define GET_SERVICES_ARG_LEN    (sizeof(struct ip_vs_get_services))
2669#define GET_SERVICE_ARG_LEN     (sizeof(struct ip_vs_service_entry))
2670#define GET_DESTS_ARG_LEN       (sizeof(struct ip_vs_get_dests))
2671#define GET_TIMEOUT_ARG_LEN     (sizeof(struct ip_vs_timeout_user))
2672#define GET_DAEMON_ARG_LEN      (sizeof(struct ip_vs_daemon_user) * 2)
2673
2674static const unsigned char get_arglen[GET_CMDID(IP_VS_SO_GET_MAX)+1] = {
2675        [GET_CMDID(IP_VS_SO_GET_VERSION)]       = 64,
2676        [GET_CMDID(IP_VS_SO_GET_INFO)]          = GET_INFO_ARG_LEN,
2677        [GET_CMDID(IP_VS_SO_GET_SERVICES)]      = GET_SERVICES_ARG_LEN,
2678        [GET_CMDID(IP_VS_SO_GET_SERVICE)]       = GET_SERVICE_ARG_LEN,
2679        [GET_CMDID(IP_VS_SO_GET_DESTS)]         = GET_DESTS_ARG_LEN,
2680        [GET_CMDID(IP_VS_SO_GET_TIMEOUT)]       = GET_TIMEOUT_ARG_LEN,
2681        [GET_CMDID(IP_VS_SO_GET_DAEMON)]        = GET_DAEMON_ARG_LEN,
2682};
2683
2684static int
2685do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
2686{
2687        unsigned char arg[128];
2688        int ret = 0;
2689        unsigned int copylen;
2690        struct net *net = sock_net(sk);
2691        struct netns_ipvs *ipvs = net_ipvs(net);
2692
2693        BUG_ON(!net);
2694        if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
2695                return -EPERM;
2696
2697        if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_GET_MAX)
2698                return -EINVAL;
2699
2700        if (*len < get_arglen[GET_CMDID(cmd)]) {
2701                pr_err("get_ctl: len %u < %u\n",
2702                       *len, get_arglen[GET_CMDID(cmd)]);
2703                return -EINVAL;
2704        }
2705
2706        copylen = get_arglen[GET_CMDID(cmd)];
2707        if (copylen > 128)
2708                return -EINVAL;
2709
2710        if (copy_from_user(arg, user, copylen) != 0)
2711                return -EFAULT;
2712        /*
2713         * Handle daemons first since it has its own locking
2714         */
2715        if (cmd == IP_VS_SO_GET_DAEMON) {
2716                struct ip_vs_daemon_user d[2];
2717
2718                memset(&d, 0, sizeof(d));
2719                mutex_lock(&ipvs->sync_mutex);
2720                if (ipvs->sync_state & IP_VS_STATE_MASTER) {
2721                        d[0].state = IP_VS_STATE_MASTER;
2722                        strlcpy(d[0].mcast_ifn, ipvs->mcfg.mcast_ifn,
2723                                sizeof(d[0].mcast_ifn));
2724                        d[0].syncid = ipvs->mcfg.syncid;
2725                }
2726                if (ipvs->sync_state & IP_VS_STATE_BACKUP) {
2727                        d[1].state = IP_VS_STATE_BACKUP;
2728                        strlcpy(d[1].mcast_ifn, ipvs->bcfg.mcast_ifn,
2729                                sizeof(d[1].mcast_ifn));
2730                        d[1].syncid = ipvs->bcfg.syncid;
2731                }
2732                if (copy_to_user(user, &d, sizeof(d)) != 0)
2733                        ret = -EFAULT;
2734                mutex_unlock(&ipvs->sync_mutex);
2735                return ret;
2736        }
2737
2738        mutex_lock(&__ip_vs_mutex);
2739        switch (cmd) {
2740        case IP_VS_SO_GET_VERSION:
2741        {
2742                char buf[64];
2743
2744                sprintf(buf, "IP Virtual Server version %d.%d.%d (size=%d)",
2745                        NVERSION(IP_VS_VERSION_CODE), ip_vs_conn_tab_size);
2746                if (copy_to_user(user, buf, strlen(buf)+1) != 0) {
2747                        ret = -EFAULT;
2748                        goto out;
2749                }
2750                *len = strlen(buf)+1;
2751        }
2752        break;
2753
2754        case IP_VS_SO_GET_INFO:
2755        {
2756                struct ip_vs_getinfo info;
2757                info.version = IP_VS_VERSION_CODE;
2758                info.size = ip_vs_conn_tab_size;
2759                info.num_services = ipvs->num_services;
2760                if (copy_to_user(user, &info, sizeof(info)) != 0)
2761                        ret = -EFAULT;
2762        }
2763        break;
2764
2765        case IP_VS_SO_GET_SERVICES:
2766        {
2767                struct ip_vs_get_services *get;
2768                int size;
2769
2770                get = (struct ip_vs_get_services *)arg;
2771                size = sizeof(*get) +
2772                        sizeof(struct ip_vs_service_entry) * get->num_services;
2773                if (*len != size) {
2774                        pr_err("length: %u != %u\n", *len, size);
2775                        ret = -EINVAL;
2776                        goto out;
2777                }
2778                ret = __ip_vs_get_service_entries(net, get, user);
2779        }
2780        break;
2781
2782        case IP_VS_SO_GET_SERVICE:
2783        {
2784                struct ip_vs_service_entry *entry;
2785                struct ip_vs_service *svc;
2786                union nf_inet_addr addr;
2787
2788                entry = (struct ip_vs_service_entry *)arg;
2789                addr.ip = entry->addr;
2790                rcu_read_lock();
2791                if (entry->fwmark)
2792                        svc = __ip_vs_svc_fwm_find(net, AF_INET, entry->fwmark);
2793                else
2794                        svc = __ip_vs_service_find(net, AF_INET,
2795                                                   entry->protocol, &addr,
2796                                                   entry->port);
2797                rcu_read_unlock();
2798                if (svc) {
2799                        ip_vs_copy_service(entry, svc);
2800                        if (copy_to_user(user, entry, sizeof(*entry)) != 0)
2801                                ret = -EFAULT;
2802                } else
2803                        ret = -ESRCH;
2804        }
2805        break;
2806
2807        case IP_VS_SO_GET_DESTS:
2808        {
2809                struct ip_vs_get_dests *get;
2810                int size;
2811
2812                get = (struct ip_vs_get_dests *)arg;
2813                size = sizeof(*get) +
2814                        sizeof(struct ip_vs_dest_entry) * get->num_dests;
2815                if (*len != size) {
2816                        pr_err("length: %u != %u\n", *len, size);
2817                        ret = -EINVAL;
2818                        goto out;
2819                }
2820                ret = __ip_vs_get_dest_entries(net, get, user);
2821        }
2822        break;
2823
2824        case IP_VS_SO_GET_TIMEOUT:
2825        {
2826                struct ip_vs_timeout_user t;
2827
2828                __ip_vs_get_timeouts(net, &t);
2829                if (copy_to_user(user, &t, sizeof(t)) != 0)
2830                        ret = -EFAULT;
2831        }
2832        break;
2833
2834        default:
2835                ret = -EINVAL;
2836        }
2837
2838out:
2839        mutex_unlock(&__ip_vs_mutex);
2840        return ret;
2841}
2842
2843
2844static struct nf_sockopt_ops ip_vs_sockopts = {
2845        .pf             = PF_INET,
2846        .set_optmin     = IP_VS_BASE_CTL,
2847        .set_optmax     = IP_VS_SO_SET_MAX+1,
2848        .set            = do_ip_vs_set_ctl,
2849        .get_optmin     = IP_VS_BASE_CTL,
2850        .get_optmax     = IP_VS_SO_GET_MAX+1,
2851        .get            = do_ip_vs_get_ctl,
2852        .owner          = THIS_MODULE,
2853};
2854
2855/*
2856 * Generic Netlink interface
2857 */
2858
2859/* IPVS genetlink family */
2860static struct genl_family ip_vs_genl_family;
2861
2862/* Policy used for first-level command attributes */
2863static const struct nla_policy ip_vs_cmd_policy[IPVS_CMD_ATTR_MAX + 1] = {
2864        [IPVS_CMD_ATTR_SERVICE]         = { .type = NLA_NESTED },
2865        [IPVS_CMD_ATTR_DEST]            = { .type = NLA_NESTED },
2866        [IPVS_CMD_ATTR_DAEMON]          = { .type = NLA_NESTED },
2867        [IPVS_CMD_ATTR_TIMEOUT_TCP]     = { .type = NLA_U32 },
2868        [IPVS_CMD_ATTR_TIMEOUT_TCP_FIN] = { .type = NLA_U32 },
2869        [IPVS_CMD_ATTR_TIMEOUT_UDP]     = { .type = NLA_U32 },
2870};
2871
2872/* Policy used for attributes in nested attribute IPVS_CMD_ATTR_DAEMON */
2873static const struct nla_policy ip_vs_daemon_policy[IPVS_DAEMON_ATTR_MAX + 1] = {
2874        [IPVS_DAEMON_ATTR_STATE]        = { .type = NLA_U32 },
2875        [IPVS_DAEMON_ATTR_MCAST_IFN]    = { .type = NLA_NUL_STRING,
2876                                            .len = IP_VS_IFNAME_MAXLEN - 1 },
2877        [IPVS_DAEMON_ATTR_SYNC_ID]      = { .type = NLA_U32 },
2878        [IPVS_DAEMON_ATTR_SYNC_MAXLEN]  = { .type = NLA_U16 },
2879};
2880
2881/* Policy used for attributes in nested attribute IPVS_CMD_ATTR_SERVICE */
2882static const struct nla_policy ip_vs_svc_policy[IPVS_SVC_ATTR_MAX + 1] = {
2883        [IPVS_SVC_ATTR_AF]              = { .type = NLA_U16 },
2884        [IPVS_SVC_ATTR_PROTOCOL]        = { .type = NLA_U16 },
2885        [IPVS_SVC_ATTR_ADDR]            = { .type = NLA_BINARY,
2886                                            .len = sizeof(union nf_inet_addr) },
2887        [IPVS_SVC_ATTR_PORT]            = { .type = NLA_U16 },
2888        [IPVS_SVC_ATTR_FWMARK]          = { .type = NLA_U32 },
2889        [IPVS_SVC_ATTR_SCHED_NAME]      = { .type = NLA_NUL_STRING,
2890                                            .len = IP_VS_SCHEDNAME_MAXLEN - 1 },
2891        [IPVS_SVC_ATTR_PE_NAME]         = { .type = NLA_NUL_STRING,
2892                                            .len = IP_VS_PENAME_MAXLEN },
2893        [IPVS_SVC_ATTR_FLAGS]           = { .type = NLA_BINARY,
2894                                            .len = sizeof(struct ip_vs_flags) },
2895        [IPVS_SVC_ATTR_TIMEOUT]         = { .type = NLA_U32 },
2896        [IPVS_SVC_ATTR_NETMASK]         = { .type = NLA_U32 },
2897        [IPVS_SVC_ATTR_STATS]           = { .type = NLA_NESTED },
2898};
2899
2900/* Policy used for attributes in nested attribute IPVS_CMD_ATTR_DEST */
2901static const struct nla_policy ip_vs_dest_policy[IPVS_DEST_ATTR_MAX + 1] = {
2902        [IPVS_DEST_ATTR_ADDR]           = { .type = NLA_BINARY,
2903                                            .len = sizeof(union nf_inet_addr) },
2904        [IPVS_DEST_ATTR_PORT]           = { .type = NLA_U16 },
2905        [IPVS_DEST_ATTR_FWD_METHOD]     = { .type = NLA_U32 },
2906        [IPVS_DEST_ATTR_WEIGHT]         = { .type = NLA_U32 },
2907        [IPVS_DEST_ATTR_U_THRESH]       = { .type = NLA_U32 },
2908        [IPVS_DEST_ATTR_L_THRESH]       = { .type = NLA_U32 },
2909        [IPVS_DEST_ATTR_ACTIVE_CONNS]   = { .type = NLA_U32 },
2910        [IPVS_DEST_ATTR_INACT_CONNS]    = { .type = NLA_U32 },
2911        [IPVS_DEST_ATTR_PERSIST_CONNS]  = { .type = NLA_U32 },
2912        [IPVS_DEST_ATTR_STATS]          = { .type = NLA_NESTED },
2913};
2914
2915static int ip_vs_genl_fill_stats(struct sk_buff *skb, int container_type,
2916                                 struct ip_vs_stats *stats)
2917{
2918        struct ip_vs_stats_user ustats;
2919        struct nlattr *nl_stats = nla_nest_start(skb, container_type);
2920        if (!nl_stats)
2921                return -EMSGSIZE;
2922
2923        ip_vs_copy_stats(&ustats, stats);
2924
2925        if (nla_put_u32(skb, IPVS_STATS_ATTR_CONNS, ustats.conns) ||
2926            nla_put_u32(skb, IPVS_STATS_ATTR_INPKTS, ustats.inpkts) ||
2927            nla_put_u32(skb, IPVS_STATS_ATTR_OUTPKTS, ustats.outpkts) ||
2928            nla_put_u64(skb, IPVS_STATS_ATTR_INBYTES, ustats.inbytes) ||
2929            nla_put_u64(skb, IPVS_STATS_ATTR_OUTBYTES, ustats.outbytes) ||
2930            nla_put_u32(skb, IPVS_STATS_ATTR_CPS, ustats.cps) ||
2931            nla_put_u32(skb, IPVS_STATS_ATTR_INPPS, ustats.inpps) ||
2932            nla_put_u32(skb, IPVS_STATS_ATTR_OUTPPS, ustats.outpps) ||
2933            nla_put_u32(skb, IPVS_STATS_ATTR_INBPS, ustats.inbps) ||
2934            nla_put_u32(skb, IPVS_STATS_ATTR_OUTBPS, ustats.outbps))
2935                goto nla_put_failure;
2936        nla_nest_end(skb, nl_stats);
2937
2938        return 0;
2939
2940nla_put_failure:
2941        nla_nest_cancel(skb, nl_stats);
2942        return -EMSGSIZE;
2943}
2944
2945static int ip_vs_genl_fill_service(struct sk_buff *skb,
2946                                   struct ip_vs_service *svc)
2947{
2948        struct ip_vs_scheduler *sched;
2949        struct ip_vs_pe *pe;
2950        struct nlattr *nl_service;
2951        struct ip_vs_flags flags = { .flags = svc->flags,
2952                                     .mask = ~0 };
2953        char *sched_name;
2954
2955        nl_service = nla_nest_start(skb, IPVS_CMD_ATTR_SERVICE);
2956        if (!nl_service)
2957                return -EMSGSIZE;
2958
2959        if (nla_put_u16(skb, IPVS_SVC_ATTR_AF, svc->af))
2960                goto nla_put_failure;
2961        if (svc->fwmark) {
2962                if (nla_put_u32(skb, IPVS_SVC_ATTR_FWMARK, svc->fwmark))
2963                        goto nla_put_failure;
2964        } else {
2965                if (nla_put_u16(skb, IPVS_SVC_ATTR_PROTOCOL, svc->protocol) ||
2966                    nla_put(skb, IPVS_SVC_ATTR_ADDR, sizeof(svc->addr), &svc->addr) ||
2967                    nla_put_be16(skb, IPVS_SVC_ATTR_PORT, svc->port))
2968                        goto nla_put_failure;
2969        }
2970
2971        sched = rcu_dereference_protected(svc->scheduler, 1);
2972        sched_name = sched ? sched->name : "none";
2973        pe = rcu_dereference_protected(svc->pe, 1);
2974        if (nla_put_string(skb, IPVS_SVC_ATTR_SCHED_NAME, sched_name) ||
2975            (pe && nla_put_string(skb, IPVS_SVC_ATTR_PE_NAME, pe->name)) ||
2976            nla_put(skb, IPVS_SVC_ATTR_FLAGS, sizeof(flags), &flags) ||
2977            nla_put_u32(skb, IPVS_SVC_ATTR_TIMEOUT, svc->timeout / HZ) ||
2978            nla_put_be32(skb, IPVS_SVC_ATTR_NETMASK, svc->netmask))
2979                goto nla_put_failure;
2980        if (ip_vs_genl_fill_stats(skb, IPVS_SVC_ATTR_STATS, &svc->stats))
2981                goto nla_put_failure;
2982
2983        nla_nest_end(skb, nl_service);
2984
2985        return 0;
2986
2987nla_put_failure:
2988        nla_nest_cancel(skb, nl_service);
2989        return -EMSGSIZE;
2990}
2991
2992static int ip_vs_genl_dump_service(struct sk_buff *skb,
2993                                   struct ip_vs_service *svc,
2994                                   struct netlink_callback *cb)
2995{
2996        void *hdr;
2997
2998        hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
2999                          &ip_vs_genl_family, NLM_F_MULTI,
3000                          IPVS_CMD_NEW_SERVICE);
3001        if (!hdr)
3002                return -EMSGSIZE;
3003
3004        if (ip_vs_genl_fill_service(skb, svc) < 0)
3005                goto nla_put_failure;
3006
3007        genlmsg_end(skb, hdr);
3008        return 0;
3009
3010nla_put_failure:
3011        genlmsg_cancel(skb, hdr);
3012        return -EMSGSIZE;
3013}
3014
3015static int ip_vs_genl_dump_services(struct sk_buff *skb,
3016                                    struct netlink_callback *cb)
3017{
3018        int idx = 0, i;
3019        int start = cb->args[0];
3020        struct ip_vs_service *svc;
3021        struct net *net = skb_sknet(skb);
3022
3023        mutex_lock(&__ip_vs_mutex);
3024        for (i = 0; i < IP_VS_SVC_TAB_SIZE; i++) {
3025                hlist_for_each_entry(svc, &ip_vs_svc_table[i], s_list) {
3026                        if (++idx <= start || !net_eq(svc->net, net))
3027                                continue;
3028                        if (ip_vs_genl_dump_service(skb, svc, cb) < 0) {
3029                                idx--;
3030                                goto nla_put_failure;
3031                        }
3032                }
3033        }
3034
3035        for (i = 0; i < IP_VS_SVC_TAB_SIZE; i++) {
3036                hlist_for_each_entry(svc, &ip_vs_svc_fwm_table[i], f_list) {
3037                        if (++idx <= start || !net_eq(svc->net, net))
3038                                continue;
3039                        if (ip_vs_genl_dump_service(skb, svc, cb) < 0) {
3040                                idx--;
3041                                goto nla_put_failure;
3042                        }
3043                }
3044        }
3045
3046nla_put_failure:
3047        mutex_unlock(&__ip_vs_mutex);
3048        cb->args[0] = idx;
3049
3050        return skb->len;
3051}
3052
3053static bool ip_vs_is_af_valid(int af)
3054{
3055        if (af == AF_INET)
3056                return true;
3057#ifdef CONFIG_IP_VS_IPV6
3058        if (af == AF_INET6 && ipv6_mod_enabled())
3059                return true;
3060#endif
3061        return false;
3062}
3063
3064static int ip_vs_genl_parse_service(struct net *net,
3065                                    struct ip_vs_service_user_kern *usvc,
3066                                    struct nlattr *nla, int full_entry,
3067                                    struct ip_vs_service **ret_svc)
3068{
3069        struct nlattr *attrs[IPVS_SVC_ATTR_MAX + 1];
3070        struct nlattr *nla_af, *nla_port, *nla_fwmark, *nla_protocol, *nla_addr;
3071        struct ip_vs_service *svc;
3072
3073        /* Parse mandatory identifying service fields first */
3074        if (nla == NULL ||
3075            nla_parse_nested(attrs, IPVS_SVC_ATTR_MAX, nla, ip_vs_svc_policy))
3076                return -EINVAL;
3077
3078        nla_af          = attrs[IPVS_SVC_ATTR_AF];
3079        nla_protocol    = attrs[IPVS_SVC_ATTR_PROTOCOL];
3080        nla_addr        = attrs[IPVS_SVC_ATTR_ADDR];
3081        nla_port        = attrs[IPVS_SVC_ATTR_PORT];
3082        nla_fwmark      = attrs[IPVS_SVC_ATTR_FWMARK];
3083
3084        if (!(nla_af && (nla_fwmark || (nla_port && nla_protocol && nla_addr))))
3085                return -EINVAL;
3086
3087        memset(usvc, 0, sizeof(*usvc));
3088
3089        usvc->af = nla_get_u16(nla_af);
3090        if (!ip_vs_is_af_valid(usvc->af))
3091                return -EAFNOSUPPORT;
3092
3093        if (nla_fwmark) {
3094                usvc->protocol = IPPROTO_TCP;
3095                usvc->fwmark = nla_get_u32(nla_fwmark);
3096        } else {
3097                usvc->protocol = nla_get_u16(nla_protocol);
3098                nla_memcpy(&usvc->addr, nla_addr, sizeof(usvc->addr));
3099                usvc->port = nla_get_be16(nla_port);
3100                usvc->fwmark = 0;
3101        }
3102
3103        rcu_read_lock();
3104        if (usvc->fwmark)
3105                svc = __ip_vs_svc_fwm_find(net, usvc->af, usvc->fwmark);
3106        else
3107                svc = __ip_vs_service_find(net, usvc->af, usvc->protocol,
3108                                           &usvc->addr, usvc->port);
3109        rcu_read_unlock();
3110        *ret_svc = svc;
3111
3112        /* If a full entry was requested, check for the additional fields */
3113        if (full_entry) {
3114                struct nlattr *nla_sched, *nla_flags, *nla_pe, *nla_timeout,
3115                              *nla_netmask;
3116                struct ip_vs_flags flags;
3117
3118                nla_sched = attrs[IPVS_SVC_ATTR_SCHED_NAME];
3119                nla_pe = attrs[IPVS_SVC_ATTR_PE_NAME];
3120                nla_flags = attrs[IPVS_SVC_ATTR_FLAGS];
3121                nla_timeout = attrs[IPVS_SVC_ATTR_TIMEOUT];
3122                nla_netmask = attrs[IPVS_SVC_ATTR_NETMASK];
3123
3124                if (!(nla_sched && nla_flags && nla_timeout && nla_netmask))
3125                        return -EINVAL;
3126
3127                nla_memcpy(&flags, nla_flags, sizeof(flags));
3128
3129                /* prefill flags from service if it already exists */
3130                if (svc)
3131                        usvc->flags = svc->flags;
3132
3133                /* set new flags from userland */
3134                usvc->flags = (usvc->flags & ~flags.mask) |
3135                              (flags.flags & flags.mask);
3136                usvc->sched_name = nla_data(nla_sched);
3137                usvc->pe_name = nla_pe ? nla_data(nla_pe) : NULL;
3138                usvc->timeout = nla_get_u32(nla_timeout);
3139                usvc->netmask = nla_get_be32(nla_netmask);
3140        }
3141
3142        return 0;
3143}
3144
3145static struct ip_vs_service *ip_vs_genl_find_service(struct net *net,
3146                                                     struct nlattr *nla)
3147{
3148        struct ip_vs_service_user_kern usvc;
3149        struct ip_vs_service *svc;
3150        int ret;
3151
3152        ret = ip_vs_genl_parse_service(net, &usvc, nla, 0, &svc);
3153        return ret ? ERR_PTR(ret) : svc;
3154}
3155
3156static int ip_vs_genl_fill_dest(struct sk_buff *skb, struct ip_vs_dest *dest)
3157{
3158        struct nlattr *nl_dest;
3159
3160        nl_dest = nla_nest_start(skb, IPVS_CMD_ATTR_DEST);
3161        if (!nl_dest)
3162                return -EMSGSIZE;
3163
3164        if (nla_put(skb, IPVS_DEST_ATTR_ADDR, sizeof(dest->addr), &dest->addr) ||
3165            nla_put_be16(skb, IPVS_DEST_ATTR_PORT, dest->port) ||
3166            nla_put_u32(skb, IPVS_DEST_ATTR_FWD_METHOD,
3167                        (atomic_read(&dest->conn_flags) &
3168                         IP_VS_CONN_F_FWD_MASK)) ||
3169            nla_put_u32(skb, IPVS_DEST_ATTR_WEIGHT,
3170                        atomic_read(&dest->weight)) ||
3171            nla_put_u32(skb, IPVS_DEST_ATTR_U_THRESH, dest->u_threshold) ||
3172            nla_put_u32(skb, IPVS_DEST_ATTR_L_THRESH, dest->l_threshold) ||
3173            nla_put_u32(skb, IPVS_DEST_ATTR_ACTIVE_CONNS,
3174                        atomic_read(&dest->activeconns)) ||
3175            nla_put_u32(skb, IPVS_DEST_ATTR_INACT_CONNS,
3176                        atomic_read(&dest->inactconns)) ||
3177            nla_put_u32(skb, IPVS_DEST_ATTR_PERSIST_CONNS,
3178                        atomic_read(&dest->persistconns)))
3179                goto nla_put_failure;
3180        if (ip_vs_genl_fill_stats(skb, IPVS_DEST_ATTR_STATS, &dest->stats))
3181                goto nla_put_failure;
3182
3183        nla_nest_end(skb, nl_dest);
3184
3185        return 0;
3186
3187nla_put_failure:
3188        nla_nest_cancel(skb, nl_dest);
3189        return -EMSGSIZE;
3190}
3191
3192static int ip_vs_genl_dump_dest(struct sk_buff *skb, struct ip_vs_dest *dest,
3193                                struct netlink_callback *cb)
3194{
3195        void *hdr;
3196
3197        hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
3198                          &ip_vs_genl_family, NLM_F_MULTI,
3199                          IPVS_CMD_NEW_DEST);
3200        if (!hdr)
3201                return -EMSGSIZE;
3202
3203        if (ip_vs_genl_fill_dest(skb, dest) < 0)
3204                goto nla_put_failure;
3205
3206        genlmsg_end(skb, hdr);
3207        return 0;
3208
3209nla_put_failure:
3210        genlmsg_cancel(skb, hdr);
3211        return -EMSGSIZE;
3212}
3213
3214static int ip_vs_genl_dump_dests(struct sk_buff *skb,
3215                                 struct netlink_callback *cb)
3216{
3217        int idx = 0;
3218        int start = cb->args[0];
3219        struct ip_vs_service *svc;
3220        struct ip_vs_dest *dest;
3221        struct nlattr *attrs[IPVS_CMD_ATTR_MAX + 1];
3222        struct net *net = skb_sknet(skb);
3223
3224        mutex_lock(&__ip_vs_mutex);
3225
3226        /* Try to find the service for which to dump destinations */
3227        if (nlmsg_parse(cb->nlh, GENL_HDRLEN, attrs,
3228                        IPVS_CMD_ATTR_MAX, ip_vs_cmd_policy))
3229                goto out_err;
3230
3231
3232        svc = ip_vs_genl_find_service(net, attrs[IPVS_CMD_ATTR_SERVICE]);
3233        if (IS_ERR(svc) || svc == NULL)
3234                goto out_err;
3235
3236        /* Dump the destinations */
3237        list_for_each_entry(dest, &svc->destinations, n_list) {
3238                if (++idx <= start)
3239                        continue;
3240                if (ip_vs_genl_dump_dest(skb, dest, cb) < 0) {
3241                        idx--;
3242                        goto nla_put_failure;
3243                }
3244        }
3245
3246nla_put_failure:
3247        cb->args[0] = idx;
3248
3249out_err:
3250        mutex_unlock(&__ip_vs_mutex);
3251
3252        return skb->len;
3253}
3254
3255static int ip_vs_genl_parse_dest(struct ip_vs_dest_user_kern *udest,
3256                                 struct nlattr *nla, int full_entry)
3257{
3258        struct nlattr *attrs[IPVS_DEST_ATTR_MAX + 1];
3259        struct nlattr *nla_addr, *nla_port;
3260
3261        /* Parse mandatory identifying destination fields first */
3262        if (nla == NULL ||
3263            nla_parse_nested(attrs, IPVS_DEST_ATTR_MAX, nla, ip_vs_dest_policy))
3264                return -EINVAL;
3265
3266        nla_addr        = attrs[IPVS_DEST_ATTR_ADDR];
3267        nla_port        = attrs[IPVS_DEST_ATTR_PORT];
3268
3269        if (!(nla_addr && nla_port))
3270                return -EINVAL;
3271
3272        memset(udest, 0, sizeof(*udest));
3273
3274        nla_memcpy(&udest->addr, nla_addr, sizeof(udest->addr));
3275        udest->port = nla_get_be16(nla_port);
3276
3277        /* If a full entry was requested, check for the additional fields */
3278        if (full_entry) {
3279                struct nlattr *nla_fwd, *nla_weight, *nla_u_thresh,
3280                              *nla_l_thresh;
3281
3282                nla_fwd         = attrs[IPVS_DEST_ATTR_FWD_METHOD];
3283                nla_weight      = attrs[IPVS_DEST_ATTR_WEIGHT];
3284                nla_u_thresh    = attrs[IPVS_DEST_ATTR_U_THRESH];
3285                nla_l_thresh    = attrs[IPVS_DEST_ATTR_L_THRESH];
3286
3287                if (!(nla_fwd && nla_weight && nla_u_thresh && nla_l_thresh))
3288                        return -EINVAL;
3289
3290                udest->conn_flags = nla_get_u32(nla_fwd)
3291                                    & IP_VS_CONN_F_FWD_MASK;
3292                udest->weight = nla_get_u32(nla_weight);
3293                udest->u_threshold = nla_get_u32(nla_u_thresh);
3294                udest->l_threshold = nla_get_u32(nla_l_thresh);
3295        }
3296
3297        return 0;
3298}
3299
3300static int ip_vs_genl_fill_daemon(struct sk_buff *skb, __u32 state,
3301                                  struct ipvs_sync_daemon_cfg *c)
3302{
3303        struct nlattr *nl_daemon;
3304
3305        nl_daemon = nla_nest_start(skb, IPVS_CMD_ATTR_DAEMON);
3306        if (!nl_daemon)
3307                return -EMSGSIZE;
3308
3309        if (nla_put_u32(skb, IPVS_DAEMON_ATTR_STATE, state) ||
3310            nla_put_string(skb, IPVS_DAEMON_ATTR_MCAST_IFN, c->mcast_ifn) ||
3311            nla_put_u32(skb, IPVS_DAEMON_ATTR_SYNC_ID, c->syncid) ||
3312            nla_put_u16(skb, IPVS_DAEMON_ATTR_SYNC_MAXLEN, c->sync_maxlen))
3313                goto nla_put_failure;
3314        nla_nest_end(skb, nl_daemon);
3315
3316        return 0;
3317
3318nla_put_failure:
3319        nla_nest_cancel(skb, nl_daemon);
3320        return -EMSGSIZE;
3321}
3322
3323static int ip_vs_genl_dump_daemon(struct sk_buff *skb, __u32 state,
3324                                  struct ipvs_sync_daemon_cfg *c,
3325                                  struct netlink_callback *cb)
3326{
3327        void *hdr;
3328        hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
3329                          &ip_vs_genl_family, NLM_F_MULTI,
3330                          IPVS_CMD_NEW_DAEMON);
3331        if (!hdr)
3332                return -EMSGSIZE;
3333
3334        if (ip_vs_genl_fill_daemon(skb, state, c))
3335                goto nla_put_failure;
3336
3337        genlmsg_end(skb, hdr);
3338        return 0;
3339
3340nla_put_failure:
3341        genlmsg_cancel(skb, hdr);
3342        return -EMSGSIZE;
3343}
3344
3345static int ip_vs_genl_dump_daemons(struct sk_buff *skb,
3346                                   struct netlink_callback *cb)
3347{
3348        struct net *net = skb_sknet(skb);
3349        struct netns_ipvs *ipvs = net_ipvs(net);
3350
3351        mutex_lock(&ipvs->sync_mutex);
3352        if ((ipvs->sync_state & IP_VS_STATE_MASTER) && !cb->args[0]) {
3353                if (ip_vs_genl_dump_daemon(skb, IP_VS_STATE_MASTER,
3354                                           &ipvs->mcfg, cb) < 0)
3355                        goto nla_put_failure;
3356
3357                cb->args[0] = 1;
3358        }
3359
3360        if ((ipvs->sync_state & IP_VS_STATE_BACKUP) && !cb->args[1]) {
3361                if (ip_vs_genl_dump_daemon(skb, IP_VS_STATE_BACKUP,
3362                                           &ipvs->bcfg, cb) < 0)
3363                        goto nla_put_failure;
3364
3365                cb->args[1] = 1;
3366        }
3367
3368nla_put_failure:
3369        mutex_unlock(&ipvs->sync_mutex);
3370
3371        return skb->len;
3372}
3373
3374static int ip_vs_genl_new_daemon(struct netns_ipvs *ipvs, struct nlattr **attrs)
3375{
3376        struct ipvs_sync_daemon_cfg c;
3377        struct nlattr *a;
3378        int ret;
3379
3380        memset(&c, 0, sizeof(c));
3381        if (!(attrs[IPVS_DAEMON_ATTR_STATE] &&
3382              attrs[IPVS_DAEMON_ATTR_MCAST_IFN] &&
3383              attrs[IPVS_DAEMON_ATTR_SYNC_ID]))
3384                return -EINVAL;
3385        strlcpy(c.mcast_ifn, nla_data(attrs[IPVS_DAEMON_ATTR_MCAST_IFN]),
3386                sizeof(c.mcast_ifn));
3387        c.syncid = nla_get_u32(attrs[IPVS_DAEMON_ATTR_SYNC_ID]);
3388
3389        a = attrs[IPVS_DAEMON_ATTR_SYNC_MAXLEN];
3390        if (a)
3391                c.sync_maxlen = nla_get_u16(a);
3392
3393        ret = start_sync_thread(ipvs, &c,
3394                                nla_get_u32(attrs[IPVS_DAEMON_ATTR_STATE]));
3395        return ret;
3396}
3397
3398static int ip_vs_genl_del_daemon(struct net *net, struct nlattr **attrs)
3399{
3400        struct netns_ipvs *ipvs = net_ipvs(net);
3401        int ret;
3402
3403        if (!attrs[IPVS_DAEMON_ATTR_STATE])
3404                return -EINVAL;
3405
3406        mutex_lock(&ipvs->sync_mutex);
3407        ret = stop_sync_thread(net,
3408                               nla_get_u32(attrs[IPVS_DAEMON_ATTR_STATE]));
3409        mutex_unlock(&ipvs->sync_mutex);
3410        return ret;
3411}
3412
3413static int ip_vs_genl_set_config(struct net *net, struct nlattr **attrs)
3414{
3415        struct ip_vs_timeout_user t;
3416
3417        __ip_vs_get_timeouts(net, &t);
3418
3419        if (attrs[IPVS_CMD_ATTR_TIMEOUT_TCP])
3420                t.tcp_timeout = nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_TCP]);
3421
3422        if (attrs[IPVS_CMD_ATTR_TIMEOUT_TCP_FIN])
3423                t.tcp_fin_timeout =
3424                        nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_TCP_FIN]);
3425
3426        if (attrs[IPVS_CMD_ATTR_TIMEOUT_UDP])
3427                t.udp_timeout = nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_UDP]);
3428
3429        return ip_vs_set_timeout(net, &t);
3430}
3431
3432static int ip_vs_genl_set_daemon(struct sk_buff *skb, struct genl_info *info)
3433{
3434        int ret = -EINVAL, cmd;
3435        struct net *net;
3436        struct netns_ipvs *ipvs;
3437
3438        net = skb_sknet(skb);
3439        ipvs = net_ipvs(net);
3440        cmd = info->genlhdr->cmd;
3441
3442        if (cmd == IPVS_CMD_NEW_DAEMON || cmd == IPVS_CMD_DEL_DAEMON) {
3443                struct nlattr *daemon_attrs[IPVS_DAEMON_ATTR_MAX + 1];
3444
3445                if (!info->attrs[IPVS_CMD_ATTR_DAEMON] ||
3446                    nla_parse_nested(daemon_attrs, IPVS_DAEMON_ATTR_MAX,
3447                                     info->attrs[IPVS_CMD_ATTR_DAEMON],
3448                                     ip_vs_daemon_policy))
3449                        goto out;
3450
3451                if (cmd == IPVS_CMD_NEW_DAEMON)
3452                        ret = ip_vs_genl_new_daemon(ipvs, daemon_attrs);
3453                else
3454                        ret = ip_vs_genl_del_daemon(net, daemon_attrs);
3455        }
3456
3457out:
3458        return ret;
3459}
3460
3461static int ip_vs_genl_set_cmd(struct sk_buff *skb, struct genl_info *info)
3462{
3463        struct ip_vs_service *svc = NULL;
3464        struct ip_vs_service_user_kern usvc;
3465        struct ip_vs_dest_user_kern udest;
3466        int ret = 0, cmd;
3467        int need_full_svc = 0, need_full_dest = 0;
3468        struct net *net;
3469
3470        net = skb_sknet(skb);
3471        cmd = info->genlhdr->cmd;
3472
3473        mutex_lock(&__ip_vs_mutex);
3474
3475        if (cmd == IPVS_CMD_FLUSH) {
3476                ret = ip_vs_flush(net, false);
3477                goto out;
3478        } else if (cmd == IPVS_CMD_SET_CONFIG) {
3479                ret = ip_vs_genl_set_config(net, info->attrs);
3480                goto out;
3481        } else if (cmd == IPVS_CMD_ZERO &&
3482                   !info->attrs[IPVS_CMD_ATTR_SERVICE]) {
3483                ret = ip_vs_zero_all(net);
3484                goto out;
3485        }
3486
3487        /* All following commands require a service argument, so check if we
3488         * received a valid one. We need a full service specification when
3489         * adding / editing a service. Only identifying members otherwise. */
3490        if (cmd == IPVS_CMD_NEW_SERVICE || cmd == IPVS_CMD_SET_SERVICE)
3491                need_full_svc = 1;
3492
3493        ret = ip_vs_genl_parse_service(net, &usvc,
3494                                       info->attrs[IPVS_CMD_ATTR_SERVICE],
3495                                       need_full_svc, &svc);
3496        if (ret)
3497                goto out;
3498
3499        /* Unless we're adding a new service, the service must already exist */
3500        if ((cmd != IPVS_CMD_NEW_SERVICE) && (svc == NULL)) {
3501                ret = -ESRCH;
3502                goto out;
3503        }
3504
3505        /* Destination commands require a valid destination argument. For
3506         * adding / editing a destination, we need a full destination
3507         * specification. */
3508        if (cmd == IPVS_CMD_NEW_DEST || cmd == IPVS_CMD_SET_DEST ||
3509            cmd == IPVS_CMD_DEL_DEST) {
3510                if (cmd != IPVS_CMD_DEL_DEST)
3511                        need_full_dest = 1;
3512
3513                ret = ip_vs_genl_parse_dest(&udest,
3514                                            info->attrs[IPVS_CMD_ATTR_DEST],
3515                                            need_full_dest);
3516                if (ret)
3517                        goto out;
3518        }
3519
3520        switch (cmd) {
3521        case IPVS_CMD_NEW_SERVICE:
3522                if (svc == NULL)
3523                        ret = ip_vs_add_service(net, &usvc, &svc);
3524                else
3525                        ret = -EEXIST;
3526                break;
3527        case IPVS_CMD_SET_SERVICE:
3528                ret = ip_vs_edit_service(svc, &usvc);
3529                break;
3530        case IPVS_CMD_DEL_SERVICE:
3531                ret = ip_vs_del_service(svc);
3532                /* do not use svc, it can be freed */
3533                break;
3534        case IPVS_CMD_NEW_DEST:
3535                ret = ip_vs_add_dest(svc, &udest);
3536                break;
3537        case IPVS_CMD_SET_DEST:
3538                ret = ip_vs_edit_dest(svc, &udest);
3539                break;
3540        case IPVS_CMD_DEL_DEST:
3541                ret = ip_vs_del_dest(svc, &udest);
3542                break;
3543        case IPVS_CMD_ZERO:
3544                ret = ip_vs_zero_service(svc);
3545                break;
3546        default:
3547                ret = -EINVAL;
3548        }
3549
3550out:
3551        mutex_unlock(&__ip_vs_mutex);
3552
3553        return ret;
3554}
3555
3556static int ip_vs_genl_get_cmd(struct sk_buff *skb, struct genl_info *info)
3557{
3558        struct sk_buff *msg;
3559        void *reply;
3560        int ret, cmd, reply_cmd;
3561        struct net *net;
3562
3563        net = skb_sknet(skb);
3564        cmd = info->genlhdr->cmd;
3565
3566        if (cmd == IPVS_CMD_GET_SERVICE)
3567                reply_cmd = IPVS_CMD_NEW_SERVICE;
3568        else if (cmd == IPVS_CMD_GET_INFO)
3569                reply_cmd = IPVS_CMD_SET_INFO;
3570        else if (cmd == IPVS_CMD_GET_CONFIG)
3571                reply_cmd = IPVS_CMD_SET_CONFIG;
3572        else {
3573                pr_err("unknown Generic Netlink command\n");
3574                return -EINVAL;
3575        }
3576
3577        msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
3578        if (!msg)
3579                return -ENOMEM;
3580
3581        mutex_lock(&__ip_vs_mutex);
3582
3583        reply = genlmsg_put_reply(msg, info, &ip_vs_genl_family, 0, reply_cmd);
3584        if (reply == NULL)
3585                goto nla_put_failure;
3586
3587        switch (cmd) {
3588        case IPVS_CMD_GET_SERVICE:
3589        {
3590                struct ip_vs_service *svc;
3591
3592                svc = ip_vs_genl_find_service(net,
3593                                              info->attrs[IPVS_CMD_ATTR_SERVICE]);
3594                if (IS_ERR(svc)) {
3595                        ret = PTR_ERR(svc);
3596                        goto out_err;
3597                } else if (svc) {
3598                        ret = ip_vs_genl_fill_service(msg, svc);
3599                        if (ret)
3600                                goto nla_put_failure;
3601                } else {
3602                        ret = -ESRCH;
3603                        goto out_err;
3604                }
3605
3606                break;
3607        }
3608
3609        case IPVS_CMD_GET_CONFIG:
3610        {
3611                struct ip_vs_timeout_user t;
3612
3613                __ip_vs_get_timeouts(net, &t);
3614#ifdef CONFIG_IP_VS_PROTO_TCP
3615                if (nla_put_u32(msg, IPVS_CMD_ATTR_TIMEOUT_TCP,
3616                                t.tcp_timeout) ||
3617                    nla_put_u32(msg, IPVS_CMD_ATTR_TIMEOUT_TCP_FIN,
3618                                t.tcp_fin_timeout))
3619                        goto nla_put_failure;
3620#endif
3621#ifdef CONFIG_IP_VS_PROTO_UDP
3622                if (nla_put_u32(msg, IPVS_CMD_ATTR_TIMEOUT_UDP, t.udp_timeout))
3623                        goto nla_put_failure;
3624#endif
3625
3626                break;
3627        }
3628
3629        case IPVS_CMD_GET_INFO:
3630                if (nla_put_u32(msg, IPVS_INFO_ATTR_VERSION,
3631                                IP_VS_VERSION_CODE) ||
3632                    nla_put_u32(msg, IPVS_INFO_ATTR_CONN_TAB_SIZE,
3633                                ip_vs_conn_tab_size))
3634                        goto nla_put_failure;
3635                break;
3636        }
3637
3638        genlmsg_end(msg, reply);
3639        ret = genlmsg_reply(msg, info);
3640        goto out;
3641
3642nla_put_failure:
3643        pr_err("not enough space in Netlink message\n");
3644        ret = -EMSGSIZE;
3645
3646out_err:
3647        nlmsg_free(msg);
3648out:
3649        mutex_unlock(&__ip_vs_mutex);
3650
3651        return ret;
3652}
3653
3654
3655static const struct genl_ops ip_vs_genl_ops[] __read_mostly = {
3656        {
3657                .cmd    = IPVS_CMD_NEW_SERVICE,
3658                .flags  = GENL_ADMIN_PERM,
3659                .policy = ip_vs_cmd_policy,
3660                .doit   = ip_vs_genl_set_cmd,
3661        },
3662        {
3663                .cmd    = IPVS_CMD_SET_SERVICE,
3664                .flags  = GENL_ADMIN_PERM,
3665                .policy = ip_vs_cmd_policy,
3666                .doit   = ip_vs_genl_set_cmd,
3667        },
3668        {
3669                .cmd    = IPVS_CMD_DEL_SERVICE,
3670                .flags  = GENL_ADMIN_PERM,
3671                .policy = ip_vs_cmd_policy,
3672                .doit   = ip_vs_genl_set_cmd,
3673        },
3674        {
3675                .cmd    = IPVS_CMD_GET_SERVICE,
3676                .flags  = GENL_ADMIN_PERM,
3677                .doit   = ip_vs_genl_get_cmd,
3678                .dumpit = ip_vs_genl_dump_services,
3679                .policy = ip_vs_cmd_policy,
3680        },
3681        {
3682                .cmd    = IPVS_CMD_NEW_DEST,
3683                .flags  = GENL_ADMIN_PERM,
3684                .policy = ip_vs_cmd_policy,
3685                .doit   = ip_vs_genl_set_cmd,
3686        },
3687        {
3688                .cmd    = IPVS_CMD_SET_DEST,
3689                .flags  = GENL_ADMIN_PERM,
3690                .policy = ip_vs_cmd_policy,
3691                .doit   = ip_vs_genl_set_cmd,
3692        },
3693        {
3694                .cmd    = IPVS_CMD_DEL_DEST,
3695                .flags  = GENL_ADMIN_PERM,
3696                .policy = ip_vs_cmd_policy,
3697                .doit   = ip_vs_genl_set_cmd,
3698        },
3699        {
3700                .cmd    = IPVS_CMD_GET_DEST,
3701                .flags  = GENL_ADMIN_PERM,
3702                .policy = ip_vs_cmd_policy,
3703                .dumpit = ip_vs_genl_dump_dests,
3704        },
3705        {
3706                .cmd    = IPVS_CMD_NEW_DAEMON,
3707                .flags  = GENL_ADMIN_PERM,
3708                .policy = ip_vs_cmd_policy,
3709                .doit   = ip_vs_genl_set_daemon,
3710        },
3711        {
3712                .cmd    = IPVS_CMD_DEL_DAEMON,
3713                .flags  = GENL_ADMIN_PERM,
3714                .policy = ip_vs_cmd_policy,
3715                .doit   = ip_vs_genl_set_daemon,
3716        },
3717        {
3718                .cmd    = IPVS_CMD_GET_DAEMON,
3719                .flags  = GENL_ADMIN_PERM,
3720                .dumpit = ip_vs_genl_dump_daemons,
3721        },
3722        {
3723                .cmd    = IPVS_CMD_SET_CONFIG,
3724                .flags  = GENL_ADMIN_PERM,
3725                .policy = ip_vs_cmd_policy,
3726                .doit   = ip_vs_genl_set_cmd,
3727        },
3728        {
3729                .cmd    = IPVS_CMD_GET_CONFIG,
3730                .flags  = GENL_ADMIN_PERM,
3731                .doit   = ip_vs_genl_get_cmd,
3732        },
3733        {
3734                .cmd    = IPVS_CMD_GET_INFO,
3735                .flags  = GENL_ADMIN_PERM,
3736                .doit   = ip_vs_genl_get_cmd,
3737        },
3738        {
3739                .cmd    = IPVS_CMD_ZERO,
3740                .flags  = GENL_ADMIN_PERM,
3741                .policy = ip_vs_cmd_policy,
3742                .doit   = ip_vs_genl_set_cmd,
3743        },
3744        {
3745                .cmd    = IPVS_CMD_FLUSH,
3746                .flags  = GENL_ADMIN_PERM,
3747                .doit   = ip_vs_genl_set_cmd,
3748        },
3749};
3750
3751static struct genl_family ip_vs_genl_family = {
3752        .hdrsize        = 0,
3753        .name           = IPVS_GENL_NAME,
3754        .version        = IPVS_GENL_VERSION,
3755        .maxattr        = IPVS_CMD_MAX,
3756        .netnsok        = true,         /* Make ipvsadm to work on netns */
3757        .module         = THIS_MODULE,
3758        .ops            = ip_vs_genl_ops,
3759        .n_ops          = ARRAY_SIZE(ip_vs_genl_ops),
3760};
3761
3762static int __init ip_vs_genl_register(void)
3763{
3764        return genl_register_family(&ip_vs_genl_family);
3765}
3766
3767static void ip_vs_genl_unregister(void)
3768{
3769        genl_unregister_family(&ip_vs_genl_family);
3770}
3771
3772/* End of Generic Netlink interface definitions */
3773
3774/*
3775 * per netns intit/exit func.
3776 */
3777#ifdef CONFIG_SYSCTL
3778static int __net_init ip_vs_control_net_init_sysctl(struct net *net)
3779{
3780        int idx;
3781        struct netns_ipvs *ipvs = net_ipvs(net);
3782        struct ctl_table *tbl;
3783
3784        atomic_set(&ipvs->dropentry, 0);
3785        spin_lock_init(&ipvs->dropentry_lock);
3786        spin_lock_init(&ipvs->droppacket_lock);
3787        spin_lock_init(&ipvs->securetcp_lock);
3788
3789        if (!net_eq(net, &init_net)) {
3790                tbl = kmemdup(vs_vars, sizeof(vs_vars), GFP_KERNEL);
3791                if (tbl == NULL)
3792                        return -ENOMEM;
3793
3794                /* Don't export sysctls to unprivileged users */
3795                if (net->user_ns != &init_user_ns)
3796                        tbl[0].procname = NULL;
3797        } else
3798                tbl = vs_vars;
3799        /* Initialize sysctl defaults */
3800        idx = 0;
3801        ipvs->sysctl_amemthresh = 1024;
3802        tbl[idx++].data = &ipvs->sysctl_amemthresh;
3803        ipvs->sysctl_am_droprate = 10;
3804        tbl[idx++].data = &ipvs->sysctl_am_droprate;
3805        tbl[idx++].data = &ipvs->sysctl_drop_entry;
3806        tbl[idx++].data = &ipvs->sysctl_drop_packet;
3807#ifdef CONFIG_IP_VS_NFCT
3808        tbl[idx++].data = &ipvs->sysctl_conntrack;
3809#endif
3810        tbl[idx++].data = &ipvs->sysctl_secure_tcp;
3811        ipvs->sysctl_snat_reroute = 1;
3812        tbl[idx++].data = &ipvs->sysctl_snat_reroute;
3813        ipvs->sysctl_sync_ver = 1;
3814        tbl[idx++].data = &ipvs->sysctl_sync_ver;
3815        ipvs->sysctl_sync_ports = 1;
3816        tbl[idx++].data = &ipvs->sysctl_sync_ports;
3817        ipvs->sysctl_sync_qlen_max = nr_free_buffer_pages() / 32;
3818        tbl[idx++].data = &ipvs->sysctl_sync_qlen_max;
3819        ipvs->sysctl_sync_sock_size = 0;
3820        tbl[idx++].data = &ipvs->sysctl_sync_sock_size;
3821        tbl[idx++].data = &ipvs->sysctl_cache_bypass;
3822        tbl[idx++].data = &ipvs->sysctl_expire_nodest_conn;
3823        tbl[idx++].data = &ipvs->sysctl_expire_quiescent_template;
3824        ipvs->sysctl_sync_threshold[0] = DEFAULT_SYNC_THRESHOLD;
3825        ipvs->sysctl_sync_threshold[1] = DEFAULT_SYNC_PERIOD;
3826        tbl[idx].data = &ipvs->sysctl_sync_threshold;
3827        tbl[idx++].maxlen = sizeof(ipvs->sysctl_sync_threshold);
3828        ipvs->sysctl_sync_refresh_period = DEFAULT_SYNC_REFRESH_PERIOD;
3829        tbl[idx++].data = &ipvs->sysctl_sync_refresh_period;
3830        ipvs->sysctl_sync_retries = clamp_t(int, DEFAULT_SYNC_RETRIES, 0, 3);
3831        tbl[idx++].data = &ipvs->sysctl_sync_retries;
3832        tbl[idx++].data = &ipvs->sysctl_nat_icmp_send;
3833        ipvs->sysctl_pmtu_disc = 1;
3834        tbl[idx++].data = &ipvs->sysctl_pmtu_disc;
3835        tbl[idx++].data = &ipvs->sysctl_backup_only;
3836        ipvs->sysctl_conn_reuse_mode = 1;
3837        tbl[idx++].data = &ipvs->sysctl_conn_reuse_mode;
3838
3839
3840        ipvs->sysctl_hdr = register_net_sysctl(net, "net/ipv4/vs", tbl);
3841        if (ipvs->sysctl_hdr == NULL) {
3842                if (!net_eq(net, &init_net))
3843                        kfree(tbl);
3844                return -ENOMEM;
3845        }
3846        ip_vs_start_estimator(net, &ipvs->tot_stats);
3847        ipvs->sysctl_tbl = tbl;
3848        /* Schedule defense work */
3849        INIT_DELAYED_WORK(&ipvs->defense_work, defense_work_handler);
3850        schedule_delayed_work(&ipvs->defense_work, DEFENSE_TIMER_PERIOD);
3851
3852        return 0;
3853}
3854
3855static void __net_exit ip_vs_control_net_cleanup_sysctl(struct net *net)
3856{
3857        struct netns_ipvs *ipvs = net_ipvs(net);
3858
3859        cancel_delayed_work_sync(&ipvs->defense_work);
3860        cancel_work_sync(&ipvs->defense_work.work);
3861        unregister_net_sysctl_table(ipvs->sysctl_hdr);
3862
3863        if (!net_eq(net, &init_net))
3864                kfree(ipvs->sysctl_tbl);
3865}
3866
3867#else
3868
3869static int __net_init ip_vs_control_net_init_sysctl(struct net *net) { return 0; }
3870static void __net_exit ip_vs_control_net_cleanup_sysctl(struct net *net) { }
3871
3872#endif
3873
3874static struct notifier_block ip_vs_dst_notifier = {
3875        .notifier_call = ip_vs_dst_event,
3876};
3877
3878int __net_init ip_vs_control_net_init(struct net *net)
3879{
3880        int idx;
3881        struct netns_ipvs *ipvs = net_ipvs(net);
3882
3883        /* Initialize rs_table */
3884        for (idx = 0; idx < IP_VS_RTAB_SIZE; idx++)
3885                INIT_HLIST_HEAD(&ipvs->rs_table[idx]);
3886
3887        INIT_LIST_HEAD(&ipvs->dest_trash);
3888        spin_lock_init(&ipvs->dest_trash_lock);
3889        setup_timer(&ipvs->dest_trash_timer, ip_vs_dest_trash_expire,
3890                    (unsigned long) net);
3891        atomic_set(&ipvs->ftpsvc_counter, 0);
3892        atomic_set(&ipvs->nullsvc_counter, 0);
3893        atomic_set(&ipvs->conn_out_counter, 0);
3894
3895        /* procfs stats */
3896        ipvs->tot_stats.cpustats = alloc_percpu(struct ip_vs_cpu_stats);
3897        if (!ipvs->tot_stats.cpustats)
3898                return -ENOMEM;
3899
3900        spin_lock_init(&ipvs->tot_stats.lock);
3901
3902        proc_create("ip_vs", 0, net->proc_net, &ip_vs_info_fops);
3903        proc_create("ip_vs_stats", 0, net->proc_net, &ip_vs_stats_fops);
3904        proc_create("ip_vs_stats_percpu", 0, net->proc_net,
3905                    &ip_vs_stats_percpu_fops);
3906
3907        if (ip_vs_control_net_init_sysctl(net))
3908                goto err;
3909
3910        return 0;
3911
3912err:
3913        free_percpu(ipvs->tot_stats.cpustats);
3914        return -ENOMEM;
3915}
3916
3917void __net_exit ip_vs_control_net_cleanup(struct net *net)
3918{
3919        struct netns_ipvs *ipvs = net_ipvs(net);
3920
3921        /* Some dest can be in grace period even before cleanup, we have to
3922         * defer ip_vs_trash_cleanup until ip_vs_dest_wait_readers is called.
3923         */
3924        rcu_barrier();
3925        ip_vs_trash_cleanup(net);
3926        ip_vs_stop_estimator(net, &ipvs->tot_stats);
3927        ip_vs_control_net_cleanup_sysctl(net);
3928        remove_proc_entry("ip_vs_stats_percpu", net->proc_net);
3929        remove_proc_entry("ip_vs_stats", net->proc_net);
3930        remove_proc_entry("ip_vs", net->proc_net);
3931        free_percpu(ipvs->tot_stats.cpustats);
3932}
3933
3934int __init ip_vs_register_nl_ioctl(void)
3935{
3936        int ret;
3937
3938        ret = nf_register_sockopt(&ip_vs_sockopts);
3939        if (ret) {
3940                pr_err("cannot register sockopt.\n");
3941                goto err_sock;
3942        }
3943
3944        ret = ip_vs_genl_register();
3945        if (ret) {
3946                pr_err("cannot register Generic Netlink interface.\n");
3947                goto err_genl;
3948        }
3949        return 0;
3950
3951err_genl:
3952        nf_unregister_sockopt(&ip_vs_sockopts);
3953err_sock:
3954        return ret;
3955}
3956
3957void ip_vs_unregister_nl_ioctl(void)
3958{
3959        ip_vs_genl_unregister();
3960        nf_unregister_sockopt(&ip_vs_sockopts);
3961}
3962
3963int __init ip_vs_control_init(void)
3964{
3965        int idx;
3966        int ret;
3967
3968        EnterFunction(2);
3969
3970        /* Initialize svc_table, ip_vs_svc_fwm_table */
3971        for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
3972                INIT_HLIST_HEAD(&ip_vs_svc_table[idx]);
3973                INIT_HLIST_HEAD(&ip_vs_svc_fwm_table[idx]);
3974        }
3975
3976        smp_wmb();      /* Do we really need it now ? */
3977
3978        ret = register_netdevice_notifier_rh(&ip_vs_dst_notifier);
3979        if (ret < 0)
3980                return ret;
3981
3982        LeaveFunction(2);
3983        return 0;
3984}
3985
3986
3987void ip_vs_control_cleanup(void)
3988{
3989        EnterFunction(2);
3990        unregister_netdevice_notifier_rh(&ip_vs_dst_notifier);
3991        LeaveFunction(2);
3992}
3993